From 86049c5d5b9f9eb384fbaed2e301f510280295e0 Mon Sep 17 00:00:00 2001 From: Jake Coxon Date: Mon, 20 Jul 2020 20:54:35 +0100 Subject: [PATCH 0001/2359] Windows 98 style --- MS Sans Serif Bold.ttf | Bin 0 -> 12256 bytes MS Sans Serif.ttf | Bin 0 -> 14280 bytes imconfig.h | 2 + imgui.cpp | 116 ++++++++++++++++++++++++++++++++- imgui.h | 5 ++ imgui_draw.cpp | 144 +++++++++++++++++++++++++++++++++++++++++ imgui_widgets.cpp | 82 +++++++++++++++++++++++ 7 files changed, 347 insertions(+), 2 deletions(-) create mode 100644 MS Sans Serif Bold.ttf create mode 100644 MS Sans Serif.ttf diff --git a/MS Sans Serif Bold.ttf b/MS Sans Serif Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b91b8faf8eca387935c1012f4309f1749e047aaa GIT binary patch literal 12256 zcmeHNOKhCg6+ZKD#<623PDo-x0zVKTD77cA0^%VNLQJwijp8VZR2-ObCiW29V`j!A zp_GDDRfu?jDpXOGZbGH9U{O_Fv|-UMP{o1;Nhw8rskBH<3k!r2h!X7S_nmvs{CCDP zj#0a*)QPU|{qMc!obP<++{Zr|Nr*_7JS!=QzCN7Y)_c?XLn7TTqW7`U$=vjnzs~JI z`*o4z#<7W$M=$kX`LoE1RU$V%JzmHid303`bCYjj&K=|E=s7j_oIn{qo5v@sCw}ts z{MYcjStPM zZ4P)o;W$bXh03qNUm#EPOFEI(=T+!Q%Z+l2+$IBZk9H|6Y^b34z(W1MeeVQse9$2ssvYqnVo zC+D$k^TRsqH=jAqHg$w^+2(v=3*|VEeVu3KXIYaE7UEKd56HdJp|mFTZ{wdR@!fhH zR(lD`t;RnWx1?lbvu~$llicpxY1trqe7i%sCGXqIAUWyV8QA`|Z+FT%dBeAtV-Gp& z+g*~CcYS+>Jebh^21t73*2F`;zgGqmCEs2nwE)2voH*y(3A8`+ z?WFW3H~4l+?oQt7+iBU6%=>nStV@31x0lK0f2p% zIQ5iouaM_c@B4O->`Oo9+r9Eg`lr6VM)r5CaBbl4?>M}xG<~vM92>7j6Q!AG+m@|& zK0F)^=cX#raG_j08a+^&II_PmHZzec50$2>!`1T4Xf;|mXJJp|#SRwAm11cs+B&%9 z;o$+Q9#GW-R2}FnR-#-~E$5CDCUfOuQR!$jG`u&`3FD>dXzx_DP@c+Fp(-~KJv5o$ zGhVGu-<{1K1+0p~8XPT6X5q%UgT0bgRtt-jY-PN3 zJiB%KT|4f&V_SBzGEku(6;d>ihabDj1webU5bY{WPGWwvvsx_|^D~4S4Ugx_g=ptQ z@mRsz8uilwn6n2<<+1EUakMa1DO9rglhB^sKDZ@2M2-34SoFk9ZuD4jYAkxHFg<>< zT!|hp!I8<6@ajaAFC5u(9S2{|JBr2zREv~w66LhlrG4WpFNJF0q@qGu^{q9$tx zVY>`uMYS3M^B|B@(?A_HTZVd|j=D9@qI#KwcSN6qcLnSd^y?V055@u&zG@^}5i9)mq zHjcw8qm&2lMMyKE$I+_7Dsda$I5J&d3QsGvj`<4ER-mf{ds#$byWAx^Q0_n`W#LN& z@u&bDvxu!Y9(l+xi*|vvf@keXv?9&VNyrj4z1j&sh`gx&8N1BRamZ1cb0#o;4DCjq zN1L=ehE4Y%Y?P71WV{IW3u>_dt6A7O>9J?w6|*Y~CX3=Q=Fu91-6z0!4wA?4Jf%HP zLCZ8yaD5T|CSJtJnC`?SMFgj( z)@Z+-+Kvufa_gT&y@kfm@PYkuKlDG-v!3^v-cw1O{q98SJj3%CWBzK6?jOk8cv|?; zGr4Cy=BIGNcH`7shuMuEDAkT-xJu1^1V~>Ix$+)v=WFBVxsPf$*N)cm7Cc8WFK*0_Gs;v&;CHDpZ=3QdNW9#_gLyEbO^rDOZ8C_xIxX&CeL?e zMJ}Foa$SQecf$hojlSTC_m+9Qk<7s`Yp2cCNdV!q)#13!Pml0sbmi46uM$mS#@&=m zinAzfv#-1gDt|jM~ss zgS)qNpH_ZX${MVXdtm23`0$1pS|u`a%9<80Bd*3-9X*hS?U0L5SJ-aWo2WVqy!p3c zs%y}Ve?Fw+O%_eYvD)Z?vzl>o)ZN6Z%TbMaO0LCt+YfnY_JI~@-J-^4n@3BDs>?X% z7f1MP*-358K8vZ<%)`0<^a$eG-Gs=;!E90k?acMFr-wU)_wUnxxrnvb#nnqGVs1p# zURR=;9_cuXb&7X?B?|KNDm`MF8u(o4X9b*cjhmmw9{UWpduzLR&N0Tf8XLKIPO*X; zzTtqIOst*wZ5@+g_ijW?l-5m5{qnHJa%@zMt^h(rev#$1{P z%?F<+=8Ntxu|g#pgrt4O-ww%*Wc+77?@-OppQYWS9NBa%=AyMY52I?WtYe<7OND zh-cKo{3aH9V~qPc=Af@73P>o=(9fFan|E=Cz;eZA8#=ND zTUgPQ)UzZbSIIx~+H#NB4ZqdlDzONd_Z?>)3zyy?8s*1o&r=f%NT2}UmxzaXZTe_0 zM3&hdBH<|Uw?gFiAAc7D$Gn%-^MdGTi)^xX(U_mb_fXCw$j#5DMSQR`ENa6mG~3y4s{^&~4d4q_z{&Z(8IxL#$~B_qTdXL&k{3*tGM9 z@?1yh5y!#htZD=g+!NVn89=LCmwdKC(niHy3D@N{J_XEV!9i_X-1SDP8!Fk9xDW(Q;cvnKa?#GE#1?52uE{a+i(2Melx z2GLjZjyzC{t|s&|`s9f$_}huw7u09=8S^G_$$uNFwp;MPT(n#@Yt93*Lsoe2p-r9% z&JX_%r%@yp>Tojg9VxRLTsGOWDB6l;%~&~aY^8L=-wRkhIui4?gm)=wGTpSLd5Spr zd{EBV&o#rE{@NJh<$PeT&9Z%zv+A?kXk?s%Ji(i{i!SvNRh(hoJM~TXp*AbRB*R^f znwSMdW_66480j?&W5LK;UyN_DwIAA47Ceu2@42?>Tp0?EGG}R%Qnb%nb0%Kzg*;Qv^4~pkhgsw(XBS8K}YV)z)Jb~r6M4zKQYx3}jl#aq5RSmXIUOJcq3C zU7G*XYrHqJz_l0i5K4w^kzlN_y6JLMa{ z+xmp-7^Q2l^9+7L(Bf30T|;l{L+vA`^u&FaXz{RoU~N{Ne*OL}z-6PBHL)J!#okfD zYD!w}_uOCWYmGm+Vx}$45j|V{`}%^j)9hH5(}qbWsvNzXb+>Qb zqoLEzJ+}rr&%lQ^cN^n@wPB`DEJVvfl#WlEVH{D4woD6oH{P%(rttszO}n%CqLB(X zbIh18AsTwC_gT-8#$#=>UfZWy={MB8YlJ>^oOQU}`>oBQZ)BPbH29@wPOI;6jUD64 zV$*mAQfCZ*s#$qY|hr~VU^P%q3o)gH;^*9W80=40Ma zhF*m^rtEOvg1q+EJ!Do`#7x5So6p88BjLDQ%6nJ$X?Wg}Z@pb2UX~A5$KUiB*Fo+5 zhtBRs|LL=xNR7UcdCRvTa`p9z@s{ra%%8d@@4w|#n04+u&v3-=IvQi2+Y1;l?eyAk zQ!Dc<&SyR4&};jca=#?KT!YPPCDyCEJ-9d2@x4^P%j+<1$tu?bku}6c(_1<8IWv4(%GM*d~8{srlFk zQWt#8lGThbW%;ZHx#DhQ=|^02=oP(X%^8Zxe}|`buHqa0pcSq`+jYzm^F8)lXZqRn z%Vuc}%gmAa*^aZg7q+n(dScqhnrR{q_6Iu^p6H$HjlB$Wd~ur=L(@Q87R!2{u0THN zKC=XyooBiRu|`|01+!;+h52Xaa_1S^G0RpHm9?n>A2J%2H{FaRem9;PNBIK#(H@kS zP<{dA$n1`NC>QXXar_oNgCEFbp2c3+i83v+96tnJ{xZrtxPx!RP3IbvSMU=})GMAx zfxaH->p{C0vc3CIswlq}Sqb@-n7ax(R(%KML;PCzUX(ZS%i1j{Z;Pyf%o@n7c^^MZ zhmN(7T??J-UPr1TMLcyGk vXm6ZFL3yZp4vo#WqsAwV;Tx7e-yvP=La+Go(f$Ba*{# zhL)5zsS6Z=U~%DP0%Q?b2AYKzMUh1zCqNfQk%bqLToic$RUZLp$BWdkT0siQe&0R! z`~QDlq-+!|P;`XL`#z8FoO|y1{~1}q%m(dM>#^jICdv;F-@WJ8W?Ro;^s7^Im4&^3 zf7b-sZ{=L(4 zjWe&^XV0PkgjwO-Y;CGyHu(~kvcEi6IkRAs>pwRuy@U11d}Xfs?e~`6L;v5*`rcTm z)f-k^Uxhp?oJT35^q|~=zmU9euaycr(BFZ79RGcL(q6VdwQnW2C41M`F_K{953OR~ zOh%JC*Votob^Tw~|9Sn&`afM6zw#y0_&@gfe>|EEN(-ZufBntxyuAI1t8^89{^8my zQ>xdNS4Vf)@OktH;9>3)_&a=l6@I+4v9?@j>}<68%4F#nDZnY=ohtoDaGb_K=pwxK z4X-)JwJg1td`x}LaSzvPj_qzmv^2jRJ}y4wE8d(}UpzF&^_t7qqRBC?fzF|3n}sq{ zR@S1gJ^5Pm93yWQwMi$xmhD!$9OF9j>OZo!%$nG+P&U!@c^H5eo3tlvJFO97L}=vx zB!zFM_S=PV*?7oy#dgv9?XKAFu~EA}wo7)a{XuN^+E$y0?LHf_mtwmgyidjUfbFrr zitR0kNk5M5L3_~tF1EKJB7G3sL-x7CzSthNvBDq6_HNr(_;YVV*lmR$FyfWAK=ykJ zKaA~y-Cp=vY!_{~@KJ2{*nuMBB-fYh!Qz3~?zKI|KZ)%=yS=y&+x>Q?_*!fa*ynqS zvAxCmdd6aV&|c^{7~9+ITRrDud&r(E^~LtEy;wRL+q>=g(%*O+@{jhG4%ZgWF3y~s zZX~m{rR3oQ4?XtmL^4sCuO}1L#hDY&S5Gd@Ru;!=^Noqd;?h(jX_{{8BysW4>SBGS zHlI8+cHr5G{iL-&(8>{+sV9}Bu~<1?ovSRKN@^#P@rh@Wuwc5jkUTTrs4mV|8lX~{ zO};!g`Sf(7vGB!m`2^&s2RX*3YI9|Xe7Q-4_mb0fpGxH~t zZ&Vki&o0)JuhpQ#+*v4eCYh`rKXkfwXzJ(}PJZRklTX@VtJ#8`wMCn;lQwM)OKcWn zOQ;{V1NM+TX3yeGBq$Y|w|Zz*!}=5Uyj8Jl2|Fqn8OOePP?$hj#OPF@)_r&PnWTmC zQSey=@0q|MfmCCVjr;efavap#3EN;nwPVpzyl&T4?}Dh}qh* z*J!`n^9TkI$o=!GZm-xMpLpSUd&-hz@6ZVImErTeAN}SSxHvR|c7np}7@xv-?OkuR z{Ox6bXawtfa1(CDy|@Rfn?E2L2KtaHt^Nig;ZfkmKSK6fv;OLD*6&$Au|A2J*GLdV ze(CeYh2kw(_hE51*0thJGR5kt_51(h7hL<%`y9dLg>8)}ODctr5*yBDz2eGX+3e~i z?i;w+d#T&LB8YR}z(r;pH!gVQfjaODSoI(WNclA@pY@oBtU_4IAz4(DzW5ZDFb}9y za}D>EjyeAu7icNYvag+7K?>qPIZ1`K<$Bbx6|)QT0UiMtTsnCEtbV>z97+lbu(d);FX zK!2Xv$MF2OsrB+Ww6?5?ep~5c5Zym zaGcavjqxU55}sPGd5!1xb+nY$gYh7_H~CT?*PBN(rxkUex3VS@tV4;OlONYQ&C}*= z``^sB3Jv1KS$Ymm&ih=|K3{x4o{@M~iYpO0`24`d7*m2);*muI#>myt;!5gc&DuvT zB(e6dj=ChEjfnZt2Sa;gtBvVtziQFlfF90$|B=!$JR5n8-fp{rQ-_aewxTK?8t*?M zS-qD3$geUh@IEOt`j6n*Y-=;mJl>?DzFUl(WI0-k7G%6#TZUyCL61}eNv)dafh$vK zAVcX`aRsLomZI8RNq(hcz7pLq7Ix&;aF+7B$M{v6-V=znGPlkR#JS6n;z zUGUH1`|h94qv>3=@t{0htuvyS$UfVWxX|EJ@72rx^n3O4;8?U;(6w|7{@R~uApBW# zo$n$q_QC~=)$z>t+7>*=?!+_hZMHX~ArzWx?jjvVNy!|>a=2)`T^Gtj4+xgWj0{o6l`11F5uPz&wC&RXFZ82=)!q zWO%s!OUL?iyeR{%%iJWzpdTlTw@G(9fin5{nmT*hmfwdcaxPux{GuF!JgPp)zPXe4{QKkj` zLbOm_T;UGRa-6pc^(R(dE017?lk=x8c^)w%H~BTalVggVsuc%x4zIlpzXCjFMf!u5D7A&e+~Bad6zJ|KRlc17OQi-H_=+0i5_{hYA=q+TVb_p z7yHLulB<`cJ$)J2g*+;p-45}CKCe?qv|J}qXu~g~wFOe8AIjQF$zP8!0*DIugt#0r zP-d2+lM++|dMj4Q3+P=O+sq=48Zn{oIfBYH+pH7x3UYP8hO;I-JDv-kSDt*X z2s43Jr)M$W6LQqx|G6B!8G|S@am&l^Jw_3os;yY@F|Y_P)ev(+Jd|ILgtrIHl!a?c zP217S z=Qtz_%IV~7luc1Xr-yF<7%|#ocsN_IHQpU(e$FSm4Ln?&gdu5AH-3b3^tf<#9a~4b z^rFwKExV3>dvlIBdTdSoHJs;EuAQA^k}UG5PTDJqY>2}DQV#B@IBwbVqV8U0iaPNC zI6K3+j92*r(V&0&cj2ebMfJ(G9r0LYmATw zg?XGloiAlhp7}5z^V67RKJM2Ue$Dd)f@tjEmkQbYulzgU4g6duE2|~H>L4fNC4Ql_ zv>8h|F1@tx-{U&Q6k198sczL%`l?Rf7zN5ahosz|8G9zl*zxZ=qx}##-4cj0GQbWV9wf&b5r!ZUf$v`Dd&Y?qvaXD;`{Pk z{K``%wbfDnMv1oj=mYY?e7Ik8x!rb_m%Xp0Yb8xKx2!0Kg#h5nfC@l5lZb_=RM@m8O7!UBa7ORwxY~;(tlXo`=C#?5<&73@2 zSzBgQWK5&|iBPaVFlJr@%{IZ9@{le+E?dTneNyy!_5!w{R+f-uetsT7W<#CChjp_) z^W`EE=Y+My7qQHUt1l`>C;3l=n+nUW8$>(h|%Vp)3;fr7k#Do^9UkOj6NOj^$yV> zpbgwemA;yuwPqdiNr?w|qUbgP*(ROhu5zLHv0d zx$X#zef2L{tFrC+`0{A0p%xVd%lYDuGt9uX5=jt&=`e$x1rqrQ?onHnB9301+?x& ze=m6L1+Tq7F#F6cC>a0DirHOHp}b?3>_GW56!84)D9UpvADi8c_TA@DJ~X=rWA|YH yy@v966zsnbJns9B+5Mn-|BuWbcpL?5K9`_;&uky|?*rX^-$wzTeZS-X#rrSWussO? literal 0 HcmV?d00001 diff --git a/imconfig.h b/imconfig.h index d556cbaf1..13e5d7a5f 100644 --- a/imconfig.h +++ b/imconfig.h @@ -14,6 +14,8 @@ #pragma once +#define WIN98 + //---- Define assertion handler. Defaults to calling assert(). // If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) diff --git a/imgui.cpp b/imgui.cpp index 76da8c68d..5b9c5f7da 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3523,8 +3523,12 @@ void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, const float border_size = g.Style.FrameBorderSize; if (border && border_size > 0.0f) { +#ifdef WIN98 + WinAddRect(p_min, p_max, true); +#else window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size); +#endif } } @@ -6193,7 +6197,48 @@ static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_ window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); } -static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size) +void ImGui::WinAddRect(const ImVec2& min, const ImVec2& max, bool inset) +{ + ImU32 top_left = IM_COL32(255,255,255,255); + ImU32 bottom_right = IM_COL32(0,0,0,255); + ImU32 top_left_inner = IM_COL32(223,223,223,255); + ImU32 bottom_right_inner = IM_COL32(128,128,128,255); + + if (inset) { + ImU32 tmp = top_left; top_left = bottom_right; bottom_right = tmp; + tmp = top_left_inner; top_left_inner = bottom_right_inner; bottom_right_inner = tmp; + } + + // ImU32 fill_col = IM_COL32(192,192,192,255); + + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + ImVec2 a = min + ImVec2(0.5f, 0.5f); + ImVec2 b = max - ImVec2(0.5f, 0.5f); + + draw_list->PathLineTo(ImVec2(a.x, b.y)); + draw_list->PathLineTo(a); + draw_list->PathLineTo(ImVec2(b.x, a.y)); + draw_list->PathStroke(top_left, false, 1.0f); + + draw_list->PathLineTo(ImVec2(a.x, b.y)); + draw_list->PathLineTo(b); + draw_list->PathLineTo(ImVec2(b.x, a.y)); + draw_list->PathStroke(bottom_right, false, 1.0f); + + + draw_list->PathLineTo(ImVec2(a.x, b.y) + ImVec2(1, -1)); + draw_list->PathLineTo(a + ImVec2(1, 1)); + draw_list->PathLineTo(ImVec2(b.x, a.y) + ImVec2(-1, 1)); + draw_list->PathStroke(top_left_inner, false, 1.0f); + + draw_list->PathLineTo(ImVec2(a.x, b.y) + ImVec2(1, -1)); + draw_list->PathLineTo(b + ImVec2(-1, -1)); + draw_list->PathLineTo(ImVec2(b.x, a.y) + ImVec2(-1, 1)); + draw_list->PathStroke(bottom_right_inner, false, 1.0f); +} + +#ifndef WIN98 +static void RenderWindowOuterSingleBorder(ImGuiWindow * window, int border_n, ImU32 border_col, float border_size) { const ImGuiResizeBorderDef& def = resize_border_def[border_n]; const float rounding = window->WindowRounding; @@ -6202,12 +6247,19 @@ static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f); window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size); } +#endif -static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) +static void ImGui::RenderWindowOuterBorders(ImGuiWindow * window) { ImGuiContext& g = *GImGui; const float border_size = window->WindowBorderSize; const ImU32 border_col = GetColorU32(ImGuiCol_Border); + +#ifdef WIN98 // window borders + IM_UNUSED(g); + if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground)) + WinAddRect(window->Pos, window->Pos + window->Size, false); +#else if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0) window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize); else if (border_size > 0.0f) @@ -6228,6 +6280,7 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) float y = window->Pos.y + window->TitleBarHeight - 1; window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize); } +#endif } // Draw background and borders @@ -6340,6 +6393,11 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl float pad_l = style.FramePadding.x; float pad_r = style.FramePadding.x; float button_sz = g.FontSize; +#ifdef WIN98 // draw title bar + button_sz = 16.0f; + // pad_l = 0.0f; + pad_r = 0.0f; +#endif ImVec2 close_button_pos; ImVec2 collapse_button_pos; if (has_close_button) @@ -6358,6 +6416,38 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl pad_l += button_sz + style.ItemInnerSpacing.x; } +#ifdef WIN98 // windows style title bar + + close_button_pos += ImVec2(0.0f, 2.0f); + collapse_button_pos += ImVec2(0.0f, 2.0f); + + ImU32 col_left = IM_COL32(128,128,128,255); + ImU32 col_right = IM_COL32(181,181,181,255); + + bool focused = IsWindowFocused(ImGuiFocusedFlags_ChildWindows); + if (focused) { + + // Windows98 colors are (0,0,128), (16,132,208) + // This code generates the secondary color from the primary while + // keeping the original windows colors + col_left = GetColorU32(ImGuiCol_TitleBgActive); + + ImVec4 secondary = GetStyleColorVec4(ImGuiCol_TitleBgActive); + ImVec4 secondary_hsv; + ColorConvertRGBtoHSV(secondary.x, secondary.y, secondary.z, secondary_hsv.x, secondary_hsv.y, secondary_hsv.z); + secondary_hsv.x -= 0.1f; + if (secondary_hsv.x < 0.0f) secondary_hsv.x += 1.0f; + secondary_hsv.y *= 0.92f; + secondary_hsv.z *= 1.625f; + ColorConvertHSVtoRGB(secondary_hsv.x, secondary_hsv.y, secondary_hsv.z, secondary.x, secondary.y, secondary.z); + + col_right = ColorConvertFloat4ToU32(secondary); + } + + + window->DrawList->AddRectFilledMultiColor(title_bar_rect.Min, title_bar_rect.Max, col_left, col_right, col_right, col_left); +#endif + // Collapse button (submitting first so it gets priority when choosing a navigation init fallback) if (has_collapse_button) if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos)) @@ -6390,6 +6480,14 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl pad_r = ImMax(pad_r, pad_extend * centerness); } +#ifdef WIN98 // windows title font + if (focused) PushStyleColor(ImGuiCol_Text, IM_COL32(255,255,255,255)); + else PushStyleColor(ImGuiCol_Text, IM_COL32(192,192,192,255)); + ImGuiIO& io = ImGui::GetIO(); + ImFont* font = io.Fonts->Fonts[1]; // Assume the icon font is here. pretty bad + PushFont(font); +#endif + ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y); ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y); if (flags & ImGuiWindowFlags_UnsavedDocument) @@ -6406,6 +6504,11 @@ 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); + +#ifdef WIN98 + PopFont(); + PopStyleColor(); +#endif } void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window) @@ -7119,7 +7222,16 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) + { +#ifdef WIN98 // title bar sizing + ImRect inset_title_rect = title_bar_rect; + inset_title_rect.Min += ImVec2(2.0f, 2.0f); + inset_title_rect.Max -= ImVec2(2.0f, 0.0f); + RenderWindowTitleBarContents(window, inset_title_rect, name, p_open); +#else RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open); +#endif + } // Clear hit test shape every frame window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0; diff --git a/imgui.h b/imgui.h index d3a74704a..61f06341d 100644 --- a/imgui.h +++ b/imgui.h @@ -1008,6 +1008,11 @@ namespace ImGui IMGUI_API void* MemAlloc(size_t size); IMGUI_API void MemFree(void* ptr); + // Windows98 functions + IMGUI_API void WinAddRect(const ImVec2& min, const ImVec2& max, bool inset); + IMGUI_API void StyleWin98(ImGuiStyle* dst = NULL); + + } // namespace ImGui //----------------------------------------------------------------------------- diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 171889f2c..1f1afa12b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -175,6 +175,12 @@ using namespace IMGUI_STB_NAMESPACE; void ImGui::StyleColorsDark(ImGuiStyle* dst) { +#ifdef WIN98 + // These colors don't make sense with win98 so just call this anyway + // also means I don't have to change all the examples + StyleWin98(dst); + return; +#else ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; @@ -231,10 +237,17 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); +#endif } void ImGui::StyleColorsClassic(ImGuiStyle* dst) { +#ifdef WIN98 + // These colors don't make sense with win98 so just call this anyway + // also means I don't have to change all the examples + StyleWin98(dst); + return; +#else ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; @@ -291,11 +304,19 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +#endif } // Those light colors are better suited with a thicker font than the default one + FrameBorder void ImGui::StyleColorsLight(ImGuiStyle* dst) { +#ifdef WIN98 + // These colors don't make sense with win98 so just call this anyway + // also means I don't have to change all the examples + StyleWin98(dst); + return; +#else + ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); ImVec4* colors = style->Colors; @@ -352,8 +373,131 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +#endif } +// Windows style config +#ifdef WIN98 +void ImGui::StyleWin98(ImGuiStyle* dst) +{ + ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); + style->FrameBorderSize = 1.0f; + style->FramePadding = ImVec2(4.0f, 4.0f); + style->WindowMenuButtonPosition = ImGuiDir_Right; + style->ScrollbarSize = 16.0f; + + ImVec4* colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.75f, 0.75f, 0.75f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.75f, 0.75f, 0.75f, 1.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.75f, 0.75f, 0.75f, 1.00f); + colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_FrameBgActive] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.00f, 0.00f, 0.50f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f); + colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f); + colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 0.62f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_Tab] = ImVec4(0.76f, 0.80f, 0.84f, 0.95f); + colors[ImGuiCol_TabHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_TabActive] = ImVec4(0.60f, 0.73f, 0.88f, 0.95f); + colors[ImGuiCol_TabUnfocused] = ImVec4(0.92f, 0.92f, 0.94f, 0.95f); + colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.74f, 0.82f, 0.91f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); + + + if (dst != NULL) return; + + // Fonts + Icons + ImGuiIO& io = ImGui::GetIO(); + for (int i = 0; i < io.Fonts->ConfigData.size(); i++) { + if (strcmp(io.Fonts->ConfigData[i].Name, "MS Sans Serif")) { + return; + } + } + ImFont *font = io.Fonts->AddFontFromFileTTF("../../MS Sans Serif.ttf", 12.0f, NULL, io.Fonts->GetGlyphRangesDefault()); + io.Fonts->AddFontFromFileTTF("../../MS Sans Serif Bold.ttf", 12.0f, NULL, io.Fonts->GetGlyphRangesDefault()); + + // Run-length encoding of some icons + // In retrorespect I should have used an icon map like FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS + unsigned char minimize[] = {86,6,6,6,0}; + unsigned char close[] = {14,2,4,2,5,2,2,2,7,4,9,2,9,4,7,2,2,2,5,2,4,2,0}; + unsigned char *run_length[] = {minimize, close}; + + int rect_ids[IM_ARRAYSIZE(run_length)]; + for (int i = 0; i < IM_ARRAYSIZE(run_length); i++) { + rect_ids[i] = io.Fonts->AddCustomRectFontGlyph(font, (ImWchar)(214 + i), 12, 9, 13+1); + } + + io.Fonts->Build(); + + unsigned char* tex_pixels = NULL; + int tex_width, tex_height; + io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); + + for (int i = 0; i < IM_ARRAYSIZE(run_length); i++) { + + int rect_id = rect_ids[i]; + if (const ImFontAtlasCustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) { + bool black = false; + unsigned char* run = run_length[i]; + int run_size = 0; + + for (int y = 0; y < rect->Height; y++) + { + ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X); + for (int x = rect->Width; x > 0; x--) { + if (black) *p = IM_COL32(255, 0, 0, 255); + p ++; + run_size ++; + if (run_size == *run) { + run_size = 0; + run ++; + black = !black; + if (*run == 0) goto done; + } + } + } + done:; + } + } + + +} +#endif + //----------------------------------------------------------------------------- // [SECTION] ImDrawList //----------------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4c3b1c046..10224e666 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -719,12 +719,22 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); +#ifdef WIN98 + const ImU32 fill_col = GetColorU32(ImGuiCol_WindowBg); + window->DrawList->AddRectFilled(bb.Min, bb.Max, fill_col, 0.0f); + + WinAddRect(bb.Min, bb.Max, (held && hovered)); + PushStyleColor(ImGuiCol_Text, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); + PopStyleColor(); +#else RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); if (g.LogEnabled) LogSetNextTextDecoration("[", "]"); RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); +#endif // Automatically close popups //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) @@ -818,7 +828,11 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) // Tweak 1: Shrink hit-testing area if button covers an abnormally large proportion of the visible region. That's in order to facilitate moving the window away. (#3825) // This may better be applied as a general hit-rect reduction mechanism for all widgets to ensure the area to move window is always accessible? +#ifdef WIN98 // close button size + const ImRect bb(pos, pos + ImVec2(16.0f, 14.0f)); +#else const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize)); +#endif ImRect bb_interact = bb; const float area_to_visible_ratio = window->OuterRectClipped.GetArea() / bb.GetArea(); if (area_to_visible_ratio < 1.5f) @@ -837,14 +851,28 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) // FIXME: Clarify this mess ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); ImVec2 center = bb.GetCenter(); + +#ifdef WIN98 // close button + IM_UNUSED(col); + const ImU32 fill_col = GetColorU32(ImGuiCol_WindowBg); + window->DrawList->AddRectFilled(bb.Min, bb.Max, fill_col, 0.0f); + WinAddRect(bb.Min, bb.Max, hovered && held); +#else if (hovered) window->DrawList->AddCircleFilled(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col); +#endif float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; ImU32 cross_col = GetColorU32(ImGuiCol_Text); center -= ImVec2(0.5f, 0.5f); +#ifdef WIN98 // close button icon + IM_UNUSED(cross_col); + IM_UNUSED(cross_extent); + RenderText(bb.Min + ImVec2(2.0f, 2.0f), "\u00D7"); +#else window->DrawList->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); window->DrawList->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); +#endif return pressed; } @@ -854,7 +882,11 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; +#ifdef WIN98 // collapse button size + ImRect bb(pos, pos + ImVec2(16.0f, 14.0f)); +#else ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize)); +#endif bool is_clipped = !ItemAdd(bb, id); bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); @@ -864,9 +896,20 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) // Render ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); ImU32 text_col = GetColorU32(ImGuiCol_Text); +#ifdef WIN98 // collapse button + IM_UNUSED(bg_col); + IM_UNUSED(text_col); + const ImU32 fill_col = GetColorU32(ImGuiCol_WindowBg); + window->DrawList->AddRectFilled(bb.Min, bb.Max, fill_col, 0.0f); + WinAddRect(bb.Min, bb.Max, hovered && held); + + // collapse icon + RenderText(bb.Min + ImVec2(2.0f, 2.0f), "\u00D6"); +#else if (hovered || held) window->DrawList->AddCircleFilled(bb.GetCenter() + ImVec2(0.0f, -0.5f), g.FontSize * 0.5f + 1.0f, bg_col); RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); +#endif // Switch to moving the window after mouse is moved beyond the initial drag threshold if (IsItemActive() && IsMouseDragging(0)) @@ -951,8 +994,19 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 const ImGuiStyle& style = g.Style; const bool allow_interaction = (alpha >= 1.0f); +#ifdef WIN98 + IM_UNUSED(flags); + ImRect bb = bb_frame; + float button_size = (axis == ImGuiAxis_X) ? bb.GetHeight() : bb.GetWidth(); + ImVec2 button_size_rect(button_size, button_size); + ImVec2 main_axis((axis == ImGuiAxis_X) ? 1.0f : 0.0f, (axis == ImGuiAxis_X) ? 0.0f : 1.0f); + ImVec2 main_axis_button_size = main_axis * button_size; + + bb.Expand(main_axis * -button_size); +#else ImRect bb = bb_frame; bb.Expand(ImVec2(-ImClamp(IM_TRUNC((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_TRUNC((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f))); +#endif // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight(); @@ -1017,6 +1071,33 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 } // Render +#ifdef WIN98 // scrollbar + + ImRect grab_rect; + if (axis == ImGuiAxis_X) { + grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y); + } else { + grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels); + } + WinAddRect(grab_rect.Min, grab_rect.Max, false); + { + const ImGuiID up_id = window->GetID("##scrollup"); + ImRect button_bounds(bb_frame.Min, bb_frame.Min + button_size_rect); + bool held_up = false; + bool hovered_up = false; + /*bool pressed_up = */ ButtonBehavior(button_bounds, up_id, &hovered_up, &held_up, 0); + WinAddRect(button_bounds.Min, button_bounds.Max, (held_up && hovered_up)); + } + { + const ImGuiID down_id = window->GetID("##scrolldown"); + ImVec2 pos = bb_frame.Min + main_axis * (((axis == ImGuiAxis_X) ? bb_frame.GetWidth() : bb_frame.GetHeight()) - button_size); + ImRect button_bounds(pos, pos + button_size_rect); + bool held_down = false; + bool hovered_down = false; + /*bool pressed_down =*/ ButtonBehavior(button_bounds, down_id, &hovered_down, &held_down, 0); + WinAddRect(button_bounds.Min, button_bounds.Max, (held_down && hovered_down)); + } +#else const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg); const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha); window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, flags); @@ -1026,6 +1107,7 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 else grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels); window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding); +#endif return held; } From 15545a7925e99c275fc6b2a7754ae0b6206c3310 Mon Sep 17 00:00:00 2001 From: Jake Coxon Date: Mon, 20 Jul 2020 21:04:15 +0100 Subject: [PATCH 0002/2359] Screenshot and readme --- README.md | 5 +++++ screenshot.png | Bin 0 -> 40795 bytes 2 files changed, 5 insertions(+) create mode 100644 README.md create mode 100644 screenshot.png diff --git a/README.md b/README.md new file mode 100644 index 000000000..4df8d64e4 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +This is a fork of [Dear ImGui](https://github.com/ocornut/imgui) to style based on Windows 98 + +[Compare diff from master](https://github.com/JakeCoxon/imgui-win98/compare/master...JakeCoxon:win98) + +![Screenshot](screenshot.png) \ No newline at end of file diff --git a/screenshot.png b/screenshot.png new file mode 100644 index 0000000000000000000000000000000000000000..8e6c06a53ff4466ea540df891136e28b29d58d64 GIT binary patch literal 40795 zcmd3OXH-*L)GbvIq^Kw;B`8v)OYcQcq$9ltMMQ)E0-?9SRa6v|7U?L`ArvV>DB-G9 z={=zdgcdp^LLl%CD&Fsn_s0AEe%vv{_3T+h7XCRT{H70;CM zS-^y*&exETAH8>3;i9>LEU3gd>$Ec;kI0?`da2(%O-boU_ol?w-k9vZAKBQ|TWVV5 zW8P{jKD0rU&(o>yfyj$apY}Rc;XyV=(SGTLnj{;TY)nD>&dkysxBLcf6mAy5ynO!L z9NXH`j1H>dT4dbd%X7@DX<#F(gyf97AEs%~q~@XIp*(fU=$(dXSR*;3 z?(G|l|5(D*0+udir|5)va&i{ru$GF8C%LH0KvRT=r87W5| z+SDLLN=jVi(UEGDqe11WT?+~o91Z({k|mogx#vSZl0HU8rbec% zscz~|zS3aRdrixC%EFt{_xk1Vl`MVhTq>_;x?d_7lF!yV1f-ISe_?&*=hP?{!Q`m= zO3BvvUt_wC8EVDz$huMEJEuhKpA9R~G6i$G!cNcrWrL6*;XM z83l7V85K7f>@>5S0!&_<`oBx$w1ZT%?pCzFZ}@d@{1r7%#bn)fO>VNkp9OBA{QveA z&)`MLz3Kj(_sHjAe_pit-0pNFQ(?B2bC4BWjA>YlBT_As>J(`FaYay2P)PSBn?E8kCLgM8k}8EDB=@gbHqr`?)%xU7f)?M+OTsDyf2-{BT_p-8Ju-@!V0{rax5 zPO3xP`d-H4J(*t7^Y_I zmrc3L=z&G@`ynW)^=swW7+_|N&T)!$vMHx$1*ih~)I2egM&H$cuk$c(nNB!z?cGik z%9Qq%%xC2g;ttH!bDywES)oEbMSx71r|u_$_Y#L6HsNiW@ZoEvBy=g~o16&ejDXyW z4SVyc^!ig*IWK1j!pgHlmJj!p%{A#`R{4 z0pa;8+Dv%F(T=AfqMCK_`?^g#y4&tko19ZO#ELdLn+`gmBuo-DszB zeW%swis)41_l$owG0ODxtI&mE^%7B|Gj3+)HfJ6+m=p!GHzQ)ME*3-9&L9qkSli8& zBXL>gzV{u9D$w`UFixx%3vSRBb0+@G2536RujiF9RMQ$8eLtb(eES_2tnXA!jr)Z4 z?(ML(egV`_w1%jBubIuD3-PMe!Iq_UHA7gzcgL1G=y>jUQ-VV>RHx|)JEhf6?QLUm zcI*v@*G^-`6QLig3x352>fz~)JRjLkR@?x;IC|Qb2!D3z=5g?#5N916?~NejwkN2_ zBQW|#-}rt{v;#Fo(*}K$(aNo98%+&Ls*ALG^Yl*ipFU9hg)Z*0c&gi1R+=&0`CqxH-2 z-!(Oz@M#&|o1A}FQVkgE_V&|?>VNPxpS@M##&I=On3{|OZIkYG)4W*Xy|P8u#;6}b zpzr16Ckx|Ct0(%IL@YfbE^lWZ9Z)D!Ys&9M^d|{{_S&>A-ZpheB{pRBI%35wcciDj zY&2-?yo)%7bKvt1U#R$4$KBsqc+A&a`c9bNx%@12!7nuL@=WS0>0C{VllM7w$HB|l z{es#zyMHTHP_E&+zcJ_66DXe@txd;BjSj_ph@-gANxxfHx?fk9(cyZp*SleTJhTnb z$(y-aFYA&HD zpE_KfLQra8Rk90gwFAz~^po{Nk~|(?7jS@j=H5_pcUS7VUX7{ouT+=7&7qw}ykgJp zedYnh&9uKjWT&s;52@m(4h+>J(7)6JymsOMm!-Yxj1?r(g0 zaqA4%K3(qqhCG@rGPV!gaWXq@8K}8Nqu~q5z5 z>{xHjhARoJ!1u`gp#1YaBeZ&63+Alll|lua6V=XkPFmy{`28~kFD;4(KtyC>);{Js z?&=|0pL@rDU%hL;)h;vKHEYQWx@JgvPU^3QhI}~Q_rDfrme=z*kN+dJdx-+d6I;XWPX3l!y5kNXF(!S#ROj^`Zt()HE z6LRiOD`>I`bRp<6;Bp;XW6XZ8O{Avw^>}Oh9vzZu^_~h?>@D_1@!vMBF)*-~CG5n8 zCeO6>`bd7(ot$R2Z8iGxoe~V!1!R~I((&JjZO4D~1 zrYl9!#h;+HZYfcu0sQwH&sRf5EA3d{T20}2Tfa5NX=I5}SUX<>wvRllkE*6KPr{yI z$|oI{%jMBn_d+ONsJ&HgyW0Cj;Qbi~@eb)Q$;&*^GAcn3Im5`YM;d7yySMfdIyQ+l zR;)8`gADXvoc4zOqE{glOf@uDydF{c4B%rvraf2mjG7-zqKVlSV<-ah&a&AF)ZPzL_i^4)$E~4mho&Gg*|y#w$>>~H3u_*0cK3nt3p=%w4?GqjDbbPMdxg*s zwZytS@5)d?5K(E9={MwSg{K3NQ6hqCDP}JNHEN5oo5Rxf<=XJ_UrZan4>MzC52Qdn zH}KM1CSh3iI{>sA%Z_kys3lJ-e9%vV=IbrRd&tRxUGu=nR2 z7JTz9PBn3tQNVn(Y&R!EKztFE$ zn6sVFyLZLl9`?Pix3=Hq?2HIC8rQp`{47-ZH>#|7-gdHF`YN9s73o*wG9f@KS`uv< zR*3ti)OH2fjVlts{$K!;b`BiRXx_I;C`v=_CC#yC{CoR5e12wnC^BhB$LlA%4Px&r z-r*=)PhtL(+u_}j>XtXHd+4dQmetyYsGZc$2}FO6-&pqU6nPA<-mHQI{Ry-IQ*wzs z!X}CQWcveK@BuCJxWT-!#M%FDBJUo*IE>ocUMOm4Xt;@6d-0>(zv~Bi>@AAH-&sKb zpo@|g5n>s_H(@kN7f%ZhTY{pM^3@&AQ`v{^VfEhu`IAo@NL}7m9uswmZ`TmCT+t(3 zTpO0x)EFpId9%ReR{VB#J}&8NJ5N!Iz!Su*#r+Wf^;9e8V5zbm21mGOtYY4YBDJhzS|NS2KpbqRdI{UP(;5S8?6V0H_=(oei6NH z`O1qXw!juvV62Vc9#pSdv6`Aq*s9EoxKC5*g5il(GM0$^&9jbI^3_W+#TpS&IHk#Y zU}5xw$@gYV?(=5Y%YXk)d@*xFD+ zX+f95+}|*EaHEn-68}FUo2urPl+<4V0j$z%vgXxM1l!>+uKGKoSWbJ+SBK9Z>}?NC zPTIe}a2(`+UKzy<@W_V^1o}3^npztsRI_!1zoD@dudMkH*H^j ziZ5KovAVB)ul{jUn#hBbC*TkTK7Z!OIWwgCW$Z#mkZ88FecyJEYE#_y+CnfdkC5+U zZw7NbZe{F~P@vfwVXr4FbTYpJbg{*^^A|uKPl;tFuz8>T0Q7SqfD+vxkNVBqoGTAa zwRns@7ddshobPCRTwB2uhPs5xx{q5{1x<)aShv2R7>Ny@>ly^Tn%PojxC{?>tGvV&i zt%Os(4Q%O`?xOO@?Ap~G?5ws7&rF(E{kZbA2bO0wKPhF|1QBJgz?r5@)g9tqhf}y< z-$u8trko%3<$b2|J7yfDfgy{Y*dXB%r9KP3kZeiH+Vn1juL*l$X&lFNAWdbgEJMY; zAl^*k7I=11L4>_@j^;16RU3wjB|tLw9JE$0e-&Ib0j;X#X>rvf3(0C8j40s9tcIQi zZ>{;d2XpEgArHWK{+17Rjg}W(jQ(J*TMU3ju4QJ^=VLGW^UEYIs3>@3e|qUU3Gtbp zFXwzN=%)k4#v2RPF#L=TaN(Ek?(xmmllfq)UWjv#c3ah0wpnp(GUohgMuvEzqh3V3 zzG#-Q+)<5DGJvN!p0<1R{?E)=rla02Z(&Jal8Z2-k9wFy?FtD5!gA|v8g$mClqY7| z$VRp#+z^&U*;b+`jv~jLs(|26$=$LAG}dj+X~HVzlMM;`n9%dQzQv5T*Z@GQp|J}= zEu31{vA(R)>015MvG}S^Z3m=(-vQ0#l$fi`qoNYor+%;7Vl=QHz}F%rh~0QyCs@G5rn!7umbk! zv(qxD_ox4+gfnjdaG~+P>-pa$wLgK8{fE>4Qs86&XjOj}AbOW<_I=PTnNfvd%%=h& zM68dnw|h{h*V2Buo-Cy2^#!Nu)DC0CLalV$Ai>V1g$FK8xpl-=t$0z$3DBI01?D8$ z^@D0AF6vOi0yB6^7VS15md681^n&z-S`)?-{1_O$9mkkn$A2OnZ1*^~UT-%EvjfXi zT5b0z5(Laa?RcciPysoD2I=(8{jNLAHfNgW3(42EX zr8PLddR8tZ30g9n$+8x&l^J@U{?8=9lz>dKZTr%gMwKq`&IGO8qWQ+Vwf>h2ui0e< zH+laeG0Y5@1BA|+y6Wm&hP?N~!!r5xjXEyqL0{Nq?mYY>9>}K&TX(w!E=*k?!l~11 ztYWIuXWt#{ZD`yr3|H()iidrr$zh@eo;L(D#UH9F;+&}r_rJ$lzU-D_Z!7g=Yo-^%#?JBcUO zGRC)ZR`0Jbzy_@KNIj!VxEaw>`BVUJy0o2qukxvKn#&+smJNm7#5VFWeD>61T}Unz zA047oeZiq4BUa#R_@~lx2>-mxMv6WCP`23HsE*~*1VXgq$*xtK-T>GjqFse`JcsWB zOOCpIq2yp4$(OsXE6e@7V_vhX&DxVZ^AJ=1lW7xI0&LJ#fBj1DJQQE3Ca1mttu1c} z+9R>NddPV!?W+-37_-CLo^tT$G3FwF%P%DbL~NGoF^h1x6wCEdv5H8G+__P&FZ4WG zVUqO9D{){#t(_(KTYY=3pF)XAN49cewnyQDv3ABlRdERf2j7CWnumQF!k;q%iQR$d za#7mX4vX#~VX}2!nO?o*Yixh##k@xXT==4g#fu?xM?+B`557f#tJn*!s@?cSGsD0oVYQ zn4rnYT98p70hh?vqEu=7Ke~DT8j7_;g4GNx7`TUpONu=IA6x&K-Z3+W#&9Yoy}cR% z0RO>E7hbT@2FLw*+0WSJ7!3pygL?scbMgbDGsb#@4a=l{gsK? z6aj+pOz2KHhAfKjgi&#et5Ik@409z$k`tx)n&0l53Pm z(S4fzYx|4y7#(S1v7PbG&E2bWVmHo@UxPs!m(X)cWxtPW} zP_BtsHT0T*+0hL#4tqV6>%rlg?&U7rX?%1ws#kjgAzAkQt_eln(T8tI8bN|pxXh8xpQ`txK7hxbY>`;`q-vh@ z_N>TN9oCzOL(7ipZ{&AokHzPA6FT?51r~EpX3kKmC+I24*B4o0s;qteIze#Uqi5#UB zCgMb+8>u6=XNtweTwjsgxBra{Om}K2#m|Ru?Mzs>t2RnSz9!w{qK#0JJql>e3B1fB z(ACvLzkfK~NYzlcmYW<*II=i=kvbIisE={(fW&z?CAOzSp-g zJD*g$Ct3q4YYKq*-OGN^l%@q5?D4`D3OTIArL?Tw=U-MiI@m5bcr!`b|LJJ)$0maT z#g-Sbp+04ekbiFg(!*#7>2owBL4A*|%~lNRk!`Z<8W8__F&;nCp4wvl&3zeMSz0YS z>F-E*w(~<#zbdc7tR?4qbhEYAdBp;REG1wrUD{c%7W_OMvjHIYJk0O1Pu{9xz>VbJ zmai~xS%;s*OzkLiUkvK`FCA5ltG(^|9Qsw5&y?5thG3a@oSwSZ36huOD#f@oeFR|% zyfKMrJ<9sZka)aViveYCn}Ji8S-bZ-<|t5u_#=1cz~8Jjp0%MC%dlnE3PJ}5QVuw@ zd0+fw>AraL*m{IfQkkDN%6<#o*RnyH@_n}3ek}CnB`llrI&~?do3y5Z^H^`+?aG`` zy59S5F0U5Zg=!{~jBO0KTH_2-6NtUJu|6DkY`~6w%5h~Kqjly_I7U{rziOa%uW z_5Qx|neyCI&!)RU2YGn$R?tz8#pSi`qkW5c#j!rrX6bIw5Y4Bf+;@kIVfAwRkJj(t z7n=fdh+o3CGQW44qzQQgAo9!*^>g36IIEnkfRyJeb^eDggG(;l=;Kf2?^t8fC@OJr>0)A79E(s zvTwDfqBQN|)+HT*k-l4FWl5JbgA^HJ5`u1iQ&AjsJwJ$-F4cb}a^y%h0WTf>lVjXc z!q=i1J*CZ4cO3^*7=~1uA+18$e!A#p-PqHkuPB<0Q=wja_fFNzhY^!<)S*)ZT|&y| zKz^CkB3zzKSh*f~Idp_!L-q6a{e}Vm8I7=py8RqbDuXiSN63!Hpy+rhZh!KTy8|c#v;BaBEvQ;7Bac+tbc7f@LRSEM>ZX4 zNG9?OZCW+x*6oKKVQU-CAECqUV(PZT4ySE%Z*c96fYI|RyzJ@4V=~q3fNjN3V4`T*tny5q=sJ{Incy^J6hUzMS>Le;)g(o z-TaRyv>qbsT!{Uw1kAOOQ4o=snX!Hly0kqd3*sT{&mf~)&q=MZ9<_t>RSuk;ku{&} zX2lMf!rm+Rx`jF0%QUS_k!bLUHP)#{ad_D7QqjuJ?fir*WUxe9ITUXhq(#dU^F7bq zOs&XIS7#~0czRZ*Dya3Y6F;@?-Bxnr1jQ^b5H?QU(w7U9+R<0Nvtl6_+nCT|l!>@5 z5k2cy^$Cc3zLe--qcG}Rox2F4VD(U`et$q06IWV8Nvwd<)(G5Jk(lp8i2S$@CiX2K zf=G{`I~x1sh=^QAFhRB`C@i1b_hNYH-c<40!8Qo7Mv4X@Vh&$4nPCvn!yHmL;jn4f zb%+#pI8vC+w9Iv|78C|;IyxVQWL#T2Y-Td^I~rp$YdxBq3Sb^wi}eUupj%w)?w)L6 z=^1~#avr?*lcmVQ@30hqIN#u) z094v2MekO{1=@Q|T?rb5t$~ij!U_WC4A*Hs^@sUf9G$edmy`gNPs&1>6F{W8%tFd} zF;e$WGrC70Qk$U#I4!-r1k-q^qfCH@1|5BeC>w3Xw&2UDsB7znL7|>{>M&rj_UVVB zj?%-7eilM6jJoeGYR+6W11#?kR2;gChvs$8hCa*bxwkwq6mZHfX@&03YY9@G9ZPNY z3CLLQD&&f-L{4R+m|cPv#@)g`4(`^{Se`ae16jB`Ax= z<Bkqzo)l9iMFTR_8eV{K*%yFZh`krSH-u6T|rO4WQ~%uV&d{NRD)w1(9Px>}T#{ zzN>4UTYD<`8A5c^)dK!`=ppu?r#V+;alFJ=qH)KtsYzvl_`a0XZi-d2YdyF2kK|_> zmS3fEHd=D(Dn_@}I8}Lfc5dX9=-kTq+P`KGV{G`Dfq?N`W#hsdMmp8YD=5YnO<>dOWn&JvF_?48sE^&3@uJE%rT@H-GhQAZv}e-R?pkf7plq9@rkeQ{b2B zokiiYk{&D{vLZHvSfI1u9wMwxfKHl+B;pQAy3sN@Oh-1VCQA#bgQpVdRV6)R-Q8%x z_S|mFB=To(CSOn`!0M6e+zfhtj>A#1x)B(P{ayYII>G0DX{e=vyiZgy9HgBYt3ib} zbZlje60N71Vy;;7Q!?Su_ipO;N00w)oGGUPa}A(cn}P}0@?J1(=tdY!xNSgn(leOg zR6&w5c^L>bVy9xNj5!ht^HX1k`DZNExZ_MyG3%vb@ydG8FZI?mB}|P*7hB;Gje0VM z-WCtR68n<-V8J2`SKEc@T+%`aJvH^`{SYp;yv@g z$uSh;0mgHO+#&viqSN~>d_e-flJWpMenNq3Ig2A?%1yQ`ogII;@u(=13g$#5YFAgO z_mm*Qyqg_Hq{QF-Cy?J9S$&VykN%4!)p3farU(?V7K@Rqcz8tZ=UZ_T@bOlHgWtd+ z9`#Z!XHphT#WU=`wjy~uc(X1%tr}fkKrKr}?3GI2RRCyr_LYrYrlXd|(kDQ{Ans?D zcxjL6r@(+c;hhkNAl0Iy*Q7{)i|F9@ZvTgb=>8=%(4v4N-{g&?lsM-8Fzs{iLNda* zu@7hxn1!!w>^C)O-n-wmGH$REA;I~Vwgc@bKugKqvZUYNOX4>GKj=I%OYc7?{a4My zu95itzY4eBD?s0T6%`mbQEEU${1Pm9lJiYRlZ1kmDCm8pQ-|(W{-<`Ykxk@sUSlan zwMy&1A$))eWa@kTxOb1poeO1Fxm%xlR20K3`&JQ(V(k-+OZB+j9@V1*YteM&Am5Th zh(g%mc4lS~F!Iy#35mZBly4+ilQ(8lLCEq|ShF7NmjM`KZUjyY|7|Bie_AG?pjF8F zWx1Ub)6gLeDD~TI*U6WeA=G4ZC7rvOcW-km!#U>&ZWp~z9Ew-(0B_2s(O+eF`d$P5 z3a110SDmCHx8x4G53x$S?ESp8ZhI?5&>`85>~w)x;&L_%Mwj#+<1-SXK15x(d^C>#d{kf~mWa9#*R)O523G+qFedd%K zP&HG9;pwaq0*jF#nW=m7E0Orl#^B1PehVEeLb0ZC`34s41a|hGl^gb+GDf!40v=@v zA7|o)!NTC#76!ldG^QJOUa5Sm;9F485>Nm?Ryg)h0q^MYvFW@aK(^ieA?1R5(CH!Q=jUg5nh_NMyfVG>8BhaoR2z}8q z{YwFPGKnT9GCB(kgbZoR_HhY>898XAMg5xH&sx!U>Rla$ZNrld#@banJ6d7-wElD0&LIu8EwK0at;$8+{=mlZ5eFZ}~*?it^Q$ z#5*^O+TWj)BGmW+Tfp~Uvms{m_vg{zsDFvUaC?&IOWljh_;7-IC2-Y;V z>S87g6%kK3Iww4=kURCRII@utMYyCIpK8NfRgy)d9U5DDKd=?9q|IUdn zRr1e)Ss$f1iH5uNPd&tp#u&N9GdTV+LyomOhUS)=TOz80?1|OBdAj~7lWF}E8Smf? z>`B?yi=E7JY7T9%pXAPG|E%8aJAi}m4=V$_Rb36XQjw0n0(#Fz<5d60{ue&S{n>6# zoq?j^oMp8Mvbe#*S^SRyIZ6(!(9`JR%>I|L5op_$%*hn`K!F6eq&ej?0VqxP;xu7j z+hHy!GReC-ThB?=O|jZ0xBgnJ0zlt>+XigM^|kMKeRnc( zU^xFprPv2p?>{WW6Tmu*5nhB;iVD&;m0WBWI-9O3$?mY9Pd z92UgOP6c}>y6>Fu_kU25JxZU>A~j@nfZ841b%B@a?vwePQq9rg>uu9*lTl~-|fXoxDhsv#}ID&J#ez1)p|*wIR6_6w2jmA6+7eCv~Q zPg2U8zm+qIbtgUvDX@cCtguFzsm-H=*KDo%olPM6ULgMGfw*1f{f;R) z-wsqLeCLD6QW6mp5Q=(Hm5Ju z)H=46wZHlcB1n|*WyI18KJhEGaY@;R@}S`=!!TM78FJOwG{4O}*Gwm3CmOl?Oq9y^ z>92}GRFkVT$|}rr$+)Vf#zOVf;$)WXve54M&c~LS1qsGH!_3J=^q{_eaT?1V1qZPk z!tIdk*l`cF2fByM(**Sk>{rDTGAXvVA0^5*+U*MufQP#~U}`oLH6BwLPlMq_W2zA3 zEA!ZNOrL$-mQMAN%2fks6-))rNm;QQorraX=C`HSyME`=So=-fFWAJSjRUva$SnOXW0gnbQ|qI zd%h1m*laDb0Ebk4jQG2h7fx?Ht+>$K$3TH&_Fr%Kxt#v9CwN{`D7jA*5ks?kj|Z)7 zCRkO}6*99)u})W%P6c#qY@mk}eqN4sopjm*br$9k@A4ts#ZeVq$*SHcx! zHjWoQ04$>Qp3KxFtEToOC{Q1SMFE*Nq%Gnc)ol&#jHbkax=XE`PbN5KyBjfy3v&ex zec`CS^sCGxF1DS5V*CD6J*TN(3hIIh2f@#`SPCin(kA<|wW4S147=CL9b1=G>A70v z{no~V&rsJLInm3ISUWN@YwOpF{~kvKe7^*RmEg z&v<@AA&Ue7RB0&vxOu?e9B_V&)oevAixU9UQwH#dsv0swA2Th4c<1e|eri0J`4)|1 zw`z{?EAB_|1{4B>NrQiS+APy@ZgM=JL{`qyJ3FGQ0uIZUNfMYcFtp%-(3Yp zyKZkbFLj!t?s~2keLZCYm*Pf%nxWDv&KDmmlRYjQhH1mPgzd)<+&TsO!u^Kc4I7nt zzTB?aF<2!bhF7y;w8Nspnz$8eQCWiLk z63aKB^IsdU{lsk|?sKrKF$naSxenPc=W)K|3nDlT1T2Hy*S3ZZ6$BE%<)yn54M8;z z&tdx|i{fk*Fb0kDPgF33_flLimltQY3eG#M8j|QFRcR~vH^gTiPtkO#sgb8si1Sl> z(S_ch_MZ9r;%OaGs;a2TO=YW%hdyu(j;4HGiwMoI(a!kP z;F28t(tCWzfAlYZQidId4wjPMDP|XBK@#Us+Q?)_9W<jizXzD%$nT`G5U^8l7yN`Op*DbW;k_=`59!(= zdaEp|74FFG6!aZR{-J?vS}qUTT9OHZ%y!#F@#mG@sUaG0>5c-lD)J92BBLOk_h(DQ zdj#`LWGyTqp%?f z{)?b`P1(ru`40~XN8JGmM~u5Sua|Ll!pm8nw{k9!JARWs$sT-q;gU7%^`8|CvZhV7 zF3iB2S!e}CTt{LcE3B%Av0fO=v}r}|Z2d~={KvW498QrQe4=|o(OPZdT>qHw7PQO{&fWkon7PFO)M#S$41b)r);gS=k!7;d|XyDrnV2*<`7hLly*x zNUvv5?v}h2r?k9tH_7lCtzKeyrWT-Ef)}p)u71)BvkG#iSpuAgu}L6g1-*W-2;!%#O16yx!uivlIi@dgp76QUXR)k1%FU zQldZ-pS}V_c$Bb!y2C70CB65Lf1f^mg0OF>GXi;iYnD-8dsBL@@t9?fLXP_YS8+Wn zHG0#71tvqYv8pN{Gi*G+VK)v!kN##Bz7(~;_gSsLE^zHUrRh2yhEbmC*&URt1#a9` z2@wFt1_>8sENdmN+$LGN_nWAK?!C!~!_{sQqzRdkD((&;oIP6y!kwI!xyMX8C5F@p z^|YG=742$*Xx&oOZ1bLo6xFZHhN$wh2ows3jBRgU=@5v(BcQS3-k&VlC!dnaT+n+9eF z0AQ*W`LA}IJhA(e6NpW~;y^-a(PE9e_w(`KSBkb3_JOlk1FmnZP6-L$oc25|hcZJz z*C)&Zauy<%L-=SucOX@I{M`uwyk%9cRC3-(SBtd0m}lYc&+3}@-YU2Utns}g;Pr!& zl{h06s9J8Sx!R}~_4MRs>g>vMbB25`O;7>pc)|pzW6+({*Z|C2G896 zCm(kRv_+{&!gz+TosltfDxZA{4)2f1G>zx@9U?a(K1{&;SzrOOs#g8xn*(*@^Ju-0 zJ2(}ScOA&V*-KwXd&t!j?mh#K;7kT@cP%G7XIQm=oJw&^vwfR2qRjSAiifvb%ZVz?N=AKoUSt(JEKMuG_7axv z`_Pf}R*TCjAK7qiWQsSIRMPY;TF6g-fp6-5S!tl?w@^mgA+e639&h&kv>^K#1s8a`@z4p7h0Ro`>sl=2i=tj@S$<0CdqWmv!#_*r0c(JO8iq2Gf}tO^pq z_*Y>CzMC^&_;is;?mgIAPIU~|jKO=q8>`t1A2}`lwnj0J${f$3wyk2k3-p3EwYltNC@6J>QX^%XE%sGgh#e0pz)p3?B0cT?m;^RSF&0v;oCseo;N1UU zdzhn5yo;#Y*R0)N>M6awClT_KCo253|LeyhQ2jqCV@P%93UCAqI3t2G8-6WEdis?7 z^HX}BE1uYnL>*a_NuGfS-cok;xZw?7NnjC>Ap!4DUHd-iDc~;&KYF~fXt*4`?2<(U z459CS?~u!`hs%Z$YUg3l;ouSckXci^2hjQh3jx$0qXVx%Sr_L$OYHZx>O9F)Alc?? zKR5UIT3lSW|9wh7)T(;8S-tG7+~t_gzBk_c@+rcx6;<8!#tx4e)%@+-Jp+3Fd?QC% zVVPlH%wYd;snkvT4o&2agI3|h9Ab4%a{-G!Ja~trKPJO_g+DoRUm&*lnbd-hfkr{o z&&i-f-`lF&$vwp@alYD4JZoi-{iJg9&*MKBAcPgsIYUrLe7z9R`h%>p89p%YwPA@9BY|Rz1rm@G%z^eofn-e; z3JUA<_VLz!_ECaCs|mS3phZ>L6@GXKPlpNnX24ne&h0`e#J*+-W{92WBa)%$=dJ>3 z2rX>#F&#!HW>z@WLf!(HK?6t%t_KlR6xr7{c4uQPN*jsG9gRYs0u%WbGQ_Ox$kP*P zi3y7SuVuqJjY%{Q=R+pkLnby#!A&X_x~q!ZWrwzJ|Ltb(MHAR%O1(?scjt?H?0{mH zeI8e-h}+(eY1t$UL5qn3X#ltj$VQ5HN7ra=8v>zNl)3CKs(r*C|k`>J=7_9Ekk0F+kJmH+1@`&NA^Lr z!r2accS^CW{|PA3sV8Jc>sx=5?`n$a#T{4jBfXd5BQJV-9xH$SSe5m$>VvG34rIg& z(1R6oH+Eh`bn1u9u&KQ4{bHfgbNJ*$Oaybs9YOf_42eeAe&3~qRpPH8r9 ztDFks%Z0zTohn(Q<&{)xI9QVbHTB!WkAO4x&&6K-JQ30kh)(P;bI)TzvK`y_K>9ds zF-p{2dX%9OqJZmUdHPEmMjvZK(MNXf-jHhF6=s&%v2SwqlrIFb&%iiffaUZla6Z}D zOJCOs-EPsJdWj}eSMfc->#iOjskCbIt4$$E?pb~EPObfVW4cqy(ERw-&~|~6z0c05 zyRqvmy1fkdb?`=hOufv61SpCp5KD|d(bJcH!E5C;RBBODmQf^%kr^zCeYpmh4(wO{wXN&*_^=KGgc94=2g4e|-~%R*<*Qv1&ZJU@TZy$8E@ z+*xlMtNTf;V)cH1spi}{rHchCg0Z*gexD5hx>t`o-97bvZ-l!L=T((1U!>PR@x9MP zkcEA{#|;19&I_HGmM1PAkUD|;TF+H`UYe-^=z*zFm0zOAJ;4UX_j@@?b=|cer;7gT z(shsmWQ%NY0ZZ_np~B;QwpX?Gk3D!sWC;UgPrjHef2)_{Q1mT+*(AqoP@3?v`7-IpNM(E7$b9JNj?+bfqvW8}^_KS39}tXln%j1T*!;s+Sl1H2J=xGc5urBX%dsxF2qVW5Tip}L8qR+ur^)R1!MxI3ot%eWbM z+al~7(DqsUX vMG*Bv2LL&>a^7JfDe?F;_h-)^H}U1MA;sHzmC=peuj{wNwWE$R zg3OJ?65pYo%j&ehJlt%cVOjA_XHGhL=S-pPfYxeYg0DZ#jEei2aMb>K6WGOhXCU)% zr(^OF+*D?UvB+1;@uk9DvE{jriflXdcr7}vF=DEkIGKp`*NK^zdSIVwt!p1;pIL}3 z9&4#sE(lF%cOQ(!@+srD&z@SkUYo)00nRSW1Rtw~2}&i^&f=*DoyU#!C=EcJ__xjU z>IB|Zd@`dc6OP}c0#352NNHX2XQ47@So5JAVi;+q@`>zOEnaSMX>ZQ4WaLjA&J#zu?4Sp>z@Y( zA`)AmnfV?_blaVgnOg6K`RzW}20%7AmDufFw@JcW1k#Y_amSuIpH1T8Qyf67ThHD*y#)BifqDVs?_;azW?`AeLQQ%z78()~ZYXSw*X z`{cI({vX)yHYEE@{yCjqgMqTWff#>0h%wYrJ}(+L4=i^Fz<-+L9l^dXQ?abjkFpl4 zqm#AX&Xc0bIXf0C;~vQk_UTg<<^AJz9W^Ti?q|qA{Bj4ZWMn*-{{wpi*JZ=z+_=u# zS(>|GY<{UjbI*&qdxTgwogSq9@Xr`XArQMr4HP+Iq<;97uO_}NM5kQz(yu(x@IUj! z7YhqmkxInY7iVWPi+=idn1ubjh658zckd=s(S1jKMj54rHXZdN;2cJajoM0?*5|(H% z2v`330(3$5*m*Jr_m)y0NM5I~=T}iJ!ZXJYN5l=koZJwovg<6!SniB#?d7KvmHprK zPwTl3w?LOZ`Xu}O{y8<_k%tq;Hri{Uj&0w*o#FVJWSKaZvcO{LwjCJ2-|qObB$6!A zQERg7+rpJLsr=;Sy5))7j|0d-=ds`D{Ld*WJ`FWlovG0Q?Y(D^THLT- z!vmfSyGjP^nuk?!YXxRtd{&1GcoiJo{WSEV4Lo?4Y6h>@31k&P>d0DXYJB@MNRUY4 z&NxEFASsb}#}HN;kH646pTXn~Z**&^gB;84XaG)G1B`%rrunru$Qz}PUb-_c>ZvJ~ z(H(NU^OaGf0a`pHfP478uP4(2Spzn~3nZ9{2Eum^itB(lPG~De_#G|uWR?P5@De3R z{)pBYY1!CY*Z(>(&(x0FPcQ7o^)PF`}3DyiR&SvtHh>8qJQE-v*RW@wG~jr ztnB$Gy}q7{RJ-Z_m-AV^?)z6?{H{HZ3XqdvrvSZBW~inbwqSVfUd3^3>n+XiZvl?Y zcLG1yFsf)9iSngg)Ls90eCqC>*I~3uFY&9p5Wc(1`yRfs~mn`e)t96!{RKgQh1$s>~?ZGZ4BF5$$*8)k+N>k@m5 zd0lmK2yseP7h3f&`M}fy&S;PdJOgQm{qpXL{R-Xj0e<^huN=k$gLH)a8$Q@d;Jjm)=VuJZ`Mn| zFyUhry##?Q>-g0V3n6KEY*X3$|9HB*S~G>92_!D%6~XNTUA7~uIhtKdaugl|@Sk*g zQ5wv&Iv&R@PEDbBcAR*#>h$*=Dht%YN3uRxcE=6R#0>ZGwON_YL>s=K>eTo=^6-{8 zK)k3Z_`NAo(cuzHEJ7s2yCRlL9Z%~h^aPQJc!hkkv8}qdVW-rm)BPrsX{x;zOKK(y zE2A-$k*NxZs&gY1m|0@tch`wkdsjp}u+Yb0!!b z%1*7D?40z!MXGih!>3kOhxGpGZz#U$(BHiJEt=Khp7F};bVdFfse~PqTHo6tJ6BSS zn9uoje>{)7YvD9zrV}~nQ*Z4;Fcee`BDit3StD#ER?*9k{sofc@;IqIN<+=r4Ffct zB)8Vh-`Le3>907f^`*dYT=?xIlwCg#R|{BfYS48T8WW_U!7wzVgY%X3no{Bdg$*vr z4QW>koy&}vk{Vl=GSbEpG`uoPp;ll4lVmAdiku0wD3`0qH)verrVa)(I_!PhRS1nw zfee5EoB+D>zb+s%nnEXU*DBfYsdB7eg2Dlm<+GR~&-fPDAILA1G=WfBovpJ!W1Eyg zLCufxX-H^2?AOM{ean(`wgAoEm3 zixMFt>*A8Kuj`U=#kGFt>ht-2zrWw(=g;eUyZ8M*=QWR2^wXZwk!VT>FE>^0tRSIDx$-@f80KKf=gNn&xHlMi%kJ+dpM`aYnVX{v-`y`kW z(De_@#~Q6;ge1f&XH}$chf{pUontQnMv*u~I>5xf@Vtejszlp>aK4m06NEsMw5g4# zV+)cYDaZ79`V?>4i@1fhmRz>khr_?pIssL+zd-(Hfh?ZSVA^B`l>eW7m}5amZvwyP z`Ig)GR}$=eu2JKMuCFs#0-(nmJpWgVXWs**iRPX6JedKobqEB}DTQV!+X79#2b4F4 zTdAkB^}|c)|04`&xekIp){;8tf7F@c_|aUyU(sym$l=4@@MNh;-uUbNgD~Ic|1&M-295R8n84T! zJEoi)D9yq6@tUgiVGZQUln~FTYdeRe^?Tm%?dACaGrLYU=a-^cl-NN<5%}%=zYUG7 z&d-(U4lZ80RhH8#bUUt$1v>UCO+|UTKZ2J`f?A8mdO7SuN_8AGqkagsJ?;aOZPL4G z=7`C~$a}iAILs;kaGMyv91i#wjEI@tCYvMgzPPsWB%?JDHy`e^XJ#>fa{%@P{{kT# zNpOOatxn}AWSK}Yyp0ok?b}YQF4E2zp#-%1ILs*($10dtbp*`mWk&qi$k8O}cu(gV zyGpegDSD0OdG&_%(^e9T^D1|z^0<)&mm=ZKiR^_-sB}hznR3!g$)n0Hr>-a@B6_{d zDsvpT3a3^CfQ<_q$l$Lr!_PNjk!`!QuUgDsWY!vsbI;J2XX z_Qo=`kE`2`&UO32nIAb`lFDNqclpKM%;Wg5yyROqBO7HIbrh=W1C}SWj!woKH6;Dy zD$N)wmEcUaChIB~z$6q!5`og$h`U=#oOpW0Ahat(*~+FNtX|T}NpY%A==Y~1QpO$) zJATS-`I%ugLB!l-(+p2UXOX-6;P>uKqZG@l*+ysV`%nem^lwHAEM>kduia%0_3BBDxr5za9ZD*iXV_^`|0g-D zQ2(18y7Wjl-K45!>beFr$hHn20Fa^yR_hwm98$Hm{;*RreO+IE)6plOK#|3YN>}To z%*?VGVdqQj#AkhtLhEmf4@pq%No|wkZpE1wjL51aB-Yh?uE@-Jl)D#I3}&VXPFI90XB+F#J2P%I)mNUz2MuEdV-jvZQL z>3~j(&)(3@Gy4HhxtOQtX6#*i(RA}_Ew-$X6wz3y{F~v-(5L-Z!q)j z4?ogEj^oolmNd1qeqLuPjLV&9suN?d49?l4m<0^7ELc90t`302BZ(+ur<_82a2&7)irsv z4P~dvd(e#tY=yq~4Oi3w4z;6eYnYgs;eii)D@nK*mNeyH%=(x&sn}=GP}Z>)PJN7?E{Gw}Kp)zJ02z?TI`r%(reoTOzc50(Df59Qz4qaAg!2@$ z2E(|q(=2(D)tN2v8NgiO60w?_kgdeiNm^Qx_l*^-< zyCR9Ce_0lPB*>>s5>q?hew;p+SjXL*x2{D6eO_77rmOAYn^gm?dsoV=+Cv7`6;u{|E&_gb>sL=RAjFQ%@+gb}b*pjR;e|mqJ0=X#Sv`Tbtz+ zD>P4y){XVOW-O0rd=A}^uXFMQWnyZ6hDUUhrP3vP>_HjIV2nHGPpU%z1(|u(aKVGC zJ-0Y^HNB3&1)pj^{QKSUb@|Hsffa8{t*h*qPZQ?0s!^daSh8i(poCdQ3|Y4Pg`G$_ zt_5Qqqy>s)^b;hbyPFaPhQl2fJU;FzVQ}77}z%q67@>c#1+wSFqHBkiN}y)TF8KLKYWAk%G*FtG*G$h*H}OckqwIumU}$d#iR$s-_v9e$zh zO%QmZIu63$mQamju!>5_^qs0p+)eJm-=yk(U!$xOJn%djVN~LLZnCZGcwk;Z`l$v3 z!{N3|_{7$A5f4$qu4riLLN9Rg`D)AkAh6fe5U-22r<0tA=Zd+<1Nc`)HIyTbmiE@1{mDsm3cYY+0XJm_{@ z%xQ87;#O00-oDbPRzS|9$Tqni&D#%0v>*T)5NK8ExhNY(_h%7)&d8H$iWn`?WIy;R z#(X-s@8x4*wa~8bdg6-qelH8_j@Nn}{YS4z2d0@a&lm!UEmm>DW5(j zv4r&GDTHw5A-eQZIPh?DEZ2Q7UOkgUfxDVT6rK;>h0h9w{;Sb1WF6XL(=S}lu!oI5 z>?=r|DzLT0M~5UP#N=nGUV?G^ns)~(m}+Ls8}PyC$b(6K?u0JArlP?lJ|a~YG&}=( zrF`>zvC0+1SZ45L&OnH(7RcPVQQL%(+IBb)h=;PhUhASIi+P)OV8U2AGb5buEj%{o zFt%dI8@^Ru%!Q5Y-|#A%|L*55w)uz~(lJ;X_Vyg^tQOv61ow@%8Pub{PW)b7r_FO4 z(tc*{^>+JD?`Ay+V>4^8u>x!FgIMC!XMqPAMrT1qZ^}XZU*w?({l?=5u0X6r_n>xL z+V;6S79R__K@@vmOfi;h8!*+9E=kmLNgIO6#W=1D7q#vtwCeNQ$Ys33*AAjO5Jm`# zg8H>Dm;RI&RUqVP)c_A9h*@#Yc$f~Z5Tu809K3)>W6=AHFcT`oH+p!GhC>sj2y@E? z`k}58VTX4ox{@O4>s9Aw7P%Ubz5@RC?r#|UVFNzvA7`yGJONsHK{~l!AB{L+vsKjV zd+wmJ7lc5I1TX#5{}7;l=c;A;H>9H+v7@MaoT^%8YWGHWyl-Ey8UN`pyk5jX!c2~? z!&__GL856jmfGals@3Oe*tx+stV_w3+UGxWAEK+5O^1bNz*@sj|31S85ja=E)p^++S>u#H0*^{R z!XJ9C$!}5;k>K*j2#)#1^Zk9cx2S*Z7B*u(aMW0e(oKd_HFy$1sSK2(*ZIe;oR0I@ zxTFlhh3k1Z^<{pi*=>B0XhC&u0yX%&)bRx}`PjG1qr*rD;LJL~7pdp$ck5aI6D*yL z8UoZC4Vu-}W1$sYYw<42A}?%L@tRb_TDiP?`5wU?A+`S@+FRr)Q2qQ68sSWD_6vcr zvz{)PUuuz{#GNyf_jVbG#w6Q?$=^r+;BS)^KasQ`LBw3{gjOl~6uc3kRSqsJ{Eg`? zNbVK!l*pkxjLA%YRlP~bYfHXJLV=CJ%t6#42=;Omb)$%={rr*{=)$s(kTL+Lwc1 zzmM1zu%W8a6DiN#IuAM2I(DoK3E%gz2p^%z0f6_{MoOLb>Y^JOTE*11CSV+TPcbLe ziz;0*FHQ7EOt!*HqgSplfzYqG+Gu(?gj7@|N}fpa^YlUG;S)zDQnc{lBR?KHj|f)| zw;WPnc?w-i;l`H|YTCy@$WuS}6aP&&?44}RCgM{vsBUR3Nx4C~0TM^8Ks=yt3e2pLH;xkMN5K)O~ilvp+2mZIL zCWk0jWNmXaFt0i-(Eo6Pte7<&taX4p>#A!gRwz8r;;|A;)UL%?_UXFG9}C+GFo1J< zaGFI}xTi)8I)>Q1$TY2dMS3C51ejO9`8bG^m6C|l@9P$1YK!G{I=g`Lt4#^0rHgwf z`mO~of8j90Jtjg-$1W^J+z3S6Y4KA&lOr&0Y>MW%-(eEN#}-^Ci*>)S$#kEP6gV1i z`FAx^WB1Ile{&XFdlB9-)OkPFbU-I|!flw#rnhiQW2BMMFS`J8T}R&O;|jO#k-n-s zP26y)WiMebhu<1^WAY|-zREW6;`z|fI#sC?vTDr zR8)rK+6nhCBeqWgx9#)(ieQ0Vl%RpR=pgYs!?`hvCCr@36oX*29p}}m(g(~?s!*1k zf>&sZ++9vFxJUUSWu~ajY22sr#~M>}=C5A&9b!C$P%WhG&Ctjk*B6G6YC~eo=zJ<* zq4VE7t)NdC28EUX8z=F?iRL{qrgh6zV+J;rc9)cZDbMw+HRBhENf>QdH1WVy9-51o=LQrYP_}geUJ^iK($~6%D=l_( z*G>=p$iHao?&AD-_znbGtQfLP1Md%@P$ypdde$Cxqp$e!$d&4>N>@y|67!%fZWJf( zR+Zrsdi3L%?UHB!ca=7;f3zcP;1$AEBS;Ioi#)imemTvL`Uk>0xOOxdjEXy?8b(Q1 zwlMfY9|75$o~hP#c|0Nv4;Kx4qgPG`$WpZ7twG|1$E%WXc^mpqheLemN?Z4-Y8Ro9 zuy`2M?)RNPj30wDb++;;=<9g$II>Qf$TqqjQaOP@>&!yhGoCba(>{1Qzb9$1DE+l? zJhu?4+H2s+lTZTbbAG`Ppmc3&#lTBl@k#$Oh7SN{Bmg-@&Ef)SXy5CrG=IWv$Z_|e zkOf%Dk=`brNCI=o?R`cv3gD7U7g;>HdG~BMEl4`BQyj6M(o{l&B%oCIRDf}*N3ff` zTxr*T6@`rnOf=N3z0U!0@NAad^w(UI@Ph2MLdH-+$7WsBB_J{~(T7n-`t?vP7I?ok zq>a^?lhNVYYkPNDq=*uzH$8QnF%dqF?z!koKnhm~8>I=ncr zV$4~vS{Gdo5!g8k6{f#Ia~V@)tgL?x1cj@VZqFMQ$=>rM+3;R%hfL6RIg-&&~O#echvd z{Xa}HMsfi-cQljMR*9LRjSu_okBYQ%!e8mgO#=$i5bGCYcmY2}8#&yMt#E8g^EG3- zrYy)%iWc+FnpDC}w|{5Y>@^#i;)=tCD2Xc)-`pteP0_>~&f68#pO4+y;VyGe_4uSD zv{}I@q6!FwzsTD61twGT3~LAPqU}T*g8v{AkG#&m@oHGrz6Q#RQ_%5^*^gbp3#Idw zcw4LB$1XkWBmmRi7`!xKG$!I>)n6siVO<5sJMcbmBp3%*oY=Bz#lpYT0H*q&whz6+ zN)yUs!9j68zTM={>n^zBptfud7iCl~IoW+`s-V+6mWuUaR$r$ z)UX$}lkW}NA?nM`OStvx$_wF7&AnfEa*&T4XVHqK)^e{pf8NOkI7roT=EJ$ODy}{- z61Lczbis_}L(Zr-KG8~JXChi1?h=Q7V7ld)?kqe~W*uY`@=R9gF|`5kSJ8vG4jiwZ zC}}Q|O8S**rYSjg)ng#>qerd!S3BCciY;^F`p(9bFl=}@Hz9uBfc;oaQ9m!zXL>_O z93Mj~kQ&i!<`fDNj}6?7AIDOzCwj~~2+?aTKQ5~A`=nKS@4Ikf<Yo0U-KNA=4BEXlLMA5j zQ2sW99Y2O(y-pOdg4RvKZxP13uGeY6)8QJ1s?CJP8TX z?IT%_o;Dwl1FNO7TB^2?dU-GmfEH4=bwisq&S&Lc8eE*dA*Np1dE{bZ;bMfLqp(B} zLlQjmfR_^CSs-VKwq4s!g4K*XHvGe+ANf{GnLk`mitIdcJa$^T`72!k{6i<^-SNfj z(NTxnl7U^1-M?fX>a|LGm;T-@a6WTN;rY+iD$(%u^2}(P`^W`O?I33+F)fg&fIPP&Se34BYTeQ9;h&QU;DmuQWOE57rlpIe`yd5&+)^HyCz_43eUxZ@dnV-=9 zCzy8|zndqKq@mbbn)#i9G;-5YYPcjUb#zkxmWfTldHmwX)0%b)hg}oJ@!j;tE)=o# z2k}nu9<=Nn$7?IN)NaX4yJW77$Wj2qTpl!|#s&3-N^-K7K(Dd^%FlSW91a*mzU%X) ztX@n&Uu>v*FPWLWA0||#=$}ermX$EedX+a?-CKGrQCop|(QqfuI!F(v3DngHGv4X% znQ40cCc%0zVePE~4?Q8QVL?%}(tPs@ZrW=*72VYD*4g1P(w~G*uLymkJlum^%?I2r zAT;WE6wy^nnypFOemnsCW#WpL%4wEjueB5XBULb@A`hl|s>Ovww}V5O6JfR@5>yc5?u*5oDAyk%R|Ksr5wFF1KyoGWOKjt)gG6RTDvtJ@XU`Ut+h z0P-^(AfcBX+Lu1spM+Kj1n+Kdx_WqcoZOw5s$iUB8v@-7wn~!%FP3W+vUg5sDq@HJ z9gX=#sSPj2vMtS)|jf+JIY^%=XrxKtet>y}A8(xlX)5y3^?K%e1_O>G3U zjTU9PIzAZ`F4m3$_vrTw_6q~oI}MU@!Tpo3|5eD-c<_oeUw_D6;`r~`)-JxieI;;~ zAYDvOCG?S{6x6pR^@<)On;FsijJtUMm-eS1+?rO8I73a(0?!hd#6PvbDWg>tYV>r# z$+sTCt0)m;Xq7l*e~@_k7`RyUjA8VM!H%egWD!-HC)dtmj$qq0Ym;zdR1!PS7vdSd zF02tN`TZSegFvT=xe;-|-zvx7KP@k-ya0acZYaU(%aa1i8+XsG_{`0yX#D(^-S$>A z8L{2m+VGZ2#P2GawVl1_`nR9cUCCQ@q>(bNiAJA6il}Fap*GwEm-XjI^uR&|_#1#r zmRVkdi<#K%R1Q?`&G0!DH~WWnho>bTzp)X@x8+kFLFMZn{dIBcHoDDt`&PHOXx4yT zPhVzG%>Aa`&7=|Sl_A*9ge~o!NDNf;BLe+7~6PhKkKr<-J)sr4UYs!yf+}idTH-_d4|lTDoGlv*%=V? z0UGA_nl{_I%A`ZRNIa6c`{tmTps-?Azv1s^v3tRZe9XQknU4x8AMLD!^|&feN7Wo> zuw+Wk%hkVTO7%=&>95<3Fh3#yg_^iI6%~`0{BK#DL@+Q4tEuc`{e5&;1 zJbw6=cJ-y3Fw~oBkwA;6h4t-Q)~eZujzE~LX8O6GsO}}Du7dVVx2Ai{Qr*~|>%sKt zIZH4PA@FDY-#MoKmMr;DPLq_>2SRluO%(FtO(ShIqFbOI#16Y(oMCI3zk7|Ctt7ZqR7)p=FD4H*NtqCx|Y#1Th|;bEXLo2($}_YvN&tor)OcVJdW&D@e|Nmr*YhAHXTZ^}Almb-thN>NZpN6|0G3NS6S1En`xp5)79cH+7uuAG&<~lIdyWilw zV;H!NErEAMmGbjLEVJE3KUT2=AIiz99)iY^je|#zn7=>zRFz2I=Ux9kkFIFcZjkrj z#8n%D_x_Y_KZvSw{r`d}rj^u;aErYtEh7qHzN;~PrR(pxAm_ngQ*Wj0(gj*n={xWF zPxMTQcQAb*{ClNC>d(Bx_<9f$(cE&AYjmDI=5MQ0tDfbXWAD#+vG4QwtVu~yPDQxo zl56nTu1zaf{I19YE8Cwf70tg-fqS9~qXBILv1dQ3g2P5a`5NX4KMotExF;JNs;X<$ z^;3>v=*_A2JMJnFt*;f5<- zQ=PXNi`TAr`y9$&lB47OPV8y+wLty<_;= zAs|yXzyCmu>zs|D*^VUUJNR;}08KBFnx~=6>A)|Vx|R=ve{aVgJW78?RIGs8s9%#{ zxHGiq{ViJ}mcwx{am*O8^FCgzHEfY>Rvin29A*w*oDD<#Ds`XDyHbNr+c}%`H;pvLG-d2n3pURjONAh54#;Qo{rMATL z9c_QCHUYQcDO9Mzhf6qkZ7!&^&enXQ%ftn*MR%{J_SBB2#d?L&JfNa`DJ7q>PFR?o z`hGlia&*#JuT0GD-h%@z_o&_a=?W&wyBm`O!AtdKTxOeqc$?19E7M=;{T#24uj|L@ z@ZzK3$t%7*iEA%uXI=z#Qu4LKBog2aPG9hi=1F?iTVc5CZx&oR28tgnV?BY(J+;!# z?_I{WJRmBL>BF_clmUCXq1eErG?TJ4Rx1a4mlZrf(;@l*$t9o>(g@uE`B7PJW*ZPI zu3PaO6iZq=H_h?=l z*B#ABOJiF>7kIPVYummx-RB-_UCMbB!(fEev}Hrhh1FNC&sbJ;S)P)vpaUDiWTJ`u zh6>b*X4FT!)w(>JSWM2+tX01ei)9dV8W8X72F)+KUq1F!a1XsiMQ@%y>@=p~INZCz zN$@6|0~J3r>+2BDV9NYJqF>87(fX{p8%gM&29^(U zx4tdM?L*^0fv>KQocEs#)0iThU~Mk$>se28=*frFV{Z-`EsK5oc3P!^;QVS#oc(y-qZ@t%3P=eI_sA)ABe`EXyO|ZEf&_}asg^VRM#cWS&OmBBk)pSwM-!|9!yO*$&B26T zY2TA~EcVUA?EjMZ?4&Ldqu!aUy*nLGV@bC?rWTIXpb3xX5k3f>hMvR)Fuu)e*Yc{f zt~Z^?R2R%5rSnQW#Y9>MVdtm{%U@nH$t~% z_TfHz`=h`Ct-thbyi*k+e+W+#wcdp#+lB8?uu{t+k%TcCp}<`4=Pl%>cc7bd;9j&_ z$iH?UvMQ$!s%9NT0WaX=2zbk+Fi&1t7UzTUp`Q`_?VxkH?r{|6U{J~eZ>atw5Jo0v}NQl>$j5pn(0~=7hU8KqOOPc5FNR3#!vIfFCJTv zv-YWgx+5>>QODT$FOFTb|8_j-fLnM;@}XA#5+sDQWAdP=wj<&{IRd0<5iq}$D1ZCk zQyo<8@6j5pBQsKh=O+%D0Cw~#trcUBfgr0bz+{O@jt3^(0J!>3=6OnccOh#yyO4|J zdo6vnEZmz^Z8&*~ig{I8=>empMqv}mv*l0xoN+$;Z&zSHw-1*BHZ=7U2d;<6IY+>_ z*e4fmRWa-YKS@92a(l4*V(#R0e=U_b{Fr8XRGYP>MHA{ zv6VRXXNqe6XvcU=gM)i+U3pz}w>Li=QiGEYl(@C%?Ort+=x&5PuTQbory=A&mptmR95ap2i(@5d4d3}^Z z^|PNnZ^4jD82MMpWOs7v3v$+8y4_Gf7hbSfRx=)Ap&zEPFZ6d(0a`^ zE}7wudV>ns6blQ`yFP`{xoMXbhFR6lsex#q6EwRHa=I8jhFQshKZ^_T@lU;TZz^tK zt7Wm&$04X{kPhWN9G6z12wnTq78|}jnJ&Cg$*U;(bKvuZq-^m4AFB(=xCc6rnNW8UX zSz1U#VmN62ZrQIWR(X}Bii^EpJ3$vcnHpdf$eH#5&D8)gsn5cOj>%t7{jT3OJYbo; z_-j3!=9VM#US@S7N(w#oVlZV86*u^B(2JTUIq!R>+0WZ!>Yj$*PMtx0ARXaZ zi!RyiXm2&6GdUo7Lq_}ZZHqQHA&Ej>d=cI+p$$EL^oHVm;iR~&nSuT;ki@y~hSC$Y z^w-CP=L>Bvte5ZB2mhJTIJvg-l7uhro*lX8Hhyjo6v3}RDVXyrp)cZ6k+yQXR&A~U zug8J`?~@o=2l@GC?+@{Vxg?J8L?5z&@cd0|dk&HHck~aEy4%3?Rnl4uAKtg0WSKPP zOO_d)`%uh(t?7tM9rUC~kZud5V5O{blHaf#znrw!P+vY9eIDD3WQN@wlDYEfZg|9j zXmxu!&ax5G%_=9Iod_A{w!Hes%}Hsb-UKYXz4vQEe|cwVkPT~1j=-39@RF_gd2vrO zd;e~7Rgm3^vF~+LClk|YJllacZ$P{HG~k@rYSH`m;zul!`!@MP&k1hU{+JU!VX2Uh z+n9*jlEtdD>d==i*n!iFLU~xrB_~4%ifiEh;uuhZv_e^`_%0LsS?~Lt8shk>CwBHU z^atApC<{N(DhxQg!PSpEIkzt!ew7yW<=IG9|DfG9{M}s5?X=?<7q*_wUvf_DIjm6% z__UgkcQH=35=l0hB#X-EcNSahKMUJm9j9Xq;g6^uTX}OkC4J1h@?qu~)Y~wx-p~9e zPK?jpSmykry~{4xp4@;~Xa7`|drpw*2BVmr>8)d&3;7<%(k=H)-!2=;Osp=|+p^yz%3x4Fk^R&8to_{+(6$fh)8QUNi7TtI@V#@mA z`RpaHJndc9)6dmXWa%=6gV=ImnGTDUT{2s9bwhrJJfy){84Lj-uzdES3FO)FjaThoo+TMOqQ^>CUpj-g#_Zn{WdGUy#dgXtu%Fd9Y^+S{s zk_4|enB$mH9akuOV@qNF<4GHbiqOm}V2-4O(*H2q&6lwm|A#n0B@bI5gM(`~NR?-e znNbfLCtG9XG#Dv|W`7-u0|$)$ ziCYS!?2bRRthY6KgVn7jPMnTMbiw2AUb&FG+A*v}salr!;_RSL(vBrGfASB4R)|MH zQ8-5DVHE2pO!0{@F9@?-Jn z5W)8pp@{#^#k`?H5{Q92JK{uI46+`#BAoxQ&2ePby~{rX12;l{gi9yEe<*afjwl3< z2V&evN=vgL@50A$9eL6=LX`wqvXs@l2Mny%f7(BO*4K5_CinMNk{iTvkEl_0+vnEn zDLAKNJNHX-;jXLV&fnY=C(T6*ho0w71z9&>Fp2H8Jdy%1!7VA~AA3Hy9k@qLXJTw= zMe$S+d1-wvF#bn!W+v=H>K{kpf8|)Tpk`_(BBnee2zeDyrkY?A8|(Fai`BuBo&T+1 zZPMkhNvmF)S71dQVIvASxNH2pkuuR6%BS(mOjIiKwb^qk{PC&+1fe2iDn9_Be*r@+ z)>wG?Zyt_NjcF8bCjY_xsh`I;>>|;7e8Yyz&ZUk9ui0NdjW96wY5jHUve>E>O_HB{r2%{( zGnu{GPI77T^d#*x+jkz)7>BZdJ(xhaZJfG~aJZkks2w67C~N%bTX|)BIb)O`x%E6< za+D)q>u;~omg=%vo>HAreUgiztrw5_?(?^BOVco|^&QW(U*R9k*elD8e@rJVncqE$ z71eKBI3MH~-&kqm!73iZadWrw9Dkm4p!mH%Vc)982(R;Z;()5w3+SElYpCSD%7)3Z zM-faL+?2s}Ap*wHbhEhKqgN<|{~|ahVtaA)W?la7Jf!H}ofI}{Wf?fxwRK~)mh;KR zuyiV3x)Hz73Sb%H}4WZ zy$M$oE+KX=`3=}NeE);dwayIJ?fAH2mw!x`)Z$?a-PjxpjFzh(qoeDr!+|-Z^btk+ zJGBSzMHlwOCe9t&+?>rU7SHC&eUzIf!JaK~%rH5bidINsiP0p-EE~Q3xNiCSLt2-> z5gQ)4<*I;W*fq72w+b2OxUJ+WcZ>^)_G-xQxS=!GBOIB0ILW+Q?ernFzbOua<2#G~ zh2z^Zaz&!OT+t$uCPR07J+ApKgfdjc#-_US2qzV>o%r6pOzO(E-c|^2y{E_vSx)Pb zCpu(isxb6tS1A;S4Kgx2KKFZf*kpWR?ysI*a+I zax?10s&c?g-*FW=$xXf}Sa*1?;$pj|{byS2Z2FH1GKU99laxQLwYiQAE+P01KPBiD zqvF+T;mb<>xY#kS&E~0)WE0y8;`aAaLrc?4g|@tgx%~Bwtpib!OM4gW+8p2QotxZg zFz?#+7{}EYt4oh1nUr$JO8|Qe)rdC)2KEItdse8{1j1z2_wqpW;AJdPV^^}6t1k3j z{P>5H9{uumc=8)lp5*H#?ZuN)O~1Fs_f*W3F|Sy9%+qN(vK+M zPj<^@8mYwGnpz6V&a`z?xu4yz-at#SL+Eamt*tG-#4P}uEso?9R*YM7Xoyy{S;Y`#0cGA-v z^ikW&eTme3?yI~oy6Dmt>u~IH($_Wl_dn)Gd$9Qpqc6yL*U!5nZ9gc(`xG2U22n6* zo));X_wG&V8gppu4A`tq6(13xv2(z>y`qcT)Y!w!dP?4WkxYm!ezkF;Y(D04jcDP9 zU^o+fcjV?wChq2`K9!X}FA!_pl_v<*Omj*-)ue5$?z5C{voT#&8;@IOA63a8em)xl zN7ji34h~+fRuR^o?p3HbdB^09q4)yJYekf16hSuj*2=T2)DM!jaE}eiZgz;eP*!Sg z7d&4C(#z#Xyvp%;d2qO8{e8$ujDjBF`=H%Bp}Z?$-yFh+pcB~JRhe9q0Y4P%K3&ex zw=G^A`f(FBtn};G_N`9YL}aP+r895`{_kj7`Xs`X#y!AWMY7O{U~PAMli@nLArgx42NY9N(D zdnp$9dk@J0EiaO;0nLR_z4+NjGqGug!F`hf-}@gK%lX*oOzPT{n<=a>pjM{2I%JEE z!}j||=bQYtPf`;bfydu#QIy3~f-c{yoF@JI&SvQ>tmUkgma~saY;Ht_?7x|oTzih8 z+M=wK&k-458%-@0N=78rT*{-aYN@VKW#pb2;pZzmdUE0KX8DjTJyS^F{4fr6F(w3P&~%>(-bbPr+?<9eE4kXUm}ek zwBlP7SCFDpfPQjBSoHG5#N8U6(X9JV3CDgKoZJVI{j`5BEVx&lGUS3Dy7hBv>Rv<< zr(Qfu)#o!uEdQQ#eTvV@Njb*8&tU3$qLpx0b7gmp_{cUKX9S7 zC5n&TwJ_mVCty%NjRRh_ii7=7R1s@67HiQAQ&12c%;qv)jEa%BlD^e(RQa$}OLAjO ztHkGDfK217V;>$4<68dx`?u|aWwlnx&Dz7RH_al=yxv{KD06WOKry!tc%`BWIlOef zUAn=!aQsyxk?4X%A}gIomY2PdVPQW$yiu4<&6p*U987K~9rieNcI9l36djXcJzD!* z)%c)+B6NgJbyVov8U+6>&d4RNW7GX?j~t3bA_d&#V=6IZ9FTZ!L!!q?Lx@n;mwNVLS@}iuX8rQ*JRp{ZD5`tO1um zvsWv04W7N|;w8op+icVS00Qwx z>U?4G;IH!6j@O3Jk7BMVp36F8DRHCcMN!#@eQWod+AFb2foAhHoK#^Fivm6sC}8}Q|ga=ePSl~pC1^n z=zAl{r(yRc&K~3WGWPn7inb?ER35aV1=GgSZu%u^_K)be?50BN4yTI|v)$jl08DIY zmtT7VGX{q;?B0Q+2<$Jmk?MYBzt_YOLFI#`tJXpYqwn_Np*n?9qax!N^O#V^D}uLE zir|(iv-mIa!#7@76H5O1>fTV5f()2l*cH{TLJdOIQn>5#ENm|@RwB!laSG6Sb% z;}oNF%WtrojkQria*V!=5CPC;@-*>(zrKH;-!I}rK0#>x3lCj0oQDUrVYFv^5jqkQ z=yWkU?<}}P7t;c{?xyHJ{+oX%Lf*w5kvZIc?{zzzGqe@e%CdU7?F;pr=(=(LCo&TFDz z((1Y?U4cB5r6#|1B#CA7G7M-ISi<; z1_1ghw%3e6Z{}{tDYv{VNz9C&SO1xE$ck}IUo~>==T9}}xmo{7H{;?vJ8iW%H}?CiVBHFu`3yLXu$?Y%TPTz+30sb%j` zj!WwN%mXPG{!Pr!lze8|*=1RBxNCQJSL4O`dq%;cVSQKm=$j6pBu=P~BACSQoGsCY zaOHw)J(Yfk)@`Dn0Tshkfkn+dX8Yn+ zqof+>l{fGXud5eZ*_`F#T`wKhSGEDR96>P4?ZKn@4`+rpY|LV^i%DSAgHZPVdK}hn}L&0uPP1F(=?$SLBV97gA8c)V0X(Y&u{Sm>&y30e~NV`F~% zD*%?MXM5IVTUykXgs@gBzNmd5S{2TO&l~qb9d_?M*)mYYczA#U7 z!c1#jFYfNu49s&iz$1LDu6nr?Zkx?oOzkT>Sf5e9t$G=g@f}(BYb`G6+p`0gt9&@& zRE1zj;lpWQD&mHp%G)fQV5%M*YN^E9W?bBAIsguly7qH%aWSmEC}rx6*)x+PX2U+k zfBI*Twd=9djsj}-8~|JbM`G}>oMuGzCS%2~BC}V*+{@s(+ak6;)7C08r2rlRiPRR) zUQv3(;B~t&Z--Rn^xfuw1$BEf+8>|ORc3j8k*=BakRcgO3wfu{fF%3%(2E(`4Ewbh zUFXS+v^3+Ysw$rwstw>N9|C`MjQ`i)#JMnt0W`Y2{*3_6#}u@Y zD;p=O0wvA=(t0AGU0q#=hD1}Ks4>c+)l00)xvH?>Aa*vV*YLgt8sueM*S!x0pk>7oxf3v5CS1S2^)xu}%bn3(4h zJqzxO`QAR5yDw!fpZ^F5F{%it_U}2uKQ!c{d+EJl#OxrU40s$kr z4IZQt9g}hWAwfw^me-fSBTvvs#&t$EQYe)A5|bxVQc_}_6G={<*^L!h1KxCB4M?V0!Q^Z^JDh&+DKxQi@vQ4#d6@l+$P6iJPjjM0&%cdt;* zb865+cV(WtBs=`eL0|{}5A&6k1M>eA4!JT_hz}3v0PQklD4^g|DC%1bbQy0KUccs; zC>yE7#!5S}4kU*xP-9tLS3d-8QCD?yPX#_8Cb5Rggn^HRP;}e`k?9y~E$EW>vzRO+ zKcY%4@iogFO4S8}(KR}c$j;JzQwm zt)awa8!Vr1&t(rTU623Z33DsWP;{mh;|QkA9a)-^2Xp6`c*5E#&5?~dO#GJj z6@L5DPW5a&07`d;t0KT&omTOw2xYx#iI0z;2lh#mI^wjKc2f^bBpLnPemB*!)?WP) z;nWuZ&p#bJw8f(`r}pcdMj8f zKf5y5RTYaoQUI3>;_jmpRcu_hYiP;ZzMZy>^G21avMi7w8sBa!Cx%1HcIs2n&Qz>n zox9-WE9VgRug>|>sCJF7nfN_hm4YUngVUcDby(&5+q7EcA2SkrP@O*Vw3m;upXF!tX`Sz!ZpN&!cc)GoYL4>OX6~~yekLyEK4`{DU z6l(=l^9LZzNEXp+bD7h+icQ1x?@vM*E6(zt4f6c$xz#&DlStjgcYnS4t5D9qG;Ni% z@Z`ypD7i}5a&Ph#Rjy!LU zP>qG6i;I^Y6{UCu23okVS6z9K%9dhlo25inbZNVGGTQ~WGmmk3bHxc9*v;OqMFZ86&57U1PPNs8 zoAHC6CgecHJ=kZ)sP`?4syJmbPY=z68Tb23X<#d zp(xb0e~ye{?AJYAQDju=%bTB>QW<^Of3F^UFl&$H^K(bhipw^j!pVWsI{k2_`)yDunzX~YDe6Bp1Ifulq5ejEW3Z&v#mjNNWO zGb)|+w{ER55#;-1-0h^UTR9-*7x0GWu;XX)q_yEq%qUhA_-@JPa@^ds{a}Z_#ja^} z$T!@>J2X~Qs6i~-c5~P7K2Zhj0ops=U46m9u9@7bQ=)2L2Gw$_3OOrbV{A69vCR1k zn^q+q8_M`mTlN36b?t#nu77;ytyE;FmKH-?Bl-EY#0%=L0pI`u*LY&BUXtvJ-a)PFZv|lHL!&W-3KO3j2wA{y%H>gi*6|GShyll*+W1%XV5#GJYnJ zWrljJd;|aVaYDBT4e#OvfTBgcI&@@se?3VQEaCJqo$yX@3g#mIf^4!oK!j<4kgt?f zkBd+mMIQQXR@0xnRdz7LlyH1~l9K>tLe}DEFgd1BflnbJCIT9+s(Qt<^;7M`IM%g4 zPuZUQaq?*yrmD;yuLU6UOM2z2R<|iKP8BF1Wr6WPhmD6LYa=?JZi4wkl1vVwtq1}g z3r8dkO-!D!WjX+7Xtx;8%z&OyaV)CZQob!ZpcWHAmqpqxvxaEi^mK`lnVCzS3;F(? zJi~Fv0qt%($(O-Wp^1xjmm`=Rgi*dZ+rkHkX8j|iwHVFXDZ+K^9oJFGsnheIi8(lj$Yf@SWXdDo_7U{ zzQ3Dc2m1BJd7NumPp=mActk*TQ12sxC(R2J*ME@J`^c-|k3LVNl9_xH1_opYi6;Nk zJ~a#z4x5;j}Pf}d=jP0H1NcuG@u(G2na|3e|yW7h5%V`15GhqW9x<5K_dQh;v z>+QlYQ1*f?UBkW;sej4QgnY=)zwcwG{^v&JLp_56s8sCkr%sQZycl&<%Oznd?j4Q% z{C%T)<$C7?-{`qaNHx#vyQUa;63x9=>ZRFiE3)IojWmha`VhJCj+n|)C@B4S zO3jwdSy^E-pX*vbxQFqZ&pLS1(E>V~hVPAw7O;7m@iKKfgo!y`;IT$+Q*gkgU%@dlzm}X)58{E(E zS_F0gSOq+JEulqjF9*@BZ$cD;M3XF$Z3r~r;ywi$^^3^h%|H?A2eAv<3T+|THubNw zbP|-zx*qQgtvP!l4!p|OW%m@ljOAPv)8xXGo58DiB zttZshKMSE6RP*F*(oEqL<1M;E&}i%$;#NDFR2n&CB#1V0euVDk>xp9G-RU$X&iiI3VoD}O;{CgmNR0Q^_>9|e2`)t10dGK-O5(EP!~Y@11SIE zUsIqSrLA8TI}WxOc4%klzb1S8DAuBmSz(crpFZ{Qv!2}?YjD2%jk0Ke*8W#_W|6?q=s+b61-sPLW$yR`x_c9-mru zz4v`@>jPW}NrsZNqr;}CCG10L_Az41Z?JifN|6JvKS+oVbT9O|B*DBZ`OpLkRY$!Z z$jzR9;8QWttL3(R--t&u-l$EsD|>%A$oBCarozSk0oupjLUa)WuV*L}n#V{mSLviE z>ug4*{@r>QYUtSJQ=#vd7w@s{l)D)Y*aB9LBv#xePCcAQMJZo99bZcN)0JzmNE5hU zR7OjAGJcq9-Z2|$umu{`B+F5E(Ohp;%*vUbe7mphd9-etP=Le6qwusN)er4)Yhv`o zdAb4oVDPrE7P>l&v2$Qu01ycr0d>FkIstZ&bGU0DMimbkHc5eMoPaiC1!v=%jZxsuD}_Kp##{k0cnBu-|9?d{rb zTG7^j*f>E*&zTX9Y9jA`!RI$qb=$9&D2xv_2aC|R9y-qIU+**YpmbXWC~A>B&hQK* z#bA>n8gc7e23;MF*Ci7RPNeOv@dm!8Eo*@3Wmt37$sCm6L(w7?6=ekl8=SzFcq$uU z1Y2mXWstt=g|lZ5bGy2zOeuO89hx9S0Y)Cw_M@PW+*Y_2GVio^MGYZg(PB`VJGD|Q zx`*5sAbK{d{yn*D7sr5q3;=8bnkP8MCWVximew26;>xQ~3X)yO3dGpAv%XRZ$dP!H zNkOVScuRp@7i5nhaWIFGzYI-SfdFgx%|~7TNPwJ;$$w`pV?eJfWEnNs?%r(nflr|6 z7H;%p5iypdBKsQ}lmR=Tt-{mnfh`fR**bO!C8_x*Yd8PGE`ovW$g=1-^0T@iOh{rm zyl-moS?a|L0dEJ8b57)L?#c)pkO5Z`$}QnJEq?EXq@iI-`?xTQ`64~w$Wk#)fT0W< z?91Q)v&r}pZr6;Zhu~SjFuF;Of?0>JvhL&u*E#4e-v!mNf%1GEzS*)fVBnt0ww2+* z=*oN1`4OrC7cjiXi=h^Qln%O%zI3vbU~)5#TK;sc8f!!p&PT|TSmU^abu075G9eU0 z+(d#YzN2F~TN3niRW1CZ1Dw@lW{$L|i&=LDm?sp&*e{sYeH-AC%1`Bk#vh9KlDS+7 zCd=FY`pU1FoeaRz~4m(WWCEzWb5&k_?PwHB2X$WZ4mmm2SZ8S>p`iK zO;*AbPU7Z^f*&i~MR9!TR4)$VICvjMn;xUoW`4|UA&|Sx#(C5=F+aN*wFMzWu>3Le zI(}HGo7sQq$4JG7`&Rl(4yeKd*eT5{%wADZ(wy7d8F3IH;q#|IW$xBr2k#ho@eY7x z_Nx)9A#MF7=4oq9K%>UL#;jE7L|>z`>r&i^jKL!au=vX(s_e+)xH?ZEV%g zgdMbwJ=k$1s$Bjra(V-lv)6ss<;E(oKGJ|+*4pb%OXpwUAMgPF4821-0;7FV#@B8E zO>?i$I&Wps5g@q=#gx%ZSzZD#tD5~l$2XEPTUVYPfs_FcA-eIvFC%?hfs22jq}g|6 z%OWVE!1cX)oq$L!ev|Sm2Va^c_6nlcKzP-Xe+CvLIL!4^X)o=D|0^!Osf;(v2j=rD z5=#;Z1O1s=yQ&m#F>Q|+F7HfOBx)4ltDIN!^9}~-*1w1ai%zle=Sbt?n-8C_Oy3m_EIG|i62-;yDnhjV z&BAB2TdSJ6gvo`1g4~L^9`QWR)P{vA4l!?-%gPM}mFX)I6KPvB2IY84CW_zEG+2Dc zgnEt_i}9X#S&7)d{{D8`M?&3>H1D?m2ELEa^aYv^h|m^d{E}QOhT3Rq<9(A;ltcgi z=~a9OM<>lYe^#-d?VGF}c}J6}ILXfccKds2?<~%7VN9u&wLr$dm~Y9*-E(QSyLDmB Y8|6#kpJWo52=KSx%HFcT-1YMR0NC|MU;qFB literal 0 HcmV?d00001 From 3232e7bb0300cd79457ead3c99826006e568d14b Mon Sep 17 00:00:00 2001 From: Jake Coxon Date: Tue, 21 Jul 2020 15:35:31 +0100 Subject: [PATCH 0003/2359] Fix compiling on C++98 --- imgui_draw.cpp | 5 +++-- imgui_widgets.cpp | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1f1afa12b..dba3cf908 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -454,11 +454,12 @@ void ImGui::StyleWin98(ImGuiStyle* dst) // In retrorespect I should have used an icon map like FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS unsigned char minimize[] = {86,6,6,6,0}; unsigned char close[] = {14,2,4,2,5,2,2,2,7,4,9,2,9,4,7,2,2,2,5,2,4,2,0}; - unsigned char *run_length[] = {minimize, close}; + unsigned char *run_length[] = {close, minimize}; int rect_ids[IM_ARRAYSIZE(run_length)]; for (int i = 0; i < IM_ARRAYSIZE(run_length); i++) { - rect_ids[i] = io.Fonts->AddCustomRectFontGlyph(font, (ImWchar)(214 + i), 12, 9, 13+1); + // Starts with unicode multiplication sign and extends + rect_ids[i] = io.Fonts->AddCustomRectFontGlyph(font, (ImWchar)(215 + i), 12, 9, 13+1); } io.Fonts->Build(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 10224e666..a8e479d11 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -868,7 +868,7 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) #ifdef WIN98 // close button icon IM_UNUSED(cross_col); IM_UNUSED(cross_extent); - RenderText(bb.Min + ImVec2(2.0f, 2.0f), "\u00D7"); + RenderText(bb.Min + ImVec2(2.0f, 2.0f), "\xC3\x97"); #else window->DrawList->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); window->DrawList->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); @@ -904,7 +904,7 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) WinAddRect(bb.Min, bb.Max, hovered && held); // collapse icon - RenderText(bb.Min + ImVec2(2.0f, 2.0f), "\u00D6"); + RenderText(bb.Min + ImVec2(2.0f, 2.0f), "\xC3\x98"); #else if (hovered || held) window->DrawList->AddCircleFilled(bb.GetCenter() + ImVec2(0.0f, -0.5f), g.FontSize * 0.5f + 1.0f, bg_col); From d46a0aa06939c5a754bb2cab0e7c464ecb36ce06 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Jun 2024 13:59:46 +0200 Subject: [PATCH 0004/2359] Internals: renamed HoveredIdDisabled to HoveredIdIsDisabled for consistency. --- imgui.cpp | 8 ++++---- imgui_internal.h | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 76da8c68d..d4d3a8a76 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4172,7 +4172,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag // Done with rectangle culling so we can perform heavier checks now. if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) { - g.HoveredIdDisabled = true; + g.HoveredIdIsDisabled = true; return false; } @@ -4207,7 +4207,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag // Release active id if turning disabled if (g.ActiveId == id && id != 0) ClearActiveID(); - g.HoveredIdDisabled = true; + g.HoveredIdIsDisabled = true; return false; } @@ -4510,7 +4510,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() g.MovingWindow = NULL; // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already) - if (g.HoveredIdDisabled) + if (g.HoveredIdIsDisabled) g.MovingWindow = NULL; } else if (root_window == NULL && g.NavWindow != NULL) @@ -4704,7 +4704,7 @@ void ImGui::NewFrame() g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; g.HoveredIdAllowOverlap = false; - g.HoveredIdDisabled = false; + g.HoveredIdIsDisabled = false; // Clear ActiveID if the item is not alive anymore. // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd(). diff --git a/imgui_internal.h b/imgui_internal.h index 27e0bfeb2..9dc832d97 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1971,7 +1971,7 @@ struct ImGuiContext float HoveredIdTimer; // Measure contiguous hovering time float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active bool HoveredIdAllowOverlap; - bool HoveredIdDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. + bool HoveredIdIsDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. bool ItemUnclipByLog; // Disable ItemAdd() clipping, essentially a memory-locality friendly copy of LogEnabled ImGuiID ActiveId; // Active widget ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) @@ -2279,7 +2279,7 @@ struct ImGuiContext DebugHookIdInfo = 0; HoveredId = HoveredIdPreviousFrame = 0; HoveredIdAllowOverlap = false; - HoveredIdDisabled = false; + HoveredIdIsDisabled = false; HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f; ItemUnclipByLog = false; ActiveId = 0; From a47bfb1b5b1b9d62676ccb31d7c8a441d8eb2686 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Jun 2024 15:02:43 +0200 Subject: [PATCH 0005/2359] Examples: GLFW+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR (#7671) --- docs/CHANGELOG.txt | 3 +++ examples/example_glfw_vulkan/main.cpp | 17 +++++++---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 62377c7b6..19b9cd36a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- Examples: GLFW+Vulkan: handle swap chain resize even without Vulkan returning + VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego] + ----------------------------------------------------------------------- VERSION 1.90.8 (Released 2024-06-06) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index b6e53ed8d..26012065a 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -485,17 +485,14 @@ int main(int, char**) glfwPollEvents(); // Resize swap chain? - if (g_SwapChainRebuild) + int fb_width, fb_height; + glfwGetFramebufferSize(window, &fb_width, &fb_height); + if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { - int width, height; - glfwGetFramebufferSize(window, &width, &height); - if (width > 0 && height > 0) - { - ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); - g_MainWindowData.FrameIndex = 0; - g_SwapChainRebuild = false; - } + ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount); + g_MainWindowData.FrameIndex = 0; + g_SwapChainRebuild = false; } // Start the Dear ImGui frame From 7538ca6f405952cb25e42ff7cc22857e2c0b3c14 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Jun 2024 15:04:40 +0200 Subject: [PATCH 0006/2359] Examples: SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR (#7671) --- docs/CHANGELOG.txt | 5 +++-- examples/example_sdl2_vulkan/main.cpp | 17 +++++++---------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 19b9cd36a..8db7c1f9e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,8 +43,9 @@ Breaking changes: Other changes: -- Examples: GLFW+Vulkan: handle swap chain resize even without Vulkan returning - VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego] +- Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan + returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) + [@AndreiNego, @ocornut] ----------------------------------------------------------------------- diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index df0db4d1e..7f8fd0abb 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -494,17 +494,14 @@ int main(int, char**) } // Resize swap chain? - if (g_SwapChainRebuild) + int fb_width, fb_height; + SDL_GetWindowSize(window, &fb_width, &fb_height); + if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { - int width, height; - SDL_GetWindowSize(window, &width, &height); - if (width > 0 && height > 0) - { - ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); - g_MainWindowData.FrameIndex = 0; - g_SwapChainRebuild = false; - } + ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount); + g_MainWindowData.FrameIndex = 0; + g_SwapChainRebuild = false; } // Start the Dear ImGui frame From 22d65c7949d6e78b5f4933733cedf4e0d6a3d11d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Jun 2024 17:42:08 +0200 Subject: [PATCH 0007/2359] Removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages). --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 14 +++++++------- imgui.h | 28 +++++++++++++++++----------- 3 files changed, 27 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8db7c1f9e..b5caca628 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ HOW TO UPDATE? Breaking changes: +- Removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to + ImGuiStoragePair (simpler for many languages). No significant nested type left. + Other changes: - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan diff --git a/imgui.cpp b/imgui.cpp index d4d3a8a76..e16dea2ac 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages). - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library. - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading. - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022): @@ -2502,15 +2503,14 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& //----------------------------------------------------------------------------- // std::lower_bound but without the bullshit -static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector& data, ImGuiID key) +static ImGuiStoragePair* LowerBound(ImVector& data, ImGuiID key) { - ImGuiStorage::ImGuiStoragePair* first = data.Data; - ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size; - size_t count = (size_t)(last - first); - while (count > 0) + ImGuiStoragePair* first = data.Data; + ImGuiStoragePair* last = data.Data + data.Size; + for (size_t count = (size_t)(last - first); count > 0; ) { size_t count2 = count >> 1; - ImGuiStorage::ImGuiStoragePair* mid = first + count2; + ImGuiStoragePair* mid = first + count2; if (mid->key < key) { first = ++mid; @@ -15419,7 +15419,7 @@ void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label) { if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes())) return; - for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data) + for (const ImGuiStoragePair& p : storage->Data) BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer. TreePop(); } diff --git a/imgui.h b/imgui.h index d3a74704a..c48fd4c75 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.90.9 WIP" -#define IMGUI_VERSION_NUM 19080 +#define IMGUI_VERSION_NUM 19081 #define IMGUI_HAS_TABLE /* @@ -178,7 +178,8 @@ struct ImGuiOnceUponAFrame; // Helper for running a block of code not mo struct ImGuiPayload; // User data payload for drag and drop operations struct ImGuiPlatformImeData; // Platform IME data for io.SetPlatformImeDataFn() function. struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) -struct ImGuiStorage; // Helper for key->value storage +struct ImGuiStorage; // Helper for key->value storage (container sorted by key) +struct ImGuiStoragePair; // Helper for key->value storage (pair) struct ImGuiStyle; // Runtime data for styling/colors struct ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) struct ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table @@ -2460,6 +2461,16 @@ struct ImGuiTextBuffer IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); }; +// [Internal] Key+Value for ImGuiStorage +struct ImGuiStoragePair +{ + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + ImGuiStoragePair(ImGuiID _key, int _val) { key = _key; val_i = _val; } + ImGuiStoragePair(ImGuiID _key, float _val) { key = _key; val_f = _val; } + ImGuiStoragePair(ImGuiID _key, void* _val) { key = _key; val_p = _val; } +}; + // Helper: Key->Value storage // Typically you don't have to worry about this since a storage is held within each Window. // We use it to e.g. store collapse state for a tree (Int 0/1) @@ -2471,15 +2482,6 @@ struct ImGuiTextBuffer struct ImGuiStorage { // [Internal] - struct ImGuiStoragePair - { - ImGuiID key; - union { int val_i; float val_f; void* val_p; }; - ImGuiStoragePair(ImGuiID _key, int _val) { key = _key; val_i = _val; } - ImGuiStoragePair(ImGuiID _key, float _val) { key = _key; val_f = _val; } - ImGuiStoragePair(ImGuiID _key, void* _val) { key = _key; val_p = _val; } - }; - ImVector Data; // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) @@ -2508,6 +2510,10 @@ struct ImGuiStorage IMGUI_API void BuildSortByKey(); // Obsolete: use on your own storage if you know only integer are being stored (open/close all tree nodes) IMGUI_API void SetAllInt(int val); + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //typedef ::ImGuiStoragePair ImGuiStoragePair; // 1.90.8: moved type outside struct +#endif }; // Helper: Manually clip large list of items. From 8caf7afbad61cd4ce7fff5bb3f29b35d64865e63 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Jun 2024 19:20:12 +0200 Subject: [PATCH 0008/2359] Internals: made ImLowerBound() accessible in internals + take a span. + rearrange child/popup/tooltips section. Because upcoming rework of ImGuiSelectionBasicStorage will want to do a lower bound on a span. --- imgui.cpp | 40 +++++++++++++++++++--------------------- imgui_internal.h | 17 ++++++++++++----- 2 files changed, 31 insertions(+), 26 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e16dea2ac..f4545ec55 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2503,17 +2503,16 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& //----------------------------------------------------------------------------- // std::lower_bound but without the bullshit -static ImGuiStoragePair* LowerBound(ImVector& data, ImGuiID key) +ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key) { - ImGuiStoragePair* first = data.Data; - ImGuiStoragePair* last = data.Data + data.Size; - for (size_t count = (size_t)(last - first); count > 0; ) + ImGuiStoragePair* in_p = in_begin; + for (size_t count = (size_t)(in_end - in_p); count > 0; ) { size_t count2 = count >> 1; - ImGuiStoragePair* mid = first + count2; + ImGuiStoragePair* mid = in_p + count2; if (mid->key < key) { - first = ++mid; + in_p = ++mid; count -= count2 + 1; } else @@ -2521,7 +2520,7 @@ static ImGuiStoragePair* LowerBound(ImVector& data, ImGuiID ke count = count2; } } - return first; + return in_p; } // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. @@ -2542,7 +2541,7 @@ void ImGuiStorage::BuildSortByKey() int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { - ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); + ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; @@ -2555,7 +2554,7 @@ bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { - ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); + ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; @@ -2563,7 +2562,7 @@ float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { - ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); + ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; @@ -2572,7 +2571,7 @@ void* ImGuiStorage::GetVoidPtr(ImGuiID key) const // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { - ImGuiStoragePair* it = LowerBound(Data, key); + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); if (it == Data.end() || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_i; @@ -2585,7 +2584,7 @@ bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { - ImGuiStoragePair* it = LowerBound(Data, key); + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); if (it == Data.end() || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_f; @@ -2593,7 +2592,7 @@ float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { - ImGuiStoragePair* it = LowerBound(Data, key); + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); if (it == Data.end() || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_p; @@ -2602,7 +2601,7 @@ void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) void ImGuiStorage::SetInt(ImGuiID key, int val) { - ImGuiStoragePair* it = LowerBound(Data, key); + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); if (it == Data.end() || it->key != key) Data.insert(it, ImGuiStoragePair(key, val)); else @@ -2616,7 +2615,7 @@ void ImGuiStorage::SetBool(ImGuiID key, bool val) void ImGuiStorage::SetFloat(ImGuiID key, float val) { - ImGuiStoragePair* it = LowerBound(Data, key); + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); if (it == Data.end() || it->key != key) Data.insert(it, ImGuiStoragePair(key, val)); else @@ -2625,7 +2624,7 @@ void ImGuiStorage::SetFloat(ImGuiID key, float val) void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { - ImGuiStoragePair* it = LowerBound(Data, key); + ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); if (it == Data.end() || it->key != key) Data.insert(it, ImGuiStoragePair(key, val)); else @@ -11238,8 +11237,8 @@ void ImGui::CloseCurrentPopup() window->DC.NavHideHighlightOneFrame = true; } -// Attention! BeginPopup() adds default flags which BeginPopupEx()! -bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) +// Attention! BeginPopup() adds default flags when calling BeginPopupEx()! +bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags) { ImGuiContext& g = *GImGui; if (!IsPopupOpen(id, ImGuiPopupFlags_None)) @@ -11249,13 +11248,12 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) } char name[20]; - if (flags & ImGuiWindowFlags_ChildMenu) + if (extra_window_flags & ImGuiWindowFlags_ChildMenu) ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth else ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame - flags |= ImGuiWindowFlags_Popup; - bool is_open = Begin(name, NULL, flags); + 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(); diff --git a/imgui_internal.h b/imgui_internal.h index 9dc832d97..244cda1a2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -348,6 +348,7 @@ namespace ImStb // - Helper: ImPool<> // - Helper: ImChunkStream<> // - Helper: ImGuiTextIndex +// - Helper: ImGuiStorage //----------------------------------------------------------------------------- // Helpers: Hashing @@ -722,7 +723,7 @@ struct ImChunkStream void swap(ImChunkStream& rhs) { rhs.Buf.swap(Buf); } }; -// Helper: ImGuiTextIndex<> +// Helper: ImGuiTextIndex // Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API. struct ImGuiTextIndex { @@ -736,6 +737,8 @@ struct ImGuiTextIndex void append(const char* base, int old_size, int new_size); }; +// Helper: ImGuiStorage +IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key); //----------------------------------------------------------------------------- // [SECTION] ImDrawList support //----------------------------------------------------------------------------- @@ -3143,16 +3146,16 @@ namespace ImGui IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL); IMGUI_API void LogSetNextTextDecoration(const char* prefix, const char* suffix); - // Popups, Modals, Tooltips + // Childs IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags); + + // Popups, Modals + IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags); IMGUI_API void 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); IMGUI_API void ClosePopupsExceptModals(); IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags); - IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); - IMGUI_API bool BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags); - IMGUI_API bool BeginTooltipHidden(); IMGUI_API ImRect GetPopupAllowedExtentRect(ImGuiWindow* window); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); IMGUI_API ImGuiWindow* GetTopMostAndVisiblePopupModal(); @@ -3160,6 +3163,10 @@ namespace ImGui IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy); + // Tooltips + IMGUI_API bool BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags); + 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); From b902fa4c4490ddffb713f8153d1a65e1940e58d1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Jun 2024 14:15:13 +0200 Subject: [PATCH 0009/2359] IO: do not disable io.ConfigWindowsResizeFromEdges when ImGuiBackendFlags_HasMouseCursors is not set by backend. Amend 42bf149ac --- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 4 ---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b5caca628..4c680cf74 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,12 @@ Breaking changes: Other changes: +- IO: do not disable io.ConfigWindowsResizeFromEdges (which allow resizing from borders + and lower-left corner) when ImGuiBackendFlags_HasMouseCursors is not set by backend. + The initial reasoning is that resizing from borders feels better when correct mouse cursor + shape change as honored by backends. Keeping this enabling will hopefully increase pressure + on third-party backends to set ImGuiBackendFlags_HasMouseCursors and honor changes of + ImGui::GetMouseCursor() value. (#1495) - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index f4545ec55..6f4398298 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9919,10 +9919,6 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1) IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); #endif - - // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. - if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) - g.IO.ConfigWindowsResizeFromEdges = false; } static void ImGui::ErrorCheckEndFrameSanityChecks() From 1b9593e88946b4cc364b74e95c228f2b4b2661b9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Jun 2024 16:51:48 -0700 Subject: [PATCH 0010/2359] Style: (Breaking) renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected. Amend #261, #351 --- docs/CHANGELOG.txt | 5 +++++ imgui.cpp | 9 +++++---- imgui.h | 20 +++++++++++++------- imgui_draw.cpp | 24 ++++++++++++------------ imgui_widgets.cpp | 4 ++-- 5 files changed, 37 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4c680cf74..ed71de843 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,11 @@ Breaking changes: - Removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages). No significant nested type left. +- Style: renamed tab colors for clarity and consistency with other changes: (#261, #351) + - ImGuiCol_TabActive -> ImGuiCol_TabSelected + - ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed + - ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected + Kept inline redirecting enums (will obsolete). Other changes: diff --git a/imgui.cpp b/imgui.cpp index 6f4398298..363c1b8ae 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected. - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages). - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library. - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading. @@ -3318,11 +3319,11 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; - case ImGuiCol_Tab: return "Tab"; case ImGuiCol_TabHovered: return "TabHovered"; - case ImGuiCol_TabActive: return "TabActive"; - case ImGuiCol_TabUnfocused: return "TabUnfocused"; - case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive"; + case ImGuiCol_Tab: return "Tab"; + case ImGuiCol_TabSelected: return "TabSelected"; + case ImGuiCol_TabDimmed: return "TabDimmed"; + case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected"; case ImGuiCol_PlotLines: return "PlotLines"; case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; diff --git a/imgui.h b/imgui.h index c48fd4c75..268cb5d28 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.90.9 WIP" -#define IMGUI_VERSION_NUM 19081 +#define IMGUI_VERSION_NUM 19082 #define IMGUI_HAS_TABLE /* @@ -1582,11 +1582,11 @@ enum ImGuiCol_ ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows. ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, - ImGuiCol_Tab, // TabItem in a TabBar - ImGuiCol_TabHovered, - ImGuiCol_TabActive, - ImGuiCol_TabUnfocused, - ImGuiCol_TabUnfocusedActive, + ImGuiCol_TabHovered, // Tab background, when hovered + ImGuiCol_Tab, // Tab background, tab-bar is focused, tab is unselected + ImGuiCol_TabSelected, // Tab background, tab-bar is focused, tab is selected + ImGuiCol_TabDimmed, // Tab background, tab-bar is unfocused, tab is unselected + ImGuiCol_TabDimmedSelected, // Tab background, tab-bar is unfocused, tab is selected ImGuiCol_PlotLines, ImGuiCol_PlotLinesHovered, ImGuiCol_PlotHistogram, @@ -1602,7 +1602,13 @@ enum ImGuiCol_ ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active - ImGuiCol_COUNT + ImGuiCol_COUNT, + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiCol_TabActive = ImGuiCol_TabSelected, // [renamed in 1.90.9] + ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed, // [renamed in 1.90.9] + ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected, // [renamed in 1.90.9] +#endif }; // Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 171889f2c..1c048ef58 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -211,11 +211,11 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); - colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; - colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); - colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); - colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); + colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); @@ -271,11 +271,11 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f); - colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; - colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); - colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); - colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); + colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); @@ -332,11 +332,11 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(0.35f, 0.35f, 0.35f, 0.17f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); - colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f); colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; - colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); - colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); - colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f); + colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4c3b1c046..46ef59bb1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7975,7 +7975,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG // Draw separator // (it would be misleading to draw this in EndTabBar() suggesting that it may be drawn over tabs, as tab bar are appendable) - const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive); + const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected); if (g.Style.TabBarBorderSize > 0.0f) { const float y = tab_bar->BarRect.Max.y; @@ -8835,7 +8835,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Render tab shape ImDrawList* display_draw_list = window->DrawList; - const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabUnfocused)); + const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed)); TabItemBackground(display_draw_list, bb, flags, tab_col); RenderNavHighlight(bb, id); From 21bda2ed994fdf2a1dc9a3cf474dac883971f408 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Jun 2024 16:52:56 -0700 Subject: [PATCH 0011/2359] TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline and ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmedSelectedOverline. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 ++ imgui.h | 15 +++++++++------ imgui_demo.cpp | 6 +++++- imgui_draw.cpp | 6 ++++++ imgui_widgets.cpp | 12 +++++++++++- 6 files changed, 36 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ed71de843..63104ce8c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,6 +57,9 @@ Other changes: shape change as honored by backends. Keeping this enabling will hopefully increase pressure on third-party backends to set ImGuiBackendFlags_HasMouseCursors and honor changes of ImGui::GetMouseCursor() value. (#1495) +- TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline option to draw an horizontal + line over selected tabs to increase visibility. This is used by docking. + Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index 363c1b8ae..472093bc7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3322,8 +3322,10 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_TabHovered: return "TabHovered"; case ImGuiCol_Tab: return "Tab"; case ImGuiCol_TabSelected: return "TabSelected"; + case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline"; case ImGuiCol_TabDimmed: return "TabDimmed"; case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected"; + case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline"; case ImGuiCol_PlotLines: return "PlotLines"; case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; diff --git a/imgui.h b/imgui.h index 268cb5d28..8c4bd25eb 100644 --- a/imgui.h +++ b/imgui.h @@ -1212,8 +1212,9 @@ enum ImGuiTabBarFlags_ ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab - ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit - ImGuiTabBarFlags_FittingPolicyScroll = 1 << 7, // Add scroll buttons when tabs don't fit + ImGuiTabBarFlags_DrawSelectedOverline = 1 << 6, // Draw selected overline markers over selected tab + ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 7, // Resize tabs when they don't fit + ImGuiTabBarFlags_FittingPolicyScroll = 1 << 8, // Add scroll buttons when tabs don't fit ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown, }; @@ -1583,10 +1584,12 @@ enum ImGuiCol_ ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, ImGuiCol_TabHovered, // Tab background, when hovered - ImGuiCol_Tab, // Tab background, tab-bar is focused, tab is unselected - ImGuiCol_TabSelected, // Tab background, tab-bar is focused, tab is selected - ImGuiCol_TabDimmed, // Tab background, tab-bar is unfocused, tab is unselected - ImGuiCol_TabDimmedSelected, // Tab background, tab-bar is unfocused, tab is selected + ImGuiCol_Tab, // Tab background, when tab-bar is focused & tab is unselected + ImGuiCol_TabSelected, // Tab background, when tab-bar is focused & tab is selected + ImGuiCol_TabSelectedOverline, // Tab horizontal overline, when tab-bar is focused & tab is selected + ImGuiCol_TabDimmed, // Tab background, when tab-bar is unfocused & tab is unselected + ImGuiCol_TabDimmedSelected, // Tab background, when tab-bar is unfocused & tab is selected + ImGuiCol_TabDimmedSelectedOverline,//..horizontal overline, when tab-bar is unfocused & tab is selected ImGuiCol_PlotLines, ImGuiCol_PlotLinesHovered, ImGuiCol_PlotHistogram, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b2f0f4a14..3548cc6cb 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1730,6 +1730,7 @@ static void ShowDemoWindowWidgets() ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs); ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); + ImGui::CheckboxFlags("ImGuiTabBarFlags_DrawSelectedOverline", &tab_bar_flags, ImGuiTabBarFlags_DrawSelectedOverline); if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) @@ -1738,11 +1739,13 @@ static void ShowDemoWindowWidgets() tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); // Tab Bar + ImGui::AlignTextToFramePadding(); + ImGui::Text("Opened:"); const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" }; static bool opened[4] = { true, true, true, true }; // Persistent user state for (int n = 0; n < IM_ARRAYSIZE(opened); n++) { - if (n > 0) { ImGui::SameLine(); } + ImGui::SameLine(); ImGui::Checkbox(names[n], &opened[n]); } @@ -8617,6 +8620,7 @@ void ShowExampleAppDocuments(bool* p_open) // Submit Tab Bar and Tabs { ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0); + tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline; if (ImGui::BeginTabBar("##tabs", tab_bar_flags)) { if (opt_reorderable) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1c048ef58..c8499441e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -214,8 +214,10 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); @@ -274,8 +276,10 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); @@ -335,8 +339,10 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabSelectedOverline] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.26f, 0.59f, 1.00f, 1.00f); colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 46ef59bb1..927cb2b98 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7921,7 +7921,9 @@ bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) tab_bar->ID = id; tab_bar->SeparatorMinX = tab_bar->BarRect.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f); tab_bar->SeparatorMaxX = tab_bar->BarRect.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f); - return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused); + //if (g.NavWindow && IsWindowChildOf(g.NavWindow, window, false, false)) + flags |= ImGuiTabBarFlags_IsFocused; + return BeginTabBarEx(tab_bar, tab_bar_bb, flags); } bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags) @@ -8837,6 +8839,14 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImDrawList* display_draw_list = window->DrawList; const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed)); TabItemBackground(display_draw_list, bb, flags, tab_col); + if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline)) + { + float x_offset = IM_TRUNC(0.4f * style.TabRounding); + if (x_offset < 2.0f * g.CurrentDpiScale) + x_offset = 0.0f; + float y_offset = 1.0f * g.CurrentDpiScale; + display_draw_list->AddLine(bb.GetTL() + ImVec2(x_offset, y_offset), bb.GetTR() + ImVec2(-x_offset, y_offset), GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline), 2.0f * g.CurrentDpiScale); + } RenderNavHighlight(bb, id); // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. From 32a037c030f84c8c755c16ff45c12f66562b810d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Jun 2024 13:36:58 -0700 Subject: [PATCH 0012/2359] Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern. (#143) Amend 0c6e260f7 --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 63104ce8c..20c943827 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,8 @@ Other changes: - TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline option to draw an horizontal line over selected tabs to increase visibility. This is used by docking. Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. +- Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern sets + active id so a multi-frame extern source doesn't interfere with hovered widgets. (#143) - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index 472093bc7..6d2c557e2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13234,6 +13234,8 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) window = NULL; source_id = ImHashStr("#SourceExtern"); source_drag_active = true; + KeepAliveID(source_id); + SetActiveID(source_id, NULL); } IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget() From 8c517fee357460a39acd7ca3fe9abb917cc1ec94 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Jun 2024 14:19:55 -0700 Subject: [PATCH 0013/2359] Drag and Drop: Fixes an issue when elapsing payload would be based on last payload frame instead of last drag source frame. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 20c943827..e42e5d6ce 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,9 @@ Other changes: Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern sets active id so a multi-frame extern source doesn't interfere with hovered widgets. (#143) +- Drag and Drop: Fixes an issue when elapsing payload would be based on last payload + frame instead of last drag source frame, which makes a difference if not resubmitting + payload every frame. - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index 6d2c557e2..41d1cfacd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5136,7 +5136,7 @@ void ImGui::EndFrame() if (g.DragDropActive) { bool is_delivered = g.DragDropPayload.Delivery; - bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton)); + bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton)); if (is_delivered || is_elapsed) ClearDragDrop(); } @@ -13306,7 +13306,7 @@ bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_s IM_ASSERT(strlen(type) < IM_ARRAYSIZE(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() + IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource() if (cond == ImGuiCond_Always || payload.DataFrameCount == -1) { From 37c243bb35a09c0732325a624c344c6c1d3eab5f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Jun 2024 17:53:34 -0700 Subject: [PATCH 0014/2359] Internals: added ImGuiContext::ContextName optionally used by debug log and to facilitate debugging. --- imgui.cpp | 5 ++++- imgui_internal.h | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 41d1cfacd..443ce9eb3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15606,7 +15606,10 @@ void ImGui::DebugLogV(const char* fmt, va_list args) { ImGuiContext& g = *GImGui; const int old_size = g.DebugLogBuf.size(); - g.DebugLogBuf.appendf("[%05d] ", g.FrameCount); + if (g.ContextName[0] != 0) + g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount); + else + g.DebugLogBuf.appendf("[%05d] ", g.FrameCount); g.DebugLogBuf.appendfv(fmt, args); g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size()); if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY) diff --git a/imgui_internal.h b/imgui_internal.h index 244cda1a2..f2940d211 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1939,6 +1939,7 @@ struct ImGuiContext bool GcCompactAll; // Request full GC bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() void* TestEngine; // Test engine user data + char ContextName[16]; // Storage for a context name (to facilitate debugging multi-context setups) // Inputs ImVector InputEventsQueue; // Input events which will be trickled/written into IO structure. @@ -2266,6 +2267,7 @@ struct ImGuiContext GcCompactAll = false; TestEngineHookItems = false; TestEngine = NULL; + memset(ContextName, 0, sizeof(ContextName)); InputEventsNextMouseSource = ImGuiMouseSource_Mouse; InputEventsNextEventId = 1; From 413c056359b2ec7d70725d94bb9c4e522bbbd9f0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Jun 2024 17:55:54 -0700 Subject: [PATCH 0015/2359] Drag and Drop: comments, debug log entries. --- imgui.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 443ce9eb3..505afa030 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5141,7 +5141,11 @@ void ImGui::EndFrame() ClearDragDrop(); } - // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing. + // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing. + // If you want to handle source item disappearing: instead of submitting your description tooltip + // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot + // (e.g. end of your item loop, or before EndFrame) by reading payload data. + // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data. if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { g.DragDropWithinSource = true; @@ -13231,6 +13235,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) } else { + // When ImGuiDragDropFlags_SourceExtern is set: window = NULL; source_id = ImHashStr("#SourceExtern"); source_drag_active = true; @@ -13247,7 +13252,8 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) { IM_ASSERT(source_id != 0); ClearDragDrop(); - IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = %08X\n", source_id); + IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n", + source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : ""); ImGuiPayload& payload = g.DragDropPayload; payload.SourceId = source_id; payload.SourceParentId = source_parent_id; @@ -13437,7 +13443,8 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery)) return NULL; - //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId); + if (payload.Delivery) + IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId); return &payload; } From 50709454b3f62c0c12bf56a89ca8bab90fcd16be Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Jun 2024 19:02:51 -0700 Subject: [PATCH 0016/2359] Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern assume a mouse button being pressed. (#143) --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e42e5d6ce..252f954a1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,9 +62,11 @@ Other changes: Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern sets active id so a multi-frame extern source doesn't interfere with hovered widgets. (#143) +- Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern does not assume + a mouse button being pressed. Facilitate implementing cross-context drag and drop. (#143) - Drag and Drop: Fixes an issue when elapsing payload would be based on last payload frame instead of last drag source frame, which makes a difference if not resubmitting - payload every frame. + payload every frame. (#143) - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index 505afa030..01beb6bf4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5136,7 +5136,7 @@ void ImGui::EndFrame() if (g.DragDropActive) { bool is_delivered = g.DragDropPayload.Delivery; - bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton)); + bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton)); if (is_delivered || is_elapsed) ClearDragDrop(); } @@ -13239,6 +13239,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) window = NULL; source_id = ImHashStr("#SourceExtern"); source_drag_active = true; + mouse_button = g.IO.MouseDown[0] ? 0 : -1; KeepAliveID(source_id); SetActiveID(source_id, NULL); } @@ -13439,7 +13440,10 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop RenderDragDropTargetRect(r, g.DragDropTargetClipRect); g.DragDropAcceptFrameCount = g.FrameCount; - payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased() + if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1) + payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount); + else + payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased() if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery)) return NULL; From 8c318dc77021a74075c496e211ce36cd7aa5e863 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Jun 2024 11:24:54 -0700 Subject: [PATCH 0017/2359] Drag and Drop: (Breaking) renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire. (#1725, #143) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 3 ++- imgui.h | 6 +++++- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 252f954a1..030f648a8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,8 @@ Breaking changes: - ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed - ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected Kept inline redirecting enums (will obsolete). +- Drag and Drop: renamed ImGuiDragDropFlags_SourceAutoExpirePayload to + ImGuiDragDropFlags_PayloadAutoExpire. Kept inline redirecting enum (will obsolete). (#1725, #143). Other changes: diff --git a/imgui.cpp b/imgui.cpp index 01beb6bf4..f45fd6411 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire. - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected. - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages). - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library. @@ -5136,7 +5137,7 @@ void ImGui::EndFrame() if (g.DragDropActive) { bool is_delivered = g.DragDropPayload.Delivery; - bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton)); + bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton)); if (is_delivered || is_elapsed) ClearDragDrop(); } diff --git a/imgui.h b/imgui.h index 8c4bd25eb..64b163625 100644 --- a/imgui.h +++ b/imgui.h @@ -1296,12 +1296,16 @@ enum ImGuiDragDropFlags_ ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. - ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + ImGuiDragDropFlags_PayloadAutoExpire = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) // AcceptDragDropPayload() flags ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiDragDropFlags_SourceAutoExpirePayload = ImGuiDragDropFlags_PayloadAutoExpire, // Renamed in 1.90.9 +#endif }; // Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui. From 77d9f80754e3ae7efb476f11dd16bb17cb0eeda7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Jun 2024 11:26:45 -0700 Subject: [PATCH 0018/2359] Drag and Drop: Added ImGuiDragDropFlags_PayloadNoCrossContext and ImGuiDragDropFlags_PayloadNoCrossProcess flags. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 5 +++++ imgui.h | 2 ++ 3 files changed, 10 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 030f648a8..06d34933e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,9 @@ Other changes: active id so a multi-frame extern source doesn't interfere with hovered widgets. (#143) - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern does not assume a mouse button being pressed. Facilitate implementing cross-context drag and drop. (#143) +- Drag and Drop: Added ImGuiDragDropFlags_PayloadNoCrossContext/_PayloadNoCrossProcess flags + as metadata to specify that a payload may not be copied outside the context/process by + some logic aiming to copy payloads around. - Drag and Drop: Fixes an issue when elapsing payload would be based on last payload frame instead of last drag source frame, which makes a difference if not resubmitting payload every frame. (#143) diff --git a/imgui.cpp b/imgui.cpp index f45fd6411..7480a8df1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14569,6 +14569,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Basic info Text("Dear ImGui %s", GetVersion()); + if (g.ContextName[0] != NULL) + { + SameLine(); + Text("(Context Name: \"%s\")", g.ContextName); + } Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount); diff --git a/imgui.h b/imgui.h index 64b163625..a7c5a3a88 100644 --- a/imgui.h +++ b/imgui.h @@ -1297,6 +1297,8 @@ enum ImGuiDragDropFlags_ ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. ImGuiDragDropFlags_PayloadAutoExpire = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + ImGuiDragDropFlags_PayloadNoCrossContext = 1 << 6, // Hint to specify that the payload may not be copied outside current dear imgui context. + ImGuiDragDropFlags_PayloadNoCrossProcess = 1 << 7, // Hint to specify that the payload may not be copied outside current process. // AcceptDragDropPayload() flags ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. From 7e7c97ac5f9c0137f9f2547deb46dca2dd12abda Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Jun 2024 14:34:42 -0700 Subject: [PATCH 0019/2359] Ignore .ini file with other suffixes. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 64b5e1221..f632636e0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ ## Dear ImGui artifacts imgui.ini +imgui*.ini ## General build artifacts *.o From 21581cf70cef16db7e9a7095703f3233997596ff Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Jun 2024 17:45:09 -0700 Subject: [PATCH 0020/2359] Fixed build warning. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 7480a8df1..6f90d94ef 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14569,7 +14569,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Basic info Text("Dear ImGui %s", GetVersion()); - if (g.ContextName[0] != NULL) + if (g.ContextName[0] != 0) { SameLine(); Text("(Context Name: \"%s\")", g.ContextName); From 8067d05f744a91821a93e4ead34435143bb79db3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Jun 2024 10:01:53 -0700 Subject: [PATCH 0021/2359] IO: added ClearInputMouse(). made ClearInputKeys() not clear mouse data. (#4921) Amend 6aa408c6a --- docs/CHANGELOG.txt | 9 ++++++--- imgui.cpp | 21 +++++++++++++++++++-- imgui.h | 9 +++++---- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 06d34933e..0961b555f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,8 @@ Breaking changes: - ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed - ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected Kept inline redirecting enums (will obsolete). +- IO: io.ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data. + Newly added io.ClearInputMouse() does. (#4921) - Drag and Drop: renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire. Kept inline redirecting enum (will obsolete). (#1725, #143). @@ -59,6 +61,7 @@ Other changes: shape change as honored by backends. Keeping this enabling will hopefully increase pressure on third-party backends to set ImGuiBackendFlags_HasMouseCursors and honor changes of ImGui::GetMouseCursor() value. (#1495) +- IO: Added io.ClearInputMouse() to clear mouse state. (#4921) - TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline option to draw an horizontal line over selected tabs to increase visibility. This is used by docking. Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. @@ -842,7 +845,7 @@ Breaking changes: - IO: Obsoleted io.ClearInputCharacters() (added in 1.47) as it now ambiguous and often incorrect/misleading considering the existence of a higher-level - input queue. This is automatically cleared by io.ClearInputsKeys(). (#4921) + input queue. This is automatically cleared by io.ClearInputKeys(). (#4921) - ImDrawData: CmdLists[] array is now owned, changed from 'ImDrawList**' to 'ImVector'. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. @@ -880,10 +883,10 @@ Other changes: will slightly reduce scrollbar size. Generally we tried to make it that window border size has no incidence on layout but this can't work with thick borders. (#2522) - IO: Added io.ClearEventsQueue() to clear incoming inputs events. (#4921) - May be useful in conjunction with io.ClearInputsKeys() if you need to clear + May be useful in conjunction with io.ClearInputKeys() if you need to clear both current inputs state and queued events (e.g. when using blocking native dialogs such as Windows's ::MessageBox() or ::GetOpenFileName()). -- IO: Changed io.ClearInputsKeys() specs to also clear current frame character buffer +- IO: Changed io.ClearInputKeys() specs to also clear current frame character buffer (what now obsoleted io.ClearInputCharacters() did), as this is effectively the desirable behavior. - Misc: Added IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION config macro to disable diff --git a/imgui.cpp b/imgui.cpp index 6f90d94ef..48c73dc31 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does. - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire. - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected. - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages). @@ -1453,7 +1454,7 @@ void ImGuiIO::ClearEventsQueue() g.InputEventsQueue.clear(); } -// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. +// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. void ImGuiIO::ClearInputKeys() { #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO @@ -1461,12 +1462,26 @@ void ImGuiIO::ClearInputKeys() #endif for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++) { + if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET))) + continue; KeysData[n].Down = false; KeysData[n].DownDuration = -1.0f; KeysData[n].DownDurationPrev = -1.0f; } KeyCtrl = KeyShift = KeyAlt = KeySuper = false; KeyMods = ImGuiMod_None; + InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters(). +} + +void ImGuiIO::ClearInputMouse() +{ + for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1)) + { + ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET]; + key_data->Down = false; + key_data->DownDuration = -1.0f; + key_data->DownDurationPrev = -1.0f; + } MousePos = ImVec2(-FLT_MAX, -FLT_MAX); for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++) { @@ -1474,7 +1489,6 @@ void ImGuiIO::ClearInputKeys() MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f; } MouseWheel = MouseWheelH = 0.0f; - InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters(). } // Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue. @@ -9632,7 +9646,10 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) // - we clear in EndFrame() and not now in order allow application/user code polling this flag // (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event). if (g.IO.AppFocusLost) + { g.IO.ClearInputKeys(); + g.IO.ClearInputMouse(); + } } ImGuiID ImGui::GetKeyOwner(ImGuiKey key) diff --git a/imgui.h b/imgui.h index a7c5a3a88..e8c1a1a5e 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.90.9 WIP" -#define IMGUI_VERSION_NUM 19082 +#define IMGUI_VERSION_NUM 19083 #define IMGUI_HAS_TABLE /* @@ -1535,7 +1535,7 @@ enum ImGuiConfigFlags_ ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad. ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth. ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. - ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the backend. + ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct dear imgui to disable mouse interactions. ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) @@ -2198,7 +2198,7 @@ struct ImGuiIO // Option to deactivate io.AddFocusEvent(false) handling. // - May facilitate interactions with a debugger when focus loss leads to clearing inputs data. // - Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them. - bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys() in input processing. + bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys()/io.ClearInputMouse() in input processing. // Options to audit .ini data bool ConfigDebugIniSettings; // = false // Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) @@ -2247,7 +2247,8 @@ struct ImGuiIO IMGUI_API void SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index = -1); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode. IMGUI_API void SetAppAcceptingEvents(bool accepting_events); // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen. IMGUI_API void ClearEventsQueue(); // Clear all incoming events. - IMGUI_API void ClearInputKeys(); // Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. + IMGUI_API void ClearInputKeys(); // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. + IMGUI_API void ClearInputMouse(); // Clear current mouse state. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS IMGUI_API void ClearInputCharacters(); // [Obsoleted in 1.89.8] Clear the current frame text input buffer. Now included within ClearInputKeys(). #endif From e3971079cf5a16088caa381bd5d05dfbdc51b353 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Jun 2024 10:08:07 -0700 Subject: [PATCH 0022/2359] IO: added ImGuiConfigFlags_NoKeyboard for consistency and convenience. (#4921) # Conflicts: # imgui.h # imgui_demo.cpp --- imgui.cpp | 9 ++++++++- imgui.h | 3 ++- imgui_demo.cpp | 13 ++++++++++--- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 48c73dc31..5efd63505 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4577,7 +4577,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) clear_hovered_windows = true; - // Disabled mouse? + // Disabled mouse hovering (we don't currently clear MousePos, we could) if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) clear_hovered_windows = true; @@ -9136,6 +9136,9 @@ static void ImGui::UpdateKeyboardInputs() ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; + if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) + io.ClearInputKeys(); + // Import legacy keys or verify they are not used #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO if (io.BackendUsingLegacyKeyArrays == 0) @@ -9582,6 +9585,8 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) else if (e->Type == ImGuiInputEventType_Key) { // Trickling Rule: Stop processing queued events if we got multiple action on the same button + if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) + continue; ImGuiKey key = e->Key.Key; IM_ASSERT(key != ImGuiKey_None); ImGuiKeyData* key_data = GetKeyData(key); @@ -9602,6 +9607,8 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) } else if (e->Type == ImGuiInputEventType_Text) { + if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) + continue; // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled)) break; diff --git a/imgui.h b/imgui.h index e8c1a1a5e..71ef3cc00 100644 --- a/imgui.h +++ b/imgui.h @@ -1535,8 +1535,9 @@ enum ImGuiConfigFlags_ ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad. ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth. ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. - ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct dear imgui to disable mouse interactions. + ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct dear imgui to disable mouse inputs and interactions. ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. + ImGuiConfigFlags_NoKeyboard = 1 << 6, // Instruct dear imgui to disable keyboard inputs and interactions. This is done by ignoring keyboard events and clearing existing states. // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3548cc6cb..de442f518 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -462,19 +462,26 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", &io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", &io.ConfigFlags, ImGuiConfigFlags_NoMouse); + ImGui::SameLine(); HelpMarker("Instruct dear imgui to disable mouse inputs and interactions."); + + // The "NoMouse" option can get us stuck with a disabled mouse! Let's provide an alternative way to fix it: if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) { - // The "NoMouse" option can get us stuck with a disabled mouse! Let's provide an alternative way to fix it: if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f) { ImGui::SameLine(); ImGui::Text("<>"); } - if (ImGui::IsKeyPressed(ImGuiKey_Space)) + // Prevent both being checked + if (ImGui::IsKeyPressed(ImGuiKey_Space) || (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)) io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse; } - ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", &io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); + + ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", &io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); ImGui::SameLine(); HelpMarker("Instruct backend to not alter mouse cursor shape and visibility."); + ImGui::CheckboxFlags("io.ConfigFlags: NoKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NoKeyboard); + ImGui::SameLine(); HelpMarker("Instruct dear imgui to disable keyboard inputs and interactions."); + ImGui::Checkbox("io.ConfigInputTrickleEventQueue", &io.ConfigInputTrickleEventQueue); ImGui::SameLine(); HelpMarker("Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates."); ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); From 7f20a4b041546fb975dccb2b5d93a8930ad16cf4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Jun 2024 10:16:15 -0700 Subject: [PATCH 0023/2359] Nav: CTRL+Tab overlay display context name if any. --- imgui.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 5efd63505..517df51eb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13135,6 +13135,8 @@ void ImGui::NavUpdateWindowingOverlay() SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); + if (g.ContextName[0] != 0) + SeparatorText(g.ContextName); for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--) { ImGuiWindow* window = g.WindowsFocusOrder[n]; From 2c8cc58fd16819c56a4eb36edebc591dc9878d83 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Jun 2024 14:45:30 -0700 Subject: [PATCH 0024/2359] Internals: storing HoveredWindowBeforeClear for use by multi-context compositor drag and drop propagation. # Conflicts: # imgui.cpp # imgui_internal.h --- imgui.cpp | 1 + imgui_internal.h | 2 ++ 2 files changed, 3 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 517df51eb..8822dd934 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4571,6 +4571,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. bool clear_hovered_windows = false; FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow); + g.HoveredWindowBeforeClear = g.HoveredWindow; // Modal windows prevents mouse from hovering behind them. ImGuiWindow* modal_window = GetTopMostPopupModal(); diff --git a/imgui_internal.h b/imgui_internal.h index f2940d211..a02f01b85 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1959,6 +1959,7 @@ struct ImGuiContext ImGuiWindow* CurrentWindow; // Window being drawn into ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + ImGuiWindow* HoveredWindowBeforeClear; // Window the mouse is hovering. Filled even with _NoMouse. This is currently useful for multi-context compositors. ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; @@ -2276,6 +2277,7 @@ struct ImGuiContext CurrentWindow = NULL; HoveredWindow = NULL; HoveredWindowUnderMovingWindow = NULL; + HoveredWindowBeforeClear = NULL; MovingWindow = NULL; WheelingWindow = NULL; WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1; From 755bf2b8c2effb4bb8ce28c7ce8a7dbc3d40dd95 Mon Sep 17 00:00:00 2001 From: cfillion Date: Wed, 12 Jun 2024 18:28:24 -0400 Subject: [PATCH 0025/2359] (Breaking) Move ImGuiWindowFlags_NavFlattened to ImGuiChildFlags_NavFlattened. (#7687) --- docs/CHANGELOG.txt | 5 +++++ imgui.cpp | 27 +++++++++++++++------------ imgui.h | 3 ++- imgui_demo.cpp | 4 ++-- 4 files changed, 24 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0961b555f..5170ea6b3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,11 @@ Breaking changes: - Removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages). No significant nested type left. +- BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window + flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for + BeginChild() calls anyhow. (#7687) [@cfillion] + - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened); + - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0) - Style: renamed tab colors for clarity and consistency with other changes: (#261, #351) - ImGuiCol_TabActive -> ImGuiCol_TabSelected - ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed diff --git a/imgui.cpp b/imgui.cpp index 8822dd934..fd6521288 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,9 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow. + - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened); + - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0); - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does. - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire. - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected. @@ -5533,7 +5536,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I IM_ASSERT(id != 0); // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. - const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle; + const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened; IM_UNUSED(ImGuiChildFlags_SupportedMask_); IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?"); IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!"); @@ -5545,6 +5548,8 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding) child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding; + if (window_flags & ImGuiWindowFlags_NavFlattened) + child_flags |= ImGuiChildFlags_NavFlattened; #endif if (child_flags & ImGuiChildFlags_AutoResizeX) child_flags &= ~ImGuiChildFlags_ResizeX; @@ -5623,7 +5628,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id); if (g.ActiveId == temp_id_for_activation) ClearActiveID(); - if (g.NavActivateId == id && !(window_flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY)) + if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY)) { FocusWindow(child_window); NavInitWindow(child_window, false); @@ -5649,7 +5654,8 @@ void ImGui::EndChild() ImGuiWindow* parent_window = g.CurrentWindow; ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size); ItemSize(child_size); - if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !(child_window->Flags & ImGuiWindowFlags_NavFlattened)) + const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0; + if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened) { ItemAdd(bb, child_window->ChildId); RenderNavHighlight(bb, child_window->ChildId); @@ -5666,7 +5672,7 @@ void ImGui::EndChild() ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav); // But when flattened we directly reach items, adjust active layer mask accordingly - if (child_window->Flags & ImGuiWindowFlags_NavFlattened) + if (nav_flattened) parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext; } if (g.HoveredWindow == child_window) @@ -6440,7 +6446,7 @@ void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags window->RootWindowPopupTree = parent_window->RootWindowPopupTree; if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight; - while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened) + while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened) { IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL); window->RootWindowForNav = window->RootWindowForNav->ParentWindow; @@ -6536,9 +6542,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs) flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; - if (flags & ImGuiWindowFlags_NavFlattened) - IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow); - const int current_frame = g.FrameCount; const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow); @@ -6603,7 +6606,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } // Add to focus scope stack - PushFocusScope((flags & ImGuiWindowFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID); + PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID); window->NavRootFocusScopeId = g.CurrentFocusScopeId; // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[] @@ -7199,7 +7202,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); - const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); + const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); if (!g.LogEnabled && !nav_request) if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) { @@ -10189,7 +10192,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent); if (g.NavId == id || g.NavAnyRequest) if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) - if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened)) + if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened)) NavProcessItem(); } @@ -11678,7 +11681,7 @@ static bool ImGui::NavScoreItem(ImGuiNavItemData* result) // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring if (window->ParentWindow == g.NavWindow) { - IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened); + IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened); if (!window->ClipRect.Overlaps(cand)) return false; cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window diff --git a/imgui.h b/imgui.h index 71ef3cc00..e3c4db777 100644 --- a/imgui.h +++ b/imgui.h @@ -1044,7 +1044,6 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, // [Internal] - ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] On child window: share focus scope, allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() @@ -1054,6 +1053,7 @@ enum ImGuiWindowFlags_ // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90: Use ImGuiChildFlags_AlwaysUseWindowPadding in BeginChild() call. + ImGuiWindowFlags_NavFlattened = 1 << 31, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call. #endif }; @@ -1077,6 +1077,7 @@ enum ImGuiChildFlags_ ImGuiChildFlags_AutoResizeY = 1 << 5, // Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. ImGuiChildFlags_AlwaysAutoResize = 1 << 6, // Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. ImGuiChildFlags_FrameStyle = 1 << 7, // Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. + ImGuiChildFlags_NavFlattened = 1 << 8, // Share focus scope, allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. }; // Flags for ImGui::InputText() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index de442f518..fba72951a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6851,7 +6851,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "Right-click to open edit options menu."); ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); - ImGui::BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened); + ImGui::BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Border | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); ImGui::PushItemWidth(ImGui::GetFontSize() * -12); for (int i = 0; i < ImGuiCol_COUNT; i++) { @@ -7251,7 +7251,7 @@ struct ExampleAppConsole // Reserve enough left-over height for 1 separator + 1 input text const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); - if (ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), ImGuiChildFlags_None, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NavFlattened)) + if (ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_HorizontalScrollbar)) { if (ImGui::BeginPopupContextWindow()) { From 48e7e7bfe8521af8802eda2ec26546a6069e5573 Mon Sep 17 00:00:00 2001 From: Gary Geng Date: Sun, 23 Jun 2024 17:26:52 -0500 Subject: [PATCH 0026/2359] Backends: SDL3: Follow SDL3 removal of keysym field in SDL_KeyboardEvent (#7729) --- backends/imgui_impl_sdl3.cpp | 6 +++--- docs/CHANGELOG.txt | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 3da22f9b5..8b210b223 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -326,10 +326,10 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: { - ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod); - ImGuiKey key = ImGui_ImplSDL3_KeycodeToImGuiKey(event->key.keysym.sym); + ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); + ImGuiKey key = ImGui_ImplSDL3_KeycodeToImGuiKey(event->key.key); io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN)); - io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. + io.SetKeyEventNativeData(key, event->key.key, event->key.scancode, event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. return true; } case SDL_EVENT_WINDOW_MOUSE_ENTER: diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5170ea6b3..35694f47e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,6 +83,7 @@ Other changes: - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] +- Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) ----------------------------------------------------------------------- From aab27130a6159a08026e1c3dc809c212999b7f88 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Jun 2024 12:57:39 -0700 Subject: [PATCH 0027/2359] Demo: Style Editor: clarify how _CalcCircleAutoSegmentCount() doesn't always get exact final segment count. (#7731) --- imgui_demo.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index fba72951a..7bc4281cf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6932,10 +6932,10 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); if (show_samples && ImGui::BeginTooltip()) { - ImGui::TextUnformatted("(R = radius, N = number of segments)"); + ImGui::TextUnformatted("(R = radius, N = approx number of segments)"); ImGui::Spacing(); ImDrawList* draw_list = ImGui::GetWindowDrawList(); - const float min_widget_width = ImGui::CalcTextSize("N: MMM\nR: MMM").x; + const float min_widget_width = ImGui::CalcTextSize("R: MMM\nN: MMM").x; for (int n = 0; n < 8; n++) { const float RAD_MIN = 5.0f; @@ -6944,6 +6944,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::BeginGroup(); + // N is not always exact here due to how PathArcTo() function work internally ImGui::Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad)); const float canvas_width = IM_MAX(min_widget_width, rad * 2.0f); From a18fb406ace8163309a27f948acb85309dfbd312 Mon Sep 17 00:00:00 2001 From: Martin Ejdestig Date: Sat, 22 Jun 2024 13:54:21 +0200 Subject: [PATCH 0028/2359] Backends: Vulkan: Remove Volk/ from volk.h #include directives (#7722, #6582, #4854) --- backends/imgui_impl_vulkan.h | 2 +- docs/CHANGELOG.txt | 4 +++- examples/example_glfw_vulkan/main.cpp | 2 +- examples/example_sdl2_vulkan/main.cpp | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index c174a6ca1..fb98bfbc4 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -55,7 +55,7 @@ // Vulkan includes #ifdef IMGUI_IMPL_VULKAN_USE_VOLK -#include +#include #else #include #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 35694f47e..eea03be61 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,10 +80,12 @@ Other changes: - Drag and Drop: Fixes an issue when elapsing payload would be based on last payload frame instead of last drag source frame, which makes a difference if not resubmitting payload every frame. (#143) +- Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) +- Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) + [@martin-ejdestig] - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] -- Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) ----------------------------------------------------------------------- diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 26012065a..e1f099e3d 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -25,7 +25,7 @@ // Volk headers #ifdef IMGUI_IMPL_VULKAN_USE_VOLK #define VOLK_IMPLEMENTATION -#include +#include #endif // [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers. diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 7f8fd0abb..afcebf1b9 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -24,7 +24,7 @@ // Volk headers #ifdef IMGUI_IMPL_VULKAN_USE_VOLK #define VOLK_IMPLEMENTATION -#include +#include #endif //#define APP_USE_UNLIMITED_FRAME_RATE From eb1cc4b8b4ebe4a10ad0d422fe8d5751a6ebf9a3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 12:17:22 +0200 Subject: [PATCH 0029/2359] Metrics/Debugger: Browsing a Storage perform hover lookup on identifier. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 3 +++ 2 files changed, 4 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index eea03be61..3c3c6ad3c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,6 +80,7 @@ Other changes: - Drag and Drop: Fixes an issue when elapsing payload would be based on last payload frame instead of last drag source frame, which makes a difference if not resubmitting payload every frame. (#143) +- Debug Tools: Metrics/Debugger: Browsing a Storage perform hover lookup on identifier. - Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) [@martin-ejdestig] diff --git a/imgui.cpp b/imgui.cpp index fd6521288..0fe364f6a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15466,7 +15466,10 @@ void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label) if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes())) return; for (const ImGuiStoragePair& p : storage->Data) + { BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer. + DebugLocateItemOnHover(p.key); + } TreePop(); } From 32f9dfc1261e4b8dd4a026588ee966c200b7f3f0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 14:32:48 +0200 Subject: [PATCH 0030/2359] Viewports: Backported 'void* ImGuiViewport::PlatformHandle' from docking branch for use by backends. --- backends/imgui_impl_glfw.cpp | 15 ++++++++------- backends/imgui_impl_osx.mm | 4 +++- backends/imgui_impl_sdl2.cpp | 17 +++++++++-------- backends/imgui_impl_sdl3.cpp | 2 +- backends/imgui_impl_win32.cpp | 3 ++- docs/CHANGELOG.txt | 2 ++ imgui.h | 3 ++- 7 files changed, 27 insertions(+), 19 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 883917875..3c95f1786 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -145,7 +145,7 @@ struct ImGui_ImplGlfw_Data GLFWcharfun PrevUserCallbackChar; GLFWmonitorfun PrevUserCallbackMonitor; #ifdef _WIN32 - WNDPROC GlfwWndProc; + WNDPROC PrevWndProc; #endif ImGui_ImplGlfw_Data() { memset((void*)this, 0, sizeof(*this)); } @@ -497,7 +497,7 @@ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wPara ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); break; } - return ::CallWindowProcW(bd->GlfwWndProc, hWnd, msg, wParam, lParam); + return ::CallWindowProcW(bd->PrevWndProc, hWnd, msg, wParam, lParam); } #endif @@ -612,6 +612,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Set platform dependent data in viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->PlatformHandle = (void*)bd->Window; #ifdef _WIN32 main_viewport->PlatformHandleRaw = glfwGetWin32Window(bd->Window); #elif defined(__APPLE__) @@ -622,8 +623,8 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Windows: register a WndProc hook so we can intercept some messages. #ifdef _WIN32 - bd->GlfwWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC); - IM_ASSERT(bd->GlfwWndProc != nullptr); + bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC); + IM_ASSERT(bd->PrevWndProc != nullptr); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); #endif @@ -661,11 +662,11 @@ void ImGui_ImplGlfw_Shutdown() for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) glfwDestroyCursor(bd->MouseCursors[cursor_n]); - // Windows: register a WndProc hook so we can intercept some messages. + // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->GlfwWndProc); - bd->GlfwWndProc = 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_osx.mm b/backends/imgui_impl_osx.mm index 322798022..14cdd85cd 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -133,7 +133,7 @@ static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view); - (void)updateImePosWithView:(NSView *)view { - NSWindow *window = view.window; + NSWindow* window = view.window; if (!window) return; NSRect contentRect = [window contentRectForFrameRect:window.frame]; @@ -402,6 +402,8 @@ bool ImGui_ImplOSX_Init(NSView* view) //io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Observer = [ImGuiObserver new]; + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (__bridge_retained void*)bd->Window; // Load cursors. Some of them are undocumented. bd->MouseCursorHidden = false; diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 892fe9050..a18c013fd 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -397,7 +397,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) return false; } -static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer) +static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); @@ -448,6 +448,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer) // Set platform dependent data in viewport // Our mouse update function expect PlatformHandle to be filled for the main viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->PlatformHandle = (void*)window; main_viewport->PlatformHandleRaw = nullptr; SDL_SysWMinfo info; SDL_VERSION(&info.version); @@ -481,13 +482,13 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer) SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); #endif + (void)sdl_gl_context; // Unused in 'master' branch. return true; } bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) { - IM_UNUSED(sdl_gl_context); // Viewport branch will need this. - return ImGui_ImplSDL2_Init(window, nullptr); + return ImGui_ImplSDL2_Init(window, nullptr, sdl_gl_context); } bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window) @@ -495,7 +496,7 @@ bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window) #if !SDL_HAS_VULKAN IM_ASSERT(0 && "Unsupported"); #endif - return ImGui_ImplSDL2_Init(window, nullptr); + return ImGui_ImplSDL2_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window) @@ -503,22 +504,22 @@ bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window) #if !defined(_WIN32) IM_ASSERT(0 && "Unsupported"); #endif - return ImGui_ImplSDL2_Init(window, nullptr); + return ImGui_ImplSDL2_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window) { - return ImGui_ImplSDL2_Init(window, nullptr); + return ImGui_ImplSDL2_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer) { - return ImGui_ImplSDL2_Init(window, renderer); + return ImGui_ImplSDL2_Init(window, renderer, nullptr); } bool ImGui_ImplSDL2_InitForOther(SDL_Window* window) { - return ImGui_ImplSDL2_Init(window, nullptr); + return ImGui_ImplSDL2_Init(window, nullptr, nullptr); } static void ImGui_ImplSDL2_CloseGamepads(); diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 8b210b223..189c6f412 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -365,7 +365,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window) { - IM_UNUSED(window); + viewport->PlatformHandle = window; viewport->PlatformHandleRaw = nullptr; #if defined(__WIN32__) && !defined(__WINRT__) viewport->PlatformHandleRaw = (HWND)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.win32.hwnd", nullptr); diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 3e59b62e3..b0f694057 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -169,7 +169,8 @@ static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) ImGui_ImplWin32_UpdateKeyboardCodePage(); // Set platform dependent data in viewport - ImGui::GetMainViewport()->PlatformHandleRaw = (void*)hwnd; + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)bd->hWnd; IM_UNUSED(platform_has_own_dc); // Used in 'docking' branch // Dynamically load XInput library diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3c3c6ad3c..ed4c1d718 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,8 @@ Other changes: frame instead of last drag source frame, which makes a difference if not resubmitting payload every frame. (#143) - Debug Tools: Metrics/Debugger: Browsing a Storage perform hover lookup on identifier. +- Viewports: Backported 'void* ImGuiViewport::PlatformHandle' from docking branch for + use by backends. - Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) [@martin-ejdestig] diff --git a/imgui.h b/imgui.h index e3c4db777..95506954b 100644 --- a/imgui.h +++ b/imgui.h @@ -2202,7 +2202,7 @@ struct ImGuiIO // - Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them. bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys()/io.ClearInputMouse() in input processing. - // Options to audit .ini data + // Option to audit .ini data bool ConfigDebugIniSettings; // = false // Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) //------------------------------------------------------------------ @@ -3240,6 +3240,7 @@ struct ImGuiViewport ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) // Platform/Backend Dependent Data + void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND, GLFWWindow*, SDL_Window*) void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms) ImGuiViewport() { memset(this, 0, sizeof(*this)); } From 7c2476986b5b01ecfab85eca064568634194d13a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 14:41:21 +0200 Subject: [PATCH 0031/2359] Backends: SDL3: Update for SDL_StartTextInput()/SDL_StopTextInput() API changes. (#7735) --- backends/imgui_impl_sdl3.cpp | 25 ++++++++++++++++++------- docs/CHANGELOG.txt | 1 + examples/imgui_examples.sln | 10 ++++++++++ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 189c6f412..f8e2c5510 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -22,6 +22,10 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures. +// 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents. +// 2024-06-03; Update for SDL3 api changes: SDL_SYSTEM_CURSOR_ renames. +// 2024-05-15: Update for SDL3 api changes: SDLK_ renames. // 2024-04-15: Inputs: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput() as SDL3 no longer enables it by default and should play nicer with IME. // 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode(). // 2023-11-13: Updated for recent SDL3 API changes. @@ -76,6 +80,9 @@ struct ImGui_ImplSDL3_Data Uint64 Time; char* ClipboardTextData; + // IME handling + SDL_Window* ImeWindow; + // Mouse handling Uint32 MouseWindowID; int MouseButtonsDown; @@ -116,8 +123,15 @@ static void ImGui_ImplSDL3_SetClipboardText(void*, const char* text) SDL_SetClipboardText(text); } -static void ImGui_ImplSDL3_SetPlatformImeData(ImGuiViewport*, ImGuiPlatformImeData* data) +static void ImGui_ImplSDL3_SetPlatformImeData(ImGuiViewport* viewport, ImGuiPlatformImeData* data) { + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + SDL_Window* window = (SDL_Window*)viewport->PlatformHandle; + if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != NULL) + { + SDL_StopTextInput(bd->ImeWindow); + bd->ImeWindow = nullptr; + } if (data->WantVisible) { SDL_Rect r; @@ -125,12 +139,9 @@ static void ImGui_ImplSDL3_SetPlatformImeData(ImGuiViewport*, ImGuiPlatformImeDa r.y = (int)data->InputPos.y; r.w = 1; r.h = (int)data->InputLineHeight; - SDL_SetTextInputRect(&r); - SDL_StartTextInput(); - } - else - { - SDL_StopTextInput(); + SDL_SetTextInputRect(window, &r); + SDL_StartTextInput(window); + bd->ImeWindow = window; } } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ed4c1d718..eba73bb2b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -84,6 +84,7 @@ Other changes: - Viewports: Backported 'void* ImGuiViewport::PlatformHandle' from docking branch for use by backends. - Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) +- Backends: SDL3: Update for SDL_StartTextInput()/SDL_StopTextInput() API changes. (#7735) - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) [@martin-ejdestig] - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index 071bcbd63..cf1e7d75f 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -29,6 +29,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_opengl3", "ex EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl2_sdlrenderer2", "example_sdl2_sdlrenderer2\example_sdl2_sdlrenderer2.vcxproj", "{0C0B2BEA-311F-473C-9652-87923EF639E3}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlrenderer3", "example_sdl3_sdlrenderer3\example_sdl3_sdlrenderer3.vcxproj", "{C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -141,6 +143,14 @@ Global {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|Win32.Build.0 = Release|Win32 {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|x64.ActiveCfg = Release|x64 {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|x64.Build.0 = Release|x64 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|Win32.ActiveCfg = Debug|Win32 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|Win32.Build.0 = Debug|Win32 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|x64.ActiveCfg = Debug|x64 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|x64.Build.0 = Debug|x64 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|Win32.ActiveCfg = Release|Win32 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|Win32.Build.0 = Release|Win32 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|x64.ActiveCfg = Release|x64 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 22b36bef9e6ec315f16eff98d11d2b853bf31f80 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 14:59:00 +0200 Subject: [PATCH 0032/2359] Examples: undo adding SDL3 example to Visual Studio sln. --- examples/imgui_examples.sln | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index cf1e7d75f..071bcbd63 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -29,8 +29,6 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_opengl3", "ex EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl2_sdlrenderer2", "example_sdl2_sdlrenderer2\example_sdl2_sdlrenderer2.vcxproj", "{0C0B2BEA-311F-473C-9652-87923EF639E3}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlrenderer3", "example_sdl3_sdlrenderer3\example_sdl3_sdlrenderer3.vcxproj", "{C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -143,14 +141,6 @@ Global {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|Win32.Build.0 = Release|Win32 {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|x64.ActiveCfg = Release|x64 {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|x64.Build.0 = Release|x64 - {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|Win32.ActiveCfg = Debug|Win32 - {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|Win32.Build.0 = Debug|Win32 - {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|x64.ActiveCfg = Debug|x64 - {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|x64.Build.0 = Debug|x64 - {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|Win32.ActiveCfg = Release|Win32 - {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|Win32.Build.0 = Release|Win32 - {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|x64.ActiveCfg = Release|x64 - {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 0c2650e8339213398c28625f3d1d91fc9bf6db6b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 16:23:27 +0200 Subject: [PATCH 0033/2359] Backends: OSX: build fix. Amend 32f9dfc --- backends/imgui_impl_osx.mm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 14cdd85cd..fdd407f3e 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -80,6 +80,7 @@ struct ImGui_ImplOSX_Data KeyEventResponder* KeyEventResponder; NSTextInputContext* InputContext; id Monitor; + NSWindow* Window; ImGui_ImplOSX_Data() { memset(this, 0, sizeof(*this)); } }; @@ -402,6 +403,7 @@ bool ImGui_ImplOSX_Init(NSView* view) //io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Observer = [ImGuiObserver new]; + bd->Window = view.window ?: NSApp.orderedWindows.firstObject; ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (__bridge_retained void*)bd->Window; From dbffb702f836f4c9bcbac97ab7e80fcb63b2e123 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 18:57:14 +0200 Subject: [PATCH 0034/2359] ImGuiStorage: tweak impl for BuildSortByKey(). --- imgui.cpp | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0fe364f6a..520590206 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2542,20 +2542,18 @@ ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_ return in_p; } +static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs) +{ + // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. + ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key; + ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key; + return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0); +} + // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. void ImGuiStorage::BuildSortByKey() { - struct StaticFunc - { - static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs) - { - // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. - if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1; - if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1; - return 0; - } - }; - ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID); + ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID); } int ImGuiStorage::GetInt(ImGuiID key, int default_val) const From fbb903e15808d6a36034d65649e10b6976d0cdb9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Jun 2024 16:37:33 +0200 Subject: [PATCH 0035/2359] Inputs: fixed using Shortcut() or SetNextItemShortcut() within a disabled block bypassing the disabled state. (#7726) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 9 ++++++++- imgui.h | 2 +- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index eba73bb2b..85bcfbb13 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,8 @@ Other changes: on third-party backends to set ImGuiBackendFlags_HasMouseCursors and honor changes of ImGui::GetMouseCursor() value. (#1495) - IO: Added io.ClearInputMouse() to clear mouse state. (#4921) +- Inputs: fixed using Shortcut() or SetNextItemShortcut() within a disabled block bypassing + the disabled state. (#7726) - TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline option to draw an horizontal line over selected tabs to increase visibility. This is used by docking. Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. diff --git a/imgui.cpp b/imgui.cpp index 520590206..72f1f1871 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4214,6 +4214,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag } // Display shortcut (only works with mouse) + // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip) if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut)) if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal)) SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut)); @@ -9793,12 +9794,15 @@ void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags) g.NextItemData.ShortcutFlags = flags; } +// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData void ImGui::ItemHandleShortcut(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiInputFlags flags = g.NextItemData.ShortcutFlags; IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()! + if (g.LastItemData.InFlags & ImGuiItemFlags_Disabled) + return; if (flags & ImGuiInputFlags_Tooltip) { g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut; @@ -9822,7 +9826,7 @@ bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags) bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id) { - //ImGuiContext& g = *GImGui; + ImGuiContext& g = *GImGui; //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id); // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any. @@ -9834,6 +9838,9 @@ bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID own if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner) owner_id = GetRoutingIdFromOwnerId(owner_id); + if (g.CurrentItemFlags & ImGuiItemFlags_Disabled) + return false; + // Submit route if (!SetShortcutRouting(key_chord, flags, owner_id)) return false; diff --git a/imgui.h b/imgui.h index 95506954b..7617addc4 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.90.9 WIP" -#define IMGUI_VERSION_NUM 19083 +#define IMGUI_VERSION_NUM 19084 #define IMGUI_HAS_TABLE /* From 953d40c929fc56ad719845ad1788aa046ef9ee33 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Jun 2024 17:17:54 +0200 Subject: [PATCH 0036/2359] Tables: moved TableGetHoveredColumn() to public API. (#7715, #3740) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 3 ++- imgui_internal.h | 1 - 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 85bcfbb13..acb2f3202 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -72,6 +72,8 @@ Other changes: - TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline option to draw an horizontal line over selected tabs to increase visibility. This is used by docking. Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. +- Tables: added TableGetHoveredColumn() to public API, as an alternative to testing for + 'TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered' on each column. (#3740) - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern sets active id so a multi-frame extern source doesn't interfere with hovered widgets. (#143) - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern does not assume diff --git a/imgui.h b/imgui.h index 7617addc4..ff8778c03 100644 --- a/imgui.h +++ b/imgui.h @@ -779,7 +779,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 column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); + 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 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. 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. @@ -812,6 +812,7 @@ namespace ImGui IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. IMGUI_API void TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) + IMGUI_API int TableGetHoveredColumn(); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. Can also use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. // Legacy Columns API (prefer using Tables!) diff --git a/imgui_internal.h b/imgui_internal.h index a02f01b85..9bbbc5eca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3332,7 +3332,6 @@ namespace ImGui IMGUI_API void TableOpenContextMenu(int column_n = -1); IMGUI_API void TableSetColumnWidth(int column_n, float width); IMGUI_API void TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs); - IMGUI_API int TableGetHoveredColumn(); // May use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. Return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. IMGUI_API int TableGetHoveredRow(); // Retrieve *PREVIOUS FRAME* hovered row. This difference with TableGetHoveredColumn() is the reason why this is not public yet. IMGUI_API float TableGetHeaderRowHeight(); IMGUI_API float TableGetHeaderAngledMaxLabelWidth(); From 77d582fa37b4958a284421432aec18ba84f138bc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Jun 2024 18:04:24 +0200 Subject: [PATCH 0037/2359] Windows: BeginChild(): fixed a glitch when during a resize of a child window which is tightly close to the boundaries of its parent. (#7706) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 11 ++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index acb2f3202..4b9b12c79 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,9 @@ Other changes: - IO: Added io.ClearInputMouse() to clear mouse state. (#4921) - Inputs: fixed using Shortcut() or SetNextItemShortcut() within a disabled block bypassing the disabled state. (#7726) +- Windows: BeginChild(): fixed a glitch when during a resize of a child window which is + tightly close to the boundaries of its parent (e.g. with zero WindowPadding), the child + position could have temporarily be moved around by erroneous padding application. (#7706) - TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline option to draw an horizontal line over selected tabs to increase visibility. This is used by docking. Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. diff --git a/imgui.cpp b/imgui.cpp index 72f1f1871..114aeee25 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6140,12 +6140,13 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si border_target = ImClamp(border_target, clamp_min, clamp_max); if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent { - ImGuiWindowFlags parent_flags = window->ParentWindow->Flags; - ImRect border_limit_rect = window->ParentWindow->InnerRect; - border_limit_rect.Expand(ImVec2(-ImMax(window->WindowPadding.x, window->WindowBorderSize), -ImMax(window->WindowPadding.y, window->WindowBorderSize))); - if ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)) + ImGuiWindow* parent_window = window->ParentWindow; + ImGuiWindowFlags parent_flags = parent_window->Flags; + ImRect border_limit_rect = parent_window->InnerRect; + border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize))); + if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar))) border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x); - if (parent_flags & ImGuiWindowFlags_NoScrollbar) + if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar)) border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y); } if (!ignore_resize) From 0582f7678a4447d9d36e3f2385d990f4885d44e1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Jun 2024 19:05:47 +0200 Subject: [PATCH 0038/2359] Nav: store NavJustMovedToIsTabbing + shuffle a few nav related fields. (for usage by multi-select) --- imgui.cpp | 5 +++++ imgui_internal.h | 26 ++++++++++++++++++-------- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 114aeee25..25423664a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12393,6 +12393,8 @@ void ImGui::NavInitRequestApplyResult() g.NavJustMovedToId = result->ID; g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = 0; + g.NavJustMovedToIsTabbing = false; + g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0; } // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) @@ -12649,6 +12651,9 @@ void ImGui::NavMoveRequestApplyResult() g.NavJustMovedToId = result->ID; g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = g.NavMoveKeyMods; + g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0; + g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0; + //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId); } // Apply new NavID/Focus diff --git a/imgui_internal.h b/imgui_internal.h index 9bbbc5eca..b75f9a324 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1599,7 +1599,7 @@ struct ImGuiNavItemData float DistBox; // Move // Best candidate box distance to current NavId float DistCenter; // Move // Best candidate center distance to current NavId float DistAxial; // Move // Best candidate axial distance to current NavId - ImGuiSelectionUserData SelectionUserData;//I+Mov // Best candidate SetNextItemSelectionData() value. + ImGuiSelectionUserData SelectionUserData;//I+Mov // Best candidate SetNextItemSelectionUserData() value. Valid if (InFlags & ImGuiItemFlags_HasSelectionUserData) ImGuiNavItemData() { Clear(); } void Clear() { Window = NULL; ID = FocusScopeId = 0; InFlags = 0; SelectionUserData = -1; DistBox = DistCenter = DistAxial = FLT_MAX; } @@ -2044,6 +2044,7 @@ struct ImGuiContext ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusedWindow' ImGuiID NavId; // Focused item for navigation ImGuiID NavFocusScopeId; // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope) + ImGuiNavLayer NavLayer; // Focused layer (main scrolling layer, or menu/title bar layer) ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItem() ImGuiID NavActivateDownId; // ~~ IsKeyDown(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyDown(ImGuiKey_NavGamepadActivate) ? NavId : 0 ImGuiID NavActivatePressedId; // ~~ IsKeyPressed(ImGuiKey_Space) || IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate) ? NavId : 0 (no repeat) @@ -2051,13 +2052,9 @@ struct ImGuiContext ImVector NavFocusRoute; // Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window->ParentWindowForFocusRoute chain. ImGuiID NavHighlightActivatedId; float NavHighlightActivatedTimer; - ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest). - ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest). - ImGuiKeyChord NavJustMovedToKeyMods; ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame. ImGuiActivateFlags NavNextActivateFlags; ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse - ImGuiNavLayer NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later. ImGuiSelectionUserData NavLastValidSelectionUserData; // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data. bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRectRel is valid bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default) @@ -2088,6 +2085,14 @@ struct ImGuiContext ImGuiNavItemData NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) ImGuiNavItemData NavTabbingResultFirst; // First tabbing request candidate within NavWindow and flattened hierarchy + // Navigation: record of last move request + ImGuiID NavJustMovedFromFocusScopeId; // Just navigated from this focus scope id (result of a successfully MoveRequest). + ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest). + ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest). + ImGuiKeyChord NavJustMovedToKeyMods; + bool NavJustMovedToIsTabbing; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. + bool NavJustMovedToHasSelectionData; // Copy of move result's InFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. + // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828) ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X) @@ -2324,18 +2329,18 @@ struct ImGuiContext NavWindow = NULL; NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0; - NavJustMovedToId = NavJustMovedToFocusScopeId = NavNextActivateId = 0; + NavLayer = ImGuiNavLayer_Main; + NavNextActivateId = 0; NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None; NavHighlightActivatedId = 0; NavHighlightActivatedTimer = 0.0f; - NavJustMovedToKeyMods = ImGuiMod_None; NavInputSource = ImGuiInputSource_Keyboard; - NavLayer = ImGuiNavLayer_Main; NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; NavIdIsAlive = false; NavMousePosDirty = false; NavDisableHighlight = true; NavDisableMouseHover = false; + NavAnyRequest = false; NavInitRequest = false; NavInitRequestFromMove = false; @@ -2350,6 +2355,11 @@ struct ImGuiContext NavTabbingDir = 0; NavTabbingCounter = 0; + NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0; + NavJustMovedToKeyMods = ImGuiMod_None; + NavJustMovedToIsTabbing = false; + NavJustMovedToHasSelectionData = false; + // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac... // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this.. ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab); From 404af57004917e4b7cb763d416a78f2acf990055 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 15:04:52 +0200 Subject: [PATCH 0039/2359] Backends: OpenGL2, OpenGL3: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) Analogous to change to Vulkan backend in 1.90. --- backends/imgui_impl_opengl2.cpp | 3 +++ backends/imgui_impl_opengl3.cpp | 3 +++ docs/CHANGELOG.txt | 2 ++ 3 files changed, 8 insertions(+) diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp index 3eb092afd..7f1ea325a 100644 --- a/backends/imgui_impl_opengl2.cpp +++ b/backends/imgui_impl_opengl2.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-06-28: OpenGL: ImGui_ImplOpenGL2_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL2_DestroyFontsTexture(). (#7748) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-12-08: OpenGL: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). @@ -113,6 +114,8 @@ void ImGui_ImplOpenGL2_NewFrame() if (!bd->FontTexture) ImGui_ImplOpenGL2_CreateDeviceObjects(); + if (!bd->FontTexture) + ImGui_ImplOpenGL2_CreateFontsTexture(); } static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 58603a047..bbe96c420 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) // 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562) // 2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447) // 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink. @@ -402,6 +403,8 @@ void ImGui_ImplOpenGL3_NewFrame() if (!bd->ShaderHandle) ImGui_ImplOpenGL3_CreateDeviceObjects(); + if (!bd->FontTexture) + ImGui_ImplOpenGL3_CreateFontsTexture(); } static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4b9b12c79..18871c060 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -90,6 +90,8 @@ Other changes: - Debug Tools: Metrics/Debugger: Browsing a Storage perform hover lookup on identifier. - Viewports: Backported 'void* ImGuiViewport::PlatformHandle' from docking branch for use by backends. +- Backends: OpenGL2, OpenGL3: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it + has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) [@mlauss2] - Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) - Backends: SDL3: Update for SDL_StartTextInput()/SDL_StopTextInput() API changes. (#7735) - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) From c7df9c71214a16790eaa2d202a5fd7b9f164578f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 15:48:08 +0200 Subject: [PATCH 0040/2359] Backends: Win32: Fixed warning with old MinGW/GCC versions. --- backends/imgui_impl_win32.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index b0f694057..9241f8edb 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -98,6 +98,7 @@ typedef DWORD(WINAPI* PFN_XInputGetState)(DWORD, XINPUT_STATE*); #endif #if defined(__GNUC__) #pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) #endif From 0403096a9d3574d6c07eda91daf79d45e3fbf927 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 15:54:40 +0200 Subject: [PATCH 0041/2359] Drags: added ImGuisliderFlags_WrapAround flag for DragInt(), DragFloat() etc. (#7749) --- docs/CHANGELOG.txt | 1 + imgui.h | 5 +++-- imgui_demo.cpp | 12 ++++++++---- imgui_widgets.cpp | 37 +++++++++++++++++++++++++------------ 4 files changed, 37 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 18871c060..d3f328494 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,7 @@ Other changes: Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. - Tables: added TableGetHoveredColumn() to public API, as an alternative to testing for 'TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered' on each column. (#3740) +- Drags: added ImGuisliderFlags_WrapAround flag for DragInt(), DragFloat() etc. (#7749) - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern sets active id so a multi-frame extern source doesn't interfere with hovered widgets. (#143) - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern does not assume diff --git a/imgui.h b/imgui.h index ff8778c03..1ba242aa0 100644 --- a/imgui.h +++ b/imgui.h @@ -1732,8 +1732,9 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_None = 0, ImGuiSliderFlags_AlwaysClamp = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. - ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) - ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget + ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). + ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget. + ImGuisliderFlags_WrapAround = 1 << 8, // Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions for now. ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. // Obsolete names diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7bc4281cf..745258617 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -720,18 +720,19 @@ static void ShowDemoWindowWidgets() { IMGUI_DEMO_MARKER("Widgets/Basic/DragInt, DragFloat"); - static int i1 = 50, i2 = 42; + static int i1 = 50, i2 = 42, i3 = 128; ImGui::DragInt("drag int", &i1, 1); ImGui::SameLine(); HelpMarker( "Click and drag to edit value.\n" "Hold SHIFT/ALT for faster/slower edit.\n" "Double-click or CTRL+click to input value."); - ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); + ImGui::DragInt("drag int wrap 100..200", &i3, 1, 100, 200, "%d", ImGuisliderFlags_WrapAround); static float f1 = 1.00f, f2 = 0.0067f; ImGui::DragFloat("drag float", &f1, 0.005f); ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); + //ImGui::DragFloat("drag wrap -1..1", &f3, 0.005f, -1.0f, 1.0f, NULL, ImGuisliderFlags_WrapAround); } ImGui::SeparatorText("Sliders"); @@ -2145,6 +2146,8 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput); ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); + ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuisliderFlags_WrapAround); + ImGui::SameLine(); HelpMarker("Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions)"); // Drags static float drag_f = 0.5f; @@ -2159,9 +2162,10 @@ static void ShowDemoWindowWidgets() // Sliders static float slider_f = 0.5f; static int slider_i = 50; + const ImGuiSliderFlags flags_for_sliders = flags & ~ImGuisliderFlags_WrapAround; ImGui::Text("Underlying float value: %f", slider_f); - ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags); - ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags); + 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::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 927cb2b98..41a14bf3d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2305,12 +2305,13 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const { ImGuiContext& g = *GImGui; const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; - const bool is_clamped = (v_min < v_max); + const bool is_bounded = (v_min < v_max); + const bool is_wrapped = is_bounded && (flags & ImGuisliderFlags_WrapAround); const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0; const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); // Default tweak speed - if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX)) + if (v_speed == 0.0f && is_bounded && (v_max - v_min < FLT_MAX)) v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio); // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings @@ -2344,8 +2345,8 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const // Clear current value on activation // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. - bool is_just_activated = g.ActiveIdIsJustActivated; - bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); + const bool is_just_activated = g.ActiveIdIsJustActivated; + const bool is_already_past_limits_and_pushing_outward = is_bounded && !is_wrapped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); if (is_just_activated || is_already_past_limits_and_pushing_outward) { g.DragCurrentAccum = 0.0f; @@ -2403,13 +2404,24 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (v_cur == (TYPE)-0) v_cur = (TYPE)0; - // Clamp values (+ handle overflow/wrap-around for integer types) - if (*v != v_cur && is_clamped) + if (*v != v_cur && is_bounded) { - if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_floating_point)) - v_cur = v_min; - if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_floating_point)) - v_cur = v_max; + if (is_wrapped) + { + // Wrap values + 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 + { + // Clamp values + handle overflow/wrap-around for integer types. + if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_floating_point)) + v_cur = v_min; + if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_floating_point)) + v_cur = v_max; + } } // Apply result @@ -2422,7 +2434,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. - IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -3015,7 +3027,8 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) { // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. - IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); + IM_ASSERT((flags & ImGuisliderFlags_WrapAround) == 0); // Not supported by SliderXXX(), only by DragXXX() switch (data_type) { From 372eebbeb2975096a8b59a1aed9dc178512e77dd Mon Sep 17 00:00:00 2001 From: Kevin Coghlan Date: Fri, 28 Jun 2024 17:06:16 +0100 Subject: [PATCH 0042/2359] Fix typo, rename ImGuisliderFlags_WrapAround flag to ImGuiSliderFlags_WrapAround. (#7752, #7749) --- docs/CHANGELOG.txt | 2 +- imgui.h | 2 +- imgui_demo.cpp | 8 ++++---- imgui_widgets.cpp | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d3f328494..0a01f1b9d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,7 +77,7 @@ Other changes: Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. - Tables: added TableGetHoveredColumn() to public API, as an alternative to testing for 'TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered' on each column. (#3740) -- Drags: added ImGuisliderFlags_WrapAround flag for DragInt(), DragFloat() etc. (#7749) +- Drags: added ImGuiSliderFlags_WrapAround flag for DragInt(), DragFloat() etc. (#7749) - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern sets active id so a multi-frame extern source doesn't interfere with hovered widgets. (#143) - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern does not assume diff --git a/imgui.h b/imgui.h index 1ba242aa0..4d9083c0e 100644 --- a/imgui.h +++ b/imgui.h @@ -1734,7 +1734,7 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget. - ImGuisliderFlags_WrapAround = 1 << 8, // Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions for now. + ImGuiSliderFlags_WrapAround = 1 << 8, // Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions for now. ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. // Obsolete names diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 745258617..838b44380 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -727,12 +727,12 @@ static void ShowDemoWindowWidgets() "Hold SHIFT/ALT for faster/slower edit.\n" "Double-click or CTRL+click to input value."); ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); - ImGui::DragInt("drag int wrap 100..200", &i3, 1, 100, 200, "%d", ImGuisliderFlags_WrapAround); + ImGui::DragInt("drag int wrap 100..200", &i3, 1, 100, 200, "%d", ImGuiSliderFlags_WrapAround); static float f1 = 1.00f, f2 = 0.0067f; ImGui::DragFloat("drag float", &f1, 0.005f); ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); - //ImGui::DragFloat("drag wrap -1..1", &f3, 0.005f, -1.0f, 1.0f, NULL, ImGuisliderFlags_WrapAround); + //ImGui::DragFloat("drag wrap -1..1", &f3, 0.005f, -1.0f, 1.0f, NULL, ImGuiSliderFlags_WrapAround); } ImGui::SeparatorText("Sliders"); @@ -2146,7 +2146,7 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput); ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); - ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuisliderFlags_WrapAround); + ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuiSliderFlags_WrapAround); ImGui::SameLine(); HelpMarker("Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions)"); // Drags @@ -2162,7 +2162,7 @@ static void ShowDemoWindowWidgets() // Sliders static float slider_f = 0.5f; static int slider_i = 50; - const ImGuiSliderFlags flags_for_sliders = flags & ~ImGuisliderFlags_WrapAround; + const ImGuiSliderFlags flags_for_sliders = flags & ~ImGuiSliderFlags_WrapAround; 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 41a14bf3d..18a94bffe 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2306,7 +2306,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const ImGuiContext& g = *GImGui; const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_bounded = (v_min < v_max); - const bool is_wrapped = is_bounded && (flags & ImGuisliderFlags_WrapAround); + const bool is_wrapped = is_bounded && (flags & ImGuiSliderFlags_WrapAround); const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0; const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); @@ -3028,7 +3028,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type { // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); - IM_ASSERT((flags & ImGuisliderFlags_WrapAround) == 0); // Not supported by SliderXXX(), only by DragXXX() + IM_ASSERT((flags & ImGuiSliderFlags_WrapAround) == 0); // Not supported by SliderXXX(), only by DragXXX() switch (data_type) { From c47928ffc0f42bd08e5643eb1d788812cba1ac3e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 18:33:57 +0200 Subject: [PATCH 0043/2359] Checkbox: minor tidying up to simplify work on multi-select branch. --- imgui_widgets.cpp | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 18a94bffe..715f236c2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1132,7 +1132,8 @@ bool ImGui::Checkbox(const char* label, bool* v) const ImVec2 pos = window->DC.CursorPos; const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); ItemSize(total_bb, style.FramePadding.y); - if (!ItemAdd(total_bb, id)) + const bool is_visible = ItemAdd(total_bb, id); + if (!is_visible) { IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return false; @@ -1147,27 +1148,29 @@ bool ImGui::Checkbox(const char* label, bool* v) } const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); - RenderNavHighlight(total_bb, id); - RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); - ImU32 check_col = GetColorU32(ImGuiCol_CheckMark); - bool mixed_value = (g.LastItemData.InFlags & ImGuiItemFlags_MixedValue) != 0; - if (mixed_value) + const bool mixed_value = (g.LastItemData.InFlags & ImGuiItemFlags_MixedValue) != 0; + if (is_visible) { - // 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) - 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); + RenderNavHighlight(total_bb, id); + RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); + ImU32 check_col = GetColorU32(ImGuiCol_CheckMark); + if (mixed_value) + { + // 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) + 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) + { + const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f)); + RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f); + } } - else if (*v) - { - const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f)); - RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f); - } - - ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); + const ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); if (g.LogEnabled) LogRenderedText(&label_pos, mixed_value ? "[~]" : *v ? "[x]" : "[ ]"); - if (label_size.x > 0.0f) + if (is_visible && label_size.x > 0.0f) RenderText(label_pos, label); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); From f2c07ed7175c79ab6e2999d14bb694c39510ad41 Mon Sep 17 00:00:00 2001 From: Connor Clark Date: Sun, 30 Jun 2024 14:25:51 -0700 Subject: [PATCH 0044/2359] Backends: Allegro5: Correctly handle unstable bit in version checks (#7755) --- backends/imgui_impl_allegro5.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 03a457082..db366fa74 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -62,8 +62,8 @@ #ifdef _WIN32 #include #endif -#define ALLEGRO_HAS_CLIPBOARD (ALLEGRO_VERSION_INT >= ((5 << 24) | (1 << 16) | (12 << 8))) // Clipboard only supported from Allegro 5.1.12 -#define ALLEGRO_HAS_DRAW_INDEXED_PRIM (ALLEGRO_VERSION_INT >= ((5 << 24) | (2 << 16) | ( 5 << 8))) // DX9 implementation of al_draw_indexed_prim() got fixed in Allegro 5.2.5 +#define ALLEGRO_HAS_CLIPBOARD ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (1 << 16) | (12 << 8))) // Clipboard only supported from Allegro 5.1.12 +#define ALLEGRO_HAS_DRAW_INDEXED_PRIM ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (2 << 16) | ( 5 << 8))) // DX9 implementation of al_draw_indexed_prim() got fixed in Allegro 5.2.5 // Visual Studio warnings #ifdef _MSC_VER From 751bbf38ba5aed4122462e11cd7f838567c2040e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 12:04:36 +0200 Subject: [PATCH 0045/2359] Backends: SDLRenderer3: Update for SDL_RenderGeometryRaw() API changes. --- backends/imgui_impl_sdlrenderer3.cpp | 29 +++++++++++++++++++++++++--- docs/CHANGELOG.txt | 1 + 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index ae75b7c8b..8ba262548 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -20,6 +20,7 @@ // - Introduction, links and more at the top of imgui.cpp // CHANGELOG +// 2024-07-01: Update for SDL3 api changes: SDL_RenderGeometryRaw() uint32 version was removed (SDL#9009). // 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter. // 2024-02-12: Amend to query SDL_RenderViewportSet() and restore viewport accordingly. // 2023-05-30: Initial version. @@ -44,8 +45,10 @@ // SDL_Renderer data struct ImGui_ImplSDLRenderer3_Data { - SDL_Renderer* Renderer; // Main viewport's renderer - SDL_Texture* FontTexture; + SDL_Renderer* Renderer; // Main viewport's renderer + SDL_Texture* FontTexture; + ImVector ColorBuffer; + ImGui_ImplSDLRenderer3_Data() { memset((void*)this, 0, sizeof(*this)); } }; @@ -106,8 +109,28 @@ void ImGui_ImplSDLRenderer3_NewFrame() ImGui_ImplSDLRenderer3_CreateDeviceObjects(); } +// https://github.com/libsdl-org/SDL/issues/9009 +static int SDL_RenderGeometryRaw8BitColor(SDL_Renderer* renderer, ImVector& colors_out, SDL_Texture* texture, const float* xy, int xy_stride, const SDL_Color* color, int color_stride, const float* uv, int uv_stride, int num_vertices, const void* indices, int num_indices, int size_indices) +{ + const Uint8* color2 = (const Uint8*)color; + colors_out.resize(num_vertices); + SDL_FColor* color3 = colors_out.Data; + for (int i = 0; i < num_vertices; i++) + { + color3[i].r = color->r / 255.0f; + color3[i].g = color->g / 255.0f; + color3[i].b = color->b / 255.0f; + color3[i].a = color->a / 255.0f; + color2 += color_stride; + color = (const SDL_Color*)color2; + } + return SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, color3, sizeof(*color3), uv, uv_stride, num_vertices, indices, num_indices, size_indices); +} + void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer) { + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + // If there's a scale factor set by the user, use that instead // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. @@ -183,7 +206,7 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* // Bind texture, Draw SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); - SDL_RenderGeometryRaw(renderer, tex, + SDL_RenderGeometryRaw8BitColor(renderer, bd->ColorBuffer, tex, xy, (int)sizeof(ImDrawVert), color, (int)sizeof(ImDrawVert), uv, (int)sizeof(ImDrawVert), diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0a01f1b9d..0ceb01215 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -95,6 +95,7 @@ Other changes: has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) [@mlauss2] - Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) - Backends: SDL3: Update for SDL_StartTextInput()/SDL_StopTextInput() API changes. (#7735) +- Backends: SDLRenderer3: Update for SDL_RenderGeometryRaw() API changes. (SDL#9009). - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) [@martin-ejdestig] - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan From ccf3ee674a063a85653056a80fafc9e398c7dd68 Mon Sep 17 00:00:00 2001 From: Max Ortner Date: Sun, 30 Jun 2024 16:28:53 -0600 Subject: [PATCH 0046/2359] Backends: SDL3: update for SDL_SetTextInputRect() -> SDL_SetTextInputArea() api change. (#7760, #7754) --- backends/imgui_impl_sdl3.cpp | 3 ++- docs/CHANGELOG.txt | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index f8e2c5510..c90455f61 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea(). // 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures. // 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents. // 2024-06-03; Update for SDL3 api changes: SDL_SYSTEM_CURSOR_ renames. @@ -139,7 +140,7 @@ static void ImGui_ImplSDL3_SetPlatformImeData(ImGuiViewport* viewport, ImGuiPlat r.y = (int)data->InputPos.y; r.w = 1; r.h = (int)data->InputLineHeight; - SDL_SetTextInputRect(window, &r); + SDL_SetTextInputArea(window, &r, 0); SDL_StartTextInput(window); bd->ImeWindow = window; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0ceb01215..359c89fb6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -95,6 +95,7 @@ Other changes: has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) [@mlauss2] - Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) - Backends: SDL3: Update for SDL_StartTextInput()/SDL_StopTextInput() API changes. (#7735) +- Backends: SDL3: Update for SDL_SetTextInputRect() API rename. (#7760, #7754) [@maxortner01] - Backends: SDLRenderer3: Update for SDL_RenderGeometryRaw() API changes. (SDL#9009). - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) [@martin-ejdestig] From 67216910fb0f6b3818fe04fa8c07c5237fff92a3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 12:10:54 +0200 Subject: [PATCH 0047/2359] Examples: SDL3: Remove use of SDL_HINT_IME_NATIVE_UI. --- docs/CHANGELOG.txt | 2 ++ examples/example_sdl3_opengl3/main.cpp | 3 --- examples/example_sdl3_sdlrenderer3/main.cpp | 3 --- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 359c89fb6..66896b294 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -99,6 +99,8 @@ Other changes: - Backends: SDLRenderer3: Update for SDL_RenderGeometryRaw() API changes. (SDL#9009). - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) [@martin-ejdestig] +- Examples: SDL3: Remove use of SDL_HINT_IME_NATIVE_UI since new SDL_HINT_IME_IMPLEMENTED_UI + values has a more suitable default for our case case. - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index da12589f8..7ce36b4e8 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -57,9 +57,6 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #endif - // Enable native IME. - SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); - // Create window with graphics context SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 98b9666ea..607d00b6b 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -31,9 +31,6 @@ int main(int, char**) return -1; } - // Enable native IME. - SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); - // Create window with SDL_Renderer graphics context Uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", 1280, 720, window_flags); From dd5c30d2d75b1038486468638729a5fed5ed3f84 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 14:32:11 +0200 Subject: [PATCH 0048/2359] Disabled: Reworked 1.90.8 behavior of Begin() not inheriting current BeginDisabled() state. Only tooltip are clearing that state. (#211, #7640) --- docs/CHANGELOG.txt | 6 ++++-- imgui.cpp | 2 +- imgui.h | 1 + imgui_demo.cpp | 3 +-- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 66896b294..bd5caffd2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,8 +67,6 @@ Other changes: on third-party backends to set ImGuiBackendFlags_HasMouseCursors and honor changes of ImGui::GetMouseCursor() value. (#1495) - IO: Added io.ClearInputMouse() to clear mouse state. (#4921) -- Inputs: fixed using Shortcut() or SetNextItemShortcut() within a disabled block bypassing - the disabled state. (#7726) - Windows: BeginChild(): fixed a glitch when during a resize of a child window which is tightly close to the boundaries of its parent (e.g. with zero WindowPadding), the child position could have temporarily be moved around by erroneous padding application. (#7706) @@ -77,6 +75,10 @@ Other changes: Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. - Tables: added TableGetHoveredColumn() to public API, as an alternative to testing for 'TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered' on each column. (#3740) +- Disabled, Inputs: fixed using Shortcut() or SetNextItemShortcut() within a disabled block + bypassing the disabled state. (#7726) +- Disabled: Reworked 1.90.8 behavior of Begin() not inheriting current BeginDisabled() state, + to make it that only tooltip windows are temporarily clearing it. (#211, #7640) - Drags: added ImGuiSliderFlags_WrapAround flag for DragInt(), DragFloat() etc. (#7749) - Drag and Drop: BeginDragDropSource() with ImGuiDragDropFlags_SourceExtern sets active id so a multi-frame extern source doesn't interfere with hovered widgets. (#143) diff --git a/imgui.cpp b/imgui.cpp index 25423664a..cb0da9398 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6589,7 +6589,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window_stack_data.Window = window; window_stack_data.ParentLastItemDataBackup = g.LastItemData; window_stack_data.StackSizesOnBegin.SetToContextState(&g); - window_stack_data.DisabledOverrideReenable = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; + window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled); g.CurrentWindowStack.push_back(window_stack_data); if (flags & ImGuiWindowFlags_ChildMenu) g.BeginMenuDepth++; diff --git a/imgui.h b/imgui.h index 4d9083c0e..d6dfd538a 100644 --- a/imgui.h +++ b/imgui.h @@ -861,6 +861,7 @@ namespace ImGui // Disabling [BETA API] // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) + // - Tooltips windows by exception are opted out of disabling. // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it. IMGUI_API void BeginDisabled(bool disabled = true); IMGUI_API void EndDisabled(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 838b44380..72ac77982 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -889,12 +889,11 @@ static void ShowDemoWindowWidgets() // Using ImGuiHoveredFlags_ForTooltip will pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav', // which default value include the ImGuiHoveredFlags_AllowWhenDisabled flag. - // As a result, Set ImGui::BeginDisabled(); ImGui::Button("Disabled item", sz); - ImGui::EndDisabled(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) ImGui::SetTooltip("I am a a tooltip for a disabled item."); + ImGui::EndDisabled(); ImGui::TreePop(); } From 50a0f18e6aeeaee2ed3de67bd6e312577af5084d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 14:57:33 +0200 Subject: [PATCH 0049/2359] imgui_freetype: fixed divide by zero while handling FT_PIXEL_MODE_BGRA glyphs. (#7267, #3369) --- docs/CHANGELOG.txt | 1 + misc/freetype/imgui_freetype.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bd5caffd2..5f35dc15a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -93,6 +93,7 @@ Other changes: - Debug Tools: Metrics/Debugger: Browsing a Storage perform hover lookup on identifier. - Viewports: Backported 'void* ImGuiViewport::PlatformHandle' from docking branch for use by backends. +- imgui_freetype: Fixed divide by zero while handling FT_PIXEL_MODE_BGRA glyphs. (#7267, #3369) - Backends: OpenGL2, OpenGL3: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) [@mlauss2] - Backends: SDL3: Update for API removal of keysym field in SDL_KeyboardEvent. (#7728) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index a5acab32d..68e38ed95 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -357,7 +357,7 @@ namespace case FT_PIXEL_MODE_BGRA: { // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. - #define DE_MULTIPLY(color, alpha) (ImU32)(255.0f * (float)color / (float)alpha + 0.5f) + #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u) if (multiply_table == nullptr) { for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) From c554c402d307e6fde50e895adad009e23343ed26 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 16:13:38 +0200 Subject: [PATCH 0050/2359] IO: do not claim io.WantCaptureMouse=true on the mouse release frame of a button which was pressed over void. (#1392) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 +- imgui.h | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5f35dc15a..889ce554e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,9 @@ Other changes: shape change as honored by backends. Keeping this enabling will hopefully increase pressure on third-party backends to set ImGuiBackendFlags_HasMouseCursors and honor changes of ImGui::GetMouseCursor() value. (#1495) +- IO: do not claim io.WantCaptureMouse=true on the mouse release frame of a button + which was pressed over void/underlying app, which is consistent/needed to allow the + mouse up event of a drag over void/underlying app to catch release. (#1392) [@Moka42] - IO: Added io.ClearInputMouse() to clear mouse state. (#4921) - Windows: BeginChild(): fixed a glitch when during a resize of a child window which is tightly close to the boundaries of its parent (e.g. with zero WindowPadding), the child diff --git a/imgui.cpp b/imgui.cpp index cb0da9398..8d8d7b64a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4598,7 +4598,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal; } mouse_any_down |= io.MouseDown[i]; - if (io.MouseDown[i]) + if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392) if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down]) mouse_earliest_down = i; } diff --git a/imgui.h b/imgui.h index d6dfd538a..b93c0d947 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.90.9 WIP" -#define IMGUI_VERSION_NUM 19084 +#define IMGUI_VERSION_NUM 19085 #define IMGUI_HAS_TABLE /* From cb16be3a3fc1f9cd146ae24d52b615f8a05fa93d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 16:50:03 +0200 Subject: [PATCH 0051/2359] Version 1.90.9 --- docs/CHANGELOG.txt | 7 +++++-- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 14 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 889ce554e..16fc04d39 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.90.9 WIP (In Progress) + VERSION 1.90.9 (Released 2024-07-01) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.9 + Breaking changes: - Removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to @@ -48,6 +50,7 @@ Breaking changes: BeginChild() calls anyhow. (#7687) [@cfillion] - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened); - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0) + Kept inline redirection flag (will obsolete). - Style: renamed tab colors for clarity and consistency with other changes: (#261, #351) - ImGuiCol_TabActive -> ImGuiCol_TabSelected - ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed @@ -56,7 +59,7 @@ Breaking changes: - IO: io.ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data. Newly added io.ClearInputMouse() does. (#4921) - Drag and Drop: renamed ImGuiDragDropFlags_SourceAutoExpirePayload to - ImGuiDragDropFlags_PayloadAutoExpire. Kept inline redirecting enum (will obsolete). (#1725, #143). + ImGuiDragDropFlags_PayloadAutoExpire. Kept inline redirecting enum (will obsolete). (#1725, #143) Other changes: diff --git a/imgui.cpp b/imgui.cpp index 8d8d7b64a..31220bdf2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 WIP +// dear imgui, v1.90.9 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index b93c0d947..a22e7ae9c 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 WIP +// dear imgui, v1.90.9 // (headers) // Help: @@ -27,8 +27,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.90.9 WIP" -#define IMGUI_VERSION_NUM 19085 +#define IMGUI_VERSION "1.90.9" +#define IMGUI_VERSION_NUM 19090 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 72ac77982..955f3d1db 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 WIP +// dear imgui, v1.90.9 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c8499441e..51974604b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 WIP +// dear imgui, v1.90.9 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index b75f9a324..cb7b7319e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 WIP +// dear imgui, v1.90.9 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 778d27afd..dc69f9462 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 WIP +// dear imgui, v1.90.9 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 715f236c2..d261ba8ff 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 WIP +// dear imgui, v1.90.9 // (widgets code) /* From 84cc72f37209fae8cf4ab440f6aa9851254ba5f8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 19:00:44 +0200 Subject: [PATCH 0052/2359] Version 1.91.0 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 12 ++++++------ imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 21 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 16fc04d39..75e10acce 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.91.0 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking changes: + +Other changes: + + ----------------------------------------------------------------------- VERSION 1.90.9 (Released 2024-07-01) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 31220bdf2..4cfa2e1a0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 +// dear imgui, v1.91.0 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index a22e7ae9c..2ec9aad26 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 +// dear imgui, v1.91.0 WIP // (headers) // Help: @@ -27,8 +27,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.90.9" -#define IMGUI_VERSION_NUM 19090 +#define IMGUI_VERSION "1.91.0 WIP" +#define IMGUI_VERSION_NUM 19091 #define IMGUI_HAS_TABLE /* @@ -1660,11 +1660,11 @@ enum ImGuiStyleVar_ ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_TabBorderSize, // float TabBorderSize ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize - ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle - ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign + ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle + ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign - ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize + ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize ImGuiStyleVar_SeparatorTextAlign, // ImVec2 SeparatorTextAlign ImGuiStyleVar_SeparatorTextPadding, // ImVec2 SeparatorTextPadding ImGuiStyleVar_COUNT diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 955f3d1db..6ea0e47d7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 +// dear imgui, v1.91.0 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 51974604b..7ef0f2c6a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 +// dear imgui, v1.91.0 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index cb7b7319e..29ed03bca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 +// dear imgui, v1.91.0 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index dc69f9462..8b392fc3c 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 +// dear imgui, v1.91.0 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d261ba8ff..b40dcce11 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.90.9 +// dear imgui, v1.91.0 WIP // (widgets code) /* From 12f92518bc51194e6eb096a2863690f7fd2efcc4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 11:32:46 +0200 Subject: [PATCH 0053/2359] Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) Also updated function signature in SDL2 backend to match and because it is expected we will use that data (as per #7672) --- backends/imgui_impl_sdl2.cpp | 5 +- backends/imgui_impl_sdl3.cpp | 96 +++++++++++++++++++----------------- docs/CHANGELOG.txt | 2 + 3 files changed, 56 insertions(+), 47 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index a18c013fd..5a319b930 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -163,8 +163,9 @@ static void ImGui_ImplSDL2_SetPlatformImeData(ImGuiViewport*, ImGuiPlatformImeDa } } -static ImGuiKey ImGui_ImplSDL2_KeycodeToImGuiKey(int keycode) +static ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode) { + IM_UNUSED(scancode); switch (keycode) { case SDLK_TAB: return ImGuiKey_Tab; @@ -361,7 +362,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) case SDL_KEYUP: { ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod); - ImGuiKey key = ImGui_ImplSDL2_KeycodeToImGuiKey(event->key.keysym.sym); + ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode); io.AddKeyEvent(key, (event->type == SDL_KEYDOWN)); io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. return true; diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index c90455f61..bbca11388 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762). // 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea(). // 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures. // 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents. @@ -146,8 +147,29 @@ static void ImGui_ImplSDL3_SetPlatformImeData(ImGuiViewport* viewport, ImGuiPlat } } -static ImGuiKey ImGui_ImplSDL3_KeycodeToImGuiKey(int keycode) +static ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode) { + // Keypad doesn't have individual key values in SDL3 + switch (scancode) + { + case SDL_SCANCODE_KP_0: return ImGuiKey_Keypad0; + case SDL_SCANCODE_KP_1: return ImGuiKey_Keypad1; + case SDL_SCANCODE_KP_2: return ImGuiKey_Keypad2; + case SDL_SCANCODE_KP_3: return ImGuiKey_Keypad3; + case SDL_SCANCODE_KP_4: return ImGuiKey_Keypad4; + case SDL_SCANCODE_KP_5: return ImGuiKey_Keypad5; + case SDL_SCANCODE_KP_6: return ImGuiKey_Keypad6; + case SDL_SCANCODE_KP_7: return ImGuiKey_Keypad7; + case SDL_SCANCODE_KP_8: return ImGuiKey_Keypad8; + case SDL_SCANCODE_KP_9: return ImGuiKey_Keypad9; + case SDL_SCANCODE_KP_PERIOD: return ImGuiKey_KeypadDecimal; + case SDL_SCANCODE_KP_DIVIDE: return ImGuiKey_KeypadDivide; + case SDL_SCANCODE_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; + case SDL_SCANCODE_KP_MINUS: return ImGuiKey_KeypadSubtract; + case SDL_SCANCODE_KP_PLUS: return ImGuiKey_KeypadAdd; + case SDL_SCANCODE_KP_ENTER: return ImGuiKey_KeypadEnter; + case SDL_SCANCODE_KP_EQUALS: return ImGuiKey_KeypadEqual; + } switch (keycode) { case SDLK_TAB: return ImGuiKey_Tab; @@ -181,23 +203,6 @@ static ImGuiKey ImGui_ImplSDL3_KeycodeToImGuiKey(int keycode) case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen; case SDLK_PAUSE: return ImGuiKey_Pause; - case SDLK_KP_0: return ImGuiKey_Keypad0; - case SDLK_KP_1: return ImGuiKey_Keypad1; - case SDLK_KP_2: return ImGuiKey_Keypad2; - case SDLK_KP_3: return ImGuiKey_Keypad3; - case SDLK_KP_4: return ImGuiKey_Keypad4; - case SDLK_KP_5: return ImGuiKey_Keypad5; - case SDLK_KP_6: return ImGuiKey_Keypad6; - case SDLK_KP_7: return ImGuiKey_Keypad7; - case SDLK_KP_8: return ImGuiKey_Keypad8; - case SDLK_KP_9: return ImGuiKey_Keypad9; - case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal; - case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide; - case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; - case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract; - case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd; - case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter; - case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual; case SDLK_LCTRL: return ImGuiKey_LeftCtrl; case SDLK_LSHIFT: return ImGuiKey_LeftShift; case SDLK_LALT: return ImGuiKey_LeftAlt; @@ -217,32 +222,32 @@ static ImGuiKey ImGui_ImplSDL3_KeycodeToImGuiKey(int keycode) case SDLK_7: return ImGuiKey_7; case SDLK_8: return ImGuiKey_8; case SDLK_9: return ImGuiKey_9; - case SDLK_a: return ImGuiKey_A; - case SDLK_b: return ImGuiKey_B; - case SDLK_c: return ImGuiKey_C; - case SDLK_d: return ImGuiKey_D; - case SDLK_e: return ImGuiKey_E; - case SDLK_f: return ImGuiKey_F; - case SDLK_g: return ImGuiKey_G; - case SDLK_h: return ImGuiKey_H; - case SDLK_i: return ImGuiKey_I; - case SDLK_j: return ImGuiKey_J; - case SDLK_k: return ImGuiKey_K; - case SDLK_l: return ImGuiKey_L; - case SDLK_m: return ImGuiKey_M; - case SDLK_n: return ImGuiKey_N; - case SDLK_o: return ImGuiKey_O; - case SDLK_p: return ImGuiKey_P; - case SDLK_q: return ImGuiKey_Q; - case SDLK_r: return ImGuiKey_R; - case SDLK_s: return ImGuiKey_S; - case SDLK_t: return ImGuiKey_T; - case SDLK_u: return ImGuiKey_U; - case SDLK_v: return ImGuiKey_V; - case SDLK_w: return ImGuiKey_W; - case SDLK_x: return ImGuiKey_X; - case SDLK_y: return ImGuiKey_Y; - case SDLK_z: return ImGuiKey_Z; + case SDLK_A: return ImGuiKey_A; + case SDLK_B: return ImGuiKey_B; + case SDLK_C: return ImGuiKey_C; + case SDLK_D: return ImGuiKey_D; + case SDLK_E: return ImGuiKey_E; + case SDLK_F: return ImGuiKey_F; + case SDLK_G: return ImGuiKey_G; + case SDLK_H: return ImGuiKey_H; + case SDLK_I: return ImGuiKey_I; + case SDLK_J: return ImGuiKey_J; + case SDLK_K: return ImGuiKey_K; + case SDLK_L: return ImGuiKey_L; + case SDLK_M: return ImGuiKey_M; + case SDLK_N: return ImGuiKey_N; + case SDLK_O: return ImGuiKey_O; + case SDLK_P: return ImGuiKey_P; + case SDLK_Q: return ImGuiKey_Q; + case SDLK_R: return ImGuiKey_R; + case SDLK_S: return ImGuiKey_S; + case SDLK_T: return ImGuiKey_T; + case SDLK_U: return ImGuiKey_U; + case SDLK_V: return ImGuiKey_V; + case SDLK_W: return ImGuiKey_W; + case SDLK_X: return ImGuiKey_X; + case SDLK_Y: return ImGuiKey_Y; + case SDLK_Z: return ImGuiKey_Z; case SDLK_F1: return ImGuiKey_F1; case SDLK_F2: return ImGuiKey_F2; case SDLK_F3: return ImGuiKey_F3; @@ -338,8 +343,9 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: { + //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod); ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); - ImGuiKey key = ImGui_ImplSDL3_KeycodeToImGuiKey(event->key.key); + ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode); io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN)); io.SetKeyEventNativeData(key, event->key.key, event->key.scancode, event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. return true; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 75e10acce..75ec36df6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking changes: Other changes: +- Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) + ----------------------------------------------------------------------- VERSION 1.90.9 (Released 2024-07-01) From a489585f8435cea7e9b24be37351a229789591c5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 11:37:18 +0200 Subject: [PATCH 0054/2359] Backends: SDL3: Updated comments (IME seems fixed in SDL3). Added SDL3 examples to Visual Studio solution. --- backends/imgui_impl_sdl3.cpp | 5 ++--- backends/imgui_impl_sdl3.h | 5 ++--- examples/imgui_examples.sln | 20 ++++++++++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index bbca11388..bc56a51a9 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -1,7 +1,8 @@ // dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) -// (IMPORTANT: SDL 3.0.0 is NOT YET RELEASED. IT IS POSSIBLE THAT ITS SPECS/API WILL CHANGE BEFORE RELEASE) + +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN**) // Implemented features: // [X] Platform: Clipboard support. @@ -9,8 +10,6 @@ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. -// Missing features: -// [ ] Platform: IME SUPPORT IS BROKEN IN SDL3 BECAUSE INPUTS GETS SENT TO BOTH APP AND IME + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h index eafb34749..f1c06db5d 100644 --- a/backends/imgui_impl_sdl3.h +++ b/backends/imgui_impl_sdl3.h @@ -1,7 +1,8 @@ // dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) -// (IMPORTANT: SDL 3.0.0 is NOT YET RELEASED. IT IS POSSIBLE THAT ITS SPECS/API WILL CHANGE BEFORE RELEASE) + +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN**) // Implemented features: // [X] Platform: Clipboard support. @@ -9,8 +10,6 @@ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. -// Missing features: -// [ ] Platform: IME SUPPORT IS BROKEN IN SDL3 BECAUSE INPUTS GETS SENT TO BOTH APP AND IME + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index 071bcbd63..9aee4a99e 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -29,6 +29,10 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_opengl3", "ex EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl2_sdlrenderer2", "example_sdl2_sdlrenderer2\example_sdl2_sdlrenderer2.vcxproj", "{0C0B2BEA-311F-473C-9652-87923EF639E3}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_opengl3", "example_sdl3_opengl3\example_sdl3_opengl3.vcxproj", "{84AAA301-84FE-428B-9E3E-817BC8123C0C}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlrenderer3", "example_sdl3_sdlrenderer3\example_sdl3_sdlrenderer3.vcxproj", "{C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -141,6 +145,22 @@ Global {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|Win32.Build.0 = Release|Win32 {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|x64.ActiveCfg = Release|x64 {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|x64.Build.0 = Release|x64 + {84AAA301-84FE-428B-9E3E-817BC8123C0C}.Debug|Win32.ActiveCfg = Debug|Win32 + {84AAA301-84FE-428B-9E3E-817BC8123C0C}.Debug|Win32.Build.0 = Debug|Win32 + {84AAA301-84FE-428B-9E3E-817BC8123C0C}.Debug|x64.ActiveCfg = Debug|x64 + {84AAA301-84FE-428B-9E3E-817BC8123C0C}.Debug|x64.Build.0 = Debug|x64 + {84AAA301-84FE-428B-9E3E-817BC8123C0C}.Release|Win32.ActiveCfg = Release|Win32 + {84AAA301-84FE-428B-9E3E-817BC8123C0C}.Release|Win32.Build.0 = Release|Win32 + {84AAA301-84FE-428B-9E3E-817BC8123C0C}.Release|x64.ActiveCfg = Release|x64 + {84AAA301-84FE-428B-9E3E-817BC8123C0C}.Release|x64.Build.0 = Release|x64 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|Win32.ActiveCfg = Debug|Win32 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|Win32.Build.0 = Debug|Win32 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|x64.ActiveCfg = Debug|x64 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Debug|x64.Build.0 = Debug|x64 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|Win32.ActiveCfg = Release|Win32 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|Win32.Build.0 = Release|Win32 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|x64.ActiveCfg = Release|x64 + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From a62794359aa9bbee5a5f624129699238b71395ca Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 12:00:55 +0200 Subject: [PATCH 0055/2359] Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 -- imgui.h | 18 ++++++++++++++++-- imgui_internal.h | 6 +----- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 75ec36df6..e06a3a152 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) + Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and + other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) diff --git a/imgui.cpp b/imgui.cpp index 4cfa2e1a0..d82757618 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16099,8 +16099,6 @@ void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {} void ImGui::DebugNodeWindowsList(ImVector*, const char*) {} void ImGui::DebugNodeViewport(ImGuiViewportP*) {} -void ImGui::DebugLog(const char*, ...) {} -void ImGui::DebugLogV(const char*, va_list) {} void ImGui::ShowDebugLogWindow(bool*) {} void ImGui::ShowIDStackToolWindow(bool*) {} void ImGui::DebugStartItemPicker() {} diff --git a/imgui.h b/imgui.h index 2ec9aad26..21728df87 100644 --- a/imgui.h +++ b/imgui.h @@ -39,7 +39,7 @@ Index of this file: // [SECTION] Dear ImGui end-user API functions // [SECTION] Flags & Enumerations // [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) -// [SECTION] Helpers: Memory allocations macros, ImVector<> +// [SECTION] Helpers: Debug log, Memory allocations macros, ImVector<> // [SECTION] ImGuiStyle // [SECTION] ImGuiIO // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) @@ -1001,6 +1001,10 @@ namespace ImGui 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. +#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); +#endif // Memory Allocators // - Those functions are not reliant on the current context. @@ -1958,9 +1962,19 @@ struct ImGuiTableColumnSortSpecs }; //----------------------------------------------------------------------------- -// [SECTION] Helpers: Memory allocations macros, ImVector<> +// [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> //----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// Debug Logging into ShowDebugLogWindow(), tty and more. +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +#define IMGUI_DEBUG_LOG(...) ImGui::DebugLog(__VA_ARGS__) +#else +#define IMGUI_DEBUG_LOG(...) ((void)0) +#endif + //----------------------------------------------------------------------------- // IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() // We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. diff --git a/imgui_internal.h b/imgui_internal.h index 29ed03bca..60bb28fd5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3513,12 +3513,8 @@ namespace ImGui IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window); IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window); - // Debug Log - IMGUI_API void DebugLog(const char* fmt, ...) IM_FMTARGS(1); - IMGUI_API void DebugLogV(const char* fmt, va_list args) IM_FMTLIST(1); - IMGUI_API void DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size); // size >= 0 : alloc, size = -1 : free - // Debug Tools + IMGUI_API void DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size); // size >= 0 : alloc, size = -1 : free IMGUI_API void ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL); IMGUI_API void ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL); IMGUI_API void ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); From 7e0b3b9caf81c783fecaee2f88f116a9c7e9bdab Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 12:10:33 +0200 Subject: [PATCH 0056/2359] Debug Log: Added "Configure Outputs.." button. (#5855) --- docs/CHANGELOG.txt | 1 + imconfig.h | 3 +++ imgui.cpp | 16 ++++++++++++++++ 3 files changed, 20 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e06a3a152..a0957c5c8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,7 @@ Other changes: - Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. +- Debug Tools: Debug Log: Added "Configure Outputs.." button. (#5855) - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) diff --git a/imconfig.h b/imconfig.h index d556cbaf1..1feaa6edc 100644 --- a/imconfig.h +++ b/imconfig.h @@ -49,6 +49,9 @@ //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available +//---- Enable Test Engine / Automation features. +//#define IMGUI_ENABLE_TEST_ENGINE // Enable imgui_test_engine hooks. Generally set automatically by include "imgui_te_config.h", see Test Engine for details. + //---- Include imgui_user.h at the end of imgui.h as a convenience // May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included. //#define IMGUI_INCLUDE_IMGUI_USER_H diff --git a/imgui.cpp b/imgui.cpp index d82757618..239dc228b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15739,6 +15739,22 @@ void ImGui::ShowDebugLogWindow(bool* p_open) SameLine(); if (SmallButton("Copy")) SetClipboardText(g.DebugLogBuf.c_str()); + SameLine(); + if (SmallButton("Configure Outputs..")) + OpenPopup("Outputs"); + if (BeginPopup("Outputs")) + { + CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY); +#ifndef IMGUI_ENABLE_TEST_ENGINE + BeginDisabled(); +#endif + CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine); +#ifndef IMGUI_ENABLE_TEST_ENGINE + EndDisabled(); +#endif + EndPopup(); + } + BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags; From ae708e3bcd761230016d3f5c8bedf396e04477d0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 12:12:25 +0200 Subject: [PATCH 0057/2359] Backends: SDL3: add default case to fix warnings. (#7763) --- backends/imgui_impl_sdl2.cpp | 1 + backends/imgui_impl_sdl3.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 5a319b930..6d2a868fa 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -287,6 +287,7 @@ static ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scanc case SDLK_F24: return ImGuiKey_F24; case SDLK_AC_BACK: return ImGuiKey_AppBack; case SDLK_AC_FORWARD: return ImGuiKey_AppForward; + default: break; } return ImGuiKey_None; } diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index bc56a51a9..c02345c8d 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -168,6 +168,7 @@ static ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scanc case SDL_SCANCODE_KP_PLUS: return ImGuiKey_KeypadAdd; case SDL_SCANCODE_KP_ENTER: return ImGuiKey_KeypadEnter; case SDL_SCANCODE_KP_EQUALS: return ImGuiKey_KeypadEqual; + default: break; } switch (keycode) { @@ -273,6 +274,7 @@ static ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scanc case SDLK_F24: return ImGuiKey_F24; case SDLK_AC_BACK: return ImGuiKey_AppBack; case SDLK_AC_FORWARD: return ImGuiKey_AppForward; + default: break; } return ImGuiKey_None; } From 0250dc903ef234a98a8a92b7462d169d8562c9e7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 14:38:44 +0200 Subject: [PATCH 0058/2359] Demo: changed style editor inline block to its own window. --- imgui_demo.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6ea0e47d7..2f8aacf06 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -540,8 +540,9 @@ void ImGui::ShowDemoWindow(bool* p_open) IMGUI_DEMO_MARKER("Configuration/Style"); if (ImGui::TreeNode("Style")) { + ImGui::Checkbox("Style Editor", &show_tool_style_editor); + ImGui::SameLine(); HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function."); - ImGui::ShowStyleEditor(); ImGui::TreePop(); ImGui::Spacing(); } From 8f36798035793196f54d9d2b4c4d5ebe523d64c7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 15:36:08 +0200 Subject: [PATCH 0059/2359] IO: added io.PlatformOpenInShellFn handler to open a link/folder/file in OS shell, added IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS. (#7660) --- docs/CHANGELOG.txt | 3 +++ imconfig.h | 1 + imgui.cpp | 41 +++++++++++++++++++++++++++++++++++++++-- imgui.h | 7 ++++++- 4 files changed, 49 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a0957c5c8..87038d978 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- IO: added io.PlatformOpenInShellFn handler to open a link/folder/file in OS shell. (#7660) + Default to use ShellExecute() under Windows, and system("") under Mac/Linux/etc. + Added IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS to disable default implementation. - Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. diff --git a/imconfig.h b/imconfig.h index 1feaa6edc..62365fb9b 100644 --- a/imconfig.h +++ b/imconfig.h @@ -42,6 +42,7 @@ //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME). //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). +//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default io.PlatformOpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) diff --git a/imgui.cpp b/imgui.cpp index 239dc228b..0e34267ab 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1015,7 +1015,7 @@ CODE #endif // [Windows] OS specific includes (optional) -#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) +#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) #define IMGUI_DISABLE_WIN32_FUNCTIONS #endif #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) @@ -1034,6 +1034,7 @@ CODE // The UWP and GDK Win32 API subsets don't support clipboard nor IME functions #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS +#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS #endif #endif @@ -1124,6 +1125,7 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSetti static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx); static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text); static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data); +static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); namespace ImGui { @@ -1369,6 +1371,7 @@ ImGuiIO::ImGuiIO() // Note: Initialize() will setup default clipboard/ime handlers. BackendPlatformName = BackendRendererName = NULL; BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL; + PlatformOpenInShellUserData = NULL; PlatformLocaleDecimalPoint = '.'; // Input (NB: we already have memset zero the entire structure!) @@ -3712,6 +3715,7 @@ void ImGui::Initialize() g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function) + g.IO.PlatformOpenInShellFn = PlatformOpenInShellFn_DefaultImpl; g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl; // Create default viewport @@ -14200,6 +14204,10 @@ static void ImGui::UpdateViewportsNewFrame() //----------------------------------------------------------------------------- // [SECTION] PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- +// - Default clipboard handlers +// - Default shell function handlers +// - Default IME handlers +//----------------------------------------------------------------------------- #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) @@ -14325,7 +14333,36 @@ static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text g.ClipboardHandlerData[(int)(text_end - text)] = 0; } +#endif // Default clipboard handlers + +//----------------------------------------------------------------------------- + +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) +#include // ShellExecuteA() +#ifdef _MSC_VER +#pragma comment(lib, "shell32") #endif +static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) +{ + ::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT); +} +#elif !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS)) +static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) +{ +#if __APPLE__ + const char* open_executable = "open"; +#else + const char* open_executable = "xdg-open"; +#endif + ImGuiTextBuffer buf; + buf.appendf("%s \"%s\"", open_executable, path); + system(buf.c_str()); +} +#else +static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) {} +#endif // Default shell handlers + +//----------------------------------------------------------------------------- // Win32 API IME support (for Asian languages, etc.) #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) @@ -14363,7 +14400,7 @@ static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatf static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {} -#endif +#endif // Default IME handlers //----------------------------------------------------------------------------- // [SECTION] METRICS/DEBUGGER WINDOW diff --git a/imgui.h b/imgui.h index 21728df87..20529dd1b 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19091 +#define IMGUI_VERSION_NUM 19092 #define IMGUI_HAS_TABLE /* @@ -2240,6 +2240,11 @@ struct ImGuiIO void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; + // Optional: Open link/folder/file in OS Shell + // (default to use ShellExecuteA() on Windows, system() on Linux/Mac) + void (*PlatformOpenInShellFn)(ImGuiContext* ctx, const char* path); + void* PlatformOpenInShellUserData; + // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) // (default to use native imm32 api on Windows) void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); From fb799bba7fdbfecc84a7038b36bc9cc2792a547a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 15:48:32 +0200 Subject: [PATCH 0060/2359] (Breaking) IO, IME: renamed platform IME hook io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() and added explicit context. --- backends/imgui_impl_osx.mm | 3 ++- backends/imgui_impl_sdl2.cpp | 5 +++-- backends/imgui_impl_sdl3.cpp | 4 ++-- docs/CHANGELOG.txt | 7 +++++++ docs/FAQ.md | 2 +- imgui.cpp | 17 ++++++++++------- imgui.h | 7 ++++--- imgui_internal.h | 2 +- 8 files changed, 30 insertions(+), 17 deletions(-) diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index fdd407f3e..ab0e0ecc6 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen. // 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen. // 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mices). @@ -464,7 +465,7 @@ bool ImGui_ImplOSX_Init(NSView* view) [view addSubview:bd->KeyEventResponder]; ImGui_ImplOSX_AddTrackingArea(view); - io.SetPlatformImeDataFn = [](ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void + io.PlatformSetImeDataFn = [](ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void { ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); if (data->WantVisible) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 6d2a868fa..5a91d5566 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. // 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode(). // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. // 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) @@ -150,7 +151,7 @@ static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text) } // Note: native IME will only display if user calls SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1") _before_ SDL_CreateWindow(). -static void ImGui_ImplSDL2_SetPlatformImeData(ImGuiViewport*, ImGuiPlatformImeData* data) +static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData* data) { if (data->WantVisible) { @@ -430,7 +431,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; io.ClipboardUserData = nullptr; - io.SetPlatformImeDataFn = ImGui_ImplSDL2_SetPlatformImeData; + io.PlatformSetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; // Gamepad handling bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst; diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index c02345c8d..23fd42cc2 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -124,7 +124,7 @@ static void ImGui_ImplSDL3_SetClipboardText(void*, const char* text) SDL_SetClipboardText(text); } -static void ImGui_ImplSDL3_SetPlatformImeData(ImGuiViewport* viewport, ImGuiPlatformImeData* data) +static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); SDL_Window* window = (SDL_Window*)viewport->PlatformHandle; @@ -425,7 +425,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void io.SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; io.ClipboardUserData = nullptr; - io.SetPlatformImeDataFn = ImGui_ImplSDL3_SetPlatformImeData; + io.PlatformSetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; // Gamepad handling bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 87038d978..eb07c1f58 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,12 @@ HOW TO UPDATE? Breaking changes: +- IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness. + - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data); + - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); + It is expected that for a vast majority of users this is automatically set by core + library and/or platform backend so it won't have any effect. + Other changes: - IO: added io.PlatformOpenInShellFn handler to open a link/folder/file in OS shell. (#7660) @@ -51,6 +57,7 @@ Other changes: other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. - Debug Tools: Debug Log: Added "Configure Outputs.." button. (#5855) - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) +- Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. ----------------------------------------------------------------------- diff --git a/docs/FAQ.md b/docs/FAQ.md index 9c7df2334..e120e8cd6 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -639,7 +639,7 @@ The applications in examples/ are doing that. Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode). You may also use `MultiByteToWideChar()` or `ToUnicode()` to retrieve Unicode codepoints from MultiByte characters or keyboard state. Windows: if your language is relying on an Input Method Editor (IME), you can write your HWND to ImGui::GetMainViewport()->PlatformHandleRaw -for the default implementation of io.SetPlatformImeDataFn() to set your Microsoft IME position correctly. +for the default implementation of io.PlatformSetImeDataFn() to set your Microsoft IME position correctly. ##### [Return to Index](#index) diff --git a/imgui.cpp b/imgui.cpp index 0e34267ab..9dc3fe348 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,9 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness. + - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data); + - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow. - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened); - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0); @@ -1124,7 +1127,7 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSetti // Platform Dependents default implementation for IO functions static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx); static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text); -static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data); +static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); namespace ImGui @@ -3716,7 +3719,7 @@ void ImGui::Initialize() g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function) g.IO.PlatformOpenInShellFn = PlatformOpenInShellFn_DefaultImpl; - g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl; + g.IO.PlatformSetImeDataFn = PlatformSetImeDataFn_DefaultImpl; // Create default viewport ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)(); @@ -5138,11 +5141,11 @@ void ImGui::EndFrame() // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) ImGuiPlatformImeData* ime_data = &g.PlatformImeData; - if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) + if (g.IO.PlatformSetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) { - IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y); + IMGUI_DEBUG_LOG_IO("[io] Calling io.PlatformSetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y); ImGuiViewport* viewport = GetMainViewport(); - g.IO.SetPlatformImeDataFn(viewport, ime_data); + g.IO.PlatformSetImeDataFn(&g, viewport, ime_data); } // Hide implicit/fallback "Debug" window if it hasn't been used @@ -14372,7 +14375,7 @@ static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) {} #pragma comment(lib, "imm32") #endif -static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data) +static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) { // Notify OS Input Method Editor of text input position HWND hwnd = (HWND)viewport->PlatformHandleRaw; @@ -14398,7 +14401,7 @@ static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatf #else -static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {} +static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {} #endif // Default IME handlers diff --git a/imgui.h b/imgui.h index 20529dd1b..f1bf2d920 100644 --- a/imgui.h +++ b/imgui.h @@ -176,7 +176,7 @@ struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKe struct ImGuiListClipper; // Helper to manually clip large list of items struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame struct ImGuiPayload; // User data payload for drag and drop operations -struct ImGuiPlatformImeData; // Platform IME data for io.SetPlatformImeDataFn() function. +struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) struct ImGuiStorage; // Helper for key->value storage (container sorted by key) struct ImGuiStoragePair; // Helper for key->value storage (pair) @@ -2247,7 +2247,8 @@ struct ImGuiIO // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) // (default to use native imm32 api on Windows) - void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); + void (*PlatformSetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); + //void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); // [Renamed to io.PlatformSetImeDataFn in 1.91.0] // Optional: Platform locale ImWchar PlatformLocaleDecimalPoint; // '.' // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point @@ -3276,7 +3277,7 @@ struct ImGuiViewport // [SECTION] Platform Dependent Interfaces //----------------------------------------------------------------------------- -// (Optional) Support for IME (Input Method Editor) via the io.SetPlatformImeDataFn() function. +// (Optional) Support for IME (Input Method Editor) via the io.PlatformSetImeDataFn() function. struct ImGuiPlatformImeData { bool WantVisible; // A widget wants the IME to be visible diff --git a/imgui_internal.h b/imgui_internal.h index 60bb28fd5..01efaa84a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2197,7 +2197,7 @@ struct ImGuiContext // Platform support ImGuiPlatformImeData PlatformImeData; // Data updated by current frame - ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data (when changing we will call io.SetPlatformImeDataFn + ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the io.PlatformSetImeDataFn() handler. // Settings bool SettingsLoaded; From ddd4c9d6b95143ae695393ca1943bb1edb8f7286 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 16:01:05 +0200 Subject: [PATCH 0061/2359] Commented out obsolete ImGuiModFlags and ImGuiModFlags_XXX values (renamed to ImGuiKeyChord and ImGuiMod_XXX in 1.89). (#4921, #456) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 +++ imgui.h | 4 ++-- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index eb07c1f58..9de3e8d14 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,9 @@ Breaking changes: - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); It is expected that for a vast majority of users this is automatically set by core library and/or platform backend so it won't have any effect. +- Commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456) +- Commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) + - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. Other changes: diff --git a/imgui.cpp b/imgui.cpp index 9dc3fe348..1ee3be682 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,9 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456) + - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) + - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness. - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data); - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); diff --git a/imgui.h b/imgui.h index f1bf2d920..4f6d406d3 100644 --- a/imgui.h +++ b/imgui.h @@ -3391,8 +3391,8 @@ namespace ImGui // RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) // RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022). Exceptionally commented out ahead of obscolescence schedule to reduce confusion and because they were not meant to be used in the first place. -typedef ImGuiKeyChord ImGuiModFlags; // == int. We generally use ImGuiKeyChord to mean "a ImGuiKey or-ed with any number of ImGuiMod_XXX value", but you may store only mods in there. -enum ImGuiModFlags_ { ImGuiModFlags_None = 0, ImGuiModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiModFlags_Shift = ImGuiMod_Shift, ImGuiModFlags_Alt = ImGuiMod_Alt, ImGuiModFlags_Super = ImGuiMod_Super }; +//typedef ImGuiKeyChord ImGuiModFlags; // == int. We generally use ImGuiKeyChord to mean "a ImGuiKey or-ed with any number of ImGuiMod_XXX value", so you may store mods in there. +//enum ImGuiModFlags_ { ImGuiModFlags_None = 0, ImGuiModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiModFlags_Shift = ImGuiMod_Shift, ImGuiModFlags_Alt = ImGuiMod_Alt, ImGuiModFlags_Super = ImGuiMod_Super }; //typedef ImGuiKeyChord ImGuiKeyModFlags; // == int //enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = 0, ImGuiKeyModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiKeyModFlags_Shift = ImGuiMod_Shift, ImGuiKeyModFlags_Alt = ImGuiMod_Alt, ImGuiKeyModFlags_Super = ImGuiMod_Super }; From 43925b9fa4ca78f5d79e2b50255861191b81ea14 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 16:10:54 +0200 Subject: [PATCH 0062/2359] Build fix for non Windows platforms. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 1ee3be682..55a32910b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14352,7 +14352,7 @@ static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { ::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT); } -#elif !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS)) +#elif !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { #if __APPLE__ From dadf9cd039b03c799fae5dd8fe54eb4d39b26f25 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 16:23:46 +0200 Subject: [PATCH 0063/2359] IO: disable default io.PlatformOpenInShellFn() implementation on iPhone, as compiler errors that system() is not available on iOS. --- imgui.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 55a32910b..260f1608c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14343,6 +14343,10 @@ static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text //----------------------------------------------------------------------------- +#if defined(__APPLE__) && defined(TARGET_OS_IPHONE) && !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) +#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#endif + #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) #include // ShellExecuteA() #ifdef _MSC_VER From 0f63d3e9164de47ec5059b9e647a6581dd3c7524 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 17:21:04 +0200 Subject: [PATCH 0064/2359] Internals: added FontScale storage. --- imgui.cpp | 6 +++++- imgui.h | 2 +- imgui_internal.h | 2 ++ imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 5 files changed, 10 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 260f1608c..d64a00eb2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3505,7 +3505,7 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con const ImFont* font = draw_list->_Data->Font; const float font_size = draw_list->_Data->FontSize; - const float font_scale = font_size / font->FontSize; + const float font_scale = draw_list->_Data->FontScale; const char* text_end_ellipsis = NULL; const float ellipsis_width = font->EllipsisWidth * font_scale; @@ -3903,6 +3903,7 @@ static void SetCurrentWindow(ImGuiWindow* window) if (window) { g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); + g.FontScale = g.FontSize / g.Font->FontSize; ImGui::NavUpdateCurrentWindowIsScrollPushableX(); } } @@ -7507,12 +7508,14 @@ void ImGui::SetCurrentFont(ImFont* font) g.Font = font; g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + g.FontScale = g.FontSize / g.FontSize; ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; g.DrawListSharedData.TexUvLines = atlas->TexUvLines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; + g.DrawListSharedData.FontScale = g.FontScale; } void ImGui::PushFont(ImFont* font) @@ -8057,6 +8060,7 @@ void ImGui::SetWindowFontScale(float scale) ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); + g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize; } void ImGui::PushFocusScope(ImGuiID id) diff --git a/imgui.h b/imgui.h index 4f6d406d3..7903f7c51 100644 --- a/imgui.h +++ b/imgui.h @@ -3203,7 +3203,7 @@ struct ImFont float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 bool DirtyLookupTables; // 1 // out // float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() - float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. diff --git a/imgui_internal.h b/imgui_internal.h index 01efaa84a..ae19cc91f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -775,6 +775,7 @@ struct IMGUI_API ImDrawListSharedData ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas ImFont* Font; // Current/default font (optional, for simplified AddText overload) float FontSize; // Current/default font size (optional, for simplified AddText overload) + float FontScale; // Current/default font scale (== FontSize / Font->FontSize) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() @@ -1927,6 +1928,7 @@ struct ImGuiContext ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. + float FontScale; // == FontSize / Font->FontSize float CurrentDpiScale; // Current window/viewport DpiScale ImDrawListSharedData DrawListSharedData; double Time; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 8b392fc3c..70c74d43e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3269,7 +3269,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label ButtonBehavior(row_r, row_id, NULL, NULL); KeepAliveID(row_id); - const float ascent_scaled = g.Font->Ascent * (g.FontSize / g.Font->FontSize); // FIXME: Standardize those scaling factors better + const float ascent_scaled = g.Font->Ascent * g.FontScale; // FIXME: Standardize those scaling factors better const float line_off_for_ascent_x = (ImMax((g.FontSize - ascent_scaled) * 0.5f, 0.0f) / -sin_a) * (flip_label ? -1.0f : 1.0f); const ImVec2 padding = g.Style.CellPadding; // We will always use swapped component const ImVec2 align = g.Style.TableAngledHeadersTextAlign; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b40dcce11..df4e7fab3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3778,7 +3778,7 @@ namespace ImStb static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->CurLenW; } static ImWchar STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx <= obj->CurLenW); return obj->TextW[idx]; } -static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance(c) * (g.FontSize / g.Font->FontSize); } +static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance(c) * g.FontScale; } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x200000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx) From 5496050f5f2c8917e133dd897498fe468d1e9f6f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 16:58:07 +0200 Subject: [PATCH 0065/2359] Added TextLink(), TextLinkOpenURL() hyperlink widgets. (#7660) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 4 ++- imgui.h | 3 ++ imgui_demo.cpp | 15 +++++++++- imgui_draw.cpp | 3 ++ imgui_internal.h | 1 + imgui_widgets.cpp | 71 ++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 96 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9de3e8d14..47aa5cdd3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,7 @@ Breaking changes: Other changes: +- Added TextLink(), TextLinkOpenURL() hyperlink widgets. (#7660) - IO: added io.PlatformOpenInShellFn handler to open a link/folder/file in OS shell. (#7660) Default to use ShellExecute() under Windows, and system("") under Mac/Linux/etc. Added IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS to disable default implementation. diff --git a/imgui.cpp b/imgui.cpp index d64a00eb2..1457db62a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3360,6 +3360,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_TableBorderLight: return "TableBorderLight"; case ImGuiCol_TableRowBg: return "TableRowBg"; case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt"; + case ImGuiCol_TextLink: return "TextLink"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; case ImGuiCol_NavHighlight: return "NavHighlight"; @@ -3682,7 +3683,7 @@ void ImGui::DestroyContext(ImGuiContext* ctx) IM_DELETE(ctx); } -// IMPORTANT: ###xxx suffixes must be same in ALL languages +// IMPORTANT: ###xxx suffixes must be same in ALL languages to allow for automation. static const ImGuiLocEntry GLocalizationEntriesEnUS[] = { { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" }, @@ -3693,6 +3694,7 @@ static const ImGuiLocEntry GLocalizationEntriesEnUS[] = { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" }, { ImGuiLocKey_WindowingPopup, "(Popup)" }, { ImGuiLocKey_WindowingUntitled, "(Untitled)" }, + { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" }, }; void ImGui::Initialize() diff --git a/imgui.h b/imgui.h index 7903f7c51..a1c8ec2c5 100644 --- a/imgui.h +++ b/imgui.h @@ -543,6 +543,8 @@ namespace ImGui 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 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 void TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked // Widgets: Images // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples @@ -1613,6 +1615,7 @@ enum ImGuiCol_ ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here) ImGuiCol_TableRowBg, // Table row background (even rows) ImGuiCol_TableRowBgAlt, // Table row background (odd rows) + ImGuiCol_TextLink, // Hyperlink color ImGuiCol_TextSelectedBg, ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2f8aacf06..6cdd679fc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -439,7 +439,9 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::BulletText("See the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!"); ImGui::BulletText("See comments in imgui.cpp."); ImGui::BulletText("See example applications in the examples/ folder."); - ImGui::BulletText("Read the FAQ at https://www.dearimgui.com/faq/"); + ImGui::BulletText("Read the FAQ at "); + ImGui::SameLine(0, 0); + ImGui::TextLinkOpenURL("https://www.dearimgui.com/faq/"); ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls."); ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls."); @@ -6513,6 +6515,17 @@ void ImGui::ShowAboutWindow(bool* p_open) } IMGUI_DEMO_MARKER("Tools/About Dear ImGui"); ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); + + ImGui::TextLinkOpenURL("Homepage", "https://github.com/ocornut/imgui"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("FAQ", "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Wiki", "https://github.com/ocornut/imgui/wiki"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Releases", "https://github.com/ocornut/imgui/releases"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Funding", "https://github.com/ocornut/imgui/wiki/Funding"); + ImGui::Separator(); ImGui::Text("By Omar Cornut and all Dear ImGui contributors."); ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information."); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7ef0f2c6a..69e4f854c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -227,6 +227,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); // Prefer using Alpha=1.0 here colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); + colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); @@ -289,6 +290,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_TableBorderLight] = ImVec4(0.26f, 0.26f, 0.28f, 1.00f); // Prefer using Alpha=1.0 here colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); + colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; @@ -352,6 +354,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_TableBorderLight] = ImVec4(0.68f, 0.68f, 0.74f, 1.00f); // Prefer using Alpha=1.0 here colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.09f); + colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; diff --git a/imgui_internal.h b/imgui_internal.h index ae19cc91f..fa489492c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1807,6 +1807,7 @@ enum ImGuiLocKey : int ImGuiLocKey_WindowingMainMenuBar, ImGuiLocKey_WindowingPopup, ImGuiLocKey_WindowingUntitled, + ImGuiLocKey_CopyLink, ImGuiLocKey_COUNT }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index df4e7fab3..ae085a682 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -422,6 +422,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // - RadioButton() // - ProgressBar() // - Bullet() +// - Hyperlink() //------------------------------------------------------------------------- // The ButtonBehavior() function is key to many interactions and used by many/most widgets. @@ -1370,6 +1371,76 @@ void ImGui::Bullet() SameLine(0, style.FramePadding.x * 2.0f); } +// This is provided as a convenience for being an often requested feature. +// 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) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(label); + const char* label_end = FindRenderedTextEnd(label); + + ImVec2 pos = window->DC.CursorPos; + ImVec2 size = CalcTextSize(label, label_end, true); + ImRect bb(pos, pos + size); + ItemSize(size, 0.0f); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_None); + + ImVec4 text_colf = g.Style.Colors[ImGuiCol_TextLink]; + ImVec4 line_colf = text_colf; + { + // FIXME-STYLE: Read comments above. This widget is NOT written in the same style as some earlier widgets, + // as we are currently experimenting/planning a different styling system. + float h, s, v; + ColorConvertRGBtoHSV(text_colf.x, text_colf.y, text_colf.z, h, s, v); + if (held || hovered) + { + v = ImSaturate(v + (held ? 0.4f : 0.3f)); + h = ImFmod(h + 0.02f, 1.0f); + } + ColorConvertHSVtoRGB(h, s, v, text_colf.x, text_colf.y, text_colf.z); + v = ImSaturate(v - 0.20f); + ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z); + } + + float line_y = bb.Max.y + ImFloor(g.Font->Descent * g.FontScale * 0.20f); + window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode. + + PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); + RenderText(bb.Min, label, label_end); + PopStyleColor(); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; +} + +void ImGui::TextLinkOpenURL(const char* label, const char* url) +{ + ImGuiContext& g = *GImGui; + if (url == NULL) + url = label; + if (TextLink(label)) + if (g.IO.PlatformOpenInShellFn != NULL) + g.IO.PlatformOpenInShellFn(&g, url); + SetItemTooltip("%s", url); // It is more reassuring for user to _always_ display URL when we same as label + if (BeginPopupContextItem()) + { + if (MenuItem(LocalizeGetMsg(ImGuiLocKey_CopyLink))) + SetClipboardText(url); + EndPopup(); + } +} + //------------------------------------------------------------------------- // [SECTION] Widgets: Low-level Layout helpers //------------------------------------------------------------------------- From 05a4f280596ac6980c505c633193d62ca4c10cd5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 17:45:12 +0200 Subject: [PATCH 0066/2359] Internals: added FontScale storage (amend 0f63d3e). --- imgui.cpp | 2 +- imgui_internal.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1457db62a..748cbe426 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7510,7 +7510,7 @@ void ImGui::SetCurrentFont(ImFont* font) g.Font = font; g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; - g.FontScale = g.FontSize / g.FontSize; + g.FontScale = g.FontSize / g.Font->FontSize; ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; diff --git a/imgui_internal.h b/imgui_internal.h index fa489492c..6f58328b3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2267,7 +2267,7 @@ struct ImGuiContext Initialized = false; FontAtlasOwnedByContext = shared_font_atlas ? false : true; Font = NULL; - FontSize = FontBaseSize = CurrentDpiScale = 0.0f; + FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); Time = 0.0f; FrameCount = 0; From 380b3559c6d7b292faf0c78fd6878438d829af2f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 18:06:19 +0200 Subject: [PATCH 0067/2359] Backends: GLFW,SDL2: Added ioPlatformOpenInShellFn handler for web/Emscripten versions. (#7660) --- backends/imgui_impl_glfw.cpp | 8 ++++++++ backends/imgui_impl_sdl2.cpp | 13 ++++++++++++- docs/CHANGELOG.txt | 1 + 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 3c95f1786..cb46abbb3 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. // 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys. // 2023-07-18: Inputs: Revert ignoring mouse data on GLFW_CURSOR_DISABLED as it can be used differently. User may set ImGuiConfigFLags_NoMouse if desired. (#5625, #6609) @@ -553,6 +554,10 @@ void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows) bd->CallbacksChainForAllWindows = chain_for_all_windows; } +#ifdef __EMSCRIPTEN__ +EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); +#endif + static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api) { ImGuiIO& io = ImGui::GetIO(); @@ -573,6 +578,9 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText; io.ClipboardUserData = bd->Window; +#ifdef __EMSCRIPTEN__ + io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); }; +#endif // Create mouse cursors // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist, diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 5a91d5566..1cde227e2 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. // 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode(). // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. @@ -91,9 +92,12 @@ // SDL #include #include -#if defined(__APPLE__) +#ifdef __APPLE__ #include #endif +#ifdef __EMSCRIPTEN__ +#include +#endif #if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 @@ -400,6 +404,10 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) return false; } +#ifdef __EMSCRIPTEN__ +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) { ImGuiIO& io = ImGui::GetIO(); @@ -432,6 +440,9 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; io.ClipboardUserData = nullptr; io.PlatformSetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; +#ifdef __EMSCRIPTEN__ + io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); }; +#endif // Gamepad handling bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 47aa5cdd3..cec7d490d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,7 @@ Other changes: - Debug Tools: Debug Log: Added "Configure Outputs.." button. (#5855) - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. +- Backends: GLFW,SDL2: Added ioPlatformOpenInShellFn handler for web/Emscripten versions. (#7660) ----------------------------------------------------------------------- From 0ebf49b4c1fa9256a2ea002245a1186075fe7567 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jul 2024 19:03:40 +0200 Subject: [PATCH 0068/2359] IO: amend PlatformOpenInShellFn specs to return a bool. (#7660) Amend 8f36798 --- backends/imgui_impl_glfw.cpp | 2 +- backends/imgui_impl_sdl2.cpp | 2 +- imgui.cpp | 12 ++++++------ imgui.h | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index cb46abbb3..53139f227 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -579,7 +579,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText; io.ClipboardUserData = bd->Window; #ifdef __EMSCRIPTEN__ - io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); }; + io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; }; #endif // Create mouse cursors diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 1cde227e2..15db0a843 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -441,7 +441,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void io.ClipboardUserData = nullptr; io.PlatformSetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; #ifdef __EMSCRIPTEN__ - io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); }; + io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; #endif // Gamepad handling diff --git a/imgui.cpp b/imgui.cpp index 748cbe426..e0294b3e4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1131,7 +1131,7 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSetti static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx); static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text); static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); -static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); +static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); namespace ImGui { @@ -14358,12 +14358,12 @@ static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text #ifdef _MSC_VER #pragma comment(lib, "shell32") #endif -static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) +static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { - ::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT); + return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32; } #elif !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) -static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) +static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { #if __APPLE__ const char* open_executable = "open"; @@ -14372,10 +14372,10 @@ static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) #endif ImGuiTextBuffer buf; buf.appendf("%s \"%s\"", open_executable, path); - system(buf.c_str()); + return system(buf.c_str()) != -1; } #else -static void PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) {} +static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; } #endif // Default shell handlers //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index a1c8ec2c5..b1796242b 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19092 +#define IMGUI_VERSION_NUM 19093 #define IMGUI_HAS_TABLE /* @@ -2245,7 +2245,7 @@ struct ImGuiIO // Optional: Open link/folder/file in OS Shell // (default to use ShellExecuteA() on Windows, system() on Linux/Mac) - void (*PlatformOpenInShellFn)(ImGuiContext* ctx, const char* path); + bool (*PlatformOpenInShellFn)(ImGuiContext* ctx, const char* path); void* PlatformOpenInShellUserData; // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) From 0a73c6ec3f68d6adc2ef17d6dfd75087fe341e70 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Jul 2024 17:26:25 +0200 Subject: [PATCH 0069/2359] Misc tweaks, comments. --- docs/CHANGELOG.txt | 3 ++- imgui.cpp | 4 ++++ imgui_demo.cpp | 2 +- imgui_internal.h | 4 ++-- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cec7d490d..fe003a23d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,7 +62,8 @@ Other changes: - Debug Tools: Debug Log: Added "Configure Outputs.." button. (#5855) - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. -- Backends: GLFW,SDL2: Added ioPlatformOpenInShellFn handler for web/Emscripten versions. (#7660) +- Backends: GLFW,SDL2: Added io.PlatformOpenInShellFn handler for web/Emscripten versions. (#7660) + [@ypujante, @ocornut] ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index e0294b3e4..8efc0dc4e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2054,6 +2054,10 @@ void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, va_end(args); } +// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller) +// 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) { ImGuiContext& g = *GImGui; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6cdd679fc..513025f7b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7755,7 +7755,7 @@ static void ShowPlaceholderObject(const char* prefix, int uid) ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::AlignTextToFramePadding(); - bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + bool node_open = ImGui::TreeNode("##Object", "%s_%u", prefix, uid); ImGui::TableSetColumnIndex(1); ImGui::Text("my sailor is rich"); diff --git a/imgui_internal.h b/imgui_internal.h index 6f58328b3..bcf586348 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -965,8 +965,8 @@ enum ImGuiSelectableFlagsPrivate_ // Extend ImGuiTreeNodeFlags_ enum ImGuiTreeNodeFlagsPrivate_ { - ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 20, - ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 21,// (FIXME-WIP) Turn Down arrow into an Up arrow, but reversed trees (#6517) + ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader() + ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, but reversed trees (#6517) }; enum ImGuiSeparatorFlags_ From 2d0baaabe62a4bd71bfc871933d9002425c45435 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Jul 2024 18:25:01 +0200 Subject: [PATCH 0070/2359] TreeNode: rename/rework ImGuiNavTreeNodeData system to be usable by more features. (#2920, #1131, #7553) Reworked to it is easier during TreeNode code to request extra data to be stored. --- imgui.cpp | 6 ++--- imgui_demo.cpp | 5 ++++- imgui_internal.h | 22 ++++++++++--------- imgui_widgets.cpp | 56 ++++++++++++++++++++++++++++++++--------------- 4 files changed, 57 insertions(+), 32 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8efc0dc4e..cdb7d2a1e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3795,7 +3795,7 @@ void ImGui::Shutdown() g.FontStack.clear(); g.OpenPopupStack.clear(); g.BeginPopupStack.clear(); - g.NavTreeNodeStack.clear(); + g.TreeNodeStack.clear(); g.Viewports.clear_delete(); @@ -7131,7 +7131,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.MenuBarAppending = false; window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user); window->DC.TreeDepth = 0; - window->DC.TreeJumpToParentOnPopMask = 0x00; + window->DC.TreeHasStackDataDepthMask = 0x00; window->DC.ChildWindows.resize(0); window->DC.StateStorage = &window->StateStorage; window->DC.CurrentColumns = NULL; @@ -12039,7 +12039,7 @@ void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result) } // Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere -void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data) +void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data) { ImGuiContext& g = *GImGui; g.NavMoveScoringItems = false; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 513025f7b..e6971299a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -953,6 +953,7 @@ static void ShowDemoWindowWidgets() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsBackHere", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsBackHere); ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); ImGui::Text("Hello!"); @@ -985,7 +986,7 @@ static void ShowDemoWindowWidgets() ImGui::Text("This is a drag and drop source"); ImGui::EndDragDropSource(); } - if (i == 2) + if (i == 2 && (base_flags & ImGuiTreeNodeFlags_SpanTextWidth)) { // Item 2 has an additional inline button to help demonstrate SpanTextWidth. ImGui::SameLine(); @@ -994,6 +995,8 @@ static void ShowDemoWindowWidgets() if (node_open) { ImGui::BulletText("Blah blah\nBlah Blah"); + ImGui::SameLine(); + ImGui::SmallButton("Button"); ImGui::TreePop(); } } diff --git a/imgui_internal.h b/imgui_internal.h index bcf586348..5a0fc7c4b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -135,7 +135,6 @@ struct ImGuiLastItemData; // Status storage for last submitted items struct ImGuiLocEntry; // A localization entry. struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only struct ImGuiNavItemData; // Result of a gamepad/keyboard directional navigation move query result -struct ImGuiNavTreeNodeData; // Temporary storage for last TreeNode() being a Left arrow landing candidate. struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions struct ImGuiNextWindowData; // Storage for SetNextWindow** functions struct ImGuiNextItemData; // Storage for SetNextItem** functions @@ -154,6 +153,7 @@ struct ImGuiTableInstanceData; // Storage for one instance of a same table struct ImGuiTableTempData; // Temporary storage for one table (one per table in the stack), shared between tables. struct ImGuiTableSettings; // Storage for a table .ini settings struct ImGuiTableColumnsSettings; // Storage for a column .ini settings +struct ImGuiTreeNodeStackData; // Temporary storage for TreeNode(). struct ImGuiTypingSelectState; // Storage for GetTypingSelectRequest() struct ImGuiTypingSelectRequest; // Storage for GetTypingSelectRequest() (aimed to be public) struct ImGuiWindow; // Storage for one window @@ -1251,14 +1251,16 @@ struct ImGuiLastItemData ImGuiLastItemData() { memset(this, 0, sizeof(*this)); } }; -// Store data emitted by TreeNode() for usage by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere. -// This is the minimum amount of data that we need to perform the equivalent of NavApplyItemToResult() and which we can't infer in TreePop() -// Only stored when the node is a potential candidate for landing on a Left arrow jump. -struct ImGuiNavTreeNodeData +// Store data emitted by TreeNode() for usage by TreePop() +// - To implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere: store the minimum amount of data +// which we can't infer in TreePop(), to perform the equivalent of NavApplyItemToResult(). +// Only stored when the node is a potential candidate for landing on a Left arrow jump. +struct ImGuiTreeNodeStackData { ImGuiID ID; - ImGuiItemFlags InFlags; - ImRect NavRect; + ImGuiTreeNodeFlags TreeFlags; + ImGuiItemFlags InFlags; // Used for nav landing + ImRect NavRect; // Used for nav landing }; struct IMGUI_API ImGuiStackSizes @@ -2038,7 +2040,7 @@ struct ImGuiContext ImVector GroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin() ImVector OpenPopupStack; // Which popups are open (persistent) ImVector BeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) - ImVector NavTreeNodeStack; // Stack for TreeNode() when a NavLeft requested is emitted. + ImVectorTreeNodeStack; // Stack for TreeNode() // Viewports ImVector Viewports; // Active viewports (Size==1 in 'master' branch). Each viewports hold their copy of ImDrawData. @@ -2503,7 +2505,7 @@ struct IMGUI_API ImGuiWindowTempData ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs. ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement int TreeDepth; // Current tree depth. - ImU32 TreeJumpToParentOnPopMask; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary. + ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. ImVector ChildWindows; ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) ImGuiOldColumns* CurrentColumns; // Current columns set @@ -3201,7 +3203,7 @@ namespace ImGui IMGUI_API void NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); IMGUI_API void NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result); - IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data); + IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data); IMGUI_API void NavMoveRequestCancel(); IMGUI_API void NavMoveRequestApplyResult(); IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ae085a682..05e470195 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6310,6 +6310,21 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID id, ImGuiTreeNodeFlags flags) return is_open; } +// Store ImGuiTreeNodeStackData for just submitted node. +static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + g.TreeNodeStack.resize(g.TreeNodeStack.Size + 1); + ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.back(); + tree_node_data->ID = g.LastItemData.ID; + tree_node_data->TreeFlags = flags; + tree_node_data->InFlags = g.LastItemData.InFlags; + tree_node_data->NavRect = g.LastItemData.NavRect; + window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); +} + bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) { ImGuiWindow* window = GetCurrentWindow(); @@ -6379,20 +6394,19 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default or move it to ImGuiStyle. // Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase. - if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) - if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) - { - g.NavTreeNodeStack.resize(g.NavTreeNodeStack.Size + 1); - ImGuiNavTreeNodeData* nav_tree_node_data = &g.NavTreeNodeStack.back(); - nav_tree_node_data->ID = id; - nav_tree_node_data->InFlags = g.LastItemData.InFlags; - nav_tree_node_data->NavRect = g.LastItemData.NavRect; - window->DC.TreeJumpToParentOnPopMask |= (1 << window->DC.TreeDepth); - } + bool store_tree_node_stack_data = false; + if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + { + if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && is_open && !g.NavIdIsAlive) + if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) + store_tree_node_stack_data = true; + } const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; if (!item_add) { + if (store_tree_node_stack_data && is_open) + TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushOverrideID(id); IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); @@ -6533,8 +6547,11 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l else RenderText(text_pos, label, label_end, false); + if (store_tree_node_stack_data && is_open) + TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushOverrideID(id); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open; } @@ -6573,16 +6590,19 @@ void ImGui::TreePop() window->DC.TreeDepth--; ImU32 tree_depth_mask = (1 << window->DC.TreeDepth); - // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled) - if (window->DC.TreeJumpToParentOnPopMask & tree_depth_mask) // Only set during request + if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) // Only set during request { - ImGuiNavTreeNodeData* nav_tree_node_data = &g.NavTreeNodeStack.back(); - IM_ASSERT(nav_tree_node_data->ID == window->IDStack.back()); - if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) - NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, nav_tree_node_data); - g.NavTreeNodeStack.pop_back(); + ImGuiTreeNodeStackData* data = &g.TreeNodeStack.back(); + IM_ASSERT(data->ID == window->IDStack.back()); + if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) + { + // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled) + if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) + NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data); + } + g.TreeNodeStack.pop_back(); + window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask; } - window->DC.TreeJumpToParentOnPopMask &= tree_depth_mask - 1; IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much. PopID(); From 1ec1f7a3de2ce96bee58b2825917707cc1b7c17c Mon Sep 17 00:00:00 2001 From: cfillion Date: Sat, 6 Jul 2024 04:12:46 -0400 Subject: [PATCH 0071/2359] Fixed Unix version of PlatformOpenInShellFn_DefaultImpl. (#7772, #7660) + Enable on non-iPhone macOS builds --- imgui.cpp | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cdb7d2a1e..2091267b6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14353,11 +14353,18 @@ static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text //----------------------------------------------------------------------------- -#if defined(__APPLE__) && defined(TARGET_OS_IPHONE) && !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) +#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#if defined(__APPLE__) && TARGET_OS_IPHONE #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS #endif -#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) +#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS) +#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#endif +#endif + +#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#ifdef _WIN32 #include // ShellExecuteA() #ifdef _MSC_VER #pragma comment(lib, "shell32") @@ -14366,18 +14373,32 @@ static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32; } -#elif !defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) +#else +#include +#include static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { #if __APPLE__ - const char* open_executable = "open"; + const char* args[] { "open", "--", path, NULL }; #else - const char* open_executable = "xdg-open"; + const char* args[] { "xdg-open", path, NULL }; #endif - ImGuiTextBuffer buf; - buf.appendf("%s \"%s\"", open_executable, path); - return system(buf.c_str()) != -1; + pid_t pid = fork(); + if (pid < 0) + return false; + if (!pid) + { + execvp(args[0], const_cast(args)); + exit(-1); + } + else + { + int status; + waitpid(pid, &status, 0); + return WEXITSTATUS(status) == 0; + } } +#endif #else static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; } #endif // Default shell handlers From 6b6026b133208725d1eb396aea0825450cefde44 Mon Sep 17 00:00:00 2001 From: Hugues Evrard Date: Mon, 8 Jul 2024 11:43:09 +0200 Subject: [PATCH 0072/2359] DemosFix typo in help text in demo Tables/Borders (#7780) The help text for flags had a "V" flag duplicated, this change corrects it to the missing "H" flag. --- imgui_demo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e6971299a..9da3cd965 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4221,7 +4221,7 @@ static void ShowDemoWindowTables() PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg); ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders); - ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterH"); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerH\n | ImGuiTableFlags_BordersOuterH"); ImGui::Indent(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH); From 9504068f66c00b9a16553f7da7dc6493906c88eb Mon Sep 17 00:00:00 2001 From: Aemony <10578344+Aemony@users.noreply.github.com> Date: Thu, 4 Jul 2024 22:15:09 +0200 Subject: [PATCH 0073/2359] Backends: Win32: fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN (#7768, #4858, #2622) Amend 075576744 The `ImGui_ImplWin32_UpdateKeyModifiers()` function maps `ImGuiMod_Super` to `VK_APPS`, the "Application" key located between the Right Windows (Super) and Right Control keys on the keyboard, see https://conemu.github.io/en/AppsKey.html This means that when using `ImGui::GetIO().KeySuper` to try to get the down state of the `VK_RWIN` or `VK_LWIN` keys, it'll always return FALSE when either of those keys are held down, and only return TRUE when `VK_APPS` is held down. --- backends/imgui_impl_win32.cpp | 3 ++- docs/CHANGELOG.txt | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 9241f8edb..0e48d8636 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. // 2023-09-25: Inputs: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it (same behavior as GLFW/SDL). // 2023-09-07: Inputs: Added support for keyboard codepage conversion for when application is compiled in MBCS mode and using a non-Unicode window. @@ -294,7 +295,7 @@ static void ImGui_ImplWin32_UpdateKeyModifiers() io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL)); io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT)); io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU)); - io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_APPS)); + io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_LWIN) || IsVkDown(VK_RWIN)); } static void ImGui_ImplWin32_UpdateMouseData() diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fe003a23d..f04a08803 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,8 @@ Other changes: Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. - Debug Tools: Debug Log: Added "Configure Outputs.." button. (#5855) +- Backends: Win32: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. + (#7768, #4858, #2622) [@Aemony] - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. - Backends: GLFW,SDL2: Added io.PlatformOpenInShellFn handler for web/Emscripten versions. (#7660) From 6816789a6b03cf27610f05a9d0fa32b3fe9f5e0a Mon Sep 17 00:00:00 2001 From: Yan Pujante Date: Mon, 8 Jul 2024 15:53:23 +0200 Subject: [PATCH 0074/2359] Backends: GLFW+Emscripten: (Breaking) Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWwindow* parameter. (#7647, #7600) + Fixed Emscripten warning when using mouse wheel on some setups. --- backends/imgui_impl_glfw.cpp | 17 +++++++++-------- backends/imgui_impl_glfw.h | 5 +++-- docs/CHANGELOG.txt | 4 ++++ examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_glfw_wgpu/main.cpp | 2 +- 5 files changed, 18 insertions(+), 12 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 53139f227..3743a5c8b 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-08: *BREAKING* Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWWindow* parameter. // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. // 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys. @@ -611,12 +612,6 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any. if (install_callbacks) ImGui_ImplGlfw_InstallCallbacks(window); - // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096) - // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves. - // FIXME: May break chaining in case user registered their own Emscripten callback? -#ifdef __EMSCRIPTEN__ - emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, nullptr, false, ImGui_ImplEmscripten_WheelCallback); -#endif // Set platform dependent data in viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); @@ -664,7 +659,8 @@ void ImGui_ImplGlfw_Shutdown() if (bd->InstalledCallbacks) ImGui_ImplGlfw_RestoreCallbacks(bd->Window); #ifdef __EMSCRIPTEN__ - emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, nullptr, false, nullptr); + if (bd->CanvasSelector) + emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, nullptr); #endif for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) @@ -844,7 +840,7 @@ static EM_BOOL ImGui_ImplEmscripten_FullscreenChangeCallback(int event_type, con // 'canvas_selector' is a CSS selector. The event listener is applied to the first element that matches the query. // STRING MUST PERSIST FOR THE APPLICATION DURATION. PLEASE USE A STRING LITERAL OR ENSURE POINTER WILL STAY VALID. -void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector) +void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow*, const char* canvas_selector) { IM_ASSERT(canvas_selector != nullptr); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); @@ -856,6 +852,11 @@ void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_sel // Change the size of the GLFW window according to the size of the canvas ImGui_ImplGlfw_OnCanvasSizeChange(EMSCRIPTEN_EVENT_RESIZE, {}, bd); + + // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096) + // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves. + // FIXME: May break chaining in case user registered their own Emscripten callback? + emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, ImGui_ImplEmscripten_WheelCallback); } #endif diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index 6a9acd05b..a30ed64ca 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -30,9 +30,10 @@ IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool ins IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown(); IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame(); -// Emscripten related initialization phase methods +// Emscripten related initialization phase methods (call after ImGui_ImplGlfw_InitForOpenGL) #ifdef __EMSCRIPTEN__ -IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector); +IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector); +//static inline void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector) { ImGui_ImplGlfw_InstallEmscriptenCallbacks(nullptr, canvas_selector); } } // Renamed in 1.91.0 #endif // GLFW callbacks install diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f04a08803..cb37ea624 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Breaking changes: - Commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456) - Commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. +- Backends: GLFW+Emscripten: Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to + ImGui_ImplGlfw_InstallEmscriptenCallbacks(), with additional GLFWWindow* parameter. (#7647) [@ypujante] Other changes: @@ -66,6 +68,8 @@ Other changes: - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. - Backends: GLFW,SDL2: Added io.PlatformOpenInShellFn handler for web/Emscripten versions. (#7660) [@ypujante, @ocornut] +- Backends: GLFW+Emscripten: Fixed Emscripten warning when using mouse wheel on some setups + "Unable to preventDefault inside passive event listener". (#7647, #7600) [@ypujante] ----------------------------------------------------------------------- diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 4438fa5bb..22ef79eb7 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -85,7 +85,7 @@ int main(int, char**) // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); #ifdef __EMSCRIPTEN__ - ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas"); + ImGui_ImplGlfw_InstallEmscriptenCallbacks(window, "#canvas"); #endif ImGui_ImplOpenGL3_Init(glsl_version); diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 4e47b8323..c5872bd85 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -101,7 +101,7 @@ int main(int, char**) // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOther(window, true); #ifdef __EMSCRIPTEN__ - ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas"); + ImGui_ImplGlfw_InstallEmscriptenCallbacks(window, "#canvas"); #endif ImGui_ImplWGPU_InitInfo init_info; init_info.Device = wgpu_device; From 2937339c1757e64df2723a4a9a4938f964c22531 Mon Sep 17 00:00:00 2001 From: Yan Pujante Date: Mon, 8 Jul 2024 22:04:27 +0200 Subject: [PATCH 0075/2359] Backends: GLFW+Emscripten: Added support for GLFW3 contrib port. (#7647) --- backends/imgui_impl_glfw.cpp | 37 +++++++++++++++++------ examples/example_glfw_wgpu/CMakeLists.txt | 15 ++++++++- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 3743a5c8b..a994bc40b 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-07-08: *BREAKING* Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWWindow* parameter. +// 2024-07-08: Emscripten: Added support for GLFW3 contrib port (GLFW 3.4.0 features + bug fixes): to enable, replace -sUSE_GLFW=3 with --use-port=contrib.glfw3 (requires emscripten 3.1.59+) (https://github.com/pongasoft/emscripten-glfw) // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. // 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys. @@ -102,6 +103,11 @@ #ifdef __EMSCRIPTEN__ #include #include +#ifdef EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 +#include +#else +#define EMSCRIPTEN_USE_EMBEDDED_GLFW3 +#endif #endif // We gather version tests as define in order to easily see which features are version-dependent. @@ -133,7 +139,7 @@ struct ImGui_ImplGlfw_Data ImVec2 LastValidMousePos; bool InstalledCallbacks; bool CallbacksChainForAllWindows; -#ifdef __EMSCRIPTEN__ +#if EMSCRIPTEN_USE_EMBEDDED_GLFW3 const char* CanvasSelector; #endif @@ -337,7 +343,7 @@ void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yo if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackScroll(window, xoffset, yoffset); -#ifdef __EMSCRIPTEN__ +#ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 // Ignore GLFW events: will be processed in ImGui_ImplEmscripten_WheelCallback(). return; #endif @@ -348,7 +354,7 @@ void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yo static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode) { -#if GLFW_HAS_GETKEYNAME && !defined(__EMSCRIPTEN__) +#if GLFW_HAS_GETKEYNAME && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3) // GLFW 3.1+ attempts to "untranslate" keys, which goes the opposite of what every other framework does, making using lettered shortcuts difficult. // (It had reasons to do so: namely GLFW is/was more likely to be used for WASD-type game controls rather than lettered shortcuts, but IHMO the 3.1 change could have been done differently) // See https://github.com/glfw/glfw/issues/1502 for details. @@ -359,7 +365,7 @@ static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode) GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr); const char* key_name = glfwGetKeyName(key, scancode); glfwSetErrorCallback(prev_error_callback); -#if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908) +#if GLFW_HAS_GETERROR && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3) // Eat errors (see #5908) (void)glfwGetError(nullptr); #endif if (key_name && key_name[0] != 0 && key_name[1] == 0) @@ -456,7 +462,7 @@ void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int) // Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too. } -#ifdef __EMSCRIPTEN__ +#ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void*) { // Mimic Emscripten_HandleWheel() in SDL. @@ -658,7 +664,7 @@ void ImGui_ImplGlfw_Shutdown() if (bd->InstalledCallbacks) ImGui_ImplGlfw_RestoreCallbacks(bd->Window); -#ifdef __EMSCRIPTEN__ +#ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 if (bd->CanvasSelector) emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, nullptr); #endif @@ -687,7 +693,7 @@ static void ImGui_ImplGlfw_UpdateMouseData() // (those braces are here to reduce diff with multi-viewports support in 'docking' branch) { GLFWwindow* window = bd->Window; -#ifdef __EMSCRIPTEN__ +#ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 const bool is_window_focused = true; #else const bool is_window_focused = glfwGetWindowAttrib(window, GLFW_FOCUSED) != 0; @@ -745,7 +751,7 @@ static void ImGui_ImplGlfw_UpdateGamepads() return; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; -#if GLFW_HAS_GAMEPAD_API && !defined(__EMSCRIPTEN__) +#if GLFW_HAS_GAMEPAD_API && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3) GLFWgamepadstate gamepad; if (!glfwGetGamepadState(GLFW_JOYSTICK_1, &gamepad)) return; @@ -819,7 +825,7 @@ void ImGui_ImplGlfw_NewFrame() ImGui_ImplGlfw_UpdateGamepads(); } -#ifdef __EMSCRIPTEN__ +#ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 static EM_BOOL ImGui_ImplGlfw_OnCanvasSizeChange(int event_type, const EmscriptenUiEvent* event, void* user_data) { ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data; @@ -858,7 +864,18 @@ void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow*, const char* canvas_s // FIXME: May break chaining in case user registered their own Emscripten callback? emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, ImGui_ImplEmscripten_WheelCallback); } -#endif +#elif defined(EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3) +// When using --use-port=contrib.glfw3 for the GLFW implementation, you can override the behavior of this call +// by invoking emscripten_glfw_make_canvas_resizable afterward. +// See https://github.com/pongasoft/emscripten-glfw/blob/master/docs/Usage.md#how-to-make-the-canvas-resizable-by-the-user for an explanation +void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector) +{ + GLFWwindow* w = (GLFWwindow*)(EM_ASM_INT({ return Module.glfwGetWindow(UTF8ToString($0)); }, canvas_selector)); + IM_ASSERT(window == w); // Sanity check + IM_UNUSED(w); + emscripten_glfw_make_canvas_resizable(window, "window", nullptr); +} +#endif // #ifdef EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 //----------------------------------------------------------------------------- diff --git a/examples/example_glfw_wgpu/CMakeLists.txt b/examples/example_glfw_wgpu/CMakeLists.txt index e682836dd..77b492fdc 100644 --- a/examples/example_glfw_wgpu/CMakeLists.txt +++ b/examples/example_glfw_wgpu/CMakeLists.txt @@ -27,6 +27,12 @@ set(IMGUI_DIR ../../) # Libraries if(EMSCRIPTEN) + if(EMSCRIPTEN_VERSION VERSION_GREATER_EQUAL "3.1.57") + set(IMGUI_EMSCRIPTEN_GLFW3 "--use-port=contrib.glfw3" CACHE STRING "Choose between --use-port=contrib.glfw3 and -sUSE_GLFW=3 for GLFW implementation (default to --use-port=contrib.glfw3)") + else() + # cannot use contrib.glfw3 prior to 3.1.57 + set(IMGUI_EMSCRIPTEN_GLFW3 "-sUSE_GLFW=3" CACHE STRING "Use -sUSE_GLFW=3 for GLFW implementation" FORCE) + endif() set(LIBRARIES glfw) add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1) else() @@ -82,9 +88,16 @@ target_link_libraries(example_glfw_wgpu PUBLIC ${LIBRARIES}) # Emscripten settings if(EMSCRIPTEN) + if("${IMGUI_EMSCRIPTEN_GLFW3}" STREQUAL "--use-port=contrib.glfw3") + target_compile_options(example_glfw_wgpu PUBLIC + "${IMGUI_EMSCRIPTEN_GLFW3}" + "-DEMSCRIPTEN_USE_PORT_CONTRIB_GLFW3" # unnecessary beyond emscripten 3.1.59 + ) + endif() + message(STATUS "Using ${IMGUI_EMSCRIPTEN_GLFW3} GLFW implementation") target_link_options(example_glfw_wgpu PRIVATE "-sUSE_WEBGPU=1" - "-sUSE_GLFW=3" + "${IMGUI_EMSCRIPTEN_GLFW3}" "-sWASM=1" "-sALLOW_MEMORY_GROWTH=1" "-sNO_EXIT_RUNTIME=0" From a8e96ae21a4ec10e5f02b19dd865dfffe8a98e67 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jul 2024 22:23:26 +0200 Subject: [PATCH 0076/2359] Backends: GLFW+Emscripten: Fixed build (#7647) --- backends/imgui_impl_glfw.cpp | 2 +- docs/CHANGELOG.txt | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index a994bc40b..305891624 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -139,7 +139,7 @@ struct ImGui_ImplGlfw_Data ImVec2 LastValidMousePos; bool InstalledCallbacks; bool CallbacksChainForAllWindows; -#if EMSCRIPTEN_USE_EMBEDDED_GLFW3 +#ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 const char* CanvasSelector; #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cb37ea624..8e7f3a00d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,10 @@ Other changes: - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. - Backends: GLFW,SDL2: Added io.PlatformOpenInShellFn handler for web/Emscripten versions. (#7660) [@ypujante, @ocornut] +- Backends; GLFW+Emscripten: Added support for GLFW3 contrib port which fixes many of the things + not supported by the embedded GLFW: gamepad support, mouse cursor shapes, copy to clipboard, + workaround for Super/Meta key, different ways of resizing, multi-window (glfw/canvas) support. + (#7647) [@ypujante] - Backends: GLFW+Emscripten: Fixed Emscripten warning when using mouse wheel on some setups "Unable to preventDefault inside passive event listener". (#7647, #7600) [@ypujante] From c3c90b49e0342c5c9772f4fa26de39dd44ea831a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Jul 2024 18:13:42 +0200 Subject: [PATCH 0077/2359] Examples: SDL3+OpenGL: Update for API changes: SDL_GL_DeleteContext() renamed to SDL_GL_DestroyContext(). --- examples/example_sdl3_opengl3/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 7ce36b4e8..c4eee77d4 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -196,7 +196,7 @@ int main(int, char**) ImGui_ImplSDL3_Shutdown(); ImGui::DestroyContext(); - SDL_GL_DeleteContext(gl_context); + SDL_GL_DestroyContext(gl_context); SDL_DestroyWindow(window); SDL_Quit(); From 126569ad5b3a2c5329cc8ee914dd5b2075f4dd50 Mon Sep 17 00:00:00 2001 From: Cyao <94928179+cheyao@users.noreply.github.com> Date: Sun, 14 Jul 2024 12:26:59 +0200 Subject: [PATCH 0078/2359] Fix definition check (#7793) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 2091267b6..0917c3092 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14378,7 +14378,7 @@ static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) #include static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { -#if __APPLE__ +#if defined(__APPLE__) const char* args[] { "open", "--", path, NULL }; #else const char* args[] { "xdg-open", path, NULL }; From df3a74389e8a39d4bdb199b29faa519e7369e3fc Mon Sep 17 00:00:00 2001 From: wermi <32251376+wermipls@users.noreply.github.com> Date: Mon, 15 Jul 2024 04:34:44 +0200 Subject: [PATCH 0079/2359] Backends: SDL3: Update for API changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) --- backends/imgui_impl_sdl3.cpp | 4 ++-- docs/CHANGELOG.txt | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 23fd42cc2..2eefbde34 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -387,9 +387,9 @@ static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Win viewport->PlatformHandle = window; viewport->PlatformHandleRaw = nullptr; #if defined(__WIN32__) && !defined(__WINRT__) - viewport->PlatformHandleRaw = (HWND)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.win32.hwnd", nullptr); + viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) - viewport->PlatformHandleRaw = (void*)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.cocoa.window", nullptr); + viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr); #endif } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8e7f3a00d..c71adfca2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -65,6 +65,7 @@ Other changes: - Backends: Win32: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768, #4858, #2622) [@Aemony] - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) +- Backends: SDL3: Update for API changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) [@wermipls] - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. - Backends: GLFW,SDL2: Added io.PlatformOpenInShellFn handler for web/Emscripten versions. (#7660) [@ypujante, @ocornut] From 9c2f6003e4f0250f14c83ec1fad6da7ec743b9ec Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jul 2024 11:17:21 +0200 Subject: [PATCH 0080/2359] Backends: SDL3: fixed typo leading to PlatformHandleRaw not being set leading to SHOWNA path not working for multi-viewports. --- backends/imgui_impl_sdl3.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 2eefbde34..7bb9ca217 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -386,7 +386,7 @@ static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Win { viewport->PlatformHandle = window; viewport->PlatformHandleRaw = nullptr; -#if defined(__WIN32__) && !defined(__WINRT__) +#if defined(_WIN32) && !defined(__WINRT__) viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr); From ac7d6fb5ca0430bc1b7a15048e24d538a8d41679 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 9 Jul 2024 16:37:17 +0200 Subject: [PATCH 0081/2359] Internals: Added TreeNodeIsOpen() to facilitate discoverability. (#7553, #1131, #2958, #2079, #722) --- imgui_internal.h | 1 + imgui_widgets.cpp | 14 ++++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5a0fc7c4b..11ada4bab 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3469,6 +3469,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); IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API void TreePushOverrideID(ImGuiID id); + IMGUI_API bool TreeNodeIsOpen(ImGuiID id); IMGUI_API void TreeNodeSetOpen(ImGuiID id, bool open); IMGUI_API bool TreeNodeUpdateNextOpen(ImGuiID id, ImGuiTreeNodeFlags flags); // Return open state. Consume previous SetNextItemOpen() data, if any. May return true when logging. IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 05e470195..558979b98 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6257,6 +6257,13 @@ bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char return TreeNodeBehavior(window->GetID(ptr_id), flags, label, label_end); } +bool ImGui::TreeNodeIsOpen(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; + return storage->GetInt(id, 0) != 0; +} + void ImGui::TreeNodeSetOpen(ImGuiID id, bool open) { ImGuiContext& g = *GImGui; @@ -6269,7 +6276,7 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID id, ImGuiTreeNodeFlags flags) if (flags & ImGuiTreeNodeFlags_Leaf) return true; - // We only write to the tree storage if the user clicks (or explicitly use the SetNextItemOpen function) + // We only write to the tree storage if the user clicks, or explicitly use the SetNextItemOpen function ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiStorage* storage = window->DC.StateStorage; @@ -6311,6 +6318,7 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID id, ImGuiTreeNodeFlags flags) } // Store ImGuiTreeNodeStackData for just submitted node. +// Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase. static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags) { ImGuiContext& g = *GImGui; @@ -6393,7 +6401,6 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // Store data for the current depth to allow returning to this node from any child item. // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default or move it to ImGuiStyle. - // Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase. bool store_tree_node_stack_data = false; if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) { @@ -6517,7 +6524,6 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l text_pos.x -= text_offset_x -padding.x; if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton) frame_bb.Max.x -= g.FontSize + style.FramePadding.x; - if (g.LogEnabled) LogSetNextTextDecoration("###", "###"); } @@ -6550,7 +6556,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (store_tree_node_stack_data && is_open) TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) - TreePushOverrideID(id); + TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open; From bc9e5b62b6beddf6173249202a176725064ec540 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jul 2024 16:49:35 +0200 Subject: [PATCH 0082/2359] Added ImGuiDataType_Bool for convenience. --- imgui.h | 3 ++- imgui_widgets.cpp | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index b1796242b..a2c2e8c08 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19093 +#define IMGUI_VERSION_NUM 19094 #define IMGUI_HAS_TABLE /* @@ -1336,6 +1336,7 @@ enum ImGuiDataType_ ImGuiDataType_U64, // unsigned long long / unsigned __int64 ImGuiDataType_Float, // float ImGuiDataType_Double, // double + ImGuiDataType_Bool, // bool (provided for user convenience, not supported by scalar widgets) ImGuiDataType_COUNT }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 558979b98..3ce3a2f2a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2131,6 +2131,7 @@ static const ImGuiDataTypeInfo GDataTypeInfo[] = #endif { sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg) { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double + { sizeof(bool), "bool", "%d", "%d" }, // ImGuiDataType_Bool }; IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT); From 46691d172ec65915b6a1e14dd9ae2c0a49dd15c4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jul 2024 17:12:11 +0200 Subject: [PATCH 0083/2359] Demo: Reworked "Property Editor" demo in a manner that more ressemble the tree data and struct description data that a real application would want to use. --- docs/CHANGELOG.txt | 2 + imgui_demo.cpp | 182 ++++++++++++++++++++++++++++++++++----------- 2 files changed, 141 insertions(+), 43 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c71adfca2..d5c58c1e7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,8 @@ Other changes: Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. - Debug Tools: Debug Log: Added "Configure Outputs.." button. (#5855) +- Demo: Reworked "Property Editor" demo in a manner that more ressemble the tree data and + struct description data that a real application would want to use. - Backends: Win32: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768, #4858, #2622) [@Aemony] - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9da3cd965..019f67d9d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7749,53 +7749,162 @@ static void ShowExampleAppLayout(bool* p_open) // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() //----------------------------------------------------------------------------- -static void ShowPlaceholderObject(const char* prefix, int uid) +// Simple representation for a tree +// (this is designed to be simple to understand for our demos, not to be efficient etc.) +struct ExampleTreeNode { - // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. - ImGui::PushID(uid); + char Name[28]; + ImGuiID UID = 0; + ExampleTreeNode* Parent = NULL; + ImVector Childs; - // Text and Tree nodes are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the tree lines equal high. + // Data + bool HasData = false; // All leaves have data + bool DataIsEnabled = false; + int DataInt = 128; + ImVec2 DataVec2 = ImVec2(0.0f, 3.141592f); +}; + +// Simple representation of struct metadata/serialization data. +// (this is a minimal version of what a typical advanced application may provide) +struct ExampleMemberInfo +{ + const char* Name; + ImGuiDataType DataType; + int DataCount; + int Offset; +}; + +// Metadata description of ExampleTreeNode struct. +static const ExampleMemberInfo ExampleTreeNodeMemberInfos[] +{ + { "Enabled", ImGuiDataType_Bool, 1, offsetof(ExampleTreeNode, DataIsEnabled) }, + { "MyInt", ImGuiDataType_S32, 1, offsetof(ExampleTreeNode, DataInt) }, + { "MyVec2", ImGuiDataType_Float, 2, offsetof(ExampleTreeNode, DataVec2) }, +}; + +static ExampleTreeNode* ExampleTree_CreateNode(const char* name, const ImGuiID uid, ExampleTreeNode* parent) +{ + ExampleTreeNode* node = IM_NEW(ExampleTreeNode); + snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name); + node->UID = uid; + node->Parent = parent; + if (parent) + parent->Childs.push_back(node); + return node; +} + +static ExampleTreeNode* ExampleTree_CreateDemoTree() +{ + static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + char name_buf[32]; + ImGuiID uid = 0; + ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); + for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * 2; idx_L0++) + { + snprintf(name_buf, 32, "%s %d", root_names[idx_L0 / 2], idx_L0 % 2); + ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); + const int number_of_childs = (int)strlen(node_L1->Name); + for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) + { + snprintf(name_buf, 32, "Child %d", idx_L1); + ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1); + node_L2->HasData = true; + if (idx_L1 == 0) + { + snprintf(name_buf, 32, "Sub-child %d", 0); + ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2); + node_L3->HasData = true; + } + } + } + return node_L0; +} + +static void PropertyEditor_ShowTreeNode(ExampleTreeNode* node) +{ + // Object tree node + ImGui::PushID((int)node->UID); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::AlignTextToFramePadding(); - bool node_open = ImGui::TreeNode("##Object", "%s_%u", prefix, uid); + ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None; + tree_flags |= ImGuiTreeNodeFlags_SpanAllColumns | ImGuiTreeNodeFlags_AllowOverlap; // Highlight whole row for visibility + tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; // Standard opening mode as we are likely to want to add selection afterwards + tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support + bool node_open = ImGui::TreeNodeEx("##Object", tree_flags, "%s", node->Name); ImGui::TableSetColumnIndex(1); - ImGui::Text("my sailor is rich"); + ImGui::TextDisabled("UID: 0x%08X", node->UID); + // Display child and data if (node_open) + for (ExampleTreeNode* child : node->Childs) + PropertyEditor_ShowTreeNode(child); + if (node_open && node->HasData) { - static float placeholder_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f }; - for (int i = 0; i < 8; i++) + // In a typical application, the structure description would be derived from a data-driven system. + // - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. + // - Limits and some details are hard-coded to simplify the demo. + // - Text and Selectable are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the selectable lines equal high. + for (const ExampleMemberInfo& field_desc : ExampleTreeNodeMemberInfos) { - ImGui::PushID(i); // Use field index as identifier. - if (i < 2) + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::AlignTextToFramePadding(); + ImGui::PushTabStop(false); // We didn't expose ImGuiItemFlags_NoNav yet, so arrow navigation will still pass through this + ImGui::Selectable(field_desc.Name, false, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); + ImGui::PopTabStop(); + ImGui::TableSetColumnIndex(1); + ImGui::PushID(field_desc.Name); + void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset); + switch (field_desc.DataType) { - ShowPlaceholderObject("Child", 424242); + case ImGuiDataType_Bool: + { + IM_ASSERT(field_desc.DataCount == 1); + ImGui::Checkbox("##Editor", (bool*)field_ptr); + break; } - else + case ImGuiDataType_S32: { - // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well) - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::AlignTextToFramePadding(); - ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet; - ImGui::TreeNodeEx("Field", flags, "Field_%d", i); - - ImGui::TableSetColumnIndex(1); + int v_min = INT_MIN, v_max = INT_MAX; ImGui::SetNextItemWidth(-FLT_MIN); - if (i >= 5) - ImGui::InputFloat("##value", &placeholder_members[i], 1.0f); - else - ImGui::DragFloat("##value", &placeholder_members[i], 0.01f); - ImGui::NextColumn(); + ImGui::DragScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, 1.0f, &v_min, &v_max); + break; + } + case ImGuiDataType_Float: + { + float v_min = 0.0f, v_max = 1.0f; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SliderScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, &v_min, &v_max); + break; + } } ImGui::PopID(); } - ImGui::TreePop(); } + if (node_open) + ImGui::TreePop(); ImGui::PopID(); } +static void PropertyEditor_ShowTree(ExampleTreeNode* root_node) +{ + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); + ImGuiTableFlags table_flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; + if (ImGui::BeginTable("##split", 2, table_flags)) + { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("Object", ImGuiTableColumnFlags_WidthStretch, 1.0f); + ImGui::TableSetupColumn("Contents", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger + ImGui::TableHeadersRow(); + for (ExampleTreeNode* node : root_node->Childs) + PropertyEditor_ShowTreeNode(node); + ImGui::EndTable(); + } + ImGui::PopStyleVar(); +} + // Demonstrate create a simple property editor. // This demo is a bit lackluster nowadays, would be nice to improve. static void ShowExampleAppPropertyEditor(bool* p_open) @@ -7808,25 +7917,12 @@ static void ShowExampleAppPropertyEditor(bool* p_open) } IMGUI_DEMO_MARKER("Examples/Property Editor"); - HelpMarker( - "This example shows how you may implement a property editor using two columns.\n" - "All objects/fields data are dummies here.\n"); + static ExampleTreeNode* tree_data = NULL; + if (tree_data == NULL) + tree_data = ExampleTree_CreateDemoTree(); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); - if (ImGui::BeginTable("##split", 2, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY)) - { - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("Object"); - ImGui::TableSetupColumn("Contents"); - ImGui::TableHeadersRow(); + PropertyEditor_ShowTree(tree_data); - // Iterate placeholder objects (all the same data) - for (int obj_i = 0; obj_i < 4; obj_i++) - ShowPlaceholderObject("Object", obj_i); - - ImGui::EndTable(); - } - ImGui::PopStyleVar(); ImGui::End(); } From 7e0800e718633c31e6e366df786aed50f46dec15 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jul 2024 17:32:41 +0200 Subject: [PATCH 0084/2359] Added PushItemFlag(), PopItemFlag(), ImGuiItemFlags. --- docs/CHANGELOG.txt | 6 ++++++ imgui.h | 16 +++++++++++++++- imgui_demo.cpp | 4 ++-- imgui_internal.h | 30 ++++++++++-------------------- imgui_widgets.cpp | 2 +- 5 files changed, 34 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d5c58c1e7..1ad1f4dd5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,12 @@ Other changes: - IO: added io.PlatformOpenInShellFn handler to open a link/folder/file in OS shell. (#7660) Default to use ShellExecute() under Windows, and system("") under Mac/Linux/etc. Added IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS to disable default implementation. +- Added PushItemFlag()/PopItemFlags(), ImGuiItemFlags to modify shared item flags: + - Added ImGuiItemFlags_NoTabStop to disable tabbing through items. + - Added ImGuiItemFlags_NoNav to disable any navigation and focus of items. (#787) + - Added ImGuiItemFlags_NoNavDefaultFocus to disable item being default focus. (#787) + - Added ImGuiItemFlags_ButtonRepeat to enable repeat on any button-like behavior. + - (previously in imgui_internal.h) - Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. diff --git a/imgui.h b/imgui.h index a2c2e8c08..2d4f251cd 100644 --- a/imgui.h +++ b/imgui.h @@ -224,6 +224,7 @@ typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: f typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. typedef int ImGuiInputFlags; // -> enum ImGuiInputFlags_ // Flags: for Shortcut(), SetNextItemShortcut() typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() +typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag(), shared by all items typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() @@ -436,9 +437,11 @@ namespace ImGui IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame(). IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. always use this if you modify the style after NewFrame(). IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); // modify specified shared item flag, e.g. PushItemFlag(ImGuiItemFlags_NoTabStop, true) + IMGUI_API void PopItemFlag(); IMGUI_API void PushTabStop(bool tab_stop); // == tab stop enable. Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets IMGUI_API void PopTabStop(); - IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PushButtonRepeat(bool repeat); // in repeat mode, any button-like function behave with a repeating behavior (using io.KeyRepeatDelay/io.KeyRepeatRate values). Note that you can call IsItemActive() after any button to tell if it is being held. IMGUI_API void PopButtonRepeat(); // Parameters stacks (current window) @@ -1088,6 +1091,17 @@ enum ImGuiChildFlags_ ImGuiChildFlags_NavFlattened = 1 << 8, // Share focus scope, allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. }; +// Flags for ImGui::PushItemFlag() +// (Those are shared by all items) +enum ImGuiItemFlags_ +{ + ImGuiItemFlags_None = 0, // (Default) + ImGuiItemFlags_NoTabStop = 1 << 0, // false // Disable keyboard tabbing. This is a "lighter" version of ImGuiItemFlags_NoNav. + ImGuiItemFlags_NoNav = 1 << 1, // false // Disable any form of focusing (keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls). + ImGuiItemFlags_NoNavDefaultFocus = 1 << 2, // false // Disable item being a candidate for default focus (e.g. used by title bar items). + ImGuiItemFlags_ButtonRepeat = 1 << 3, // false // Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. +}; + // Flags for ImGui::InputText() // (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) enum ImGuiInputTextFlags_ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 019f67d9d..31debeff5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7851,9 +7851,9 @@ static void PropertyEditor_ShowTreeNode(ExampleTreeNode* node) ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::AlignTextToFramePadding(); - ImGui::PushTabStop(false); // We didn't expose ImGuiItemFlags_NoNav yet, so arrow navigation will still pass through this + ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop | ImGuiItemFlags_NoNav, true); ImGui::Selectable(field_desc.Name, false, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); - ImGui::PopTabStop(); + ImGui::PopItemFlag(); ImGui::TableSetColumnIndex(1); ImGui::PushID(field_desc.Name); void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset); diff --git a/imgui_internal.h b/imgui_internal.h index 11ada4bab..0a46ee93e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -169,7 +169,6 @@ typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // E typedef int ImGuiActivateFlags; // -> enum ImGuiActivateFlags_ // Flags: for navigation/focus function (will be for ActivateItem() later) typedef int ImGuiDebugLogFlags; // -> enum ImGuiDebugLogFlags_ // Flags: for ShowDebugLogWindow(), g.DebugLogFlags typedef int ImGuiFocusRequestFlags; // -> enum ImGuiFocusRequestFlags_ // Flags: for FocusWindow(); -typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag(), g.LastItemData.InFlags typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for g.LastItemData.StatusFlags typedef int ImGuiOldColumnFlags; // -> enum ImGuiOldColumnFlags_ // Flags: for BeginColumns() typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() @@ -840,29 +839,22 @@ enum ImGuiDataTypePrivate_ // [SECTION] Widgets support: flags, enums, data structures //----------------------------------------------------------------------------- -// Flags used by upcoming items +// Extend ImGuiItemFlags // - input: PushItemFlag() manipulates g.CurrentItemFlags, ItemAdd() calls may add extra flags. // - output: stored in g.LastItemData.InFlags -// Current window shared by all windows. -// This is going to be exposed in imgui.h when stabilized enough. -enum ImGuiItemFlags_ +enum ImGuiItemFlagsPrivate_ { // Controlled by user - ImGuiItemFlags_None = 0, - ImGuiItemFlags_NoTabStop = 1 << 0, // false // Disable keyboard tabbing. This is a "lighter" version of ImGuiItemFlags_NoNav. - ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. - ImGuiItemFlags_Disabled = 1 << 2, // false // Disable interactions but doesn't affect visuals. See BeginDisabled()/EndDisabled(). See github.com/ocornut/imgui/issues/211 - ImGuiItemFlags_NoNav = 1 << 3, // false // Disable any form of focusing (keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls) - ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false // Disable item being a candidate for default focus (e.g. used by title bar items) - ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // Disable MenuItem/Selectable() automatically closing their popup window - ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) - ImGuiItemFlags_ReadOnly = 1 << 7, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. - ImGuiItemFlags_NoWindowHoverableCheck = 1 << 8, // false // Disable hoverable check in ItemHoverable() - ImGuiItemFlags_AllowOverlap = 1 << 9, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. + ImGuiItemFlags_Disabled = 1 << 10, // false // Disable interactions (DOES NOT affect visuals, see BeginDisabled()/EndDisabled() for full disable feature, and github #211). + ImGuiItemFlags_SelectableDontClosePopup = 1 << 11, // false // Disable MenuItem/Selectable() automatically closing their popup window + ImGuiItemFlags_MixedValue = 1 << 12, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) + ImGuiItemFlags_ReadOnly = 1 << 13, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. + ImGuiItemFlags_NoWindowHoverableCheck = 1 << 14, // false // Disable hoverable check in ItemHoverable() + ImGuiItemFlags_AllowOverlap = 1 << 15, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. // Controlled by widget code - ImGuiItemFlags_Inputable = 1 << 10, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. - ImGuiItemFlags_HasSelectionUserData = 1 << 11, // false // Set by SetNextItemSelectionUserData() + ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. + ImGuiItemFlags_HasSelectionUserData = 1 << 21, // false // Set by SetNextItemSelectionUserData() }; // Status flags for an already submitted item @@ -3153,8 +3145,6 @@ namespace ImGui IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); // Parameter stacks (shared) - IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); - IMGUI_API void PopItemFlag(); IMGUI_API const ImGuiDataVarInfo* GetStyleVarInfo(ImGuiStyleVar idx); IMGUI_API void BeginDisabledOverrideReenable(); IMGUI_API void EndDisabledOverrideReenable(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3ce3a2f2a..6af70d96d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6745,7 +6745,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl } const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; - const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? ImGuiItemFlags_Disabled : ImGuiItemFlags_None); + const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags_)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); if (span_all_columns) { window->ClipRect.Min.x = backup_clip_rect_min_x; From b4ca869c407950d6eb26b9e683230ead674c438e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jul 2024 17:46:32 +0200 Subject: [PATCH 0085/2359] (Breaking) Obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag()/PopItemFlag() with ImGuiItemFlags_ButtonRepeat. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 11 +---------- imgui.h | 5 +++-- imgui_demo.cpp | 8 +++----- 4 files changed, 9 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1ad1f4dd5..317e18efa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,8 @@ Breaking changes: - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); It is expected that for a vast majority of users this is automatically set by core library and/or platform backend so it won't have any effect. +- Obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag()/PopItemFlag() + with ImGuiItemFlags_ButtonRepeat. Kept inline redirecting functions (will obsolete). - Commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456) - Commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. diff --git a/imgui.cpp b/imgui.cpp index 0917c3092..beb6bc678 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag(). - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456) - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. @@ -7630,16 +7631,6 @@ void ImGui::PopTabStop() PopItemFlag(); } -void ImGui::PushButtonRepeat(bool repeat) -{ - PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); -} - -void ImGui::PopButtonRepeat() -{ - PopItemFlag(); -} - void ImGui::PushTextWrapPos(float wrap_pos_x) { ImGuiWindow* window = GetCurrentWindow(); diff --git a/imgui.h b/imgui.h index 2d4f251cd..e57535d6a 100644 --- a/imgui.h +++ b/imgui.h @@ -441,8 +441,6 @@ namespace ImGui IMGUI_API void PopItemFlag(); IMGUI_API void PushTabStop(bool tab_stop); // == tab stop enable. Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets IMGUI_API void PopTabStop(); - IMGUI_API void PushButtonRepeat(bool repeat); // in repeat mode, any button-like function behave with a repeating behavior (using io.KeyRepeatDelay/io.KeyRepeatRate values). Note that you can call IsItemActive() after any button to tell if it is being held. - IMGUI_API void PopButtonRepeat(); // Parameters stacks (current window) IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). @@ -3314,6 +3312,9 @@ struct ImGuiPlatformImeData #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.91.0 (from July 2024) + static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } + static inline void PopButtonRepeat() { PopItemFlag(); } // OBSOLETED in 1.90.0 (from September 2023) static inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } static inline void EndChildFrame() { EndChild(); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 31debeff5..c89ec38cf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -662,11 +662,11 @@ static void ShowDemoWindowWidgets() IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Repeating)"); static int counter = 0; float spacing = ImGui::GetStyle().ItemInnerSpacing.x; - ImGui::PushButtonRepeat(true); + ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); if (ImGui::ArrowButton("##left", ImGuiDir_Left)) { counter--; } ImGui::SameLine(0.0f, spacing); if (ImGui::ArrowButton("##right", ImGuiDir_Right)) { counter++; } - ImGui::PopButtonRepeat(); + ImGui::PopItemFlag(); ImGui::SameLine(); ImGui::Text("%d", counter); @@ -2581,7 +2581,7 @@ static void ShowDemoWindowWidgets() ImGui::BeginDisabled(true); if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button - if (item_type == 2) { ImGui::PushButtonRepeat(true); ret = ImGui::Button("ITEM: Button"); ImGui::PopButtonRepeat(); } // Testing button (with repeater) + if (item_type == 2) { ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); ret = ImGui::Button("ITEM: Button"); ImGui::PopItemFlag(); } // Testing button (with repeater) if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) @@ -5875,7 +5875,6 @@ static void ShowDemoWindowTables() // Show data // FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here? - ImGui::PushButtonRepeat(true); #if 1 // Demonstrate using clipper for large vertical lists ImGuiListClipper clipper; @@ -5960,7 +5959,6 @@ static void ShowDemoWindowTables() ImGui::PopID(); } } - ImGui::PopButtonRepeat(); // Store some info to display debug details below table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY()); From 0de88a928d7feb5c89d4b73c0fe373a6e16da394 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jul 2024 17:58:43 +0200 Subject: [PATCH 0086/2359] Added ImGuiItemFlags_AutoClosePopups as a replacement for internal's ImGuiItemFlags_SelectableDontClosePopup. (#1379, #1468, #2200, #4936, #5216, #7302, #7573) --- docs/CHANGELOG.txt | 8 +++++++- imgui.cpp | 3 ++- imgui.h | 1 + imgui_internal.h | 12 ++++++++---- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 6 files changed, 20 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 317e18efa..584835e99 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,9 @@ Breaking changes: - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. - Backends: GLFW+Emscripten: Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), with additional GLFWWindow* parameter. (#7647) [@ypujante] +- Internals: changed/inverted ImGuiItemFlags_SelectableDontClosePopup (default==false) to + ImGuiItemFlags_AutoClosePopups (default==true), same logic, only inverted behavior. + (#1379, #2200, #4936, #5216, #7302) Other changes: @@ -65,7 +68,10 @@ Other changes: - Added ImGuiItemFlags_NoNav to disable any navigation and focus of items. (#787) - Added ImGuiItemFlags_NoNavDefaultFocus to disable item being default focus. (#787) - Added ImGuiItemFlags_ButtonRepeat to enable repeat on any button-like behavior. - - (previously in imgui_internal.h) + - Added ImGuiItemFlags_AutoClosePopups to disable menu items/selection auto closing parent popups. + Disabling this was previously possible for Selectable() via a direct flag but not for MenuItem(). + (#1379, #1468, #2200, #4936, #5216, #7302, #7573) + - This was mostly all previously in imgui_internal.h. - Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. diff --git a/imgui.cpp b/imgui.cpp index beb6bc678..14d726caa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4903,7 +4903,8 @@ void ImGui::NewFrame() g.CurrentWindowStack.resize(0); g.BeginPopupStack.resize(0); g.ItemFlagsStack.resize(0); - g.ItemFlagsStack.push_back(ImGuiItemFlags_None); + g.ItemFlagsStack.push_back(ImGuiItemFlags_AutoClosePopups); // Default flags + g.CurrentItemFlags = g.ItemFlagsStack.back(); g.GroupStack.resize(0); // [DEBUG] Update debug features diff --git a/imgui.h b/imgui.h index e57535d6a..dd5f9c6de 100644 --- a/imgui.h +++ b/imgui.h @@ -1098,6 +1098,7 @@ enum ImGuiItemFlags_ ImGuiItemFlags_NoNav = 1 << 1, // false // Disable any form of focusing (keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls). ImGuiItemFlags_NoNavDefaultFocus = 1 << 2, // false // Disable item being a candidate for default focus (e.g. used by title bar items). ImGuiItemFlags_ButtonRepeat = 1 << 3, // false // Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. + ImGuiItemFlags_AutoClosePopups = 1 << 4, // true // MenuItem()/Selectable() automatically close their parent popup window. }; // Flags for ImGui::InputText() diff --git a/imgui_internal.h b/imgui_internal.h index 0a46ee93e..cefdb6ae9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -846,15 +846,19 @@ enum ImGuiItemFlagsPrivate_ { // Controlled by user ImGuiItemFlags_Disabled = 1 << 10, // false // Disable interactions (DOES NOT affect visuals, see BeginDisabled()/EndDisabled() for full disable feature, and github #211). - ImGuiItemFlags_SelectableDontClosePopup = 1 << 11, // false // Disable MenuItem/Selectable() automatically closing their popup window + ImGuiItemFlags_ReadOnly = 1 << 11, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. ImGuiItemFlags_MixedValue = 1 << 12, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) - ImGuiItemFlags_ReadOnly = 1 << 13, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. - ImGuiItemFlags_NoWindowHoverableCheck = 1 << 14, // false // Disable hoverable check in ItemHoverable() - ImGuiItemFlags_AllowOverlap = 1 << 15, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. + ImGuiItemFlags_NoWindowHoverableCheck = 1 << 13, // false // Disable hoverable check in ItemHoverable() + ImGuiItemFlags_AllowOverlap = 1 << 14, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. // Controlled by widget code ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. ImGuiItemFlags_HasSelectionUserData = 1 << 21, // false // Set by SetNextItemSelectionUserData() + + ImGuiItemFlags_Default_ = ImGuiItemFlags_AutoClosePopups, // Please don't change, use PushItemFlag() instead. + + // Obsolete + //ImGuiItemFlags_SelectableDontClosePopup = !ImGuiItemFlags_AutoClosePopups, // Can't have a redirect as we inverted the behavior }; // Status flags for an already submitted item diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 70c74d43e..90131c83d 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3471,7 +3471,7 @@ void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags Separator(); want_separator = true; - PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true); + PushItemFlag(ImGuiItemFlags_AutoClosePopups, false); for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) { ImGuiTableColumn* other_column = &table->Columns[other_column_n]; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6af70d96d..ccef757ab 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6831,7 +6831,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); // Automatically close popups - if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(g.LastItemData.InFlags & ImGuiItemFlags_SelectableDontClosePopup)) + if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && (g.LastItemData.InFlags & ImGuiItemFlags_AutoClosePopups)) CloseCurrentPopup(); if (disabled_item && !disabled_global) From 3de75138d1c3fda656957834fa2fe167c5ff6afa Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jul 2024 18:14:33 +0200 Subject: [PATCH 0087/2359] (Breaking) Renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573) --- docs/CHANGELOG.txt | 13 ++++++++----- imgui.cpp | 2 ++ imgui.h | 5 +++-- imgui_widgets.cpp | 4 ++-- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 584835e99..cf3b98f4e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,16 +46,19 @@ Breaking changes: - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); It is expected that for a vast majority of users this is automatically set by core library and/or platform backend so it won't have any effect. -- Obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag()/PopItemFlag() - with ImGuiItemFlags_ButtonRepeat. Kept inline redirecting functions (will obsolete). +- Item flag changes: + - Obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag()/PopItemFlag() + with ImGuiItemFlags_ButtonRepeat. Kept inline redirecting functions (will obsolete). + - Renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups for + consistency. Kept inline redirecting functions (will obsolete). + + Internals: changed/inverted ImGuiItemFlags_SelectableDontClosePopup (default==false) to + ImGuiItemFlags_AutoClosePopups (default==true), same logic, only inverted behavior. + (#1379, #1468, #2200, #4936, #5216, #7302, #7573) - Commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456) - Commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. - Backends: GLFW+Emscripten: Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), with additional GLFWWindow* parameter. (#7647) [@ypujante] -- Internals: changed/inverted ImGuiItemFlags_SelectableDontClosePopup (default==false) to - ImGuiItemFlags_AutoClosePopups (default==true), same logic, only inverted behavior. - (#1379, #2200, #4936, #5216, #7302) Other changes: diff --git a/imgui.cpp b/imgui.cpp index 14d726caa..17871e855 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,8 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573) + (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors) - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag(). - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456) - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) diff --git a/imgui.h b/imgui.h index dd5f9c6de..aadd2d0ec 100644 --- a/imgui.h +++ b/imgui.h @@ -1198,14 +1198,15 @@ enum ImGuiPopupFlags_ enum ImGuiSelectableFlags_ { ImGuiSelectableFlags_None = 0, - ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this doesn't close parent popup window + ImGuiSelectableFlags_NoAutoClosePopups = 1 << 0, // Clicking this doesn't close parent popup window (overrides ImGuiItemFlags_AutoClosePopups) ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Frame will span all columns of its container table (text will still fit in current column) ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text ImGuiSelectableFlags_AllowOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 + ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 + ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 #endif }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ccef757ab..341da042c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6831,7 +6831,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); // Automatically close popups - if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && (g.LastItemData.InFlags & ImGuiItemFlags_AutoClosePopups)) + if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.InFlags & ImGuiItemFlags_AutoClosePopups)) CloseCurrentPopup(); if (disabled_item && !disabled_global) @@ -7659,7 +7659,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) bool pressed; // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another. - const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_DontClosePopups; + const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_NoAutoClosePopups; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { // Menu inside an horizontal menu bar From 0e4dcfa55299eebd4659181b3622d24566f2f764 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jul 2024 18:41:06 +0200 Subject: [PATCH 0088/2359] Obsoleted PushTabStop()/PopTabStop() in favor of using new PushItemFlag()/PopItemFlag() with ImGuiItemFlags_NoTabStop. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 14 ++------------ imgui.h | 30 +++++++++++++++--------------- imgui_demo.cpp | 8 ++++---- 4 files changed, 23 insertions(+), 31 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cf3b98f4e..56b4576ed 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Breaking changes: - Item flag changes: - Obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag()/PopItemFlag() with ImGuiItemFlags_ButtonRepeat. Kept inline redirecting functions (will obsolete). + - Obsoleted PushTabStop()/PopTabStop() in favor of using new PushItemFlag()/PopItemFlag() + with ImGuiItemFlags_NoTabStop. Kept inline redirecting functions (will obsolete). - Renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups for consistency. Kept inline redirecting functions (will obsolete). + Internals: changed/inverted ImGuiItemFlags_SelectableDontClosePopup (default==false) to diff --git a/imgui.cpp b/imgui.cpp index 17871e855..605fae215 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7624,16 +7624,6 @@ void ImGui::EndDisabledOverrideReenable() g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha; } -void ImGui::PushTabStop(bool tab_stop) -{ - PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); -} - -void ImGui::PopTabStop() -{ - PopItemFlag(); -} - void ImGui::PushTextWrapPos(float wrap_pos_x) { ImGuiWindow* window = GetCurrentWindow(); @@ -13773,10 +13763,10 @@ void ImGui::LogButtons() #endif const bool log_to_file = Button("Log To File"); SameLine(); const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); - PushTabStop(false); + PushItemFlag(ImGuiItemFlags_NoTabStop, true); SetNextItemWidth(80.0f); SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); - PopTabStop(); + PopItemFlag(); PopID(); // Start logging at the end of the function so that the buttons don't appear in the log diff --git a/imgui.h b/imgui.h index aadd2d0ec..0e657b46a 100644 --- a/imgui.h +++ b/imgui.h @@ -439,8 +439,6 @@ namespace ImGui IMGUI_API void PopStyleVar(int count = 1); IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); // modify specified shared item flag, e.g. PushItemFlag(ImGuiItemFlags_NoTabStop, true) IMGUI_API void PopItemFlag(); - IMGUI_API void PushTabStop(bool tab_stop); // == tab stop enable. Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets - IMGUI_API void PopTabStop(); // Parameters stacks (current window) IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). @@ -3315,31 +3313,33 @@ struct ImGuiPlatformImeData namespace ImGui { // OBSOLETED in 1.91.0 (from July 2024) - static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } - static inline void PopButtonRepeat() { PopItemFlag(); } + static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } + static inline void PopButtonRepeat() { PopItemFlag(); } + static inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + static inline void PopTabStop() { PopItemFlag(); } // OBSOLETED in 1.90.0 (from September 2023) - static inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } - static inline void EndChildFrame() { EndChild(); } + static inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } + static inline void EndChildFrame() { EndChild(); } //static inline bool BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags window_flags){ return BeginChild(str_id, size_arg, border ? ImGuiChildFlags_Border : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Border //static inline bool BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags window_flags) { return BeginChild(id, size_arg, border ? ImGuiChildFlags_Border : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Border - static inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } - 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); + static inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } 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); + 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); // OBSOLETED in 1.89.7 (from June 2023) - IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() before item. + IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() before item. // OBSOLETED in 1.89.4 (from March 2023) - static inline void PushAllowKeyboardFocus(bool tab_stop) { PushTabStop(tab_stop); } - static inline void PopAllowKeyboardFocus() { PopTabStop(); } + static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + static inline void PopAllowKeyboardFocus() { PopItemFlag(); } // OBSOLETED in 1.89 (from August 2022) IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // Use new ImageButton() signature (explicit item id, regular FramePadding) // OBSOLETED in 1.87 (from February 2022 but more formally obsoleted April 2024) - IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value! - //static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; } + IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value! + //static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; } // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) //-- OBSOLETED in 1.88 (from May 2022) - //static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. - //static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. + //static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. + //static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. //-- OBSOLETED in 1.86 (from November 2021) //IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Code removed, see 1.90 for last version of the code. Calculate range of visible items for large list of evenly sized items. Prefer using ImGuiListClipper. //-- OBSOLETED in 1.85 (from August 2021) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c89ec38cf..dba63ee55 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6421,10 +6421,10 @@ static void ShowDemoWindowInputs() ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); - ImGui::PushTabStop(false); + ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, true); ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab."); - ImGui::PopTabStop(); + ImGui::PopItemFlag(); ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); ImGui::TreePop(); } @@ -6446,12 +6446,12 @@ static void ShowDemoWindowInputs() ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); if (ImGui::IsItemActive()) has_focus = 2; - ImGui::PushTabStop(false); + ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, true); if (focus_3) ImGui::SetKeyboardFocusHere(); ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); if (ImGui::IsItemActive()) has_focus = 3; ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab."); - ImGui::PopTabStop(); + ImGui::PopItemFlag(); if (has_focus) ImGui::Text("Item with focus: %d", has_focus); From 9c1f922b02bc53af6825e5e3f6e49519aedddc85 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jul 2024 17:19:12 +0200 Subject: [PATCH 0089/2359] Fixed pvs-studio warning. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 341da042c..26968192b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6745,7 +6745,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl } const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; - const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags_)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); + const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); if (span_all_columns) { window->ClipRect.Min.x = backup_clip_rect_min_x; From 4247f190c23325fbbf42c6452a0416ac2aebfcb0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Jul 2024 13:41:59 +0200 Subject: [PATCH 0090/2359] Demo: Property Editor: rearrange code + replace use of bool to proper ImGuiChildFlags. Amend 46691d1 --- imgui_demo.cpp | 173 ++++++++++++++++++++++++---------------------- imgui_tables.cpp | 4 +- imgui_widgets.cpp | 2 +- 3 files changed, 92 insertions(+), 87 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index dba63ee55..96e7e0ba6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -83,6 +83,7 @@ Index of this file: // [SECTION] Example App: Debug Console / ShowExampleAppConsole() // [SECTION] Example App: Debug Log / ShowExampleAppLog() // [SECTION] Example App: Simple Layout / ShowExampleAppLayout() +// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor etc.) // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() // [SECTION] Example App: Long Text / ShowExampleAppLongText() // [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() @@ -7744,7 +7745,7 @@ static void ShowExampleAppLayout(bool* p_open) } //----------------------------------------------------------------------------- -// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor etc.) //----------------------------------------------------------------------------- // Simple representation for a tree @@ -7819,92 +7820,98 @@ static ExampleTreeNode* ExampleTree_CreateDemoTree() return node_L0; } -static void PropertyEditor_ShowTreeNode(ExampleTreeNode* node) -{ - // Object tree node - ImGui::PushID((int)node->UID); - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::AlignTextToFramePadding(); - ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None; - tree_flags |= ImGuiTreeNodeFlags_SpanAllColumns | ImGuiTreeNodeFlags_AllowOverlap; // Highlight whole row for visibility - tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; // Standard opening mode as we are likely to want to add selection afterwards - tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support - bool node_open = ImGui::TreeNodeEx("##Object", tree_flags, "%s", node->Name); - ImGui::TableSetColumnIndex(1); - ImGui::TextDisabled("UID: 0x%08X", node->UID); +//----------------------------------------------------------------------------- +// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +//----------------------------------------------------------------------------- - // Display child and data - if (node_open) - for (ExampleTreeNode* child : node->Childs) - PropertyEditor_ShowTreeNode(child); - if (node_open && node->HasData) +struct ExampleAppPropertyEditor +{ + void Draw(ExampleTreeNode* root_node) { - // In a typical application, the structure description would be derived from a data-driven system. - // - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. - // - Limits and some details are hard-coded to simplify the demo. - // - Text and Selectable are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the selectable lines equal high. - for (const ExampleMemberInfo& field_desc : ExampleTreeNodeMemberInfos) + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); + ImGuiTableFlags table_flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; + if (ImGui::BeginTable("##split", 2, table_flags)) { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::AlignTextToFramePadding(); - ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop | ImGuiItemFlags_NoNav, true); - ImGui::Selectable(field_desc.Name, false, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); - ImGui::PopItemFlag(); - ImGui::TableSetColumnIndex(1); - ImGui::PushID(field_desc.Name); - void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset); - switch (field_desc.DataType) - { - case ImGuiDataType_Bool: - { - IM_ASSERT(field_desc.DataCount == 1); - ImGui::Checkbox("##Editor", (bool*)field_ptr); - break; - } - case ImGuiDataType_S32: - { - int v_min = INT_MIN, v_max = INT_MAX; - ImGui::SetNextItemWidth(-FLT_MIN); - ImGui::DragScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, 1.0f, &v_min, &v_max); - break; - } - case ImGuiDataType_Float: - { - float v_min = 0.0f, v_max = 1.0f; - ImGui::SetNextItemWidth(-FLT_MIN); - ImGui::SliderScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, &v_min, &v_max); - break; - } - } - ImGui::PopID(); + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("Object", ImGuiTableColumnFlags_WidthStretch, 1.0f); + ImGui::TableSetupColumn("Contents", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger + ImGui::TableHeadersRow(); + for (ExampleTreeNode* node : root_node->Childs) + DrawTreeNode(node); + ImGui::EndTable(); } + ImGui::PopStyleVar(); } - if (node_open) - ImGui::TreePop(); - ImGui::PopID(); -} -static void PropertyEditor_ShowTree(ExampleTreeNode* root_node) -{ - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); - ImGuiTableFlags table_flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; - if (ImGui::BeginTable("##split", 2, table_flags)) + void DrawTreeNode(ExampleTreeNode* node) { - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("Object", ImGuiTableColumnFlags_WidthStretch, 1.0f); - ImGui::TableSetupColumn("Contents", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger - ImGui::TableHeadersRow(); - for (ExampleTreeNode* node : root_node->Childs) - PropertyEditor_ShowTreeNode(node); - ImGui::EndTable(); - } - ImGui::PopStyleVar(); -} + // Object tree node + ImGui::PushID((int)node->UID); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::AlignTextToFramePadding(); + ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None; + tree_flags |= ImGuiTreeNodeFlags_SpanAllColumns | ImGuiTreeNodeFlags_AllowOverlap; // Highlight whole row for visibility + tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; // Standard opening mode as we are likely to want to add selection afterwards + tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support + bool node_open = ImGui::TreeNodeEx("##Object", tree_flags, "%s", node->Name); + ImGui::TableSetColumnIndex(1); + ImGui::TextDisabled("UID: 0x%08X", node->UID); -// Demonstrate create a simple property editor. -// This demo is a bit lackluster nowadays, would be nice to improve. + // Display child and data + if (node_open) + for (ExampleTreeNode* child : node->Childs) + DrawTreeNode(child); + if (node_open && node->HasData) + { + // In a typical application, the structure description would be derived from a data-driven system. + // - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. + // - Limits and some details are hard-coded to simplify the demo. + // - Text and Selectable are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the selectable lines equal high. + for (const ExampleMemberInfo& field_desc : ExampleTreeNodeMemberInfos) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::AlignTextToFramePadding(); + ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop | ImGuiItemFlags_NoNav, true); + ImGui::Selectable(field_desc.Name, false, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); + ImGui::PopItemFlag(); + ImGui::TableSetColumnIndex(1); + ImGui::PushID(field_desc.Name); + void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset); + switch (field_desc.DataType) + { + case ImGuiDataType_Bool: + { + IM_ASSERT(field_desc.DataCount == 1); + ImGui::Checkbox("##Editor", (bool*)field_ptr); + break; + } + case ImGuiDataType_S32: + { + int v_min = INT_MIN, v_max = INT_MAX; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::DragScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, 1.0f, &v_min, &v_max); + break; + } + case ImGuiDataType_Float: + { + float v_min = 0.0f, v_max = 1.0f; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SliderScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, &v_min, &v_max); + break; + } + } + ImGui::PopID(); + } + } + if (node_open) + ImGui::TreePop(); + ImGui::PopID(); + } +}; + +// Demonstrate creating a simple property editor. static void ShowExampleAppPropertyEditor(bool* p_open) { ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver); @@ -7915,11 +7922,9 @@ static void ShowExampleAppPropertyEditor(bool* p_open) } IMGUI_DEMO_MARKER("Examples/Property Editor"); - static ExampleTreeNode* tree_data = NULL; - if (tree_data == NULL) - tree_data = ExampleTree_CreateDemoTree(); - - PropertyEditor_ShowTree(tree_data); + static ExampleAppPropertyEditor property_editor; + static ExampleTreeNode* tree_data = ExampleTree_CreateDemoTree(); + property_editor.Draw(tree_data); ImGui::End(); } diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 90131c83d..ce6fed1ea 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -412,8 +412,8 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG SetNextWindowScroll(ImVec2(0.0f, 0.0f)); // Create scrolling region (without border and zero window padding) - ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None; - BeginChildEx(name, instance_id, outer_rect.GetSize(), false, child_flags); + ImGuiWindowFlags child_window_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None; + BeginChildEx(name, instance_id, outer_rect.GetSize(), ImGuiChildFlags_None, child_window_flags); table->InnerWindow = g.CurrentWindow; table->WorkRect = table->InnerWindow->WorkRect; table->OuterRect = table->InnerWindow->Rect(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 26968192b..be3d41a37 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4284,7 +4284,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges - bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), true, ImGuiWindowFlags_NoMove); + bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Border, ImGuiWindowFlags_NoMove); g.NavActivateId = backup_activate_id; PopStyleVar(3); PopStyleColor(); From 67e9aa4d3df8922dd27978eb7e93654785a0e339 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Jul 2024 14:01:02 +0200 Subject: [PATCH 0091/2359] Demo: Property Editor: add basic filter. --- imgui_demo.cpp | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 96e7e0ba6..8f16e6c31 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7823,24 +7823,40 @@ static ExampleTreeNode* ExampleTree_CreateDemoTree() //----------------------------------------------------------------------------- // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() //----------------------------------------------------------------------------- +// Some of the interactions are a bit lack-luster: +// - We would want the table scrolling window to use NavFlattened. +// - We would want pressing validating or leaving the filter to somehow restore focus. +//----------------------------------------------------------------------------- struct ExampleAppPropertyEditor { + ImGuiTextFilter Filter; + void Draw(ExampleTreeNode* root_node) { - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); - ImGuiTableFlags table_flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); + ImGui::PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); + if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_ARRAYSIZE(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) + Filter.Build(); + ImGui::PopItemFlag(); + + //ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); + ImGuiTableFlags table_flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; if (ImGui::BeginTable("##split", 2, table_flags)) { - ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("Object", ImGuiTableColumnFlags_WidthStretch, 1.0f); ImGui::TableSetupColumn("Contents", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger - ImGui::TableHeadersRow(); + //ImGui::TableSetupScrollFreeze(0, 1); + //ImGui::TableHeadersRow(); + + // Filter root node for (ExampleTreeNode* node : root_node->Childs) - DrawTreeNode(node); + if (Filter.PassFilter(node->Name)) + DrawTreeNode(node); ImGui::EndTable(); } - ImGui::PopStyleVar(); + //ImGui::PopStyleVar(); } void DrawTreeNode(ExampleTreeNode* node) From 669021be4cde053edb8c0ee5f3d247fdb265d1aa Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Jul 2024 15:23:53 +0200 Subject: [PATCH 0092/2359] Style: close button and collapse/window-menu button hover highlight made rectangular instead of round. The reason they were round in the first place was to work better with rounded windows/frames. However since the 4a8142449 rework #6749 we can naturally use a tigher bounding box and it seems to work ok either way. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 19 +++++++++---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 56b4576ed..ea3b649ab 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,7 @@ Other changes: Disabling this was previously possible for Selectable() via a direct flag but not for MenuItem(). (#1379, #1468, #2200, #4936, #5216, #7302, #7573) - This was mostly all previously in imgui_internal.h. +- Style: close button and collapse/window-menu button hover highlight made rectangular instead of round. - Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index be3d41a37..702c5ea98 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -835,17 +835,15 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) return pressed; // Render - // FIXME: Clarify this mess - ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); - ImVec2 center = bb.GetCenter(); + ImU32 bg_col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); if (hovered) - window->DrawList->AddCircleFilled(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col); - - float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; + window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_Compact); ImU32 cross_col = GetColorU32(ImGuiCol_Text); - center -= ImVec2(0.5f, 0.5f); - window->DrawList->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); - window->DrawList->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); + ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f); + float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; + window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); + window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); return pressed; } @@ -866,7 +864,8 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); ImU32 text_col = GetColorU32(ImGuiCol_Text); if (hovered || held) - window->DrawList->AddCircleFilled(bb.GetCenter() + ImVec2(0.0f, -0.5f), g.FontSize * 0.5f + 1.0f, bg_col); + window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_Compact); RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); // Switch to moving the window after mouse is moved beyond the initial drag threshold From 74a1854db9a21d83f1c91681eb295ee05129a91f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Jul 2024 15:56:45 +0200 Subject: [PATCH 0093/2359] Nav, Demo: comments. --- imgui.cpp | 5 ++++- imgui_demo.cpp | 9 ++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 605fae215..0f64254f2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1096,7 +1096,7 @@ CODE #endif // Debug options -#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL +#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction. #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. @@ -11716,6 +11716,9 @@ static bool ImGui::NavScoreItem(ImGuiNavItemData* result) if (dbx != 0.0f || dby != 0.0f) { // For non-overlapping boxes, use distance between boxes + // FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y + // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail. + // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty. dax = dbx; day = dby; dist_axial = dist_box; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8f16e6c31..dd253454f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7793,6 +7793,7 @@ static ExampleTreeNode* ExampleTree_CreateNode(const char* name, const ImGuiID u return node; } +// Create example tree data static ExampleTreeNode* ExampleTree_CreateDemoTree() { static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; @@ -7826,6 +7827,7 @@ static ExampleTreeNode* ExampleTree_CreateDemoTree() // Some of the interactions are a bit lack-luster: // - We would want the table scrolling window to use NavFlattened. // - We would want pressing validating or leaving the filter to somehow restore focus. +// - We may want more advanced filtering (child nodes) and clipper support: both will need extra work. //----------------------------------------------------------------------------- struct ExampleAppPropertyEditor @@ -7835,13 +7837,12 @@ struct ExampleAppPropertyEditor void Draw(ExampleTreeNode* root_node) { ImGui::SetNextItemWidth(-FLT_MIN); - ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); ImGui::PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_ARRAYSIZE(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) Filter.Build(); ImGui::PopItemFlag(); - //ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); ImGuiTableFlags table_flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; if (ImGui::BeginTable("##split", 2, table_flags)) { @@ -7850,13 +7851,11 @@ struct ExampleAppPropertyEditor //ImGui::TableSetupScrollFreeze(0, 1); //ImGui::TableHeadersRow(); - // Filter root node for (ExampleTreeNode* node : root_node->Childs) - if (Filter.PassFilter(node->Name)) + if (Filter.PassFilter(node->Name)) // Filter root node DrawTreeNode(node); ImGui::EndTable(); } - //ImGui::PopStyleVar(); } void DrawTreeNode(ExampleTreeNode* node) From 8bab3eab6a86bfc277abec966fd3c591bf8fd13f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Jul 2024 18:14:01 +0200 Subject: [PATCH 0094/2359] Clipper: added SeekCursorForItem() function, for use when using ImGuiListClipper::Begin(INT_MAX). (#1311) Tagging #3609 just in case we made a mistake introducing a regression (but tests are passing and have been extended). --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 30 ++++++++++++++++++------------ imgui.h | 10 ++++++++-- 3 files changed, 30 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ea3b649ab..1bb5efa53 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,10 @@ Other changes: Disabling this was previously possible for Selectable() via a direct flag but not for MenuItem(). (#1379, #1468, #2200, #4936, #5216, #7302, #7573) - This was mostly all previously in imgui_internal.h. +- Clipper: added SeekCursorForItem() function. When using ImGuiListClipper::Begin(INT_MAX) you can + can use the clipper without knowing the amount of items beforehand. (#1311) + In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) as the end of your iteration + loop to position the layout cursor correctly. This is done automatically if provided a count to Begin(). - Style: close button and collapse/window-menu button hover highlight made rectangular instead of round. - Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and diff --git a/imgui.cpp b/imgui.cpp index 0f64254f2..733a5dfe1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2911,15 +2911,6 @@ static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_ } } -static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n) -{ - // StartPosY starts from ItemsFrozen hence the subtraction - // Perform the add and multiply with double to allow seeking through larger ranges - ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData; - float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight); - ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight); -} - ImGuiListClipper::ImGuiListClipper() { memset(this, 0, sizeof(*this)); @@ -2956,6 +2947,7 @@ void ImGuiListClipper::Begin(int items_count, float items_height) data->Reset(this); data->LossynessOffset = window->DC.CursorStartPosLossyness.y; TempData = data; + StartSeekOffsetY = data->LossynessOffset; } void ImGuiListClipper::End() @@ -2966,7 +2958,7 @@ void ImGuiListClipper::End() ImGuiContext& g = *Ctx; IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name); if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0) - ImGuiListClipper_SeekCursorForItem(this, ItemsCount); + SeekCursorForItem(ItemsCount); // Restore temporary buffer and fix back pointers which may be invalidated when nesting IM_ASSERT(data->ListClipper == this); @@ -2990,6 +2982,17 @@ void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end) data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end)); } +// This is already called while stepping. +// The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper::Begin() because you couldn't step item count beforehand. +void ImGuiListClipper::SeekCursorForItem(int item_n) +{ + // - Perform the add and multiply with double to allow seeking through larger ranges. + // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight). + // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done. + float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight); + ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, ItemsHeight); +} + static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) { ImGuiContext& g = *clipper->Ctx; @@ -3053,6 +3056,9 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) const int already_submitted = clipper->DisplayEnd; if (calc_clipping) { + // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done + clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight; + if (g.LogEnabled) { // If logging is active, do not perform any clipping @@ -3100,7 +3106,7 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted); clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount); if (clipper->DisplayStart > already_submitted) //-V1051 - ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart); + clipper->SeekCursorForItem(clipper->DisplayStart); data->StepNo++; if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size) continue; @@ -3110,7 +3116,7 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), // Advance the cursor to the end of the list and then returns 'false' to end the loop. if (clipper->ItemsCount < INT_MAX) - ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount); + clipper->SeekCursorForItem(clipper->ItemsCount); return false; } diff --git a/imgui.h b/imgui.h index 0e657b46a..26965fd86 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19094 +#define IMGUI_VERSION_NUM 19095 #define IMGUI_HAS_TABLE /* @@ -2601,9 +2601,10 @@ struct ImGuiListClipper int ItemsCount; // [Internal] Number of items float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it float StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed + double StartSeekOffsetY; // [Internal] Account for frozen rows in a table and initial loss of precision in very large windows. void* TempData; // [Internal] Internal data - // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step) + // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step, and you can call SeekCursorForItem() manually if you need) // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). IMGUI_API ImGuiListClipper(); IMGUI_API ~ImGuiListClipper(); @@ -2616,6 +2617,11 @@ struct ImGuiListClipper inline void IncludeItemByIndex(int item_index) { IncludeItemsByIndex(item_index, item_index + 1); } IMGUI_API void IncludeItemsByIndex(int item_begin, int item_end); // item_end is exclusive e.g. use (42, 42+1) to make item 42 never clipped. + // Seek cursor toward given item. This is automatically called while stepping. + // - The only reason to call this is: you can use ImGuiListClipper::Begin(INT_MAX) if you don't know item count ahead of time. + // - In this case, after all steps are done, you'll want to call SeekCursorForItem(item_count). + IMGUI_API void SeekCursorForItem(int item_index); + #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9] inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] From 7c6d4ff28de462e4bc1ead3b450dfb3eb72a7b93 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Jul 2024 19:19:52 +0200 Subject: [PATCH 0095/2359] TreeNode: Internals: facilitate dissociating item ID from storage ID (useful for 1861) --- imgui_internal.h | 12 +++++++----- imgui_widgets.cpp | 44 ++++++++++++++++++++++++-------------------- 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index cefdb6ae9..4523a0228 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3461,13 +3461,15 @@ namespace ImGui IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); 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); - IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); - IMGUI_API void TreePushOverrideID(ImGuiID id); - IMGUI_API bool TreeNodeIsOpen(ImGuiID id); - IMGUI_API void TreeNodeSetOpen(ImGuiID id, bool open); - IMGUI_API bool TreeNodeUpdateNextOpen(ImGuiID id, ImGuiTreeNodeFlags flags); // Return open state. Consume previous SetNextItemOpen() data, if any. May return true when logging. IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); + // Widgets: Tree Nodes + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API void TreePushOverrideID(ImGuiID id); + IMGUI_API bool TreeNodeIsOpen(ImGuiID storage_id); + IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); + IMGUI_API bool TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags); // Return open state. Consume previous SetNextItemOpen() data, if any. May return true when logging. + // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 702c5ea98..6e0b5d990 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6195,7 +6195,8 @@ bool ImGui::TreeNode(const char* label) ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - return TreeNodeBehavior(window->GetID(label), 0, label, NULL); + ImGuiID id = window->GetID(label); + return TreeNodeBehavior(id, id, ImGuiTreeNodeFlags_None, label, NULL); } bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) @@ -6213,8 +6214,8 @@ bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - - return TreeNodeBehavior(window->GetID(label), flags, label, NULL); + ImGuiID id = window->GetID(label); + return TreeNodeBehavior(id, id, flags, label, NULL); } bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) @@ -6241,9 +6242,10 @@ bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char if (window->SkipItems) return false; + ImGuiID id = window->GetID(str_id); const char* label, *label_end; ImFormatStringToTempBufferV(&label, &label_end, fmt, args); - return TreeNodeBehavior(window->GetID(str_id), flags, label, label_end); + return TreeNodeBehavior(id, id, flags, label, label_end); } bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) @@ -6252,26 +6254,27 @@ bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char if (window->SkipItems) return false; + ImGuiID id = window->GetID(ptr_id); const char* label, *label_end; ImFormatStringToTempBufferV(&label, &label_end, fmt, args); - return TreeNodeBehavior(window->GetID(ptr_id), flags, label, label_end); + return TreeNodeBehavior(id, id, flags, label, label_end); } -bool ImGui::TreeNodeIsOpen(ImGuiID id) +bool ImGui::TreeNodeIsOpen(ImGuiID storage_id) { ImGuiContext& g = *GImGui; ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; - return storage->GetInt(id, 0) != 0; + return storage->GetInt(storage_id, 0) != 0; } -void ImGui::TreeNodeSetOpen(ImGuiID id, bool open) +void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool open) { ImGuiContext& g = *GImGui; ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; - storage->SetInt(id, open ? 1 : 0); + storage->SetInt(storage_id, open ? 1 : 0); } -bool ImGui::TreeNodeUpdateNextOpen(ImGuiID id, ImGuiTreeNodeFlags flags) +bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) { if (flags & ImGuiTreeNodeFlags_Leaf) return true; @@ -6287,16 +6290,16 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID id, ImGuiTreeNodeFlags flags) if (g.NextItemData.OpenCond & ImGuiCond_Always) { is_open = g.NextItemData.OpenVal; - TreeNodeSetOpen(id, is_open); + TreeNodeSetOpen(storage_id, is_open); } else { // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently. - const int stored_value = storage->GetInt(id, -1); + const int stored_value = storage->GetInt(storage_id, -1); if (stored_value == -1) { is_open = g.NextItemData.OpenVal; - TreeNodeSetOpen(id, is_open); + TreeNodeSetOpen(storage_id, is_open); } else { @@ -6306,7 +6309,7 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID id, ImGuiTreeNodeFlags flags) } else { - is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; + is_open = storage->GetInt(storage_id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; } // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). @@ -6333,7 +6336,8 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags) window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); } -bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +// When using public API, currently 'id == storage_id' is always true, but we separate the values to facilitate advanced user code doing storage queries outside of UI loop. +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -6386,7 +6390,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l } // Compute open and multi-select states before ItemAdd() as it clear NextItem data. - bool is_open = TreeNodeUpdateNextOpen(id, flags); + bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); bool item_add = ItemAdd(interact_bb, id); g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; g.LastItemData.DisplayRect = frame_bb; @@ -6498,7 +6502,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (toggled) { is_open = !is_open; - window->DC.StateStorage->SetInt(id, is_open); + window->DC.StateStorage->SetInt(storage_id, is_open); g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen; } } @@ -6639,8 +6643,8 @@ bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - - return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader, label); + ImGuiID id = window->GetID(label); + return TreeNodeBehavior(id, id, flags | ImGuiTreeNodeFlags_CollapsingHeader, label); } // p_visible == NULL : regular collapsing header @@ -6660,7 +6664,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFl flags |= ImGuiTreeNodeFlags_CollapsingHeader; if (p_visible) flags |= ImGuiTreeNodeFlags_AllowOverlap | (ImGuiTreeNodeFlags)ImGuiTreeNodeFlags_ClipLabelForTrailingButton; - bool is_open = TreeNodeBehavior(id, flags, label); + bool is_open = TreeNodeBehavior(id, id, flags, label); if (p_visible != NULL) { // Create a small overlapping close button From 070c046cd1fcbe694e3f19e2f5eaff9df0cb6357 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Jul 2024 20:01:55 +0200 Subject: [PATCH 0096/2359] Internals: rename recently added TreeNodeIsOpen() -> TreeNodeGetOpen(). (#7553, #1131, #2958, #2079, #722) Amend ac7d6fb --- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 4523a0228..5d8f2332c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3466,7 +3466,7 @@ namespace ImGui // Widgets: Tree Nodes IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API void TreePushOverrideID(ImGuiID id); - IMGUI_API bool TreeNodeIsOpen(ImGuiID storage_id); + IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); IMGUI_API bool TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags); // Return open state. Consume previous SetNextItemOpen() data, if any. May return true when logging. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6e0b5d990..a7ab721c8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6260,7 +6260,7 @@ bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char return TreeNodeBehavior(id, id, flags, label, label_end); } -bool ImGui::TreeNodeIsOpen(ImGuiID storage_id) +bool ImGui::TreeNodeGetOpen(ImGuiID storage_id) { ImGuiContext& g = *GImGui; ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; From c2d21ab04f26a9846fc303dae710a57446bbe4d3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 18 Jul 2024 14:02:17 +0200 Subject: [PATCH 0097/2359] Backends: SDL3: Update for API changes: SDL_GetClipboardText() string ownership change. (#7801) --- backends/imgui_impl_sdl3.cpp | 5 ++++- docs/CHANGELOG.txt | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 7bb9ca217..5cd852599 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -21,6 +21,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() string ownership change. (#7801) +// 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) // 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762). // 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea(). // 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures. @@ -115,7 +117,8 @@ static const char* ImGui_ImplSDL3_GetClipboardText(void*) ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); - bd->ClipboardTextData = SDL_GetClipboardText(); + const char* sdl_clipboard_text = SDL_GetClipboardText(); + bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : NULL; return bd->ClipboardTextData; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1bb5efa53..fea2fe5c2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -90,6 +90,7 @@ Other changes: struct description data that a real application would want to use. - Backends: Win32: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768, #4858, #2622) [@Aemony] +- Backends: SDL3: Update for API changes: SDL_GetClipboardText() string ownership change. (#7801) - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) - Backends: SDL3: Update for API changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) [@wermipls] - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. From 554db6bc0f3b8d8ebdcd596d95eaaa364f51e575 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 12:22:57 +0100 Subject: [PATCH 0098/2359] MultiSelect: WIP range-select (#1861) (rebased six millions times) --- imgui.cpp | 4 + imgui.h | 82 ++++++++++++ imgui_demo.cpp | 155 ++++++++++++++++++----- imgui_internal.h | 36 ++++-- imgui_widgets.cpp | 315 ++++++++++++++++++++++++++++++++++++++++++---- 5 files changed, 533 insertions(+), 59 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 733a5dfe1..b1e990353 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1273,6 +1273,7 @@ ImGuiStyle::ImGuiStyle() TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. + SelectableSpacing = ImVec2(0.0f,0.0f);// Horizontal and vertical spacing between selectables (by default they are canceling out the effect of ItemSpacing). SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. SeparatorTextBorderSize = 3.0f; // Thickkness of border in SeparatorText() SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). @@ -1321,6 +1322,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX; + SelectableSpacing = ImTrunc(SelectableSpacing * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); @@ -3257,6 +3259,7 @@ static const ImGuiDataVarInfo GStyleVarInfo[] = { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign + { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableSpacing) }, // ImGuiStyleVar_SelectableSpacing { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign @@ -3822,6 +3825,7 @@ void ImGui::Shutdown() g.MenusIdSubmittedThisFrame.clear(); g.InputTextState.ClearFreeMemory(); g.InputTextDeactivatedState.ClearFreeMemory(); + g.MultiSelectScopeWindow = NULL; g.SettingsWindows.clear(); g.SettingsHandlers.clear(); diff --git a/imgui.h b/imgui.h index 26965fd86..80e6ca7e1 100644 --- a/imgui.h +++ b/imgui.h @@ -44,6 +44,7 @@ Index of this file: // [SECTION] ImGuiIO // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectData) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) @@ -174,6 +175,7 @@ struct ImGuiIO; // Main configuration and I/O between your a struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiMultiSelectData; // State for a BeginMultiSelect() block struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame struct ImGuiPayload; // User data payload for drag and drop operations struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. @@ -227,6 +229,7 @@ typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: f typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag(), shared by all items typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() +typedef int ImGuiMultiSelectFlags; // -> enum ImGuiMultiSelectFlags_// Flags: for BeginMultiSelect() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() @@ -262,6 +265,10 @@ typedef ImWchar32 ImWchar; typedef ImWchar16 ImWchar; #endif +// Multi-Selection item index or identifier when using SetNextItemSelectionUserData()/BeginMultiSelect() +// (Most users are likely to use this store an item INDEX but this may be used to store a POINTER as well.) +typedef ImS64 ImGuiSelectionUserData; + // Callback and functions types typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText() typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints() @@ -661,6 +668,14 @@ namespace ImGui 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. + // Multi-selection system for Selectable() and TreeNode() functions. + // This enables standard multi-selection/range-selection idioms (CTRL+Click/Arrow, SHIFT+Click/Arrow, etc) in a way that allow items to be fully clipped (= not submitted at all) when not visible. + // Read comments near ImGuiMultiSelectData for details. + // When enabled, Selectable() and TreeNode() functions will return true when selection needs toggling. + IMGUI_API ImGuiMultiSelectData* BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected); + IMGUI_API ImGuiMultiSelectData* EndMultiSelect(); + IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); + // Widgets: List Boxes // - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. // - You can submit contents and manage your selection state however you want it, by creating e.g. Selectable() or any other items. @@ -893,6 +908,7 @@ namespace ImGui IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing. IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode(). + IMGUI_API bool IsItemToggledSelection(); // was the last item selection state toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) IMGUI_API bool IsAnyItemHovered(); // is any item hovered? IMGUI_API bool IsAnyItemActive(); // is any item active? IMGUI_API bool IsAnyItemFocused(); // is any item focused? @@ -1683,6 +1699,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign + ImGuiStyleVar_SelectableSpacing, // ImVec2 SelectableSpacing ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize ImGuiStyleVar_SeparatorTextAlign, // ImVec2 SeparatorTextAlign @@ -2127,6 +2144,7 @@ struct ImGuiStyle ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). + ImVec2 SelectableSpacing; // Horizontal and vertical spacing between selectables (by default they are canceling out the effect of ItemSpacing). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. float SeparatorTextBorderSize; // Thickkness of border in SeparatorText() ImVec2 SeparatorTextAlign; // Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). @@ -2702,6 +2720,70 @@ struct ImColor static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); } }; +//----------------------------------------------------------------------------- +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectData) +//----------------------------------------------------------------------------- + +// Flags for BeginMultiSelect(). +// This system is designed to allow mouse/keyboard multi-selection, including support for range-selection (SHIFT + click) which is difficult to re-implement manually. +// If you disable multi-selection with ImGuiMultiSelectFlags_NoMultiSelect (which is provided for consistency and flexibility), the whole BeginMultiSelect() system +// becomes largely overkill as you can handle single-selection in a simpler manner by just calling Selectable() and reacting on clicks yourself. +enum ImGuiMultiSelectFlags_ +{ + ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, + ImGuiMultiSelectFlags_NoUnselect = 1 << 1, // Disable unselecting items with CTRL+Click, CTRL+Space etc. + ImGuiMultiSelectFlags_NoSelectAll = 1 << 2, // Disable CTRL+A shortcut to set RequestSelectAll +}; + +// Abstract: +// - This system implements standard multi-selection idioms (CTRL+Click/Arrow, SHIFT+Click/Arrow, etc) in a way that allow items to be +// fully clipped (= not submitted at all) when not visible. Clipping is typically provided by ImGuiListClipper. +// Handling all of this in a single pass imgui is a little tricky, and this is why we provide those functionalities. +// Note however that if you don't need SHIFT+Click/Arrow range-select, you can handle a simpler form of multi-selection yourself, +// by reacting to click/presses on Selectable() items and checking keyboard modifiers. +// The complexity of this system here is mostly caused by the handling of range-select while optionally allowing to clip elements. +// - The work involved to deal with multi-selection differs whether you want to only submit visible items (and clip others) or submit all items +// regardless of their visibility. Clipping items is more efficient and will allow you to deal with large lists (1k~100k items) with near zero +// performance penalty, but requires a little more work on the code. If you only have a few hundreds elements in your possible selection set, +// you may as well not bother with clipping, as the cost should be negligible (as least on imgui side). +// If you are not sure, always start without clipping and you can work your way to the more optimized version afterwards. +// - The void* Src/Dst value represent a selectable object. They are the values you pass to SetNextItemMultiSelectData(). +// Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points. But the code never assume that sortable integers are used. +// - In the spirit of imgui design, your code own the selection data. So this is designed to handle all kind of selection data: instructive (store a bool inside each object), +// external array (store an array aside from your objects), set (store only selected items in a hash/map/set), using intervals (store indices in an interval tree), etc. +// Usage flow: +// 1) Call BeginMultiSelect() with the last saved value of ->RangeSrc and its selection status. As a default value for the initial frame or when, +// resetting your selection state: you may use the value for your first item or a "null" value that matches the type stored in your void*. +// 2) Honor Clear/SelectAll requests by updating your selection data. [Only required if you are using a clipper in step 4] +// 3) Set RangeSrcPassedBy=true if the RangeSrc item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] +// This is because for range-selection we need to know if we are currently "inside" or "outside" the range. +// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrc) { data->RangeSrcPassedBy = true; } +// 4) Submit your items with SetNextItemMultiSelectData() + Selectable()/TreeNode() calls. +// Call IsItemSelectionToggled() to query with the selection state has been toggled, in which you need the info immediately (before EndMultiSelect()) for your display. +// When cannot reliably return a "IsItemSelected()" value because we need to consider clipped (unprocessed) item, this is why we return a toggle event instead. +// 5) Call EndMultiSelect(). Save the value of ->RangeSrc for the next frame (you may convert the value in a format that is safe for persistance) +// 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) +// If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable() on a per-item basis. +struct ImGuiMultiSelectData +{ + bool RequestClear; // Begin, End // Request user to clear selection + bool RequestSelectAll; // Begin, End // Request user to select all + bool RequestSetRange; // End // Request user to set or clear selection in the [RangeSrc..RangeDst] range + bool RangeSrcPassedBy; // After Begin // Need to be set by user is RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. + bool RangeValue; // End // End: parameter from RequestSetRange request. True = Select Range, False = Unselect range. + void* RangeSrc; // Begin, End // End: parameter from RequestSetRange request + you need to save this value so you can pass it again next frame. / Begin: this is the value you passed to BeginMultiSelect() + void* RangeDst; // End // End: parameter from RequestSetRange request. + int RangeDirection; // End // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. + + ImGuiMultiSelectData() { Clear(); } + void Clear() + { + RequestClear = RequestSelectAll = RequestSetRange = RangeSrcPassedBy = RangeValue = false; + RangeSrc = RangeDst = NULL; + RangeDirection = 0; + } +}; + //----------------------------------------------------------------------------- // [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index dd253454f..8e7312602 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -72,6 +72,7 @@ Index of this file: // [SECTION] Demo Window / ShowDemoWindow() // - ShowDemoWindow() // - sub section: ShowDemoWindowWidgets() +// - sub section: ShowDemoWindowMultiSelect() // - sub section: ShowDemoWindowLayout() // - sub section: ShowDemoWindowPopups() // - sub section: ShowDemoWindowTables() @@ -214,6 +215,7 @@ static void ShowExampleMenuFile(); // We split the contents of the big ShowDemoWindow() function into smaller functions // (because the link time of very large functions grow non-linearly) static void ShowDemoWindowWidgets(); +static void ShowDemoWindowMultiSelect(); static void ShowDemoWindowLayout(); static void ShowDemoWindowPopups(); static void ShowDemoWindowTables(); @@ -251,6 +253,7 @@ void* GImGuiDemoMarkerCallbackUserData = NULL; //----------------------------------------------------------------------------- // - ShowDemoWindow() // - ShowDemoWindowWidgets() +// - ShowDemoWindowMultiSelect() // - ShowDemoWindowLayout() // - ShowDemoWindowPopups() // - ShowDemoWindowTables() @@ -1371,37 +1374,6 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selectables/Single Selection"); - if (ImGui::TreeNode("Selection State: Single Selection")) - { - static int selected = -1; - for (int n = 0; n < 5; n++) - { - char buf[32]; - sprintf(buf, "Object %d", n); - if (ImGui::Selectable(buf, selected == n)) - selected = n; - } - ImGui::TreePop(); - } - IMGUI_DEMO_MARKER("Widgets/Selectables/Multiple Selection"); - if (ImGui::TreeNode("Selection State: Multiple Selection")) - { - HelpMarker("Hold CTRL and click to select multiple items."); - static bool selection[5] = { false, false, false, false, false }; - for (int n = 0; n < 5; n++) - { - char buf[32]; - sprintf(buf, "Object %d", n); - if (ImGui::Selectable(buf, selection[n])) - { - if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held - memset(selection, 0, sizeof(selection)); - selection[n] ^= 1; - } - } - ImGui::TreePop(); - } IMGUI_DEMO_MARKER("Widgets/Selectables/Rendering more items on the same line"); if (ImGui::TreeNode("Rendering more items on the same line")) { @@ -1461,6 +1433,15 @@ static void ShowDemoWindowWidgets() if (winning_state) ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f))); + static float spacing = 0.0f; + ImGui::PushItemWidth(100); + ImGui::SliderFloat("SelectableSpacing", &spacing, 0, 20, "%.0f"); + ImGui::SameLine(); HelpMarker("Selectable cancel out the regular spacing between items by extending itself by ItemSpacing/2 in each direction.\nThis has two purposes:\n- Avoid the gap between items so the mouse is always hitting something.\n- Avoid the gap between items so range-selected item looks connected.\nBy changing SelectableSpacing we can enforce spacing between selectables."); + ImGui::PopItemWidth(); + ImGui::Spacing(); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8, 8)); + ImGui::PushStyleVar(ImGuiStyleVar_SelectableSpacing, ImVec2(spacing, spacing)); + for (int y = 0; y < 4; y++) for (int x = 0; x < 4; x++) { @@ -1479,8 +1460,10 @@ static void ShowDemoWindowWidgets() ImGui::PopID(); } + ImGui::PopStyleVar(2); if (winning_state) ImGui::PopStyleVar(); + ImGui::TreePop(); } IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment"); @@ -1509,6 +1492,8 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } + ShowDemoWindowMultiSelect(); + // To wire InputText() with std::string or any other custom string type, // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. IMGUI_DEMO_MARKER("Widgets/Text Input"); @@ -2785,6 +2770,113 @@ static void ShowDemoWindowWidgets() } } +static void ShowDemoWindowMultiSelect() +{ + IMGUI_DEMO_MARKER("Widgets/Selection State"); + if (ImGui::TreeNode("Selection State")) + { + HelpMarker("Selections can be built under Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data."); + + IMGUI_DEMO_MARKER("Widgets/Selection State/Single Selection"); + if (ImGui::TreeNode("Single Selection")) + { + static int selected = -1; + for (int n = 0; n < 5; n++) + { + char buf[32]; + sprintf(buf, "Object %d", n); + if (ImGui::Selectable(buf, selected == n)) + selected = n; + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (Basic)"); + if (ImGui::TreeNode("Multiple Selection (Basic)")) + { + HelpMarker("Hold CTRL and click to select multiple items."); + static bool selection[5] = { false, false, false, false, false }; + for (int n = 0; n < 5; n++) + { + char buf[32]; + sprintf(buf, "Object %d", n); + if (ImGui::Selectable(buf, selection[n])) + { + if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held + memset(selection, 0, sizeof(selection)); + selection[n] ^= 1; + } + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (Full)"); + if (ImGui::TreeNode("Multiple Selection (Full)")) + { + // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. + // In this demo we use ImGuiStorage (simple key->value storage) to avoid external dependencies but it's probably not optimal. + // In your real code you could use e.g std::unordered_set<> or your own data structure for storing selection. + // If you don't mind being limited to one view over your objects, the simplest way is to use an intrusive selection (e.g. store bool inside object, as used in examples above). + // Otherwise external set/hash/map/interval trees (storing indices, etc.) may be appropriate. + struct MySelection + { + ImGuiStorage Storage; + void Clear() { Storage.Clear(); } + void SelectAll(int count) { Storage.Data.reserve(count); Storage.Data.resize(0); for (int n = 0; n < count; n++) Storage.Data.push_back(ImGuiStoragePair((ImGuiID)n, 1)); } + void SetRange(int a, int b, int sel) { if (b < a) { int tmp = b; b = a; a = tmp; } for (int n = a; n <= b; n++) Storage.SetInt((ImGuiID)n, sel); } + bool GetSelected(int id) const { return Storage.GetInt((ImGuiID)id) != 0; } + void SetSelected(int id, bool v) { SetRange(id, id, v ? 1 : 0); } + }; + + static int selection_ref = 0; // Selection pivot (last clicked item, we need to preserve this to handle range-select) + static MySelection selection; + const char* random_names[] = + { + "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", + "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", + "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Celtuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" + }; + + int COUNT = 1000; + HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range."); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&ImGui::GetIO().ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + + if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + { + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(0, (void*)(intptr_t)selection_ref, selection.GetSelected((int)selection_ref)); + if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestSelectAll) { selection.SelectAll(COUNT); } + ImGuiListClipper clipper; + clipper.Begin(COUNT); + while (clipper.Step()) + { + if (clipper.DisplayStart > (int)selection_ref) + multi_select_data->RangeSrcPassedBy = true; + for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) + { + ImGui::PushID(n); + char label[64]; + sprintf(label, "Object %05d (category: %s)", n, random_names[n % IM_ARRAYSIZE(random_names)]); + bool item_is_selected = selection.GetSelected(n); + ImGui::SetNextItemSelectionUserData(n); + if (ImGui::Selectable(label, item_is_selected)) + selection.SetSelected(n, !item_is_selected); + ImGui::PopID(); + } + } + multi_select_data = ImGui::EndMultiSelect(); + selection_ref = (int)(intptr_t)multi_select_data->RangeSrc; + ImGui::EndListBox(); + if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestSelectAll) { selection.SelectAll(COUNT); } + if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + static void ShowDemoWindowLayout() { IMGUI_DEMO_MARKER("Layout"); @@ -6771,6 +6863,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("SelectableSpacing", (float*)&style.SelectableSpacing, 0.0f, 20.0f, "%.0f"); ImGui::SameLine(); HelpMarker("SelectableSpacing must be < ItemSpacing.\nSelectables display their highlight after canceling out the effect of ItemSpacing, so they can be look tightly packed. This setting allows to enforce spacing between them."); ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); diff --git a/imgui_internal.h b/imgui_internal.h index 5d8f2332c..63b80400c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -134,6 +134,7 @@ struct ImGuiInputTextDeactivateData;// Short term storage to backup text of a de struct ImGuiLastItemData; // Status storage for last submitted items struct ImGuiLocEntry; // A localization entry. struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only +struct ImGuiMultiSelectState; // Multi-selection state struct ImGuiNavItemData; // Result of a gamepad/keyboard directional navigation move query result struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions struct ImGuiNextWindowData; // Storage for SetNextWindow** functions @@ -854,6 +855,7 @@ enum ImGuiItemFlagsPrivate_ // Controlled by widget code ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. ImGuiItemFlags_HasSelectionUserData = 1 << 21, // false // Set by SetNextItemSelectionUserData() + ImGuiItemFlags_IsMultiSelect = 1 << 22, // false // Set by SetNextItemSelectionUserData() ImGuiItemFlags_Default_ = ImGuiItemFlags_AutoClosePopups, // Please don't change, use PushItemFlag() instead. @@ -1201,10 +1203,6 @@ struct ImGuiNextWindowData inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; } }; -// Multi-Selection item index or identifier when using SetNextItemSelectionUserData()/BeginMultiSelect() -// (Most users are likely to use this store an item INDEX but this may be used to store a POINTER as well.) -typedef ImS64 ImGuiSelectionUserData; - enum ImGuiNextItemDataFlags_ { ImGuiNextItemDataFlags_None = 0, @@ -1711,8 +1709,20 @@ struct ImGuiOldColumns // We always assume that -1 is an invalid value (which works for indices and pointers) #define ImGuiSelectionUserData_Invalid ((ImGuiSelectionUserData)-1) +#define IMGUI_HAS_MULTI_SELECT 1 #ifdef IMGUI_HAS_MULTI_SELECT -// + +struct IMGUI_API ImGuiMultiSelectState +{ + ImGuiMultiSelectData In; // The In requests are set and returned by BeginMultiSelect() + ImGuiMultiSelectData Out; // The Out requests are finalized and returned by EndMultiSelect() + bool InRangeDstPassedBy; // (Internal) set by the the item that match NavJustMovedToId when InRequestRangeSetNav is set. + bool InRequestSetRangeNav; // (Internal) set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. + + ImGuiMultiSelectState() { Clear(); } + void Clear() { In.Clear(); Out.Clear(); InRangeDstPassedBy = InRequestSetRangeNav = false; } +}; + #endif // #ifdef IMGUI_HAS_MULTI_SELECT //----------------------------------------------------------------------------- @@ -2107,6 +2117,12 @@ struct ImGuiContext ImVec2 NavWindowingAccumDeltaPos; ImVec2 NavWindowingAccumDeltaSize; + // Range-Select/Multi-Select + ImGuiID MultiSelectScopeId; + ImGuiWindow* MultiSelectScopeWindow; + ImGuiMultiSelectFlags MultiSelectFlags; + ImGuiMultiSelectState MultiSelectState; + // Render float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) @@ -2370,6 +2386,10 @@ struct ImGuiContext NavWindowingToggleLayer = false; NavWindowingToggleKey = ImGuiKey_None; + MultiSelectScopeId = 0; + MultiSelectScopeWindow = NULL; + MultiSelectFlags = 0; + DimBgRatio = 0.0f; DragDropActive = DragDropWithinSource = DragDropWithinTarget = false; @@ -3144,7 +3164,6 @@ namespace ImGui IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); IMGUI_API void PushMultiItemsWidths(int components, float width_full); - IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) IMGUI_API ImVec2 GetContentRegionMaxAbs(); IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); @@ -3325,6 +3344,10 @@ namespace ImGui IMGUI_API int TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); IMGUI_API int TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data); + // Multi-Select/Range-Select API + IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected); + IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); + // Internal 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(). @@ -3461,7 +3484,6 @@ namespace ImGui IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); 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); - IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); // Widgets: Tree Nodes IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a7ab721c8..a07908cd9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6465,6 +6465,26 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; const bool was_selected = selected; + // Multi-selection support (header) + const bool is_multi_select = (g.MultiSelectScopeWindow == window); + if (is_multi_select) + { + flags |= ImGuiTreeNodeFlags_OpenOnArrow; + MultiSelectItemHeader(id, &selected); + button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; + + // To handle drag and drop of multiple items we need to avoid clearing selection on click. + // Enabling this test makes actions using CTRL+SHIFT delay their effect on the mouse release which is annoying, but it allows drag and drop of multiple items. + if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) + button_flags |= ImGuiButtonFlags_PressedOnClick; + else + button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + } + else + { + button_flags |= ImGuiButtonFlags_NoKeyModifiers; + } + bool hovered, held; bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); bool toggled = false; @@ -6472,7 +6492,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags { if (pressed && g.DragDropHoldJustPressedId != id) { - if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id)) + if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id && !is_multi_select)) toggled = true; if (flags & ImGuiTreeNodeFlags_OpenOnArrow) toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job @@ -6507,13 +6527,23 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags } } - // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger. - if (selected != was_selected) //-V547 + // Multi-selection support (footer) + if (is_multi_select) + { + bool pressed_copy = pressed && !toggled; + MultiSelectItemFooter(id, &selected, &pressed_copy); + if (pressed) + SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, interact_bb); + } + + if (selected != was_selected) g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render const ImU32 text_col = GetColorU32(ImGuiCol_Text); ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_Compact; + if (is_multi_select) + nav_highlight_flags |= ImGuiNavHighlightFlags_AlwaysDraw; // Always show the nav rectangle if (display_frame) { // Framed type @@ -6727,8 +6757,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ImRect bb(min_x, pos.y, text_max.x, text_max.y); if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) { - const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x; - const float spacing_y = style.ItemSpacing.y; + const float spacing_x = span_all_columns ? 0.0f : ImMax(style.ItemSpacing.x - style.SelectableSpacing.x, 0.0f); + const float spacing_y = ImMax(style.ItemSpacing.y - style.SelectableSpacing.y, 0.0f); const float spacing_L = IM_TRUNC(spacing_x * 0.50f); const float spacing_U = IM_TRUNC(spacing_y * 0.50f); bb.Min.x -= spacing_L; @@ -6783,20 +6813,43 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; } if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; } + // Multi-selection support (header) + const bool is_multi_select = (g.MultiSelectScopeWindow == window); const bool was_selected = selected; + if (is_multi_select) + { + MultiSelectItemHeader(id, &selected); + button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; + + // To handle drag and drop of multiple items we need to avoid clearing selection on click. + // Enabling this test makes actions using CTRL+SHIFT delay their effect on the mouse release which is annoying, but it allows drag and drop of multiple items. + if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) + button_flags |= ImGuiButtonFlags_PressedOnClick; + else + button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + } + bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); - // Auto-select when moved into - // - This will be more fully fleshed in the range-select branch - // - This is not exposed as it won't nicely work with some user side handling of shift/control - // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons - // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope()) - // - (2) usage will fail with clipped items - // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API. - if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId) - if (g.NavJustMovedToId == id) - selected = pressed = true; + // Multi-selection support (footer) + if (is_multi_select) + { + MultiSelectItemFooter(id, &selected, &pressed); + } + else + { + // Auto-select when moved into + // - This will be more fully fleshed in the range-select branch + // - This is not exposed as it won't nicely work with some user side handling of shift/control + // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons + // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope()) + // - (2) usage will fail with clipped items + // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API. + if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId) + if (g.NavJustMovedToId == id) + selected = pressed = true; + } // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover))) @@ -6810,18 +6863,27 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (pressed) MarkItemEdited(id); - // In this branch, Selectable() cannot toggle the selection so this will never trigger. - if (selected != was_selected) //-V547 + if (selected != was_selected) g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render if (hovered || selected) { - const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + // FIXME-MULTISELECT, FIXME-STYLE: Color for 'selected' elements? ImGuiCol_HeaderSelected + ImU32 col; + if (selected && !hovered) + col = GetColorU32(ImLerp(GetStyleColorVec4(ImGuiCol_Header), GetStyleColorVec4(ImGuiCol_HeaderHovered), 0.5f)); + else + col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(bb.Min, bb.Max, col, false, 0.0f); } if (g.NavId == id) - RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_Compact | ImGuiNavHighlightFlags_NoRounding); + { + ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_Compact | ImGuiNavHighlightFlags_NoRounding; + if (is_multi_select) + nav_highlight_flags |= ImGuiNavHighlightFlags_AlwaysDraw; // Always show the nav rectangle + RenderNavHighlight(bb, id, nav_highlight_flags); + } if (span_all_columns) { @@ -6841,7 +6903,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl EndDisabled(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); - return pressed; //-V1020 + return pressed || (was_selected != selected); //-V1020 } bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) @@ -7049,16 +7111,227 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) //------------------------------------------------------------------------- // [SECTION] Widgets: Multi-Select support //------------------------------------------------------------------------- +// - BeginMultiSelect() +// - EndMultiSelect() +// - SetNextItemMultiSelectData() +// - MultiSelectItemHeader() [Internal] +// - MultiSelectItemFooter() [Internal] +//------------------------------------------------------------------------- + +ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) +{ + ImGuiContext& g = *ImGui::GetCurrentContext(); + ImGuiWindow* window = g.CurrentWindow; + + IM_ASSERT(g.MultiSelectScopeId == 0); // No recursion allowed yet (we could allow it if we deem it useful) + IM_ASSERT(g.MultiSelectFlags == 0); + + ImGuiMultiSelectState* ms = &g.MultiSelectState; + g.MultiSelectScopeId = window->IDStack.back(); + g.MultiSelectScopeWindow = window; + g.MultiSelectFlags = flags; + ms->Clear(); + + if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) + { + ms->In.RangeSrc = ms->Out.RangeSrc = range_ref; + ms->In.RangeValue = ms->Out.RangeValue = range_ref_is_selected; + } + + // Auto clear when using Navigation to move within the selection (we compare SelectScopeId so it possible to use multiple lists inside a same window) + if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.MultiSelectScopeId) + { + if (g.IO.KeyShift) + ms->InRequestSetRangeNav = true; + if (!g.IO.KeyCtrl && !g.IO.KeyShift) + ms->In.RequestClear = true; + } + + // Select All helper shortcut + if (!(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (IsWindowFocused() && g.IO.KeyCtrl && IsKeyPressed(GetKeyIndex(ImGuiKey_A))) + ms->In.RequestSelectAll = true; + +#ifdef IMGUI_DEBUG_MULTISELECT + if (ms->In.RequestClear) printf("[%05d] BeginMultiSelect: RequestClear\n", g.FrameCount); + if (ms->In.RequestSelectAll) printf("[%05d] BeginMultiSelect: RequestSelectAll\n", g.FrameCount); +#endif + + return &ms->In; +} + +ImGuiMultiSelectData* ImGui::EndMultiSelect() +{ + ImGuiContext& g = *ImGui::GetCurrentContext(); + ImGuiMultiSelectState* ms = &g.MultiSelectState; + IM_ASSERT(g.MultiSelectScopeId != 0); + if (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoUnselect) + ms->Out.RangeValue = true; + g.MultiSelectScopeId = 0; + g.MultiSelectScopeWindow = NULL; + g.MultiSelectFlags = 0; + +#ifdef IMGUI_DEBUG_MULTISELECT + if (ms->Out.RequestClear) printf("[%05d] EndMultiSelect: RequestClear\n", g.FrameCount); + if (ms->Out.RequestSelectAll) printf("[%05d] EndMultiSelect: RequestSelectAll\n", g.FrameCount); + if (ms->Out.RequestSetRange) printf("[%05d] EndMultiSelect: RequestSetRange %p..%p = %d\n", g.FrameCount, ms->Out.RangeSrc, ms->Out.RangeDst, ms->Out.RangeValue); +#endif + + return &ms->Out; +} void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data) { // Note that flags will be cleared by ItemAdd(), so it's only useful for Navigation code! // This designed so widgets can also cheaply set this before calling ItemAdd(), so we are not tied to MultiSelect api. ImGuiContext& g = *GImGui; - g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData; + if (g.MultiSelectScopeId != 0) + g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect; + else + g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData; g.NextItemData.SelectionUserData = selection_user_data; } +void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) +{ + ImGuiContext& g = *GImGui; + ImGuiMultiSelectState* ms = &g.MultiSelectState; + + IM_ASSERT((g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid) && "Forgot to call SetNextItemMultiSelectData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); + void* item_data = (void*)g.NextItemData.SelectionUserData; + + // Apply Clear/SelectAll requests requested by BeginMultiSelect(). + // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. + // If you are using a clipper (aka not submitting every element of the list) you need to process the Clear/SelectAll request after calling BeginMultiSelect() + bool selected = *p_selected; + if (ms->In.RequestClear) + selected = false; + else if (ms->In.RequestSelectAll) + selected = true; + + const bool is_range_src = (ms->In.RangeSrc == item_data); + if (is_range_src) + ms->In.RangeSrcPassedBy = true; + + // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) + // For this to work, IF the user is clipping items, they need to set RangeSrcPassedBy = true to notify the system. + if (ms->InRequestSetRangeNav) + { + IM_ASSERT(id != 0); + IM_ASSERT(g.IO.KeyShift); + const bool is_range_dst = !ms->InRangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. + if (is_range_dst) + ms->InRangeDstPassedBy = true; + if (is_range_src || is_range_dst || ms->In.RangeSrcPassedBy != ms->InRangeDstPassedBy) + selected = ms->In.RangeValue; + else if (!g.IO.KeyCtrl) + selected = false; + } + + *p_selected = selected; +} + +void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiMultiSelectState* ms = &g.MultiSelectState; + + void* item_data = (void*)g.NextItemData.SelectionUserData; + + bool selected = *p_selected; + bool pressed = *p_pressed; + bool is_ctrl = g.IO.KeyCtrl; + bool is_shift = g.IO.KeyShift; + const bool is_multiselect = (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoMultiSelect) == 0; + + // Auto-select as you navigate a list + if (g.NavJustMovedToId == id) + { + if (!g.IO.KeyCtrl) + selected = pressed = true; + else if (g.IO.KeyCtrl && g.IO.KeyShift) + pressed = true; + } + + // Right-click handling: this could be moved at the Selectable() level. + bool hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (hovered && IsMouseClicked(1)) + { + SetFocusID(g.LastItemData.ID, window); + if (!pressed && !selected) + { + pressed = true; + is_ctrl = is_shift = false; + } + } + + if (pressed) + { + //------------------------------------------------------------------------------------------------------------------------------------------------- + // ACTION | Begin | Item Old | Item New | End + //------------------------------------------------------------------------------------------------------------------------------------------------- + // Keys Navigated, Ctrl=0, Shift=0 | In.Clear | Clear -> Sel=0 | Src=item, Pressed -> Sel=1 | + // Keys Navigated, Ctrl=0, Shift=1 | n/a | n/a | Dst=item, Pressed -> Sel=1, Out.Clear, Out.SetRange=1 | Clear + SetRange + // Keys Navigated, Ctrl=1, Shift=1 | n/a | n/a | Dst=item, Pressed -> Sel=Src, Out.Clear, Out.SetRange=Src | Clear + SetRange + // Mouse Pressed, Ctrl=0, Shift=0 | n/a | n/a (Sel=1) | Src=item, Pressed -> Sel=1, Out.Clear, Out.SetRange=1 | Clear + SetRange + // Mouse Pressed, Ctrl=0, Shift=1 | n/a | n/a | Dst=item, Pressed -> Sel=1, Out.Clear, Out.SetRange=1 | Clear + SetRange + //------------------------------------------------------------------------------------------------------------------------------------------------- + + ImGuiInputSource input_source = (g.NavJustMovedToId != 0 && g.NavWindow == window && g.NavJustMovedToId == g.LastItemData.ID) ? g.NavInputSource : ImGuiInputSource_Mouse; + if (is_shift && is_multiselect) + { + ms->Out.RequestSetRange = true; + ms->Out.RangeDst = item_data; + if (!is_ctrl) + ms->Out.RangeValue = true; + ms->Out.RangeDirection = ms->In.RangeSrcPassedBy ? +1 : -1; + } + else + { + selected = (!is_ctrl || (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoUnselect)) ? true : !selected; + ms->Out.RangeSrc = ms->Out.RangeDst = item_data; + ms->Out.RangeValue = selected; + } + + if (input_source == ImGuiInputSource_Mouse) + { + // Mouse click without CTRL clears the selection, unless the clicked item is already selected + bool preserve_existing_selection = g.DragDropActive; + if (is_multiselect && !is_ctrl && !preserve_existing_selection) + ms->Out.RequestClear = true; + if (is_multiselect && !is_shift && !preserve_existing_selection && ms->Out.RequestClear) + { + // For toggle selection unless there is a Clear request, we can handle it completely locally without sending a RangeSet request. + IM_ASSERT(ms->Out.RangeSrc == ms->Out.RangeDst); // Setup by block above + ms->Out.RequestSetRange = true; + ms->Out.RangeValue = selected; + ms->Out.RangeDirection = +1; + } + if (!is_multiselect) + { + // Clear selection, set single item range + IM_ASSERT(ms->Out.RangeSrc == item_data && ms->Out.RangeDst == item_data); // Setup by block above + ms->Out.RequestClear = true; + ms->Out.RequestSetRange = true; + } + } + else if (input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) + { + if (!is_multiselect) + ms->Out.RequestClear = true; + else if (is_shift && !is_ctrl && is_multiselect) + ms->Out.RequestClear = true; + } + } + + // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) + if (ms->Out.RangeSrc == item_data && is_ctrl && is_shift && is_multiselect && !(g.MultiSelectFlags & ImGuiMultiSelectFlags_NoUnselect)) + ms->Out.RangeValue = selected; + + *p_selected = selected; + *p_pressed = pressed; +} //------------------------------------------------------------------------- // [SECTION] Widgets: ListBox From 8947c35fa1e22084a2b832e1236195ac09810361 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Dec 2020 19:36:04 +0100 Subject: [PATCH 0099/2359] MultiSelect: Removed SelectableSpacing as I'm not sure it is of use for now (history insert) --- imgui.cpp | 3 --- imgui.h | 2 -- imgui_demo.cpp | 12 ------------ imgui_widgets.cpp | 4 ++-- 4 files changed, 2 insertions(+), 19 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b1e990353..3cdd6fbde 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1273,7 +1273,6 @@ ImGuiStyle::ImGuiStyle() TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. - SelectableSpacing = ImVec2(0.0f,0.0f);// Horizontal and vertical spacing between selectables (by default they are canceling out the effect of ItemSpacing). SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. SeparatorTextBorderSize = 3.0f; // Thickkness of border in SeparatorText() SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). @@ -1322,7 +1321,6 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX; - SelectableSpacing = ImTrunc(SelectableSpacing * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); @@ -3259,7 +3257,6 @@ static const ImGuiDataVarInfo GStyleVarInfo[] = { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableSpacing) }, // ImGuiStyleVar_SelectableSpacing { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign diff --git a/imgui.h b/imgui.h index 80e6ca7e1..0016ad7e9 100644 --- a/imgui.h +++ b/imgui.h @@ -1699,7 +1699,6 @@ enum ImGuiStyleVar_ ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign - ImGuiStyleVar_SelectableSpacing, // ImVec2 SelectableSpacing ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize ImGuiStyleVar_SeparatorTextAlign, // ImVec2 SeparatorTextAlign @@ -2144,7 +2143,6 @@ struct ImGuiStyle ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). - ImVec2 SelectableSpacing; // Horizontal and vertical spacing between selectables (by default they are canceling out the effect of ItemSpacing). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. float SeparatorTextBorderSize; // Thickkness of border in SeparatorText() ImVec2 SeparatorTextAlign; // Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8e7312602..bab08ce9b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1433,15 +1433,6 @@ static void ShowDemoWindowWidgets() if (winning_state) ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f))); - static float spacing = 0.0f; - ImGui::PushItemWidth(100); - ImGui::SliderFloat("SelectableSpacing", &spacing, 0, 20, "%.0f"); - ImGui::SameLine(); HelpMarker("Selectable cancel out the regular spacing between items by extending itself by ItemSpacing/2 in each direction.\nThis has two purposes:\n- Avoid the gap between items so the mouse is always hitting something.\n- Avoid the gap between items so range-selected item looks connected.\nBy changing SelectableSpacing we can enforce spacing between selectables."); - ImGui::PopItemWidth(); - ImGui::Spacing(); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8, 8)); - ImGui::PushStyleVar(ImGuiStyleVar_SelectableSpacing, ImVec2(spacing, spacing)); - for (int y = 0; y < 4; y++) for (int x = 0; x < 4; x++) { @@ -1460,10 +1451,8 @@ static void ShowDemoWindowWidgets() ImGui::PopID(); } - ImGui::PopStyleVar(2); if (winning_state) ImGui::PopStyleVar(); - ImGui::TreePop(); } IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment"); @@ -6863,7 +6852,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("SelectableSpacing", (float*)&style.SelectableSpacing, 0.0f, 20.0f, "%.0f"); ImGui::SameLine(); HelpMarker("SelectableSpacing must be < ItemSpacing.\nSelectables display their highlight after canceling out the effect of ItemSpacing, so they can be look tightly packed. This setting allows to enforce spacing between them."); ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a07908cd9..89f7e6716 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6757,8 +6757,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ImRect bb(min_x, pos.y, text_max.x, text_max.y); if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) { - const float spacing_x = span_all_columns ? 0.0f : ImMax(style.ItemSpacing.x - style.SelectableSpacing.x, 0.0f); - const float spacing_y = ImMax(style.ItemSpacing.y - style.SelectableSpacing.y, 0.0f); + const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x; + const float spacing_y = style.ItemSpacing.y; const float spacing_L = IM_TRUNC(spacing_x * 0.50f); const float spacing_U = IM_TRUNC(spacing_y * 0.50f); bb.Min.x -= spacing_L; From 57da88093f54178b349e097e35b5ce12fb582d36 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 15 Apr 2019 19:13:36 +0200 Subject: [PATCH 0100/2359] MultiSelect: Added IMGUI_HAS_MULTI_SELECT define. Fixed right-click toggling selection without clearing active id, could lead to MarkItemEdited() asserting. Fixed demo. --- imgui.h | 2 ++ imgui_internal.h | 1 - imgui_widgets.cpp | 4 +++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 0016ad7e9..3b92a9ff8 100644 --- a/imgui.h +++ b/imgui.h @@ -2722,6 +2722,8 @@ struct ImColor // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectData) //----------------------------------------------------------------------------- +#define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. + // Flags for BeginMultiSelect(). // This system is designed to allow mouse/keyboard multi-selection, including support for range-selection (SHIFT + click) which is difficult to re-implement manually. // If you disable multi-selection with ImGuiMultiSelectFlags_NoMultiSelect (which is provided for consistency and flexibility), the whole BeginMultiSelect() system diff --git a/imgui_internal.h b/imgui_internal.h index 63b80400c..41dac9c90 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1709,7 +1709,6 @@ struct ImGuiOldColumns // We always assume that -1 is an invalid value (which works for indices and pointers) #define ImGuiSelectionUserData_Invalid ((ImGuiSelectionUserData)-1) -#define IMGUI_HAS_MULTI_SELECT 1 #ifdef IMGUI_HAS_MULTI_SELECT struct IMGUI_API ImGuiMultiSelectState diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 89f7e6716..53f0c57ac 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7258,7 +7258,9 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) bool hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); if (hovered && IsMouseClicked(1)) { - SetFocusID(g.LastItemData.ID, window); + if (g.ActiveId != 0 && g.ActiveId != id) + ClearActiveID(); + SetFocusID(id, window); if (!pressed && !selected) { pressed = true; From 17c4c2154a17ba38108c60883285af71514d04dc Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 21 Dec 2019 23:21:23 +0100 Subject: [PATCH 0101/2359] MultiSelect: Demo sharing selection helper code. Fixed static analyzer warnings. --- imgui.h | 8 ++++--- imgui_demo.cpp | 56 +++++++++++++++++++++++++++++++---------------- imgui_widgets.cpp | 10 ++++----- 3 files changed, 47 insertions(+), 27 deletions(-) diff --git a/imgui.h b/imgui.h index 3b92a9ff8..6acdab580 100644 --- a/imgui.h +++ b/imgui.h @@ -2725,11 +2725,13 @@ struct ImColor #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. // Flags for BeginMultiSelect(). -// This system is designed to allow mouse/keyboard multi-selection, including support for range-selection (SHIFT + click) which is difficult to re-implement manually. -// If you disable multi-selection with ImGuiMultiSelectFlags_NoMultiSelect (which is provided for consistency and flexibility), the whole BeginMultiSelect() system -// becomes largely overkill as you can handle single-selection in a simpler manner by just calling Selectable() and reacting on clicks yourself. +// This system is designed to allow mouse/keyboard multi-selection, including support for range-selection (SHIFT + click), +// which is difficult to re-implement manually. If you disable multi-selection with ImGuiMultiSelectFlags_NoMultiSelect +// (which is provided for consistency and flexibility), the whole BeginMultiSelect() system becomes largely overkill as +// you can handle single-selection in a simpler manner by just calling Selectable() and reacting on clicks yourself. enum ImGuiMultiSelectFlags_ { + ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, ImGuiMultiSelectFlags_NoUnselect = 1 << 1, // Disable unselecting items with CTRL+Click, CTRL+Space etc. ImGuiMultiSelectFlags_NoSelectAll = 1 << 2, // Disable CTRL+A shortcut to set RequestSelectAll diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bab08ce9b..291410c4d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2759,6 +2759,38 @@ static void ShowDemoWindowWidgets() } } +// [Advanced] Helper class to simulate storage of a multi-selection state, used by the advanced multi-selection demos. +// We use ImGuiStorage (simple key->value storage) to avoid external dependencies but it's probably not optimal. +// To store a single-selection: +// - You only need a single variable and don't need any of this! +// To store a multi-selection, in your real application you could: +// - Use intrusively stored selection (e.g. 'bool IsSelected' inside your object). This is by far the simplest +// way to store your selection data, but it means you cannot have multiple simultaneous views over your objects. +// This is what may of the simpler demos in this file are using (so they are not using this class). +// - Otherwise, any externally stored unordered_set/set/hash/map/interval trees (storing indices, objects id, etc.) +// are generally appropriate. Even a large array of bool might work for you... +struct ExampleSelectionData +{ + ImGuiStorage Storage; + int SelectedCount; // Number of selected items (storage will keep this updated) + + ExampleSelectionData() { Clear(); } + void Clear() { Storage.Clear(); SelectedCount = 0; } + bool GetSelected(int id) const { return Storage.GetInt((ImGuiID)id) != 0; } + void SetSelected(int id, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)id); if (*p_int == (int)v) return; SelectedCount = v ? (SelectedCount + 1) : (SelectedCount - 1); *p_int = (bool)v; } + int GetSelectedCount() const { return SelectedCount; } + + // When using SelectAll() / SetRange() we assume that our objects ID are indices. + // In this demo we always store selection using indices and never in another manner (e.g. object ID or pointers). + // If your selection system is storing selection using object ID and you want to support Shift+Click range-selection, + // you will need a way to iterate from one object to another given the ID you use. + // You are likely to need some kind of data structure to convert 'view index' from/to 'ID'. + // FIXME-MULTISELECT: Would be worth providing a demo of doing this. + // FIXME-MULTISELECT: SetRange() is currently very inefficient since it doesn't take advantage of the fact that ImGuiStorage stores sorted key. + void SetRange(int a, int b, bool v) { if (b < a) { int tmp = b; b = a; a = tmp; } for (int n = a; n <= b; n++) SetSelected(n, v); } + void SelectAll(int count) { Storage.Data.resize(count); for (int n = 0; n < count; n++) Storage.Data[n] = ImGuiStoragePair((ImGuiID)n, 1); SelectedCount = count; } // This could be using SetRange() but this is faster. +}; + static void ShowDemoWindowMultiSelect() { IMGUI_DEMO_MARKER("Widgets/Selection State"); @@ -2803,22 +2835,8 @@ static void ShowDemoWindowMultiSelect() if (ImGui::TreeNode("Multiple Selection (Full)")) { // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. - // In this demo we use ImGuiStorage (simple key->value storage) to avoid external dependencies but it's probably not optimal. - // In your real code you could use e.g std::unordered_set<> or your own data structure for storing selection. - // If you don't mind being limited to one view over your objects, the simplest way is to use an intrusive selection (e.g. store bool inside object, as used in examples above). - // Otherwise external set/hash/map/interval trees (storing indices, etc.) may be appropriate. - struct MySelection - { - ImGuiStorage Storage; - void Clear() { Storage.Clear(); } - void SelectAll(int count) { Storage.Data.reserve(count); Storage.Data.resize(0); for (int n = 0; n < count; n++) Storage.Data.push_back(ImGuiStoragePair((ImGuiID)n, 1)); } - void SetRange(int a, int b, int sel) { if (b < a) { int tmp = b; b = a; a = tmp; } for (int n = a; n <= b; n++) Storage.SetInt((ImGuiID)n, sel); } - bool GetSelected(int id) const { return Storage.GetInt((ImGuiID)id) != 0; } - void SetSelected(int id, bool v) { SetRange(id, id, v ? 1 : 0); } - }; - static int selection_ref = 0; // Selection pivot (last clicked item, we need to preserve this to handle range-select) - static MySelection selection; + static ExampleSelectionData selection; const char* random_names[] = { "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", @@ -2832,8 +2850,8 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(0, (void*)(intptr_t)selection_ref, selection.GetSelected((int)selection_ref)); - if (multi_select_data->RequestClear) { selection.Clear(); } + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection_ref, selection.GetSelected((int)selection_ref)); + if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(COUNT); } ImGuiListClipper clipper; clipper.Begin(COUNT); @@ -2856,9 +2874,9 @@ static void ShowDemoWindowMultiSelect() multi_select_data = ImGui::EndMultiSelect(); selection_ref = (int)(intptr_t)multi_select_data->RangeSrc; ImGui::EndListBox(); - if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(COUNT); } - if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } } ImGui::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 53f0c57ac..091efc99b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7248,10 +7248,10 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Auto-select as you navigate a list if (g.NavJustMovedToId == id) { - if (!g.IO.KeyCtrl) - selected = pressed = true; - else if (g.IO.KeyCtrl && g.IO.KeyShift) + if (is_ctrl && is_shift) pressed = true; + else if (!is_ctrl) + selected = pressed = true; } // Right-click handling: this could be moved at the Selectable() level. @@ -7320,9 +7320,9 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } else if (input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) { - if (!is_multiselect) + if (is_multiselect && is_shift && !is_ctrl) ms->Out.RequestClear = true; - else if (is_shift && !is_ctrl && is_multiselect) + else if (!is_multiselect) ms->Out.RequestClear = true; } } From 4afbfd5e71913e1e6f5de44f822a159fa8fa868f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 14 Jan 2020 16:18:55 +0100 Subject: [PATCH 0102/2359] MultiSelect: Renamed SetNextItemMultiSelectData() to SetNextItemSelectionUserData() --- imgui.h | 4 ++-- imgui_demo.cpp | 10 +++++++++- imgui_widgets.cpp | 4 ++-- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index 6acdab580..e57a29752 100644 --- a/imgui.h +++ b/imgui.h @@ -2749,7 +2749,7 @@ enum ImGuiMultiSelectFlags_ // performance penalty, but requires a little more work on the code. If you only have a few hundreds elements in your possible selection set, // you may as well not bother with clipping, as the cost should be negligible (as least on imgui side). // If you are not sure, always start without clipping and you can work your way to the more optimized version afterwards. -// - The void* Src/Dst value represent a selectable object. They are the values you pass to SetNextItemMultiSelectData(). +// - The void* Src/Dst value represent a selectable object. They are the values you pass to SetNextItemSelectionUserData(). // Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points. But the code never assume that sortable integers are used. // - In the spirit of imgui design, your code own the selection data. So this is designed to handle all kind of selection data: instructive (store a bool inside each object), // external array (store an array aside from your objects), set (store only selected items in a hash/map/set), using intervals (store indices in an interval tree), etc. @@ -2760,7 +2760,7 @@ enum ImGuiMultiSelectFlags_ // 3) Set RangeSrcPassedBy=true if the RangeSrc item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] // This is because for range-selection we need to know if we are currently "inside" or "outside" the range. // If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrc) { data->RangeSrcPassedBy = true; } -// 4) Submit your items with SetNextItemMultiSelectData() + Selectable()/TreeNode() calls. +// 4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // Call IsItemSelectionToggled() to query with the selection state has been toggled, in which you need the info immediately (before EndMultiSelect()) for your display. // When cannot reliably return a "IsItemSelected()" value because we need to consider clipped (unprocessed) item, this is why we return a toggle event instead. // 5) Call EndMultiSelect(). Save the value of ->RangeSrc for the next frame (you may convert the value in a format that is safe for persistance) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 291410c4d..fca877fd5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2845,7 +2845,7 @@ static void ShowDemoWindowMultiSelect() }; int COUNT = 1000; - HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range."); + HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range. Keyboard is also supported."); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&ImGui::GetIO().ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) @@ -2853,6 +2853,7 @@ static void ShowDemoWindowMultiSelect() ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection_ref, selection.GetSelected((int)selection_ref)); if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(COUNT); } + ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); ImGuiListClipper clipper; clipper.Begin(COUNT); while (clipper.Step()) @@ -2865,6 +2866,13 @@ static void ShowDemoWindowMultiSelect() char label[64]; sprintf(label, "Object %05d (category: %s)", n, random_names[n % IM_ARRAYSIZE(random_names)]); bool item_is_selected = selection.GetSelected(n); + + // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part + // of the selection scope doesn't erroneously alter our selection. + ImVec4 dummy_col = ImColor((ImU32)ImGui::GetID(label)); + ImGui::ColorButton("##", dummy_col, ImGuiColorEditFlags_NoTooltip, color_button_sz); + ImGui::SameLine(); + ImGui::SetNextItemSelectionUserData(n); if (ImGui::Selectable(label, item_is_selected)) selection.SetSelected(n, !item_is_selected); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 091efc99b..62b063d18 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7113,7 +7113,7 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) //------------------------------------------------------------------------- // - BeginMultiSelect() // - EndMultiSelect() -// - SetNextItemMultiSelectData() +// - SetNextItemSelectionUserData() // - MultiSelectItemHeader() [Internal] // - MultiSelectItemFooter() [Internal] //------------------------------------------------------------------------- @@ -7197,7 +7197,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) ImGuiContext& g = *GImGui; ImGuiMultiSelectState* ms = &g.MultiSelectState; - IM_ASSERT((g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid) && "Forgot to call SetNextItemMultiSelectData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); + IM_ASSERT((g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid) && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); void* item_data = (void*)g.NextItemData.SelectionUserData; // Apply Clear/SelectAll requests requested by BeginMultiSelect(). From 9c7183dd048ecd8f4c17f54662ca067c997d3bfb Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 13 Jan 2020 15:05:53 +0100 Subject: [PATCH 0103/2359] MultiSelect: Transition to use FocusScope bits merged in master. Preserve ability to shift+arrow into an item that is part of FocusScope but doesn't carry a selection without breaking selection. --- imgui.cpp | 1 - imgui_internal.h | 15 ++++++++------- imgui_widgets.cpp | 37 +++++++++++++++++++++++-------------- 3 files changed, 31 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3cdd6fbde..733a5dfe1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3822,7 +3822,6 @@ void ImGui::Shutdown() g.MenusIdSubmittedThisFrame.clear(); g.InputTextState.ClearFreeMemory(); g.InputTextDeactivatedState.ClearFreeMemory(); - g.MultiSelectScopeWindow = NULL; g.SettingsWindows.clear(); g.SettingsHandlers.clear(); diff --git a/imgui_internal.h b/imgui_internal.h index 41dac9c90..dd5853466 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1210,6 +1210,7 @@ enum ImGuiNextItemDataFlags_ ImGuiNextItemDataFlags_HasOpen = 1 << 1, ImGuiNextItemDataFlags_HasShortcut = 1 << 2, ImGuiNextItemDataFlags_HasRefVal = 1 << 3, + ImGuiNextItemDataFlags_HasSelectionData = 1 << 4, }; struct ImGuiNextItemData @@ -1217,6 +1218,7 @@ struct ImGuiNextItemData ImGuiNextItemDataFlags Flags; ImGuiItemFlags ItemFlags; // Currently only tested/used for ImGuiItemFlags_AllowOverlap. // Non-flags members are NOT cleared by ItemAdd() meaning they are still valid during NavProcessItem() + ImGuiID FocusScopeId; // Set by SetNextItemSelectionUserData() (!= 0 signify value has been set) ImGuiSelectionUserData SelectionUserData; // Set by SetNextItemSelectionUserData() (note that NULL/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) float Width; // Set by SetNextItemWidth() ImGuiKeyChord Shortcut; // Set by SetNextItemShortcut() @@ -1713,13 +1715,14 @@ struct ImGuiOldColumns struct IMGUI_API ImGuiMultiSelectState { + ImGuiID FocusScopeId; // Same as CurrentWindow->DC.FocusScopeIdCurrent (unless another selection scope was pushed manually) ImGuiMultiSelectData In; // The In requests are set and returned by BeginMultiSelect() ImGuiMultiSelectData Out; // The Out requests are finalized and returned by EndMultiSelect() bool InRangeDstPassedBy; // (Internal) set by the the item that match NavJustMovedToId when InRequestRangeSetNav is set. bool InRequestSetRangeNav; // (Internal) set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. ImGuiMultiSelectState() { Clear(); } - void Clear() { In.Clear(); Out.Clear(); InRangeDstPassedBy = InRequestSetRangeNav = false; } + void Clear() { FocusScopeId = 0; In.Clear(); Out.Clear(); InRangeDstPassedBy = InRequestSetRangeNav = false; } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT @@ -2117,10 +2120,9 @@ struct ImGuiContext ImVec2 NavWindowingAccumDeltaSize; // Range-Select/Multi-Select - ImGuiID MultiSelectScopeId; - ImGuiWindow* MultiSelectScopeWindow; + bool MultiSelectEnabled; ImGuiMultiSelectFlags MultiSelectFlags; - ImGuiMultiSelectState MultiSelectState; + ImGuiMultiSelectState MultiSelectState; // We currently don't support recursing/stacking multi-select // Render float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) @@ -2385,9 +2387,8 @@ struct ImGuiContext NavWindowingToggleLayer = false; NavWindowingToggleKey = ImGuiKey_None; - MultiSelectScopeId = 0; - MultiSelectScopeWindow = NULL; - MultiSelectFlags = 0; + MultiSelectEnabled = false; + MultiSelectFlags = ImGuiMultiSelectFlags_None; DimBgRatio = 0.0f; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 62b063d18..4da256960 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6466,7 +6466,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags const bool was_selected = selected; // Multi-selection support (header) - const bool is_multi_select = (g.MultiSelectScopeWindow == window); + const bool is_multi_select = g.MultiSelectEnabled; if (is_multi_select) { flags |= ImGuiTreeNodeFlags_OpenOnArrow; @@ -6814,7 +6814,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; } // Multi-selection support (header) - const bool is_multi_select = (g.MultiSelectScopeWindow == window); + const bool is_multi_select = g.MultiSelectEnabled; const bool was_selected = selected; if (is_multi_select) { @@ -7120,17 +7120,20 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) { - ImGuiContext& g = *ImGui::GetCurrentContext(); + ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(g.MultiSelectScopeId == 0); // No recursion allowed yet (we could allow it if we deem it useful) + IM_ASSERT(g.MultiSelectEnabled == false); // No recursion allowed yet (we could allow it if we deem it useful) IM_ASSERT(g.MultiSelectFlags == 0); + IM_ASSERT(g.MultiSelectState.FocusScopeId == 0); + // FIXME: BeginFocusScope() ImGuiMultiSelectState* ms = &g.MultiSelectState; - g.MultiSelectScopeId = window->IDStack.back(); - g.MultiSelectScopeWindow = window; - g.MultiSelectFlags = flags; ms->Clear(); + ms->FocusScopeId = window->IDStack.back(); + PushFocusScope(ms->FocusScopeId); + g.MultiSelectEnabled = true; + g.MultiSelectFlags = flags; if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) { @@ -7139,7 +7142,7 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* } // Auto clear when using Navigation to move within the selection (we compare SelectScopeId so it possible to use multiple lists inside a same window) - if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.MultiSelectScopeId) + if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) { if (g.IO.KeyShift) ms->InRequestSetRangeNav = true; @@ -7162,14 +7165,16 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ImGuiMultiSelectData* ImGui::EndMultiSelect() { - ImGuiContext& g = *ImGui::GetCurrentContext(); + ImGuiContext& g = *GImGui; ImGuiMultiSelectState* ms = &g.MultiSelectState; - IM_ASSERT(g.MultiSelectScopeId != 0); + IM_ASSERT(g.MultiSelectState.FocusScopeId == g.CurrentFocusScopeId); + if (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoUnselect) ms->Out.RangeValue = true; - g.MultiSelectScopeId = 0; - g.MultiSelectScopeWindow = NULL; - g.MultiSelectFlags = 0; + g.MultiSelectState.FocusScopeId = 0; + PopFocusScope(); + g.MultiSelectEnabled = false; + g.MultiSelectFlags = ImGuiMultiSelectFlags_None; #ifdef IMGUI_DEBUG_MULTISELECT if (ms->Out.RequestClear) printf("[%05d] EndMultiSelect: RequestClear\n", g.FrameCount); @@ -7185,18 +7190,22 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d // Note that flags will be cleared by ItemAdd(), so it's only useful for Navigation code! // This designed so widgets can also cheaply set this before calling ItemAdd(), so we are not tied to MultiSelect api. ImGuiContext& g = *GImGui; - if (g.MultiSelectScopeId != 0) + if (g.MultiSelectState.FocusScopeId != 0) g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect; else g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData; g.NextItemData.SelectionUserData = selection_user_data; + g.NextItemData.FocusScopeId = g.CurrentFocusScopeId; } void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) { ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; ImGuiMultiSelectState* ms = &g.MultiSelectState; + IM_UNUSED(window); + IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); IM_ASSERT((g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid) && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); void* item_data = (void*)g.NextItemData.SelectionUserData; From 7abda179af618da2114153b00119dfe878652adc Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Mar 2020 21:57:18 +0100 Subject: [PATCH 0104/2359] MultiSelect: Fix for TreeNode following merge of 011d4755. Demo: basic test for tree nodes. --- imgui_demo.cpp | 56 ++++++++++++++++++++++++++++++++++++----------- imgui_widgets.cpp | 10 +++++---- 2 files changed, 49 insertions(+), 17 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index fca877fd5..c571a922e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2844,18 +2844,29 @@ static void ShowDemoWindowMultiSelect() "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Celtuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" }; - int COUNT = 1000; - HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range. Keyboard is also supported."); + // Test both Selectable() and TreeNode() widgets + enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; + static WidgetType widget_type = WidgetType_TreeNode; + if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } + ImGui::SameLine(); + if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&ImGui::GetIO().ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::SameLine(); HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range. Keyboard is also supported."); + // Open a scrolling region + const int ITEMS_COUNT = 1000; if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection_ref, selection.GetSelected((int)selection_ref)); - if (multi_select_data->RequestClear) { selection.Clear(); } - if (multi_select_data->RequestSelectAll) { selection.SelectAll(COUNT); } ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); + if (widget_type == WidgetType_TreeNode) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); + + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection_ref, selection.GetSelected(selection_ref)); + if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } + ImGuiListClipper clipper; - clipper.Begin(COUNT); + clipper.Begin(ITEMS_COUNT); while (clipper.Step()) { if (clipper.DisplayStart > (int)selection_ref) @@ -2868,23 +2879,42 @@ static void ShowDemoWindowMultiSelect() bool item_is_selected = selection.GetSelected(n); // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part - // of the selection scope doesn't erroneously alter our selection. - ImVec4 dummy_col = ImColor((ImU32)ImGui::GetID(label)); - ImGui::ColorButton("##", dummy_col, ImGuiColorEditFlags_NoTooltip, color_button_sz); + // of the selection scope doesn't erroneously alter our selection (FIXME-TESTS: Add a test for that!). + ImU32 dummy_col = (ImU32)ImGui::GetID(label); + ImGui::ColorButton("##", ImColor(dummy_col), ImGuiColorEditFlags_NoTooltip, color_button_sz); ImGui::SameLine(); ImGui::SetNextItemSelectionUserData(n); - if (ImGui::Selectable(label, item_is_selected)) - selection.SetSelected(n, !item_is_selected); + if (widget_type == WidgetType_Selectable) + { + if (ImGui::Selectable(label, item_is_selected)) + selection.SetSelected(n, !item_is_selected); + } + else if (widget_type == WidgetType_TreeNode) + { + ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnDoubleClick; + if (item_is_selected) + tree_node_flags |= ImGuiTreeNodeFlags_Selected; + ImGui::TreeNodeEx(label, tree_node_flags); + if (ImGui::IsItemToggledSelection()) + selection.SetSelected(n, !item_is_selected); + } + ImGui::PopID(); } } + + // Apply multi-select requests multi_select_data = ImGui::EndMultiSelect(); selection_ref = (int)(intptr_t)multi_select_data->RangeSrc; - ImGui::EndListBox(); if (multi_select_data->RequestClear) { selection.Clear(); } - if (multi_select_data->RequestSelectAll) { selection.SelectAll(COUNT); } + if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + + if (widget_type == WidgetType_TreeNode) + ImGui::PopStyleVar(); + + ImGui::EndListBox(); } ImGui::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4da256960..9f546a5e3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6443,8 +6443,6 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags const float arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x; const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x; const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2); - if (window != g.HoveredWindow || !is_mouse_x_over_arrow) - button_flags |= ImGuiButtonFlags_NoKeyModifiers; // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. @@ -6469,12 +6467,15 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags const bool is_multi_select = g.MultiSelectEnabled; if (is_multi_select) { - flags |= ImGuiTreeNodeFlags_OpenOnArrow; MultiSelectItemHeader(id, &selected); button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; + // We absolutely need to distinguish open vs select so this is the default when multi-select is enabled. + flags |= ImGuiTreeNodeFlags_OpenOnArrow; + // To handle drag and drop of multiple items we need to avoid clearing selection on click. // Enabling this test makes actions using CTRL+SHIFT delay their effect on the mouse release which is annoying, but it allows drag and drop of multiple items. + // FIXME-MULTISELECT: Consider opt-in for drag and drop behavior in ImGuiMultiSelectFlags? if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) button_flags |= ImGuiButtonFlags_PressedOnClick; else @@ -6482,7 +6483,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags } else { - button_flags |= ImGuiButtonFlags_NoKeyModifiers; + if (window != g.HoveredWindow || !is_mouse_x_over_arrow) + button_flags |= ImGuiButtonFlags_NoKeyModifiers; } bool hovered, held; From 9aeebd24f77fdc82b8e1c8fb7ed51ea53d981fd3 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 20 Mar 2020 12:34:52 +0100 Subject: [PATCH 0105/2359] MultiSelect: Fixed CTRL+A not testing focus scope id. Fixed CTRL+A not testing active id. Added demo code. Comments. --- imgui_demo.cpp | 43 ++++++++++++++++++++++++++++++++++--------- imgui_widgets.cpp | 6 ++++-- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c571a922e..87e2e0bac 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2769,26 +2769,28 @@ static void ShowDemoWindowWidgets() // This is what may of the simpler demos in this file are using (so they are not using this class). // - Otherwise, any externally stored unordered_set/set/hash/map/interval trees (storing indices, objects id, etc.) // are generally appropriate. Even a large array of bool might work for you... +// - If you need to handle extremely large selections, it might be advantageous to support a "negative" mode in +// your storage, so "Select All" becomes "Negative=1, Clear" and then sparse unselect can add to the storage. struct ExampleSelectionData { ImGuiStorage Storage; - int SelectedCount; // Number of selected items (storage will keep this updated) + int SelectionSize; // Number of selected items (== number of 1 in the Storage) ExampleSelectionData() { Clear(); } - void Clear() { Storage.Clear(); SelectedCount = 0; } - bool GetSelected(int id) const { return Storage.GetInt((ImGuiID)id) != 0; } - void SetSelected(int id, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)id); if (*p_int == (int)v) return; SelectedCount = v ? (SelectedCount + 1) : (SelectedCount - 1); *p_int = (bool)v; } - int GetSelectedCount() const { return SelectedCount; } + void Clear() { Storage.Clear(); SelectionSize = 0; } + bool GetSelected(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } + void SetSelected(int n, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == (int)v) return; if (v) SelectionSize++; else SelectionSize--; *p_int = (bool)v; } + int GetSelectionSize() const { return SelectionSize; } // When using SelectAll() / SetRange() we assume that our objects ID are indices. // In this demo we always store selection using indices and never in another manner (e.g. object ID or pointers). // If your selection system is storing selection using object ID and you want to support Shift+Click range-selection, // you will need a way to iterate from one object to another given the ID you use. - // You are likely to need some kind of data structure to convert 'view index' from/to 'ID'. + // You are likely to need some kind of data structure to convert 'view index' <> 'object ID'. // FIXME-MULTISELECT: Would be worth providing a demo of doing this. // FIXME-MULTISELECT: SetRange() is currently very inefficient since it doesn't take advantage of the fact that ImGuiStorage stores sorted key. - void SetRange(int a, int b, bool v) { if (b < a) { int tmp = b; b = a; a = tmp; } for (int n = a; n <= b; n++) SetSelected(n, v); } - void SelectAll(int count) { Storage.Data.resize(count); for (int n = 0; n < count; n++) Storage.Data[n] = ImGuiStoragePair((ImGuiID)n, 1); SelectedCount = count; } // This could be using SetRange() but this is faster. + void SetRange(int n1, int n2, bool v) { if (n2 < n1) { int tmp = n2; n2 = n1; n1 = tmp; } for (int n = n1; n <= n2; n++) SetSelected(n, v); } + void SelectAll(int count) { Storage.Data.resize(count); for (int idx = 0; idx < count; idx++) Storage.Data[idx] = ImGuiStoragePair((ImGuiID)idx, 1); SelectionSize = count; } // This could be using SetRange(), but it this way is faster. }; static void ShowDemoWindowMultiSelect() @@ -2846,10 +2848,13 @@ static void ShowDemoWindowMultiSelect() // Test both Selectable() and TreeNode() widgets enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; + static bool use_columns = false; static WidgetType widget_type = WidgetType_TreeNode; if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } + ImGui::SameLine(); + ImGui::Checkbox("Use 2 columns", &use_columns); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&ImGui::GetIO().ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); ImGui::SameLine(); HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range. Keyboard is also supported."); @@ -2865,6 +2870,12 @@ static void ShowDemoWindowMultiSelect() if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } + if (use_columns) + { + ImGui::Columns(2); + //ImGui::PushStyleVar(ImGuiStyleVar_FrtemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); + } + ImGuiListClipper clipper; clipper.Begin(ITEMS_COUNT); while (clipper.Step()) @@ -2874,8 +2885,9 @@ static void ShowDemoWindowMultiSelect() for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) { ImGui::PushID(n); + const char* category = random_names[n % IM_ARRAYSIZE(random_names)]; char label[64]; - sprintf(label, "Object %05d (category: %s)", n, random_names[n % IM_ARRAYSIZE(random_names)]); + sprintf(label, "Object %05d (category: %s)", n, category); bool item_is_selected = selection.GetSelected(n); // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part @@ -2900,10 +2912,23 @@ static void ShowDemoWindowMultiSelect() selection.SetSelected(n, !item_is_selected); } + if (use_columns) + { + ImGui::NextColumn(); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::InputText("###NoLabel", (char*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); + ImGui::PopStyleVar(); + ImGui::NextColumn(); + } + ImGui::PopID(); } } + if (use_columns) + ImGui::Columns(1); + // Apply multi-select requests multi_select_data = ImGui::EndMultiSelect(); selection_ref = (int)(intptr_t)multi_select_data->RangeSrc; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9f546a5e3..cada96d81 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7153,9 +7153,11 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* } // Select All helper shortcut + // Note: we are comparing FocusScope so we don't need to be testing for IsWindowFocused() if (!(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) - if (IsWindowFocused() && g.IO.KeyCtrl && IsKeyPressed(GetKeyIndex(ImGuiKey_A))) - ms->In.RequestSelectAll = true; + if (ms->FocusScopeId == g.NavFocusScopeId && g.ActiveId == 0) + if (g.IO.KeyCtrl && IsKeyPressed(GetKeyIndex(ImGuiKey_A))) + ms->In.RequestSelectAll = true; #ifdef IMGUI_DEBUG_MULTISELECT if (ms->In.RequestClear) printf("[%05d] BeginMultiSelect: RequestClear\n", g.FrameCount); From 0479b188d063e49a3a1a58acf4217b6797804e57 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 1 Apr 2020 20:14:51 +0200 Subject: [PATCH 0106/2359] MultiSelect: Comments. Tweak demo. --- imgui.h | 41 +++++++++++++++++++++++------------------ imgui_demo.cpp | 27 ++++++++++++++++----------- imgui_widgets.cpp | 2 +- 3 files changed, 40 insertions(+), 30 deletions(-) diff --git a/imgui.h b/imgui.h index e57a29752..96e86161a 100644 --- a/imgui.h +++ b/imgui.h @@ -2738,31 +2738,36 @@ enum ImGuiMultiSelectFlags_ }; // Abstract: -// - This system implements standard multi-selection idioms (CTRL+Click/Arrow, SHIFT+Click/Arrow, etc) in a way that allow items to be -// fully clipped (= not submitted at all) when not visible. Clipping is typically provided by ImGuiListClipper. +// - This system helps you implements standard multi-selection idioms (CTRL+Click/Arrow, SHIFT+Click/Arrow, etc) in a way that allow +// selectable items to be fully clipped (= not submitted at all) when not visible. Clipping is typically provided by ImGuiListClipper. // Handling all of this in a single pass imgui is a little tricky, and this is why we provide those functionalities. -// Note however that if you don't need SHIFT+Click/Arrow range-select, you can handle a simpler form of multi-selection yourself, -// by reacting to click/presses on Selectable() items and checking keyboard modifiers. -// The complexity of this system here is mostly caused by the handling of range-select while optionally allowing to clip elements. +// Note however that if you don't need SHIFT+Click/Arrow range-select + clipping, you can handle a simpler form of multi-selection +// yourself, by reacting to click/presses on Selectable() items and checking keyboard modifiers. +// The unusual complexity of this system is mostly caused by supporting SHIFT+Click/Arrow range-select with clipped elements. +// - TreeNode() and Selectable() are supported. // - The work involved to deal with multi-selection differs whether you want to only submit visible items (and clip others) or submit all items // regardless of their visibility. Clipping items is more efficient and will allow you to deal with large lists (1k~100k items) with near zero // performance penalty, but requires a little more work on the code. If you only have a few hundreds elements in your possible selection set, -// you may as well not bother with clipping, as the cost should be negligible (as least on imgui side). +// you may as well not bother with clipping, as the cost should be negligible (as least on Dear ImGui side). // If you are not sure, always start without clipping and you can work your way to the more optimized version afterwards. -// - The void* Src/Dst value represent a selectable object. They are the values you pass to SetNextItemSelectionUserData(). -// Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points. But the code never assume that sortable integers are used. -// - In the spirit of imgui design, your code own the selection data. So this is designed to handle all kind of selection data: instructive (store a bool inside each object), -// external array (store an array aside from your objects), set (store only selected items in a hash/map/set), using intervals (store indices in an interval tree), etc. +// - The void* RangeSrc/RangeDst value represent a selectable object. They are the values you pass to SetNextItemSelectionUserData(). +// Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points and you will need to interpolate +// between them to honor range selection. But the code never assume that sortable integers are used (you may store pointers to your object, +// and then from the pointer have your own way of iterating from RangeSrc to RangeDst). +// - In the spirit of Dear ImGui design, your code own the selection data. So this is designed to handle all kind of selection data: +// e.g. instructive selection (store a bool inside each object), external array (store an array aside from your objects), +// hash/map/set (store only selected items in a hash/map/set), or other structures (store indices in an interval tree), etc. // Usage flow: -// 1) Call BeginMultiSelect() with the last saved value of ->RangeSrc and its selection status. As a default value for the initial frame or when, -// resetting your selection state: you may use the value for your first item or a "null" value that matches the type stored in your void*. -// 2) Honor Clear/SelectAll requests by updating your selection data. [Only required if you are using a clipper in step 4] -// 3) Set RangeSrcPassedBy=true if the RangeSrc item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] +// 1) Call BeginMultiSelect() with the last saved value of ->RangeSrc and its selection state. +// It is because you need to pass its selection state (and you own selection) that we don't store this value in Dear ImGui. +// (For the initial frame or when resetting your selection state: you may use the value for your first item or a "null" value that matches the type stored in your void*). +// 2) Honor Clear/SelectAll requests by updating your selection data. [Only required if you are using a clipper in step 4] +// 3) Set RangeSrcPassedBy=true if the RangeSrc item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] // This is because for range-selection we need to know if we are currently "inside" or "outside" the range. -// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrc) { data->RangeSrcPassedBy = true; } +// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrc) { data->RangeSrcPassedBy = true; } // 4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. -// Call IsItemSelectionToggled() to query with the selection state has been toggled, in which you need the info immediately (before EndMultiSelect()) for your display. -// When cannot reliably return a "IsItemSelected()" value because we need to consider clipped (unprocessed) item, this is why we return a toggle event instead. +// Call IsItemToggledSelection() to query if the selection state has been toggled, if you need the info immediately for your display (before EndMultiSelect()). +// When cannot return a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggle" event instead. // 5) Call EndMultiSelect(). Save the value of ->RangeSrc for the next frame (you may convert the value in a format that is safe for persistance) // 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable() on a per-item basis. @@ -2771,7 +2776,7 @@ struct ImGuiMultiSelectData bool RequestClear; // Begin, End // Request user to clear selection bool RequestSelectAll; // Begin, End // Request user to select all bool RequestSetRange; // End // Request user to set or clear selection in the [RangeSrc..RangeDst] range - bool RangeSrcPassedBy; // After Begin // Need to be set by user is RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. + bool RangeSrcPassedBy; // In loop // (If clipping) Need to be set by user if RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. bool RangeValue; // End // End: parameter from RequestSetRange request. True = Select Range, False = Unselect range. void* RangeSrc; // Begin, End // End: parameter from RequestSetRange request + you need to save this value so you can pass it again next frame. / Begin: this is the value you passed to BeginMultiSelect() void* RangeDst; // End // End: parameter from RequestSetRange request. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 87e2e0bac..698e13a79 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2771,12 +2771,15 @@ static void ShowDemoWindowWidgets() // are generally appropriate. Even a large array of bool might work for you... // - If you need to handle extremely large selections, it might be advantageous to support a "negative" mode in // your storage, so "Select All" becomes "Negative=1, Clear" and then sparse unselect can add to the storage. -struct ExampleSelectionData +// About RefItem: +// - The MultiSelect API requires you to store information about the reference/pivot item (generally the last clicked item). +struct ExampleSelection { ImGuiStorage Storage; - int SelectionSize; // Number of selected items (== number of 1 in the Storage) + int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class) + int RangeRef; // Reference/pivot item (generally last clicked item) - ExampleSelectionData() { Clear(); } + ExampleSelection() { RangeRef = 0; Clear(); } void Clear() { Storage.Clear(); SelectionSize = 0; } bool GetSelected(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } void SetSelected(int n, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == (int)v) return; if (v) SelectionSize++; else SelectionSize--; *p_int = (bool)v; } @@ -2837,8 +2840,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::TreeNode("Multiple Selection (Full)")) { // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. - static int selection_ref = 0; // Selection pivot (last clicked item, we need to preserve this to handle range-select) - static ExampleSelectionData selection; + static ExampleSelection selection; const char* random_names[] = { "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", @@ -2866,7 +2868,7 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_TreeNode) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection_ref, selection.GetSelected(selection_ref)); + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } @@ -2880,7 +2882,7 @@ static void ShowDemoWindowMultiSelect() clipper.Begin(ITEMS_COUNT); while (clipper.Step()) { - if (clipper.DisplayStart > (int)selection_ref) + if (clipper.DisplayStart > selection.RangeRef) multi_select_data->RangeSrcPassedBy = true; for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) { @@ -2904,12 +2906,15 @@ static void ShowDemoWindowMultiSelect() } else if (widget_type == WidgetType_TreeNode) { - ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnDoubleClick; + ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth; + tree_node_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; if (item_is_selected) tree_node_flags |= ImGuiTreeNodeFlags_Selected; - ImGui::TreeNodeEx(label, tree_node_flags); + bool open = ImGui::TreeNodeEx(label, tree_node_flags); if (ImGui::IsItemToggledSelection()) selection.SetSelected(n, !item_is_selected); + if (open) + ImGui::TreePop(); } if (use_columns) @@ -2917,7 +2922,7 @@ static void ShowDemoWindowMultiSelect() ImGui::NextColumn(); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); - ImGui::InputText("###NoLabel", (char*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); + ImGui::InputText("###NoLabel", (char*)(void*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); ImGui::PopStyleVar(); ImGui::NextColumn(); } @@ -2931,7 +2936,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests multi_select_data = ImGui::EndMultiSelect(); - selection_ref = (int)(intptr_t)multi_select_data->RangeSrc; + selection.RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index cada96d81..95224cac4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6474,7 +6474,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags flags |= ImGuiTreeNodeFlags_OpenOnArrow; // To handle drag and drop of multiple items we need to avoid clearing selection on click. - // Enabling this test makes actions using CTRL+SHIFT delay their effect on the mouse release which is annoying, but it allows drag and drop of multiple items. + // Enabling this test makes actions using CTRL+SHIFT delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. // FIXME-MULTISELECT: Consider opt-in for drag and drop behavior in ImGuiMultiSelectFlags? if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) button_flags |= ImGuiButtonFlags_PressedOnClick; From 3ba3f0d905fb8db4eae1beaf67d7a6df037733f2 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 1 Apr 2020 20:34:30 +0200 Subject: [PATCH 0107/2359] MultiSelect: Fix Selectable() ambiguous return value, clarify need to use IsItemToggledSelection(). --- imgui_demo.cpp | 3 ++- imgui_widgets.cpp | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 698e13a79..b4a7f099e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2901,7 +2901,8 @@ static void ShowDemoWindowMultiSelect() ImGui::SetNextItemSelectionUserData(n); if (widget_type == WidgetType_Selectable) { - if (ImGui::Selectable(label, item_is_selected)) + ImGui::Selectable(label, item_is_selected); + if (ImGui::IsItemToggledSelection()) selection.SetSelected(n, !item_is_selected); } else if (widget_type == WidgetType_TreeNode) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 95224cac4..ba59b802c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6904,8 +6904,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (disabled_item && !disabled_global) EndDisabled(); + // Users of BeginMultiSelect() scope: call ImGui::IsItemToggledSelection() to retrieve selection toggle. Selectable() returns a pressed state! IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); - return pressed || (was_selected != selected); //-V1020 + return pressed; //-V1020 } bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) @@ -7144,6 +7145,7 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* } // Auto clear when using Navigation to move within the selection (we compare SelectScopeId so it possible to use multiple lists inside a same window) + // FIXME: Polling key mods after the fact (frame following the move request) is incorrect, but latching it would requires non-trivial change in MultiSelectItemFooter() if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) { if (g.IO.KeyShift) From 00c4b8f2a345f5dbf34fa4471f1acd8b117fdbd7 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 2 Apr 2020 16:46:53 +0200 Subject: [PATCH 0108/2359] MultiSelect: Fix testing key mods from after the nav request (remove need to hold the mod longer) --- imgui_internal.h | 2 ++ imgui_widgets.cpp | 15 +++++++++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index dd5853466..005df3065 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2123,6 +2123,7 @@ struct ImGuiContext bool MultiSelectEnabled; ImGuiMultiSelectFlags MultiSelectFlags; ImGuiMultiSelectState MultiSelectState; // We currently don't support recursing/stacking multi-select + ImGuiKeyChord MultiSelectKeyMods; // Render float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) @@ -2389,6 +2390,7 @@ struct ImGuiContext MultiSelectEnabled = false; MultiSelectFlags = ImGuiMultiSelectFlags_None; + MultiSelectKeyMods = ImGuiMod_None; DimBgRatio = 0.0f; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ba59b802c..5c344c7b2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7138,6 +7138,9 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* g.MultiSelectEnabled = true; g.MultiSelectFlags = flags; + // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. + g.MultiSelectKeyMods = g.NavJustMovedToId ? g.NavJustMovedToKeyMods : g.IO.KeyMods; + if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) { ms->In.RangeSrc = ms->Out.RangeSrc = range_ref; @@ -7148,9 +7151,9 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* // FIXME: Polling key mods after the fact (frame following the move request) is incorrect, but latching it would requires non-trivial change in MultiSelectItemFooter() if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) { - if (g.IO.KeyShift) + if (g.MultiSelectKeyMods & ImGuiMod_Shift) ms->InRequestSetRangeNav = true; - if (!g.IO.KeyCtrl && !g.IO.KeyShift) + if ((g.MultiSelectKeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) ms->In.RequestClear = true; } @@ -7233,13 +7236,13 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) if (ms->InRequestSetRangeNav) { IM_ASSERT(id != 0); - IM_ASSERT(g.IO.KeyShift); + IM_ASSERT((g.MultiSelectKeyMods & ImGuiMod_Shift) != 0); const bool is_range_dst = !ms->InRangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. if (is_range_dst) ms->InRangeDstPassedBy = true; if (is_range_src || is_range_dst || ms->In.RangeSrcPassedBy != ms->InRangeDstPassedBy) selected = ms->In.RangeValue; - else if (!g.IO.KeyCtrl) + else if ((g.MultiSelectKeyMods & ImGuiMod_Ctrl) == 0) selected = false; } @@ -7256,9 +7259,9 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) bool selected = *p_selected; bool pressed = *p_pressed; - bool is_ctrl = g.IO.KeyCtrl; - bool is_shift = g.IO.KeyShift; const bool is_multiselect = (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoMultiSelect) == 0; + bool is_ctrl = (g.MultiSelectKeyMods & ImGuiMod_Ctrl) != 0; + bool is_shift = (g.MultiSelectKeyMods & ImGuiMod_Shift) != 0; // Auto-select as you navigate a list if (g.NavJustMovedToId == id) From b9721c1ed71e06588bc822e8ca52c2736c622b3e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 20:46:57 +0200 Subject: [PATCH 0109/2359] MultiSelect: Temporary fix/work-around for child/popup to not inherit MultiSelectEnabled flag, until we make mulit-select data stackable. --- imgui_demo.cpp | 10 +++++++++- imgui_internal.h | 6 +++--- imgui_widgets.cpp | 10 +++++----- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b4a7f099e..d7f7aa749 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2857,7 +2857,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } ImGui::SameLine(); ImGui::Checkbox("Use 2 columns", &use_columns); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&ImGui::GetIO().ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &ImGui::GetIO().ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); ImGui::SameLine(); HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range. Keyboard is also supported."); // Open a scrolling region @@ -2918,6 +2918,14 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } + // Right-click: context menu + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("(Testing Selectable inside an embedded popup)"); + ImGui::Selectable("Close"); + ImGui::EndPopup(); + } + if (use_columns) { ImGui::NextColumn(); diff --git a/imgui_internal.h b/imgui_internal.h index 005df3065..60a028003 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2120,9 +2120,9 @@ struct ImGuiContext ImVec2 NavWindowingAccumDeltaSize; // Range-Select/Multi-Select - bool MultiSelectEnabled; + ImGuiWindow* MultiSelectEnabledWindow; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select ImGuiMultiSelectFlags MultiSelectFlags; - ImGuiMultiSelectState MultiSelectState; // We currently don't support recursing/stacking multi-select + ImGuiMultiSelectState MultiSelectState; ImGuiKeyChord MultiSelectKeyMods; // Render @@ -2388,7 +2388,7 @@ struct ImGuiContext NavWindowingToggleLayer = false; NavWindowingToggleKey = ImGuiKey_None; - MultiSelectEnabled = false; + MultiSelectEnabledWindow = NULL; MultiSelectFlags = ImGuiMultiSelectFlags_None; MultiSelectKeyMods = ImGuiMod_None; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5c344c7b2..528a91833 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6464,7 +6464,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags const bool was_selected = selected; // Multi-selection support (header) - const bool is_multi_select = g.MultiSelectEnabled; + const bool is_multi_select = (g.MultiSelectEnabledWindow == window); if (is_multi_select) { MultiSelectItemHeader(id, &selected); @@ -6816,7 +6816,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; } // Multi-selection support (header) - const bool is_multi_select = g.MultiSelectEnabled; + const bool is_multi_select = (g.MultiSelectEnabledWindow == window); const bool was_selected = selected; if (is_multi_select) { @@ -7126,7 +7126,7 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(g.MultiSelectEnabled == false); // No recursion allowed yet (we could allow it if we deem it useful) + IM_ASSERT(g.MultiSelectEnabledWindow == NULL); // No recursion allowed yet (we could allow it if we deem it useful) IM_ASSERT(g.MultiSelectFlags == 0); IM_ASSERT(g.MultiSelectState.FocusScopeId == 0); @@ -7135,7 +7135,7 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ms->Clear(); ms->FocusScopeId = window->IDStack.back(); PushFocusScope(ms->FocusScopeId); - g.MultiSelectEnabled = true; + g.MultiSelectEnabledWindow = window; g.MultiSelectFlags = flags; // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. @@ -7182,7 +7182,7 @@ ImGuiMultiSelectData* ImGui::EndMultiSelect() ms->Out.RangeValue = true; g.MultiSelectState.FocusScopeId = 0; PopFocusScope(); - g.MultiSelectEnabled = false; + g.MultiSelectEnabledWindow = NULL; g.MultiSelectFlags = ImGuiMultiSelectFlags_None; #ifdef IMGUI_DEBUG_MULTISELECT From ad5d3c9bff8ee15556e6c5ee21234accfd98d3f8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 17 Jun 2022 15:55:59 +0200 Subject: [PATCH 0110/2359] MultiSelect: Fixed issue with Ctrl+click on TreeNode + amend demo to test drag and drop. --- imgui_demo.cpp | 25 ++++++++++++++++++++----- imgui_widgets.cpp | 2 +- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d7f7aa749..7b899eb32 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2817,8 +2817,8 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (Basic)"); - if (ImGui::TreeNode("Multiple Selection (Basic)")) + IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (Simplified)"); + if (ImGui::TreeNode("Multiple Selection (Simplified)")) { HelpMarker("Hold CTRL and click to select multiple items."); static bool selection[5] = { false, false, false, false, false }; @@ -2837,6 +2837,7 @@ static void ShowDemoWindowMultiSelect() } IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (Full)"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Multiple Selection (Full)")) { // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. @@ -2851,14 +2852,18 @@ static void ShowDemoWindowMultiSelect() // Test both Selectable() and TreeNode() widgets enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; static bool use_columns = false; + static bool use_drag_drop = true; static WidgetType widget_type = WidgetType_TreeNode; if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } ImGui::SameLine(); ImGui::Checkbox("Use 2 columns", &use_columns); + ImGui::SameLine(); + ImGui::Checkbox("Use drag & drop", &use_drag_drop); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &ImGui::GetIO().ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); ImGui::SameLine(); HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range. Keyboard is also supported."); + ImGui::Text("Selection size: %d", selection.GetSelectionSize()); // Open a scrolling region const int ITEMS_COUNT = 1000; @@ -2869,7 +2874,7 @@ static void ShowDemoWindowMultiSelect() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); - if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } if (use_columns) @@ -2904,6 +2909,11 @@ static void ShowDemoWindowMultiSelect() ImGui::Selectable(label, item_is_selected); if (ImGui::IsItemToggledSelection()) selection.SetSelected(n, !item_is_selected); + if (use_drag_drop && ImGui::BeginDragDropSource()) + { + ImGui::Text("(Dragging %d items)", selection.GetSelectionSize()); + ImGui::EndDragDropSource(); + } } else if (widget_type == WidgetType_TreeNode) { @@ -2914,6 +2924,11 @@ static void ShowDemoWindowMultiSelect() bool open = ImGui::TreeNodeEx(label, tree_node_flags); if (ImGui::IsItemToggledSelection()) selection.SetSelected(n, !item_is_selected); + if (use_drag_drop && ImGui::BeginDragDropSource()) + { + ImGui::Text("(Dragging %d items)", selection.GetSelectionSize()); + ImGui::EndDragDropSource(); + } if (open) ImGui::TreePop(); } @@ -2946,9 +2961,9 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests multi_select_data = ImGui::EndMultiSelect(); selection.RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; - if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } - if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 528a91833..5f245dd2b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6477,7 +6477,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags // Enabling this test makes actions using CTRL+SHIFT delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. // FIXME-MULTISELECT: Consider opt-in for drag and drop behavior in ImGuiMultiSelectFlags? if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) - button_flags |= ImGuiButtonFlags_PressedOnClick; + button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; else button_flags |= ImGuiButtonFlags_PressedOnClickRelease; } From 919cac14829e3e597c2886e7e655a82545ab714a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Apr 2023 17:38:23 +0200 Subject: [PATCH 0111/2359] MultiSelect: Demo: Add a simpler version. --- imgui_demo.cpp | 122 +++++++++++++++++++++++++++++++++++----------- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 3 files changed, 96 insertions(+), 30 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7b899eb32..3e50d0954 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2817,8 +2817,8 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (Simplified)"); - if (ImGui::TreeNode("Multiple Selection (Simplified)")) + IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (simplfied, manual)"); + if (ImGui::TreeNode("Multiple Selection (simplified, manual)")) { HelpMarker("Hold CTRL and click to select multiple items."); static bool selection[5] = { false, false, false, false, false }; @@ -2836,33 +2836,88 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (Full)"); + const char* random_names[] = + { + "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", + "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", + "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Celtuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" + }; + + // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. + // SHIFT+Click w/ CTRL and other standard features are supported. + IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full)"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); - if (ImGui::TreeNode("Multiple Selection (Full)")) + if (ImGui::TreeNode("Multiple Selection (full)")) + { + static ExampleSelection selection; + + ImGui::Text("Supported features:"); + ImGui::BulletText("Keyboard navigation (arrows, page up/down, home/end, space)."); + ImGui::BulletText("Ctrl modifier to preserve and toggle selection."); + ImGui::BulletText("Shift modifier for range selection."); + ImGui::BulletText("CTRL+A to select all."); + + // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling regions). + const int ITEMS_COUNT = 50; + ImGui::Text("Selection size: %d", selection.GetSelectionSize()); + if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + { + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); + if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } + + for (int n = 0; n < ITEMS_COUNT; n++) + { + // FIXME-MULTISELECT: This should not be needed but currently is because coarse clipping break the auto-setup. + if (n > selection.RangeRef) + multi_select_data->RangeSrcPassedBy = true; + + char label[64]; + sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); + + bool item_is_selected = selection.GetSelected(n); + ImGui::SetNextItemSelectionData((void*)(intptr_t)n); + ImGui::Selectable(label, item_is_selected); + if (ImGui::IsItemToggledSelection()) + selection.SetSelected(n, !item_is_selected); + } + + // Apply multi-select requests + multi_select_data = ImGui::EndMultiSelect(); + selection.RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; + if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } + if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + + ImGui::EndListBox(); + } + + ImGui::TreePop(); + } + + // Advanced demonstration of BeginMultiSelect() + // - Showcase clipping. + // - Showcase basic drag and drop. + // - Showcase TreeNode variant (note that tree node don't expand in the demo: supporting expanding tree nodes + clipping a separate thing). + // - Showcase using inside a table. + IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, advanced)"); + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Multiple Selection (full, advanced)")) { // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. static ExampleSelection selection; - const char* random_names[] = - { - "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", - "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", - "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Celtuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" - }; // Test both Selectable() and TreeNode() widgets enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; - static bool use_columns = false; + static bool use_table = false; static bool use_drag_drop = true; static WidgetType widget_type = WidgetType_TreeNode; if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } - ImGui::SameLine(); - ImGui::Checkbox("Use 2 columns", &use_columns); - ImGui::SameLine(); + ImGui::Checkbox("Use table", &use_table); ImGui::Checkbox("Use drag & drop", &use_drag_drop); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &ImGui::GetIO().ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); - ImGui::SameLine(); HelpMarker("Hold CTRL and click to select multiple items. Hold SHIFT to select a range. Keyboard is also supported."); + ImGui::Text("Selection size: %d", selection.GetSelectionSize()); // Open a scrolling region @@ -2874,23 +2929,31 @@ static void ShowDemoWindowMultiSelect() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); - if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } - if (use_columns) + if (use_table) { - ImGui::Columns(2); - //ImGui::PushStyleVar(ImGuiStyleVar_FrtemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0.0f, 0.0f)); + ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f); + //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); } ImGuiListClipper clipper; clipper.Begin(ITEMS_COUNT); while (clipper.Step()) { + // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeRef was passed over. if (clipper.DisplayStart > selection.RangeRef) multi_select_data->RangeSrcPassedBy = true; + for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) { + if (use_table) + ImGui::TableNextColumn(); + ImGui::PushID(n); const char* category = random_names[n % IM_ARRAYSIZE(random_names)]; char label[64]; @@ -2899,7 +2962,7 @@ static void ShowDemoWindowMultiSelect() // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part // of the selection scope doesn't erroneously alter our selection (FIXME-TESTS: Add a test for that!). - ImU32 dummy_col = (ImU32)ImGui::GetID(label); + ImU32 dummy_col = (ImU32)((unsigned int)n * 0xC250B74B) | IM_COL32_A_MASK; ImGui::ColorButton("##", ImColor(dummy_col), ImGuiColorEditFlags_NoTooltip, color_button_sz); ImGui::SameLine(); @@ -2941,35 +3004,38 @@ static void ShowDemoWindowMultiSelect() ImGui::EndPopup(); } - if (use_columns) + if (use_table) { - ImGui::NextColumn(); + ImGui::TableNextColumn(); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); ImGui::InputText("###NoLabel", (char*)(void*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); ImGui::PopStyleVar(); - ImGui::NextColumn(); } ImGui::PopID(); } } - if (use_columns) - ImGui::Columns(1); + if (use_table) + { + ImGui::EndTable(); + ImGui::PopStyleVar(); + } // Apply multi-select requests multi_select_data = ImGui::EndMultiSelect(); selection.RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; - if (multi_select_data->RequestClear) { selection.Clear(); } + if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } - if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); ImGui::EndListBox(); } + ImGui::TreePop(); } ImGui::TreePop(); diff --git a/imgui_internal.h b/imgui_internal.h index 60a028003..88eaf1b28 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1715,7 +1715,7 @@ struct ImGuiOldColumns struct IMGUI_API ImGuiMultiSelectState { - ImGuiID FocusScopeId; // Same as CurrentWindow->DC.FocusScopeIdCurrent (unless another selection scope was pushed manually) + ImGuiID FocusScopeId; // Same as g.CurrentFocusScopeId (unless another selection scope was pushed manually) ImGuiMultiSelectData In; // The In requests are set and returned by BeginMultiSelect() ImGuiMultiSelectData Out; // The Out requests are finalized and returned by EndMultiSelect() bool InRangeDstPassedBy; // (Internal) set by the the item that match NavJustMovedToId when InRequestRangeSetNav is set. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5f245dd2b..3729283f9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7229,7 +7229,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) const bool is_range_src = (ms->In.RangeSrc == item_data); if (is_range_src) - ms->In.RangeSrcPassedBy = true; + ms->In.RangeSrcPassedBy = true; // FIXME-MULTISELECT: The promise that this would be automatically done is not because of ItemAdd() clipping. // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) // For this to work, IF the user is clipping items, they need to set RangeSrcPassedBy = true to notify the system. From 19086c1c48974c72b76c6dee064b8f90145930be Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Apr 2023 17:59:06 +0200 Subject: [PATCH 0112/2359] MultiSelect: Added ImGuiMultiSelectFlags_ClearOnEscape (unsure of best design), expose IsFocused for custom shortcuts. --- imgui.h | 5 ++++- imgui_demo.cpp | 5 +++-- imgui_widgets.cpp | 30 ++++++++++++++++++++---------- 3 files changed, 27 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index 96e86161a..0cf6f43ed 100644 --- a/imgui.h +++ b/imgui.h @@ -2725,7 +2725,7 @@ struct ImColor #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. // Flags for BeginMultiSelect(). -// This system is designed to allow mouse/keyboard multi-selection, including support for range-selection (SHIFT + click), +// This system is designed to allow mouse/keyboard multi-selection, including support for range-selection (SHIFT+click and SHIFT+keyboard), // which is difficult to re-implement manually. If you disable multi-selection with ImGuiMultiSelectFlags_NoMultiSelect // (which is provided for consistency and flexibility), the whole BeginMultiSelect() system becomes largely overkill as // you can handle single-selection in a simpler manner by just calling Selectable() and reacting on clicks yourself. @@ -2735,6 +2735,7 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, ImGuiMultiSelectFlags_NoUnselect = 1 << 1, // Disable unselecting items with CTRL+Click, CTRL+Space etc. ImGuiMultiSelectFlags_NoSelectAll = 1 << 2, // Disable CTRL+A shortcut to set RequestSelectAll + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 3, // Enable ESC shortcut to clear selection }; // Abstract: @@ -2773,6 +2774,7 @@ enum ImGuiMultiSelectFlags_ // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable() on a per-item basis. struct ImGuiMultiSelectData { + bool IsFocused; // Begin // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool RequestClear; // Begin, End // Request user to clear selection bool RequestSelectAll; // Begin, End // Request user to select all bool RequestSetRange; // End // Request user to set or clear selection in the [RangeSrc..RangeDst] range @@ -2785,6 +2787,7 @@ struct ImGuiMultiSelectData ImGuiMultiSelectData() { Clear(); } void Clear() { + IsFocused = false; RequestClear = RequestSelectAll = RequestSetRange = RangeSrcPassedBy = RangeValue = false; RangeSrc = RangeDst = NULL; RangeDirection = 0; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3e50d0954..023d47cf6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2862,7 +2862,8 @@ static void ShowDemoWindowMultiSelect() ImGui::Text("Selection size: %d", selection.GetSelectionSize()); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); if (multi_select_data->RequestClear) { selection.Clear(); } if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } @@ -2876,7 +2877,7 @@ static void ShowDemoWindowMultiSelect() sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); bool item_is_selected = selection.GetSelected(n); - ImGui::SetNextItemSelectionData((void*)(intptr_t)n); + ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); if (ImGui::IsItemToggledSelection()) selection.SetSelected(n, !item_is_selected); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3729283f9..ba4cce289 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7138,6 +7138,9 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* g.MultiSelectEnabledWindow = window; g.MultiSelectFlags = flags; + // Report focus + ms->In.IsFocused = ms->Out.IsFocused = (ms->FocusScopeId == g.NavFocusScopeId); + // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. g.MultiSelectKeyMods = g.NavJustMovedToId ? g.NavJustMovedToKeyMods : g.IO.KeyMods; @@ -7157,16 +7160,23 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ms->In.RequestClear = true; } - // Select All helper shortcut - // Note: we are comparing FocusScope so we don't need to be testing for IsWindowFocused() - if (!(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) - if (ms->FocusScopeId == g.NavFocusScopeId && g.ActiveId == 0) - if (g.IO.KeyCtrl && IsKeyPressed(GetKeyIndex(ImGuiKey_A))) + // Shortcuts + if (ms->In.IsFocused) + { + // Select All helper shortcut (CTRL+A) + // Note: we are comparing FocusScope so we don't need to be testing for IsWindowFocused() + if (!(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) ms->In.RequestSelectAll = true; + if (flags & ImGuiMultiSelectFlags_ClearOnEscape) + if (Shortcut(ImGuiKey_Escape)) + ms->In.RequestClear = true; + } + #ifdef IMGUI_DEBUG_MULTISELECT - if (ms->In.RequestClear) printf("[%05d] BeginMultiSelect: RequestClear\n", g.FrameCount); - if (ms->In.RequestSelectAll) printf("[%05d] BeginMultiSelect: RequestSelectAll\n", g.FrameCount); + if (ms->In.RequestClear) IMGUI_DEBUG_LOG("BeginMultiSelect: RequestClear\n"); + if (ms->In.RequestSelectAll) IMGUI_DEBUG_LOG("BeginMultiSelect: RequestSelectAll\n"); #endif return &ms->In; @@ -7186,9 +7196,9 @@ ImGuiMultiSelectData* ImGui::EndMultiSelect() g.MultiSelectFlags = ImGuiMultiSelectFlags_None; #ifdef IMGUI_DEBUG_MULTISELECT - if (ms->Out.RequestClear) printf("[%05d] EndMultiSelect: RequestClear\n", g.FrameCount); - if (ms->Out.RequestSelectAll) printf("[%05d] EndMultiSelect: RequestSelectAll\n", g.FrameCount); - if (ms->Out.RequestSetRange) printf("[%05d] EndMultiSelect: RequestSetRange %p..%p = %d\n", g.FrameCount, ms->Out.RangeSrc, ms->Out.RangeDst, ms->Out.RangeValue); + if (ms->Out.RequestClear) IMGUI_DEBUG_LOG("EndMultiSelect: RequestClear\n"); + if (ms->Out.RequestSelectAll) IMGUI_DEBUG_LOG("EndMultiSelect: RequestSelectAll\n"); + if (ms->Out.RequestSetRange) IMGUI_DEBUG_LOG("EndMultiSelect: RequestSetRange %p..%p = %d\n", ms->Out.RangeSrc, ms->Out.RangeDst, ms->Out.RangeValue); #endif return &ms->Out; From b91ae122e15e087adb19a68df04e7c9be5e93457 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Apr 2023 19:33:38 +0200 Subject: [PATCH 0113/2359] MultiSelect: Demo: Added pointer indirection and indent level. This is to reduce noise for upcoming commits, ahead of adding a loop here. --- imgui_demo.cpp | 219 +++++++++++++++++++++++++------------------------ 1 file changed, 114 insertions(+), 105 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 023d47cf6..9a3d2363e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2906,9 +2906,10 @@ static void ShowDemoWindowMultiSelect() if (ImGui::TreeNode("Multiple Selection (full, advanced)")) { // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. - static ExampleSelection selection; + static ExampleSelection selections_data[1]; + ExampleSelection* selection = &selections_data[0]; - // Test both Selectable() and TreeNode() widgets + // Options enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; static bool use_table = false; static bool use_drag_drop = true; @@ -2919,103 +2920,124 @@ static void ShowDemoWindowMultiSelect() ImGui::Checkbox("Use table", &use_table); ImGui::Checkbox("Use drag & drop", &use_drag_drop); - ImGui::Text("Selection size: %d", selection.GetSelectionSize()); - - // Open a scrolling region - const int ITEMS_COUNT = 1000; - if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + // (spare brace to add a loop here later) { - ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); - if (widget_type == WidgetType_TreeNode) - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); + ImGui::Text("Selection size: %d", selection->GetSelectionSize()); - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); - if (multi_select_data->RequestClear) { selection.Clear(); } - if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } - - if (use_table) + // Open a scrolling region + const int ITEMS_COUNT = 1000; + if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0.0f, 0.0f)); - ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX); - ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f); - ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f); - //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - } + ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); + if (widget_type == WidgetType_TreeNode) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - ImGuiListClipper clipper; - clipper.Begin(ITEMS_COUNT); - while (clipper.Step()) - { - // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeRef was passed over. - if (clipper.DisplayStart > selection.RangeRef) - multi_select_data->RangeSrcPassedBy = true; + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); + if (multi_select_data->RequestClear) { selection->Clear(); } + if (multi_select_data->RequestSelectAll) { selection->SelectAll(ITEMS_COUNT); } - for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) + if (use_table) { - if (use_table) - ImGui::TableNextColumn(); - - ImGui::PushID(n); - const char* category = random_names[n % IM_ARRAYSIZE(random_names)]; - char label[64]; - sprintf(label, "Object %05d (category: %s)", n, category); - bool item_is_selected = selection.GetSelected(n); - - // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part - // of the selection scope doesn't erroneously alter our selection (FIXME-TESTS: Add a test for that!). - ImU32 dummy_col = (ImU32)((unsigned int)n * 0xC250B74B) | IM_COL32_A_MASK; - ImGui::ColorButton("##", ImColor(dummy_col), ImGuiColorEditFlags_NoTooltip, color_button_sz); - ImGui::SameLine(); - - ImGui::SetNextItemSelectionUserData(n); - if (widget_type == WidgetType_Selectable) - { - ImGui::Selectable(label, item_is_selected); - if (ImGui::IsItemToggledSelection()) - selection.SetSelected(n, !item_is_selected); - if (use_drag_drop && ImGui::BeginDragDropSource()) - { - ImGui::Text("(Dragging %d items)", selection.GetSelectionSize()); - ImGui::EndDragDropSource(); - } - } - else if (widget_type == WidgetType_TreeNode) - { - ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth; - tree_node_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; - if (item_is_selected) - tree_node_flags |= ImGuiTreeNodeFlags_Selected; - bool open = ImGui::TreeNodeEx(label, tree_node_flags); - if (ImGui::IsItemToggledSelection()) - selection.SetSelected(n, !item_is_selected); - if (use_drag_drop && ImGui::BeginDragDropSource()) - { - ImGui::Text("(Dragging %d items)", selection.GetSelectionSize()); - ImGui::EndDragDropSource(); - } - if (open) - ImGui::TreePop(); - } - - // Right-click: context menu - if (ImGui::BeginPopupContextItem()) - { - ImGui::Text("(Testing Selectable inside an embedded popup)"); - ImGui::Selectable("Close"); - ImGui::EndPopup(); - } - - if (use_table) - { - ImGui::TableNextColumn(); - ImGui::SetNextItemWidth(-FLT_MIN); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); - ImGui::InputText("###NoLabel", (char*)(void*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); - ImGui::PopStyleVar(); - } - - ImGui::PopID(); + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0.0f, 0.0f)); + ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f); + //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); } + + ImGuiListClipper clipper; + clipper.Begin(ITEMS_COUNT); + while (clipper.Step()) + { + // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeRef was passed over. + if (clipper.DisplayStart > selection->RangeRef) + multi_select_data->RangeSrcPassedBy = true; + + for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) + { + if (use_table) + ImGui::TableNextColumn(); + + ImGui::PushID(n); + const char* category = random_names[n % IM_ARRAYSIZE(random_names)]; + char label[64]; + sprintf(label, "Object %05d (category: %s)", n, category); + bool item_is_selected = selection->GetSelected(n); + + // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part + // of the selection scope doesn't erroneously alter our selection (FIXME-TESTS: Add a test for that!). + ImU32 dummy_col = (ImU32)((unsigned int)n * 0xC250B74B) | IM_COL32_A_MASK; + ImGui::ColorButton("##", ImColor(dummy_col), ImGuiColorEditFlags_NoTooltip, color_button_sz); + ImGui::SameLine(); + + ImGui::SetNextItemSelectionUserData(n); + if (widget_type == WidgetType_Selectable) + { + ImGui::Selectable(label, item_is_selected); + if (ImGui::IsItemToggledSelection()) + selection->SetSelected(n, !item_is_selected); + if (use_drag_drop && ImGui::BeginDragDropSource()) + { + ImGui::Text("(Dragging %d items)", selection->GetSelectionSize()); + ImGui::EndDragDropSource(); + } + } + else if (widget_type == WidgetType_TreeNode) + { + ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth; + tree_node_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; + if (item_is_selected) + tree_node_flags |= ImGuiTreeNodeFlags_Selected; + bool open = ImGui::TreeNodeEx(label, tree_node_flags); + if (ImGui::IsItemToggledSelection()) + selection->SetSelected(n, !item_is_selected); + if (use_drag_drop && ImGui::BeginDragDropSource()) + { + ImGui::Text("(Dragging %d items)", selection->GetSelectionSize()); + ImGui::EndDragDropSource(); + } + if (open) + ImGui::TreePop(); + } + + // Right-click: context menu + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("(Testing Selectable inside an embedded popup)"); + ImGui::Selectable("Close"); + ImGui::EndPopup(); + } + + if (use_table) + { + ImGui::TableNextColumn(); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::InputText("###NoLabel", (char*)(void*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); + ImGui::PopStyleVar(); + } + + ImGui::PopID(); + } + } + + if (use_table) + { + ImGui::EndTable(); + ImGui::PopStyleVar(); + } + + // Apply multi-select requests + multi_select_data = ImGui::EndMultiSelect(); + selection->RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; + if (multi_select_data->RequestClear) { selection->Clear(); } + if (multi_select_data->RequestSelectAll) { selection->SelectAll(ITEMS_COUNT); } + if (multi_select_data->RequestSetRange) { selection->SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + + if (widget_type == WidgetType_TreeNode) + ImGui::PopStyleVar(); + + ImGui::EndListBox(); } if (use_table) @@ -3023,20 +3045,7 @@ static void ShowDemoWindowMultiSelect() ImGui::EndTable(); ImGui::PopStyleVar(); } - - // Apply multi-select requests - multi_select_data = ImGui::EndMultiSelect(); - selection.RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; - if (multi_select_data->RequestClear) { selection.Clear(); } - if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } - if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } - - if (widget_type == WidgetType_TreeNode) - ImGui::PopStyleVar(); - - ImGui::EndListBox(); } - ImGui::TreePop(); } ImGui::TreePop(); From 35bbadcf0c78634e0b5547f1670ccd304f25835a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Apr 2023 19:40:02 +0200 Subject: [PATCH 0114/2359] MultiSelect: Added ImGuiMultiSelectFlags_ClearOnClickWindowVoid. + Demo: showcase multiple selection scopes in same window. --- imgui.h | 12 ++++++----- imgui_demo.cpp | 51 ++++++++++++++++++++++++++++++++--------------- imgui_internal.h | 1 + imgui_widgets.cpp | 11 ++++++++++ 4 files changed, 54 insertions(+), 21 deletions(-) diff --git a/imgui.h b/imgui.h index 0cf6f43ed..3268688d0 100644 --- a/imgui.h +++ b/imgui.h @@ -2731,11 +2731,13 @@ struct ImColor // you can handle single-selection in a simpler manner by just calling Selectable() and reacting on clicks yourself. enum ImGuiMultiSelectFlags_ { - ImGuiMultiSelectFlags_None = 0, - ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, - ImGuiMultiSelectFlags_NoUnselect = 1 << 1, // Disable unselecting items with CTRL+Click, CTRL+Space etc. - ImGuiMultiSelectFlags_NoSelectAll = 1 << 2, // Disable CTRL+A shortcut to set RequestSelectAll - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 3, // Enable ESC shortcut to clear selection + ImGuiMultiSelectFlags_None = 0, + ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, + ImGuiMultiSelectFlags_NoUnselect = 1 << 1, // Disable unselecting items with CTRL+Click, CTRL+Space etc. + ImGuiMultiSelectFlags_NoSelectAll = 1 << 2, // Disable CTRL+A shortcut to set RequestSelectAll + ImGuiMultiSelectFlags_ClearOnClickWindowVoid= 1 << 3, // Clear selection when clicking on empty location within host window (use if BeginMultiSelect() covers a whole window) + //ImGuiMultiSelectFlags_ClearOnClickRectVoid= 1 << 4, // Clear selection when clicking on empty location within rectangle covered by selection scope (use if multiple BeginMultiSelect() are used in the same host window) + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 5, // Clear selection when pressing Escape while scope is focused. }; // Abstract: diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9a3d2363e..b683c495b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2900,42 +2900,64 @@ static void ShowDemoWindowMultiSelect() // - Showcase clipping. // - Showcase basic drag and drop. // - Showcase TreeNode variant (note that tree node don't expand in the demo: supporting expanding tree nodes + clipping a separate thing). + // - Showcase having multiple multi-selection scopes in the same window. // - Showcase using inside a table. IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, advanced)"); ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Multiple Selection (full, advanced)")) { - // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. - static ExampleSelection selections_data[1]; - ExampleSelection* selection = &selections_data[0]; - // Options enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; static bool use_table = false; static bool use_drag_drop = true; + static bool multiple_selection_scopes = false; static WidgetType widget_type = WidgetType_TreeNode; if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } ImGui::Checkbox("Use table", &use_table); ImGui::Checkbox("Use drag & drop", &use_drag_drop); + ImGui::Checkbox("Distinct selection scopes in same window", &multiple_selection_scopes); - // (spare brace to add a loop here later) + // When 'multiple_selection_scopes' is set we show 3 selection scopes in the host window instead of 1 in a scrolling window. + static ExampleSelection selections_data[3]; + const int selection_scope_count = multiple_selection_scopes ? 3 : 1; + for (int selection_scope_n = 0; selection_scope_n < selection_scope_count; selection_scope_n++) { - ImGui::Text("Selection size: %d", selection->GetSelectionSize()); + ExampleSelection* selection = &selections_data[selection_scope_n]; + + const int ITEMS_COUNT = multiple_selection_scopes ? 12 : 1000; + ImGui::PushID(selection_scope_n); // Open a scrolling region - const int ITEMS_COUNT = 1000; - if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + bool draw_selection = true; + if (multiple_selection_scopes) + { + ImGui::SeparatorText("Selection scope"); + } + else + { + ImGui::Text("Selection size: %d", selection->GetSelectionSize()); + draw_selection = ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20)); + } + if (draw_selection) { ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); if (widget_type == WidgetType_TreeNode) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; + if (multiple_selection_scopes) + ;// flags |= ImGuiMultiSelectFlags_ClearOnClickRectVoid; + else + flags |= ImGuiMultiSelectFlags_ClearOnClickWindowVoid; + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); if (multi_select_data->RequestClear) { selection->Clear(); } if (multi_select_data->RequestSelectAll) { selection->SelectAll(ITEMS_COUNT); } + if (multiple_selection_scopes) + ImGui::Text("Selection size: %d", selection->GetSelectionSize()); // Draw counter below Separator and after BeginMultiSelect() + if (use_table) { ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0.0f, 0.0f)); @@ -3037,15 +3059,12 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); - ImGui::EndListBox(); + if (multiple_selection_scopes == false) + ImGui::EndListBox(); } + ImGui::PopID(); // ImGui::PushID(selection_scope_n); + } // for each selection scope (1 or 3) - if (use_table) - { - ImGui::EndTable(); - ImGui::PopStyleVar(); - } - } ImGui::TreePop(); } ImGui::TreePop(); diff --git a/imgui_internal.h b/imgui_internal.h index 88eaf1b28..757204567 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1720,6 +1720,7 @@ struct IMGUI_API ImGuiMultiSelectState ImGuiMultiSelectData Out; // The Out requests are finalized and returned by EndMultiSelect() bool InRangeDstPassedBy; // (Internal) set by the the item that match NavJustMovedToId when InRequestRangeSetNav is set. bool InRequestSetRangeNav; // (Internal) set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. + //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectState() { Clear(); } void Clear() { FocusScopeId = 0; In.Clear(); Out.Clear(); InRangeDstPassedBy = InRequestSetRangeNav = false; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ba4cce289..99f332640 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7188,6 +7188,17 @@ ImGuiMultiSelectData* ImGui::EndMultiSelect() ImGuiMultiSelectState* ms = &g.MultiSelectState; IM_ASSERT(g.MultiSelectState.FocusScopeId == g.CurrentFocusScopeId); + // Clear selection when clicking void? + // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! + if (g.MultiSelectFlags & ImGuiMultiSelectFlags_ClearOnClickWindowVoid) + if (IsWindowHovered() && g.HoveredId == 0) + if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) + { + ms->Out.RequestClear = true; + ms->Out.RequestSelectAll = ms->Out.RequestSetRange = false; + } + + // Unwind if (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoUnselect) ms->Out.RangeValue = true; g.MultiSelectState.FocusScopeId = 0; From a05700e3272d59c255846fdf36a013849b0fe5ac Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Apr 2023 19:44:41 +0200 Subject: [PATCH 0115/2359] MultiSelect: Enter doesn't alter selection (unlike Space). Fix for changes done in 5606. --- imgui_widgets.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 99f332640..aa067502e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7307,7 +7307,11 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } } - if (pressed) + // Unlike Space, Enter doesn't alter selection (but can still return a press) + const bool enter_pressed = pressed && (g.NavActivateId == id) && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput); + + // Alter selection + if (pressed && !enter_pressed) { //------------------------------------------------------------------------------------------------------------------------------------------------- // ACTION | Begin | Item Old | Item New | End @@ -7319,7 +7323,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Mouse Pressed, Ctrl=0, Shift=1 | n/a | n/a | Dst=item, Pressed -> Sel=1, Out.Clear, Out.SetRange=1 | Clear + SetRange //------------------------------------------------------------------------------------------------------------------------------------------------- - ImGuiInputSource input_source = (g.NavJustMovedToId != 0 && g.NavWindow == window && g.NavJustMovedToId == g.LastItemData.ID) ? g.NavInputSource : ImGuiInputSource_Mouse; + ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; if (is_shift && is_multiselect) { ms->Out.RequestSetRange = true; @@ -7335,7 +7339,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ms->Out.RangeValue = selected; } - if (input_source == ImGuiInputSource_Mouse) + if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) { // Mouse click without CTRL clears the selection, unless the clicked item is already selected bool preserve_existing_selection = g.DragDropActive; From 78cb1661cb5fb0ebc9fb6d56f670b5d9a030ef33 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Apr 2023 19:48:58 +0200 Subject: [PATCH 0116/2359] MultiSelect: Shallow tweaks/refactors. Including moving IsFocused back internally for now. --- imgui.h | 46 ++++++++++++++++++---------------- imgui_demo.cpp | 51 +++++++++++++++++++++---------------- imgui_internal.h | 17 ++++++------- imgui_widgets.cpp | 64 +++++++++++++++++++++-------------------------- 4 files changed, 88 insertions(+), 90 deletions(-) diff --git a/imgui.h b/imgui.h index 3268688d0..987d7e7fb 100644 --- a/imgui.h +++ b/imgui.h @@ -2754,6 +2754,7 @@ enum ImGuiMultiSelectFlags_ // you may as well not bother with clipping, as the cost should be negligible (as least on Dear ImGui side). // If you are not sure, always start without clipping and you can work your way to the more optimized version afterwards. // - The void* RangeSrc/RangeDst value represent a selectable object. They are the values you pass to SetNextItemSelectionUserData(). +// Most likely you will want to store an index here. // Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points and you will need to interpolate // between them to honor range selection. But the code never assume that sortable integers are used (you may store pointers to your object, // and then from the pointer have your own way of iterating from RangeSrc to RangeDst). @@ -2761,35 +2762,36 @@ enum ImGuiMultiSelectFlags_ // e.g. instructive selection (store a bool inside each object), external array (store an array aside from your objects), // hash/map/set (store only selected items in a hash/map/set), or other structures (store indices in an interval tree), etc. // Usage flow: -// 1) Call BeginMultiSelect() with the last saved value of ->RangeSrc and its selection state. -// It is because you need to pass its selection state (and you own selection) that we don't store this value in Dear ImGui. -// (For the initial frame or when resetting your selection state: you may use the value for your first item or a "null" value that matches the type stored in your void*). -// 2) Honor Clear/SelectAll requests by updating your selection data. [Only required if you are using a clipper in step 4] -// 3) Set RangeSrcPassedBy=true if the RangeSrc item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] -// This is because for range-selection we need to know if we are currently "inside" or "outside" the range. -// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrc) { data->RangeSrcPassedBy = true; } -// 4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. -// Call IsItemToggledSelection() to query if the selection state has been toggled, if you need the info immediately for your display (before EndMultiSelect()). -// When cannot return a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggle" event instead. -// 5) Call EndMultiSelect(). Save the value of ->RangeSrc for the next frame (you may convert the value in a format that is safe for persistance) -// 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) +// Begin +// 1) Call BeginMultiSelect() with the last saved value of ->RangeSrc and its selection state. +// It is because you need to pass its selection state (and you own selection) that we don't store this value in Dear ImGui. +// (For the initial frame or when resetting your selection state: you may use the value for your first item or a "null" value that matches the type stored in your void*). +// 2) Honor Clear/SelectAll requests by updating your selection data. Only required if you are using a clipper in step 4: but you can use same code as step 6 anyway. +// Loop +// 3) Set RangeSrcPassedBy=true if the RangeSrc item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] +// This is because for range-selection we need to know if we are currently "inside" or "outside" the range. +// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrc) { data->RangeSrcPassedBy = true; } +// 4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. +// Call IsItemToggledSelection() to query if the selection state has been toggled, if you need the info immediately for your display (before EndMultiSelect()). +// When cannot return a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggle" event instead. +// End +// 5) Call EndMultiSelect(). Save the value of ->RangeSrc for the next frame (you may convert the value in a format that is safe for persistance) +// 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable() on a per-item basis. struct ImGuiMultiSelectData { - bool IsFocused; // Begin // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. - bool RequestClear; // Begin, End // Request user to clear selection - bool RequestSelectAll; // Begin, End // Request user to select all - bool RequestSetRange; // End // Request user to set or clear selection in the [RangeSrc..RangeDst] range - bool RangeSrcPassedBy; // In loop // (If clipping) Need to be set by user if RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. - bool RangeValue; // End // End: parameter from RequestSetRange request. True = Select Range, False = Unselect range. - void* RangeSrc; // Begin, End // End: parameter from RequestSetRange request + you need to save this value so you can pass it again next frame. / Begin: this is the value you passed to BeginMultiSelect() - void* RangeDst; // End // End: parameter from RequestSetRange request. - int RangeDirection; // End // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. + bool RequestClear; // Begin, End // 1. Request user to clear selection + bool RequestSelectAll; // Begin, End // 2. Request user to select all + bool RequestSetRange; // End // 3. Request user to set or clear selection in the [RangeSrc..RangeDst] range + bool RangeSrcPassedBy; // Loop // (If clipping) Need to be set by user if RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. + bool RangeValue; // End // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. + void* RangeSrc; // Begin, End // End: parameter from RequestSetRange request + you need to save this value so you can pass it again next frame. / Begin: this is the value you passed to BeginMultiSelect() + void* RangeDst; // End // End: parameter from RequestSetRange request. + int RangeDirection; // End // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. ImGuiMultiSelectData() { Clear(); } void Clear() { - IsFocused = false; RequestClear = RequestSelectAll = RequestSetRange = RangeSrcPassedBy = RangeValue = false; RangeSrc = RangeDst = NULL; RangeDirection = 0; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b683c495b..c8fc424dc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -608,6 +608,7 @@ void ImGui::ShowDemoWindow(bool* p_open) static void ShowDemoWindowWidgets() { IMGUI_DEMO_MARKER("Widgets"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (!ImGui::CollapsingHeader("Widgets")) return; @@ -1353,6 +1354,7 @@ static void ShowDemoWindowWidgets() } IMGUI_DEMO_MARKER("Widgets/Selectables"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Selectables")) { // Selectable() has 2 overloads: @@ -2759,26 +2761,28 @@ static void ShowDemoWindowWidgets() } } -// [Advanced] Helper class to simulate storage of a multi-selection state, used by the advanced multi-selection demos. +// [Advanced] Helper class to simulate storage of a multi-selection state, used by the BeginMultiSelect() demos. // We use ImGuiStorage (simple key->value storage) to avoid external dependencies but it's probably not optimal. // To store a single-selection: // - You only need a single variable and don't need any of this! // To store a multi-selection, in your real application you could: // - Use intrusively stored selection (e.g. 'bool IsSelected' inside your object). This is by far the simplest // way to store your selection data, but it means you cannot have multiple simultaneous views over your objects. -// This is what may of the simpler demos in this file are using (so they are not using this class). -// - Otherwise, any externally stored unordered_set/set/hash/map/interval trees (storing indices, objects id, etc.) +// This is what many of the simpler demos in this file are using (so they are not using this class). +// - Use external storage: e.g. unordered_set/set/hash/map/interval trees (storing indices, objects id, etc.) // are generally appropriate. Even a large array of bool might work for you... // - If you need to handle extremely large selections, it might be advantageous to support a "negative" mode in -// your storage, so "Select All" becomes "Negative=1, Clear" and then sparse unselect can add to the storage. +// your storage, so "Select All" becomes "Negative=1 + Clear" and then sparse unselect can add to the storage. // About RefItem: -// - The MultiSelect API requires you to store information about the reference/pivot item (generally the last clicked item). +// - The BeginMultiSelect() API requires you to store information about the reference/pivot item (generally the last clicked item). struct ExampleSelection { - ImGuiStorage Storage; + // Data + ImGuiStorage Storage; // Selection set int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class) int RangeRef; // Reference/pivot item (generally last clicked item) + // Functions ExampleSelection() { RangeRef = 0; Clear(); } void Clear() { Storage.Clear(); SelectionSize = 0; } bool GetSelected(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } @@ -2791,11 +2795,20 @@ struct ExampleSelection // you will need a way to iterate from one object to another given the ID you use. // You are likely to need some kind of data structure to convert 'view index' <> 'object ID'. // FIXME-MULTISELECT: Would be worth providing a demo of doing this. - // FIXME-MULTISELECT: SetRange() is currently very inefficient since it doesn't take advantage of the fact that ImGuiStorage stores sorted key. - void SetRange(int n1, int n2, bool v) { if (n2 < n1) { int tmp = n2; n2 = n1; n1 = tmp; } for (int n = n1; n <= n2; n++) SetSelected(n, v); } - void SelectAll(int count) { Storage.Data.resize(count); for (int idx = 0; idx < count; idx++) Storage.Data[idx] = ImGuiStoragePair((ImGuiID)idx, 1); SelectionSize = count; } // This could be using SetRange(), but it this way is faster. + // FIXME-MULTISELECT: This implementation of SetRange() is inefficient because it doesn't take advantage of the fact that ImGuiStorage stores sorted key. + void SetRange(int a, int b, bool v) { if (b < a) { int tmp = b; b = a; a = tmp; } for (int n = a; n <= b; n++) SetSelected(n, v); } + void SelectAll(int count) { Storage.Data.resize(count); for (int idx = 0; idx < count; idx++) Storage.Data[idx] = ImGuiStoragePair((ImGuiID)idx, 1); SelectionSize = count; } // This could be using SetRange(), but it this way is faster. + + // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). Must be done in this order! Order->SelectAll->SetRange. + void ApplyRequests(ImGuiMultiSelectData* ms_data, int items_count) + { + if (ms_data->RequestClear) { Clear(); } + if (ms_data->RequestSelectAll) { SelectAll(items_count); } + if (ms_data->RequestSetRange) { SetRange((int)(intptr_t)ms_data->RangeSrc, (int)(intptr_t)ms_data->RangeDst, ms_data->RangeValue ? 1 : 0); } + } }; + static void ShowDemoWindowMultiSelect() { IMGUI_DEMO_MARKER("Widgets/Selection State"); @@ -2864,8 +2877,7 @@ static void ShowDemoWindowMultiSelect() { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); - if (multi_select_data->RequestClear) { selection.Clear(); } - if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } + selection.ApplyRequests(multi_select_data, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) { @@ -2886,9 +2898,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests multi_select_data = ImGui::EndMultiSelect(); selection.RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; - if (multi_select_data->RequestClear) { selection.Clear(); } - if (multi_select_data->RequestSelectAll) { selection.SelectAll(ITEMS_COUNT); } - if (multi_select_data->RequestSetRange) { selection.SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + selection.ApplyRequests(multi_select_data, ITEMS_COUNT); ImGui::EndListBox(); } @@ -2903,7 +2913,7 @@ static void ShowDemoWindowMultiSelect() // - Showcase having multiple multi-selection scopes in the same window. // - Showcase using inside a table. IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, advanced)"); - ImGui::SetNextItemOpen(true, ImGuiCond_Once); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Multiple Selection (full, advanced)")) { // Options @@ -2952,8 +2962,7 @@ static void ShowDemoWindowMultiSelect() else flags |= ImGuiMultiSelectFlags_ClearOnClickWindowVoid; ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); - if (multi_select_data->RequestClear) { selection->Clear(); } - if (multi_select_data->RequestSelectAll) { selection->SelectAll(ITEMS_COUNT); } + selection->ApplyRequests(multi_select_data, ITEMS_COUNT); if (multiple_selection_scopes) ImGui::Text("Selection size: %d", selection->GetSelectionSize()); // Draw counter below Separator and after BeginMultiSelect() @@ -2971,8 +2980,8 @@ static void ShowDemoWindowMultiSelect() clipper.Begin(ITEMS_COUNT); while (clipper.Step()) { - // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeRef was passed over. - if (clipper.DisplayStart > selection->RangeRef) + // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. + if ((int)(intptr_t)multi_select_data->RangeSrc <= clipper.DisplayStart) multi_select_data->RangeSrcPassedBy = true; for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) @@ -3052,9 +3061,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests multi_select_data = ImGui::EndMultiSelect(); selection->RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; - if (multi_select_data->RequestClear) { selection->Clear(); } - if (multi_select_data->RequestSelectAll) { selection->SelectAll(ITEMS_COUNT); } - if (multi_select_data->RequestSetRange) { selection->SetRange((int)(intptr_t)multi_select_data->RangeSrc, (int)(intptr_t)multi_select_data->RangeDst, multi_select_data->RangeValue ? 1 : 0); } + selection->ApplyRequests(multi_select_data, ITEMS_COUNT); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); diff --git a/imgui_internal.h b/imgui_internal.h index 757204567..82f67dc60 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1715,15 +1715,19 @@ struct ImGuiOldColumns struct IMGUI_API ImGuiMultiSelectState { - ImGuiID FocusScopeId; // Same as g.CurrentFocusScopeId (unless another selection scope was pushed manually) + ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) + ImGuiMultiSelectFlags Flags; + ImGuiKeyChord KeyMods; + ImGuiWindow* Window; ImGuiMultiSelectData In; // The In requests are set and returned by BeginMultiSelect() ImGuiMultiSelectData Out; // The Out requests are finalized and returned by EndMultiSelect() + bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool InRangeDstPassedBy; // (Internal) set by the the item that match NavJustMovedToId when InRequestRangeSetNav is set. bool InRequestSetRangeNav; // (Internal) set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectState() { Clear(); } - void Clear() { FocusScopeId = 0; In.Clear(); Out.Clear(); InRangeDstPassedBy = InRequestSetRangeNav = false; } + void Clear() { FocusScopeId = 0; Flags = ImGuiMultiSelectFlags_None; KeyMods = ImGuiMod_None; Window = NULL; In.Clear(); Out.Clear(); InRangeDstPassedBy = InRequestSetRangeNav = false; } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT @@ -2121,10 +2125,7 @@ struct ImGuiContext ImVec2 NavWindowingAccumDeltaSize; // Range-Select/Multi-Select - ImGuiWindow* MultiSelectEnabledWindow; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select - ImGuiMultiSelectFlags MultiSelectFlags; - ImGuiMultiSelectState MultiSelectState; - ImGuiKeyChord MultiSelectKeyMods; + ImGuiMultiSelectState MultiSelectState; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select // Render float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) @@ -2389,10 +2390,6 @@ struct ImGuiContext NavWindowingToggleLayer = false; NavWindowingToggleKey = ImGuiKey_None; - MultiSelectEnabledWindow = NULL; - MultiSelectFlags = ImGuiMultiSelectFlags_None; - MultiSelectKeyMods = ImGuiMod_None; - DimBgRatio = 0.0f; DragDropActive = DragDropWithinSource = DragDropWithinTarget = false; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index aa067502e..5da30ea2e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6464,7 +6464,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags const bool was_selected = selected; // Multi-selection support (header) - const bool is_multi_select = (g.MultiSelectEnabledWindow == window); + const bool is_multi_select = (g.MultiSelectState.Window == window); if (is_multi_select) { MultiSelectItemHeader(id, &selected); @@ -6816,7 +6816,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; } // Multi-selection support (header) - const bool is_multi_select = (g.MultiSelectEnabledWindow == window); + const bool is_multi_select = (g.MultiSelectState.Window == window); const bool was_selected = selected; if (is_multi_select) { @@ -7126,23 +7126,19 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(g.MultiSelectEnabledWindow == NULL); // No recursion allowed yet (we could allow it if we deem it useful) - IM_ASSERT(g.MultiSelectFlags == 0); - IM_ASSERT(g.MultiSelectState.FocusScopeId == 0); + ImGuiMultiSelectState* ms = &g.MultiSelectState; + IM_ASSERT(ms->Window == NULL && ms->Flags == 0 && ms->FocusScopeId == 0); // No recursion allowed yet (we could allow it if we deem it useful) // FIXME: BeginFocusScope() - ImGuiMultiSelectState* ms = &g.MultiSelectState; ms->Clear(); ms->FocusScopeId = window->IDStack.back(); + ms->Flags = flags; + ms->Window = window; + ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId); PushFocusScope(ms->FocusScopeId); - g.MultiSelectEnabledWindow = window; - g.MultiSelectFlags = flags; - - // Report focus - ms->In.IsFocused = ms->Out.IsFocused = (ms->FocusScopeId == g.NavFocusScopeId); // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. - g.MultiSelectKeyMods = g.NavJustMovedToId ? g.NavJustMovedToKeyMods : g.IO.KeyMods; + ms->KeyMods = g.NavJustMovedToId ? g.NavJustMovedToKeyMods : g.IO.KeyMods; if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) { @@ -7154,14 +7150,14 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* // FIXME: Polling key mods after the fact (frame following the move request) is incorrect, but latching it would requires non-trivial change in MultiSelectItemFooter() if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) { - if (g.MultiSelectKeyMods & ImGuiMod_Shift) + if (ms->KeyMods & ImGuiMod_Shift) ms->InRequestSetRangeNav = true; - if ((g.MultiSelectKeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) + if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) ms->In.RequestClear = true; } // Shortcuts - if (ms->In.IsFocused) + if (ms->IsFocused) { // Select All helper shortcut (CTRL+A) // Note: we are comparing FocusScope so we don't need to be testing for IsWindowFocused() @@ -7174,10 +7170,8 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ms->In.RequestClear = true; } -#ifdef IMGUI_DEBUG_MULTISELECT - if (ms->In.RequestClear) IMGUI_DEBUG_LOG("BeginMultiSelect: RequestClear\n"); - if (ms->In.RequestSelectAll) IMGUI_DEBUG_LOG("BeginMultiSelect: RequestSelectAll\n"); -#endif + //if (ms->In.RequestClear) IMGUI_DEBUG_LOG("BeginMultiSelect: RequestClear\n"); + //if (ms->In.RequestSelectAll) IMGUI_DEBUG_LOG("BeginMultiSelect: RequestSelectAll\n"); return &ms->In; } @@ -7190,7 +7184,7 @@ ImGuiMultiSelectData* ImGui::EndMultiSelect() // Clear selection when clicking void? // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! - if (g.MultiSelectFlags & ImGuiMultiSelectFlags_ClearOnClickWindowVoid) + if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickWindowVoid) if (IsWindowHovered() && g.HoveredId == 0) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { @@ -7199,18 +7193,16 @@ ImGuiMultiSelectData* ImGui::EndMultiSelect() } // Unwind - if (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoUnselect) + if (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) ms->Out.RangeValue = true; - g.MultiSelectState.FocusScopeId = 0; + ms->FocusScopeId = 0; + ms->Window = NULL; + ms->Flags = ImGuiMultiSelectFlags_None; PopFocusScope(); - g.MultiSelectEnabledWindow = NULL; - g.MultiSelectFlags = ImGuiMultiSelectFlags_None; -#ifdef IMGUI_DEBUG_MULTISELECT - if (ms->Out.RequestClear) IMGUI_DEBUG_LOG("EndMultiSelect: RequestClear\n"); - if (ms->Out.RequestSelectAll) IMGUI_DEBUG_LOG("EndMultiSelect: RequestSelectAll\n"); - if (ms->Out.RequestSetRange) IMGUI_DEBUG_LOG("EndMultiSelect: RequestSetRange %p..%p = %d\n", ms->Out.RangeSrc, ms->Out.RangeDst, ms->Out.RangeValue); -#endif + //if (ms->Out.RequestClear) IMGUI_DEBUG_LOG("EndMultiSelect: RequestClear\n"); + //if (ms->Out.RequestSelectAll) IMGUI_DEBUG_LOG("EndMultiSelect: RequestSelectAll\n"); + //if (ms->Out.RequestSetRange) IMGUI_DEBUG_LOG("EndMultiSelect: RequestSetRange %p..%p = %d\n", ms->Out.RangeSrc, ms->Out.RangeDst, ms->Out.RangeValue); return &ms->Out; } @@ -7257,13 +7249,13 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) if (ms->InRequestSetRangeNav) { IM_ASSERT(id != 0); - IM_ASSERT((g.MultiSelectKeyMods & ImGuiMod_Shift) != 0); + IM_ASSERT((ms->KeyMods & ImGuiMod_Shift) != 0); const bool is_range_dst = !ms->InRangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. if (is_range_dst) ms->InRangeDstPassedBy = true; if (is_range_src || is_range_dst || ms->In.RangeSrcPassedBy != ms->InRangeDstPassedBy) selected = ms->In.RangeValue; - else if ((g.MultiSelectKeyMods & ImGuiMod_Ctrl) == 0) + else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) selected = false; } @@ -7278,11 +7270,11 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) void* item_data = (void*)g.NextItemData.SelectionUserData; + const bool is_multiselect = (ms->Flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0; bool selected = *p_selected; bool pressed = *p_pressed; - const bool is_multiselect = (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoMultiSelect) == 0; - bool is_ctrl = (g.MultiSelectKeyMods & ImGuiMod_Ctrl) != 0; - bool is_shift = (g.MultiSelectKeyMods & ImGuiMod_Shift) != 0; + bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; + bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; // Auto-select as you navigate a list if (g.NavJustMovedToId == id) @@ -7334,7 +7326,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } else { - selected = (!is_ctrl || (g.MultiSelectFlags & ImGuiMultiSelectFlags_NoUnselect)) ? true : !selected; + selected = (!is_ctrl || (ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) ? true : !selected; ms->Out.RangeSrc = ms->Out.RangeDst = item_data; ms->Out.RangeValue = selected; } @@ -7371,7 +7363,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) - if (ms->Out.RangeSrc == item_data && is_ctrl && is_shift && is_multiselect && !(g.MultiSelectFlags & ImGuiMultiSelectFlags_NoUnselect)) + if (ms->Out.RangeSrc == item_data && is_ctrl && is_shift && is_multiselect && !(ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) ms->Out.RangeValue = selected; *p_selected = selected; From 815c61b82eb5f00ea8eb0a772b646306a25dd2d2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Apr 2023 22:14:32 +0200 Subject: [PATCH 0117/2359] MultiSelect: Fixed needing to set RangeSrcPassedBy when not using clipper. --- imgui_demo.cpp | 4 ---- imgui_widgets.cpp | 9 +++++---- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c8fc424dc..3b98bc5c4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2881,10 +2881,6 @@ static void ShowDemoWindowMultiSelect() for (int n = 0; n < ITEMS_COUNT; n++) { - // FIXME-MULTISELECT: This should not be needed but currently is because coarse clipping break the auto-setup. - if (n > selection.RangeRef) - multi_select_data->RangeSrcPassedBy = true; - char label[64]; sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5da30ea2e..f1da8b168 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7218,6 +7218,10 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData; g.NextItemData.SelectionUserData = selection_user_data; g.NextItemData.FocusScopeId = g.CurrentFocusScopeId; + + // Auto updating RangeSrcPassedBy for cases were clipped is not used. + if (g.MultiSelectState.In.RangeSrc == (void*)selection_user_data) + g.MultiSelectState.In.RangeSrcPassedBy = true; } void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) @@ -7240,16 +7244,13 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) else if (ms->In.RequestSelectAll) selected = true; - const bool is_range_src = (ms->In.RangeSrc == item_data); - if (is_range_src) - ms->In.RangeSrcPassedBy = true; // FIXME-MULTISELECT: The promise that this would be automatically done is not because of ItemAdd() clipping. - // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) // For this to work, IF the user is clipping items, they need to set RangeSrcPassedBy = true to notify the system. if (ms->InRequestSetRangeNav) { IM_ASSERT(id != 0); IM_ASSERT((ms->KeyMods & ImGuiMod_Shift) != 0); + const bool is_range_src = (ms->In.RangeSrc == item_data); const bool is_range_dst = !ms->InRangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. if (is_range_dst) ms->InRangeDstPassedBy = true; From d2f208a30c426f48e918897bd5e3b97999aa80f2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 20 May 2023 15:51:39 +0200 Subject: [PATCH 0118/2359] MultiSelect: made SetNextItemSelectionData() optional to allow disjoint selection (e.g. with a CollapsingHeader between items). Amend demo. --- imgui.h | 4 ++-- imgui_demo.cpp | 40 +++++++++++++++++++++++----------------- imgui_widgets.cpp | 7 ++++--- 3 files changed, 29 insertions(+), 22 deletions(-) diff --git a/imgui.h b/imgui.h index 987d7e7fb..6c65045e3 100644 --- a/imgui.h +++ b/imgui.h @@ -2766,14 +2766,14 @@ enum ImGuiMultiSelectFlags_ // 1) Call BeginMultiSelect() with the last saved value of ->RangeSrc and its selection state. // It is because you need to pass its selection state (and you own selection) that we don't store this value in Dear ImGui. // (For the initial frame or when resetting your selection state: you may use the value for your first item or a "null" value that matches the type stored in your void*). -// 2) Honor Clear/SelectAll requests by updating your selection data. Only required if you are using a clipper in step 4: but you can use same code as step 6 anyway. +// 2) Honor Clear/SelectAll/SetRange requests by updating your selection data. (Only required if you are using a clipper in step 4: but you can use same code as step 6 anyway.) // Loop // 3) Set RangeSrcPassedBy=true if the RangeSrc item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] // This is because for range-selection we need to know if we are currently "inside" or "outside" the range. // If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrc) { data->RangeSrcPassedBy = true; } // 4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // Call IsItemToggledSelection() to query if the selection state has been toggled, if you need the info immediately for your display (before EndMultiSelect()). -// When cannot return a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggle" event instead. +// When cannot provide a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggled" event instead. // End // 5) Call EndMultiSelect(). Save the value of ->RangeSrc for the next frame (you may convert the value in a format that is safe for persistance) // 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3b98bc5c4..52e512e29 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2830,6 +2830,7 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } + // Demonstrate implementation a most-basic form of multi-selection manually IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (simplfied, manual)"); if (ImGui::TreeNode("Multiple Selection (simplified, manual)")) { @@ -2841,9 +2842,9 @@ static void ShowDemoWindowMultiSelect() sprintf(buf, "Object %d", n); if (ImGui::Selectable(buf, selection[n])) { - if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held + if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held memset(selection, 0, sizeof(selection)); - selection[n] ^= 1; + selection[n] ^= 1; // Toggle current item } } ImGui::TreePop(); @@ -2883,7 +2884,6 @@ static void ShowDemoWindowMultiSelect() { char label[64]; sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); - bool item_is_selected = selection.GetSelected(n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); @@ -2916,28 +2916,36 @@ static void ShowDemoWindowMultiSelect() enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; static bool use_table = false; static bool use_drag_drop = true; - static bool multiple_selection_scopes = false; + static bool use_multiple_scopes = false; + static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; static WidgetType widget_type = WidgetType_TreeNode; if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } ImGui::Checkbox("Use table", &use_table); ImGui::Checkbox("Use drag & drop", &use_drag_drop); - ImGui::Checkbox("Distinct selection scopes in same window", &multiple_selection_scopes); + ImGui::Checkbox("Multiple selection scopes in same window", &use_multiple_scopes); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoMultiSelect", &flags, ImGuiMultiSelectFlags_NoMultiSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoUnselect", &flags, ImGuiMultiSelectFlags_NoUnselect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); + ImGui::BeginDisabled(use_multiple_scopes); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickWindowVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickWindowVoid); + ImGui::EndDisabled(); - // When 'multiple_selection_scopes' is set we show 3 selection scopes in the host window instead of 1 in a scrolling window. + // When 'use_multiple_scopes' is set we show 3 selection scopes in the host window instead of 1 in a scrolling window. static ExampleSelection selections_data[3]; - const int selection_scope_count = multiple_selection_scopes ? 3 : 1; + const int selection_scope_count = use_multiple_scopes ? 3 : 1; for (int selection_scope_n = 0; selection_scope_n < selection_scope_count; selection_scope_n++) { ExampleSelection* selection = &selections_data[selection_scope_n]; - const int ITEMS_COUNT = multiple_selection_scopes ? 12 : 1000; + const int ITEMS_COUNT = use_multiple_scopes ? 12 : 1000; // Smaller count to make it easier to see multiple scopes in same screen. ImGui::PushID(selection_scope_n); // Open a scrolling region bool draw_selection = true; - if (multiple_selection_scopes) + if (use_multiple_scopes) { ImGui::SeparatorText("Selection scope"); } @@ -2952,15 +2960,13 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_TreeNode) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; - if (multiple_selection_scopes) - ;// flags |= ImGuiMultiSelectFlags_ClearOnClickRectVoid; - else - flags |= ImGuiMultiSelectFlags_ClearOnClickWindowVoid; - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); + ImGuiMultiSelectFlags local_flags = flags; + if (use_multiple_scopes) + local_flags &= ~ImGuiMultiSelectFlags_ClearOnClickWindowVoid; // local_flags |= ImGuiMultiSelectFlags_ClearOnClickRectVoid; + ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(local_flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); selection->ApplyRequests(multi_select_data, ITEMS_COUNT); - if (multiple_selection_scopes) + if (use_multiple_scopes) ImGui::Text("Selection size: %d", selection->GetSelectionSize()); // Draw counter below Separator and after BeginMultiSelect() if (use_table) @@ -3062,7 +3068,7 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); - if (multiple_selection_scopes == false) + if (use_multiple_scopes == false) ImGui::EndListBox(); } ImGui::PopID(); // ImGui::PushID(selection_scope_n); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f1da8b168..481853948 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6391,6 +6391,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags // Compute open and multi-select states before ItemAdd() as it clear NextItem data. bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); + const bool is_multi_select = (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasSelectionData) != 0; // Before ItemAdd() bool item_add = ItemAdd(interact_bb, id); g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; g.LastItemData.DisplayRect = frame_bb; @@ -6464,7 +6465,6 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags const bool was_selected = selected; // Multi-selection support (header) - const bool is_multi_select = (g.MultiSelectState.Window == window); if (is_multi_select) { MultiSelectItemHeader(id, &selected); @@ -6780,7 +6780,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl } const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; + const bool is_multi_select = (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasSelectionData) != 0; // Before ItemAdd() const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); + if (span_all_columns) { window->ClipRect.Min.x = backup_clip_rect_min_x; @@ -6816,7 +6818,6 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; } // Multi-selection support (header) - const bool is_multi_select = (g.MultiSelectState.Window == window); const bool was_selected = selected; if (is_multi_select) { @@ -7166,7 +7167,7 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ms->In.RequestSelectAll = true; if (flags & ImGuiMultiSelectFlags_ClearOnEscape) - if (Shortcut(ImGuiKey_Escape)) + if (Shortcut(ImGuiKey_Escape)) // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. ms->In.RequestClear = true; } From 85954c845e3f8c6abc08e5a60fac24a9f3ec83ea Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 20 May 2023 15:59:30 +0200 Subject: [PATCH 0119/2359] MultiSelect: Enter can alter selection if current item is not selected. --- imgui_widgets.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 481853948..71f0530c4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7301,11 +7301,13 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } } - // Unlike Space, Enter doesn't alter selection (but can still return a press) + // Unlike Space, Enter doesn't alter selection (but can still return a press) unless current item is not selected. + // The later, "unless current item is not select", may become optional? It seems like a better default if Enter doesn't necessarily open something + // (unlike e.g. Windows explorer). For use case where Enter always open something, we might decide to make this optional? const bool enter_pressed = pressed && (g.NavActivateId == id) && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput); // Alter selection - if (pressed && !enter_pressed) + if (pressed && (!enter_pressed || !selected)) { //------------------------------------------------------------------------------------------------------------------------------------------------- // ACTION | Begin | Item Old | Item New | End From 5d71314f712649b08f590b3aafea569bbab2b9c1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 May 2023 10:28:40 +0200 Subject: [PATCH 0120/2359] MultiSelect: removed DragDropActive/preserve_existing_selection logic which seems unused + comments. Can't find trace of early prototype for range-select but I couldn't find way to trigger this anymore. May be wrong. Will find out. --- imgui.h | 4 ++-- imgui_demo.cpp | 19 ++++++++++--------- imgui_internal.h | 8 ++++---- imgui_widgets.cpp | 45 ++++++++++++++++++++++----------------------- 4 files changed, 38 insertions(+), 38 deletions(-) diff --git a/imgui.h b/imgui.h index 6c65045e3..550e64361 100644 --- a/imgui.h +++ b/imgui.h @@ -2732,7 +2732,7 @@ struct ImColor enum ImGuiMultiSelectFlags_ { ImGuiMultiSelectFlags_None = 0, - ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, + ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, // Disable selecting more than one item. This is not very useful at this kind of selection can be implemented without BeginMultiSelect(), but this is available for consistency. ImGuiMultiSelectFlags_NoUnselect = 1 << 1, // Disable unselecting items with CTRL+Click, CTRL+Space etc. ImGuiMultiSelectFlags_NoSelectAll = 1 << 2, // Disable CTRL+A shortcut to set RequestSelectAll ImGuiMultiSelectFlags_ClearOnClickWindowVoid= 1 << 3, // Clear selection when clicking on empty location within host window (use if BeginMultiSelect() covers a whole window) @@ -2787,7 +2787,7 @@ struct ImGuiMultiSelectData bool RangeValue; // End // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. void* RangeSrc; // Begin, End // End: parameter from RequestSetRange request + you need to save this value so you can pass it again next frame. / Begin: this is the value you passed to BeginMultiSelect() void* RangeDst; // End // End: parameter from RequestSetRange request. - int RangeDirection; // End // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. + int RangeDirection; // End // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. ImGuiMultiSelectData() { Clear(); } void Clear() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 52e512e29..3008ca946 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2787,7 +2787,7 @@ struct ExampleSelection void Clear() { Storage.Clear(); SelectionSize = 0; } bool GetSelected(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } void SetSelected(int n, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == (int)v) return; if (v) SelectionSize++; else SelectionSize--; *p_int = (bool)v; } - int GetSelectionSize() const { return SelectionSize; } + int GetSize() const { return SelectionSize; } // When using SelectAll() / SetRange() we assume that our objects ID are indices. // In this demo we always store selection using indices and never in another manner (e.g. object ID or pointers). @@ -2808,7 +2808,6 @@ struct ExampleSelection } }; - static void ShowDemoWindowMultiSelect() { IMGUI_DEMO_MARKER("Widgets/Selection State"); @@ -2873,7 +2872,7 @@ static void ShowDemoWindowMultiSelect() // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling regions). const int ITEMS_COUNT = 50; - ImGui::Text("Selection size: %d", selection.GetSelectionSize()); + ImGui::Text("Selection size: %d", selection.GetSize()); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; @@ -2918,7 +2917,8 @@ static void ShowDemoWindowMultiSelect() static bool use_drag_drop = true; static bool use_multiple_scopes = false; static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; - static WidgetType widget_type = WidgetType_TreeNode; + static WidgetType widget_type = WidgetType_Selectable; + if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } @@ -2951,7 +2951,7 @@ static void ShowDemoWindowMultiSelect() } else { - ImGui::Text("Selection size: %d", selection->GetSelectionSize()); + ImGui::Text("Selection size: %d", selection->GetSize()); draw_selection = ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20)); } if (draw_selection) @@ -2967,7 +2967,7 @@ static void ShowDemoWindowMultiSelect() selection->ApplyRequests(multi_select_data, ITEMS_COUNT); if (use_multiple_scopes) - ImGui::Text("Selection size: %d", selection->GetSelectionSize()); // Draw counter below Separator and after BeginMultiSelect() + ImGui::Text("Selection size: %d", selection->GetSize()); // Draw counter below Separator and after BeginMultiSelect() if (use_table) { @@ -2994,7 +2994,7 @@ static void ShowDemoWindowMultiSelect() ImGui::PushID(n); const char* category = random_names[n % IM_ARRAYSIZE(random_names)]; char label[64]; - sprintf(label, "Object %05d (category: %s)", n, category); + sprintf(label, "Object %05d: category: %s", n, category); bool item_is_selected = selection->GetSelected(n); // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part @@ -3011,7 +3011,7 @@ static void ShowDemoWindowMultiSelect() selection->SetSelected(n, !item_is_selected); if (use_drag_drop && ImGui::BeginDragDropSource()) { - ImGui::Text("(Dragging %d items)", selection->GetSelectionSize()); + ImGui::Text("(Dragging %d items)", selection->GetSize()); ImGui::EndDragDropSource(); } } @@ -3026,7 +3026,7 @@ static void ShowDemoWindowMultiSelect() selection->SetSelected(n, !item_is_selected); if (use_drag_drop && ImGui::BeginDragDropSource()) { - ImGui::Text("(Dragging %d items)", selection->GetSelectionSize()); + ImGui::Text("(Dragging %d items)", selection->GetSize()); ImGui::EndDragDropSource(); } if (open) @@ -3041,6 +3041,7 @@ static void ShowDemoWindowMultiSelect() ImGui::EndPopup(); } + // Demo content within a table if (use_table) { ImGui::TableNextColumn(); diff --git a/imgui_internal.h b/imgui_internal.h index 82f67dc60..c51f28759 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2124,9 +2124,6 @@ struct ImGuiContext ImVec2 NavWindowingAccumDeltaPos; ImVec2 NavWindowingAccumDeltaSize; - // Range-Select/Multi-Select - ImGuiMultiSelectState MultiSelectState; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select - // Render float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) @@ -2169,6 +2166,9 @@ struct ImGuiContext ImVector CurrentTabBarStack; ImVector ShrinkWidthBuffer; + // Multi-Select state + ImGuiMultiSelectState MultiSelectState; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select + // Hover Delay system ImGuiID HoverItemDelayId; ImGuiID HoverItemDelayIdPreviousFrame; @@ -3344,7 +3344,7 @@ namespace ImGui IMGUI_API int TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); IMGUI_API int TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data); - // Multi-Select/Range-Select API + // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 71f0530c4..5fbe0821d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7157,22 +7157,20 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ms->In.RequestClear = true; } - // Shortcuts - if (ms->IsFocused) - { - // Select All helper shortcut (CTRL+A) - // Note: we are comparing FocusScope so we don't need to be testing for IsWindowFocused() - if (!(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) - if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) - ms->In.RequestSelectAll = true; + // Shortcut: Select all (CTRL+A) + if (ms->IsFocused && !(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) + ms->In.RequestSelectAll = true; - if (flags & ImGuiMultiSelectFlags_ClearOnEscape) - if (Shortcut(ImGuiKey_Escape)) // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. - ms->In.RequestClear = true; - } + // Shortcut: Clear selection (Escape) + // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. + // Otherwise may be done by caller but it means Shortcut() needs to be exposed. + if (ms->IsFocused && (flags & ImGuiMultiSelectFlags_ClearOnEscape)) + if (Shortcut(ImGuiKey_Escape)) + ms->In.RequestClear = true; - //if (ms->In.RequestClear) IMGUI_DEBUG_LOG("BeginMultiSelect: RequestClear\n"); - //if (ms->In.RequestSelectAll) IMGUI_DEBUG_LOG("BeginMultiSelect: RequestSelectAll\n"); + //if (ms->In.RequestClear) IMGUI_DEBUG_LOG_SELECTION("BeginMultiSelect: RequestClear\n"); + //if (ms->In.RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("BeginMultiSelect: RequestSelectAll\n"); return &ms->In; } @@ -7201,9 +7199,9 @@ ImGuiMultiSelectData* ImGui::EndMultiSelect() ms->Flags = ImGuiMultiSelectFlags_None; PopFocusScope(); - //if (ms->Out.RequestClear) IMGUI_DEBUG_LOG("EndMultiSelect: RequestClear\n"); - //if (ms->Out.RequestSelectAll) IMGUI_DEBUG_LOG("EndMultiSelect: RequestSelectAll\n"); - //if (ms->Out.RequestSetRange) IMGUI_DEBUG_LOG("EndMultiSelect: RequestSetRange %p..%p = %d\n", ms->Out.RangeSrc, ms->Out.RangeDst, ms->Out.RangeValue); + //if (ms->Out.RequestClear) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestClear\n"); + //if (ms->Out.RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSelectAll\n"); + //if (ms->Out.RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSetRange %p..%p = %d (dir %+d)\n", ms->Out.RangeSrc, ms->Out.RangeDst, ms->Out.RangeValue, ms->Out.RangeDirection); return &ms->Out; } @@ -7220,7 +7218,7 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d g.NextItemData.SelectionUserData = selection_user_data; g.NextItemData.FocusScopeId = g.CurrentFocusScopeId; - // Auto updating RangeSrcPassedBy for cases were clipped is not used. + // Auto updating RangeSrcPassedBy for cases were clipper is not used. if (g.MultiSelectState.In.RangeSrc == (void*)selection_user_data) g.MultiSelectState.In.RangeSrcPassedBy = true; } @@ -7322,6 +7320,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; if (is_shift && is_multiselect) { + // Shift+Arrow always select, Ctrl+Shift+Arrow copy source selection state. ms->Out.RequestSetRange = true; ms->Out.RangeDst = item_data; if (!is_ctrl) @@ -7330,7 +7329,8 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } else { - selected = (!is_ctrl || (ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) ? true : !selected; + // Ctrl inverts selection, otherwise always select + selected = (is_ctrl && (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) == 0) ? !selected : true; ms->Out.RangeSrc = ms->Out.RangeDst = item_data; ms->Out.RangeValue = selected; } @@ -7338,13 +7338,12 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) { // Mouse click without CTRL clears the selection, unless the clicked item is already selected - bool preserve_existing_selection = g.DragDropActive; - if (is_multiselect && !is_ctrl && !preserve_existing_selection) + if (is_multiselect && !is_ctrl) ms->Out.RequestClear = true; - if (is_multiselect && !is_shift && !preserve_existing_selection && ms->Out.RequestClear) + if (is_multiselect && !is_shift && ms->Out.RequestClear) { // For toggle selection unless there is a Clear request, we can handle it completely locally without sending a RangeSet request. - IM_ASSERT(ms->Out.RangeSrc == ms->Out.RangeDst); // Setup by block above + IM_ASSERT(ms->Out.RangeSrc == ms->Out.RangeDst); // Setup by else block above ms->Out.RequestSetRange = true; ms->Out.RangeValue = selected; ms->Out.RangeDirection = +1; From 11bcae1ebd4a5098d09e322aeb6ace356e019e03 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 May 2023 19:36:11 +0200 Subject: [PATCH 0121/2359] MultiSelect: refactor before introducing persistant state pool and to facilitate adding recursion + debug log calls. This is mostly the noisy/shallow stuff committed here, to get this out of the way. --- imgui.cpp | 2 +- imgui.h | 7 ++++--- imgui_internal.h | 10 ++++++---- imgui_widgets.cpp | 40 +++++++++++++++++++++++++--------------- 4 files changed, 36 insertions(+), 23 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 733a5dfe1..8f34acf92 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15799,7 +15799,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open) ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO); ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav); ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup); - //ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection); + ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection); ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting); if (SmallButton("Clear")) diff --git a/imgui.h b/imgui.h index 550e64361..349c77f3e 100644 --- a/imgui.h +++ b/imgui.h @@ -2747,6 +2747,10 @@ enum ImGuiMultiSelectFlags_ // Note however that if you don't need SHIFT+Click/Arrow range-select + clipping, you can handle a simpler form of multi-selection // yourself, by reacting to click/presses on Selectable() items and checking keyboard modifiers. // The unusual complexity of this system is mostly caused by supporting SHIFT+Click/Arrow range-select with clipped elements. +// - In the spirit of Dear ImGui design, your code owns the selection data. +// So this is designed to handle all kind of selection data: e.g. instructive selection (store a bool inside each object), +// external array (store an array aside from your objects), hash/map/set (store only selected items in a hash/map/set), +// or other structures (store indices in an interval tree), etc. // - TreeNode() and Selectable() are supported. // - The work involved to deal with multi-selection differs whether you want to only submit visible items (and clip others) or submit all items // regardless of their visibility. Clipping items is more efficient and will allow you to deal with large lists (1k~100k items) with near zero @@ -2758,9 +2762,6 @@ enum ImGuiMultiSelectFlags_ // Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points and you will need to interpolate // between them to honor range selection. But the code never assume that sortable integers are used (you may store pointers to your object, // and then from the pointer have your own way of iterating from RangeSrc to RangeDst). -// - In the spirit of Dear ImGui design, your code own the selection data. So this is designed to handle all kind of selection data: -// e.g. instructive selection (store a bool inside each object), external array (store an array aside from your objects), -// hash/map/set (store only selected items in a hash/map/set), or other structures (store indices in an interval tree), etc. // Usage flow: // Begin // 1) Call BeginMultiSelect() with the last saved value of ->RangeSrc and its selection state. diff --git a/imgui_internal.h b/imgui_internal.h index c51f28759..ad5366765 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -134,7 +134,7 @@ struct ImGuiInputTextDeactivateData;// Short term storage to backup text of a de struct ImGuiLastItemData; // Status storage for last submitted items struct ImGuiLocEntry; // A localization entry. struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only -struct ImGuiMultiSelectState; // Multi-selection state +struct ImGuiMultiSelectTempData; // Multi-selection temporary state (while traversing). struct ImGuiNavItemData; // Result of a gamepad/keyboard directional navigation move query result struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions struct ImGuiNextWindowData; // Storage for SetNextWindow** functions @@ -1713,7 +1713,7 @@ struct ImGuiOldColumns #ifdef IMGUI_HAS_MULTI_SELECT -struct IMGUI_API ImGuiMultiSelectState +struct IMGUI_API ImGuiMultiSelectTempData { ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) ImGuiMultiSelectFlags Flags; @@ -1726,7 +1726,7 @@ struct IMGUI_API ImGuiMultiSelectState bool InRequestSetRangeNav; // (Internal) set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. - ImGuiMultiSelectState() { Clear(); } + ImGuiMultiSelectTempData() { Clear(); } void Clear() { FocusScopeId = 0; Flags = ImGuiMultiSelectFlags_None; KeyMods = ImGuiMod_None; Window = NULL; In.Clear(); Out.Clear(); InRangeDstPassedBy = InRequestSetRangeNav = false; } }; @@ -2167,7 +2167,8 @@ struct ImGuiContext ImVector ShrinkWidthBuffer; // Multi-Select state - ImGuiMultiSelectState MultiSelectState; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select + ImGuiMultiSelectTempData* CurrentMultiSelect; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select + ImGuiMultiSelectTempData MultiSelectTempData[1]; // Hover Delay system ImGuiID HoverItemDelayId; @@ -2409,6 +2410,7 @@ struct ImGuiContext CurrentTable = NULL; TablesTempDataStacked = 0; CurrentTabBar = NULL; + CurrentMultiSelect = NULL; HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0; HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5fbe0821d..55453dd50 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7122,13 +7122,21 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) // - MultiSelectItemFooter() [Internal] //------------------------------------------------------------------------- +static void DebugLogMultiSelectRequests(const ImGuiMultiSelectData* data) +{ + ImGuiContext& g = *GImGui; + if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestClear\n"); + if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSelectAll\n"); + if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSetRange %p..%p = %d (dir %+d)\n", data->RangeSrc, data->RangeDst, data->RangeValue, data->RangeDirection); +} + ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - - ImGuiMultiSelectState* ms = &g.MultiSelectState; - IM_ASSERT(ms->Window == NULL && ms->Flags == 0 && ms->FocusScopeId == 0); // No recursion allowed yet (we could allow it if we deem it useful) + ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[0];; + IM_ASSERT(g.CurrentMultiSelect == NULL); // No recursion allowed yet (we could allow it if we deem it useful) + g.CurrentMultiSelect = ms; // FIXME: BeginFocusScope() ms->Clear(); @@ -7169,8 +7177,8 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* if (Shortcut(ImGuiKey_Escape)) ms->In.RequestClear = true; - //if (ms->In.RequestClear) IMGUI_DEBUG_LOG_SELECTION("BeginMultiSelect: RequestClear\n"); - //if (ms->In.RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("BeginMultiSelect: RequestSelectAll\n"); + if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) + DebugLogMultiSelectRequests(&ms->In); return &ms->In; } @@ -7178,8 +7186,9 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* ImGuiMultiSelectData* ImGui::EndMultiSelect() { ImGuiContext& g = *GImGui; - ImGuiMultiSelectState* ms = &g.MultiSelectState; - IM_ASSERT(g.MultiSelectState.FocusScopeId == g.CurrentFocusScopeId); + ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; + IM_ASSERT(ms->FocusScopeId == g.CurrentFocusScopeId); + IM_ASSERT(g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Window == g.CurrentWindow); // Clear selection when clicking void? // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! @@ -7198,10 +7207,10 @@ ImGuiMultiSelectData* ImGui::EndMultiSelect() ms->Window = NULL; ms->Flags = ImGuiMultiSelectFlags_None; PopFocusScope(); + g.CurrentMultiSelect = NULL; - //if (ms->Out.RequestClear) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestClear\n"); - //if (ms->Out.RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSelectAll\n"); - //if (ms->Out.RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSetRange %p..%p = %d (dir %+d)\n", ms->Out.RangeSrc, ms->Out.RangeDst, ms->Out.RangeValue, ms->Out.RangeDirection); + if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) + DebugLogMultiSelectRequests(&ms->Out); return &ms->Out; } @@ -7218,16 +7227,17 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d g.NextItemData.SelectionUserData = selection_user_data; g.NextItemData.FocusScopeId = g.CurrentFocusScopeId; - // Auto updating RangeSrcPassedBy for cases were clipper is not used. - if (g.MultiSelectState.In.RangeSrc == (void*)selection_user_data) - g.MultiSelectState.In.RangeSrcPassedBy = true; + // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) + if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect) + if (ms->In.RangeSrc == (void*)selection_user_data) + ms->In.RangeSrcPassedBy = true; } void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGuiMultiSelectState* ms = &g.MultiSelectState; + ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; IM_UNUSED(window); IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); @@ -7266,7 +7276,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGuiMultiSelectState* ms = &g.MultiSelectState; + ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; void* item_data = (void*)g.NextItemData.SelectionUserData; From 35b5ebc9b55f92f685cacbe5caf1f0bac1226e6f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 May 2023 15:16:17 +0200 Subject: [PATCH 0122/2359] MultiSelect: (Breaking) Rename ImGuiMultiSelectData to ImGuiMultiSelectIO. --- imgui.h | 18 +++++++++++------- imgui_demo.cpp | 32 ++++++++++++++++---------------- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 6 +++--- 4 files changed, 32 insertions(+), 28 deletions(-) diff --git a/imgui.h b/imgui.h index 349c77f3e..b18a770ba 100644 --- a/imgui.h +++ b/imgui.h @@ -175,7 +175,7 @@ struct ImGuiIO; // Main configuration and I/O between your a struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. struct ImGuiListClipper; // Helper to manually clip large list of items -struct ImGuiMultiSelectData; // State for a BeginMultiSelect() block +struct ImGuiMultiSelectIO; // Structure to interact with a BeginMultiSelect()/EndMultiSelect() block struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame struct ImGuiPayload; // User data payload for drag and drop operations struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. @@ -670,10 +670,10 @@ namespace ImGui // Multi-selection system for Selectable() and TreeNode() functions. // This enables standard multi-selection/range-selection idioms (CTRL+Click/Arrow, SHIFT+Click/Arrow, etc) in a way that allow items to be fully clipped (= not submitted at all) when not visible. - // Read comments near ImGuiMultiSelectData for details. + // Read comments near ImGuiMultiSelectIO for details. // When enabled, Selectable() and TreeNode() functions will return true when selection needs toggling. - IMGUI_API ImGuiMultiSelectData* BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected); - IMGUI_API ImGuiMultiSelectData* EndMultiSelect(); + IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected); + IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); // Widgets: List Boxes @@ -2779,18 +2779,22 @@ enum ImGuiMultiSelectFlags_ // 5) Call EndMultiSelect(). Save the value of ->RangeSrc for the next frame (you may convert the value in a format that is safe for persistance) // 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable() on a per-item basis. -struct ImGuiMultiSelectData +struct ImGuiMultiSelectIO { + // Output (return by BeginMultiSelect()/EndMultiSelect() + // - Always process requests in their structure order. bool RequestClear; // Begin, End // 1. Request user to clear selection bool RequestSelectAll; // Begin, End // 2. Request user to select all bool RequestSetRange; // End // 3. Request user to set or clear selection in the [RangeSrc..RangeDst] range - bool RangeSrcPassedBy; // Loop // (If clipping) Need to be set by user if RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. bool RangeValue; // End // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. void* RangeSrc; // Begin, End // End: parameter from RequestSetRange request + you need to save this value so you can pass it again next frame. / Begin: this is the value you passed to BeginMultiSelect() void* RangeDst; // End // End: parameter from RequestSetRange request. int RangeDirection; // End // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. - ImGuiMultiSelectData() { Clear(); } + // Input (written by user between BeginMultiSelect()/EndMultiSelect() + bool RangeSrcPassedBy; // Loop // (If using a clipper) Need to be set by user if RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. + + ImGuiMultiSelectIO() { Clear(); } void Clear() { RequestClear = RequestSelectAll = RequestSetRange = RangeSrcPassedBy = RangeValue = false; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3008ca946..e476864d8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2800,11 +2800,11 @@ struct ExampleSelection void SelectAll(int count) { Storage.Data.resize(count); for (int idx = 0; idx < count; idx++) Storage.Data[idx] = ImGuiStoragePair((ImGuiID)idx, 1); SelectionSize = count; } // This could be using SetRange(), but it this way is faster. // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). Must be done in this order! Order->SelectAll->SetRange. - void ApplyRequests(ImGuiMultiSelectData* ms_data, int items_count) + void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) { - if (ms_data->RequestClear) { Clear(); } - if (ms_data->RequestSelectAll) { SelectAll(items_count); } - if (ms_data->RequestSetRange) { SetRange((int)(intptr_t)ms_data->RangeSrc, (int)(intptr_t)ms_data->RangeDst, ms_data->RangeValue ? 1 : 0); } + if (ms_io->RequestClear) { Clear(); } + if (ms_io->RequestSelectAll) { SelectAll(items_count); } + if (ms_io->RequestSetRange) { SetRange((int)(intptr_t)ms_io->RangeSrc, (int)(intptr_t)ms_io->RangeDst, ms_io->RangeValue ? 1 : 0); } } }; @@ -2876,8 +2876,8 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); - selection.ApplyRequests(multi_select_data, ITEMS_COUNT); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); + selection.ApplyRequests(ms_io, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) { @@ -2891,9 +2891,9 @@ static void ShowDemoWindowMultiSelect() } // Apply multi-select requests - multi_select_data = ImGui::EndMultiSelect(); - selection.RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; - selection.ApplyRequests(multi_select_data, ITEMS_COUNT); + ms_io = ImGui::EndMultiSelect(); + selection.RangeRef = (int)(intptr_t)ms_io->RangeSrc; + selection.ApplyRequests(ms_io, ITEMS_COUNT); ImGui::EndListBox(); } @@ -2963,8 +2963,8 @@ static void ShowDemoWindowMultiSelect() ImGuiMultiSelectFlags local_flags = flags; if (use_multiple_scopes) local_flags &= ~ImGuiMultiSelectFlags_ClearOnClickWindowVoid; // local_flags |= ImGuiMultiSelectFlags_ClearOnClickRectVoid; - ImGuiMultiSelectData* multi_select_data = ImGui::BeginMultiSelect(local_flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); - selection->ApplyRequests(multi_select_data, ITEMS_COUNT); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(local_flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); + selection->ApplyRequests(ms_io, ITEMS_COUNT); if (use_multiple_scopes) ImGui::Text("Selection size: %d", selection->GetSize()); // Draw counter below Separator and after BeginMultiSelect() @@ -2983,8 +2983,8 @@ static void ShowDemoWindowMultiSelect() while (clipper.Step()) { // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. - if ((int)(intptr_t)multi_select_data->RangeSrc <= clipper.DisplayStart) - multi_select_data->RangeSrcPassedBy = true; + if ((int)(intptr_t)ms_io->RangeSrc <= clipper.DisplayStart) + ms_io->RangeSrcPassedBy = true; for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) { @@ -3062,9 +3062,9 @@ static void ShowDemoWindowMultiSelect() } // Apply multi-select requests - multi_select_data = ImGui::EndMultiSelect(); - selection->RangeRef = (int)(intptr_t)multi_select_data->RangeSrc; - selection->ApplyRequests(multi_select_data, ITEMS_COUNT); + ms_io = ImGui::EndMultiSelect(); + selection->RangeRef = (int)(intptr_t)ms_io->RangeSrc; + selection->ApplyRequests(ms_io, ITEMS_COUNT); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); diff --git a/imgui_internal.h b/imgui_internal.h index ad5366765..4770a2fd6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1719,8 +1719,8 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiMultiSelectFlags Flags; ImGuiKeyChord KeyMods; ImGuiWindow* Window; - ImGuiMultiSelectData In; // The In requests are set and returned by BeginMultiSelect() - ImGuiMultiSelectData Out; // The Out requests are finalized and returned by EndMultiSelect() + ImGuiMultiSelectIO In; // The In requests are set and returned by BeginMultiSelect() + ImGuiMultiSelectIO Out; // The Out requests are finalized and returned by EndMultiSelect() bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool InRangeDstPassedBy; // (Internal) set by the the item that match NavJustMovedToId when InRequestRangeSetNav is set. bool InRequestSetRangeNav; // (Internal) set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 55453dd50..de53de54d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7122,7 +7122,7 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) // - MultiSelectItemFooter() [Internal] //------------------------------------------------------------------------- -static void DebugLogMultiSelectRequests(const ImGuiMultiSelectData* data) +static void DebugLogMultiSelectRequests(const ImGuiMultiSelectIO* data) { ImGuiContext& g = *GImGui; if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestClear\n"); @@ -7130,7 +7130,7 @@ static void DebugLogMultiSelectRequests(const ImGuiMultiSelectData* data) if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSetRange %p..%p = %d (dir %+d)\n", data->RangeSrc, data->RangeDst, data->RangeValue, data->RangeDirection); } -ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) +ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -7183,7 +7183,7 @@ ImGuiMultiSelectData* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* return &ms->In; } -ImGuiMultiSelectData* ImGui::EndMultiSelect() +ImGuiMultiSelectIO* ImGui::EndMultiSelect() { ImGuiContext& g = *GImGui; ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; From c61ada200f9f4d3bf50fe70bcdbad4a76f6b7182 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 May 2023 16:31:00 +0200 Subject: [PATCH 0123/2359] MultiSelect: Demo tweak. Removed multi-scope from Advanced (too messy), made it a seperate mini-demo. --- imgui_demo.cpp | 282 +++++++++++++++++++++++++++---------------------- 1 file changed, 153 insertions(+), 129 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e476864d8..8117437da 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2870,9 +2870,10 @@ static void ShowDemoWindowMultiSelect() ImGui::BulletText("Shift modifier for range selection."); ImGui::BulletText("CTRL+A to select all."); - // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling regions). + // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling region). const int ITEMS_COUNT = 50; ImGui::Text("Selection size: %d", selection.GetSize()); + ImGui::Text("RangeRef: %d", selection.RangeRef); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; @@ -2901,11 +2902,49 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } + // Demonstrate individual selection scopes in same window + IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, multiple scopes)"); + if (ImGui::TreeNode("Multiple Selection (full, multiple scopes)")) + { + const int SCOPES_COUNT = 3; + const int ITEMS_COUNT = 8; // Per scope + static ExampleSelection selections_data[SCOPES_COUNT]; + + for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++) + { + ExampleSelection* selection = &selections_data[selection_scope_n]; + ImGui::SeparatorText("Selection scope"); + ImGui::Text("Selection size: %d/%d", selection->GetSize(), ITEMS_COUNT); + ImGui::PushID(selection_scope_n); + + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; // | ImGuiMultiSelectFlags_ClearOnClickRectVoid + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); + selection->ApplyRequests(ms_io, ITEMS_COUNT); + + for (int n = 0; n < ITEMS_COUNT; n++) + { + char label[64]; + sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); + bool item_is_selected = selection->GetSelected(n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Selectable(label, item_is_selected); + if (ImGui::IsItemToggledSelection()) + selection->SetSelected(n, !item_is_selected); + } + + // Apply multi-select requests + ms_io = ImGui::EndMultiSelect(); + selection->RangeRef = (int)(intptr_t)ms_io->RangeSrc; + selection->ApplyRequests(ms_io, ITEMS_COUNT); + ImGui::PopID(); + } + ImGui::TreePop(); + } + // Advanced demonstration of BeginMultiSelect() // - Showcase clipping. // - Showcase basic drag and drop. // - Showcase TreeNode variant (note that tree node don't expand in the demo: supporting expanding tree nodes + clipping a separate thing). - // - Showcase having multiple multi-selection scopes in the same window. // - Showcase using inside a table. IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, advanced)"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); @@ -2913,167 +2952,152 @@ static void ShowDemoWindowMultiSelect() { // Options enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; - static bool use_table = false; + static bool use_clipper = true; static bool use_drag_drop = true; - static bool use_multiple_scopes = false; + static bool show_in_table = false; + static bool show_color_button = false; static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; static WidgetType widget_type = WidgetType_Selectable; if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } - ImGui::Checkbox("Use table", &use_table); - ImGui::Checkbox("Use drag & drop", &use_drag_drop); - ImGui::Checkbox("Multiple selection scopes in same window", &use_multiple_scopes); + ImGui::Checkbox("Enable clipper", &use_clipper); + ImGui::Checkbox("Enable drag & drop", &use_drag_drop); + ImGui::Checkbox("Show in a table", &show_in_table); + ImGui::Checkbox("Show color button", &show_color_button); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoMultiSelect", &flags, ImGuiMultiSelectFlags_NoMultiSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoUnselect", &flags, ImGuiMultiSelectFlags_NoUnselect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); - ImGui::BeginDisabled(use_multiple_scopes); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickWindowVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickWindowVoid); - ImGui::EndDisabled(); - // When 'use_multiple_scopes' is set we show 3 selection scopes in the host window instead of 1 in a scrolling window. - static ExampleSelection selections_data[3]; - const int selection_scope_count = use_multiple_scopes ? 3 : 1; - for (int selection_scope_n = 0; selection_scope_n < selection_scope_count; selection_scope_n++) + const int ITEMS_COUNT = 1000; + static ExampleSelection selection; + + ImGui::Text("Selection size: %d/%d", selection.GetSize(), ITEMS_COUNT); + if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { - ExampleSelection* selection = &selections_data[selection_scope_n]; + ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); + if (widget_type == WidgetType_TreeNode) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - const int ITEMS_COUNT = use_multiple_scopes ? 12 : 1000; // Smaller count to make it easier to see multiple scopes in same screen. - ImGui::PushID(selection_scope_n); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); + selection.ApplyRequests(ms_io, ITEMS_COUNT); - // Open a scrolling region - bool draw_selection = true; - if (use_multiple_scopes) + if (show_in_table) { - ImGui::SeparatorText("Selection scope"); - } - else - { - ImGui::Text("Selection size: %d", selection->GetSize()); - draw_selection = ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20)); - } - if (draw_selection) - { - ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); if (widget_type == WidgetType_TreeNode) - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - - ImGuiMultiSelectFlags local_flags = flags; - if (use_multiple_scopes) - local_flags &= ~ImGuiMultiSelectFlags_ClearOnClickWindowVoid; // local_flags |= ImGuiMultiSelectFlags_ClearOnClickRectVoid; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(local_flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); - selection->ApplyRequests(ms_io, ITEMS_COUNT); - - if (use_multiple_scopes) - ImGui::Text("Selection size: %d", selection->GetSize()); // Draw counter below Separator and after BeginMultiSelect() - - if (use_table) - { ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0.0f, 0.0f)); - ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX); - ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f); - ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f); - //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - } + ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f); + //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); + } - ImGuiListClipper clipper; + ImGuiListClipper clipper; + if (use_clipper) clipper.Begin(ITEMS_COUNT); - while (clipper.Step()) - { - // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. + + while (!use_clipper || clipper.Step()) + { + // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. + if (use_clipper) if ((int)(intptr_t)ms_io->RangeSrc <= clipper.DisplayStart) ms_io->RangeSrcPassedBy = true; - for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) + const int item_begin = use_clipper ? clipper.DisplayStart : 0; + const int item_end = use_clipper ? clipper.DisplayEnd : ITEMS_COUNT; + for (int n = item_begin; n < item_end; n++) + { + if (show_in_table) + ImGui::TableNextColumn(); + + ImGui::PushID(n); + const char* category = random_names[n % IM_ARRAYSIZE(random_names)]; + char label[64]; + sprintf(label, "Object %05d: %s", n, category); + + // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part + // of the selection scope doesn't erroneously alter our selection (FIXME-TESTS: Add a test for that!). + if (show_color_button) { - if (use_table) - ImGui::TableNextColumn(); - - ImGui::PushID(n); - const char* category = random_names[n % IM_ARRAYSIZE(random_names)]; - char label[64]; - sprintf(label, "Object %05d: category: %s", n, category); - bool item_is_selected = selection->GetSelected(n); - - // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part - // of the selection scope doesn't erroneously alter our selection (FIXME-TESTS: Add a test for that!). ImU32 dummy_col = (ImU32)((unsigned int)n * 0xC250B74B) | IM_COL32_A_MASK; ImGui::ColorButton("##", ImColor(dummy_col), ImGuiColorEditFlags_NoTooltip, color_button_sz); ImGui::SameLine(); - - ImGui::SetNextItemSelectionUserData(n); - if (widget_type == WidgetType_Selectable) - { - ImGui::Selectable(label, item_is_selected); - if (ImGui::IsItemToggledSelection()) - selection->SetSelected(n, !item_is_selected); - if (use_drag_drop && ImGui::BeginDragDropSource()) - { - ImGui::Text("(Dragging %d items)", selection->GetSize()); - ImGui::EndDragDropSource(); - } - } - else if (widget_type == WidgetType_TreeNode) - { - ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth; - tree_node_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; - if (item_is_selected) - tree_node_flags |= ImGuiTreeNodeFlags_Selected; - bool open = ImGui::TreeNodeEx(label, tree_node_flags); - if (ImGui::IsItemToggledSelection()) - selection->SetSelected(n, !item_is_selected); - if (use_drag_drop && ImGui::BeginDragDropSource()) - { - ImGui::Text("(Dragging %d items)", selection->GetSize()); - ImGui::EndDragDropSource(); - } - if (open) - ImGui::TreePop(); - } - - // Right-click: context menu - if (ImGui::BeginPopupContextItem()) - { - ImGui::Text("(Testing Selectable inside an embedded popup)"); - ImGui::Selectable("Close"); - ImGui::EndPopup(); - } - - // Demo content within a table - if (use_table) - { - ImGui::TableNextColumn(); - ImGui::SetNextItemWidth(-FLT_MIN); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); - ImGui::InputText("###NoLabel", (char*)(void*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); - ImGui::PopStyleVar(); - } - - ImGui::PopID(); } + + bool item_is_selected = selection.GetSelected(n); + ImGui::SetNextItemSelectionUserData(n); + if (widget_type == WidgetType_Selectable) + { + ImGui::Selectable(label, item_is_selected); + if (ImGui::IsItemToggledSelection()) + selection.SetSelected(n, !item_is_selected); + if (use_drag_drop && ImGui::BeginDragDropSource()) + { + ImGui::Text("(Dragging %d items)", selection.GetSize()); + ImGui::EndDragDropSource(); + } + } + else if (widget_type == WidgetType_TreeNode) + { + ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth; + tree_node_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; + if (item_is_selected) + tree_node_flags |= ImGuiTreeNodeFlags_Selected; + bool open = ImGui::TreeNodeEx(label, tree_node_flags); + if (ImGui::IsItemToggledSelection()) + selection.SetSelected(n, !item_is_selected); + if (use_drag_drop && ImGui::BeginDragDropSource()) + { + ImGui::Text("(Dragging %d items)", selection.GetSize()); + ImGui::EndDragDropSource(); + } + if (open) + ImGui::TreePop(); + } + + // Right-click: context menu + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("(Testing Selectable inside an embedded popup)"); + ImGui::Selectable("Close"); + ImGui::EndPopup(); + } + + // Demo content within a table + if (show_in_table) + { + ImGui::TableNextColumn(); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::InputText("###NoLabel", (char*)(void*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); + ImGui::PopStyleVar(); + } + + ImGui::PopID(); } + if (!use_clipper) + break; + } - if (use_table) - { - ImGui::EndTable(); - ImGui::PopStyleVar(); - } - - // Apply multi-select requests - ms_io = ImGui::EndMultiSelect(); - selection->RangeRef = (int)(intptr_t)ms_io->RangeSrc; - selection->ApplyRequests(ms_io, ITEMS_COUNT); - + if (show_in_table) + { + ImGui::EndTable(); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); - - if (use_multiple_scopes == false) - ImGui::EndListBox(); } - ImGui::PopID(); // ImGui::PushID(selection_scope_n); - } // for each selection scope (1 or 3) + + // Apply multi-select requests + ms_io = ImGui::EndMultiSelect(); + selection.RangeRef = (int)(intptr_t)ms_io->RangeSrc; + selection.ApplyRequests(ms_io, ITEMS_COUNT); + + if (widget_type == WidgetType_TreeNode) + ImGui::PopStyleVar(); + ImGui::EndListBox(); + } ImGui::TreePop(); } From a39f9e766147a9d018814894314ec6a64d011479 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Jun 2023 17:49:33 +0200 Subject: [PATCH 0124/2359] MultiSelect: Internals rename of IO fields to avoid ambiguity with io/rw concepts + memset constructors, tweaks. debug --- imgui.h | 32 +++++++--------- imgui_demo.cpp | 2 +- imgui_internal.h | 13 ++++--- imgui_widgets.cpp | 96 +++++++++++++++++++++++------------------------ 4 files changed, 69 insertions(+), 74 deletions(-) diff --git a/imgui.h b/imgui.h index b18a770ba..7d0582a28 100644 --- a/imgui.h +++ b/imgui.h @@ -2781,26 +2781,20 @@ enum ImGuiMultiSelectFlags_ // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable() on a per-item basis. struct ImGuiMultiSelectIO { - // Output (return by BeginMultiSelect()/EndMultiSelect() - // - Always process requests in their structure order. - bool RequestClear; // Begin, End // 1. Request user to clear selection - bool RequestSelectAll; // Begin, End // 2. Request user to select all - bool RequestSetRange; // End // 3. Request user to set or clear selection in the [RangeSrc..RangeDst] range - bool RangeValue; // End // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. - void* RangeSrc; // Begin, End // End: parameter from RequestSetRange request + you need to save this value so you can pass it again next frame. / Begin: this is the value you passed to BeginMultiSelect() - void* RangeDst; // End // End: parameter from RequestSetRange request. - int RangeDirection; // End // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. + // - Always process requests in this order: Clear, SelectAll, SetRange. + // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code. + // // BEGIN / LOOP / END + bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request user to clear selection (processed by app code) + bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request user to select all (processed by app code) + bool RequestSetRange; // / / ms:w, app:r // 3. Request user to alter selection in the [RangeSrc..RangeDst] range using RangeValue. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. + void* RangeSrc; // ms:w / app:r / ms:w, app:r // Begin: Last known RangeSrc value. End: parameter from RequestSetRange request. + void* RangeDst; // / / ms:w, app:r // End: parameter from RequestSetRange request. + ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. + bool RangeValue; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. + bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using a clipper) Need to be set by user if RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. - // Input (written by user between BeginMultiSelect()/EndMultiSelect() - bool RangeSrcPassedBy; // Loop // (If using a clipper) Need to be set by user if RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. - - ImGuiMultiSelectIO() { Clear(); } - void Clear() - { - RequestClear = RequestSelectAll = RequestSetRange = RangeSrcPassedBy = RangeValue = false; - RangeSrc = RangeDst = NULL; - RangeDirection = 0; - } + ImGuiMultiSelectIO() { Clear(); } + void Clear() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8117437da..a07cc6ebf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2779,7 +2779,7 @@ struct ExampleSelection { // Data ImGuiStorage Storage; // Selection set - int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class) + int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class) // FIXME-RANGESELECT: Imply more difficult to track with intrusive selection schemes? int RangeRef; // Reference/pivot item (generally last clicked item) // Functions diff --git a/imgui_internal.h b/imgui_internal.h index 4770a2fd6..42f822c38 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1713,21 +1713,22 @@ struct ImGuiOldColumns #ifdef IMGUI_HAS_MULTI_SELECT +// Temporary storage for multi-select struct IMGUI_API ImGuiMultiSelectTempData { ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) ImGuiMultiSelectFlags Flags; ImGuiKeyChord KeyMods; ImGuiWindow* Window; - ImGuiMultiSelectIO In; // The In requests are set and returned by BeginMultiSelect() - ImGuiMultiSelectIO Out; // The Out requests are finalized and returned by EndMultiSelect() + ImGuiMultiSelectIO BeginIO; // Requests are set and returned by BeginMultiSelect(), written to by user during the loop. + ImGuiMultiSelectIO EndIO; // Requests are set during the loop and returned by EndMultiSelect(). bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. - bool InRangeDstPassedBy; // (Internal) set by the the item that match NavJustMovedToId when InRequestRangeSetNav is set. - bool InRequestSetRangeNav; // (Internal) set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. + bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. + bool SetRangeDstPassedBy; // Set by the the item that matches NavJustMovedToId when IsSetRange is set. //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. - ImGuiMultiSelectTempData() { Clear(); } - void Clear() { FocusScopeId = 0; Flags = ImGuiMultiSelectFlags_None; KeyMods = ImGuiMod_None; Window = NULL; In.Clear(); Out.Clear(); InRangeDstPassedBy = InRequestSetRangeNav = false; } + ImGuiMultiSelectTempData() { Clear(); } + void Clear() { memset(this, 0, sizeof(*this)); } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index de53de54d..d9008e340 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7120,21 +7120,22 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) // - SetNextItemSelectionUserData() // - MultiSelectItemHeader() [Internal] // - MultiSelectItemFooter() [Internal] +// - DebugNodeMultiSelectState() [Internal] //------------------------------------------------------------------------- -static void DebugLogMultiSelectRequests(const ImGuiMultiSelectIO* data) +static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* data) { ImGuiContext& g = *GImGui; - if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestClear\n"); - if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSelectAll\n"); - if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("EndMultiSelect: RequestSetRange %p..%p = %d (dir %+d)\n", data->RangeSrc, data->RangeDst, data->RangeValue, data->RangeDirection); + if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); + if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); + if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, data->RangeSrc, data->RangeDst, data->RangeValue, data->RangeDirection); } ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[0];; + ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[0]; IM_ASSERT(g.CurrentMultiSelect == NULL); // No recursion allowed yet (we could allow it if we deem it useful) g.CurrentMultiSelect = ms; @@ -7151,36 +7152,35 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* r if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) { - ms->In.RangeSrc = ms->Out.RangeSrc = range_ref; - ms->In.RangeValue = ms->Out.RangeValue = range_ref_is_selected; + ms->BeginIO.RangeSrc = ms->EndIO.RangeSrc = range_ref; + ms->BeginIO.RangeValue = ms->EndIO.RangeValue = range_ref_is_selected; } // Auto clear when using Navigation to move within the selection (we compare SelectScopeId so it possible to use multiple lists inside a same window) - // FIXME: Polling key mods after the fact (frame following the move request) is incorrect, but latching it would requires non-trivial change in MultiSelectItemFooter() if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) { if (ms->KeyMods & ImGuiMod_Shift) - ms->InRequestSetRangeNav = true; + ms->IsSetRange = true; if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) - ms->In.RequestClear = true; + ms->BeginIO.RequestClear = true; } // Shortcut: Select all (CTRL+A) if (ms->IsFocused && !(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) - ms->In.RequestSelectAll = true; + ms->BeginIO.RequestSelectAll = true; // Shortcut: Clear selection (Escape) // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. // Otherwise may be done by caller but it means Shortcut() needs to be exposed. if (ms->IsFocused && (flags & ImGuiMultiSelectFlags_ClearOnEscape)) if (Shortcut(ImGuiKey_Escape)) - ms->In.RequestClear = true; + ms->BeginIO.RequestClear = true; if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) - DebugLogMultiSelectRequests(&ms->In); + DebugLogMultiSelectRequests("BeginMultiSelect", &ms->BeginIO); - return &ms->In; + return &ms->BeginIO; } ImGuiMultiSelectIO* ImGui::EndMultiSelect() @@ -7196,13 +7196,13 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (IsWindowHovered() && g.HoveredId == 0) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { - ms->Out.RequestClear = true; - ms->Out.RequestSelectAll = ms->Out.RequestSetRange = false; + ms->EndIO.RequestClear = true; + ms->EndIO.RequestSelectAll = ms->EndIO.RequestSetRange = false; } // Unwind if (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) - ms->Out.RangeValue = true; + ms->EndIO.RangeValue = true; ms->FocusScopeId = 0; ms->Window = NULL; ms->Flags = ImGuiMultiSelectFlags_None; @@ -7210,9 +7210,9 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() g.CurrentMultiSelect = NULL; if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) - DebugLogMultiSelectRequests(&ms->Out); + DebugLogMultiSelectRequests("EndMultiSelect", &ms->EndIO); - return &ms->Out; + return &ms->EndIO; } void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data) @@ -7229,8 +7229,8 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect) - if (ms->In.RangeSrc == (void*)selection_user_data) - ms->In.RangeSrcPassedBy = true; + if (ms->BeginIO.RangeSrc == (void*)selection_user_data) + ms->BeginIO.RangeSrcPassedBy = true; } void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) @@ -7248,23 +7248,23 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. // If you are using a clipper (aka not submitting every element of the list) you need to process the Clear/SelectAll request after calling BeginMultiSelect() bool selected = *p_selected; - if (ms->In.RequestClear) + if (ms->BeginIO.RequestClear) selected = false; - else if (ms->In.RequestSelectAll) + else if (ms->BeginIO.RequestSelectAll) selected = true; // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) // For this to work, IF the user is clipping items, they need to set RangeSrcPassedBy = true to notify the system. - if (ms->InRequestSetRangeNav) + if (ms->IsSetRange) { IM_ASSERT(id != 0); IM_ASSERT((ms->KeyMods & ImGuiMod_Shift) != 0); - const bool is_range_src = (ms->In.RangeSrc == item_data); - const bool is_range_dst = !ms->InRangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. + const bool is_range_src = (ms->BeginIO.RangeSrc == item_data); + const bool is_range_dst = !ms->SetRangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. if (is_range_dst) - ms->InRangeDstPassedBy = true; - if (is_range_src || is_range_dst || ms->In.RangeSrcPassedBy != ms->InRangeDstPassedBy) - selected = ms->In.RangeValue; + ms->SetRangeDstPassedBy = true; + if (is_range_src || is_range_dst || ms->BeginIO.RangeSrcPassedBy != ms->SetRangeDstPassedBy) + selected = ms->BeginIO.RangeValue; else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) selected = false; } @@ -7331,53 +7331,53 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) if (is_shift && is_multiselect) { // Shift+Arrow always select, Ctrl+Shift+Arrow copy source selection state. - ms->Out.RequestSetRange = true; - ms->Out.RangeDst = item_data; + ms->EndIO.RequestSetRange = true; + ms->EndIO.RangeDst = item_data; if (!is_ctrl) - ms->Out.RangeValue = true; - ms->Out.RangeDirection = ms->In.RangeSrcPassedBy ? +1 : -1; + ms->EndIO.RangeValue = true; + ms->EndIO.RangeDirection = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; } else { // Ctrl inverts selection, otherwise always select selected = (is_ctrl && (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) == 0) ? !selected : true; - ms->Out.RangeSrc = ms->Out.RangeDst = item_data; - ms->Out.RangeValue = selected; + ms->EndIO.RangeSrc = ms->EndIO.RangeDst = item_data; + ms->EndIO.RangeValue = selected; } if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) { // Mouse click without CTRL clears the selection, unless the clicked item is already selected if (is_multiselect && !is_ctrl) - ms->Out.RequestClear = true; - if (is_multiselect && !is_shift && ms->Out.RequestClear) + ms->EndIO.RequestClear = true; + if (is_multiselect && !is_shift && ms->EndIO.RequestClear) { // For toggle selection unless there is a Clear request, we can handle it completely locally without sending a RangeSet request. - IM_ASSERT(ms->Out.RangeSrc == ms->Out.RangeDst); // Setup by else block above - ms->Out.RequestSetRange = true; - ms->Out.RangeValue = selected; - ms->Out.RangeDirection = +1; + IM_ASSERT(ms->EndIO.RangeSrc == ms->EndIO.RangeDst); // Setup by else block above + ms->EndIO.RequestSetRange = true; + ms->EndIO.RangeValue = selected; + ms->EndIO.RangeDirection = +1; } if (!is_multiselect) { // Clear selection, set single item range - IM_ASSERT(ms->Out.RangeSrc == item_data && ms->Out.RangeDst == item_data); // Setup by block above - ms->Out.RequestClear = true; - ms->Out.RequestSetRange = true; + IM_ASSERT(ms->EndIO.RangeSrc == item_data && ms->EndIO.RangeDst == item_data); // Setup by block above + ms->EndIO.RequestClear = true; + ms->EndIO.RequestSetRange = true; } } else if (input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) { if (is_multiselect && is_shift && !is_ctrl) - ms->Out.RequestClear = true; + ms->EndIO.RequestClear = true; else if (!is_multiselect) - ms->Out.RequestClear = true; + ms->EndIO.RequestClear = true; } } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) - if (ms->Out.RangeSrc == item_data && is_ctrl && is_shift && is_multiselect && !(ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) - ms->Out.RangeValue = selected; + if (ms->EndIO.RangeSrc == item_data && is_ctrl && is_shift && is_multiselect && !(ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) + ms->EndIO.RangeValue = selected; *p_selected = selected; *p_pressed = pressed; From a83326bc52969f71b4ec0ad5368b4922f6e0f25b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 2 Jun 2023 15:49:17 +0200 Subject: [PATCH 0125/2359] MultiSelect: (Breaking) Renamed 'RangeSrc -> 'RangeSrcItem', "RangeDst' -> 'RangeDstItem' This is necessary to have consistent names in upcoming fields (NavIdItem etc.) --- imgui.h | 22 +++++++++++----------- imgui_demo.cpp | 12 ++++++------ imgui_internal.h | 2 +- imgui_widgets.cpp | 24 ++++++++++++------------ 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/imgui.h b/imgui.h index 7d0582a28..fc25f3798 100644 --- a/imgui.h +++ b/imgui.h @@ -2757,26 +2757,26 @@ enum ImGuiMultiSelectFlags_ // performance penalty, but requires a little more work on the code. If you only have a few hundreds elements in your possible selection set, // you may as well not bother with clipping, as the cost should be negligible (as least on Dear ImGui side). // If you are not sure, always start without clipping and you can work your way to the more optimized version afterwards. -// - The void* RangeSrc/RangeDst value represent a selectable object. They are the values you pass to SetNextItemSelectionUserData(). +// - The void* RangeSrcItem/RangeDstItem value represent a selectable object. They are the value you pass to SetNextItemSelectionUserData(). // Most likely you will want to store an index here. // Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points and you will need to interpolate // between them to honor range selection. But the code never assume that sortable integers are used (you may store pointers to your object, -// and then from the pointer have your own way of iterating from RangeSrc to RangeDst). +// and then from the pointer have your own way of iterating from RangeSrcItem to RangeDstItem). // Usage flow: // Begin -// 1) Call BeginMultiSelect() with the last saved value of ->RangeSrc and its selection state. +// 1) Call BeginMultiSelect() with the last saved value of ->RangeSrcItem and its selection state. // It is because you need to pass its selection state (and you own selection) that we don't store this value in Dear ImGui. // (For the initial frame or when resetting your selection state: you may use the value for your first item or a "null" value that matches the type stored in your void*). // 2) Honor Clear/SelectAll/SetRange requests by updating your selection data. (Only required if you are using a clipper in step 4: but you can use same code as step 6 anyway.) // Loop -// 3) Set RangeSrcPassedBy=true if the RangeSrc item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] +// 3) Set RangeSrcPassedBy=true if the RangeSrcItem item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] // This is because for range-selection we need to know if we are currently "inside" or "outside" the range. -// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrc) { data->RangeSrcPassedBy = true; } +// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrcItem) { data->RangeSrcPassedBy = true; } // 4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // Call IsItemToggledSelection() to query if the selection state has been toggled, if you need the info immediately for your display (before EndMultiSelect()). // When cannot provide a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggled" event instead. // End -// 5) Call EndMultiSelect(). Save the value of ->RangeSrc for the next frame (you may convert the value in a format that is safe for persistance) +// 5) Call EndMultiSelect(). Save the value of ->RangeSrcItem for the next frame (you may convert the value in a format that is safe for persistance) // 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable() on a per-item basis. struct ImGuiMultiSelectIO @@ -2786,12 +2786,12 @@ struct ImGuiMultiSelectIO // // BEGIN / LOOP / END bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request user to clear selection (processed by app code) bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request user to select all (processed by app code) - bool RequestSetRange; // / / ms:w, app:r // 3. Request user to alter selection in the [RangeSrc..RangeDst] range using RangeValue. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. - void* RangeSrc; // ms:w / app:r / ms:w, app:r // Begin: Last known RangeSrc value. End: parameter from RequestSetRange request. - void* RangeDst; // / / ms:w, app:r // End: parameter from RequestSetRange request. - ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrc came before RangeDst, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. + bool RequestSetRange; // / / ms:w, app:r // 3. Request user to alter selection in the [RangeSrcItem..RangeDstItem] range using RangeValue. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. + void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionData() value for RangeSrcItem value. End: parameter from RequestSetRange request. + void* RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. + ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrcItem came before RangeDstItem, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. bool RangeValue; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. - bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using a clipper) Need to be set by user if RangeSrc was part of the clipped set before submitting the visible items. Ignore if not clipping. + bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using a clipper) Need to be set by user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. ImGuiMultiSelectIO() { Clear(); } void Clear() { memset(this, 0, sizeof(*this)); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a07cc6ebf..17c976c83 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2804,7 +2804,7 @@ struct ExampleSelection { if (ms_io->RequestClear) { Clear(); } if (ms_io->RequestSelectAll) { SelectAll(items_count); } - if (ms_io->RequestSetRange) { SetRange((int)(intptr_t)ms_io->RangeSrc, (int)(intptr_t)ms_io->RangeDst, ms_io->RangeValue ? 1 : 0); } + if (ms_io->RequestSetRange) { SetRange((int)(intptr_t)ms_io->RangeSrcItem, (int)(intptr_t)ms_io->RangeDstItem, ms_io->RangeValue ? 1 : 0); } } }; @@ -2893,7 +2893,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.RangeRef = (int)(intptr_t)ms_io->RangeSrc; + selection.RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; selection.ApplyRequests(ms_io, ITEMS_COUNT); ImGui::EndListBox(); @@ -2934,7 +2934,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection->RangeRef = (int)(intptr_t)ms_io->RangeSrc; + selection->RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; selection->ApplyRequests(ms_io, ITEMS_COUNT); ImGui::PopID(); } @@ -3001,9 +3001,9 @@ static void ShowDemoWindowMultiSelect() while (!use_clipper || clipper.Step()) { - // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. + // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeSrcItem was passed over. if (use_clipper) - if ((int)(intptr_t)ms_io->RangeSrc <= clipper.DisplayStart) + if ((int)(intptr_t)ms_io->RangeSrcItem <= clipper.DisplayStart) ms_io->RangeSrcPassedBy = true; const int item_begin = use_clipper ? clipper.DisplayStart : 0; @@ -3091,7 +3091,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.RangeRef = (int)(intptr_t)ms_io->RangeSrc; + selection.RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; selection.ApplyRequests(ms_io, ITEMS_COUNT); if (widget_type == WidgetType_TreeNode) diff --git a/imgui_internal.h b/imgui_internal.h index 42f822c38..2e1a0bee3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1724,7 +1724,7 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiMultiSelectIO EndIO; // Requests are set during the loop and returned by EndMultiSelect(). bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. - bool SetRangeDstPassedBy; // Set by the the item that matches NavJustMovedToId when IsSetRange is set. + bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectTempData() { Clear(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d9008e340..523d2add0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7128,7 +7128,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe ImGuiContext& g = *GImGui; if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); - if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, data->RangeSrc, data->RangeDst, data->RangeValue, data->RangeDirection); + if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, data->RangeSrcItem, data->RangeDstItem, data->RangeValue, data->RangeDirection); } ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) @@ -7152,7 +7152,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* r if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) { - ms->BeginIO.RangeSrc = ms->EndIO.RangeSrc = range_ref; + ms->BeginIO.RangeSrcItem = ms->EndIO.RangeSrcItem = range_ref; ms->BeginIO.RangeValue = ms->EndIO.RangeValue = range_ref_is_selected; } @@ -7229,7 +7229,7 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect) - if (ms->BeginIO.RangeSrc == (void*)selection_user_data) + if (ms->BeginIO.RangeSrcItem == (void*)selection_user_data) ms->BeginIO.RangeSrcPassedBy = true; } @@ -7259,11 +7259,11 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) { IM_ASSERT(id != 0); IM_ASSERT((ms->KeyMods & ImGuiMod_Shift) != 0); - const bool is_range_src = (ms->BeginIO.RangeSrc == item_data); - const bool is_range_dst = !ms->SetRangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. + const bool is_range_src = (ms->BeginIO.RangeSrcItem == item_data); + const bool is_range_dst = !ms->RangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. if (is_range_dst) - ms->SetRangeDstPassedBy = true; - if (is_range_src || is_range_dst || ms->BeginIO.RangeSrcPassedBy != ms->SetRangeDstPassedBy) + ms->RangeDstPassedBy = true; + if (is_range_src || is_range_dst || ms->BeginIO.RangeSrcPassedBy != ms->RangeDstPassedBy) selected = ms->BeginIO.RangeValue; else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) selected = false; @@ -7332,7 +7332,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { // Shift+Arrow always select, Ctrl+Shift+Arrow copy source selection state. ms->EndIO.RequestSetRange = true; - ms->EndIO.RangeDst = item_data; + ms->EndIO.RangeDstItem = item_data; if (!is_ctrl) ms->EndIO.RangeValue = true; ms->EndIO.RangeDirection = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; @@ -7341,7 +7341,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { // Ctrl inverts selection, otherwise always select selected = (is_ctrl && (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) == 0) ? !selected : true; - ms->EndIO.RangeSrc = ms->EndIO.RangeDst = item_data; + ms->EndIO.RangeSrcItem = ms->EndIO.RangeDstItem = item_data; ms->EndIO.RangeValue = selected; } @@ -7353,7 +7353,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) if (is_multiselect && !is_shift && ms->EndIO.RequestClear) { // For toggle selection unless there is a Clear request, we can handle it completely locally without sending a RangeSet request. - IM_ASSERT(ms->EndIO.RangeSrc == ms->EndIO.RangeDst); // Setup by else block above + IM_ASSERT(ms->EndIO.RangeSrcItem == ms->EndIO.RangeDstItem); // Setup by else block above ms->EndIO.RequestSetRange = true; ms->EndIO.RangeValue = selected; ms->EndIO.RangeDirection = +1; @@ -7361,7 +7361,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) if (!is_multiselect) { // Clear selection, set single item range - IM_ASSERT(ms->EndIO.RangeSrc == item_data && ms->EndIO.RangeDst == item_data); // Setup by block above + IM_ASSERT(ms->EndIO.RangeSrcItem == item_data && ms->EndIO.RangeDstItem == item_data); // Setup by block above ms->EndIO.RequestClear = true; ms->EndIO.RequestSetRange = true; } @@ -7376,7 +7376,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) - if (ms->EndIO.RangeSrc == item_data && is_ctrl && is_shift && is_multiselect && !(ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) + if (ms->EndIO.RangeSrcItem == item_data && is_ctrl && is_shift && is_multiselect && !(ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) ms->EndIO.RangeValue = selected; *p_selected = selected; From ccf43d6a964e4a1cb81e9288636846ab39292879 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 2 Jun 2023 16:19:24 +0200 Subject: [PATCH 0126/2359] MultiSelect: (Breaking) Renamed 'RangeValue' -> 'RangeSelected' + amend comments. --- imgui.h | 17 +++++++++-------- imgui_demo.cpp | 3 ++- imgui_widgets.cpp | 16 ++++++++-------- 3 files changed, 19 insertions(+), 17 deletions(-) diff --git a/imgui.h b/imgui.h index fc25f3798..3c9a4bc62 100644 --- a/imgui.h +++ b/imgui.h @@ -2782,16 +2782,17 @@ enum ImGuiMultiSelectFlags_ struct ImGuiMultiSelectIO { // - Always process requests in this order: Clear, SelectAll, SetRange. - // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code. - // // BEGIN / LOOP / END - bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request user to clear selection (processed by app code) - bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request user to select all (processed by app code) - bool RequestSetRange; // / / ms:w, app:r // 3. Request user to alter selection in the [RangeSrcItem..RangeDstItem] range using RangeValue. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. - void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionData() value for RangeSrcItem value. End: parameter from RequestSetRange request. + // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. + // REQUESTS ----------------// BEGIN / LOOP / END + bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. + bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. + bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeSrcItem..RangeDstItem] items, based on RangeSelected. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. + // STATE/ARGUMENTS ---------// BEGIN / LOOP / END + void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionData() value for RangeSrcItem. End: parameter from RequestSetRange request. void* RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrcItem came before RangeDstItem, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. - bool RangeValue; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. - bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using a clipper) Need to be set by user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. + bool RangeSelected; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. + bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. ImGuiMultiSelectIO() { Clear(); } void Clear() { memset(this, 0, sizeof(*this)); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 17c976c83..16c53adf8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -605,6 +605,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::End(); } + static void ShowDemoWindowWidgets() { IMGUI_DEMO_MARKER("Widgets"); @@ -2804,7 +2805,7 @@ struct ExampleSelection { if (ms_io->RequestClear) { Clear(); } if (ms_io->RequestSelectAll) { SelectAll(items_count); } - if (ms_io->RequestSetRange) { SetRange((int)(intptr_t)ms_io->RangeSrcItem, (int)(intptr_t)ms_io->RangeDstItem, ms_io->RangeValue ? 1 : 0); } + if (ms_io->RequestSetRange) { SetRange((int)(intptr_t)ms_io->RangeSrcItem, (int)(intptr_t)ms_io->RangeDstItem, ms_io->RangeSelected ? 1 : 0); } } }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 523d2add0..5c9a0eede 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7128,7 +7128,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe ImGuiContext& g = *GImGui; if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); - if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, data->RangeSrcItem, data->RangeDstItem, data->RangeValue, data->RangeDirection); + if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, data->RangeSrcItem, data->RangeDstItem, data->RangeSelected, data->RangeDirection); } ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) @@ -7153,7 +7153,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* r if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) { ms->BeginIO.RangeSrcItem = ms->EndIO.RangeSrcItem = range_ref; - ms->BeginIO.RangeValue = ms->EndIO.RangeValue = range_ref_is_selected; + ms->BeginIO.RangeSelected = ms->EndIO.RangeSelected = range_ref_is_selected; } // Auto clear when using Navigation to move within the selection (we compare SelectScopeId so it possible to use multiple lists inside a same window) @@ -7202,7 +7202,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() // Unwind if (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) - ms->EndIO.RangeValue = true; + ms->EndIO.RangeSelected = true; ms->FocusScopeId = 0; ms->Window = NULL; ms->Flags = ImGuiMultiSelectFlags_None; @@ -7264,7 +7264,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) if (is_range_dst) ms->RangeDstPassedBy = true; if (is_range_src || is_range_dst || ms->BeginIO.RangeSrcPassedBy != ms->RangeDstPassedBy) - selected = ms->BeginIO.RangeValue; + selected = ms->BeginIO.RangeSelected; else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) selected = false; } @@ -7334,7 +7334,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ms->EndIO.RequestSetRange = true; ms->EndIO.RangeDstItem = item_data; if (!is_ctrl) - ms->EndIO.RangeValue = true; + ms->EndIO.RangeSelected = true; ms->EndIO.RangeDirection = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; } else @@ -7342,7 +7342,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Ctrl inverts selection, otherwise always select selected = (is_ctrl && (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) == 0) ? !selected : true; ms->EndIO.RangeSrcItem = ms->EndIO.RangeDstItem = item_data; - ms->EndIO.RangeValue = selected; + ms->EndIO.RangeSelected = selected; } if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) @@ -7355,7 +7355,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // For toggle selection unless there is a Clear request, we can handle it completely locally without sending a RangeSet request. IM_ASSERT(ms->EndIO.RangeSrcItem == ms->EndIO.RangeDstItem); // Setup by else block above ms->EndIO.RequestSetRange = true; - ms->EndIO.RangeValue = selected; + ms->EndIO.RangeSelected = selected; ms->EndIO.RangeDirection = +1; } if (!is_multiselect) @@ -7377,7 +7377,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) if (ms->EndIO.RangeSrcItem == item_data && is_ctrl && is_shift && is_multiselect && !(ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) - ms->EndIO.RangeValue = selected; + ms->EndIO.RangeSelected = selected; *p_selected = selected; *p_pressed = pressed; From 6ef70a97fd43276a306a5347ef11d1ba00939be7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jun 2023 15:03:24 +0200 Subject: [PATCH 0127/2359] MultiSelect: Remove ImGuiMultiSelectFlags_NoUnselect because I currently can't find use for this specific design. And/or it seem partly broken. --- imgui.h | 9 ++++----- imgui_demo.cpp | 1 - imgui_widgets.cpp | 6 ++---- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/imgui.h b/imgui.h index 3c9a4bc62..e42141782 100644 --- a/imgui.h +++ b/imgui.h @@ -44,7 +44,7 @@ Index of this file: // [SECTION] ImGuiIO // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectData) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) @@ -2719,7 +2719,7 @@ struct ImColor }; //----------------------------------------------------------------------------- -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectData) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO) //----------------------------------------------------------------------------- #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. @@ -2733,11 +2733,10 @@ enum ImGuiMultiSelectFlags_ { ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, // Disable selecting more than one item. This is not very useful at this kind of selection can be implemented without BeginMultiSelect(), but this is available for consistency. - ImGuiMultiSelectFlags_NoUnselect = 1 << 1, // Disable unselecting items with CTRL+Click, CTRL+Space etc. - ImGuiMultiSelectFlags_NoSelectAll = 1 << 2, // Disable CTRL+A shortcut to set RequestSelectAll + ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to set RequestSelectAll + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 2, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickWindowVoid= 1 << 3, // Clear selection when clicking on empty location within host window (use if BeginMultiSelect() covers a whole window) //ImGuiMultiSelectFlags_ClearOnClickRectVoid= 1 << 4, // Clear selection when clicking on empty location within rectangle covered by selection scope (use if multiple BeginMultiSelect() are used in the same host window) - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 5, // Clear selection when pressing Escape while scope is focused. }; // Abstract: diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 16c53adf8..3bb6171a9 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2968,7 +2968,6 @@ static void ShowDemoWindowMultiSelect() ImGui::Checkbox("Show in a table", &show_in_table); ImGui::Checkbox("Show color button", &show_color_button); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoMultiSelect", &flags, ImGuiMultiSelectFlags_NoMultiSelect); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoUnselect", &flags, ImGuiMultiSelectFlags_NoUnselect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickWindowVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickWindowVoid); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5c9a0eede..6cf0f958e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7201,8 +7201,6 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() } // Unwind - if (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) - ms->EndIO.RangeSelected = true; ms->FocusScopeId = 0; ms->Window = NULL; ms->Flags = ImGuiMultiSelectFlags_None; @@ -7340,7 +7338,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) else { // Ctrl inverts selection, otherwise always select - selected = (is_ctrl && (ms->Flags & ImGuiMultiSelectFlags_NoUnselect) == 0) ? !selected : true; + selected = is_ctrl ? !selected : true; ms->EndIO.RangeSrcItem = ms->EndIO.RangeDstItem = item_data; ms->EndIO.RangeSelected = selected; } @@ -7376,7 +7374,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) - if (ms->EndIO.RangeSrcItem == item_data && is_ctrl && is_shift && is_multiselect && !(ms->Flags & ImGuiMultiSelectFlags_NoUnselect)) + if (ms->EndIO.RangeSrcItem == item_data && is_ctrl && is_shift && is_multiselect) ms->EndIO.RangeSelected = selected; *p_selected = selected; From 1ea9ca748cdc24e9997e442e9cd93b4687e6bbcb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Jun 2023 17:00:43 +0200 Subject: [PATCH 0128/2359] MultiSelect: Remove the need for using IsItemToggledSelection(). Update comments. This is the simple version that past our tests. MultiSelectItemFooter() is in need of a cleanup. --- imgui.h | 4 ++-- imgui_demo.cpp | 8 -------- imgui_widgets.cpp | 33 +++++++++++++++++++++------------ 3 files changed, 23 insertions(+), 22 deletions(-) diff --git a/imgui.h b/imgui.h index e42141782..d00adb1f7 100644 --- a/imgui.h +++ b/imgui.h @@ -2772,8 +2772,8 @@ enum ImGuiMultiSelectFlags_ // This is because for range-selection we need to know if we are currently "inside" or "outside" the range. // If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrcItem) { data->RangeSrcPassedBy = true; } // 4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. -// Call IsItemToggledSelection() to query if the selection state has been toggled, if you need the info immediately for your display (before EndMultiSelect()). -// When cannot provide a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggled" event instead. +// (You may optionally call IsItemToggledSelection() to query if the selection state has been toggled for a given item, if you need that info immediately for your display (before EndMultiSelect()).) +// (When cannot provide a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggled" event instead.) // End // 5) Call EndMultiSelect(). Save the value of ->RangeSrcItem for the next frame (you may convert the value in a format that is safe for persistance) // 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3bb6171a9..c66a9e434 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2888,8 +2888,6 @@ static void ShowDemoWindowMultiSelect() bool item_is_selected = selection.GetSelected(n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); - if (ImGui::IsItemToggledSelection()) - selection.SetSelected(n, !item_is_selected); } // Apply multi-select requests @@ -2929,8 +2927,6 @@ static void ShowDemoWindowMultiSelect() bool item_is_selected = selection->GetSelected(n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); - if (ImGui::IsItemToggledSelection()) - selection->SetSelected(n, !item_is_selected); } // Apply multi-select requests @@ -3032,8 +3028,6 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_Selectable) { ImGui::Selectable(label, item_is_selected); - if (ImGui::IsItemToggledSelection()) - selection.SetSelected(n, !item_is_selected); if (use_drag_drop && ImGui::BeginDragDropSource()) { ImGui::Text("(Dragging %d items)", selection.GetSize()); @@ -3047,8 +3041,6 @@ static void ShowDemoWindowMultiSelect() if (item_is_selected) tree_node_flags |= ImGuiTreeNodeFlags_Selected; bool open = ImGui::TreeNodeEx(label, tree_node_flags); - if (ImGui::IsItemToggledSelection()) - selection.SetSelected(n, !item_is_selected); if (use_drag_drop && ImGui::BeginDragDropSource()) { ImGui::Text("(Dragging %d items)", selection.GetSize()); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6cf0f958e..2cd774ee1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7156,7 +7156,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* r ms->BeginIO.RangeSelected = ms->EndIO.RangeSelected = range_ref_is_selected; } - // Auto clear when using Navigation to move within the selection (we compare SelectScopeId so it possible to use multiple lists inside a same window) + // Auto clear when using Navigation to move within the selection + // (we compare FocusScopeId so it possible to use multiple selections inside a same window) if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) { if (ms->KeyMods & ImGuiMod_Shift) @@ -7255,8 +7256,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) // For this to work, IF the user is clipping items, they need to set RangeSrcPassedBy = true to notify the system. if (ms->IsSetRange) { - IM_ASSERT(id != 0); - IM_ASSERT((ms->KeyMods & ImGuiMod_Shift) != 0); + IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0); const bool is_range_src = (ms->BeginIO.RangeSrcItem == item_data); const bool is_range_dst = !ms->RangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. if (is_range_dst) @@ -7315,15 +7315,22 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Alter selection if (pressed && (!enter_pressed || !selected)) { - //------------------------------------------------------------------------------------------------------------------------------------------------- - // ACTION | Begin | Item Old | Item New | End - //------------------------------------------------------------------------------------------------------------------------------------------------- - // Keys Navigated, Ctrl=0, Shift=0 | In.Clear | Clear -> Sel=0 | Src=item, Pressed -> Sel=1 | - // Keys Navigated, Ctrl=0, Shift=1 | n/a | n/a | Dst=item, Pressed -> Sel=1, Out.Clear, Out.SetRange=1 | Clear + SetRange - // Keys Navigated, Ctrl=1, Shift=1 | n/a | n/a | Dst=item, Pressed -> Sel=Src, Out.Clear, Out.SetRange=Src | Clear + SetRange - // Mouse Pressed, Ctrl=0, Shift=0 | n/a | n/a (Sel=1) | Src=item, Pressed -> Sel=1, Out.Clear, Out.SetRange=1 | Clear + SetRange - // Mouse Pressed, Ctrl=0, Shift=1 | n/a | n/a | Dst=item, Pressed -> Sel=1, Out.Clear, Out.SetRange=1 | Clear + SetRange - //------------------------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------- + // ACTION | Begin | Pressed/Activated | End + //---------------------------------------------------------------------------------------- + // Keys Navigated: | Clear | Src=item, Sel=1 SetRange 1 + // Keys Navigated: Ctrl | n/a | n/a + // Keys Navigated: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1 + // Keys Navigated: Ctrl+Shift | n/a | Dst=item, Sel=Src => Clear + SetRange Src-Dst + // Keys Activated: | n/a | Src=item, Sel=1 => Clear + SetRange 1 + // Keys Activated: Ctrl | n/a | Src=item, Sel=!Sel => SetSange 1 + // Keys Activated: Shift | n/a | Dst=item, Sel=1 => Clear + SetSange 1 + //---------------------------------------------------------------------------------------- + // Mouse Pressed: | n/a | Src=item, Sel=1, => Clear + SetRange 1 + // Mouse Pressed: Ctrl | n/a | Src=item, Sel=!Sel => SetRange 1 + // Mouse Pressed: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1 + // Mouse Pressed: Ctrl+Shift | n/a | Dst=item, Sel=!Sel => SetRange Src-Dst + //---------------------------------------------------------------------------------------- ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; if (is_shift && is_multiselect) @@ -7341,6 +7348,8 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = is_ctrl ? !selected : true; ms->EndIO.RangeSrcItem = ms->EndIO.RangeDstItem = item_data; ms->EndIO.RangeSelected = selected; + ms->EndIO.RequestSetRange = true; + ms->EndIO.RangeDirection = +1; } if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) From 961b81c362891b31c433fa130db57df2239fa17f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 Jun 2023 14:17:16 +0200 Subject: [PATCH 0129/2359] MultiSelect: Tidying up/simpllifying MultiSelectItemFooter(). Intended to be entirely a no-op, merely a transform of source code for simplification. But committing separatey from behavior change in previous change. --- imgui_widgets.cpp | 33 +++++++++------------------------ 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2cd774ee1..911aa8b1d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7294,6 +7294,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } // Right-click handling: this could be moved at the Selectable() level. + // FIXME-MULTISELECT: See https://github.com/ocornut/imgui/pull/5816 bool hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); if (hovered && IsMouseClicked(1)) { @@ -7333,11 +7334,12 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) //---------------------------------------------------------------------------------------- ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; + ms->EndIO.RequestSetRange = true; + ms->EndIO.RangeDstItem = item_data; if (is_shift && is_multiselect) { - // Shift+Arrow always select, Ctrl+Shift+Arrow copy source selection state. - ms->EndIO.RequestSetRange = true; - ms->EndIO.RangeDstItem = item_data; + // Shift+Arrow always select + // Ctrl+Shift+Arrow copy source selection state (alrady stored by BeginMultiSelect() in RangeSelected) if (!is_ctrl) ms->EndIO.RangeSelected = true; ms->EndIO.RangeDirection = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; @@ -7346,40 +7348,23 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { // Ctrl inverts selection, otherwise always select selected = is_ctrl ? !selected : true; - ms->EndIO.RangeSrcItem = ms->EndIO.RangeDstItem = item_data; + ms->EndIO.RangeSrcItem = item_data; ms->EndIO.RangeSelected = selected; - ms->EndIO.RequestSetRange = true; ms->EndIO.RangeDirection = +1; } if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) { - // Mouse click without CTRL clears the selection, unless the clicked item is already selected if (is_multiselect && !is_ctrl) ms->EndIO.RequestClear = true; - if (is_multiselect && !is_shift && ms->EndIO.RequestClear) - { - // For toggle selection unless there is a Clear request, we can handle it completely locally without sending a RangeSet request. - IM_ASSERT(ms->EndIO.RangeSrcItem == ms->EndIO.RangeDstItem); // Setup by else block above - ms->EndIO.RequestSetRange = true; - ms->EndIO.RangeSelected = selected; - ms->EndIO.RangeDirection = +1; - } - if (!is_multiselect) - { - // Clear selection, set single item range - IM_ASSERT(ms->EndIO.RangeSrcItem == item_data && ms->EndIO.RangeDstItem == item_data); // Setup by block above - ms->EndIO.RequestClear = true; - ms->EndIO.RequestSetRange = true; - } } else if (input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) { - if (is_multiselect && is_shift && !is_ctrl) - ms->EndIO.RequestClear = true; - else if (!is_multiselect) + if (is_multiselect && is_shift && !is_ctrl) // Without Shift the RequestClear was done in BeginIO, not necessary to do again. ms->EndIO.RequestClear = true; } + else if (!is_multiselect) + ms->EndIO.RequestClear = true; } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) From 387fc138945dae9a9d78af27b1110d1597bc4b7e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 Jun 2023 16:25:19 +0200 Subject: [PATCH 0130/2359] MultiSelect: Clarify and better enforce lifetime of BeginMultiSelect() value. --- imgui_demo.cpp | 11 +++++------ imgui_widgets.cpp | 3 +++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c66a9e434..09ac14057 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2780,7 +2780,7 @@ struct ExampleSelection { // Data ImGuiStorage Storage; // Selection set - int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class) // FIXME-RANGESELECT: Imply more difficult to track with intrusive selection schemes? + int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class). // FIXME-MULTISELECT: Imply more difficult to track with intrusive selection schemes? int RangeRef; // Reference/pivot item (generally last clicked item) // Functions @@ -2790,13 +2790,12 @@ struct ExampleSelection void SetSelected(int n, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == (int)v) return; if (v) SelectionSize++; else SelectionSize--; *p_int = (bool)v; } int GetSize() const { return SelectionSize; } - // When using SelectAll() / SetRange() we assume that our objects ID are indices. + // When using SetRange() / SelectAll() we assume that our objects ID are indices. // In this demo we always store selection using indices and never in another manner (e.g. object ID or pointers). // If your selection system is storing selection using object ID and you want to support Shift+Click range-selection, - // you will need a way to iterate from one object to another given the ID you use. - // You are likely to need some kind of data structure to convert 'view index' <> 'object ID'. - // FIXME-MULTISELECT: Would be worth providing a demo of doing this. - // FIXME-MULTISELECT: This implementation of SetRange() is inefficient because it doesn't take advantage of the fact that ImGuiStorage stores sorted key. + // you will need a way to iterate from one item to the other item given the ID you use. + // You are likely to need some kind of data structure to convert 'view index' <> 'object ID' (FIXME-MULTISELECT: Would be worth providing a demo of doing this). + // Note: This implementation of SetRange() is inefficient because it doesn't take advantage of the fact that ImGuiStorage stores sorted key. void SetRange(int a, int b, bool v) { if (b < a) { int tmp = b; b = a; a = tmp; } for (int n = a; n <= b; n++) SetSelected(n, v); } void SelectAll(int count) { Storage.Data.resize(count); for (int idx = 0; idx < count; idx++) Storage.Data[idx] = ImGuiStoragePair((ImGuiID)idx, 1); SelectionSize = count; } // This could be using SetRange(), but it this way is faster. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 911aa8b1d..350a9e86c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7131,6 +7131,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, data->RangeSrcItem, data->RangeDstItem, data->RangeSelected, data->RangeDirection); } +// Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) { ImGuiContext& g = *GImGui; @@ -7184,6 +7185,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* r return &ms->BeginIO; } +// Return updated ImGuiMultiSelectIO structure. Lifetime: until EndFrame() or next BeginMultiSelect() call. ImGuiMultiSelectIO* ImGui::EndMultiSelect() { ImGuiContext& g = *GImGui; @@ -7205,6 +7207,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() ms->FocusScopeId = 0; ms->Window = NULL; ms->Flags = ImGuiMultiSelectFlags_None; + ms->BeginIO.Clear(); // Invalidate contents of BeginMultiSelect() to enforce scope. PopFocusScope(); g.CurrentMultiSelect = NULL; From 564dde0ee34675d630d8f4115b022dbd3884f9d6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 2 Jun 2023 14:22:13 +0200 Subject: [PATCH 0131/2359] MultiSelect: Demo: first-draft of user-side deletion idioms. (will need support from lib) --- imgui_demo.cpp | 168 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 157 insertions(+), 11 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 09ac14057..7a1664473 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -605,7 +605,6 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::End(); } - static void ShowDemoWindowWidgets() { IMGUI_DEMO_MARKER("Widgets"); @@ -2806,11 +2805,61 @@ struct ExampleSelection if (ms_io->RequestSelectAll) { SelectAll(items_count); } if (ms_io->RequestSetRange) { SetRange((int)(intptr_t)ms_io->RangeSrcItem, (int)(intptr_t)ms_io->RangeDstItem, ms_io->RangeSelected ? 1 : 0); } } + + // Call after BeginMultiSelect() + // We cannot provide this logic in core Dear ImGui because we don't have access to selection data. + // Essentially this would be a ms_io->RequestNextFocusBeforeDeletion + // Important: This only works if the item ID are stable: aka not depend on their index, but on e.g. item id/ptr. + template + int CalcNextFocusIdxForBeforeDeletion(ImGuiMultiSelectIO* ms_io, ImVector& items) + { + // Return first unselected item after RangeSrcItem + for (int n = (int)(intptr_t)ms_io->RangeSrcItem + 1; n < items.Size; n++) + if (!GetSelected(n)) + return n; + + // Otherwise return last unselected item + for (int n = (int)(intptr_t)ms_io->RangeSrcItem - 1; n >= 0; n--) + if (!GetSelected(n)) + return n; + return -1; + } + + // Call after EndMultiSelect() + // Apply deletion request + return index of item to refocus, if any. + template + void ApplyDeletion(ImGuiMultiSelectIO* ms_io, ImVector& items, int next_focus_idx_in_old_selection) + { + // This does two things: + // - (1) Update Items List (delete items from it) + // - (2) Convert the new focus index from old selection index (before deletion) to new selection index (after selection), and select it. + // FIXME: (2.3) if NavId is not selected, stay on same item -> facilitate persisting focus if ID change? (if ID is index-based) -> by setting focus again + // You are expected to handle both of those in user-space because Dear ImGui rightfully doesn't own items data nor selection data. + // This particular ExampleSelection case is designed to showcase maintaining selection-state separated from items-data. + IM_UNUSED(ms_io); + ImVector new_items; + new_items.reserve(items.Size - SelectionSize); + int next_focus_idx_in_new_selection = -1; + for (int n = 0; n < items.Size; n++) + { + if (!GetSelected(n)) + new_items.push_back(items[n]); + if (next_focus_idx_in_old_selection == n) + next_focus_idx_in_new_selection = new_items.Size - 1; + } + items.swap(new_items); + + // Update selection + Clear(); + if (next_focus_idx_in_new_selection != -1) + SetSelected(next_focus_idx_in_new_selection, true); + } }; static void ShowDemoWindowMultiSelect() { IMGUI_DEMO_MARKER("Widgets/Selection State"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Selection State")) { HelpMarker("Selections can be built under Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data."); @@ -2896,7 +2945,77 @@ static void ShowDemoWindowMultiSelect() ImGui::EndListBox(); } + ImGui::TreePop(); + } + // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. + // SHIFT+Click w/ CTRL and other standard features are supported. + IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, with deletion)"); + if (ImGui::TreeNode("Multiple Selection (full, with deletion)")) + { + // Intentionally separating items data from selection data! + // But you may decide to store selection data inside your item (aka ' + static ImVector items; + static ExampleSelection selection; + + ImGui::Text("Adding features:"); + ImGui::BulletText("Dynamic list with Delete key support."); + + // Initialize default list with 50 items + button to add more. + static int items_next_id = 0; + if (items_next_id == 0) + for (int n = 0; n < 50; n++) + items.push_back(items_next_id++); + ImGui::Text("Selection: %d/%d", selection.GetSize(), items.Size); + ImGui::SameLine(); + if (ImGui::SmallButton("Add 20 items")) + for (int n = 0; n < 20; n++) + items.push_back(items_next_id++); + + ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); + ImGui::Text("RangeRef: %d", selection.RangeRef); + + // Extra to support deletion: Submit scrolling range to avoid glitches on deletion + const float items_height = ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); + if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + { + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); + selection.ApplyRequests(ms_io, items.Size); + + // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. + // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. + // FIXME-MULTISELECT: Test with intermediary modal dialog. + const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); + const int next_focus_item_idx = want_delete ? selection.CalcNextFocusIdxForBeforeDeletion(ms_io, items) : -1; + + for (int n = 0; n < items.Size; n++) + { + const int item_id = items[n]; + char label[64]; + sprintf(label, "Object %05d: %s", item_id, random_names[item_id % IM_ARRAYSIZE(random_names)]); + + bool item_is_selected = selection.GetSelected(n); + ImGui::SetNextItemSelectionData((void*)(intptr_t)n); + ImGui::Selectable(label, item_is_selected); + if (ImGui::IsItemToggledSelection()) + selection.SetSelected(n, !item_is_selected); + + // FIXME-MULTISELECT: turn into a ms_io->RequestFocusIdx + if (next_focus_item_idx == n) + ImGui::SetKeyboardFocusHere(-1); + } + + // Apply multi-select requests + ms_io = ImGui::EndMultiSelect(); + selection.RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; + selection.ApplyRequests(ms_io, items.Size); + if (want_delete) + selection.ApplyDeletion(ms_io, items, next_focus_item_idx); + + ImGui::EndListBox(); + } ImGui::TreePop(); } @@ -2939,6 +3058,7 @@ static void ShowDemoWindowMultiSelect() // Advanced demonstration of BeginMultiSelect() // - Showcase clipping. + // - Showcase deletion. // - Showcase basic drag and drop. // - Showcase TreeNode variant (note that tree node don't expand in the demo: supporting expanding tree nodes + clipping a separate thing). // - Showcase using inside a table. @@ -2949,6 +3069,7 @@ static void ShowDemoWindowMultiSelect() // Options enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; static bool use_clipper = true; + static bool use_deletion = true; static bool use_drag_drop = true; static bool show_in_table = false; static bool show_color_button = false; @@ -2959,6 +3080,7 @@ static void ShowDemoWindowMultiSelect() ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } ImGui::Checkbox("Enable clipper", &use_clipper); + ImGui::Checkbox("Enable deletion", &use_deletion); ImGui::Checkbox("Enable drag & drop", &use_drag_drop); ImGui::Checkbox("Show in a table", &show_in_table); ImGui::Checkbox("Show color button", &show_color_button); @@ -2967,10 +3089,16 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickWindowVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickWindowVoid); - const int ITEMS_COUNT = 1000; + // Initialize default list with 1000 items. + static ImVector items; + static int items_next_id = 0; + if (items_next_id == 0) { for (int n = 0; n < 1000; n++) { items.push_back(items_next_id++); } } static ExampleSelection selection; - ImGui::Text("Selection size: %d/%d", selection.GetSize(), ITEMS_COUNT); + ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); + + const float items_height = (widget_type == WidgetType_TreeNode) ? ImGui::GetTextLineHeight() : ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); @@ -2978,7 +3106,13 @@ static void ShowDemoWindowMultiSelect() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + selection.ApplyRequests(ms_io, items.Size); + + // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. + // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. + // FIXME-MULTISELECT: Test with intermediary modal dialog. + const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); + const int next_focus_item_idx = want_delete ? selection.CalcNextFocusIdxForBeforeDeletion(ms_io, items) : -1; if (show_in_table) { @@ -2992,7 +3126,7 @@ static void ShowDemoWindowMultiSelect() ImGuiListClipper clipper; if (use_clipper) - clipper.Begin(ITEMS_COUNT); + clipper.Begin(items.Size); while (!use_clipper || clipper.Step()) { @@ -3002,16 +3136,22 @@ static void ShowDemoWindowMultiSelect() ms_io->RangeSrcPassedBy = true; const int item_begin = use_clipper ? clipper.DisplayStart : 0; - const int item_end = use_clipper ? clipper.DisplayEnd : ITEMS_COUNT; + const int item_end = use_clipper ? clipper.DisplayEnd : items.Size; for (int n = item_begin; n < item_end; n++) { if (show_in_table) ImGui::TableNextColumn(); - ImGui::PushID(n); - const char* category = random_names[n % IM_ARRAYSIZE(random_names)]; + const int item_id = items[n]; + const char* item_category = random_names[item_id % IM_ARRAYSIZE(random_names)]; char label[64]; - sprintf(label, "Object %05d: %s", n, category); + sprintf(label, "Object %05d: %s", item_id, item_category); + + // IMPORTANT: for deletion refocus to work we need object ID to be stable, + // aka not depend on their index in the list. Here we use our persistent item_id + // instead of index to build a unique ID that will persist. + // (If we used PushID(n) instead, focus wouldn't be restored correctly after deletion). + ImGui::PushID(item_id); // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part // of the selection scope doesn't erroneously alter our selection (FIXME-TESTS: Add a test for that!). @@ -3027,6 +3167,8 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_Selectable) { ImGui::Selectable(label, item_is_selected); + if (next_focus_item_idx == n) + ImGui::SetKeyboardFocusHere(-1); // FIXME-MULTISELECT: turn into a ms_io->RequestFocusIdx if (use_drag_drop && ImGui::BeginDragDropSource()) { ImGui::Text("(Dragging %d items)", selection.GetSize()); @@ -3040,6 +3182,8 @@ static void ShowDemoWindowMultiSelect() if (item_is_selected) tree_node_flags |= ImGuiTreeNodeFlags_Selected; bool open = ImGui::TreeNodeEx(label, tree_node_flags); + if (next_focus_item_idx == n) + ImGui::SetKeyboardFocusHere(-1); // FIXME-MULTISELECT: turn into a ms_io->RequestFocusIdx if (use_drag_drop && ImGui::BeginDragDropSource()) { ImGui::Text("(Dragging %d items)", selection.GetSize()); @@ -3063,7 +3207,7 @@ static void ShowDemoWindowMultiSelect() ImGui::TableNextColumn(); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); - ImGui::InputText("###NoLabel", (char*)(void*)category, strlen(category), ImGuiInputTextFlags_ReadOnly); + ImGui::InputText("###NoLabel", (char*)(void*)item_category, strlen(item_category), ImGuiInputTextFlags_ReadOnly); ImGui::PopStyleVar(); } @@ -3083,7 +3227,9 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); selection.RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; - selection.ApplyRequests(ms_io, ITEMS_COUNT); + selection.ApplyRequests(ms_io, items.Size); + if (want_delete) + selection.ApplyDeletion(ms_io, items, next_focus_item_idx); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); From 9223ffc2552dfd4112d351427714ea1a7a032291 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 2 Jun 2023 14:34:22 +0200 Subject: [PATCH 0132/2359] MultiSelect: (Breaking) BeginMultiSelect() doesn't need two last params maintained by users. Moving some storage from user to core. Proper deletion demo. --- imgui.cpp | 9 +++ imgui.h | 57 +++++++++---------- imgui_demo.cpp | 114 +++++++++++++++++++++++++++----------- imgui_internal.h | 36 +++++++++--- imgui_widgets.cpp | 136 ++++++++++++++++++++++++++++++++++++++-------- 5 files changed, 257 insertions(+), 95 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8f34acf92..26f0f36bc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14957,6 +14957,15 @@ void ImGui::ShowMetricsWindow(bool* p_open) TreePop(); } + // Details for MultiSelect + if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount())) + { + for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++) + if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n)) + DebugNodeMultiSelectState(state); + TreePop(); + } + // Details for Docking #ifdef IMGUI_HAS_DOCK if (TreeNode("Docking")) diff --git a/imgui.h b/imgui.h index d00adb1f7..cb4e27832 100644 --- a/imgui.h +++ b/imgui.h @@ -669,10 +669,9 @@ namespace ImGui 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. // Multi-selection system for Selectable() and TreeNode() functions. - // This enables standard multi-selection/range-selection idioms (CTRL+Click/Arrow, SHIFT+Click/Arrow, etc) in a way that allow items to be fully clipped (= not submitted at all) when not visible. - // Read comments near ImGuiMultiSelectIO for details. - // When enabled, Selectable() and TreeNode() functions will return true when selection needs toggling. - IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected); + // - 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. + // - Read comments near ImGuiMultiSelectIO for details. + IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); @@ -908,7 +907,7 @@ namespace ImGui IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing. IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode(). - IMGUI_API bool IsItemToggledSelection(); // was the last item selection state toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) + IMGUI_API bool IsItemToggledSelection(); // was the last item selection state toggled? (after Selectable(), TreeNode() etc.) We only returns toggle _event_ in order to handle clipping correctly. IMGUI_API bool IsAnyItemHovered(); // is any item hovered? IMGUI_API bool IsAnyItemActive(); // is any item active? IMGUI_API bool IsAnyItemFocused(); // is any item focused? @@ -2725,10 +2724,8 @@ struct ImColor #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. // Flags for BeginMultiSelect(). -// This system is designed to allow mouse/keyboard multi-selection, including support for range-selection (SHIFT+click and SHIFT+keyboard), -// which is difficult to re-implement manually. If you disable multi-selection with ImGuiMultiSelectFlags_NoMultiSelect -// (which is provided for consistency and flexibility), the whole BeginMultiSelect() system becomes largely overkill as -// you can handle single-selection in a simpler manner by just calling Selectable() and reacting on clicks yourself. +// (we provide 'ImGuiMultiSelectFlags_NoMultiSelect' for consistency and flexiblity, but it essentially disable the main purpose of BeginMultiSelect(). +// If you use 'ImGuiMultiSelectFlags_NoMultiSelect' you can handle single-selection in a simpler way by just calling Selectable()/TreeNode() and reacting on clicks). enum ImGuiMultiSelectFlags_ { ImGuiMultiSelectFlags_None = 0, @@ -2739,12 +2736,11 @@ enum ImGuiMultiSelectFlags_ //ImGuiMultiSelectFlags_ClearOnClickRectVoid= 1 << 4, // Clear selection when clicking on empty location within rectangle covered by selection scope (use if multiple BeginMultiSelect() are used in the same host window) }; -// Abstract: -// - This system helps you implements standard multi-selection idioms (CTRL+Click/Arrow, SHIFT+Click/Arrow, etc) in a way that allow -// selectable items to be fully clipped (= not submitted at all) when not visible. Clipping is typically provided by ImGuiListClipper. -// Handling all of this in a single pass imgui is a little tricky, and this is why we provide those functionalities. -// Note however that if you don't need SHIFT+Click/Arrow range-select + clipping, you can handle a simpler form of multi-selection -// yourself, by reacting to click/presses on Selectable() items and checking keyboard modifiers. +// Multi-selection system +// - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) in a way that +// allow a clipper to be used (so most non-visible items won't be submitted). Handling this correctly is tricky, this is why +// we provide the functionality. Note however that if you don't need SHIFT+Mouse/Keyboard range-select + clipping, you could use +// a simpler form of multi-selection yourself, by reacting to click/presses on Selectable() items and checking keyboard modifiers. // The unusual complexity of this system is mostly caused by supporting SHIFT+Click/Arrow range-select with clipped elements. // - In the spirit of Dear ImGui design, your code owns the selection data. // So this is designed to handle all kind of selection data: e.g. instructive selection (store a bool inside each object), @@ -2762,36 +2758,33 @@ enum ImGuiMultiSelectFlags_ // between them to honor range selection. But the code never assume that sortable integers are used (you may store pointers to your object, // and then from the pointer have your own way of iterating from RangeSrcItem to RangeDstItem). // Usage flow: -// Begin -// 1) Call BeginMultiSelect() with the last saved value of ->RangeSrcItem and its selection state. -// It is because you need to pass its selection state (and you own selection) that we don't store this value in Dear ImGui. -// (For the initial frame or when resetting your selection state: you may use the value for your first item or a "null" value that matches the type stored in your void*). -// 2) Honor Clear/SelectAll/SetRange requests by updating your selection data. (Only required if you are using a clipper in step 4: but you can use same code as step 6 anyway.) -// Loop -// 3) Set RangeSrcPassedBy=true if the RangeSrcItem item is part of the items clipped before the first submitted/visible item. [Only required if you are using a clipper in step 4] -// This is because for range-selection we need to know if we are currently "inside" or "outside" the range. -// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrcItem) { data->RangeSrcPassedBy = true; } -// 4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. -// (You may optionally call IsItemToggledSelection() to query if the selection state has been toggled for a given item, if you need that info immediately for your display (before EndMultiSelect()).) -// (When cannot provide a "IsItemSelected()" value because we need to consider clipped/unprocessed items, this is why we return a "Toggled" event instead.) -// End -// 5) Call EndMultiSelect(). Save the value of ->RangeSrcItem for the next frame (you may convert the value in a format that is safe for persistance) -// 6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously) -// If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable() on a per-item basis. +// BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. +// - (2) [If using a clipper] Honor Clear/SelectAll/SetRange requests by updating your selection data. Can use same code as Step 6. +// LOOP - (3) [If using a clipper] Set RangeSrcPassedBy=true if the RangeSrcItem item is part of the items clipped before the first submitted/visible item. +// This is because for range-selection we need to know if we are currently "inside" or "outside" the range. +// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrcItem) { data->RangeSrcPassedBy = true; } +// - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. +// (optionally call IsItemToggledSelection() to query if the selection state has been toggled for a given visible item, if you need that info immediately for your display, before EndMultiSelect()) +// END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. +// - (6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously). Can use same code as Step 2. +// If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. struct ImGuiMultiSelectIO { // - Always process requests in this order: Clear, SelectAll, SetRange. + // - Some fields are only necessary if your list is dynamic and allows deletion (getting "post-deletion" state right is exhibited in the demo) // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. // REQUESTS ----------------// BEGIN / LOOP / END bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeSrcItem..RangeDstItem] items, based on RangeSelected. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. // STATE/ARGUMENTS ---------// BEGIN / LOOP / END - void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionData() value for RangeSrcItem. End: parameter from RequestSetRange request. + void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionUserData() value for RangeSrcItem. End: parameter from RequestSetRange request. void* RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrcItem came before RangeDstItem, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. bool RangeSelected; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. + bool RangeSrcReset; // / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). + void* NavIdItem; // ms:w, app:r / / ms:w app:r // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items) ImGuiMultiSelectIO() { Clear(); } void Clear() { memset(this, 0, sizeof(*this)); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7a1664473..8681ae47d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2773,17 +2773,14 @@ static void ShowDemoWindowWidgets() // are generally appropriate. Even a large array of bool might work for you... // - If you need to handle extremely large selections, it might be advantageous to support a "negative" mode in // your storage, so "Select All" becomes "Negative=1 + Clear" and then sparse unselect can add to the storage. -// About RefItem: -// - The BeginMultiSelect() API requires you to store information about the reference/pivot item (generally the last clicked item). struct ExampleSelection { // Data ImGuiStorage Storage; // Selection set int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class). // FIXME-MULTISELECT: Imply more difficult to track with intrusive selection schemes? - int RangeRef; // Reference/pivot item (generally last clicked item) // Functions - ExampleSelection() { RangeRef = 0; Clear(); } + ExampleSelection() { Clear(); } void Clear() { Storage.Clear(); SelectionSize = 0; } bool GetSelected(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } void SetSelected(int n, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == (int)v) return; if (v) SelectionSize++; else SelectionSize--; *p_int = (bool)v; } @@ -2806,6 +2803,17 @@ struct ExampleSelection if (ms_io->RequestSetRange) { SetRange((int)(intptr_t)ms_io->RangeSrcItem, (int)(intptr_t)ms_io->RangeDstItem, ms_io->RangeSelected ? 1 : 0); } } + void DebugTooltip() + { + if (ImGui::BeginTooltip()) + { + for (auto& pair : Storage.Data) + if (pair.val_i) + ImGui::Text("0x%03X (%d)", pair.key, pair.key); + ImGui::EndTooltip(); + } + } + // Call after BeginMultiSelect() // We cannot provide this logic in core Dear ImGui because we don't have access to selection data. // Essentially this would be a ms_io->RequestNextFocusBeforeDeletion @@ -2813,13 +2821,17 @@ struct ExampleSelection template int CalcNextFocusIdxForBeforeDeletion(ImGuiMultiSelectIO* ms_io, ImVector& items) { + // FIXME-MULTISELECT: Need to avoid auto-select, aka SetKeyboardFocusHere() into public facing FocusItem() that doesn't activate. + if (!GetSelected((int)(intptr_t)ms_io->NavIdItem)) + return (int)(intptr_t)ms_io->NavIdItem; + // Return first unselected item after RangeSrcItem for (int n = (int)(intptr_t)ms_io->RangeSrcItem + 1; n < items.Size; n++) if (!GetSelected(n)) return n; // Otherwise return last unselected item - for (int n = (int)(intptr_t)ms_io->RangeSrcItem - 1; n >= 0; n--) + for (int n = IM_MIN((int)(intptr_t)ms_io->RangeSrcItem, items.Size) - 1; n >= 0; n--) if (!GetSelected(n)) return n; return -1; @@ -2833,7 +2845,7 @@ struct ExampleSelection // This does two things: // - (1) Update Items List (delete items from it) // - (2) Convert the new focus index from old selection index (before deletion) to new selection index (after selection), and select it. - // FIXME: (2.3) if NavId is not selected, stay on same item -> facilitate persisting focus if ID change? (if ID is index-based) -> by setting focus again + // If NavId was not selected, next_focus_idx_in_old_selection == -1 and we stay on same item. // You are expected to handle both of those in user-space because Dear ImGui rightfully doesn't own items data nor selection data. // This particular ExampleSelection case is designed to showcase maintaining selection-state separated from items-data. IM_UNUSED(ms_io); @@ -2850,6 +2862,7 @@ struct ExampleSelection items.swap(new_items); // Update selection + //IMGUI_DEBUG_LOG("ApplyDeletion(): next_focus_idx_in_new_selection = %d\n", next_focus_idx_in_new_selection); Clear(); if (next_focus_idx_in_new_selection != -1) SetSelected(next_focus_idx_in_new_selection, true); @@ -2922,11 +2935,10 @@ static void ShowDemoWindowMultiSelect() // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling region). const int ITEMS_COUNT = 50; ImGui::Text("Selection size: %d", selection.GetSize()); - ImGui::Text("RangeRef: %d", selection.RangeRef); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) @@ -2940,7 +2952,6 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; selection.ApplyRequests(ms_io, ITEMS_COUNT); ImGui::EndListBox(); @@ -2960,20 +2971,18 @@ static void ShowDemoWindowMultiSelect() ImGui::Text("Adding features:"); ImGui::BulletText("Dynamic list with Delete key support."); + ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); + if (ImGui::IsItemHovered() && selection.GetSize() > 0) + selection.DebugTooltip(); // Initialize default list with 50 items + button to add more. static int items_next_id = 0; if (items_next_id == 0) for (int n = 0; n < 50; n++) items.push_back(items_next_id++); - ImGui::Text("Selection: %d/%d", selection.GetSize(), items.Size); + if (ImGui::SmallButton("Add 20 items")) { for (int n = 0; n < 20; n++) { items.push_back(items_next_id++); } } ImGui::SameLine(); - if (ImGui::SmallButton("Add 20 items")) - for (int n = 0; n < 20; n++) - items.push_back(items_next_id++); - - ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); - ImGui::Text("RangeRef: %d", selection.RangeRef); + if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.SetSelected(items.Size - 1, false); items.pop_back(); } } // This is to test // Extra to support deletion: Submit scrolling range to avoid glitches on deletion const float items_height = ImGui::GetTextLineHeightWithSpacing(); @@ -2981,7 +2990,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, items.Size); // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. @@ -2989,6 +2998,7 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Test with intermediary modal dialog. const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); const int next_focus_item_idx = want_delete ? selection.CalcNextFocusIdxForBeforeDeletion(ms_io, items) : -1; + //if (want_delete) { IMGUI_DEBUG_LOG("next_focus_item_idx = %d\n", next_focus_item_idx); } for (int n = 0; n < items.Size; n++) { @@ -2997,22 +3007,44 @@ static void ShowDemoWindowMultiSelect() sprintf(label, "Object %05d: %s", item_id, random_names[item_id % IM_ARRAYSIZE(random_names)]); bool item_is_selected = selection.GetSelected(n); - ImGui::SetNextItemSelectionData((void*)(intptr_t)n); + ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); if (ImGui::IsItemToggledSelection()) selection.SetSelected(n, !item_is_selected); // FIXME-MULTISELECT: turn into a ms_io->RequestFocusIdx if (next_focus_item_idx == n) - ImGui::SetKeyboardFocusHere(-1); + ImGui::SetKeyboardFocusHere(-1); // FIXME-MULTISELECT: Need to avoid selection. } - // Apply multi-select requests +#if 0 + bool nav_id_was_selected = selection.GetSelected((int)(intptr_t)ms_io->NavIdData); + if (want_delete && !nav_id_was_selected) // FIXME: would work without '&& !nav_id_was_selected' just take an extra frame to recover RangeSrc + ms_io->RangeSrcReset = true; ms_io = ImGui::EndMultiSelect(); - selection.RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; selection.ApplyRequests(ms_io, items.Size); if (want_delete) - selection.ApplyDeletion(ms_io, items, next_focus_item_idx); + selection.ApplyDeletion(ms_io, items, nav_id_was_selected ? next_focus_item_idx : -1); +#else + // Apply multi-select requests + if (want_delete) + { + // When deleting: this handle details for scrolling/focus/selection to be updated correctly without any glitches. + bool nav_id_was_selected = selection.GetSelected((int)(intptr_t)ms_io->NavIdItem); + if (!nav_id_was_selected) // FIXME: would work without '&& !nav_id_was_selected' just take an extra frame to recover RangeSrc + ms_io->RangeSrcReset = true; + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io, items.Size); + selection.ApplyDeletion(ms_io, items, nav_id_was_selected ? next_focus_item_idx : -1); + } + else + { + // Simple version + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io, items.Size); + } +#endif + ImGui::EndListBox(); } @@ -3035,7 +3067,7 @@ static void ShowDemoWindowMultiSelect() ImGui::PushID(selection_scope_n); ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; // | ImGuiMultiSelectFlags_ClearOnClickRectVoid - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection->RangeRef, selection->GetSelected(selection->RangeRef)); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection->ApplyRequests(ms_io, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) @@ -3049,7 +3081,6 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection->RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; selection->ApplyRequests(ms_io, ITEMS_COUNT); ImGui::PopID(); } @@ -3105,7 +3136,7 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_TreeNode) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, (void*)(intptr_t)selection.RangeRef, selection.GetSelected(selection.RangeRef)); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, items.Size); // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. @@ -3113,6 +3144,7 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Test with intermediary modal dialog. const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); const int next_focus_item_idx = want_delete ? selection.CalcNextFocusIdxForBeforeDeletion(ms_io, items) : -1; + //if (want_delete) { IMGUI_DEBUG_LOG("next_focus_item_idx = %d\n", next_focus_item_idx); } if (show_in_table) { @@ -3126,14 +3158,18 @@ static void ShowDemoWindowMultiSelect() ImGuiListClipper clipper; if (use_clipper) + { clipper.Begin(items.Size); + if (next_focus_item_idx != -1) + clipper.IncludeItemByIndex(next_focus_item_idx); // Ensure item to focus is not clipped + } while (!use_clipper || clipper.Step()) { - // IF clipping is used you need to set 'RangeSrcPassedBy = true' if RangeSrcItem was passed over. - if (use_clipper) - if ((int)(intptr_t)ms_io->RangeSrcItem <= clipper.DisplayStart) - ms_io->RangeSrcPassedBy = true; + // IF clipping is used: you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. + // If you submit all items this is unnecessary as this is one by SetNextItemSelectionUserData() + if (use_clipper && clipper.DisplayStart > (int)(intptr_t)ms_io->RangeSrcItem) + ms_io->RangeSrcPassedBy = true; const int item_begin = use_clipper ? clipper.DisplayStart : 0; const int item_end = use_clipper ? clipper.DisplayEnd : items.Size; @@ -3217,6 +3253,12 @@ static void ShowDemoWindowMultiSelect() break; } + // If clipping is used: you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. + // If you submit all items this is unnecessary as this is one by SetNextItemSelectionUserData() + // Here we essentially notify before EndMultiSelect() that RangeSrc is still present in our data set. + if (use_clipper && items.Size > (int)(intptr_t)ms_io->RangeSrcItem) + ms_io->RangeSrcPassedBy = true; + if (show_in_table) { ImGui::EndTable(); @@ -3225,11 +3267,21 @@ static void ShowDemoWindowMultiSelect() } // Apply multi-select requests +#if 1 + // full correct + bool nav_id_was_selected = selection.GetSelected((int)(intptr_t)ms_io->NavIdItem); + if (want_delete && !nav_id_was_selected) + ms_io->RangeSrcReset = true; ms_io = ImGui::EndMultiSelect(); - selection.RangeRef = (int)(intptr_t)ms_io->RangeSrcItem; selection.ApplyRequests(ms_io, items.Size); if (want_delete) - selection.ApplyDeletion(ms_io, items, next_focus_item_idx); + selection.ApplyDeletion(ms_io, items, nav_id_was_selected ? next_focus_item_idx : -1); +#else + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io, items.Size); + if (want_delete) + selection.ApplyDeletion(ms_io, items, nav_id_was_selected ? next_focus_item_idx : -1); +#endif if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); diff --git a/imgui_internal.h b/imgui_internal.h index 2e1a0bee3..eaeca4ece 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -134,6 +134,7 @@ struct ImGuiInputTextDeactivateData;// Short term storage to backup text of a de struct ImGuiLastItemData; // Status storage for last submitted items struct ImGuiLocEntry; // A localization entry. struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only +struct ImGuiMultiSelectState; // Multi-selection persistent state (for focused selection). struct ImGuiMultiSelectTempData; // Multi-selection temporary state (while traversing). struct ImGuiNavItemData; // Result of a gamepad/keyboard directional navigation move query result struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions @@ -1716,19 +1717,34 @@ struct ImGuiOldColumns // Temporary storage for multi-select struct IMGUI_API ImGuiMultiSelectTempData { - ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) + ImGuiMultiSelectState* Storage; + ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) ImGuiMultiSelectFlags Flags; ImGuiKeyChord KeyMods; - ImGuiWindow* Window; - ImGuiMultiSelectIO BeginIO; // Requests are set and returned by BeginMultiSelect(), written to by user during the loop. - ImGuiMultiSelectIO EndIO; // Requests are set during the loop and returned by EndMultiSelect(). - bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. - bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. - bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. - //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. + ImGuiMultiSelectIO BeginIO; // Requests are set and returned by BeginMultiSelect(), written to by user during the loop. + ImGuiMultiSelectIO EndIO; // Requests are set during the loop and returned by EndMultiSelect(). + bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. + bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. + bool NavIdPassedBy; + bool RangeDstPassedBy; // Set by the the item that matches NavJustMovedToId when IsSetRange is set. + //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectTempData() { Clear(); } - void Clear() { memset(this, 0, sizeof(*this)); } + void Clear() { memset(this, 0, sizeof(*this)); BeginIO.RangeSrcItem = EndIO.RangeSrcItem = BeginIO.RangeDstItem = EndIO.RangeDstItem = BeginIO.NavIdItem = EndIO.NavIdItem = (void*)-1; } +}; + +// Persistent storage for multi-select (as long as selection is alive) +struct IMGUI_API ImGuiMultiSelectState +{ + ImGuiWindow* Window; + ImGuiID ID; + int LastFrameActive; // Last used frame-count, for GC. + ImS8 RangeSelected; // -1 (don't have) or true/false + void* RangeSrcItem; // + void* NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) + + ImGuiMultiSelectState() { Init(0); } + void Init(ImGuiID id) { Window = NULL; ID = id; LastFrameActive = 0; RangeSelected = -1; RangeSrcItem = NavIdItem = (void*)-1; } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT @@ -2170,6 +2186,7 @@ struct ImGuiContext // Multi-Select state ImGuiMultiSelectTempData* CurrentMultiSelect; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select ImGuiMultiSelectTempData MultiSelectTempData[1]; + ImPool MultiSelectStorage; // Hover Delay system ImGuiID HoverItemDelayId; @@ -3568,6 +3585,7 @@ namespace ImGui IMGUI_API void DebugNodeTableSettings(ImGuiTableSettings* settings); IMGUI_API void DebugNodeInputTextState(ImGuiInputTextState* state); IMGUI_API void DebugNodeTypingSelectState(ImGuiTypingSelectState* state); + IMGUI_API void DebugNodeMultiSelectState(ImGuiMultiSelectState* state); IMGUI_API void DebugNodeWindow(ImGuiWindow* window, const char* label); IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings* settings); IMGUI_API void DebugNodeWindowsList(ImVector* windows, const char* label); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 350a9e86c..126727c23 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7132,7 +7132,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe } // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). -ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* range_ref, bool range_ref_is_selected) +ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -7141,21 +7141,38 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* r g.CurrentMultiSelect = ms; // FIXME: BeginFocusScope() + const ImGuiID id = window->IDStack.back(); ms->Clear(); - ms->FocusScopeId = window->IDStack.back(); + ms->FocusScopeId = id; ms->Flags = flags; - ms->Window = window; ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId); PushFocusScope(ms->FocusScopeId); // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. ms->KeyMods = g.NavJustMovedToId ? g.NavJustMovedToKeyMods : g.IO.KeyMods; + // Bind storage + ImGuiMultiSelectState* storage = g.MultiSelectStorage.GetOrAddByKey(id); + storage->ID = id; + storage->LastFrameActive = g.FrameCount; + storage->Window = window; + ms->Storage = storage; + + // FIXME-MULTISELECT: Set for the purpose of user calling RangeSrcPassedBy + // FIXME-MULTISELECT: Index vs Pointers. + ms->BeginIO.RangeSrcItem = storage->RangeSrcItem; + ms->BeginIO.NavIdItem = storage->NavIdItem; + + if (!ms->IsFocused) + return &ms->BeginIO; // This is cleared at this point. + + /* if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) { ms->BeginIO.RangeSrcItem = ms->EndIO.RangeSrcItem = range_ref; ms->BeginIO.RangeSelected = ms->EndIO.RangeSelected = range_ref_is_selected; } + */ // Auto clear when using Navigation to move within the selection // (we compare FocusScopeId so it possible to use multiple selections inside a same window) @@ -7163,19 +7180,21 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, void* r { if (ms->KeyMods & ImGuiMod_Shift) ms->IsSetRange = true; + if (ms->IsSetRange) + IM_ASSERT(storage->RangeSrcItem != (void*)-1); // Not ready -> could clear? if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) ms->BeginIO.RequestClear = true; } // Shortcut: Select all (CTRL+A) - if (ms->IsFocused && !(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (!(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) ms->BeginIO.RequestSelectAll = true; // Shortcut: Clear selection (Escape) // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. // Otherwise may be done by caller but it means Shortcut() needs to be exposed. - if (ms->IsFocused && (flags & ImGuiMultiSelectFlags_ClearOnEscape)) + if (flags & ImGuiMultiSelectFlags_ClearOnEscape) if (Shortcut(ImGuiKey_Escape)) ms->BeginIO.RequestClear = true; @@ -7191,7 +7210,21 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() ImGuiContext& g = *GImGui; ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; IM_ASSERT(ms->FocusScopeId == g.CurrentFocusScopeId); - IM_ASSERT(g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Window == g.CurrentWindow); + IM_ASSERT(g.CurrentMultiSelect != NULL && ms->Storage->Window == g.CurrentWindow); + + if (ms->IsFocused) + { + if (ms->BeginIO.RangeSrcReset || (ms->BeginIO.RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != (void*)-1)) + { + IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrc.\n"); // Will set be to NavId. + ms->Storage->RangeSrcItem = (void*)-1; + } + if (ms->NavIdPassedBy == false && ms->Storage->NavIdItem != (void*)-1) + { + IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdData.\n"); + ms->Storage->NavIdItem = (void*)-1; + } + } // Clear selection when clicking void? // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! @@ -7205,7 +7238,6 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() // Unwind ms->FocusScopeId = 0; - ms->Window = NULL; ms->Flags = ImGuiMultiSelectFlags_None; ms->BeginIO.Clear(); // Invalidate contents of BeginMultiSelect() to enforce scope. PopFocusScope(); @@ -7222,28 +7254,31 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d // Note that flags will be cleared by ItemAdd(), so it's only useful for Navigation code! // This designed so widgets can also cheaply set this before calling ItemAdd(), so we are not tied to MultiSelect api. ImGuiContext& g = *GImGui; - if (g.MultiSelectState.FocusScopeId != 0) - g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect; - else - g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData; g.NextItemData.SelectionUserData = selection_user_data; g.NextItemData.FocusScopeId = g.CurrentFocusScopeId; - // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect) + { + // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) + g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect; if (ms->BeginIO.RangeSrcItem == (void*)selection_user_data) ms->BeginIO.RangeSrcPassedBy = true; + } + else + { + g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData; + } } void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) { ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; + if (!ms->IsFocused) + return; + ImGuiMultiSelectState* storage = ms->Storage; - IM_UNUSED(window); IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); - IM_ASSERT((g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid) && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); void* item_data = (void*)g.NextItemData.SelectionUserData; // Apply Clear/SelectAll requests requested by BeginMultiSelect(). @@ -7260,12 +7295,22 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) if (ms->IsSetRange) { IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0); - const bool is_range_src = (ms->BeginIO.RangeSrcItem == item_data); - const bool is_range_dst = !ms->RangeDstPassedBy && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. + const bool is_range_dst = (ms->RangeDstPassedBy == false) && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. if (is_range_dst) + { ms->RangeDstPassedBy = true; + if (storage->RangeSrcItem == (void*)-1) // If we don't have RangeSrc, assign RangeSrc = RangeDst + { + storage->RangeSrcItem = item_data; + storage->RangeSelected = selected ? 1 : 0; + } + } + const bool is_range_src = storage->RangeSrcItem == item_data; if (is_range_src || is_range_dst || ms->BeginIO.RangeSrcPassedBy != ms->RangeDstPassedBy) - selected = ms->BeginIO.RangeSelected; + { + IM_ASSERT(storage->RangeSrcItem != (void*)-1 && storage->RangeSelected != -1); + selected = (storage->RangeSelected != 0); + } else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) selected = false; } @@ -7277,16 +7322,36 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + + bool selected = *p_selected; + bool pressed = *p_pressed; ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; + ImGuiMultiSelectState* storage = ms->Storage; + if (pressed) + { + ms->IsFocused = true; + //if (storage->Id != ms->FocusScopeId) + // storage->Init(ms->FocusScopeId); + } + if (!ms->IsFocused) + return; void* item_data = (void*)g.NextItemData.SelectionUserData; const bool is_multiselect = (ms->Flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0; - bool selected = *p_selected; - bool pressed = *p_pressed; bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; + if (g.NavId == id) + storage->NavIdItem = item_data; + if (g.NavId == id && storage->RangeSrcItem == (void*)-1) + { + storage->RangeSrcItem = item_data; + storage->RangeSelected = selected; // Will be updated at the end of this function anyway. + } + if (storage->NavIdItem == item_data) + ms->NavIdPassedBy = true; + // Auto-select as you navigate a list if (g.NavJustMovedToId == id) { @@ -7343,15 +7408,16 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { // Shift+Arrow always select // Ctrl+Shift+Arrow copy source selection state (alrady stored by BeginMultiSelect() in RangeSelected) - if (!is_ctrl) - ms->EndIO.RangeSelected = true; + //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); + ms->EndIO.RangeSrcItem = (storage->RangeSrcItem != (void*)-1) ? storage->RangeSrcItem : item_data; + ms->EndIO.RangeSelected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; ms->EndIO.RangeDirection = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; } else { // Ctrl inverts selection, otherwise always select selected = is_ctrl ? !selected : true; - ms->EndIO.RangeSrcItem = item_data; + ms->EndIO.RangeSrcItem = storage->RangeSrcItem = item_data; ms->EndIO.RangeSelected = selected; ms->EndIO.RangeDirection = +1; } @@ -7371,13 +7437,37 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) + if (storage->RangeSrcItem == item_data) + storage->RangeSelected = selected ? 1 : 0; if (ms->EndIO.RangeSrcItem == item_data && is_ctrl && is_shift && is_multiselect) + { + if (ms->EndIO.RequestSetRange) + IM_ASSERT(storage->RangeSrcItem == ms->EndIO.RangeSrcItem); ms->EndIO.RangeSelected = selected; + } *p_selected = selected; *p_pressed = pressed; } +void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) +{ +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + const bool is_active = (storage->LastFrameActive >= GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here. + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open = TreeNode((void*)(intptr_t)storage->ID, "MultiSelect 0x%08X%s", storage->ID, is_active ? "" : " *Inactive*"); + if (!is_active) { PopStyleColor(); } + if (!open) + return; + Text("ID = 0x%08X", storage->ID); + Text("RangeSrcItem = %p, RangeSelected = %d", storage->RangeSrcItem, storage->RangeSelected); + Text("NavIdItem = %p", storage->NavIdItem); + TreePop(); +#else + IM_UNUSED(storage); +#endif +} + //------------------------------------------------------------------------- // [SECTION] Widgets: ListBox //------------------------------------------------------------------------- From df1eeb9a20d70fdd6b712f292ec23881809465f7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 2 Jun 2023 15:17:01 +0200 Subject: [PATCH 0133/2359] MultiSelect: Maintain NavIdSelected for user. Simplify deletion demo. --- imgui.h | 1 + imgui_demo.cpp | 44 +++++++------------------------------------- imgui_internal.h | 3 ++- imgui_widgets.cpp | 30 +++++++++++++++++------------- 4 files changed, 27 insertions(+), 51 deletions(-) diff --git a/imgui.h b/imgui.h index cb4e27832..df38b174c 100644 --- a/imgui.h +++ b/imgui.h @@ -2784,6 +2784,7 @@ struct ImGuiMultiSelectIO bool RangeSelected; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. bool RangeSrcReset; // / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). + bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). void* NavIdItem; // ms:w, app:r / / ms:w app:r // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items) ImGuiMultiSelectIO() { Clear(); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8681ae47d..b0cc60bd8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2821,8 +2821,7 @@ struct ExampleSelection template int CalcNextFocusIdxForBeforeDeletion(ImGuiMultiSelectIO* ms_io, ImVector& items) { - // FIXME-MULTISELECT: Need to avoid auto-select, aka SetKeyboardFocusHere() into public facing FocusItem() that doesn't activate. - if (!GetSelected((int)(intptr_t)ms_io->NavIdItem)) + if (ms_io->NavIdSelected == false) return (int)(intptr_t)ms_io->NavIdItem; // Return first unselected item after RangeSrcItem @@ -2996,6 +2995,7 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. // FIXME-MULTISELECT: Test with intermediary modal dialog. + // FIXME-MULTISELECT: If pressing Delete + another key we have slightly ambiguous behavior. const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); const int next_focus_item_idx = want_delete ? selection.CalcNextFocusIdxForBeforeDeletion(ms_io, items) : -1; //if (want_delete) { IMGUI_DEBUG_LOG("next_focus_item_idx = %d\n", next_focus_item_idx); } @@ -3017,34 +3017,13 @@ static void ShowDemoWindowMultiSelect() ImGui::SetKeyboardFocusHere(-1); // FIXME-MULTISELECT: Need to avoid selection. } -#if 0 - bool nav_id_was_selected = selection.GetSelected((int)(intptr_t)ms_io->NavIdData); - if (want_delete && !nav_id_was_selected) // FIXME: would work without '&& !nav_id_was_selected' just take an extra frame to recover RangeSrc + // Apply multi-select requests + if (want_delete && ms_io->NavIdSelected == false) // FIXME: would work without '&& !NavIdSelected' just take an extra frame to recover RangeSrc ms_io->RangeSrcReset = true; ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, items.Size); if (want_delete) - selection.ApplyDeletion(ms_io, items, nav_id_was_selected ? next_focus_item_idx : -1); -#else - // Apply multi-select requests - if (want_delete) - { - // When deleting: this handle details for scrolling/focus/selection to be updated correctly without any glitches. - bool nav_id_was_selected = selection.GetSelected((int)(intptr_t)ms_io->NavIdItem); - if (!nav_id_was_selected) // FIXME: would work without '&& !nav_id_was_selected' just take an extra frame to recover RangeSrc - ms_io->RangeSrcReset = true; - ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, items.Size); - selection.ApplyDeletion(ms_io, items, nav_id_was_selected ? next_focus_item_idx : -1); - } - else - { - // Simple version - ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, items.Size); - } -#endif - + selection.ApplyDeletion(ms_io, items, ms_io->NavIdSelected ? next_focus_item_idx : -1); ImGui::EndListBox(); } @@ -3267,21 +3246,12 @@ static void ShowDemoWindowMultiSelect() } // Apply multi-select requests -#if 1 - // full correct - bool nav_id_was_selected = selection.GetSelected((int)(intptr_t)ms_io->NavIdItem); - if (want_delete && !nav_id_was_selected) + if (want_delete && ms_io->NavIdSelected == false) ms_io->RangeSrcReset = true; ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, items.Size); if (want_delete) - selection.ApplyDeletion(ms_io, items, nav_id_was_selected ? next_focus_item_idx : -1); -#else - ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, items.Size); - if (want_delete) - selection.ApplyDeletion(ms_io, items, nav_id_was_selected ? next_focus_item_idx : -1); -#endif + selection.ApplyDeletion(ms_io, items, ms_io->NavIdSelected ? next_focus_item_idx : -1); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); diff --git a/imgui_internal.h b/imgui_internal.h index eaeca4ece..21d350c89 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1740,11 +1740,12 @@ struct IMGUI_API ImGuiMultiSelectState ImGuiID ID; int LastFrameActive; // Last used frame-count, for GC. ImS8 RangeSelected; // -1 (don't have) or true/false + ImS8 NavIdSelected; // -1 (don't have) or true/false void* RangeSrcItem; // void* NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) ImGuiMultiSelectState() { Init(0); } - void Init(ImGuiID id) { Window = NULL; ID = id; LastFrameActive = 0; RangeSelected = -1; RangeSrcItem = NavIdItem = (void*)-1; } + void Init(ImGuiID id) { Window = NULL; ID = id; LastFrameActive = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = (void*)-1; } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 126727c23..f7b91dd47 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7160,8 +7160,10 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) // FIXME-MULTISELECT: Set for the purpose of user calling RangeSrcPassedBy // FIXME-MULTISELECT: Index vs Pointers. - ms->BeginIO.RangeSrcItem = storage->RangeSrcItem; - ms->BeginIO.NavIdItem = storage->NavIdItem; + // We want EndIO's NavIdItem/NavIdSelected to match BeginIO's one, so the value never changes after EndMultiSelect() + ms->BeginIO.RangeSrcItem = ms->EndIO.RangeSrcItem = storage->RangeSrcItem; + ms->BeginIO.NavIdItem = ms->EndIO.NavIdItem = storage->NavIdItem; + ms->BeginIO.NavIdSelected = ms->EndIO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; if (!ms->IsFocused) return &ms->BeginIO; // This is cleared at this point. @@ -7216,13 +7218,14 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() { if (ms->BeginIO.RangeSrcReset || (ms->BeginIO.RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != (void*)-1)) { - IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrc.\n"); // Will set be to NavId. + IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. ms->Storage->RangeSrcItem = (void*)-1; } if (ms->NavIdPassedBy == false && ms->Storage->NavIdItem != (void*)-1) { - IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdData.\n"); + IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdItem.\n"); ms->Storage->NavIdItem = (void*)-1; + ms->Storage->NavIdSelected = -1; } } @@ -7328,11 +7331,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; ImGuiMultiSelectState* storage = ms->Storage; if (pressed) - { ms->IsFocused = true; - //if (storage->Id != ms->FocusScopeId) - // storage->Init(ms->FocusScopeId); - } if (!ms->IsFocused) return; @@ -7342,15 +7341,11 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; - if (g.NavId == id) - storage->NavIdItem = item_data; if (g.NavId == id && storage->RangeSrcItem == (void*)-1) { storage->RangeSrcItem = item_data; storage->RangeSelected = selected; // Will be updated at the end of this function anyway. } - if (storage->NavIdItem == item_data) - ms->NavIdPassedBy = true; // Auto-select as you navigate a list if (g.NavJustMovedToId == id) @@ -7446,6 +7441,15 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ms->EndIO.RangeSelected = selected; } + // Update/store the selection state of focused item + if (g.NavId == id) + { + storage->NavIdItem = item_data; + storage->NavIdSelected = selected ? 1 : 0; + } + if (storage->NavIdItem == item_data) + ms->NavIdPassedBy = true; + *p_selected = selected; *p_pressed = pressed; } @@ -7461,7 +7465,7 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) return; Text("ID = 0x%08X", storage->ID); Text("RangeSrcItem = %p, RangeSelected = %d", storage->RangeSrcItem, storage->RangeSelected); - Text("NavIdItem = %p", storage->NavIdItem); + Text("NavIdData = %p, NavIdSelected = %d", storage->NavIdItem, storage->NavIdSelected); TreePop(); #else IM_UNUSED(storage); From c0035705cae649a3f0e8a576efbcd802da94102f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 2 Jun 2023 15:29:55 +0200 Subject: [PATCH 0134/2359] MultiSelect: Further simplication of user code to support Deletion. Provide standard RequestFocusItem storage. --- imgui.h | 7 +++-- imgui_demo.cpp | 77 +++++++++++++++++++++++++++--------------------- imgui_internal.h | 2 +- 3 files changed, 48 insertions(+), 38 deletions(-) diff --git a/imgui.h b/imgui.h index df38b174c..98e6c2b34 100644 --- a/imgui.h +++ b/imgui.h @@ -2777,18 +2777,19 @@ struct ImGuiMultiSelectIO bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeSrcItem..RangeDstItem] items, based on RangeSelected. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. + void* RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implemention of deletion idiom (see demo). // STATE/ARGUMENTS ---------// BEGIN / LOOP / END void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionUserData() value for RangeSrcItem. End: parameter from RequestSetRange request. void* RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrcItem came before RangeDstItem, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. bool RangeSelected; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. - bool RangeSrcReset; // / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). + bool RangeSrcReset; // app:w / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). - void* NavIdItem; // ms:w, app:r / / ms:w app:r // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items) + void* NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). ImGuiMultiSelectIO() { Clear(); } - void Clear() { memset(this, 0, sizeof(*this)); } + void Clear() { memset(this, 0, sizeof(*this)); RequestFocusItem = NavIdItem = RangeSrcItem = RangeDstItem = (void*)-1; } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b0cc60bd8..53f60067e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2814,32 +2814,38 @@ struct ExampleSelection } } - // Call after BeginMultiSelect() - // We cannot provide this logic in core Dear ImGui because we don't have access to selection data. - // Essentially this would be a ms_io->RequestNextFocusBeforeDeletion - // Important: This only works if the item ID are stable: aka not depend on their index, but on e.g. item id/ptr. + // Call after BeginMultiSelect(). + // - Calculate and set ms_io->RequestFocusItem, which we will focus during the loop. + // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. + // - Essentially this would be a ms_io->RequestNextFocusBeforeDeletion + // - Important: This only works if the item ID are stable: aka not depend on their index, but on e.g. item id/ptr. template - int CalcNextFocusIdxForBeforeDeletion(ImGuiMultiSelectIO* ms_io, ImVector& items) + int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, ImVector& items) { - if (ms_io->NavIdSelected == false) - return (int)(intptr_t)ms_io->NavIdItem; + // If current item is not selected. + if (ms_io->NavIdSelected == false) // Here 'NavIdSelected' should be == to 'GetSelected(ms_io->NavIdData)' + { + ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even without the !NavIdSelected test but it would take an extra frame to recover RangeSrc when deleting a selected item. + return (int)(intptr_t)ms_io->NavIdItem; // Request to land on same item after deletion. + } - // Return first unselected item after RangeSrcItem + // If current item is selected: land on first unselected item after RangeSrc. for (int n = (int)(intptr_t)ms_io->RangeSrcItem + 1; n < items.Size; n++) if (!GetSelected(n)) return n; - // Otherwise return last unselected item + // If current item is selected: otherwise return last unselected item. for (int n = IM_MIN((int)(intptr_t)ms_io->RangeSrcItem, items.Size) - 1; n >= 0; n--) if (!GetSelected(n)) return n; + return -1; } // Call after EndMultiSelect() // Apply deletion request + return index of item to refocus, if any. template - void ApplyDeletion(ImGuiMultiSelectIO* ms_io, ImVector& items, int next_focus_idx_in_old_selection) + void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ImVector& items) { // This does two things: // - (1) Update Items List (delete items from it) @@ -2850,6 +2856,7 @@ struct ExampleSelection IM_UNUSED(ms_io); ImVector new_items; new_items.reserve(items.Size - SelectionSize); + int next_focus_idx_in_old_selection = (int)(intptr_t)ms_io->RequestFocusItem; int next_focus_idx_in_new_selection = -1; for (int n = 0; n < items.Size; n++) { @@ -2861,9 +2868,8 @@ struct ExampleSelection items.swap(new_items); // Update selection - //IMGUI_DEBUG_LOG("ApplyDeletion(): next_focus_idx_in_new_selection = %d\n", next_focus_idx_in_new_selection); Clear(); - if (next_focus_idx_in_new_selection != -1) + if (next_focus_idx_in_new_selection != -1 && ms_io->NavIdSelected) SetSelected(next_focus_idx_in_new_selection, true); } }; @@ -2917,7 +2923,7 @@ static void ShowDemoWindowMultiSelect() "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Celtuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" }; - // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. + // Demonstrate holding/updating multi-selection data using the BeginMultiSelect/EndMultiSelect API. // SHIFT+Click w/ CTRL and other standard features are supported. IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full)"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); @@ -2958,13 +2964,19 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } - // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API to support range-selection and clipping. + // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API + support dynamic item list and deletion. // SHIFT+Click w/ CTRL and other standard features are supported. + // In order to support Deletion without any glitches you need to: + // - (1) If items are submitted in their own scrolling area, submit contents size SetNextWindowContentSize() ahead of time to prevent one-frame readjustment of scrolling. + // - (2) Items needs to have persistent ID Stack identifier = ID needs to not depends on their index. PushID(index) = KO. PushID(item_id) = OK. This is in order to focus items reliably after a selection. + // - (3) BeginXXXX process + // - (4) Focus process + // - (5) EndXXXX process IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, with deletion)"); if (ImGui::TreeNode("Multiple Selection (full, with deletion)")) { // Intentionally separating items data from selection data! - // But you may decide to store selection data inside your item (aka ' + // But you may decide to store selection data inside your item (aka intrusive storage). static ImVector items; static ExampleSelection selection; @@ -2974,7 +2986,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::IsItemHovered() && selection.GetSize() > 0) selection.DebugTooltip(); - // Initialize default list with 50 items + button to add more. + // Initialize default list with 50 items + button to add/remove items. static int items_next_id = 0; if (items_next_id == 0) for (int n = 0; n < 50; n++) @@ -2983,9 +2995,10 @@ static void ShowDemoWindowMultiSelect() ImGui::SameLine(); if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.SetSelected(items.Size - 1, false); items.pop_back(); } } // This is to test - // Extra to support deletion: Submit scrolling range to avoid glitches on deletion + // (1) Extra to support deletion: Submit scrolling range to avoid glitches on deletion const float items_height = ImGui::GetTextLineHeightWithSpacing(); ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); + if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; @@ -2994,11 +3007,11 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. - // FIXME-MULTISELECT: Test with intermediary modal dialog. - // FIXME-MULTISELECT: If pressing Delete + another key we have slightly ambiguous behavior. + // FIXME-MULTISELECT: If pressing Delete + another key we have ambiguous behavior. const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); - const int next_focus_item_idx = want_delete ? selection.CalcNextFocusIdxForBeforeDeletion(ms_io, items) : -1; - //if (want_delete) { IMGUI_DEBUG_LOG("next_focus_item_idx = %d\n", next_focus_item_idx); } + if (want_delete) + ms_io->RequestFocusItem = (void*)(intptr_t)selection.ApplyDeletionPreLoop(ms_io, items); + const int next_focus_item_idx = (int)(intptr_t)ms_io->RequestFocusItem; for (int n = 0; n < items.Size; n++) { @@ -3011,19 +3024,15 @@ static void ShowDemoWindowMultiSelect() ImGui::Selectable(label, item_is_selected); if (ImGui::IsItemToggledSelection()) selection.SetSelected(n, !item_is_selected); - - // FIXME-MULTISELECT: turn into a ms_io->RequestFocusIdx if (next_focus_item_idx == n) - ImGui::SetKeyboardFocusHere(-1); // FIXME-MULTISELECT: Need to avoid selection. + ImGui::SetKeyboardFocusHere(-1); } // Apply multi-select requests - if (want_delete && ms_io->NavIdSelected == false) // FIXME: would work without '&& !NavIdSelected' just take an extra frame to recover RangeSrc - ms_io->RangeSrcReset = true; ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, items.Size); if (want_delete) - selection.ApplyDeletion(ms_io, items, ms_io->NavIdSelected ? next_focus_item_idx : -1); + selection.ApplyDeletionPostLoop(ms_io, items); ImGui::EndListBox(); } @@ -3122,8 +3131,9 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. // FIXME-MULTISELECT: Test with intermediary modal dialog. const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); - const int next_focus_item_idx = want_delete ? selection.CalcNextFocusIdxForBeforeDeletion(ms_io, items) : -1; - //if (want_delete) { IMGUI_DEBUG_LOG("next_focus_item_idx = %d\n", next_focus_item_idx); } + if (want_delete) + selection.ApplyDeletionPreLoop(ms_io, items); + const int next_focus_item_idx = (int)(intptr_t)ms_io->RequestFocusItem; if (show_in_table) { @@ -3183,7 +3193,8 @@ static void ShowDemoWindowMultiSelect() { ImGui::Selectable(label, item_is_selected); if (next_focus_item_idx == n) - ImGui::SetKeyboardFocusHere(-1); // FIXME-MULTISELECT: turn into a ms_io->RequestFocusIdx + ImGui::SetKeyboardFocusHere(-1); + if (use_drag_drop && ImGui::BeginDragDropSource()) { ImGui::Text("(Dragging %d items)", selection.GetSize()); @@ -3198,7 +3209,7 @@ static void ShowDemoWindowMultiSelect() tree_node_flags |= ImGuiTreeNodeFlags_Selected; bool open = ImGui::TreeNodeEx(label, tree_node_flags); if (next_focus_item_idx == n) - ImGui::SetKeyboardFocusHere(-1); // FIXME-MULTISELECT: turn into a ms_io->RequestFocusIdx + ImGui::SetKeyboardFocusHere(-1); if (use_drag_drop && ImGui::BeginDragDropSource()) { ImGui::Text("(Dragging %d items)", selection.GetSize()); @@ -3246,12 +3257,10 @@ static void ShowDemoWindowMultiSelect() } // Apply multi-select requests - if (want_delete && ms_io->NavIdSelected == false) - ms_io->RangeSrcReset = true; ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, items.Size); if (want_delete) - selection.ApplyDeletion(ms_io, items, ms_io->NavIdSelected ? next_focus_item_idx : -1); + selection.ApplyDeletionPostLoop(ms_io, items); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); diff --git a/imgui_internal.h b/imgui_internal.h index 21d350c89..b076368e5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1730,7 +1730,7 @@ struct IMGUI_API ImGuiMultiSelectTempData //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectTempData() { Clear(); } - void Clear() { memset(this, 0, sizeof(*this)); BeginIO.RangeSrcItem = EndIO.RangeSrcItem = BeginIO.RangeDstItem = EndIO.RangeDstItem = BeginIO.NavIdItem = EndIO.NavIdItem = (void*)-1; } + void Clear() { memset(this, 0, sizeof(*this)); BeginIO.Clear(); EndIO.Clear(); } }; // Persistent storage for multi-select (as long as selection is alive) From e3616e151ff7a12121f1fff9360a772b735abfdc Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 Jun 2023 17:28:22 +0200 Subject: [PATCH 0135/2359] MultiSelect: Demo: Delete items from menu. --- imgui_demo.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 53f60067e..76255107c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2778,10 +2778,11 @@ struct ExampleSelection // Data ImGuiStorage Storage; // Selection set int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class). // FIXME-MULTISELECT: Imply more difficult to track with intrusive selection schemes? + bool QueueDeletion; // Request deleting selected items // Functions ExampleSelection() { Clear(); } - void Clear() { Storage.Clear(); SelectionSize = 0; } + void Clear() { Storage.Clear(); SelectionSize = 0; QueueDeletion = false; } bool GetSelected(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } void SetSelected(int n, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == (int)v) return; if (v) SelectionSize++; else SelectionSize--; *p_int = (bool)v; } int GetSize() const { return SelectionSize; } @@ -2822,6 +2823,8 @@ struct ExampleSelection template int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, ImVector& items) { + QueueDeletion = false; + // If current item is not selected. if (ms_io->NavIdSelected == false) // Here 'NavIdSelected' should be == to 'GetSelected(ms_io->NavIdData)' { @@ -3130,7 +3133,7 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. // FIXME-MULTISELECT: Test with intermediary modal dialog. - const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); + const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); if (want_delete) selection.ApplyDeletionPreLoop(ms_io, items); const int next_focus_item_idx = (int)(intptr_t)ms_io->RequestFocusItem; @@ -3222,7 +3225,10 @@ static void ShowDemoWindowMultiSelect() // Right-click: context menu if (ImGui::BeginPopupContextItem()) { - ImGui::Text("(Testing Selectable inside an embedded popup)"); + ImGui::BeginDisabled(!use_deletion || selection.GetSize() == 0); + sprintf(label, "Delete %d item(s)###DeleteSelected", selection.GetSize()); + selection.QueueDeletion |= ImGui::Selectable(label); + ImGui::EndDisabled(); ImGui::Selectable("Close"); ImGui::EndPopup(); } From ab9326f4ae93c5861b2854cd321573fe62d5aeb8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 Jun 2023 17:40:59 +0200 Subject: [PATCH 0136/2359] MultiSelect: Fixed right-click handling in MultiSelectItemFooter() when not focused. --- imgui_widgets.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f7b91dd47..712e709d5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7332,7 +7332,11 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiMultiSelectState* storage = ms->Storage; if (pressed) ms->IsFocused = true; - if (!ms->IsFocused) + + bool hovered = false; + if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) + hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (!ms->IsFocused && !hovered) return; void* item_data = (void*)g.NextItemData.SelectionUserData; @@ -7358,7 +7362,6 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Right-click handling: this could be moved at the Selectable() level. // FIXME-MULTISELECT: See https://github.com/ocornut/imgui/pull/5816 - bool hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); if (hovered && IsMouseClicked(1)) { if (g.ActiveId != 0 && g.ActiveId != id) From 0cf376348bc3c6726ede236fa96f9075db3a500b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jun 2023 15:01:10 +0200 Subject: [PATCH 0137/2359] MultiSelect: Cleanup unused comments/code. --- imgui.h | 2 +- imgui_demo.cpp | 3 +-- imgui_widgets.cpp | 9 --------- 3 files changed, 2 insertions(+), 12 deletions(-) diff --git a/imgui.h b/imgui.h index 98e6c2b34..1ac315d70 100644 --- a/imgui.h +++ b/imgui.h @@ -2777,7 +2777,7 @@ struct ImGuiMultiSelectIO bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeSrcItem..RangeDstItem] items, based on RangeSelected. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. - void* RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implemention of deletion idiom (see demo). + void* RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implementing a deletion idiom (see demo). // STATE/ARGUMENTS ---------// BEGIN / LOOP / END void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionUserData() value for RangeSrcItem. End: parameter from RequestSetRange request. void* RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 76255107c..27aa35694 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2818,7 +2818,7 @@ struct ExampleSelection // Call after BeginMultiSelect(). // - Calculate and set ms_io->RequestFocusItem, which we will focus during the loop. // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. - // - Essentially this would be a ms_io->RequestNextFocusBeforeDeletion + // - Return value is stored into 'ms_io->RequestFocusItem' which is provided as a convenience for this idiom (but not used by core imgui) // - Important: This only works if the item ID are stable: aka not depend on their index, but on e.g. item id/ptr. template int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, ImVector& items) @@ -3132,7 +3132,6 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. - // FIXME-MULTISELECT: Test with intermediary modal dialog. const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); if (want_delete) selection.ApplyDeletionPreLoop(ms_io, items); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 712e709d5..8ffbd27c3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7158,7 +7158,6 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) storage->Window = window; ms->Storage = storage; - // FIXME-MULTISELECT: Set for the purpose of user calling RangeSrcPassedBy // FIXME-MULTISELECT: Index vs Pointers. // We want EndIO's NavIdItem/NavIdSelected to match BeginIO's one, so the value never changes after EndMultiSelect() ms->BeginIO.RangeSrcItem = ms->EndIO.RangeSrcItem = storage->RangeSrcItem; @@ -7168,14 +7167,6 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (!ms->IsFocused) return &ms->BeginIO; // This is cleared at this point. - /* - if ((flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0) - { - ms->BeginIO.RangeSrcItem = ms->EndIO.RangeSrcItem = range_ref; - ms->BeginIO.RangeSelected = ms->EndIO.RangeSelected = range_ref_is_selected; - } - */ - // Auto clear when using Navigation to move within the selection // (we compare FocusScopeId so it possible to use multiple selections inside a same window) if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) From 847b1dde8c5c9dbad9fced2cbed378e1429ff0fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 4 Aug 2023 10:23:44 +0200 Subject: [PATCH 0138/2359] MultiSelect: (Breaking) Fix + Rename ImGuiMultiSelectFlags_NoMultiSelect to ImGuiMultiSelectFlags_SingleSelect as it seems easier to grasp. Feature was broken by "Tidying up..." June 30 commit. --- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_widgets.cpp | 16 +++++++++------- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/imgui.h b/imgui.h index 1ac315d70..aa9774759 100644 --- a/imgui.h +++ b/imgui.h @@ -2724,12 +2724,12 @@ struct ImColor #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. // Flags for BeginMultiSelect(). -// (we provide 'ImGuiMultiSelectFlags_NoMultiSelect' for consistency and flexiblity, but it essentially disable the main purpose of BeginMultiSelect(). -// If you use 'ImGuiMultiSelectFlags_NoMultiSelect' you can handle single-selection in a simpler way by just calling Selectable()/TreeNode() and reacting on clicks). +// (we provide 'ImGuiMultiSelectFlags_SingleSelect' for consistency and flexiblity to allow a single-selection to use same code/logic, but it essentially disable the biggest purpose of BeginMultiSelect(). +// If you use 'ImGuiMultiSelectFlags_SingleSelect' you can handle single-selection in a simpler way by just calling Selectable()/TreeNode() and reacting on clicks). enum ImGuiMultiSelectFlags_ { ImGuiMultiSelectFlags_None = 0, - ImGuiMultiSelectFlags_NoMultiSelect = 1 << 0, // Disable selecting more than one item. This is not very useful at this kind of selection can be implemented without BeginMultiSelect(), but this is available for consistency. + ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to use same code/logic is desired, but may not be very useful. ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to set RequestSelectAll ImGuiMultiSelectFlags_ClearOnEscape = 1 << 2, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickWindowVoid= 1 << 3, // Clear selection when clicking on empty location within host window (use if BeginMultiSelect() covers a whole window) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 27aa35694..c532ff9b4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3106,7 +3106,7 @@ static void ShowDemoWindowMultiSelect() ImGui::Checkbox("Enable drag & drop", &use_drag_drop); ImGui::Checkbox("Show in a table", &show_in_table); ImGui::Checkbox("Show color button", &show_color_button); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoMultiSelect", &flags, ImGuiMultiSelectFlags_NoMultiSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickWindowVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickWindowVoid); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8ffbd27c3..58467a1de 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7180,7 +7180,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) } // Shortcut: Select all (CTRL+A) - if (!(flags & ImGuiMultiSelectFlags_NoMultiSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) ms->BeginIO.RequestSelectAll = true; @@ -7332,7 +7332,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) void* item_data = (void*)g.NextItemData.SelectionUserData; - const bool is_multiselect = (ms->Flags & ImGuiMultiSelectFlags_NoMultiSelect) == 0; + const bool is_multiselect = (ms->Flags & ImGuiMultiSelectFlags_SingleSelect) == 0; bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; @@ -7411,18 +7411,20 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ms->EndIO.RangeDirection = +1; } - if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) + if (!is_multiselect) { - if (is_multiselect && !is_ctrl) + ms->EndIO.RequestClear = true; + } + else if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) + { + if (!is_ctrl) ms->EndIO.RequestClear = true; } else if (input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) { - if (is_multiselect && is_shift && !is_ctrl) // Without Shift the RequestClear was done in BeginIO, not necessary to do again. + if (is_shift && !is_ctrl) // Without Shift the RequestClear was done in BeginIO, not necessary to do again. ms->EndIO.RequestClear = true; } - else if (!is_multiselect) - ms->EndIO.RequestClear = true; } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) From 140a2f0565b4f07056673c3922ba2995640f70dc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Aug 2023 12:34:20 +0200 Subject: [PATCH 0139/2359] MultiSelect: Comments, tweaks. + Alignment to reduce noise on next commit. --- imgui.h | 75 ++++++++++++++++++++++++----------------------- imgui_demo.cpp | 5 +++- imgui_widgets.cpp | 3 +- 3 files changed, 44 insertions(+), 39 deletions(-) diff --git a/imgui.h b/imgui.h index aa9774759..811bf940e 100644 --- a/imgui.h +++ b/imgui.h @@ -2737,21 +2737,23 @@ enum ImGuiMultiSelectFlags_ }; // Multi-selection system -// - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) in a way that -// allow a clipper to be used (so most non-visible items won't be submitted). Handling this correctly is tricky, this is why -// we provide the functionality. Note however that if you don't need SHIFT+Mouse/Keyboard range-select + clipping, you could use -// a simpler form of multi-selection yourself, by reacting to click/presses on Selectable() items and checking keyboard modifiers. -// The unusual complexity of this system is mostly caused by supporting SHIFT+Click/Arrow range-select with clipped elements. -// - In the spirit of Dear ImGui design, your code owns the selection data. -// So this is designed to handle all kind of selection data: e.g. instructive selection (store a bool inside each object), -// external array (store an array aside from your objects), hash/map/set (store only selected items in a hash/map/set), -// or other structures (store indices in an interval tree), etc. -// - TreeNode() and Selectable() are supported. -// - The work involved to deal with multi-selection differs whether you want to only submit visible items (and clip others) or submit all items -// regardless of their visibility. Clipping items is more efficient and will allow you to deal with large lists (1k~100k items) with near zero -// performance penalty, but requires a little more work on the code. If you only have a few hundreds elements in your possible selection set, -// you may as well not bother with clipping, as the cost should be negligible (as least on Dear ImGui side). -// If you are not sure, always start without clipping and you can work your way to the more optimized version afterwards. +// - Refer to 'Demo->Widgets->Selection State' for references using this. +// - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) +// and supports a clipper being used. Handling this manually may be tricky, this is why we provide the functionality. +// If you don't need SHIFT+Mouse/Keyboard range-select + clipping, you can use a simpler form of multi-selection yourself, +// by reacting to click/presses on Selectable() items and checking keyboard modifiers. +// The complexity of this system is mostly caused by supporting SHIFT+Click/Arrow range-select with clipped elements. +// - TreeNode() and Selectable() are supported but custom widgets may use it as well. +// - In the spirit of Dear ImGui design, your code owns actual selection data. +// This is designed to allow all kinds of selection storage you may use in your application: +// e.g. instructive selection (store a bool inside each object), external array (store an array in your view data, next +// to your objects), set/map/hash (store only selected items), or other structures (store indices in an interval tree), etc. +// - The work involved to deal with multi-selection differs whether you want to only submit visible items and clip others, +// or submit all items regardless of their visibility. Clipping items is more efficient and will allow you to deal with +// large lists (1k~100k items) with no performance penalty, but requires a little more work on the code. +// For small selection set (<100 items), you might want to not bother with using the clipper, as the cost you should +// be negligible (as least on Dear ImGui side). +// If you are not sure, always start without clipping and you can work your way to the optimized version afterwards. // - The void* RangeSrcItem/RangeDstItem value represent a selectable object. They are the value you pass to SetNextItemSelectionUserData(). // Most likely you will want to store an index here. // Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points and you will need to interpolate @@ -2759,34 +2761,35 @@ enum ImGuiMultiSelectFlags_ // and then from the pointer have your own way of iterating from RangeSrcItem to RangeDstItem). // Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (2) [If using a clipper] Honor Clear/SelectAll/SetRange requests by updating your selection data. Can use same code as Step 6. -// LOOP - (3) [If using a clipper] Set RangeSrcPassedBy=true if the RangeSrcItem item is part of the items clipped before the first submitted/visible item. +// - (2) [If using clipper] Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 6. +// LOOP - (3) [If using clipper] Set RangeSrcPassedBy=true if the RangeSrcItem item is part of the items clipped before the first submitted/visible item. // This is because for range-selection we need to know if we are currently "inside" or "outside" the range. -// If you are using integer indices everywhere, this is easy to compute: if (clipper.DisplayStart > (int)data->RangeSrcItem) { data->RangeSrcPassedBy = true; } -// - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. -// (optionally call IsItemToggledSelection() to query if the selection state has been toggled for a given visible item, if you need that info immediately for your display, before EndMultiSelect()) +// - If you are using integer indices, this is easy to compute: if (clipper.DisplayStart > data->RangeSrcItem) { data->RangeSrcPassedBy = true; } +// - If you are using pointers, you may need additional processing in each clipper step to tell if current DisplayStart comes after RangeSrcItem.. +// - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. (optionally call IsItemToggledSelection() if you need that info immediately for displaying your item, before EndMultiSelect()) // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Always process them in this order (as you will receive Clear+SetRange request simultaneously). Can use same code as Step 2. +// - (6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 2. // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. +// However it is perfectly fine to honor all steps even if you don't use a clipper. struct ImGuiMultiSelectIO { - // - Always process requests in this order: Clear, SelectAll, SetRange. + // - Always process requests in this order: Clear, SelectAll, SetRange. Use 'Debug Log->Selection' to see requests as they happen. // - Some fields are only necessary if your list is dynamic and allows deletion (getting "post-deletion" state right is exhibited in the demo) // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. - // REQUESTS ----------------// BEGIN / LOOP / END - bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. - bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. - bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeSrcItem..RangeDstItem] items, based on RangeSelected. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. - void* RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implementing a deletion idiom (see demo). - // STATE/ARGUMENTS ---------// BEGIN / LOOP / END - void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionUserData() value for RangeSrcItem. End: parameter from RequestSetRange request. - void* RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. - ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrcItem came before RangeDstItem, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. - bool RangeSelected; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. - bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. - bool RangeSrcReset; // app:w / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). - bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). - void* NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). + // REQUESTS --------------------------------// BEGIN / LOOP / END + bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. + bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. + bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeSrcItem..RangeDstItem] items, based on RangeSelected. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. + void* RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implementing a deletion idiom (see demo). + // STATE/ARGUMENTS -------------------------// BEGIN / LOOP / END + void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionUserData() value for RangeSrcItem. End: parameter from RequestSetRange request. + void* RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. + ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrcItem came before RangeDstItem, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. + bool RangeSelected; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. + bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. + bool RangeSrcReset; // app:w / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). + bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). + void* NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). ImGuiMultiSelectIO() { Clear(); } void Clear() { memset(this, 0, sizeof(*this)); RequestFocusItem = NavIdItem = RangeSrcItem = RangeDstItem = (void*)-1; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c532ff9b4..bd4618e32 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2796,7 +2796,8 @@ struct ExampleSelection void SetRange(int a, int b, bool v) { if (b < a) { int tmp = b; b = a; a = tmp; } for (int n = a; n <= b; n++) SetSelected(n, v); } void SelectAll(int count) { Storage.Data.resize(count); for (int idx = 0; idx < count; idx++) Storage.Data[idx] = ImGuiStoragePair((ImGuiID)idx, 1); SelectionSize = count; } // This could be using SetRange(), but it this way is faster. - // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). Must be done in this order! Order->SelectAll->SetRange. + // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). Must be done in this order! Clear->SelectAll->SetRange. + // Enable 'Debug Log->Selection' to see selection requests as they happen. void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) { if (ms_io->RequestClear) { Clear(); } @@ -2934,6 +2935,8 @@ static void ShowDemoWindowMultiSelect() { static ExampleSelection selection; + ImGui::Text("Tips: Use 'Debug Log->Selection' to see selection requests as they happen."); + ImGui::Text("Supported features:"); ImGui::BulletText("Keyboard navigation (arrows, page up/down, home/end, space)."); ImGui::BulletText("Ctrl modifier to preserve and toggle selection."); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 58467a1de..9dacb010d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7455,11 +7455,10 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) #ifndef IMGUI_DISABLE_DEBUG_TOOLS const bool is_active = (storage->LastFrameActive >= GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here. if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } - bool open = TreeNode((void*)(intptr_t)storage->ID, "MultiSelect 0x%08X%s", storage->ID, is_active ? "" : " *Inactive*"); + bool open = TreeNode((void*)(intptr_t)storage->ID, "MultiSelect 0x%08X in '%s'%s", storage->ID, storage->Window ? storage->Window->Name : "N/A", is_active ? "" : " *Inactive*"); if (!is_active) { PopStyleColor(); } if (!open) return; - Text("ID = 0x%08X", storage->ID); Text("RangeSrcItem = %p, RangeSelected = %d", storage->RangeSrcItem, storage->RangeSelected); Text("NavIdData = %p, NavIdSelected = %d", storage->NavIdItem, storage->NavIdSelected); TreePop(); From e82b49d2d468f9d26dbd4f7ad500016ebf4e2943 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Aug 2023 12:38:24 +0200 Subject: [PATCH 0140/2359] MultiSelect: (Breaking) Use ImGuiSelectionUserData (= ImS64) instead of void* for selection user data. Less confusing for most users, less casting. --- imgui.h | 38 +++++++++++++++++++++++--------------- imgui_demo.cpp | 24 ++++++++++++------------ imgui_internal.h | 6 +++--- imgui_widgets.cpp | 30 +++++++++++++++--------------- 4 files changed, 53 insertions(+), 45 deletions(-) diff --git a/imgui.h b/imgui.h index 811bf940e..4d6ecaf0b 100644 --- a/imgui.h +++ b/imgui.h @@ -265,8 +265,9 @@ typedef ImWchar32 ImWchar; typedef ImWchar16 ImWchar; #endif -// Multi-Selection item index or identifier when using SetNextItemSelectionUserData()/BeginMultiSelect() -// (Most users are likely to use this store an item INDEX but this may be used to store a POINTER as well.) +// Multi-Selection item index or identifier when using BeginMultiSelect() +// - Used by SetNextItemSelectionUserData() + and inside ImGuiMultiSelectIO structure. +// - Most users are likely to use this store an item INDEX but this may be used to store a POINTER as well. Read comments near ImGuiMultiSelectIO for details. typedef ImS64 ImGuiSelectionUserData; // Callback and functions types @@ -670,7 +671,7 @@ namespace ImGui // Multi-selection system for Selectable() and TreeNode() functions. // - 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. - // - Read comments near ImGuiMultiSelectIO for details. + // - ImGuiSelectionUserData is often used to store your item index. Read comments near ImGuiMultiSelectIO for details. IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); @@ -2754,18 +2755,25 @@ enum ImGuiMultiSelectFlags_ // For small selection set (<100 items), you might want to not bother with using the clipper, as the cost you should // be negligible (as least on Dear ImGui side). // If you are not sure, always start without clipping and you can work your way to the optimized version afterwards. -// - The void* RangeSrcItem/RangeDstItem value represent a selectable object. They are the value you pass to SetNextItemSelectionUserData(). -// Most likely you will want to store an index here. -// Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points and you will need to interpolate -// between them to honor range selection. But the code never assume that sortable integers are used (you may store pointers to your object, -// and then from the pointer have your own way of iterating from RangeSrcItem to RangeDstItem). +// About ImGuiSelectionUserData: +// - This is your application-defined identifier in a selection set: +// - For each item is submitted by your calls to SetNextItemSelectionUserData(). +// - In return we store them into RangeSrcItem/RangeDstItem and other fields ImGuiMultiSelectIO. +// - Most applications will store an object INDEX, hence the chosen name and type. +// Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points +// and you will need to interpolate between them to honor range selection. +// - However it is perfectly possible to store a POINTER inside this value! The multi-selection system never assume +// that you identify items by indices, and never attempt to interpolate between two ImGuiSelectionUserData values. +// - As most users will want to cast this to integer, for convenience and to reduce confusion we use ImS64 instead +// of void*, being syntactically easier to downcast. But feel free to reinterpret_cast a pointer into this. +// - If you need to wrap this API for another language/framework, feel free to expose this as 'int' if simpler. // Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (2) [If using clipper] Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 6. // LOOP - (3) [If using clipper] Set RangeSrcPassedBy=true if the RangeSrcItem item is part of the items clipped before the first submitted/visible item. // This is because for range-selection we need to know if we are currently "inside" or "outside" the range. -// - If you are using integer indices, this is easy to compute: if (clipper.DisplayStart > data->RangeSrcItem) { data->RangeSrcPassedBy = true; } -// - If you are using pointers, you may need additional processing in each clipper step to tell if current DisplayStart comes after RangeSrcItem.. +// - If you are using integer indices in ImGuiSelectionUserData, this is easy to compute: if (clipper.DisplayStart > data->RangeSrcItem) { data->RangeSrcPassedBy = true; } +// - If you are using pointers in ImGuiSelectionUserData, you may need additional processing in each clipper step to tell if current DisplayStart comes after RangeSrcItem.. // - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. (optionally call IsItemToggledSelection() if you need that info immediately for displaying your item, before EndMultiSelect()) // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 2. @@ -2780,19 +2788,19 @@ struct ImGuiMultiSelectIO bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeSrcItem..RangeDstItem] items, based on RangeSelected. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. - void* RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implementing a deletion idiom (see demo). + ImGuiSelectionUserData RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implementing a deletion idiom (see demo). // STATE/ARGUMENTS -------------------------// BEGIN / LOOP / END - void* RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionUserData() value for RangeSrcItem. End: parameter from RequestSetRange request. - void* RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. + ImGuiSelectionUserData RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionUserData() value for RangeSrcItem. End: parameter from RequestSetRange request. + ImGuiSelectionUserData RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrcItem came before RangeDstItem, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. bool RangeSelected; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. bool RangeSrcReset; // app:w / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). - void* NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). + ImGuiSelectionUserData NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). ImGuiMultiSelectIO() { Clear(); } - void Clear() { memset(this, 0, sizeof(*this)); RequestFocusItem = NavIdItem = RangeSrcItem = RangeDstItem = (void*)-1; } + void Clear() { memset(this, 0, sizeof(*this)); RequestFocusItem = NavIdItem = RangeSrcItem = RangeDstItem = (ImGuiSelectionUserData)-1; } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bd4618e32..af8604182 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2802,7 +2802,7 @@ struct ExampleSelection { if (ms_io->RequestClear) { Clear(); } if (ms_io->RequestSelectAll) { SelectAll(items_count); } - if (ms_io->RequestSetRange) { SetRange((int)(intptr_t)ms_io->RangeSrcItem, (int)(intptr_t)ms_io->RangeDstItem, ms_io->RangeSelected ? 1 : 0); } + if (ms_io->RequestSetRange) { SetRange((int)ms_io->RangeSrcItem, (int)ms_io->RangeDstItem, ms_io->RangeSelected ? 1 : 0); } } void DebugTooltip() @@ -2827,19 +2827,19 @@ struct ExampleSelection QueueDeletion = false; // If current item is not selected. - if (ms_io->NavIdSelected == false) // Here 'NavIdSelected' should be == to 'GetSelected(ms_io->NavIdData)' + if (ms_io->NavIdSelected == false) // Here 'NavIdSelected' should be == to 'GetSelected(ms_io->NavIdData)' { - ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even without the !NavIdSelected test but it would take an extra frame to recover RangeSrc when deleting a selected item. - return (int)(intptr_t)ms_io->NavIdItem; // Request to land on same item after deletion. + ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even without the !NavIdSelected test but it would take an extra frame to recover RangeSrc when deleting a selected item. + return (int)ms_io->NavIdItem; // Request to land on same item after deletion. } // If current item is selected: land on first unselected item after RangeSrc. - for (int n = (int)(intptr_t)ms_io->RangeSrcItem + 1; n < items.Size; n++) + for (int n = (int)ms_io->RangeSrcItem + 1; n < items.Size; n++) if (!GetSelected(n)) return n; // If current item is selected: otherwise return last unselected item. - for (int n = IM_MIN((int)(intptr_t)ms_io->RangeSrcItem, items.Size) - 1; n >= 0; n--) + for (int n = IM_MIN((int)ms_io->RangeSrcItem, items.Size) - 1; n >= 0; n--) if (!GetSelected(n)) return n; @@ -2860,7 +2860,7 @@ struct ExampleSelection IM_UNUSED(ms_io); ImVector new_items; new_items.reserve(items.Size - SelectionSize); - int next_focus_idx_in_old_selection = (int)(intptr_t)ms_io->RequestFocusItem; + int next_focus_idx_in_old_selection = (int)ms_io->RequestFocusItem; int next_focus_idx_in_new_selection = -1; for (int n = 0; n < items.Size; n++) { @@ -3016,8 +3016,8 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: If pressing Delete + another key we have ambiguous behavior. const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); if (want_delete) - ms_io->RequestFocusItem = (void*)(intptr_t)selection.ApplyDeletionPreLoop(ms_io, items); - const int next_focus_item_idx = (int)(intptr_t)ms_io->RequestFocusItem; + ms_io->RequestFocusItem = selection.ApplyDeletionPreLoop(ms_io, items); + const int next_focus_item_idx = (int)ms_io->RequestFocusItem; for (int n = 0; n < items.Size; n++) { @@ -3138,7 +3138,7 @@ static void ShowDemoWindowMultiSelect() const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); if (want_delete) selection.ApplyDeletionPreLoop(ms_io, items); - const int next_focus_item_idx = (int)(intptr_t)ms_io->RequestFocusItem; + const int next_focus_item_idx = (int)ms_io->RequestFocusItem; if (show_in_table) { @@ -3162,7 +3162,7 @@ static void ShowDemoWindowMultiSelect() { // IF clipping is used: you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. // If you submit all items this is unnecessary as this is one by SetNextItemSelectionUserData() - if (use_clipper && clipper.DisplayStart > (int)(intptr_t)ms_io->RangeSrcItem) + if (use_clipper && !ms_io->RangeSrcPassedBy && clipper.DisplayStart > ms_io->RangeSrcItem) ms_io->RangeSrcPassedBy = true; const int item_begin = use_clipper ? clipper.DisplayStart : 0; @@ -3254,7 +3254,7 @@ static void ShowDemoWindowMultiSelect() // If clipping is used: you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. // If you submit all items this is unnecessary as this is one by SetNextItemSelectionUserData() // Here we essentially notify before EndMultiSelect() that RangeSrc is still present in our data set. - if (use_clipper && items.Size > (int)(intptr_t)ms_io->RangeSrcItem) + if (use_clipper && !ms_io->RangeSrcPassedBy && items.Size > ms_io->RangeSrcItem) ms_io->RangeSrcPassedBy = true; if (show_in_table) diff --git a/imgui_internal.h b/imgui_internal.h index b076368e5..ce80d94be 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1741,11 +1741,11 @@ struct IMGUI_API ImGuiMultiSelectState int LastFrameActive; // Last used frame-count, for GC. ImS8 RangeSelected; // -1 (don't have) or true/false ImS8 NavIdSelected; // -1 (don't have) or true/false - void* RangeSrcItem; // - void* NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) + ImGuiSelectionUserData RangeSrcItem; // + ImGuiSelectionUserData NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) ImGuiMultiSelectState() { Init(0); } - void Init(ImGuiID id) { Window = NULL; ID = id; LastFrameActive = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = (void*)-1; } + void Init(ImGuiID id) { Window = NULL; ID = id; LastFrameActive = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9dacb010d..e62a8e100 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7128,7 +7128,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe ImGuiContext& g = *GImGui; if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); - if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, data->RangeSrcItem, data->RangeDstItem, data->RangeSelected, data->RangeDirection); + if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, (void*)data->RangeSrcItem, (void*)data->RangeDstItem, data->RangeSelected, data->RangeDirection); } // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). @@ -7174,7 +7174,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (ms->KeyMods & ImGuiMod_Shift) ms->IsSetRange = true; if (ms->IsSetRange) - IM_ASSERT(storage->RangeSrcItem != (void*)-1); // Not ready -> could clear? + IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid); // Not ready -> could clear? if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) ms->BeginIO.RequestClear = true; } @@ -7207,15 +7207,15 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->IsFocused) { - if (ms->BeginIO.RangeSrcReset || (ms->BeginIO.RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != (void*)-1)) + if (ms->BeginIO.RangeSrcReset || (ms->BeginIO.RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. - ms->Storage->RangeSrcItem = (void*)-1; + ms->Storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; } - if (ms->NavIdPassedBy == false && ms->Storage->NavIdItem != (void*)-1) + if (ms->NavIdPassedBy == false && ms->Storage->NavIdItem != ImGuiSelectionUserData_Invalid) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdItem.\n"); - ms->Storage->NavIdItem = (void*)-1; + ms->Storage->NavIdItem = ImGuiSelectionUserData_Invalid; ms->Storage->NavIdSelected = -1; } } @@ -7255,7 +7255,7 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d { // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect; - if (ms->BeginIO.RangeSrcItem == (void*)selection_user_data) + if (ms->BeginIO.RangeSrcItem == selection_user_data) ms->BeginIO.RangeSrcPassedBy = true; } else @@ -7273,7 +7273,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) ImGuiMultiSelectState* storage = ms->Storage; IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); - void* item_data = (void*)g.NextItemData.SelectionUserData; + ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; // Apply Clear/SelectAll requests requested by BeginMultiSelect(). // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. @@ -7293,7 +7293,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) if (is_range_dst) { ms->RangeDstPassedBy = true; - if (storage->RangeSrcItem == (void*)-1) // If we don't have RangeSrc, assign RangeSrc = RangeDst + if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst { storage->RangeSrcItem = item_data; storage->RangeSelected = selected ? 1 : 0; @@ -7302,7 +7302,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) const bool is_range_src = storage->RangeSrcItem == item_data; if (is_range_src || is_range_dst || ms->BeginIO.RangeSrcPassedBy != ms->RangeDstPassedBy) { - IM_ASSERT(storage->RangeSrcItem != (void*)-1 && storage->RangeSelected != -1); + IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1); selected = (storage->RangeSelected != 0); } else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) @@ -7330,13 +7330,13 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) if (!ms->IsFocused && !hovered) return; - void* item_data = (void*)g.NextItemData.SelectionUserData; + ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; const bool is_multiselect = (ms->Flags & ImGuiMultiSelectFlags_SingleSelect) == 0; bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; - if (g.NavId == id && storage->RangeSrcItem == (void*)-1) + if (g.NavId == id && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) { storage->RangeSrcItem = item_data; storage->RangeSelected = selected; // Will be updated at the end of this function anyway. @@ -7398,7 +7398,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Shift+Arrow always select // Ctrl+Shift+Arrow copy source selection state (alrady stored by BeginMultiSelect() in RangeSelected) //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); - ms->EndIO.RangeSrcItem = (storage->RangeSrcItem != (void*)-1) ? storage->RangeSrcItem : item_data; + ms->EndIO.RangeSrcItem = (storage->RangeSrcItem != ImGuiSelectionUserData_Invalid) ? storage->RangeSrcItem : item_data; ms->EndIO.RangeSelected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; ms->EndIO.RangeDirection = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; } @@ -7459,8 +7459,8 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) if (!is_active) { PopStyleColor(); } if (!open) return; - Text("RangeSrcItem = %p, RangeSelected = %d", storage->RangeSrcItem, storage->RangeSelected); - Text("NavIdData = %p, NavIdSelected = %d", storage->NavIdItem, storage->NavIdSelected); + Text("RangeSrcItem = %p, RangeSelected = %d", (void*)storage->RangeSrcItem, storage->RangeSelected); + Text("NavIdData = %p, NavIdSelected = %d", (void*)storage->NavIdItem, storage->NavIdSelected); TreePop(); #else IM_UNUSED(storage); From c9eb3714e8b0768117ce4492d6410a5b880045cc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Aug 2023 18:53:57 +0200 Subject: [PATCH 0141/2359] MultiSelect: move HasSelectionData to ImGuiItemFlags to facilitate copying around in standardized fieds. Required/motivated to simplify support for ImGuiTreeNodeFlags_NavLeftJumpsBackHere (bc3c0ce) in this branch. --- imgui_internal.h | 5 ++--- imgui_widgets.cpp | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ce80d94be..3bf729e3b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1211,15 +1211,14 @@ enum ImGuiNextItemDataFlags_ ImGuiNextItemDataFlags_HasOpen = 1 << 1, ImGuiNextItemDataFlags_HasShortcut = 1 << 2, ImGuiNextItemDataFlags_HasRefVal = 1 << 3, - ImGuiNextItemDataFlags_HasSelectionData = 1 << 4, }; struct ImGuiNextItemData { ImGuiNextItemDataFlags Flags; - ImGuiItemFlags ItemFlags; // Currently only tested/used for ImGuiItemFlags_AllowOverlap. + ImGuiItemFlags ItemFlags; // Currently only tested/used for ImGuiItemFlags_AllowOverlap and ImGuiItemFlags_HasSelectionUserData. // Non-flags members are NOT cleared by ItemAdd() meaning they are still valid during NavProcessItem() - ImGuiID FocusScopeId; // Set by SetNextItemSelectionUserData() (!= 0 signify value has been set) + ImGuiID FocusScopeId; // Set by SetNextItemSelectionUserData() ImGuiSelectionUserData SelectionUserData; // Set by SetNextItemSelectionUserData() (note that NULL/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) float Width; // Set by SetNextItemWidth() ImGuiKeyChord Shortcut; // Set by SetNextItemShortcut() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e62a8e100..48336721d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6390,8 +6390,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags } // Compute open and multi-select states before ItemAdd() as it clear NextItem data. + const bool is_multi_select = (g.NextItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0; // Before ItemAdd() bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); - const bool is_multi_select = (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasSelectionData) != 0; // Before ItemAdd() bool item_add = ItemAdd(interact_bb, id); g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; g.LastItemData.DisplayRect = frame_bb; @@ -6780,7 +6780,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl } const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; - const bool is_multi_select = (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasSelectionData) != 0; // Before ItemAdd() + const bool is_multi_select = (g.NextItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0; // Before ItemAdd() const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); if (span_all_columns) From 6821401a3f00e637a1646d02a5c364728a653b21 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 8 Aug 2023 14:47:50 +0200 Subject: [PATCH 0142/2359] MultiSelect: Tweak debug log to print decimal+hex values for item data. Struggled to get standard PRIX64 to work on CI. --- imgui_widgets.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 48336721d..9ccb63d60 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -70,6 +70,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #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-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. #pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') @@ -7128,7 +7129,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe ImGuiContext& g = *GImGui; if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); - if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %p..%p = %d (dir %+d)\n", function, (void*)data->RangeSrcItem, (void*)data->RangeDstItem, data->RangeSelected, data->RangeDirection); + if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d (dir %+d)\n", function, data->RangeSrcItem, data->RangeDstItem, data->RangeSrcItem, data->RangeDstItem, data->RangeSelected, data->RangeDirection); } // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). @@ -7459,8 +7460,8 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) if (!is_active) { PopStyleColor(); } if (!open) return; - Text("RangeSrcItem = %p, RangeSelected = %d", (void*)storage->RangeSrcItem, storage->RangeSelected); - Text("NavIdData = %p, NavIdSelected = %d", (void*)storage->NavIdItem, storage->NavIdSelected); + Text("RangeSrcItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), RangeSelected = %d", storage->RangeSrcItem, storage->RangeSrcItem, storage->RangeSelected); + Text("NavIdItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), NavIdSelected = %d", storage->NavIdItem, storage->NavIdItem, storage->NavIdSelected); TreePop(); #else IM_UNUSED(storage); From af83a3eea44a0a0397ea6f1e44a475b84a8958bf Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 15 Aug 2023 18:11:14 +0200 Subject: [PATCH 0143/2359] MultiSelect: clear selection when leaving a scope with a nav directional request. May need to clarify how to depends on actions being performed (e.g. click doesn't). May become optional? --- imgui.cpp | 3 +++ imgui_widgets.cpp | 36 +++++++++++++++++++++--------------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 26f0f36bc..19beed8ed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12251,6 +12251,7 @@ static void ImGui::NavUpdate() // Process navigation init request (select first/default focus) g.NavJustMovedToId = 0; + g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0; if (g.NavInitResult.ID != 0) NavInitRequestApplyResult(); g.NavInitRequest = false; @@ -12403,6 +12404,7 @@ void ImGui::NavInitRequestApplyResult() ImGuiNavItemData* result = &g.NavInitResult; if (g.NavId != result->ID) { + g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId; g.NavJustMovedToId = result->ID; g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = 0; @@ -12661,6 +12663,7 @@ void ImGui::NavMoveRequestApplyResult() // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior. if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0) { + g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId; g.NavJustMovedToId = result->ID; g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = g.NavMoveKeyMods; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9ccb63d60..94123de76 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7165,10 +7165,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) ms->BeginIO.NavIdItem = ms->EndIO.NavIdItem = storage->NavIdItem; ms->BeginIO.NavIdSelected = ms->EndIO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; - if (!ms->IsFocused) - return &ms->BeginIO; // This is cleared at this point. - - // Auto clear when using Navigation to move within the selection + // Clear when using Navigation to move within the scope // (we compare FocusScopeId so it possible to use multiple selections inside a same window) if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) { @@ -7179,18 +7176,27 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) ms->BeginIO.RequestClear = true; } - - // Shortcut: Select all (CTRL+A) - if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) - if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) - ms->BeginIO.RequestSelectAll = true; - - // Shortcut: Clear selection (Escape) - // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. - // Otherwise may be done by caller but it means Shortcut() needs to be exposed. - if (flags & ImGuiMultiSelectFlags_ClearOnEscape) - if (Shortcut(ImGuiKey_Escape)) + else if (g.NavJustMovedFromFocusScopeId == ms->FocusScopeId) + { + // Also clear on leaving scope (may be optional?) + if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) ms->BeginIO.RequestClear = true; + } + + if (ms->IsFocused) + { + // Shortcut: Select all (CTRL+A) + if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) + ms->BeginIO.RequestSelectAll = true; + + // Shortcut: Clear selection (Escape) + // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. + // Otherwise may be done by caller but it means Shortcut() needs to be exposed. + if (flags & ImGuiMultiSelectFlags_ClearOnEscape) + if (Shortcut(ImGuiKey_Escape)) + ms->BeginIO.RequestClear = true; + } if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) DebugLogMultiSelectRequests("BeginMultiSelect", &ms->BeginIO); From ff95fdb668a05375dcde40df1c5cd40b6cc530c2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Aug 2023 19:20:51 +0200 Subject: [PATCH 0144/2359] MultiSelect: (Breaking) RequestSetRange's parameter are RangeFirstItem...RangeLastItem (which was always ordered unlike RangeSrcItem...RangeDstItme). Removed RangeDstItem. Removed RangeDirection. --- imgui.h | 14 +++++++------- imgui_demo.cpp | 4 ++-- imgui_widgets.cpp | 12 +++++++----- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/imgui.h b/imgui.h index 4d6ecaf0b..9e5a9aef2 100644 --- a/imgui.h +++ b/imgui.h @@ -2758,7 +2758,7 @@ enum ImGuiMultiSelectFlags_ // About ImGuiSelectionUserData: // - This is your application-defined identifier in a selection set: // - For each item is submitted by your calls to SetNextItemSelectionUserData(). -// - In return we store them into RangeSrcItem/RangeDstItem and other fields ImGuiMultiSelectIO. +// - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. // - Most applications will store an object INDEX, hence the chosen name and type. // Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points // and you will need to interpolate between them to honor range selection. @@ -2787,20 +2787,20 @@ struct ImGuiMultiSelectIO // REQUESTS --------------------------------// BEGIN / LOOP / END bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. - bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeSrcItem..RangeDstItem] items, based on RangeSelected. In practice, only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. + bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeFirstItem..RangeLastItem] items, based on RangeSelected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. ImGuiSelectionUserData RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implementing a deletion idiom (see demo). // STATE/ARGUMENTS -------------------------// BEGIN / LOOP / END - ImGuiSelectionUserData RangeSrcItem; // ms:w / app:r / ms:w, app:r // Begin: Last known SetNextItemSelectionUserData() value for RangeSrcItem. End: parameter from RequestSetRange request. - ImGuiSelectionUserData RangeDstItem; // / / ms:w, app:r // End: parameter from RequestSetRange request. - ImS8 RangeDirection; // / / ms:w, app:r // End: parameter from RequestSetRange request. +1 if RangeSrcItem came before RangeDstItem, -1 otherwise. Available as an indicator in case you cannot infer order from the void* values. If your void* values are storing indices you will never need this. - bool RangeSelected; // / / ms:w, app:r // End: parameter from RequestSetRange request. true = Select Range, false = Unselect Range. + ImGuiSelectionUserData RangeSrcItem; // ms:w / app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point). Read during loop in order for user code to set RangeSrcPassedBy. + ImGuiSelectionUserData RangeFirstItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) + ImGuiSelectionUserData RangeLastItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) + bool RangeSelected; // / / ms:w, app:r // End: parameter for RequestSetRange request. true = Select Range, false = Unselect Range. bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. bool RangeSrcReset; // app:w / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). ImGuiSelectionUserData NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). ImGuiMultiSelectIO() { Clear(); } - void Clear() { memset(this, 0, sizeof(*this)); RequestFocusItem = NavIdItem = RangeSrcItem = RangeDstItem = (ImGuiSelectionUserData)-1; } + void Clear() { memset(this, 0, sizeof(*this)); RequestFocusItem = NavIdItem = RangeSrcItem = RangeFirstItem = RangeLastItem = (ImGuiSelectionUserData)-1; } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index af8604182..7a1d74b96 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2793,7 +2793,7 @@ struct ExampleSelection // you will need a way to iterate from one item to the other item given the ID you use. // You are likely to need some kind of data structure to convert 'view index' <> 'object ID' (FIXME-MULTISELECT: Would be worth providing a demo of doing this). // Note: This implementation of SetRange() is inefficient because it doesn't take advantage of the fact that ImGuiStorage stores sorted key. - void SetRange(int a, int b, bool v) { if (b < a) { int tmp = b; b = a; a = tmp; } for (int n = a; n <= b; n++) SetSelected(n, v); } + void SetRange(int a, int b, bool v) { for (int n = a; n <= b; n++) SetSelected(n, v); } void SelectAll(int count) { Storage.Data.resize(count); for (int idx = 0; idx < count; idx++) Storage.Data[idx] = ImGuiStoragePair((ImGuiID)idx, 1); SelectionSize = count; } // This could be using SetRange(), but it this way is faster. // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). Must be done in this order! Clear->SelectAll->SetRange. @@ -2802,7 +2802,7 @@ struct ExampleSelection { if (ms_io->RequestClear) { Clear(); } if (ms_io->RequestSelectAll) { SelectAll(items_count); } - if (ms_io->RequestSetRange) { SetRange((int)ms_io->RangeSrcItem, (int)ms_io->RangeDstItem, ms_io->RangeSelected ? 1 : 0); } + if (ms_io->RequestSetRange) { SetRange((int)ms_io->RangeFirstItem, (int)ms_io->RangeLastItem, ms_io->RangeSelected ? 1 : 0); } } void DebugTooltip() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 94123de76..178f0991f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7129,7 +7129,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe ImGuiContext& g = *GImGui; if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); - if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d (dir %+d)\n", function, data->RangeSrcItem, data->RangeDstItem, data->RangeSrcItem, data->RangeDstItem, data->RangeSelected, data->RangeDirection); + if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, data->RangeFirstItem, data->RangeLastItem, data->RangeFirstItem, data->RangeLastItem, data->RangeSelected); } // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). @@ -7159,7 +7159,6 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) storage->Window = window; ms->Storage = storage; - // FIXME-MULTISELECT: Index vs Pointers. // We want EndIO's NavIdItem/NavIdSelected to match BeginIO's one, so the value never changes after EndMultiSelect() ms->BeginIO.RangeSrcItem = ms->EndIO.RangeSrcItem = storage->RangeSrcItem; ms->BeginIO.NavIdItem = ms->EndIO.NavIdItem = storage->NavIdItem; @@ -7398,8 +7397,8 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) //---------------------------------------------------------------------------------------- ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; + int range_direction; ms->EndIO.RequestSetRange = true; - ms->EndIO.RangeDstItem = item_data; if (is_shift && is_multiselect) { // Shift+Arrow always select @@ -7407,7 +7406,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); ms->EndIO.RangeSrcItem = (storage->RangeSrcItem != ImGuiSelectionUserData_Invalid) ? storage->RangeSrcItem : item_data; ms->EndIO.RangeSelected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; - ms->EndIO.RangeDirection = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; + range_direction = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; } else { @@ -7415,8 +7414,11 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = is_ctrl ? !selected : true; ms->EndIO.RangeSrcItem = storage->RangeSrcItem = item_data; ms->EndIO.RangeSelected = selected; - ms->EndIO.RangeDirection = +1; + range_direction = +1; } + ImGuiSelectionUserData range_dst_item = item_data; + ms->EndIO.RangeFirstItem = (range_direction > 0) ? ms->EndIO.RangeSrcItem : range_dst_item; + ms->EndIO.RangeLastItem = (range_direction > 0) ? range_dst_item : ms->EndIO.RangeSrcItem; if (!is_multiselect) { From c3753809b1d44cef960843eabf70ceb2ea30229f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Aug 2023 17:46:19 +0200 Subject: [PATCH 0145/2359] MultiSelect: Demo: rework ExampleSelection names to map better to typical user code + variety of Comments tweaks. --- imgui.h | 47 +++++++++++-------- imgui_demo.cpp | 122 ++++++++++++++++++++++--------------------------- 2 files changed, 82 insertions(+), 87 deletions(-) diff --git a/imgui.h b/imgui.h index 9e5a9aef2..730a53e2b 100644 --- a/imgui.h +++ b/imgui.h @@ -671,7 +671,8 @@ namespace ImGui // Multi-selection system for Selectable() and TreeNode() functions. // - 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. - // - ImGuiSelectionUserData is often used to store your item index. Read comments near ImGuiMultiSelectIO for details. + // - ImGuiSelectionUserData is often used to store your item index. + // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State' for demo. IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); @@ -2740,32 +2741,35 @@ enum ImGuiMultiSelectFlags_ // Multi-selection system // - Refer to 'Demo->Widgets->Selection State' for references using this. // - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) -// and supports a clipper being used. Handling this manually may be tricky, this is why we provide the functionality. -// If you don't need SHIFT+Mouse/Keyboard range-select + clipping, you can use a simpler form of multi-selection yourself, -// by reacting to click/presses on Selectable() items and checking keyboard modifiers. -// The complexity of this system is mostly caused by supporting SHIFT+Click/Arrow range-select with clipped elements. +// and supports a clipper being used. Handling this manually and correctly i tricky, this is why we provide +// the functionality. If you don't need SHIFT+Mouse/Keyboard range-select + clipping, you can implement a +// simple form of multi-selection yourself, by reacting to click/presses on Selectable() items. // - TreeNode() and Selectable() are supported but custom widgets may use it as well. // - In the spirit of Dear ImGui design, your code owns actual selection data. // This is designed to allow all kinds of selection storage you may use in your application: -// e.g. instructive selection (store a bool inside each object), external array (store an array in your view data, next -// to your objects), set/map/hash (store only selected items), or other structures (store indices in an interval tree), etc. -// - The work involved to deal with multi-selection differs whether you want to only submit visible items and clip others, -// or submit all items regardless of their visibility. Clipping items is more efficient and will allow you to deal with -// large lists (1k~100k items) with no performance penalty, but requires a little more work on the code. -// For small selection set (<100 items), you might want to not bother with using the clipper, as the cost you should -// be negligible (as least on Dear ImGui side). -// If you are not sure, always start without clipping and you can work your way to the optimized version afterwards. +// e.g. set/map/hash (store only selected items), instructive selection (store a bool inside each object), +// external array (store an array in your view data, next to your objects), or other structures (store indices +// in an interval tree), etc. +// - The work involved to deal with multi-selection differs whether you want to only submit visible items and +// clip others, or submit all items regardless of their visibility. Clipping items is more efficient and will +// allow you to deal with large lists (1k~100k items) with no performance penalty, but requires a little more +// work on the code. +// For small selection set (<100 items), you might want to not bother with using the clipper, as the cost +// should be negligible (as least on Dear ImGui side). +// If you are not sure, always start without clipping! You can work your way to the optimized version afterwards. // About ImGuiSelectionUserData: // - This is your application-defined identifier in a selection set: // - For each item is submitted by your calls to SetNextItemSelectionUserData(). // - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. // - Most applications will store an object INDEX, hence the chosen name and type. -// Storing an integer index is the easiest thing to do, as SetRange requests will give you two end points -// and you will need to interpolate between them to honor range selection. +// Storing an integer index is the easiest thing to do, as RequestSetRange requests will give you two end-points +// and you will need to iterate/interpolate between them to honor range selection. // - However it is perfectly possible to store a POINTER inside this value! The multi-selection system never assume -// that you identify items by indices, and never attempt to interpolate between two ImGuiSelectionUserData values. +// that you identify items by indices. It never attempt to iterate/interpolate between 2 ImGuiSelectionUserData values. // - As most users will want to cast this to integer, for convenience and to reduce confusion we use ImS64 instead // of void*, being syntactically easier to downcast. But feel free to reinterpret_cast a pointer into this. +// - You may store another type of (e.g. an data) but this may make your lookups and the interpolation between +// two values more cumbersome. // - If you need to wrap this API for another language/framework, feel free to expose this as 'int' if simpler. // Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. @@ -2777,12 +2781,15 @@ enum ImGuiMultiSelectFlags_ // - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. (optionally call IsItemToggledSelection() if you need that info immediately for displaying your item, before EndMultiSelect()) // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 2. -// If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. -// However it is perfectly fine to honor all steps even if you don't use a clipper. +// If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. +// However it is perfectly fine to honor all steps even if you don't use a clipper. +// Advanced: +// - Deletion: If you need to handle items deletion a little more work if needed for post-deletion focus and scrolling to be correct. +// refer to 'Demo->Widgets->Selection State' for demos supporting deletion. struct ImGuiMultiSelectIO { - // - Always process requests in this order: Clear, SelectAll, SetRange. Use 'Debug Log->Selection' to see requests as they happen. - // - Some fields are only necessary if your list is dynamic and allows deletion (getting "post-deletion" state right is exhibited in the demo) + // - Always process requests in this order: Clear, SelectAll, SetRange. Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. + // - Some fields are only necessary if your list is dynamic and allows deletion (getting "post-deletion" state right is shown in the demo) // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. // REQUESTS --------------------------------// BEGIN / LOOP / END bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7a1d74b96..3cd8bf6ad 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2766,54 +2766,45 @@ static void ShowDemoWindowWidgets() // To store a single-selection: // - You only need a single variable and don't need any of this! // To store a multi-selection, in your real application you could: -// - Use intrusively stored selection (e.g. 'bool IsSelected' inside your object). This is by far the simplest -// way to store your selection data, but it means you cannot have multiple simultaneous views over your objects. -// This is what many of the simpler demos in this file are using (so they are not using this class). // - Use external storage: e.g. unordered_set/set/hash/map/interval trees (storing indices, objects id, etc.) -// are generally appropriate. Even a large array of bool might work for you... -// - If you need to handle extremely large selections, it might be advantageous to support a "negative" mode in -// your storage, so "Select All" becomes "Negative=1 + Clear" and then sparse unselect can add to the storage. +// are generally appropriate. Even a large array of bool might work for you... This is what we are doing here. +// - Use intrusively stored selection (e.g. 'bool IsSelected' inside your object). +// - This is simple, but it means you cannot have multiple simultaneous views over your objects. +// - This is what many of the simpler demos in other sections of this file are using (so they are not using this class). +// - Some of our features requires you to provide the selection size, which with this specific strategy require additional work: +// either you maintain it (which requires storage outside of objects) either you recompute (which may be costly for large sets). +// - So I would suggest that using intrusive selection for multi-select is not the most adequate. struct ExampleSelection { // Data ImGuiStorage Storage; // Selection set - int SelectionSize; // Number of selected items (== number of 1 in the Storage, maintained by this class). // FIXME-MULTISELECT: Imply more difficult to track with intrusive selection schemes? + int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). // FIXME-MULTISELECT: Imply more difficult to track with intrusive selection schemes? bool QueueDeletion; // Request deleting selected items // Functions ExampleSelection() { Clear(); } - void Clear() { Storage.Clear(); SelectionSize = 0; QueueDeletion = false; } - bool GetSelected(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } - void SetSelected(int n, bool v) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == (int)v) return; if (v) SelectionSize++; else SelectionSize--; *p_int = (bool)v; } - int GetSize() const { return SelectionSize; } + void Clear() { Storage.Clear(); Size = 0; QueueDeletion = false; } + bool Contains(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } + void AddItem(int n) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int != 0) return; *p_int = 1; Size++; } + void RemoveItem(int n) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == 0) return; *p_int = 0; Size--; } + void UpdateItem(int n, bool v) { if (v) AddItem(n); else RemoveItem(n); } + int GetSize() const { return Size; } + void DebugTooltip() { if (ImGui::BeginTooltip()) { for (auto& pair : Storage.Data) if (pair.val_i) ImGui::Text("0x%03X (%d)", pair.key, pair.key); ImGui::EndTooltip(); } } - // When using SetRange() / SelectAll() we assume that our objects ID are indices. - // In this demo we always store selection using indices and never in another manner (e.g. object ID or pointers). - // If your selection system is storing selection using object ID and you want to support Shift+Click range-selection, - // you will need a way to iterate from one item to the other item given the ID you use. - // You are likely to need some kind of data structure to convert 'view index' <> 'object ID' (FIXME-MULTISELECT: Would be worth providing a demo of doing this). - // Note: This implementation of SetRange() is inefficient because it doesn't take advantage of the fact that ImGuiStorage stores sorted key. - void SetRange(int a, int b, bool v) { for (int n = a; n <= b; n++) SetSelected(n, v); } - void SelectAll(int count) { Storage.Data.resize(count); for (int idx = 0; idx < count; idx++) Storage.Data[idx] = ImGuiStoragePair((ImGuiID)idx, 1); SelectionSize = count; } // This could be using SetRange(), but it this way is faster. - - // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). Must be done in this order! Clear->SelectAll->SetRange. - // Enable 'Debug Log->Selection' to see selection requests as they happen. + // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). + // - Must be done in this order! Clear->SelectAll->SetRange. Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. + // - Honoring RequestSetRange requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. + // - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection. + // - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform + // a lookup and have some way to iterate between two values. + // - A full-featured application is likely to allow search/filtering which is likely to lead to using indices and + // constructing a view index <> object id/ptr data structure. (FIXME-MULTISELECT: Would be worth providing a demo of doing this). + // - (Our implementation is slightly inefficient because it doesn't take advantage of the fat that ImguiStorage stores sorted key) void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) { if (ms_io->RequestClear) { Clear(); } - if (ms_io->RequestSelectAll) { SelectAll(items_count); } - if (ms_io->RequestSetRange) { SetRange((int)ms_io->RangeFirstItem, (int)ms_io->RangeLastItem, ms_io->RangeSelected ? 1 : 0); } - } - - void DebugTooltip() - { - if (ImGui::BeginTooltip()) - { - for (auto& pair : Storage.Data) - if (pair.val_i) - ImGui::Text("0x%03X (%d)", pair.key, pair.key); - ImGui::EndTooltip(); - } + if (ms_io->RequestSelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } + if (ms_io->RequestSetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } } // Call after BeginMultiSelect(). @@ -2827,20 +2818,20 @@ struct ExampleSelection QueueDeletion = false; // If current item is not selected. - if (ms_io->NavIdSelected == false) // Here 'NavIdSelected' should be == to 'GetSelected(ms_io->NavIdData)' + if (ms_io->NavIdSelected == false) // Here 'NavIdSelected' should be == to 'GetSelected(ms_io->NavIdData)' { - ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even without the !NavIdSelected test but it would take an extra frame to recover RangeSrc when deleting a selected item. - return (int)ms_io->NavIdItem; // Request to land on same item after deletion. + ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even without the !NavIdSelected test but it would take an extra frame to recover RangeSrc when deleting a selected item. + return (int)ms_io->NavIdItem; // Request to land on same item after deletion. } // If current item is selected: land on first unselected item after RangeSrc. for (int n = (int)ms_io->RangeSrcItem + 1; n < items.Size; n++) - if (!GetSelected(n)) + if (!Contains(n)) return n; // If current item is selected: otherwise return last unselected item. for (int n = IM_MIN((int)ms_io->RangeSrcItem, items.Size) - 1; n >= 0; n--) - if (!GetSelected(n)) + if (!Contains(n)) return n; return -1; @@ -2859,12 +2850,12 @@ struct ExampleSelection // This particular ExampleSelection case is designed to showcase maintaining selection-state separated from items-data. IM_UNUSED(ms_io); ImVector new_items; - new_items.reserve(items.Size - SelectionSize); + new_items.reserve(items.Size - Size); int next_focus_idx_in_old_selection = (int)ms_io->RequestFocusItem; int next_focus_idx_in_new_selection = -1; for (int n = 0; n < items.Size; n++) { - if (!GetSelected(n)) + if (!Contains(n)) new_items.push_back(items[n]); if (next_focus_idx_in_old_selection == n) next_focus_idx_in_new_selection = new_items.Size - 1; @@ -2874,20 +2865,19 @@ struct ExampleSelection // Update selection Clear(); if (next_focus_idx_in_new_selection != -1 && ms_io->NavIdSelected) - SetSelected(next_focus_idx_in_new_selection, true); + AddItem(next_focus_idx_in_new_selection); } }; static void ShowDemoWindowMultiSelect() { - IMGUI_DEMO_MARKER("Widgets/Selection State"); - //ImGui::SetNextItemOpen(true, ImGuiCond_Once); - if (ImGui::TreeNode("Selection State")) + IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); + if (ImGui::TreeNode("Selection State & Multi-Select")) { HelpMarker("Selections can be built under Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data."); - IMGUI_DEMO_MARKER("Widgets/Selection State/Single Selection"); - if (ImGui::TreeNode("Single Selection")) + IMGUI_DEMO_MARKER("Widgets/Selection State/Single-Select"); + if (ImGui::TreeNode("Single-Select")) { static int selected = -1; for (int n = 0; n < 5; n++) @@ -2901,8 +2891,9 @@ static void ShowDemoWindowMultiSelect() } // Demonstrate implementation a most-basic form of multi-selection manually - IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (simplfied, manual)"); - if (ImGui::TreeNode("Multiple Selection (simplified, manual)")) + // This doesn't support the SHIFT modifier which requires BeginMultiSelect()! + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (manual/simplified, without BeginMultiSelect)"); + if (ImGui::TreeNode("Multi-Select (manual/simplified, without BeginMultiSelect)")) { HelpMarker("Hold CTRL and click to select multiple items."); static bool selection[5] = { false, false, false, false, false }; @@ -2929,9 +2920,8 @@ static void ShowDemoWindowMultiSelect() // Demonstrate holding/updating multi-selection data using the BeginMultiSelect/EndMultiSelect API. // SHIFT+Click w/ CTRL and other standard features are supported. - IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full)"); - //ImGui::SetNextItemOpen(true, ImGuiCond_Once); - if (ImGui::TreeNode("Multiple Selection (full)")) + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); + if (ImGui::TreeNode("Multi-Select")) { static ExampleSelection selection; @@ -2956,7 +2946,7 @@ static void ShowDemoWindowMultiSelect() { char label[64]; sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); - bool item_is_selected = selection.GetSelected(n); + bool item_is_selected = selection.Contains(n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); } @@ -2978,8 +2968,8 @@ static void ShowDemoWindowMultiSelect() // - (3) BeginXXXX process // - (4) Focus process // - (5) EndXXXX process - IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, with deletion)"); - if (ImGui::TreeNode("Multiple Selection (full, with deletion)")) + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with deletion)"); + if (ImGui::TreeNode("Multi-Select (with deletion)")) { // Intentionally separating items data from selection data! // But you may decide to store selection data inside your item (aka intrusive storage). @@ -2999,7 +2989,7 @@ static void ShowDemoWindowMultiSelect() items.push_back(items_next_id++); if (ImGui::SmallButton("Add 20 items")) { for (int n = 0; n < 20; n++) { items.push_back(items_next_id++); } } ImGui::SameLine(); - if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.SetSelected(items.Size - 1, false); items.pop_back(); } } // This is to test + if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.RemoveItem(items.Size - 1); items.pop_back(); } } // This is to test // (1) Extra to support deletion: Submit scrolling range to avoid glitches on deletion const float items_height = ImGui::GetTextLineHeightWithSpacing(); @@ -3025,11 +3015,9 @@ static void ShowDemoWindowMultiSelect() char label[64]; sprintf(label, "Object %05d: %s", item_id, random_names[item_id % IM_ARRAYSIZE(random_names)]); - bool item_is_selected = selection.GetSelected(n); + bool item_is_selected = selection.Contains(n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); - if (ImGui::IsItemToggledSelection()) - selection.SetSelected(n, !item_is_selected); if (next_focus_item_idx == n) ImGui::SetKeyboardFocusHere(-1); } @@ -3046,8 +3034,8 @@ static void ShowDemoWindowMultiSelect() } // Demonstrate individual selection scopes in same window - IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, multiple scopes)"); - if (ImGui::TreeNode("Multiple Selection (full, multiple scopes)")) + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (multiple scopes)"); + if (ImGui::TreeNode("Multi-Select (multiple scopes)")) { const int SCOPES_COUNT = 3; const int ITEMS_COUNT = 8; // Per scope @@ -3068,7 +3056,7 @@ static void ShowDemoWindowMultiSelect() { char label[64]; sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); - bool item_is_selected = selection->GetSelected(n); + bool item_is_selected = selection->Contains(n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); } @@ -3087,9 +3075,9 @@ static void ShowDemoWindowMultiSelect() // - Showcase basic drag and drop. // - Showcase TreeNode variant (note that tree node don't expand in the demo: supporting expanding tree nodes + clipping a separate thing). // - Showcase using inside a table. - IMGUI_DEMO_MARKER("Widgets/Selection State/Multiple Selection (full, advanced)"); + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); - if (ImGui::TreeNode("Multiple Selection (full, advanced)")) + if (ImGui::TreeNode("Multi-Select (advanced)")) { // Options enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; @@ -3137,7 +3125,7 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); if (want_delete) - selection.ApplyDeletionPreLoop(ms_io, items); + ms_io->RequestFocusItem = selection.ApplyDeletionPreLoop(ms_io, items); const int next_focus_item_idx = (int)ms_io->RequestFocusItem; if (show_in_table) @@ -3192,7 +3180,7 @@ static void ShowDemoWindowMultiSelect() ImGui::SameLine(); } - bool item_is_selected = selection.GetSelected(n); + bool item_is_selected = selection.Contains(n); ImGui::SetNextItemSelectionUserData(n); if (widget_type == WidgetType_Selectable) { From 6ddc5f38afa990875a38b9e8b644f4770173da7e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Aug 2023 19:47:24 +0200 Subject: [PATCH 0146/2359] MultiSelect: Demo: added simpler demo using Clipper. Clarify RangeSrcPassedBy doc. --- imgui.h | 12 +++++++----- imgui_demo.cpp | 48 +++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index 730a53e2b..ea47d0fd8 100644 --- a/imgui.h +++ b/imgui.h @@ -2774,11 +2774,13 @@ enum ImGuiMultiSelectFlags_ // Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (2) [If using clipper] Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 6. -// LOOP - (3) [If using clipper] Set RangeSrcPassedBy=true if the RangeSrcItem item is part of the items clipped before the first submitted/visible item. +// LOOP - (3) [If using clipper] Set RangeSrcPassedBy=true if the RangeSrcItem item was already passed by. // This is because for range-selection we need to know if we are currently "inside" or "outside" the range. -// - If you are using integer indices in ImGuiSelectionUserData, this is easy to compute: if (clipper.DisplayStart > data->RangeSrcItem) { data->RangeSrcPassedBy = true; } -// - If you are using pointers in ImGuiSelectionUserData, you may need additional processing in each clipper step to tell if current DisplayStart comes after RangeSrcItem.. -// - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. (optionally call IsItemToggledSelection() if you need that info immediately for displaying your item, before EndMultiSelect()) +// - If you are using integer indices in ImGuiSelectionUserData, this is easy to compute: +// if (clipper.DisplayStart > data->RangeSrcItem) { data->RangeSrcPassedBy = true; } +// - If you are using pointers in ImGuiSelectionUserData, you may need additional processing, e.g. find the index of RangeSrcItem before applying the above operation. +// - This also needs to be done at the end of the clipper loop, otherwise we can't tell if the item still exist. +// - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 2. // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. @@ -2801,7 +2803,7 @@ struct ImGuiMultiSelectIO ImGuiSelectionUserData RangeFirstItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) ImGuiSelectionUserData RangeLastItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) bool RangeSelected; // / / ms:w, app:r // End: parameter for RequestSetRange request. true = Select Range, false = Unselect Range. - bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was part of the clipped set before submitting the visible items. Ignore if not clipping. + bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was passed by. Ignore if not clipping. bool RangeSrcReset; // app:w / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). ImGuiSelectionUserData NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3cd8bf6ad..3cf95e646 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2911,7 +2911,7 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } - const char* random_names[] = + static const char* random_names[] = { "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", @@ -2935,7 +2935,7 @@ static void ShowDemoWindowMultiSelect() // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling region). const int ITEMS_COUNT = 50; - ImGui::Text("Selection size: %d", selection.GetSize()); + ImGui::Text("Selection: %d/%d", selection.GetSize(), ITEMS_COUNT); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; @@ -2951,7 +2951,49 @@ static void ShowDemoWindowMultiSelect() ImGui::Selectable(label, item_is_selected); } - // Apply multi-select requests + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io, ITEMS_COUNT); + + ImGui::EndListBox(); + } + ImGui::TreePop(); + } + + // Demonstrate using the clipper with BeginMultiSelect()/EndMultiSelect() + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with clipper)"); + if (ImGui::TreeNode("Multi-Select (with clipper)")) + { + static ExampleSelection selection; + + ImGui::Text("Added features:"); + ImGui::BulletText("Using ImGuiListClipper."); + + const int ITEMS_COUNT = 10000; + ImGui::Text("Selection: %d/%d", selection.GetSize(), ITEMS_COUNT); + if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + { + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + selection.ApplyRequests(ms_io, ITEMS_COUNT); + + ImGuiListClipper clipper; + clipper.Begin(ITEMS_COUNT); + while (clipper.Step()) + { + if (!ms_io->RangeSrcPassedBy && clipper.DisplayStart > ms_io->RangeSrcItem) + ms_io->RangeSrcPassedBy = true; + for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) + { + char label[64]; + sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); + bool item_is_selected = selection.Contains(n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Selectable(label, item_is_selected); + } + } + if (!ms_io->RangeSrcPassedBy && ITEMS_COUNT > ms_io->RangeSrcItem) + ms_io->RangeSrcPassedBy = true; + ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, ITEMS_COUNT); From 8fe6b3195282b6247f53f75c0cfb5907448b05ec Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Aug 2023 20:45:02 +0200 Subject: [PATCH 0147/2359] MultiSelect: (Breaking) Removed RangeSrcPassedBy in favor of favoring user to call IncludeByIndex(RangeSrcItem) which is easier/simpler to honor. Especially as recent changes made it required to also update RangeSrcPassedBy after last clipper Step. Should now be simpler. --- imgui.h | 14 ++++---------- imgui_demo.cpp | 21 +++++---------------- imgui_internal.h | 3 ++- imgui_widgets.cpp | 10 +++++----- 4 files changed, 16 insertions(+), 32 deletions(-) diff --git a/imgui.h b/imgui.h index ea47d0fd8..efc7c6888 100644 --- a/imgui.h +++ b/imgui.h @@ -2774,13 +2774,8 @@ enum ImGuiMultiSelectFlags_ // Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (2) [If using clipper] Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 6. -// LOOP - (3) [If using clipper] Set RangeSrcPassedBy=true if the RangeSrcItem item was already passed by. -// This is because for range-selection we need to know if we are currently "inside" or "outside" the range. -// - If you are using integer indices in ImGuiSelectionUserData, this is easy to compute: -// if (clipper.DisplayStart > data->RangeSrcItem) { data->RangeSrcPassedBy = true; } -// - If you are using pointers in ImGuiSelectionUserData, you may need additional processing, e.g. find the index of RangeSrcItem before applying the above operation. -// - This also needs to be done at the end of the clipper loop, otherwise we can't tell if the item still exist. -// - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. +// - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeIndex(). If already using indices in ImGuiSelectionUserData, it is as simple as clipper.IncludeIndex((int)ms_io->RangeSrcItem); +// LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 2. // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. @@ -2799,12 +2794,11 @@ struct ImGuiMultiSelectIO bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeFirstItem..RangeLastItem] items, based on RangeSelected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. ImGuiSelectionUserData RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implementing a deletion idiom (see demo). // STATE/ARGUMENTS -------------------------// BEGIN / LOOP / END - ImGuiSelectionUserData RangeSrcItem; // ms:w / app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point). Read during loop in order for user code to set RangeSrcPassedBy. + ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be cliped! ImGuiSelectionUserData RangeFirstItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) ImGuiSelectionUserData RangeLastItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) bool RangeSelected; // / / ms:w, app:r // End: parameter for RequestSetRange request. true = Select Range, false = Unselect Range. - bool RangeSrcPassedBy; // / ms:rw app:w / ms:r // (If using clipper) Need to be set by app/user if RangeSrcItem was passed by. Ignore if not clipping. - bool RangeSrcReset; // app:w / app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). + bool RangeSrcReset; // app:w / / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). ImGuiSelectionUserData NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3cf95e646..5b889a271 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2978,10 +2978,10 @@ static void ShowDemoWindowMultiSelect() ImGuiListClipper clipper; clipper.Begin(ITEMS_COUNT); + if (ms_io->RangeSrcItem > 0) + clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. while (clipper.Step()) { - if (!ms_io->RangeSrcPassedBy && clipper.DisplayStart > ms_io->RangeSrcItem) - ms_io->RangeSrcPassedBy = true; for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) { char label[64]; @@ -2991,8 +2991,6 @@ static void ShowDemoWindowMultiSelect() ImGui::Selectable(label, item_is_selected); } } - if (!ms_io->RangeSrcPassedBy && ITEMS_COUNT > ms_io->RangeSrcItem) - ms_io->RangeSrcPassedBy = true; ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, ITEMS_COUNT); @@ -3185,16 +3183,13 @@ static void ShowDemoWindowMultiSelect() { clipper.Begin(items.Size); if (next_focus_item_idx != -1) - clipper.IncludeItemByIndex(next_focus_item_idx); // Ensure item to focus is not clipped + clipper.IncludeItemByIndex(next_focus_item_idx); // Ensure focused item is not clipped + if (ms_io->RangeSrcItem > 0) + clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. } while (!use_clipper || clipper.Step()) { - // IF clipping is used: you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. - // If you submit all items this is unnecessary as this is one by SetNextItemSelectionUserData() - if (use_clipper && !ms_io->RangeSrcPassedBy && clipper.DisplayStart > ms_io->RangeSrcItem) - ms_io->RangeSrcPassedBy = true; - const int item_begin = use_clipper ? clipper.DisplayStart : 0; const int item_end = use_clipper ? clipper.DisplayEnd : items.Size; for (int n = item_begin; n < item_end; n++) @@ -3281,12 +3276,6 @@ static void ShowDemoWindowMultiSelect() break; } - // If clipping is used: you need to set 'RangeSrcPassedBy = true' if RangeSrc was passed over. - // If you submit all items this is unnecessary as this is one by SetNextItemSelectionUserData() - // Here we essentially notify before EndMultiSelect() that RangeSrc is still present in our data set. - if (use_clipper && !ms_io->RangeSrcPassedBy && items.Size > ms_io->RangeSrcItem) - ms_io->RangeSrcPassedBy = true; - if (show_in_table) { ImGui::EndTable(); diff --git a/imgui_internal.h b/imgui_internal.h index 3bf729e3b..2e2999a92 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1725,7 +1725,8 @@ struct IMGUI_API ImGuiMultiSelectTempData bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. bool NavIdPassedBy; - bool RangeDstPassedBy; // Set by the the item that matches NavJustMovedToId when IsSetRange is set. + bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. + bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectTempData() { Clear(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 178f0991f..1930fd790 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7213,7 +7213,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->IsFocused) { - if (ms->BeginIO.RangeSrcReset || (ms->BeginIO.RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) + if (ms->BeginIO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. ms->Storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; @@ -7262,7 +7262,7 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect; if (ms->BeginIO.RangeSrcItem == selection_user_data) - ms->BeginIO.RangeSrcPassedBy = true; + ms->RangeSrcPassedBy = true; } else { @@ -7291,7 +7291,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) selected = true; // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) - // For this to work, IF the user is clipping items, they need to set RangeSrcPassedBy = true to notify the system. + // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function) if (ms->IsSetRange) { IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0); @@ -7306,7 +7306,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) } } const bool is_range_src = storage->RangeSrcItem == item_data; - if (is_range_src || is_range_dst || ms->BeginIO.RangeSrcPassedBy != ms->RangeDstPassedBy) + if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy) { IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1); selected = (storage->RangeSelected != 0); @@ -7406,7 +7406,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); ms->EndIO.RangeSrcItem = (storage->RangeSrcItem != ImGuiSelectionUserData_Invalid) ? storage->RangeSrcItem : item_data; ms->EndIO.RangeSelected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; - range_direction = ms->BeginIO.RangeSrcPassedBy ? +1 : -1; + range_direction = ms->RangeSrcPassedBy ? +1 : -1; } else { From 8c1f659b3dc709ba1838f3aed99e5db27c001bbb Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Aug 2023 15:53:20 +0200 Subject: [PATCH 0148/2359] MultiSelect: Demo: rework ExampleSelection with an ExampleSelectionAdapter layer, allowing to share more code accross examples using different storage systems. Not ideal way to showcase this demo but this is really more flexible. --- imgui_demo.cpp | 101 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 74 insertions(+), 27 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5b889a271..f7caa12ef 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2761,19 +2761,41 @@ static void ShowDemoWindowWidgets() } } -// [Advanced] Helper class to simulate storage of a multi-selection state, used by the BeginMultiSelect() demos. -// We use ImGuiStorage (simple key->value storage) to avoid external dependencies but it's probably not optimal. +// We use a little extra indirection layer here in order to use and demonstrate different ways to +// - identify items in the multi-selection system (using index? using identifiers? using pointers?) +// - store our persistent selection data (using index? using identifiers? using pointers?) +// Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. +// WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ExampleSelectionAdapter' INDIRECTION LOGIC. +// In theory we could add a IndexToUserData() function which would be used when calling SetNextItemSelectionUserData(), but omitting it makes things clearer. +struct ExampleSelectionAdapter +{ + void* Data = NULL; + int (*UserDataToIndex)(ExampleSelectionAdapter* self, ImGuiSelectionUserData item_data); // Function to convert item ImGuiSelectionUserData to item index + ImGuiID (*IndexToStorage)(ExampleSelectionAdapter* self, int idx); // Function to convert item index to data stored in persistent selection + + ExampleSelectionAdapter() { SetupForDirectIndexes(); } + + // Example for the simplest case: UserData==Index==SelectionStorage (this adapter doesn't even need to use the item data field) + void SetupForDirectIndexes() + { + UserDataToIndex = [](ExampleSelectionAdapter*, ImGuiSelectionUserData item_data) { return (int)item_data; }; // No transform: Pass indices to SetNextItemSelectionUserData() + IndexToStorage = [](ExampleSelectionAdapter*, int idx) { return (ImGuiID)idx; }; // No transform: Store indices inside persistent selection storage + } +}; + +// [Advanced] Helper class to store multi-selection state, used by the BeginMultiSelect() demos. +// Provide an abstraction layer for the purpose of the demo showcasing different forms of underlying selection data. // To store a single-selection: // - You only need a single variable and don't need any of this! // To store a multi-selection, in your real application you could: -// - Use external storage: e.g. unordered_set/set/hash/map/interval trees (storing indices, objects id, etc.) -// are generally appropriate. Even a large array of bool might work for you... This is what we are doing here. -// - Use intrusively stored selection (e.g. 'bool IsSelected' inside your object). -// - This is simple, but it means you cannot have multiple simultaneous views over your objects. -// - This is what many of the simpler demos in other sections of this file are using (so they are not using this class). -// - Some of our features requires you to provide the selection size, which with this specific strategy require additional work: +// - A) Use external storage: e.g. std::set, std::set, std::vector, interval trees, etc. +// are generally appropriate. Even a large array of bool might work for you... +// This code here use ImGuiStorage (a simple key->value storage) as a std::set replacement to avoid external dependencies. +// - B) Or use intrusively stored selection (e.g. 'bool IsSelected' inside your object). +// - It is simple, but it means you cannot have multiple simultaneous views over your objects. +// - Some of our features requires you to provide the selection _size_, which with this specific strategy require additional work: // either you maintain it (which requires storage outside of objects) either you recompute (which may be costly for large sets). -// - So I would suggest that using intrusive selection for multi-select is not the most adequate. +// - So we suggest using intrusive selection for multi-select is not really adequate. struct ExampleSelection { // Data @@ -2784,6 +2806,7 @@ struct ExampleSelection // Functions ExampleSelection() { Clear(); } void Clear() { Storage.Clear(); Size = 0; QueueDeletion = false; } + void Swap(ExampleSelection& rhs) { Storage.Data.swap(rhs.Storage.Data); } bool Contains(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } void AddItem(int n) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int != 0) return; *p_int = 1; Size++; } void RemoveItem(int n) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == 0) return; *p_int = 0; Size--; } @@ -2796,15 +2819,33 @@ struct ExampleSelection // - Honoring RequestSetRange requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. // - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection. // - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform - // a lookup and have some way to iterate between two values. - // - A full-featured application is likely to allow search/filtering which is likely to lead to using indices and - // constructing a view index <> object id/ptr data structure. (FIXME-MULTISELECT: Would be worth providing a demo of doing this). - // - (Our implementation is slightly inefficient because it doesn't take advantage of the fat that ImguiStorage stores sorted key) - void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) + // a lookup in order to have some way to iterate/interpolate between two items. + // - A full-featured application is likely to allow search/filtering which is likely to lead to using indices + // and constructing a view index <> object id/ptr data structure anyway. + // WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ExampleSelectionAdapter' INDIRECTION LOGIC. + // Notice that with the simplest adapter (using indices everywhere), all functions return their parameters. + // The most simple implementation (using indices everywhere) would look like: + // if (ms_io->RequestClear) { Clear(); } + // if (ms_io->RequestSelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } + // if (ms_io->RequestSetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } + void ApplyRequests(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, int items_count) { - if (ms_io->RequestClear) { Clear(); } - if (ms_io->RequestSelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } - if (ms_io->RequestSetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } + IM_ASSERT(adapter->UserDataToIndex != NULL && adapter->IndexToStorage != NULL); + + if (ms_io->RequestClear || ms_io->RequestSelectAll) + Clear(); + + if (ms_io->RequestSelectAll) + for (int idx = 0; idx < items_count; idx++) + AddItem(adapter->IndexToStorage(adapter, idx)); + + if (ms_io->RequestSetRange) + { + int first_item_idx = adapter->UserDataToIndex(adapter, ms_io->RangeFirstItem); + int last_item_idx = adapter->UserDataToIndex(adapter, ms_io->RangeLastItem); + for (int idx = first_item_idx; idx <= last_item_idx; idx++) + UpdateItem(adapter->IndexToStorage(adapter, idx), ms_io->RangeSelected); + } } // Call after BeginMultiSelect(). @@ -2924,6 +2965,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::TreeNode("Multi-Select")) { static ExampleSelection selection; + ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Tips: Use 'Debug Log->Selection' to see selection requests as they happen."); @@ -2940,7 +2982,7 @@ static void ShowDemoWindowMultiSelect() { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + selection.ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) { @@ -2952,7 +2994,7 @@ static void ShowDemoWindowMultiSelect() } ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + selection.ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); ImGui::EndListBox(); } @@ -2964,6 +3006,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::TreeNode("Multi-Select (with clipper)")) { static ExampleSelection selection; + ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Added features:"); ImGui::BulletText("Using ImGuiListClipper."); @@ -2974,7 +3017,7 @@ static void ShowDemoWindowMultiSelect() { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + selection.ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); ImGuiListClipper clipper; clipper.Begin(ITEMS_COUNT); @@ -2993,7 +3036,7 @@ static void ShowDemoWindowMultiSelect() } ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + selection.ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); ImGui::EndListBox(); } @@ -3015,6 +3058,8 @@ static void ShowDemoWindowMultiSelect() // But you may decide to store selection data inside your item (aka intrusive storage). static ImVector items; static ExampleSelection selection; + ExampleSelectionAdapter selection_adapter; + selection_adapter.SetupForDirectIndexes(); // Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Adding features:"); ImGui::BulletText("Dynamic list with Delete key support."); @@ -3039,7 +3084,7 @@ static void ShowDemoWindowMultiSelect() { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection.ApplyRequests(ms_io, items.Size); + selection.ApplyRequests(ms_io, &selection_adapter, items.Size); // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. @@ -3064,7 +3109,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, items.Size); + selection.ApplyRequests(ms_io, &selection_adapter, items.Size); if (want_delete) selection.ApplyDeletionPostLoop(ms_io, items); @@ -3080,6 +3125,7 @@ static void ShowDemoWindowMultiSelect() const int SCOPES_COUNT = 3; const int ITEMS_COUNT = 8; // Per scope static ExampleSelection selections_data[SCOPES_COUNT]; + ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++) { @@ -3090,7 +3136,7 @@ static void ShowDemoWindowMultiSelect() ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; // | ImGuiMultiSelectFlags_ClearOnClickRectVoid ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection->ApplyRequests(ms_io, ITEMS_COUNT); + selection->ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) { @@ -3103,7 +3149,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection->ApplyRequests(ms_io, ITEMS_COUNT); + selection->ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); ImGui::PopID(); } ImGui::TreePop(); @@ -3147,6 +3193,7 @@ static void ShowDemoWindowMultiSelect() static int items_next_id = 0; if (items_next_id == 0) { for (int n = 0; n < 1000; n++) { items.push_back(items_next_id++); } } static ExampleSelection selection; + ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); @@ -3159,7 +3206,7 @@ static void ShowDemoWindowMultiSelect() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection.ApplyRequests(ms_io, items.Size); + selection.ApplyRequests(ms_io, &selection_adapter, items.Size); // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. @@ -3285,7 +3332,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, items.Size); + selection.ApplyRequests(ms_io, &selection_adapter, items.Size); if (want_delete) selection.ApplyDeletionPostLoop(ms_io, items); From 530155d85aaf68f06b97dce5ae5b655e06bc970c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 1 Sep 2023 16:09:41 +0200 Subject: [PATCH 0149/2359] MultiSelect: Demo: Remove UserDataToIndex from ExampleSelectionAdapter. Seems to make a better demo this way. --- imgui_demo.cpp | 35 ++++++++++++++++------------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f7caa12ef..90cb7e993 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2761,26 +2761,27 @@ static void ShowDemoWindowWidgets() } } -// We use a little extra indirection layer here in order to use and demonstrate different ways to -// - identify items in the multi-selection system (using index? using identifiers? using pointers?) -// - store our persistent selection data (using index? using identifiers? using pointers?) +// Our multi-selection system doesn't make assumption about: +// - how you want to identify items in multi-selection API? Indices(*) / Custom Identifiers / Pointers ? +// - how you want to store persistent selection data? Indices / Custom Identifiers(*) / Pointers ? +// (*) This is the suggested solution: pass indices to API (because easy to iterate/interpolate) + persist your custom identifiers inside selection data. +// In this demo we: +// - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) +// - use a little extra indirection layer in order to abstract how persistent selection data is derived from an index. +// - in some cases we use Index as custom identifier, in some cases we read from some custom item data structure. // Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. // WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ExampleSelectionAdapter' INDIRECTION LOGIC. -// In theory we could add a IndexToUserData() function which would be used when calling SetNextItemSelectionUserData(), but omitting it makes things clearer. +// In theory, for maximum abstraction, this class could contains IndexToUserData() and UserDataToIndex() functions, +// but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that for clarify. struct ExampleSelectionAdapter { void* Data = NULL; - int (*UserDataToIndex)(ExampleSelectionAdapter* self, ImGuiSelectionUserData item_data); // Function to convert item ImGuiSelectionUserData to item index - ImGuiID (*IndexToStorage)(ExampleSelectionAdapter* self, int idx); // Function to convert item index to data stored in persistent selection + ImGuiID (*IndexToStorage)(ExampleSelectionAdapter* self, int idx); // Function to convert item index to data stored in persistent selection - ExampleSelectionAdapter() { SetupForDirectIndexes(); } + ExampleSelectionAdapter() { SetupForDirectIndexes(); } - // Example for the simplest case: UserData==Index==SelectionStorage (this adapter doesn't even need to use the item data field) - void SetupForDirectIndexes() - { - UserDataToIndex = [](ExampleSelectionAdapter*, ImGuiSelectionUserData item_data) { return (int)item_data; }; // No transform: Pass indices to SetNextItemSelectionUserData() - IndexToStorage = [](ExampleSelectionAdapter*, int idx) { return (ImGuiID)idx; }; // No transform: Store indices inside persistent selection storage - } + // Example for the simplest case: Index==SelectionStorage (this adapter doesn't even need to use the item data field) + void SetupForDirectIndexes() { IndexToStorage = [](ExampleSelectionAdapter*, int idx) { return (ImGuiID)idx; }; } }; // [Advanced] Helper class to store multi-selection state, used by the BeginMultiSelect() demos. @@ -2830,7 +2831,7 @@ struct ExampleSelection // if (ms_io->RequestSetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } void ApplyRequests(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, int items_count) { - IM_ASSERT(adapter->UserDataToIndex != NULL && adapter->IndexToStorage != NULL); + IM_ASSERT(adapter->IndexToStorage != NULL); if (ms_io->RequestClear || ms_io->RequestSelectAll) Clear(); @@ -2840,12 +2841,8 @@ struct ExampleSelection AddItem(adapter->IndexToStorage(adapter, idx)); if (ms_io->RequestSetRange) - { - int first_item_idx = adapter->UserDataToIndex(adapter, ms_io->RangeFirstItem); - int last_item_idx = adapter->UserDataToIndex(adapter, ms_io->RangeLastItem); - for (int idx = first_item_idx; idx <= last_item_idx; idx++) + for (int idx = (int)ms_io->RangeFirstItem; idx <= (int)ms_io->RangeLastItem; idx++) UpdateItem(adapter->IndexToStorage(adapter, idx), ms_io->RangeSelected); - } } // Call after BeginMultiSelect(). From fa516c3d76503836472a9f3902ffa7f4ef0b409f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 28 Aug 2023 17:36:59 +0200 Subject: [PATCH 0150/2359] MultiSelect: Demo: Make ExampleSelection use ImGuiID. More self-explanatory. --- imgui_demo.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 90cb7e993..2351a177e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2801,17 +2801,17 @@ struct ExampleSelection { // Data ImGuiStorage Storage; // Selection set - int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). // FIXME-MULTISELECT: Imply more difficult to track with intrusive selection schemes? + int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). bool QueueDeletion; // Request deleting selected items // Functions ExampleSelection() { Clear(); } void Clear() { Storage.Clear(); Size = 0; QueueDeletion = false; } void Swap(ExampleSelection& rhs) { Storage.Data.swap(rhs.Storage.Data); } - bool Contains(int n) const { return Storage.GetInt((ImGuiID)n, 0) != 0; } - void AddItem(int n) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int != 0) return; *p_int = 1; Size++; } - void RemoveItem(int n) { int* p_int = Storage.GetIntRef((ImGuiID)n, 0); if (*p_int == 0) return; *p_int = 0; Size--; } - void UpdateItem(int n, bool v) { if (v) AddItem(n); else RemoveItem(n); } + bool Contains(ImGuiID key) const { return Storage.GetInt(key, 0) != 0; } + void AddItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int != 0) return; *p_int = 1; Size++; } + void RemoveItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int == 0) return; *p_int = 0; Size--; } + void UpdateItem(ImGuiID key, bool v){ if (v) AddItem(key); else RemoveItem(key); } int GetSize() const { return Size; } void DebugTooltip() { if (ImGui::BeginTooltip()) { for (auto& pair : Storage.Data) if (pair.val_i) ImGui::Text("0x%03X (%d)", pair.key, pair.key); ImGui::EndTooltip(); } } @@ -2985,7 +2985,7 @@ static void ShowDemoWindowMultiSelect() { char label[64]; sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); - bool item_is_selected = selection.Contains(n); + bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); } @@ -3026,7 +3026,7 @@ static void ShowDemoWindowMultiSelect() { char label[64]; sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); - bool item_is_selected = selection.Contains(n); + bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); } @@ -3071,7 +3071,7 @@ static void ShowDemoWindowMultiSelect() items.push_back(items_next_id++); if (ImGui::SmallButton("Add 20 items")) { for (int n = 0; n < 20; n++) { items.push_back(items_next_id++); } } ImGui::SameLine(); - if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.RemoveItem(items.Size - 1); items.pop_back(); } } // This is to test + if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.RemoveItem((ImGuiID)(items.Size - 1)); items.pop_back(); } } // This is to test // (1) Extra to support deletion: Submit scrolling range to avoid glitches on deletion const float items_height = ImGui::GetTextLineHeightWithSpacing(); @@ -3097,7 +3097,7 @@ static void ShowDemoWindowMultiSelect() char label[64]; sprintf(label, "Object %05d: %s", item_id, random_names[item_id % IM_ARRAYSIZE(random_names)]); - bool item_is_selected = selection.Contains(n); + bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); if (next_focus_item_idx == n) @@ -3139,7 +3139,7 @@ static void ShowDemoWindowMultiSelect() { char label[64]; sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); - bool item_is_selected = selection->Contains(n); + bool item_is_selected = selection->Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); } @@ -3261,7 +3261,7 @@ static void ShowDemoWindowMultiSelect() ImGui::SameLine(); } - bool item_is_selected = selection.Contains(n); + bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); if (widget_type == WidgetType_Selectable) { From e1d21092087b9aba367cb29bdd59202a1618bc2c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Aug 2023 16:48:04 +0200 Subject: [PATCH 0151/2359] MultiSelect: Demo: Deletion: Rework ApplyDeletionPreLoop to use adapter + fix PostLoop not using right value of RequestFocusItem. Recovery made it transparent visually but user side selection would be empty for a frame before recovery. --- imgui.h | 3 +-- imgui_demo.cpp | 64 +++++++++++++++++++++++--------------------------- 2 files changed, 31 insertions(+), 36 deletions(-) diff --git a/imgui.h b/imgui.h index efc7c6888..5add92931 100644 --- a/imgui.h +++ b/imgui.h @@ -2792,7 +2792,6 @@ struct ImGuiMultiSelectIO bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeFirstItem..RangeLastItem] items, based on RangeSelected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. - ImGuiSelectionUserData RequestFocusItem; // app:w / app:r / app:r // (If using deletion) 4. Request user to focus item. This is actually only manipulated in user-space, but we provide storage to facilitate implementing a deletion idiom (see demo). // STATE/ARGUMENTS -------------------------// BEGIN / LOOP / END ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be cliped! ImGuiSelectionUserData RangeFirstItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) @@ -2803,7 +2802,7 @@ struct ImGuiMultiSelectIO ImGuiSelectionUserData NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). ImGuiMultiSelectIO() { Clear(); } - void Clear() { memset(this, 0, sizeof(*this)); RequestFocusItem = NavIdItem = RangeSrcItem = RangeFirstItem = RangeLastItem = (ImGuiSelectionUserData)-1; } + void Clear() { memset(this, 0, sizeof(*this)); NavIdItem = RangeSrcItem = RangeFirstItem = RangeLastItem = (ImGuiSelectionUserData)-1; } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2351a177e..e70b80c60 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2845,65 +2845,61 @@ struct ExampleSelection UpdateItem(adapter->IndexToStorage(adapter, idx), ms_io->RangeSelected); } - // Call after BeginMultiSelect(). - // - Calculate and set ms_io->RequestFocusItem, which we will focus during the loop. + // Find which item should be focused after deletion. // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. - // - Return value is stored into 'ms_io->RequestFocusItem' which is provided as a convenience for this idiom (but not used by core imgui) - // - Important: This only works if the item ID are stable: aka not depend on their index, but on e.g. item id/ptr. - template - int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, ImVector& items) + // - Important: Deletion only works if the underlying imgui id for your items are stable: aka not depend on their index, but on e.g. item id/ptr. + int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, int items_count, void* items = NULL) { QueueDeletion = false; - // If current item is not selected. - if (ms_io->NavIdSelected == false) // Here 'NavIdSelected' should be == to 'GetSelected(ms_io->NavIdData)' + // If current item is not selected: land on same item. + if (ms_io->NavIdSelected == false) // At this point 'ms_io->NavIdSelected == Contains(ms_io->NavIdItem)' should be true. { - ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even without the !NavIdSelected test but it would take an extra frame to recover RangeSrc when deleting a selected item. - return (int)ms_io->NavIdItem; // Request to land on same item after deletion. + int idx = adapter->UserDataToIndex(items, ms_io->NavIdItem); + ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even without the NavIdSelected==false test but it would take an extra frame to recover RangeSrc when deleting a selected item. + return idx; // Request to land on same item after deletion. } // If current item is selected: land on first unselected item after RangeSrc. - for (int n = (int)ms_io->RangeSrcItem + 1; n < items.Size; n++) - if (!Contains(n)) - return n; + int src_idx = adapter->UserDataToIndex(items, ms_io->RangeSrcItem); + for (int idx = src_idx + 1; idx < items_count; idx++) + if (!Contains(adapter->IndexToStorage(items, idx))) + return idx; // If current item is selected: otherwise return last unselected item. - for (int n = IM_MIN((int)ms_io->RangeSrcItem, items.Size) - 1; n >= 0; n--) - if (!Contains(n)) - return n; + for (int idx = IM_MIN(src_idx, items_count) - 1; idx >= 0; idx--) + if (!Contains(adapter->IndexToStorage(items, idx))) + return idx; return -1; } // Call after EndMultiSelect() - // Apply deletion request + return index of item to refocus, if any. + // Apply deletion request on items + apply deletion request on selection data template - void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ImVector& items) + void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ImVector& items, int next_focus_idx_in_old_list) { // This does two things: // - (1) Update Items List (delete items from it) - // - (2) Convert the new focus index from old selection index (before deletion) to new selection index (after selection), and select it. + // - (2) Convert from old selection index (before deletion) to new selection index (after selection), and select it. // If NavId was not selected, next_focus_idx_in_old_selection == -1 and we stay on same item. // You are expected to handle both of those in user-space because Dear ImGui rightfully doesn't own items data nor selection data. - // This particular ExampleSelection case is designed to showcase maintaining selection-state separated from items-data. - IM_UNUSED(ms_io); ImVector new_items; new_items.reserve(items.Size - Size); - int next_focus_idx_in_old_selection = (int)ms_io->RequestFocusItem; - int next_focus_idx_in_new_selection = -1; + int next_focus_idx_in_new_list = -1; for (int n = 0; n < items.Size; n++) { if (!Contains(n)) new_items.push_back(items[n]); - if (next_focus_idx_in_old_selection == n) - next_focus_idx_in_new_selection = new_items.Size - 1; + if (next_focus_idx_in_old_list == n) + next_focus_idx_in_new_list = new_items.Size - 1; } items.swap(new_items); // Update selection Clear(); - if (next_focus_idx_in_new_selection != -1 && ms_io->NavIdSelected) - AddItem(next_focus_idx_in_new_selection); + if (next_focus_idx_in_new_list != -1 && ms_io->NavIdSelected) + AddItem(next_focus_idx_in_new_list); } }; @@ -3086,10 +3082,10 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. // FIXME-MULTISELECT: If pressing Delete + another key we have ambiguous behavior. - const bool want_delete = (selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); + const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); + int next_focus_item_idx = -1; if (want_delete) - ms_io->RequestFocusItem = selection.ApplyDeletionPreLoop(ms_io, items); - const int next_focus_item_idx = (int)ms_io->RequestFocusItem; + next_focus_item_idx = selection.ApplyDeletionPreLoop(ms_io, &selection_adapter, items.Size); for (int n = 0; n < items.Size; n++) { @@ -3108,7 +3104,7 @@ static void ShowDemoWindowMultiSelect() ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, &selection_adapter, items.Size); if (want_delete) - selection.ApplyDeletionPostLoop(ms_io, items); + selection.ApplyDeletionPostLoop(ms_io, items, next_focus_item_idx); ImGui::EndListBox(); } @@ -3208,9 +3204,9 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); + int next_focus_item_idx = -1; if (want_delete) - ms_io->RequestFocusItem = selection.ApplyDeletionPreLoop(ms_io, items); - const int next_focus_item_idx = (int)ms_io->RequestFocusItem; + next_focus_item_idx = selection.ApplyDeletionPreLoop(ms_io, &selection_adapter, items.Size); if (show_in_table) { @@ -3331,7 +3327,7 @@ static void ShowDemoWindowMultiSelect() ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, &selection_adapter, items.Size); if (want_delete) - selection.ApplyDeletionPostLoop(ms_io, items); + selection.ApplyDeletionPostLoop(ms_io, items, next_focus_item_idx); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); From ba698df7bbda31bf56c151258649d277e348ced6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 28 Aug 2023 16:33:30 +0200 Subject: [PATCH 0152/2359] MultiSelect: Demo: Deletion: Various renames to clarify. Use adapter and item list in both ApplyDeletion functions. This also minify the patch for an alternative/wip attmept at redesgining pre/post deletion logic. But turns out current attempt may be easier to grasp. --- imgui_demo.cpp | 89 +++++++++++++++++++++++++------------------------- 1 file changed, 45 insertions(+), 44 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e70b80c60..3e91336dc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2845,61 +2845,63 @@ struct ExampleSelection UpdateItem(adapter->IndexToStorage(adapter, idx), ms_io->RangeSelected); } - // Find which item should be focused after deletion. + // Find which item should be Focused after deletion. + // We output an index in the before-deletion-items list, that user will call SetKeyboardFocusHere() on. + // The subsequent ApplyDeletionPostLoop() code will use it to apply Selection. // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. - // - Important: Deletion only works if the underlying imgui id for your items are stable: aka not depend on their index, but on e.g. item id/ptr. - int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, int items_count, void* items = NULL) + // - We don't actually manipulate the ImVector<> here, only in ApplyDeletionPostLoop(), but using similar API for consistency and flexibility. + // - Important: Deletion only works if the underlying ImGuiID for your items are stable: aka not depend on their index, but on e.g. item id/ptr. + // FIXME-MULTISELECT: Doesn't take account of the possibility focus target will be moved during deletion. Need refocus or offset. + template + int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, ImVector& items) { QueueDeletion = false; - // If current item is not selected: land on same item. - if (ms_io->NavIdSelected == false) // At this point 'ms_io->NavIdSelected == Contains(ms_io->NavIdItem)' should be true. + // If focused item is not selected... + const int focused_idx = adapter->UserDataToIndex(adapter, ms_io->NavIdItem); // Index of currently focused item + if (ms_io->NavIdSelected == false) // This is merely a shortcut, == Contains(adapter->IndexToStorage(items, focused_idx)) { - int idx = adapter->UserDataToIndex(items, ms_io->NavIdItem); - ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even without the NavIdSelected==false test but it would take an extra frame to recover RangeSrc when deleting a selected item. - return idx; // Request to land on same item after deletion. + ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even when NavIdSelected==true, but it would take an extra frame to recover RangeSrc when deleting a selected item. + return focused_idx; // Request to focus same item after deletion. } - // If current item is selected: land on first unselected item after RangeSrc. - int src_idx = adapter->UserDataToIndex(items, ms_io->RangeSrcItem); - for (int idx = src_idx + 1; idx < items_count; idx++) - if (!Contains(adapter->IndexToStorage(items, idx))) + // If focused item is selected: land on first unselected item after focused item. + for (int idx = focused_idx + 1; idx < items.Size; idx++) + if (!Contains(adapter->IndexToStorage(adapter, idx))) return idx; - // If current item is selected: otherwise return last unselected item. - for (int idx = IM_MIN(src_idx, items_count) - 1; idx >= 0; idx--) - if (!Contains(adapter->IndexToStorage(items, idx))) + // If focused item is selected: otherwise return last unselected item before focused item. + for (int idx = IM_MIN(focused_idx, items.Size) - 1; idx >= 0; idx--) + if (!Contains(adapter->IndexToStorage(adapter, idx))) return idx; return -1; } - // Call after EndMultiSelect() - // Apply deletion request on items + apply deletion request on selection data + // Rewrite item list (delete items) + update selection. + // - Call after EndMultiSelect() + // - We cannot provide this logic in core Dear ImGui because we don't have access to your items, nor to selection data. template - void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ImVector& items, int next_focus_idx_in_old_list) + void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, ImVector& items, int item_curr_idx_to_select) { - // This does two things: - // - (1) Update Items List (delete items from it) - // - (2) Convert from old selection index (before deletion) to new selection index (after selection), and select it. - // If NavId was not selected, next_focus_idx_in_old_selection == -1 and we stay on same item. - // You are expected to handle both of those in user-space because Dear ImGui rightfully doesn't own items data nor selection data. + // Rewrite item list (delete items) + convert old selection index (before deletion) to new selection index (after selection). + // If NavId was not part of selection, we will stay on same item. ImVector new_items; new_items.reserve(items.Size - Size); - int next_focus_idx_in_new_list = -1; - for (int n = 0; n < items.Size; n++) + int item_next_idx_to_select = -1; + for (int idx = 0; idx < items.Size; idx++) { - if (!Contains(n)) - new_items.push_back(items[n]); - if (next_focus_idx_in_old_list == n) - next_focus_idx_in_new_list = new_items.Size - 1; + if (!Contains(adapter->IndexToStorage(adapter, idx))) + new_items.push_back(items[idx]); + if (item_curr_idx_to_select == idx) + item_next_idx_to_select = new_items.Size - 1; } items.swap(new_items); // Update selection Clear(); - if (next_focus_idx_in_new_list != -1 && ms_io->NavIdSelected) - AddItem(next_focus_idx_in_new_list); + if (item_next_idx_to_select != -1 && ms_io->NavIdSelected) + AddItem(adapter->IndexToStorage(adapter, item_next_idx_to_select)); } }; @@ -3051,8 +3053,7 @@ static void ShowDemoWindowMultiSelect() // But you may decide to store selection data inside your item (aka intrusive storage). static ImVector items; static ExampleSelection selection; - ExampleSelectionAdapter selection_adapter; - selection_adapter.SetupForDirectIndexes(); // Pass index to SetNextItemSelectionUserData(), store index in Selection + ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Adding features:"); ImGui::BulletText("Dynamic list with Delete key support."); @@ -3083,9 +3084,9 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. // FIXME-MULTISELECT: If pressing Delete + another key we have ambiguous behavior. const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); - int next_focus_item_idx = -1; + int item_curr_idx_to_focus = -1; if (want_delete) - next_focus_item_idx = selection.ApplyDeletionPreLoop(ms_io, &selection_adapter, items.Size); + item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, &selection_adapter, items); for (int n = 0; n < items.Size; n++) { @@ -3096,7 +3097,7 @@ static void ShowDemoWindowMultiSelect() bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); - if (next_focus_item_idx == n) + if (item_curr_idx_to_focus == n) ImGui::SetKeyboardFocusHere(-1); } @@ -3104,7 +3105,7 @@ static void ShowDemoWindowMultiSelect() ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, &selection_adapter, items.Size); if (want_delete) - selection.ApplyDeletionPostLoop(ms_io, items, next_focus_item_idx); + selection.ApplyDeletionPostLoop(ms_io, &selection_adapter, items, item_curr_idx_to_focus); ImGui::EndListBox(); } @@ -3204,9 +3205,9 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); - int next_focus_item_idx = -1; + int item_curr_idx_to_focus = -1; if (want_delete) - next_focus_item_idx = selection.ApplyDeletionPreLoop(ms_io, &selection_adapter, items.Size); + item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, &selection_adapter, items); if (show_in_table) { @@ -3222,8 +3223,8 @@ static void ShowDemoWindowMultiSelect() if (use_clipper) { clipper.Begin(items.Size); - if (next_focus_item_idx != -1) - clipper.IncludeItemByIndex(next_focus_item_idx); // Ensure focused item is not clipped + if (item_curr_idx_to_focus != -1) + clipper.IncludeItemByIndex(item_curr_idx_to_focus); // Ensure focused item is not clipped if (ms_io->RangeSrcItem > 0) clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. } @@ -3262,7 +3263,7 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_Selectable) { ImGui::Selectable(label, item_is_selected); - if (next_focus_item_idx == n) + if (item_curr_idx_to_focus == n) ImGui::SetKeyboardFocusHere(-1); if (use_drag_drop && ImGui::BeginDragDropSource()) @@ -3278,7 +3279,7 @@ static void ShowDemoWindowMultiSelect() if (item_is_selected) tree_node_flags |= ImGuiTreeNodeFlags_Selected; bool open = ImGui::TreeNodeEx(label, tree_node_flags); - if (next_focus_item_idx == n) + if (item_curr_idx_to_focus == n) ImGui::SetKeyboardFocusHere(-1); if (use_drag_drop && ImGui::BeginDragDropSource()) { @@ -3327,7 +3328,7 @@ static void ShowDemoWindowMultiSelect() ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, &selection_adapter, items.Size); if (want_delete) - selection.ApplyDeletionPostLoop(ms_io, items, next_focus_item_idx); + selection.ApplyDeletionPostLoop(ms_io, &selection_adapter, items, item_curr_idx_to_focus); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); From dce02f5c4b0794b8003478013205a185d2182fcf Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Aug 2023 15:53:50 +0200 Subject: [PATCH 0153/2359] Demo: Dual List Box: Added a dual list box (6648) --- imgui_demo.cpp | 183 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 170 insertions(+), 13 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3e91336dc..98e44e058 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2761,6 +2761,13 @@ static void ShowDemoWindowWidgets() } } +static const char* ExampleNames[] = +{ + "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", + "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", + "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Celtuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" +}; + // Our multi-selection system doesn't make assumption about: // - how you want to identify items in multi-selection API? Indices(*) / Custom Identifiers / Pointers ? // - how you want to store persistent selection data? Indices / Custom Identifiers(*) / Pointers ? @@ -2858,7 +2865,7 @@ struct ExampleSelection QueueDeletion = false; // If focused item is not selected... - const int focused_idx = adapter->UserDataToIndex(adapter, ms_io->NavIdItem); // Index of currently focused item + const int focused_idx = (int)ms_io->NavIdItem; // Index of currently focused item if (ms_io->NavIdSelected == false) // This is merely a shortcut, == Contains(adapter->IndexToStorage(items, focused_idx)) { ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even when NavIdSelected==true, but it would take an extra frame to recover RangeSrc when deleting a selected item. @@ -2905,6 +2912,147 @@ struct ExampleSelection } }; +// Example: Implement dual list box storage and interface +struct ExampleDualListBox +{ + ImVector Items[2]; // ID is index into ExampleName[] + ExampleSelection Selections[2]; // Store ExampleItemId into selection + bool OptKeepSorted = true; + + void MoveAll(int src, int dst) + { + IM_ASSERT((src == 0 && dst == 1) || (src == 1 && dst == 0)); + for (ImGuiID item_id : Items[src]) + Items[dst].push_back(item_id); + Items[src].clear(); + SortItems(dst); + Selections[src].Swap(Selections[dst]); + Selections[src].Clear(); + } + void MoveSelected(int src, int dst) + { + for (int src_n = 0; src_n < Items[src].Size; src_n++) + { + ImGuiID item_id = Items[src][src_n]; + if (!Selections[src].Contains(item_id)) + continue; + Items[src].erase(&Items[src][src_n]); // FIXME-OPT: Could be implemented more optimally (rebuild src items and swap) + Items[dst].push_back(item_id); + src_n--; + } + if (OptKeepSorted) + SortItems(dst); + Selections[src].Swap(Selections[dst]); + Selections[src].Clear(); + } + void ApplySelectionRequests(ImGuiMultiSelectIO* ms_io, int side) + { + // In this example we store item id in selection (instead of item index) + ExampleSelectionAdapter adapter; + adapter.Data = Items[side].Data; + adapter.IndexToStorage = [](ExampleSelectionAdapter* self, int idx) { return (ImGuiID)((ImGuiID*)self->Data)[idx]; }; + Selections[side].ApplyRequests(ms_io, &adapter, Items[side].Size); + } + static int IMGUI_CDECL CompareItemsByValue(const void* lhs, const void* rhs) + { + const int* a = (const int*)lhs; + const int* b = (const int*)rhs; + return (*a - *b) > 0 ? +1 : -1; + } + void SortItems(int n) + { + qsort(Items[n].Data, (size_t)Items[n].Size, sizeof(Items[n][0]), CompareItemsByValue); + } + void Show() + { + ImGui::Checkbox("Sorted", &OptKeepSorted); + if (ImGui::BeginTable("split", 3, ImGuiTableFlags_None)) + { + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Left side + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); // Buttons + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Right side + ImGui::TableNextRow(); + + int request_move_selected = -1; + int request_move_all = -1; + for (int side = 0; side < 2; side++) + { + // FIXME-MULTISELECT: Dual List Box: Add context menus + // FIXME-NAV: Using ImGuiWindowFlags_NavFlattened exhibit many issues. + ImVector& items = Items[side]; + ExampleSelection& selection = Selections[side]; + + ImGui::TableSetColumnIndex((side == 0) ? 0 : 2); + ImGui::Text("%s (%d)", (side == 0) ? "Available" : "Basket", items.Size); + + // Submit scrolling range to avoid glitches on moving/deletion + const float items_height = ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); + + if (ImGui::BeginChild(ImGui::GetID(side ? "1" : "0"), ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle)) + { + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ApplySelectionRequests(ms_io, side); + + for (int item_n = 0; item_n < items.Size; item_n++) + { + ImGuiID item_id = items[item_n]; + bool item_is_selected = selection.Contains(item_id); + ImGui::SetNextItemSelectionUserData(item_n); + ImGui::Selectable(ExampleNames[item_id], item_is_selected, ImGuiSelectableFlags_AllowDoubleClick); + if (ImGui::IsItemFocused()) + { + // FIXME-MULTISELECT: Dual List Box: Transfer focus + if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)) + request_move_selected = side; + if (ImGui::IsMouseDoubleClicked(0)) // FIXME-MULTISELECT: Double-click on multi-selection? + request_move_selected = side; + } + } + + ms_io = ImGui::EndMultiSelect(); + ApplySelectionRequests(ms_io, side); + } + ImGui::EndChild(); + } + + // Buttons columns + ImGui::TableSetColumnIndex(1); + ImGui::NewLine(); + //ImVec2 button_sz = { ImGui::CalcTextSize(">>").x + ImGui::GetStyle().FramePadding.x * 2.0f, ImGui::GetFrameHeight() + padding.y * 2.0f }; + ImVec2 button_sz = { ImGui::GetFrameHeight(), ImGui::GetFrameHeight() }; + + // (Using BeginDisabled()/EndDisabled() works but feels distracting given how it is currently visualized) + if (ImGui::Button(">>", button_sz)) + request_move_all = 0; + if (ImGui::Button(">", button_sz)) + request_move_selected = 0; + if (ImGui::Button("<", button_sz)) + request_move_selected = 1; + if (ImGui::Button("<<", button_sz)) + request_move_all = 1; + + // Process requests + if (request_move_all != -1) + MoveAll(request_move_all, request_move_all ^ 1); + if (request_move_selected != -1) + MoveSelected(request_move_selected, request_move_selected ^ 1); + + // FIXME-MULTISELECT: action from outside + if (OptKeepSorted == false) + { + ImGui::NewLine(); + if (ImGui::ArrowButton("MoveUp", ImGuiDir_Up)) {} + if (ImGui::ArrowButton("MoveDown", ImGuiDir_Down)) {} + } + + ImGui::EndTable(); + } + } +}; + + static void ShowDemoWindowMultiSelect() { IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); @@ -2947,13 +3095,6 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } - static const char* random_names[] = - { - "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", - "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", - "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Celtuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" - }; - // Demonstrate holding/updating multi-selection data using the BeginMultiSelect/EndMultiSelect API. // SHIFT+Click w/ CTRL and other standard features are supported. IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); @@ -2982,7 +3123,7 @@ static void ShowDemoWindowMultiSelect() for (int n = 0; n < ITEMS_COUNT; n++) { char label[64]; - sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); @@ -3023,7 +3164,7 @@ static void ShowDemoWindowMultiSelect() for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) { char label[64]; - sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); @@ -3092,7 +3233,7 @@ static void ShowDemoWindowMultiSelect() { const int item_id = items[n]; char label[64]; - sprintf(label, "Object %05d: %s", item_id, random_names[item_id % IM_ARRAYSIZE(random_names)]); + sprintf(label, "Object %05d: %s", item_id, ExampleNames[item_id % IM_ARRAYSIZE(ExampleNames)]); bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); @@ -3112,6 +3253,22 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } + // Implement a Dual List Box (#6648) + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (dual list box)"); + if (ImGui::TreeNode("Multi-Select (dual list box)")) + { + // Init default state + static ExampleDualListBox dlb; + if (dlb.Items[0].Size == 0 && dlb.Items[1].Size == 0) + for (int item_id = 0; item_id < IM_ARRAYSIZE(ExampleNames); item_id++) + dlb.Items[0].push_back((ImGuiID)item_id); + + // Show + dlb.Show(); + + ImGui::TreePop(); + } + // Demonstrate individual selection scopes in same window IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (multiple scopes)"); if (ImGui::TreeNode("Multi-Select (multiple scopes)")) @@ -3135,7 +3292,7 @@ static void ShowDemoWindowMultiSelect() for (int n = 0; n < ITEMS_COUNT; n++) { char label[64]; - sprintf(label, "Object %05d: %s", n, random_names[n % IM_ARRAYSIZE(random_names)]); + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); bool item_is_selected = selection->Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); @@ -3239,7 +3396,7 @@ static void ShowDemoWindowMultiSelect() ImGui::TableNextColumn(); const int item_id = items[n]; - const char* item_category = random_names[item_id % IM_ARRAYSIZE(random_names)]; + const char* item_category = ExampleNames[item_id % IM_ARRAYSIZE(ExampleNames)]; char label[64]; sprintf(label, "Object %05d: %s", item_id, item_category); From a6f43dfadda53a9e3f04ebcaf85317ab58cae0af Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 29 Aug 2023 18:18:24 +0200 Subject: [PATCH 0154/2359] MultiSelect: ImGuiMultiSelectIO's field are not used during loop anymore, stripping them out of comments. --- imgui.h | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/imgui.h b/imgui.h index 5add92931..177db867f 100644 --- a/imgui.h +++ b/imgui.h @@ -2788,18 +2788,18 @@ struct ImGuiMultiSelectIO // - Always process requests in this order: Clear, SelectAll, SetRange. Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. // - Some fields are only necessary if your list is dynamic and allows deletion (getting "post-deletion" state right is shown in the demo) // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. - // REQUESTS --------------------------------// BEGIN / LOOP / END - bool RequestClear; // ms:w, app:r / / ms:w, app:r // 1. Request app/user to clear selection. - bool RequestSelectAll; // ms:w, app:r / / ms:w, app:r // 2. Request app/user to select all. - bool RequestSetRange; // / / ms:w, app:r // 3. Request app/user to select/unselect [RangeFirstItem..RangeLastItem] items, based on RangeSelected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. - // STATE/ARGUMENTS -------------------------// BEGIN / LOOP / END - ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be cliped! - ImGuiSelectionUserData RangeFirstItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) - ImGuiSelectionUserData RangeLastItem; // / / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) - bool RangeSelected; // / / ms:w, app:r // End: parameter for RequestSetRange request. true = Select Range, false = Unselect Range. - bool RangeSrcReset; // app:w / / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). - bool NavIdSelected; // ms:w, app:r / / // (If using deletion) Last known selection state for NavId (if part of submitted items). - ImGuiSelectionUserData NavIdItem; // ms:w, app:r / / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). + // REQUESTS --------------------------------// BEGIN / END + bool RequestClear; // ms:w, app:r / ms:w, app:r // 1. Request app/user to clear selection. + bool RequestSelectAll; // ms:w, app:r / ms:w, app:r // 2. Request app/user to select all. + bool RequestSetRange; // / ms:w, app:r // 3. Request app/user to select/unselect [RangeFirstItem..RangeLastItem] items based on 'bool RangeSelected'. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. + // STATE/ARGUMENTS -------------------------// BEGIN / END + ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be cliped! + ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) + ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) + bool RangeSelected; // / ms:w, app:r // End: parameter for RequestSetRange request. true = Select Range, false = Unselect Range. + bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). + bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). + ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). ImGuiMultiSelectIO() { Clear(); } void Clear() { memset(this, 0, sizeof(*this)); NavIdItem = RangeSrcItem = RangeFirstItem = RangeLastItem = (ImGuiSelectionUserData)-1; } From 9da4efed2a1d288abac9eea80873e232f32edebb Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 29 Aug 2023 18:53:58 +0200 Subject: [PATCH 0155/2359] MultiSelect: moved RequestClear output so it'll match request list version better. Use Storage->RangeSrcItem in EndMultiSelect(). --- imgui_widgets.cpp | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1930fd790..987f50cb0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7213,7 +7213,8 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->IsFocused) { - if (ms->BeginIO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) + // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here. + if (ms->BeginIO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here! (see tests) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. ms->Storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; @@ -7396,7 +7397,14 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Mouse Pressed: Ctrl+Shift | n/a | Dst=item, Sel=!Sel => SetRange Src-Dst //---------------------------------------------------------------------------------------- - ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; + const ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; + if (!is_multiselect) + ms->EndIO.RequestClear = true; + else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl) + ms->EndIO.RequestClear = true; + else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl) + ms->EndIO.RequestClear = true; // With is_false==false the RequestClear was done in BeginIO, not necessary to do again. + int range_direction; ms->EndIO.RequestSetRange = true; if (is_shift && is_multiselect) @@ -7419,21 +7427,6 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiSelectionUserData range_dst_item = item_data; ms->EndIO.RangeFirstItem = (range_direction > 0) ? ms->EndIO.RangeSrcItem : range_dst_item; ms->EndIO.RangeLastItem = (range_direction > 0) ? range_dst_item : ms->EndIO.RangeSrcItem; - - if (!is_multiselect) - { - ms->EndIO.RequestClear = true; - } - else if (input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) - { - if (!is_ctrl) - ms->EndIO.RequestClear = true; - } - else if (input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) - { - if (is_shift && !is_ctrl) // Without Shift the RequestClear was done in BeginIO, not necessary to do again. - ms->EndIO.RequestClear = true; - } } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) From 5628dda5a5c27f9edde952270813082abff7ac79 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Aug 2023 15:03:51 +0200 Subject: [PATCH 0156/2359] MultiSelect: move shared logic to MultiSelectItemHeader(). No logic change AFAIK but added an indent level in MultiSelectItemHeader(). Logic changes will come in next commit. --- imgui_demo.cpp | 3 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 111 ++++++++++++++++++++++------------------------ 3 files changed, 57 insertions(+), 59 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 98e44e058..ac0ddc269 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3419,7 +3419,8 @@ static void ShowDemoWindowMultiSelect() ImGui::SetNextItemSelectionUserData(n); if (widget_type == WidgetType_Selectable) { - ImGui::Selectable(label, item_is_selected); + ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_None; + ImGui::Selectable(label, item_is_selected, selectable_flags); if (item_curr_idx_to_focus == n) ImGui::SetKeyboardFocusHere(-1); diff --git a/imgui_internal.h b/imgui_internal.h index 2e2999a92..bdfaac28c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3366,7 +3366,7 @@ namespace ImGui IMGUI_API int TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data); // Multi-Select API - IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected); + IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 987f50cb0..69c758dc3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6468,19 +6468,11 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags // Multi-selection support (header) if (is_multi_select) { - MultiSelectItemHeader(id, &selected); - button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; + // Handle multi-select + alter button flags for it + MultiSelectItemHeader(id, &selected, &button_flags); - // We absolutely need to distinguish open vs select so this is the default when multi-select is enabled. + // We absolutely need to distinguish open vs select so comes by default flags |= ImGuiTreeNodeFlags_OpenOnArrow; - - // To handle drag and drop of multiple items we need to avoid clearing selection on click. - // Enabling this test makes actions using CTRL+SHIFT delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. - // FIXME-MULTISELECT: Consider opt-in for drag and drop behavior in ImGuiMultiSelectFlags? - if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) - button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; - else - button_flags |= ImGuiButtonFlags_PressedOnClickRelease; } else { @@ -6822,15 +6814,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const bool was_selected = selected; if (is_multi_select) { - MultiSelectItemHeader(id, &selected); - button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; - - // To handle drag and drop of multiple items we need to avoid clearing selection on click. - // Enabling this test makes actions using CTRL+SHIFT delay their effect on the mouse release which is annoying, but it allows drag and drop of multiple items. - if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) - button_flags |= ImGuiButtonFlags_PressedOnClick; - else - button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + // Handle multi-select + alter button flags for it + MultiSelectItemHeader(id, &selected, &button_flags); } bool hovered, held; @@ -7271,52 +7256,64 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d } } -void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected) +void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags) { ImGuiContext& g = *GImGui; ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; - if (!ms->IsFocused) - return; - ImGuiMultiSelectState* storage = ms->Storage; - IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); - ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; - - // Apply Clear/SelectAll requests requested by BeginMultiSelect(). - // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. - // If you are using a clipper (aka not submitting every element of the list) you need to process the Clear/SelectAll request after calling BeginMultiSelect() bool selected = *p_selected; - if (ms->BeginIO.RequestClear) - selected = false; - else if (ms->BeginIO.RequestSelectAll) - selected = true; - - // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) - // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function) - if (ms->IsSetRange) + if (ms->IsFocused) { - IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0); - const bool is_range_dst = (ms->RangeDstPassedBy == false) && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. - if (is_range_dst) - { - ms->RangeDstPassedBy = true; - if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst - { - storage->RangeSrcItem = item_data; - storage->RangeSelected = selected ? 1 : 0; - } - } - const bool is_range_src = storage->RangeSrcItem == item_data; - if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy) - { - IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1); - selected = (storage->RangeSelected != 0); - } - else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) + ImGuiMultiSelectState* storage = ms->Storage; + ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; + IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); + + // Apply Clear/SelectAll requests requested by BeginMultiSelect(). + // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. + // If you are using a clipper (aka not submitting every element of the list) you need to process the Clear/SelectAll request after calling BeginMultiSelect() + if (ms->BeginIO.RequestClear) selected = false; + else if (ms->BeginIO.RequestSelectAll) + selected = true; + + // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) + // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function) + if (ms->IsSetRange) + { + IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0); + const bool is_range_dst = (ms->RangeDstPassedBy == false) && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. + if (is_range_dst) + { + ms->RangeDstPassedBy = true; + if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst + { + storage->RangeSrcItem = item_data; + storage->RangeSelected = selected ? 1 : 0; + } + } + const bool is_range_src = storage->RangeSrcItem == item_data; + if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy) + { + IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1); + selected = (storage->RangeSelected != 0); + } + else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) + selected = false; + } + *p_selected = selected; } - *p_selected = selected; + // Alter button behavior flags + // To handle drag and drop of multiple items we need to avoid clearing selection on click. + // Enabling this test makes actions using CTRL+SHIFT delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. + // FIXME-MULTISELECT: Consider opt-in for drag and drop behavior in ImGuiMultiSelectFlags? + ImGuiButtonFlags button_flags = *p_button_flags; + button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; + if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) + button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; + else + button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + *p_button_flags = button_flags; } void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) From 82de6c470b1c73171d07b5b30ccdc973cbc3fb63 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Aug 2023 15:50:01 +0200 Subject: [PATCH 0157/2359] MultiSelect: Added ImGuiMultiSelectFlags_SelectOnClickRelease to allow dragging an unselected item without altering selection + update drag and drop demo. --- imgui.h | 2 ++ imgui_demo.cpp | 67 ++++++++++++++++++++++++++++++----------------- imgui_widgets.cpp | 3 +-- 3 files changed, 46 insertions(+), 26 deletions(-) diff --git a/imgui.h b/imgui.h index 177db867f..f7f01a4ff 100644 --- a/imgui.h +++ b/imgui.h @@ -2736,6 +2736,8 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_ClearOnEscape = 1 << 2, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickWindowVoid= 1 << 3, // Clear selection when clicking on empty location within host window (use if BeginMultiSelect() covers a whole window) //ImGuiMultiSelectFlags_ClearOnClickRectVoid= 1 << 4, // Clear selection when clicking on empty location within rectangle covered by selection scope (use if multiple BeginMultiSelect() are used in the same host window) + ImGuiMultiSelectFlags_SelectOnClick = 1 << 5, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 6, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. }; // Multi-selection system diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ac0ddc269..6192b6343 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3338,6 +3338,7 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickWindowVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickWindowVoid); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClickRelease", &flags, ImGuiMultiSelectFlags_SelectOnClickRelease); ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); // Initialize default list with 1000 items. static ImVector items; @@ -3403,11 +3404,11 @@ static void ShowDemoWindowMultiSelect() // IMPORTANT: for deletion refocus to work we need object ID to be stable, // aka not depend on their index in the list. Here we use our persistent item_id // instead of index to build a unique ID that will persist. - // (If we used PushID(n) instead, focus wouldn't be restored correctly after deletion). + // (If we used PushID(index) instead, focus wouldn't be restored correctly after deletion). ImGui::PushID(item_id); // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part - // of the selection scope doesn't erroneously alter our selection (FIXME-TESTS: Add a test for that!). + // of the selection scope doesn't erroneously alter our selection. if (show_color_button) { ImU32 dummy_col = (ImU32)((unsigned int)n * 0xC250B74B) | IM_COL32_A_MASK; @@ -3415,39 +3416,57 @@ static void ShowDemoWindowMultiSelect() ImGui::SameLine(); } + // Submit item bool item_is_selected = selection.Contains((ImGuiID)n); + bool item_is_open = false; ImGui::SetNextItemSelectionUserData(n); if (widget_type == WidgetType_Selectable) { - ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_None; - ImGui::Selectable(label, item_is_selected, selectable_flags); - if (item_curr_idx_to_focus == n) - ImGui::SetKeyboardFocusHere(-1); - - if (use_drag_drop && ImGui::BeginDragDropSource()) - { - ImGui::Text("(Dragging %d items)", selection.GetSize()); - ImGui::EndDragDropSource(); - } + ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_None); } else if (widget_type == WidgetType_TreeNode) { - ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth; - tree_node_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; + ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; if (item_is_selected) tree_node_flags |= ImGuiTreeNodeFlags_Selected; - bool open = ImGui::TreeNodeEx(label, tree_node_flags); - if (item_curr_idx_to_focus == n) - ImGui::SetKeyboardFocusHere(-1); - if (use_drag_drop && ImGui::BeginDragDropSource()) - { - ImGui::Text("(Dragging %d items)", selection.GetSize()); - ImGui::EndDragDropSource(); - } - if (open) - ImGui::TreePop(); + item_is_open = ImGui::TreeNodeEx(label, tree_node_flags); } + // Focus (for after deletion) + if (item_curr_idx_to_focus == n) + ImGui::SetKeyboardFocusHere(-1); + + // Drag and Drop + if (use_drag_drop && ImGui::BeginDragDropSource()) + { + // Write payload with full selection OR single unselected item (only possible with ImGuiMultiSelectFlags_SelectOnClickRelease) + if (ImGui::GetDragDropPayload() == NULL) + { + ImVector payload_items; + if (!item_is_selected) + payload_items.push_back(item_id); + else + for (const ImGuiStoragePair& pair : selection.Storage.Data) + if (pair.val_i) + payload_items.push_back((int)pair.key); + ImGui::SetDragDropPayload("MULTISELECT_DEMO_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes()); + } + + // Display payload content in tooltip + const ImGuiPayload* payload = ImGui::GetDragDropPayload(); + const int* payload_items = (int*)payload->Data; + const int payload_count = (int)payload->DataSize / (int)sizeof(payload_items[0]); + if (payload_count == 1) + ImGui::Text("Object %05d: %s", payload_items[0], ExampleNames[payload_items[0] % IM_ARRAYSIZE(ExampleNames)]); + else + ImGui::Text("Dragging %d objects", payload_count); + + ImGui::EndDragDropSource(); + } + + if (widget_type == WidgetType_TreeNode && item_is_open) + ImGui::TreePop(); + // Right-click: context menu if (ImGui::BeginPopupContextItem()) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 69c758dc3..102fa167a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7306,10 +7306,9 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags // Alter button behavior flags // To handle drag and drop of multiple items we need to avoid clearing selection on click. // Enabling this test makes actions using CTRL+SHIFT delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. - // FIXME-MULTISELECT: Consider opt-in for drag and drop behavior in ImGuiMultiSelectFlags? ImGuiButtonFlags button_flags = *p_button_flags; button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; - if (!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) + if ((!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) && !(ms->Flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; else button_flags |= ImGuiButtonFlags_PressedOnClickRelease; From d18e57e673271c1c8374d3e193c32babeb4946d3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Aug 2023 20:06:22 +0200 Subject: [PATCH 0158/2359] Demo: Assets Browser: Added assets browser demo. --- imgui_demo.cpp | 206 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 206 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6192b6343..982d846c4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -94,6 +94,7 @@ Index of this file: // [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() // [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() // [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() +// [SECTION] Example App: Assets Browser / ShowExampleAppAssetsBrowser() */ @@ -198,6 +199,7 @@ Index of this file: // Forward Declarations static void ShowExampleAppMainMenuBar(); +static void ShowExampleAppAssetsBrowser(bool* p_open); static void ShowExampleAppConsole(bool* p_open); static void ShowExampleAppCustomRendering(bool* p_open); static void ShowExampleAppDocuments(bool* p_open); @@ -275,6 +277,7 @@ void ImGui::ShowDemoWindow(bool* p_open) // Examples Apps (accessible from the "Examples" menu) static bool show_app_main_menu_bar = false; + static bool show_app_assets_browser = false; static bool show_app_console = false; static bool show_app_custom_rendering = false; static bool show_app_documents = false; @@ -290,6 +293,7 @@ void ImGui::ShowDemoWindow(bool* p_open) if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); + if (show_app_assets_browser) ShowExampleAppAssetsBrowser(&show_app_assets_browser); if (show_app_console) ShowExampleAppConsole(&show_app_console); if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering); if (show_app_log) ShowExampleAppLog(&show_app_log); @@ -385,6 +389,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar); ImGui::SeparatorText("Mini apps"); + ImGui::MenuItem("Assets Browser", NULL, &show_app_assets_browser); ImGui::MenuItem("Console", NULL, &show_app_console); ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering); ImGui::MenuItem("Documents", NULL, &show_app_documents); @@ -3306,6 +3311,12 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } + if (ImGui::TreeNode("Multi-Select (tiled assets browser)")) + { + ImGui::BulletText("See 'Examples->Assets Browser' in menu"); + ImGui::TreePop(); + } + // Advanced demonstration of BeginMultiSelect() // - Showcase clipping. // - Showcase deletion. @@ -9623,6 +9634,201 @@ void ShowExampleAppDocuments(bool* p_open) ImGui::End(); } +//----------------------------------------------------------------------------- +// [SECTION] Example App: Assets Browser / ShowExampleAppAssetsBrowser() +//----------------------------------------------------------------------------- + +//#include "imgui_internal.h" // NavMoveRequestTryWrapping() + +struct ExampleAssetsBrowser +{ + // State + int ItemsCount = 10000; + ExampleSelection Selection; + float IconSize = 32.0f; + int IconSpacing = 7; + bool StretchSpacing = true; + float ZoomWheelAccum = 0.0f; + + // Functions + void Draw(const char* title, bool* p_open) + { + if (!ImGui::Begin(title, p_open, ImGuiWindowFlags_MenuBar)) + { + ImGui::End(); + return; + } + + // Menu bar + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Close", NULL, false, p_open != NULL)) + *p_open = false; + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Options")) + { + ImGui::PushItemWidth(ImGui::GetFontSize() * 10); + ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f"); + ImGui::SliderInt("Icon Spacing", &IconSpacing, 0, 32); + ImGui::Checkbox("Stretch Spacing", &StretchSpacing); + ImGui::PopItemWidth(); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // Zooming with CTRL+Wheel + // FIXME-MULTISELECT: Try to maintain scroll. + ImGuiIO& io = ImGui::GetIO(); + if (ImGui::IsWindowAppearing()) + ZoomWheelAccum = 0.0f; + if (io.MouseWheel != 0.0f && ImGui::IsKeyDown(ImGuiMod_Ctrl) && ImGui::IsAnyItemActive() == false) + { + ZoomWheelAccum += io.MouseWheel; + if (fabsf(ZoomWheelAccum) >= 1.0f) + { + IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum); + IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f); + ZoomWheelAccum -= (int)ZoomWheelAccum; + } + } + + // Show a table with ONLY one header row to showcase the idea/possibility of using this to provide a sorting UI + // FIXME-MULTISELECT: Showcase sorting. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + ImGuiTableFlags table_flags_for_sort_specs = ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders; + if (ImGui::BeginTable("for_sort_specs_only", 3, table_flags_for_sort_specs, ImVec2(0.0f, ImGui::GetFrameHeight()))) + { + ImGui::TableSetupColumn("Index"); + ImGui::TableSetupColumn("Color"); + ImGui::TableSetupColumn("Type"); + ImGui::TableHeadersRow(); + if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs()) + sort_specs->SpecsDirty = false; // No actual sorting in this demo yet + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + + if (ImGui::BeginChild("Assets", ImVec2(0, 0), true, ImGuiWindowFlags_NoMove)) + { + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + const ImVec2 item_size(floorf(IconSize), floorf(IconSize)); + + // Layout: when not stretching: allow extending into right-most spacing. + float item_spacing = (float)IconSpacing; + const float avail_width = ImGui::GetContentRegionAvail().x + (StretchSpacing ? 0.0f : floorf(item_spacing * 0.5f)); + + // Layout: calculate number of icon per line and number of lines + const int column_count = IM_MAX((int)(avail_width / (item_size.x + IconSpacing)), 1); + const int line_count = (ItemsCount + column_count - 1) / column_count; + + // Layout: when stretching: allocate remaining space to more spacing. Round before division, so item_spacing may be non-integer. + if (StretchSpacing && column_count > 1) + item_spacing = floorf(avail_width - item_size.x * column_count) / column_count; + + // Calculate and store start position. + const float outer_padding = floorf(item_spacing * 0.5f); + ImVec2 start_pos = ImGui::GetCursorScreenPos(); + start_pos = ImVec2(start_pos.x + outer_padding, start_pos.y + outer_padding); + ImGui::SetCursorScreenPos(start_pos); + + // Multi-select + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnClickWindowVoid; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ExampleSelectionAdapter selection_adapter; + Selection.ApplyRequests(ms_io, &selection_adapter, ItemsCount); + + // Altering ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()... + // But it is necessary for two reasons: + // - Selectables uses it by default to visually fill the space between two items. + // - The vertical spacing would be measured by Clipper to calculate line height if we didn't provide it explicitly (here we do). + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(item_spacing, item_spacing)); + + const float line_height = item_size.y + item_spacing; + ImGuiListClipper clipper; + clipper.Begin(line_count, line_height); + if (ms_io->RangeSrcItem != -1) + clipper.IncludeItemByIndex((int)(ms_io->RangeSrcItem / column_count)); + while (clipper.Step()) + { + for (int line_idx = clipper.DisplayStart; line_idx < clipper.DisplayEnd; line_idx++) + { + const int item_min_idx_for_current_line = line_idx * column_count; + const int item_max_idx_for_current_line = IM_MIN((line_idx + 1) * column_count, ItemsCount); + for (int item_idx = item_min_idx_for_current_line; item_idx < item_max_idx_for_current_line; ++item_idx) + { + ImGui::PushID(item_idx); + + // Position item + ImVec2 pos = ImVec2(start_pos.x + (item_idx % column_count) * (item_size.x + item_spacing), start_pos.y + (line_idx * line_height)); + ImGui::SetCursorScreenPos(pos); + + // Draw box + ImVec2 box_min(pos.x - 1, pos.y - 1); + ImVec2 box_max(box_min.x + item_size.x + 2, box_min.y + item_size.y + 2); + draw_list->AddRect(box_min, box_max, IM_COL32(90, 90, 90, 255)); + + bool item_is_selected = Selection.Contains((ImGuiID)item_idx); + ImGui::SetNextItemSelectionUserData(item_idx); + ImGui::Selectable("##select", item_is_selected, ImGuiSelectableFlags_None, item_size); + + // Update our selection state immediately (without waiting for EndMultiSelect() requests) + // because we use this to alter the color of our text/icon. + if (ImGui::IsItemToggledSelection()) + item_is_selected = !item_is_selected; + + // Drag and drop + if (ImGui::BeginDragDropSource()) + { + ImGui::SetDragDropPayload("ASSETS_BROWSER_ITEMS", "Dummy", 5); + ImGui::Text("%d assets", Selection.Size); + ImGui::EndDragDropSource(); + } + + // Popup menu + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("Selection: %d items", Selection.Size); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + // A real app would likely display an image/thumbnail here. + char label[32]; + sprintf(label, "%d", item_idx); + draw_list->AddRectFilled(box_min, box_max, IM_COL32(48, 48, 48, 128)); + draw_list->AddText(ImVec2(box_min.x, box_max.y - ImGui::GetFontSize()), item_is_selected ? IM_COL32(255, 255, 255, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled), label); + + ImGui::PopID(); + } + } + } + clipper.End(); + ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing + + ms_io = ImGui::EndMultiSelect(); + Selection.ApplyRequests(ms_io, &selection_adapter, ItemsCount); + + // FIXME-MULTISELECT: Find a way to expose this in public API. This currently requires "imgui_internal.h" + //ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); + } + + ImGui::EndChild(); + ImGui::End(); + } +}; + +void ShowExampleAppAssetsBrowser(bool* p_open) +{ + IMGUI_DEMO_MARKER("Examples/Assets Browser"); + static ExampleAssetsBrowser assets_browser; + assets_browser.Draw("Example: Assets Browser", p_open); +} + // End of Demo code #else From 88df5901458100a6f4268385f3fb5c36bdb6ac8b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 1 Sep 2023 14:54:28 +0200 Subject: [PATCH 0159/2359] Demo: Assets Browser: store items, sorting, type overlay. --- imgui_demo.cpp | 146 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 121 insertions(+), 25 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 982d846c4..93addbb1c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2770,7 +2770,7 @@ static const char* ExampleNames[] = { "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", - "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Celtuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" + "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" }; // Our multi-selection system doesn't make assumption about: @@ -9640,19 +9640,84 @@ void ShowExampleAppDocuments(bool* p_open) //#include "imgui_internal.h" // NavMoveRequestTryWrapping() +struct ExampleAsset +{ + int ID; + int Type; + + ExampleAsset(int id, int type) { ID = id; Type = type; } + + static const ImGuiTableSortSpecs* s_current_sort_specs; + + static void SortWithSortSpecs(ImGuiTableSortSpecs* sort_specs, ExampleAsset* items, int items_count) + { + s_current_sort_specs = sort_specs; // Store in variable accessible by the sort function. + if (items_count > 1) + qsort(items, (size_t)items_count, sizeof(items[0]), ExampleAsset::CompareWithSortSpecs); + s_current_sort_specs = NULL; + } + + // Compare function to be used by qsort() + static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs) + { + const ExampleAsset* a = (const ExampleAsset*)lhs; + const ExampleAsset* b = (const ExampleAsset*)rhs; + for (int n = 0; n < s_current_sort_specs->SpecsCount; n++) + { + const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n]; + int delta = 0; + if (sort_spec->ColumnIndex == 0) + delta = (a->ID - b->ID); + else if (sort_spec->ColumnIndex == 1) + delta = (a->Type - b->Type); + if (delta > 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1; + if (delta < 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; + } + return (a->ID - b->ID); + } +}; +const ImGuiTableSortSpecs* ExampleAsset::s_current_sort_specs = NULL; + struct ExampleAssetsBrowser { + // Options + bool ShowTypeOverlay = true; + float IconSize = 32.0f; + int IconSpacing = 7; + bool StretchSpacing = true; + // State - int ItemsCount = 10000; - ExampleSelection Selection; - float IconSize = 32.0f; - int IconSpacing = 7; - bool StretchSpacing = true; - float ZoomWheelAccum = 0.0f; + ImVector Items; + ExampleSelection Selection; + int NextItemId = 0; + bool SortDirty = false; + float ZoomWheelAccum = 0.0f; // Functions + ExampleAssetsBrowser() + { + AddItems(10000); + } + void AddItems(int count) + { + if (Items.Size == 0) + NextItemId = 0; + Items.reserve(Items.Size + count); + for (int n = 0; n < count; n++, NextItemId++) + Items.push_back(ExampleAsset(NextItemId, (NextItemId % 20) < 15 ? 0 : (NextItemId % 20) < 18 ? 1 : 2)); + SortDirty = true; + } + void ClearItems() + { + Items.clear(); + Selection.Clear(); + } + void Draw(const char* title, bool* p_open) { + ImGui::SetNextWindowSize(ImVec2(IconSize * 25, IconSize * 15), ImGuiCond_FirstUseEver); if (!ImGui::Begin(title, p_open, ImGuiWindowFlags_MenuBar)) { ImGui::End(); @@ -9664,6 +9729,11 @@ struct ExampleAssetsBrowser { if (ImGui::BeginMenu("File")) { + if (ImGui::MenuItem("Add 10000 items")) + AddItems(10000); + if (ImGui::MenuItem("Clear items")) + ClearItems(); + ImGui::Separator(); if (ImGui::MenuItem("Close", NULL, false, p_open != NULL)) *p_open = false; ImGui::EndMenu(); @@ -9671,6 +9741,11 @@ struct ExampleAssetsBrowser if (ImGui::BeginMenu("Options")) { ImGui::PushItemWidth(ImGui::GetFontSize() * 10); + + ImGui::SeparatorText("Contents"); + ImGui::Checkbox("Show Type Overlay", &ShowTypeOverlay); + + ImGui::SeparatorText("Layout"); ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f"); ImGui::SliderInt("Icon Spacing", &IconSpacing, 0, 32); ImGui::Checkbox("Stretch Spacing", &StretchSpacing); @@ -9697,22 +9772,24 @@ struct ExampleAssetsBrowser } // Show a table with ONLY one header row to showcase the idea/possibility of using this to provide a sorting UI - // FIXME-MULTISELECT: Showcase sorting. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); ImGuiTableFlags table_flags_for_sort_specs = ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders; - if (ImGui::BeginTable("for_sort_specs_only", 3, table_flags_for_sort_specs, ImVec2(0.0f, ImGui::GetFrameHeight()))) + if (ImGui::BeginTable("for_sort_specs_only", 2, table_flags_for_sort_specs, ImVec2(0.0f, ImGui::GetFrameHeight()))) { ImGui::TableSetupColumn("Index"); - ImGui::TableSetupColumn("Color"); ImGui::TableSetupColumn("Type"); ImGui::TableHeadersRow(); if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs()) - sort_specs->SpecsDirty = false; // No actual sorting in this demo yet + if (sort_specs->SpecsDirty || SortDirty) + { + ExampleAsset::SortWithSortSpecs(sort_specs, Items.Data, Items.Size); + sort_specs->SpecsDirty = SortDirty = false; + } ImGui::EndTable(); } ImGui::PopStyleVar(); - if (ImGui::BeginChild("Assets", ImVec2(0, 0), true, ImGuiWindowFlags_NoMove)) + if (ImGui::BeginChild("Assets", ImVec2(0, -ImGui::GetTextLineHeightWithSpacing()), true, ImGuiWindowFlags_NoMove)) { ImDrawList* draw_list = ImGui::GetWindowDrawList(); const ImVec2 item_size(floorf(IconSize), floorf(IconSize)); @@ -9723,7 +9800,7 @@ struct ExampleAssetsBrowser // Layout: calculate number of icon per line and number of lines const int column_count = IM_MAX((int)(avail_width / (item_size.x + IconSpacing)), 1); - const int line_count = (ItemsCount + column_count - 1) / column_count; + const int line_count = (Items.Size + column_count - 1) / column_count; // Layout: when stretching: allocate remaining space to more spacing. Round before division, so item_spacing may be non-integer. if (StretchSpacing && column_count > 1) @@ -9736,10 +9813,12 @@ struct ExampleAssetsBrowser ImGui::SetCursorScreenPos(start_pos); // Multi-select - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnClickWindowVoid; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickWindowVoid; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags); ExampleSelectionAdapter selection_adapter; - Selection.ApplyRequests(ms_io, &selection_adapter, ItemsCount); + selection_adapter.Data = this; + selection_adapter.IndexToStorage = [](ExampleSelectionAdapter* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->Data; return (ImGuiID)self->Items[idx].ID; }; + Selection.ApplyRequests(ms_io, &selection_adapter, Items.Size); // Altering ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()... // But it is necessary for two reasons: @@ -9747,6 +9826,12 @@ struct ExampleAssetsBrowser // - The vertical spacing would be measured by Clipper to calculate line height if we didn't provide it explicitly (here we do). ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(item_spacing, item_spacing)); + // Rendering parameters + const ImU32 icon_bg_color = IM_COL32(48, 48, 48, 128); + const ImU32 icon_type_overlay_colors[3] = { 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255) }; + const ImVec2 icon_type_overlay_size = ImVec2(4.0f, 4.0f); + const bool display_label = (item_size.x >= ImGui::CalcTextSize("999").x); + const float line_height = item_size.y + item_spacing; ImGuiListClipper clipper; clipper.Begin(line_count, line_height); @@ -9757,10 +9842,11 @@ struct ExampleAssetsBrowser for (int line_idx = clipper.DisplayStart; line_idx < clipper.DisplayEnd; line_idx++) { const int item_min_idx_for_current_line = line_idx * column_count; - const int item_max_idx_for_current_line = IM_MIN((line_idx + 1) * column_count, ItemsCount); + const int item_max_idx_for_current_line = IM_MIN((line_idx + 1) * column_count, Items.Size); for (int item_idx = item_min_idx_for_current_line; item_idx < item_max_idx_for_current_line; ++item_idx) { - ImGui::PushID(item_idx); + ExampleAsset* item_data = &Items[item_idx]; + ImGui::PushID(item_data->ID); // Position item ImVec2 pos = ImVec2(start_pos.x + (item_idx % column_count) * (item_size.x + item_spacing), start_pos.y + (line_idx * line_height)); @@ -9771,9 +9857,9 @@ struct ExampleAssetsBrowser ImVec2 box_max(box_min.x + item_size.x + 2, box_min.y + item_size.y + 2); draw_list->AddRect(box_min, box_max, IM_COL32(90, 90, 90, 255)); - bool item_is_selected = Selection.Contains((ImGuiID)item_idx); ImGui::SetNextItemSelectionUserData(item_idx); - ImGui::Selectable("##select", item_is_selected, ImGuiSelectableFlags_None, item_size); + bool item_is_selected = Selection.Contains((ImGuiID)item_data->ID); + ImGui::Selectable("", item_is_selected, ImGuiSelectableFlags_None, item_size); // Update our selection state immediately (without waiting for EndMultiSelect() requests) // because we use this to alter the color of our text/icon. @@ -9798,10 +9884,19 @@ struct ExampleAssetsBrowser } // A real app would likely display an image/thumbnail here. - char label[32]; - sprintf(label, "%d", item_idx); - draw_list->AddRectFilled(box_min, box_max, IM_COL32(48, 48, 48, 128)); - draw_list->AddText(ImVec2(box_min.x, box_max.y - ImGui::GetFontSize()), item_is_selected ? IM_COL32(255, 255, 255, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled), label); + draw_list->AddRectFilled(box_min, box_max, icon_bg_color); + if (ShowTypeOverlay && item_data->Type != 0) + { + ImU32 type_col = icon_type_overlay_colors[item_data->Type % IM_ARRAYSIZE(icon_type_overlay_colors)]; + draw_list->AddRectFilled(ImVec2(box_max.x - 2 - icon_type_overlay_size.x, box_min.y + 2), ImVec2(box_max.x - 2, box_min.y + 2 + icon_type_overlay_size.y), type_col); + } + if (display_label) + { + ImU32 label_col = item_is_selected ? IM_COL32(255, 255, 255, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled); + char label[32]; + sprintf(label, "%d", item_data->ID); + draw_list->AddText(ImVec2(box_min.x, box_max.y - ImGui::GetFontSize()), label_col, label); + } ImGui::PopID(); } @@ -9811,13 +9906,14 @@ struct ExampleAssetsBrowser ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing ms_io = ImGui::EndMultiSelect(); - Selection.ApplyRequests(ms_io, &selection_adapter, ItemsCount); + Selection.ApplyRequests(ms_io, &selection_adapter, Items.Size); // FIXME-MULTISELECT: Find a way to expose this in public API. This currently requires "imgui_internal.h" //ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); } ImGui::EndChild(); + ImGui::Text("Selected: %d/%d items", Selection.Size, Items.Size); ImGui::End(); } }; From 2765fdb43ea38aaba20109b2a9f4935ccb9ebae7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Sep 2023 19:10:08 +0200 Subject: [PATCH 0160/2359] MultiSelect: removed seemingly unnecessary block in BeginMultiSelect(). - EndIO.RangeSelected always set along with EndIO.RequestSetRange - Trying to assert for the assignment making a difference when EndIO.RequestSetRange is already set couldn't find a case (tests passing). --- imgui.h | 2 +- imgui_widgets.cpp | 24 +++++++++--------------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/imgui.h b/imgui.h index f7f01a4ff..95622e852 100644 --- a/imgui.h +++ b/imgui.h @@ -2795,7 +2795,7 @@ struct ImGuiMultiSelectIO bool RequestSelectAll; // ms:w, app:r / ms:w, app:r // 2. Request app/user to select all. bool RequestSetRange; // / ms:w, app:r // 3. Request app/user to select/unselect [RangeFirstItem..RangeLastItem] items based on 'bool RangeSelected'. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. // STATE/ARGUMENTS -------------------------// BEGIN / END - ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be cliped! + ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be clipped! ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) bool RangeSelected; // / ms:w, app:r // End: parameter for RequestSetRange request. true = Select Range, false = Unselect Range. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 102fa167a..7bb21c252 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7109,12 +7109,12 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) // - DebugNodeMultiSelectState() [Internal] //------------------------------------------------------------------------- -static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* data) +static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io) { ImGuiContext& g = *GImGui; - if (data->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); - if (data->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); - if (data->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, data->RangeFirstItem, data->RangeLastItem, data->RangeFirstItem, data->RangeLastItem, data->RangeSelected); + if (io->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); + if (io->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); + if (io->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, io->RangeFirstItem, io->RangeLastItem, io->RangeFirstItem, io->RangeLastItem, io->RangeSelected); } // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). @@ -7169,17 +7169,17 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (ms->IsFocused) { - // Shortcut: Select all (CTRL+A) - if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) - if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) - ms->BeginIO.RequestSelectAll = true; - // Shortcut: Clear selection (Escape) // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. // Otherwise may be done by caller but it means Shortcut() needs to be exposed. if (flags & ImGuiMultiSelectFlags_ClearOnEscape) if (Shortcut(ImGuiKey_Escape)) ms->BeginIO.RequestClear = true; + + // Shortcut: Select all (CTRL+A) + if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) + ms->BeginIO.RequestSelectAll = true; } if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) @@ -7428,12 +7428,6 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) if (storage->RangeSrcItem == item_data) storage->RangeSelected = selected ? 1 : 0; - if (ms->EndIO.RangeSrcItem == item_data && is_ctrl && is_shift && is_multiselect) - { - if (ms->EndIO.RequestSetRange) - IM_ASSERT(storage->RangeSrcItem == ms->EndIO.RangeSrcItem); - ms->EndIO.RangeSelected = selected; - } // Update/store the selection state of focused item if (g.NavId == id) From c3998b70ccb07c30e57872d84446fdb1a707350e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 21 Sep 2023 20:40:21 +0200 Subject: [PATCH 0161/2359] MultiSelect: clarified purpose and use of IsItemToggledSelection(). Added assert. Moved to multi-selection section of imgui.h. --- imgui.cpp | 6 ++++++ imgui.h | 2 +- imgui_widgets.cpp | 12 +++++++----- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 19beed8ed..59c7580bb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5446,9 +5446,15 @@ bool ImGui::IsItemToggledOpen() return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false; } +// Call after a Selectable() or TreeNode() involved in multi-selection. +// Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose. +// This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block. +// (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets +// return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.) bool ImGui::IsItemToggledSelection() { ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect() return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false; } diff --git a/imgui.h b/imgui.h index 95622e852..96b29d560 100644 --- a/imgui.h +++ b/imgui.h @@ -676,6 +676,7 @@ namespace ImGui IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); + IMGUI_API bool IsItemToggledSelection(); // Was the last item selection state toggled? Useful if you need the per-item information _before_ reaching EndMultiSelect(). We only returns toggle _event_ in order to handle clipping correctly. // Widgets: List Boxes // - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. @@ -909,7 +910,6 @@ namespace ImGui IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing. IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode(). - IMGUI_API bool IsItemToggledSelection(); // was the last item selection state toggled? (after Selectable(), TreeNode() etc.) We only returns toggle _event_ in order to handle clipping correctly. IMGUI_API bool IsAnyItemHovered(); // is any item hovered? IMGUI_API bool IsAnyItemActive(); // is any item active? IMGUI_API bool IsAnyItemFocused(); // is any item focused? diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7bb21c252..b2ae35cb0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6891,7 +6891,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (disabled_item && !disabled_global) EndDisabled(); - // Users of BeginMultiSelect() scope: call ImGui::IsItemToggledSelection() to retrieve selection toggle. Selectable() returns a pressed state! + // Selectable() always returns a pressed state! + // Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve + // selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect(). IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; //-V1020 } @@ -7335,7 +7337,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; - const bool is_multiselect = (ms->Flags & ImGuiMultiSelectFlags_SingleSelect) == 0; + const bool is_singleselect = (ms->Flags & ImGuiMultiSelectFlags_SingleSelect) != 0; bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; @@ -7394,16 +7396,16 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) //---------------------------------------------------------------------------------------- const ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; - if (!is_multiselect) + if (is_singleselect) ms->EndIO.RequestClear = true; else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl) ms->EndIO.RequestClear = true; else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl) - ms->EndIO.RequestClear = true; // With is_false==false the RequestClear was done in BeginIO, not necessary to do again. + ms->EndIO.RequestClear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. int range_direction; ms->EndIO.RequestSetRange = true; - if (is_shift && is_multiselect) + if (is_shift && !is_singleselect) { // Shift+Arrow always select // Ctrl+Shift+Arrow copy source selection state (alrady stored by BeginMultiSelect() in RangeSelected) From a6adfb2b49482f117a44a98e79bb92b049843f06 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 Sep 2023 14:30:56 +0200 Subject: [PATCH 0162/2359] MultiSelect: added missing call on Shutdown(). Better reuse selection buffer. --- imgui.cpp | 2 ++ imgui_demo.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 59c7580bb..f932e4efa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3818,6 +3818,8 @@ void ImGui::Shutdown() g.TablesTempData.clear_destruct(); g.DrawChannelsTempMergeBuffer.clear(); + g.MultiSelectStorage.Clear(); + g.ClipboardHandlerData.clear(); g.MenusIdSubmittedThisFrame.clear(); g.InputTextState.ClearFreeMemory(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 93addbb1c..59b7162ac 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2818,7 +2818,7 @@ struct ExampleSelection // Functions ExampleSelection() { Clear(); } - void Clear() { Storage.Clear(); Size = 0; QueueDeletion = false; } + void Clear() { Storage.Data.resize(0); Size = 0; QueueDeletion = false; } void Swap(ExampleSelection& rhs) { Storage.Data.swap(rhs.Storage.Data); } bool Contains(ImGuiID key) const { return Storage.GetInt(key, 0) != 0; } void AddItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int != 0) return; *p_int = 1; Size++; } @@ -2849,8 +2849,11 @@ struct ExampleSelection Clear(); if (ms_io->RequestSelectAll) + { + Storage.Data.reserve(items_count); for (int idx = 0; idx < items_count; idx++) AddItem(adapter->IndexToStorage(adapter, idx)); + } if (ms_io->RequestSetRange) for (int idx = (int)ms_io->RangeFirstItem; idx <= (int)ms_io->RangeLastItem; idx++) From 6feff6ff0514db74b387843768cb023e39d148fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 Sep 2023 14:23:40 +0200 Subject: [PATCH 0163/2359] MultiSelect: (Breaking) io contains a ImVector list. --- imgui.h | 53 +++++++++++++++++++++++++++----------------- imgui_demo.cpp | 33 +++++++++++++++------------- imgui_internal.h | 4 +++- imgui_widgets.cpp | 56 +++++++++++++++++++++++++++++++---------------- 4 files changed, 91 insertions(+), 55 deletions(-) diff --git a/imgui.h b/imgui.h index 96b29d560..2ce1f1983 100644 --- a/imgui.h +++ b/imgui.h @@ -44,7 +44,7 @@ Index of this file: // [SECTION] ImGuiIO // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) @@ -2720,7 +2720,7 @@ struct ImColor }; //----------------------------------------------------------------------------- -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO) +// [SECTION] Multi-Select API flags & structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO) //----------------------------------------------------------------------------- #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. @@ -2775,36 +2775,49 @@ enum ImGuiMultiSelectFlags_ // - If you need to wrap this API for another language/framework, feel free to expose this as 'int' if simpler. // Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (2) [If using clipper] Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 6. +// - (2) [If using clipper] Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 6. // - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeIndex(). If already using indices in ImGuiSelectionUserData, it is as simple as clipper.IncludeIndex((int)ms_io->RangeSrcItem); // LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (6) Honor Clear/SelectAll/SetRange requests by updating your selection data. Same code as Step 2. +// - (6) Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 2. // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. // However it is perfectly fine to honor all steps even if you don't use a clipper. // Advanced: // - Deletion: If you need to handle items deletion a little more work if needed for post-deletion focus and scrolling to be correct. // refer to 'Demo->Widgets->Selection State' for demos supporting deletion. + +enum ImGuiSelectionRequestType +{ + ImGuiSelectionRequestType_None = 0, + ImGuiSelectionRequestType_Clear, // Request app to clear selection. + ImGuiSelectionRequestType_SelectAll, // Request app to select all. + ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items based on 'bool RangeSelected'. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. +}; + +// List of requests stored in ImGuiMultiSelectIO +// - Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. +// - Some fields are only necessary if your list is dynamic and allows deletion (handling deletion and getting "post-deletion" state right is shown in the demo) +// - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. +struct ImGuiSelectionRequest +{ + ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r + bool RangeSelected; // / ms:w, app:r // Parameter for SetRange request (true = select range, false = unselect range) + ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) + ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) + + ImGuiSelectionRequest(ImGuiSelectionRequestType type = ImGuiSelectionRequestType_None) { Type = type; RangeSelected = false; RangeFirstItem = RangeLastItem = (ImGuiSelectionUserData)-1; } +}; + struct ImGuiMultiSelectIO { - // - Always process requests in this order: Clear, SelectAll, SetRange. Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. - // - Some fields are only necessary if your list is dynamic and allows deletion (getting "post-deletion" state right is shown in the demo) - // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. - // REQUESTS --------------------------------// BEGIN / END - bool RequestClear; // ms:w, app:r / ms:w, app:r // 1. Request app/user to clear selection. - bool RequestSelectAll; // ms:w, app:r / ms:w, app:r // 2. Request app/user to select all. - bool RequestSetRange; // / ms:w, app:r // 3. Request app/user to select/unselect [RangeFirstItem..RangeLastItem] items based on 'bool RangeSelected'. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. - // STATE/ARGUMENTS -------------------------// BEGIN / END - ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be clipped! - ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) - ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // End: parameter for RequestSetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) - bool RangeSelected; // / ms:w, app:r // End: parameter for RequestSetRange request. true = Select Range, false = Unselect Range. - bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). - bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). - ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). + ImVector Requests; // ms:w, app:r / ms:w app:r // Requests + ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be clipped! + ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). + bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). + bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). ImGuiMultiSelectIO() { Clear(); } - void Clear() { memset(this, 0, sizeof(*this)); NavIdItem = RangeSrcItem = RangeFirstItem = RangeLastItem = (ImGuiSelectionUserData)-1; } + void Clear() { Requests.resize(0); RangeSrcItem = NavIdItem = (ImGuiSelectionUserData)-1; NavIdSelected = RangeSrcReset = false; } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 59b7162ac..770eb3c9d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2838,26 +2838,29 @@ struct ExampleSelection // WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ExampleSelectionAdapter' INDIRECTION LOGIC. // Notice that with the simplest adapter (using indices everywhere), all functions return their parameters. // The most simple implementation (using indices everywhere) would look like: - // if (ms_io->RequestClear) { Clear(); } - // if (ms_io->RequestSelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } - // if (ms_io->RequestSetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } + // for (ImGuiSelectionRequest& req : ms_io->Requests) + // { + // if (req.Type == ImGuiSelectionRequestType_Clear) { Clear(); } + // if (req.Type == ImGuiSelectionRequestType_SelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } + // if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } + // } void ApplyRequests(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, int items_count) { IM_ASSERT(adapter->IndexToStorage != NULL); - - if (ms_io->RequestClear || ms_io->RequestSelectAll) - Clear(); - - if (ms_io->RequestSelectAll) + for (ImGuiSelectionRequest& req : ms_io->Requests) { - Storage.Data.reserve(items_count); - for (int idx = 0; idx < items_count; idx++) - AddItem(adapter->IndexToStorage(adapter, idx)); + if (req.Type == ImGuiSelectionRequestType_Clear || req.Type == ImGuiSelectionRequestType_SelectAll) + Clear(); + if (req.Type == ImGuiSelectionRequestType_SelectAll) + { + Storage.Data.reserve(items_count); + for (int idx = 0; idx < items_count; idx++) + AddItem(adapter->IndexToStorage(adapter, idx)); + } + if (req.Type == ImGuiSelectionRequestType_SetRange) + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) + UpdateItem(adapter->IndexToStorage(adapter, idx), req.RangeSelected); } - - if (ms_io->RequestSetRange) - for (int idx = (int)ms_io->RangeFirstItem; idx <= (int)ms_io->RangeLastItem; idx++) - UpdateItem(adapter->IndexToStorage(adapter, idx), ms_io->RangeSelected); } // Find which item should be Focused after deletion. diff --git a/imgui_internal.h b/imgui_internal.h index bdfaac28c..9df3b01e8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1722,6 +1722,8 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiKeyChord KeyMods; ImGuiMultiSelectIO BeginIO; // Requests are set and returned by BeginMultiSelect(), written to by user during the loop. ImGuiMultiSelectIO EndIO; // Requests are set during the loop and returned by EndMultiSelect(). + bool LoopRequestClear; + bool LoopRequestSelectAll; bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. bool NavIdPassedBy; @@ -1730,7 +1732,7 @@ struct IMGUI_API ImGuiMultiSelectTempData //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectTempData() { Clear(); } - void Clear() { memset(this, 0, sizeof(*this)); BeginIO.Clear(); EndIO.Clear(); } + void Clear() { Storage = NULL; FocusScopeId = 0; Flags = 0; KeyMods = 0; BeginIO.Clear(); EndIO.Clear(); LoopRequestClear = LoopRequestSelectAll = IsFocused = IsSetRange = NavIdPassedBy = RangeSrcPassedBy = RangeDstPassedBy = false; } }; // Persistent storage for multi-select (as long as selection is alive) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b2ae35cb0..17162e393 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7114,9 +7114,12 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io) { ImGuiContext& g = *GImGui; - if (io->RequestClear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestClear\n", function); - if (io->RequestSelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSelectAll\n", function); - if (io->RequestSetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: RequestSetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, io->RangeFirstItem, io->RangeLastItem, io->RangeFirstItem, io->RangeLastItem, io->RangeSelected); + for (const ImGuiSelectionRequest& req : io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_Clear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: Clear\n", function); + if (req.Type == ImGuiSelectionRequestType_SelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SelectAll\n", function); + if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.RangeSelected); + } } // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). @@ -7151,6 +7154,9 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) ms->BeginIO.NavIdItem = ms->EndIO.NavIdItem = storage->NavIdItem; ms->BeginIO.NavIdSelected = ms->EndIO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; + bool request_clear = false; + bool request_select_all = false; + // Clear when using Navigation to move within the scope // (we compare FocusScopeId so it possible to use multiple selections inside a same window) if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) @@ -7160,13 +7166,13 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (ms->IsSetRange) IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid); // Not ready -> could clear? if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) - ms->BeginIO.RequestClear = true; + request_clear = true; } else if (g.NavJustMovedFromFocusScopeId == ms->FocusScopeId) { // Also clear on leaving scope (may be optional?) if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) - ms->BeginIO.RequestClear = true; + request_clear = true; } if (ms->IsFocused) @@ -7176,14 +7182,19 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) // Otherwise may be done by caller but it means Shortcut() needs to be exposed. if (flags & ImGuiMultiSelectFlags_ClearOnEscape) if (Shortcut(ImGuiKey_Escape)) - ms->BeginIO.RequestClear = true; + request_clear = true; // Shortcut: Select all (CTRL+A) if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) - ms->BeginIO.RequestSelectAll = true; + request_select_all = true; } + if (request_clear || request_select_all) + ms->BeginIO.Requests.push_back(ImGuiSelectionRequest(request_select_all ? ImGuiSelectionRequestType_SelectAll : ImGuiSelectionRequestType_Clear)); + ms->LoopRequestClear = request_clear; + ms->LoopRequestSelectAll = request_select_all; + if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) DebugLogMultiSelectRequests("BeginMultiSelect", &ms->BeginIO); @@ -7220,8 +7231,8 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (IsWindowHovered() && g.HoveredId == 0) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { - ms->EndIO.RequestClear = true; - ms->EndIO.RequestSelectAll = ms->EndIO.RequestSetRange = false; + ms->EndIO.Requests.resize(0); + ms->EndIO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); } // Unwind @@ -7273,9 +7284,9 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags // Apply Clear/SelectAll requests requested by BeginMultiSelect(). // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. // If you are using a clipper (aka not submitting every element of the list) you need to process the Clear/SelectAll request after calling BeginMultiSelect() - if (ms->BeginIO.RequestClear) + if (ms->LoopRequestClear) selected = false; - else if (ms->BeginIO.RequestSelectAll) + else if (ms->LoopRequestSelectAll) selected = true; // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) @@ -7396,22 +7407,28 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) //---------------------------------------------------------------------------------------- const ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; + bool request_clear = false; if (is_singleselect) - ms->EndIO.RequestClear = true; + request_clear = true; else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl) - ms->EndIO.RequestClear = true; + request_clear = true; else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl) - ms->EndIO.RequestClear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. + request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. + if (request_clear) + { + ms->EndIO.Requests.resize(0); + ms->EndIO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); + } int range_direction; - ms->EndIO.RequestSetRange = true; + ImGuiSelectionRequest req(ImGuiSelectionRequestType_SetRange); if (is_shift && !is_singleselect) { // Shift+Arrow always select // Ctrl+Shift+Arrow copy source selection state (alrady stored by BeginMultiSelect() in RangeSelected) //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); ms->EndIO.RangeSrcItem = (storage->RangeSrcItem != ImGuiSelectionUserData_Invalid) ? storage->RangeSrcItem : item_data; - ms->EndIO.RangeSelected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; + req.RangeSelected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; range_direction = ms->RangeSrcPassedBy ? +1 : -1; } else @@ -7419,12 +7436,13 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Ctrl inverts selection, otherwise always select selected = is_ctrl ? !selected : true; ms->EndIO.RangeSrcItem = storage->RangeSrcItem = item_data; - ms->EndIO.RangeSelected = selected; + req.RangeSelected = selected; range_direction = +1; } ImGuiSelectionUserData range_dst_item = item_data; - ms->EndIO.RangeFirstItem = (range_direction > 0) ? ms->EndIO.RangeSrcItem : range_dst_item; - ms->EndIO.RangeLastItem = (range_direction > 0) ? range_dst_item : ms->EndIO.RangeSrcItem; + req.RangeFirstItem = (range_direction > 0) ? ms->EndIO.RangeSrcItem : range_dst_item; + req.RangeLastItem = (range_direction > 0) ? range_dst_item : ms->EndIO.RangeSrcItem; + ms->EndIO.Requests.push_back(req); } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) From c527cba470066440c6f42a872c8f553007bcafe2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 Sep 2023 15:05:38 +0200 Subject: [PATCH 0164/2359] MultiSelect: we don't need to ever write to EndIO.RangeSrcItem as this is not meant to be used. --- imgui_widgets.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 17162e393..a3f06f3ad 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7212,7 +7212,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->IsFocused) { // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here. - if (ms->BeginIO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here! (see tests) + if (ms->BeginIO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at begining of the scope (see tests for easy failure) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. ms->Storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; @@ -7427,7 +7427,8 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Shift+Arrow always select // Ctrl+Shift+Arrow copy source selection state (alrady stored by BeginMultiSelect() in RangeSelected) //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); - ms->EndIO.RangeSrcItem = (storage->RangeSrcItem != ImGuiSelectionUserData_Invalid) ? storage->RangeSrcItem : item_data; + if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) + storage->RangeSrcItem = item_data; req.RangeSelected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; range_direction = ms->RangeSrcPassedBy ? +1 : -1; } @@ -7435,13 +7436,13 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { // Ctrl inverts selection, otherwise always select selected = is_ctrl ? !selected : true; - ms->EndIO.RangeSrcItem = storage->RangeSrcItem = item_data; + storage->RangeSrcItem = item_data; req.RangeSelected = selected; range_direction = +1; } ImGuiSelectionUserData range_dst_item = item_data; - req.RangeFirstItem = (range_direction > 0) ? ms->EndIO.RangeSrcItem : range_dst_item; - req.RangeLastItem = (range_direction > 0) ? range_dst_item : ms->EndIO.RangeSrcItem; + req.RangeFirstItem = (range_direction > 0) ? storage->RangeSrcItem : range_dst_item; + req.RangeLastItem = (range_direction > 0) ? range_dst_item : storage->RangeSrcItem; ms->EndIO.Requests.push_back(req); } From 5941edd9f7ca30226a4afb3c8c23431d405f4f2a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 Sep 2023 15:28:04 +0200 Subject: [PATCH 0165/2359] MultiSelect: added support for recovery in ErrorCheckEndWindowRecover(). --- imgui.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index f932e4efa..ab9cc59b6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10068,6 +10068,11 @@ void ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, vo if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name); EndTabBar(); } + while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) + { + if (log_callback) log_callback(user_data, "Recovered from missing EndMultiSelect() in '%s'", window->Name); + EndMultiSelect(); + } while (window->DC.TreeDepth > 0) { if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name); From 33fc61a091e0c631594e7354491ce91c233e69ff Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 Sep 2023 15:34:25 +0200 Subject: [PATCH 0166/2359] MultiSelect: use a single ImGuiMultiSelectIO buffer. + using local storage var in EndMultiSelect(), should be no-op. --- imgui_internal.h | 6 +++--- imgui_widgets.cpp | 52 +++++++++++++++++++++++++++-------------------- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 9df3b01e8..63772203d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1720,10 +1720,10 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) ImGuiMultiSelectFlags Flags; ImGuiKeyChord KeyMods; - ImGuiMultiSelectIO BeginIO; // Requests are set and returned by BeginMultiSelect(), written to by user during the loop. - ImGuiMultiSelectIO EndIO; // Requests are set during the loop and returned by EndMultiSelect(). + ImGuiMultiSelectIO IO; // Requests are set and returned by BeginMultiSelect()/EndMultiSelect() + written to by user during the loop. bool LoopRequestClear; bool LoopRequestSelectAll; + bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. bool NavIdPassedBy; @@ -1732,7 +1732,7 @@ struct IMGUI_API ImGuiMultiSelectTempData //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectTempData() { Clear(); } - void Clear() { Storage = NULL; FocusScopeId = 0; Flags = 0; KeyMods = 0; BeginIO.Clear(); EndIO.Clear(); LoopRequestClear = LoopRequestSelectAll = IsFocused = IsSetRange = NavIdPassedBy = RangeSrcPassedBy = RangeDstPassedBy = false; } + void Clear() { Storage = NULL; FocusScopeId = 0; Flags = 0; KeyMods = 0; IO.Clear(); IsEndIO = LoopRequestClear = LoopRequestSelectAll = IsFocused = IsSetRange = NavIdPassedBy = RangeSrcPassedBy = RangeDstPassedBy = false; } }; // Persistent storage for multi-select (as long as selection is alive) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a3f06f3ad..edf48aa68 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7149,10 +7149,10 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) storage->Window = window; ms->Storage = storage; - // We want EndIO's NavIdItem/NavIdSelected to match BeginIO's one, so the value never changes after EndMultiSelect() - ms->BeginIO.RangeSrcItem = ms->EndIO.RangeSrcItem = storage->RangeSrcItem; - ms->BeginIO.NavIdItem = ms->EndIO.NavIdItem = storage->NavIdItem; - ms->BeginIO.NavIdSelected = ms->EndIO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; + ms->IO.RangeSrcItem = storage->RangeSrcItem; + ms->IO.NavIdItem = storage->NavIdItem; + ms->IO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; + ms->IO.Requests.resize(0); bool request_clear = false; bool request_select_all = false; @@ -7191,14 +7191,14 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) } if (request_clear || request_select_all) - ms->BeginIO.Requests.push_back(ImGuiSelectionRequest(request_select_all ? ImGuiSelectionRequestType_SelectAll : ImGuiSelectionRequestType_Clear)); + ms->IO.Requests.push_back(ImGuiSelectionRequest(request_select_all ? ImGuiSelectionRequestType_SelectAll : ImGuiSelectionRequestType_Clear)); ms->LoopRequestClear = request_clear; ms->LoopRequestSelectAll = request_select_all; if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) - DebugLogMultiSelectRequests("BeginMultiSelect", &ms->BeginIO); + DebugLogMultiSelectRequests("BeginMultiSelect", &ms->IO); - return &ms->BeginIO; + return &ms->IO; } // Return updated ImGuiMultiSelectIO structure. Lifetime: until EndFrame() or next BeginMultiSelect() call. @@ -7206,46 +7206,49 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() { ImGuiContext& g = *GImGui; ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; + ImGuiMultiSelectState* storage = ms->Storage; IM_ASSERT(ms->FocusScopeId == g.CurrentFocusScopeId); - IM_ASSERT(g.CurrentMultiSelect != NULL && ms->Storage->Window == g.CurrentWindow); + IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow); if (ms->IsFocused) { // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here. - if (ms->BeginIO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->BeginIO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at begining of the scope (see tests for easy failure) + if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at begining of the scope (see tests for easy failure) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. - ms->Storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; + storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; } - if (ms->NavIdPassedBy == false && ms->Storage->NavIdItem != ImGuiSelectionUserData_Invalid) + if (ms->NavIdPassedBy == false && storage->NavIdItem != ImGuiSelectionUserData_Invalid) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdItem.\n"); - ms->Storage->NavIdItem = ImGuiSelectionUserData_Invalid; - ms->Storage->NavIdSelected = -1; + storage->NavIdItem = ImGuiSelectionUserData_Invalid; + storage->NavIdSelected = -1; } } + if (ms->IsEndIO == false) + ms->IO.Requests.resize(0); + // Clear selection when clicking void? // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickWindowVoid) if (IsWindowHovered() && g.HoveredId == 0) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { - ms->EndIO.Requests.resize(0); - ms->EndIO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); + ms->IO.Requests.resize(0); + ms->IO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); } // Unwind ms->FocusScopeId = 0; ms->Flags = ImGuiMultiSelectFlags_None; - ms->BeginIO.Clear(); // Invalidate contents of BeginMultiSelect() to enforce scope. PopFocusScope(); g.CurrentMultiSelect = NULL; if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) - DebugLogMultiSelectRequests("EndMultiSelect", &ms->EndIO); + DebugLogMultiSelectRequests("EndMultiSelect", &ms->IO); - return &ms->EndIO; + return &ms->IO; } void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data) @@ -7260,7 +7263,7 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d { // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping) g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect; - if (ms->BeginIO.RangeSrcItem == selection_user_data) + if (ms->IO.RangeSrcItem == selection_user_data) ms->RangeSrcPassedBy = true; } else @@ -7357,6 +7360,11 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) storage->RangeSrcItem = item_data; storage->RangeSelected = selected; // Will be updated at the end of this function anyway. } + if (ms->IsEndIO == false) + { + ms->IO.Requests.resize(0); + ms->IsEndIO = true; + } // Auto-select as you navigate a list if (g.NavJustMovedToId == id) @@ -7416,8 +7424,8 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. if (request_clear) { - ms->EndIO.Requests.resize(0); - ms->EndIO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); + ms->IO.Requests.resize(0); + ms->IO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); } int range_direction; @@ -7443,7 +7451,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiSelectionUserData range_dst_item = item_data; req.RangeFirstItem = (range_direction > 0) ? storage->RangeSrcItem : range_dst_item; req.RangeLastItem = (range_direction > 0) ? range_dst_item : storage->RangeSrcItem; - ms->EndIO.Requests.push_back(req); + ms->IO.Requests.push_back(req); } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) From 3d41994a6326b113fa51dd7b04237c68e06b3ee4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Sep 2023 14:24:23 +0200 Subject: [PATCH 0167/2359] MultiSelect: simplify clearing ImGuiMultiSelectTempData. --- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 63772203d..9bb378f23 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1716,11 +1716,11 @@ struct ImGuiOldColumns // Temporary storage for multi-select struct IMGUI_API ImGuiMultiSelectTempData { + ImGuiMultiSelectIO IO; // MUST BE FIRST FIELD. Requests are set and returned by BeginMultiSelect()/EndMultiSelect() + written to by user during the loop. ImGuiMultiSelectState* Storage; ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) ImGuiMultiSelectFlags Flags; ImGuiKeyChord KeyMods; - ImGuiMultiSelectIO IO; // Requests are set and returned by BeginMultiSelect()/EndMultiSelect() + written to by user during the loop. bool LoopRequestClear; bool LoopRequestSelectAll; bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. @@ -1732,7 +1732,7 @@ struct IMGUI_API ImGuiMultiSelectTempData //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectTempData() { Clear(); } - void Clear() { Storage = NULL; FocusScopeId = 0; Flags = 0; KeyMods = 0; IO.Clear(); IsEndIO = LoopRequestClear = LoopRequestSelectAll = IsFocused = IsSetRange = NavIdPassedBy = RangeSrcPassedBy = RangeDstPassedBy = false; } + void Clear() { size_t io_sz = sizeof(IO); IO.Clear(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO }; // Persistent storage for multi-select (as long as selection is alive) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index edf48aa68..500be32f1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7129,6 +7129,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) ImGuiWindow* window = g.CurrentWindow; ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[0]; IM_ASSERT(g.CurrentMultiSelect == NULL); // No recursion allowed yet (we could allow it if we deem it useful) + IM_STATIC_ASSERT(offsetof(ImGuiMultiSelectTempData, IO) == 0); // Clear() relies on that. g.CurrentMultiSelect = ms; // FIXME: BeginFocusScope() From bf017954830bc664fb07380b09e5ca1cf7fcf337 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 Sep 2023 17:21:19 +0200 Subject: [PATCH 0168/2359] Demo: Assets Browser: add hit spacing, requierd for box-select patterns. --- imgui_demo.cpp | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 770eb3c9d..9ae3c68cf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3456,7 +3456,8 @@ static void ShowDemoWindowMultiSelect() // Drag and Drop if (use_drag_drop && ImGui::BeginDragDropSource()) { - // Write payload with full selection OR single unselected item (only possible with ImGuiMultiSelectFlags_SelectOnClickRelease) + // Consider payload to be full selection OR single unselected item. + // (the later is only possible when using ImGuiMultiSelectFlags_SelectOnClickRelease) if (ImGui::GetDragDropPayload() == NULL) { ImVector payload_items; @@ -9690,8 +9691,10 @@ struct ExampleAssetsBrowser { // Options bool ShowTypeOverlay = true; + bool AllowDragUnselected = false; float IconSize = 32.0f; - int IconSpacing = 7; + int IconSpacing = 10; + int IconHitSpacing = 4; // Increase hit-spacing if you want to make it possible to clear or box-select from gaps. Some spacing is required to able to amend with Shift+box-select. Value is small in Explorer. bool StretchSpacing = true; // State @@ -9751,9 +9754,13 @@ struct ExampleAssetsBrowser ImGui::SeparatorText("Contents"); ImGui::Checkbox("Show Type Overlay", &ShowTypeOverlay); + ImGui::SeparatorText("Selection Behavior"); + ImGui::Checkbox("Allow dragging unselected item", &AllowDragUnselected); + ImGui::SeparatorText("Layout"); ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f"); ImGui::SliderInt("Icon Spacing", &IconSpacing, 0, 32); + ImGui::SliderInt("Icon Hit Spacing", &IconHitSpacing, 0, 32); ImGui::Checkbox("Stretch Spacing", &StretchSpacing); ImGui::PopItemWidth(); ImGui::EndMenu(); @@ -9820,6 +9827,9 @@ struct ExampleAssetsBrowser // Multi-select ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickWindowVoid; + if (AllowDragUnselected) + ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags); ExampleSelectionAdapter selection_adapter; selection_adapter.Data = this; @@ -9830,7 +9840,8 @@ struct ExampleAssetsBrowser // But it is necessary for two reasons: // - Selectables uses it by default to visually fill the space between two items. // - The vertical spacing would be measured by Clipper to calculate line height if we didn't provide it explicitly (here we do). - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(item_spacing, item_spacing)); + const float selectable_spacing = IM_MAX(floorf(item_spacing) - IconHitSpacing, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(selectable_spacing, selectable_spacing)); // Rendering parameters const ImU32 icon_bg_color = IM_COL32(48, 48, 48, 128); @@ -9875,8 +9886,13 @@ struct ExampleAssetsBrowser // Drag and drop if (ImGui::BeginDragDropSource()) { - ImGui::SetDragDropPayload("ASSETS_BROWSER_ITEMS", "Dummy", 5); - ImGui::Text("%d assets", Selection.Size); + // Consider payload to be full selection OR single unselected item + // (the later is only possible when using ImGuiMultiSelectFlags_SelectOnClickRelease) + int payload_size = item_is_selected ? Selection.Size : 1; + if (ImGui::GetDragDropPayload() == NULL) + ImGui::SetDragDropPayload("ASSETS_BROWSER_ITEMS", "Dummy", 5); // Dummy payload + + ImGui::Text("%d assets", payload_size); ImGui::EndDragDropSource(); } From 90305c57e43d57338c2743ecc1644f4ca8e5e368 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 Sep 2023 19:53:02 +0200 Subject: [PATCH 0169/2359] MultiSelect: (breaking) renamed ImGuiMultiSelectFlags_ClearOnClickWindowVoid -> ImGuiMultiSelectFlags_ClearOnClickVoid. Added ImGuiMultiSelectFlags_ScopeWindow, ImGuiMultiSelectFlags_ScopeRect. --- imgui.h | 9 +++++---- imgui_demo.cpp | 30 +++++++++++++++++++++++------- imgui_internal.h | 3 ++- imgui_widgets.cpp | 13 +++++++++++-- 4 files changed, 41 insertions(+), 14 deletions(-) diff --git a/imgui.h b/imgui.h index 2ce1f1983..53a51c42a 100644 --- a/imgui.h +++ b/imgui.h @@ -2734,10 +2734,11 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to use same code/logic is desired, but may not be very useful. ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to set RequestSelectAll ImGuiMultiSelectFlags_ClearOnEscape = 1 << 2, // Clear selection when pressing Escape while scope is focused. - ImGuiMultiSelectFlags_ClearOnClickWindowVoid= 1 << 3, // Clear selection when clicking on empty location within host window (use if BeginMultiSelect() covers a whole window) - //ImGuiMultiSelectFlags_ClearOnClickRectVoid= 1 << 4, // Clear selection when clicking on empty location within rectangle covered by selection scope (use if multiple BeginMultiSelect() are used in the same host window) - ImGuiMultiSelectFlags_SelectOnClick = 1 << 5, // Apply selection on mouse down when clicking on unselected item. (Default) - ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 6, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 3, // Clear selection when clicking on empty location within scope. + ImGuiMultiSelectFlags_ScopeWindow = 1 << 4, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if (use if BeginMultiSelect() covers a whole window. + ImGuiMultiSelectFlags_ScopeRect = 1 << 5, // Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. Use if multiple BeginMultiSelect() are used in the same host window. + ImGuiMultiSelectFlags_SelectOnClick = 1 << 7, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 8, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. }; // Multi-selection system diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9ae3c68cf..00b02eb08 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3289,17 +3289,25 @@ static void ShowDemoWindowMultiSelect() static ExampleSelection selections_data[SCOPES_COUNT]; ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection + // Use ImGuiMultiSelectFlags_ScopeRect to not affect other selections in same window. + static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ScopeRect | ImGuiMultiSelectFlags_ClearOnEscape;// | ImGuiMultiSelectFlags_ClearOnClickVoid; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) + flags &= ~ImGuiMultiSelectFlags_ScopeRect; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect)) + flags &= ~ImGuiMultiSelectFlags_ScopeWindow; + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); + for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++) { ExampleSelection* selection = &selections_data[selection_scope_n]; + + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + selection->ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); + ImGui::SeparatorText("Selection scope"); ImGui::Text("Selection size: %d/%d", selection->GetSize(), ITEMS_COUNT); ImGui::PushID(selection_scope_n); - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; // | ImGuiMultiSelectFlags_ClearOnClickRectVoid - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection->ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); - for (int n = 0; n < ITEMS_COUNT; n++) { char label[64]; @@ -3354,8 +3362,16 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickWindowVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickWindowVoid); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClickRelease", &flags, ImGuiMultiSelectFlags_SelectOnClickRelease); ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) + flags &= ~ImGuiMultiSelectFlags_ScopeRect; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect)) + flags &= ~ImGuiMultiSelectFlags_ScopeWindow; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClick", &flags, ImGuiMultiSelectFlags_SelectOnClick) && (flags & ImGuiMultiSelectFlags_SelectOnClick)) + flags &= ~ImGuiMultiSelectFlags_SelectOnClickRelease; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClickRelease", &flags, ImGuiMultiSelectFlags_SelectOnClickRelease) && (flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) + flags &= ~ImGuiMultiSelectFlags_SelectOnClick; + ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); // Initialize default list with 1000 items. static ImVector items; @@ -9826,7 +9842,7 @@ struct ExampleAssetsBrowser ImGui::SetCursorScreenPos(start_pos); // Multi-select - ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickWindowVoid; + ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickVoid; if (AllowDragUnselected) ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. diff --git a/imgui_internal.h b/imgui_internal.h index 9bb378f23..6f930aec4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1720,6 +1720,8 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiMultiSelectState* Storage; ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) ImGuiMultiSelectFlags Flags; + ImVec2 ScopeRectMin; + ImVec2 BackupCursorMaxPos; ImGuiKeyChord KeyMods; bool LoopRequestClear; bool LoopRequestSelectAll; @@ -1729,7 +1731,6 @@ struct IMGUI_API ImGuiMultiSelectTempData bool NavIdPassedBy; bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. - //ImRect Rect; // Extent of selection scope between BeginMultiSelect() / EndMultiSelect(), used by ImGuiMultiSelectFlags_ClearOnClickRectVoid. ImGuiMultiSelectTempData() { Clear(); } void Clear() { size_t io_sz = sizeof(IO); IO.Clear(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 500be32f1..dade5fb38 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7138,6 +7138,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) ms->FocusScopeId = id; ms->Flags = flags; ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId); + ms->BackupCursorMaxPos = window->DC.CursorMaxPos; + ms->ScopeRectMin = window->DC.CursorMaxPos = window->DC.CursorPos; PushFocusScope(ms->FocusScopeId); // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. @@ -7208,6 +7210,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() ImGuiContext& g = *GImGui; ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect; ImGuiMultiSelectState* storage = ms->Storage; + ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(ms->FocusScopeId == g.CurrentFocusScopeId); IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow); @@ -7230,17 +7233,23 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->IsEndIO == false) ms->IO.Requests.resize(0); + const ImRect scope_rect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin)); + const bool scope_hovered = (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) ? IsMouseHoveringRect(scope_rect.Min, scope_rect.Max) : IsWindowHovered(); + // Clear selection when clicking void? // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! - if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickWindowVoid) - if (IsWindowHovered() && g.HoveredId == 0) + if (scope_hovered && g.HoveredId == 0) + { + if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { ms->IO.Requests.resize(0); ms->IO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); } + } // Unwind + window->DC.CursorMaxPos = ImMax(ms->BackupCursorMaxPos, window->DC.CursorMaxPos); ms->FocusScopeId = 0; ms->Flags = ImGuiMultiSelectFlags_None; PopFocusScope(); From f904a6646c2b144c9b28e50b65cc66cd4c6f18b1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 29 Aug 2023 16:27:31 +0200 Subject: [PATCH 0170/2359] MultiSelect: Box-Select: added support for ImGuiMultiSelectFlags_BoxSelect. (v11) FIXME: broken on clipping demo. --- imgui.h | 13 ++++---- imgui_demo.cpp | 5 +-- imgui_internal.h | 16 +++++++-- imgui_widgets.cpp | 84 ++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 107 insertions(+), 11 deletions(-) diff --git a/imgui.h b/imgui.h index 53a51c42a..701d995dd 100644 --- a/imgui.h +++ b/imgui.h @@ -2733,12 +2733,13 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to use same code/logic is desired, but may not be very useful. ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to set RequestSelectAll - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 2, // Clear selection when pressing Escape while scope is focused. - ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 3, // Clear selection when clicking on empty location within scope. - ImGuiMultiSelectFlags_ScopeWindow = 1 << 4, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if (use if BeginMultiSelect() covers a whole window. - ImGuiMultiSelectFlags_ScopeRect = 1 << 5, // Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. Use if multiple BeginMultiSelect() are used in the same host window. - ImGuiMultiSelectFlags_SelectOnClick = 1 << 7, // Apply selection on mouse down when clicking on unselected item. (Default) - ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 8, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. + ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 4, // Clear selection when pressing Escape while scope is focused. + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 5, // Clear selection when clicking on empty location within scope. + ImGuiMultiSelectFlags_ScopeWindow = 1 << 6, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if (use if BeginMultiSelect() covers a whole window. + ImGuiMultiSelectFlags_ScopeRect = 1 << 7, // Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. Use if multiple BeginMultiSelect() are used in the same host window. + ImGuiMultiSelectFlags_SelectOnClick = 1 << 8, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 9, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. }; // Multi-selection system diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 00b02eb08..a97972648 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3299,14 +3299,13 @@ static void ShowDemoWindowMultiSelect() for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++) { + ImGui::PushID(selection_scope_n); ExampleSelection* selection = &selections_data[selection_scope_n]; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection->ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); ImGui::SeparatorText("Selection scope"); ImGui::Text("Selection size: %d/%d", selection->GetSize(), ITEMS_COUNT); - ImGui::PushID(selection_scope_n); for (int n = 0; n < ITEMS_COUNT; n++) { @@ -3325,6 +3324,7 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } + // See ShowExampleAppAssetsBrowser() if (ImGui::TreeNode("Multi-Select (tiled assets browser)")) { ImGui::BulletText("See 'Examples->Assets Browser' in menu"); @@ -3361,6 +3361,7 @@ static void ShowDemoWindowMultiSelect() ImGui::Checkbox("Show color button", &show_color_button); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) diff --git a/imgui_internal.h b/imgui_internal.h index 6f930aec4..2ce16fb1a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1722,6 +1722,10 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiMultiSelectFlags Flags; ImVec2 ScopeRectMin; ImVec2 BackupCursorMaxPos; + ImGuiID BoxSelectId; + ImRect BoxSelectRectCurr; // Selection rectangle in absolute coordinates (derived from Storage->BoxSelectStartPosRel + MousePos) + ImRect BoxSelectRectPrev; + ImGuiSelectionUserData BoxSelectLastitem; ImGuiKeyChord KeyMods; bool LoopRequestClear; bool LoopRequestSelectAll; @@ -1733,7 +1737,7 @@ struct IMGUI_API ImGuiMultiSelectTempData bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. ImGuiMultiSelectTempData() { Clear(); } - void Clear() { size_t io_sz = sizeof(IO); IO.Clear(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO + void Clear() { size_t io_sz = sizeof(IO); IO.Clear(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); BoxSelectLastitem = -1; } // Zero-clear except IO }; // Persistent storage for multi-select (as long as selection is alive) @@ -1747,8 +1751,15 @@ struct IMGUI_API ImGuiMultiSelectState ImGuiSelectionUserData RangeSrcItem; // ImGuiSelectionUserData NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) + bool BoxSelectActive; + bool BoxSelectStarting; + bool BoxSelectFromVoid; + ImGuiKeyChord BoxSelectKeyMods : 16; // Latched key-mods for box-select logic. + ImVec2 BoxSelectStartPosRel; // Start position in window-relative space (to support scrolling) + ImVec2 BoxSelectEndPosRel; // End position in window-relative space + ImGuiMultiSelectState() { Init(0); } - void Init(ImGuiID id) { Window = NULL; ID = id; LastFrameActive = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } + void Init(ImGuiID id) { Window = NULL; ID = id; LastFrameActive = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; BoxSelectActive = BoxSelectStarting = BoxSelectFromVoid = false; BoxSelectKeyMods = 0; } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT @@ -3087,6 +3098,7 @@ namespace ImGui inline ImRect WindowRectAbsToRel(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); } inline ImRect WindowRectRelToAbs(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); } inline ImVec2 WindowPosRelToAbs(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x + off.x, p.y + off.y); } + inline ImVec2 WindowPosAbsToRel(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x - off.x, p.y - off.y); } // Windows: Display Order and Focus Order IMGUI_API void FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags = 0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index dade5fb38..ec4f53744 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7103,6 +7103,8 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) //------------------------------------------------------------------------- // [SECTION] Widgets: Multi-Select support //------------------------------------------------------------------------- +// - DebugLogMultiSelectRequests() [Internal] +// - BoxSelectStart() [Internal] // - BeginMultiSelect() // - EndMultiSelect() // - SetNextItemSelectionUserData() @@ -7122,6 +7124,15 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe } } +static void BoxSelectStart(ImGuiMultiSelectState* storage, ImGuiSelectionUserData clicked_item) +{ + ImGuiContext& g = *GImGui; + storage->BoxSelectStarting = true; // Consider starting box-select. + storage->BoxSelectFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid); + storage->BoxSelectKeyMods = g.IO.KeyMods; + storage->BoxSelectStartPosRel = storage->BoxSelectEndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); +} + // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) { @@ -7193,6 +7204,38 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) request_select_all = true; } + // Box-select handling: update active state. + if (flags & ImGuiMultiSelectFlags_BoxSelect) + { + ms->BoxSelectId = GetID("##BoxSelect"); + KeepAliveID(ms->BoxSelectId); + + // BoxSelectStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. + if (storage->BoxSelectStarting && IsMouseDragPastThreshold(0)) + { + storage->BoxSelectActive = true; + storage->BoxSelectStarting = false; + SetActiveID(ms->BoxSelectId, window); + if (storage->BoxSelectFromVoid && (storage->BoxSelectKeyMods & ImGuiMod_Shift) == 0) + request_clear = true; + } + else if ((storage->BoxSelectStarting || storage->BoxSelectActive) && g.IO.MouseDown[0] == false) + { + storage->BoxSelectActive = storage->BoxSelectStarting = false; + if (g.ActiveId == ms->BoxSelectId) + ClearActiveID(); + } + if (storage->BoxSelectActive) + { + ImVec2 start_pos_abs = WindowPosRelToAbs(window, storage->BoxSelectStartPosRel); + ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, storage->BoxSelectEndPosRel); + ms->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); + ms->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); + ms->BoxSelectRectCurr.Min = ImMin(start_pos_abs, g.IO.MousePos); + ms->BoxSelectRectCurr.Max = ImMax(start_pos_abs, g.IO.MousePos); + } + } + if (request_clear || request_select_all) ms->IO.Requests.push_back(ImGuiSelectionRequest(request_select_all ? ImGuiSelectionRequestType_SelectAll : ImGuiSelectionRequestType_Clear)); ms->LoopRequestClear = request_clear; @@ -7228,6 +7271,15 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() storage->NavIdItem = ImGuiSelectionUserData_Invalid; storage->NavIdSelected = -1; } + + // Box-select: render selection rectangle + // FIXME-MULTISELECT: Scroll on box-select + if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && storage->BoxSelectActive) + { + ms->Storage->BoxSelectEndPosRel = WindowPosAbsToRel(window, g.IO.MousePos); + window->DrawList->AddRectFilled(ms->BoxSelectRectCurr.Min, ms->BoxSelectRectCurr.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling + window->DrawList->AddRect(ms->BoxSelectRectCurr.Min, ms->BoxSelectRectCurr.Max, GetColorU32(ImGuiCol_NavHighlight)); // FIXME-MULTISELECT: Styling + } } if (ms->IsEndIO == false) @@ -7240,6 +7292,10 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! if (scope_hovered && g.HoveredId == 0) { + if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) + if (!storage->BoxSelectActive && !storage->BoxSelectStarting && g.IO.MouseClickedCount[0] == 1) + BoxSelectStart(storage, ImGuiSelectionUserData_Invalid); + if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { @@ -7385,6 +7441,26 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = pressed = true; } + // Box-select handling + if (ms->Storage->BoxSelectActive) + { + const bool rect_overlap_curr = ms->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect); + const bool rect_overlap_prev = ms->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect); + if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr)) + { + selected = !selected; + ImGuiSelectionRequest req(ImGuiSelectionRequestType_SetRange); + req.RangeFirstItem = req.RangeLastItem = item_data; + req.RangeSelected = selected; + ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; + if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->RangeSelected == selected) + prev_req->RangeLastItem = item_data; // Merge span into same request + else + ms->IO.Requests.push_back(req); + } + ms->BoxSelectLastitem = item_data; + } + // Right-click handling: this could be moved at the Selectable() level. // FIXME-MULTISELECT: See https://github.com/ocornut/imgui/pull/5816 if (hovered && IsMouseClicked(1)) @@ -7407,6 +7483,12 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Alter selection if (pressed && (!enter_pressed || !selected)) { + // Box-select + ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; + if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) + if (selected == false && !storage->BoxSelectActive && !storage->BoxSelectStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) + BoxSelectStart(storage, item_data); + //---------------------------------------------------------------------------------------- // ACTION | Begin | Pressed/Activated | End //---------------------------------------------------------------------------------------- @@ -7424,7 +7506,6 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Mouse Pressed: Ctrl+Shift | n/a | Dst=item, Sel=!Sel => SetRange Src-Dst //---------------------------------------------------------------------------------------- - const ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; bool request_clear = false; if (is_singleselect) request_clear = true; @@ -7492,6 +7573,7 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) return; Text("RangeSrcItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), RangeSelected = %d", storage->RangeSrcItem, storage->RangeSrcItem, storage->RangeSelected); Text("NavIdItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), NavIdSelected = %d", storage->NavIdItem, storage->NavIdItem, storage->NavIdSelected); + Text("BoxSelect Starting = %d, Active %d", storage->BoxSelectStarting, storage->BoxSelectActive); TreePop(); #else IM_UNUSED(storage); From aa4d64be925da3575bce51111114d5cb0ebe5433 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Sep 2023 13:44:10 +0200 Subject: [PATCH 0171/2359] MultiSelect: Box-Select: added scroll support. --- imgui.h | 1 + imgui_demo.cpp | 3 ++- imgui_internal.h | 1 + imgui_widgets.cpp | 42 ++++++++++++++++++++++++++++++++++-------- 4 files changed, 38 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index 701d995dd..bb6ab85fc 100644 --- a/imgui.h +++ b/imgui.h @@ -2734,6 +2734,7 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to use same code/logic is desired, but may not be very useful. ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to set RequestSelectAll ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_NoBoxSelectScroll = 1 << 3, // Disable scrolling when box-selecting near edges of scope. ImGuiMultiSelectFlags_ClearOnEscape = 1 << 4, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 5, // Clear selection when clicking on empty location within scope. ImGuiMultiSelectFlags_ScopeWindow = 1 << 6, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if (use if BeginMultiSelect() covers a whole window. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a97972648..46ccf7dd7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3362,6 +3362,7 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoBoxSelectScroll", &flags, ImGuiMultiSelectFlags_NoBoxSelectScroll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) @@ -3372,7 +3373,7 @@ static void ShowDemoWindowMultiSelect() flags &= ~ImGuiMultiSelectFlags_SelectOnClickRelease; if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClickRelease", &flags, ImGuiMultiSelectFlags_SelectOnClickRelease) && (flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) flags &= ~ImGuiMultiSelectFlags_SelectOnClick; - ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); + ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); // Initialize default list with 1000 items. static ImVector items; diff --git a/imgui_internal.h b/imgui_internal.h index 2ce16fb1a..271946569 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -490,6 +490,7 @@ static inline int ImModPositive(int a, int b) static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; } +static inline float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x) { return ImSaturate((x - s0) / (s1 - s0)) * (d1 - d0) + d0; } static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } static inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } static inline float ImExponentialMovingAverage(float avg, float sample, int n) { avg -= avg / n; avg += sample / n; return avg; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ec4f53744..b8b7032aa 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7105,6 +7105,7 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) //------------------------------------------------------------------------- // - DebugLogMultiSelectRequests() [Internal] // - BoxSelectStart() [Internal] +// - BoxSelectScrollWithMouseDrag() [Internal] // - BeginMultiSelect() // - EndMultiSelect() // - SetNextItemSelectionUserData() @@ -7133,6 +7134,23 @@ static void BoxSelectStart(ImGuiMultiSelectState* storage, ImGuiSelectionUserDat storage->BoxSelectStartPosRel = storage->BoxSelectEndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); } +static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& r) +{ + ImGuiContext& g = *GImGui; + for (int n = 0; n < 2; n++) + { + float dist = (g.IO.MousePos[n] > r.Max[n]) ? g.IO.MousePos[n] - r.Max[n] : (g.IO.MousePos[n] < r.Min[n]) ? g.IO.MousePos[n] - r.Min[n] : 0.0f; + if (dist == 0.0f || (dist < 0.0f && window->Scroll[n] < 0.0f) || (dist > 0.0f && window->Scroll[n] >= window->ScrollMax[n])) + continue; + float speed_multiplier = ImLinearRemapClamp(g.FontSize, g.FontSize * 5.0f, 1.0f, 4.0f, ImAbs(dist)); // x1 to x4 depending on distance + float scroll_step = IM_ROUND(g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime); + if (n == 0) + ImGui::SetScrollX(window, window->Scroll[n] + scroll_step); + else + ImGui::SetScrollY(window, window->Scroll[n] + scroll_step); + } +} + // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) { @@ -7142,6 +7160,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) IM_ASSERT(g.CurrentMultiSelect == NULL); // No recursion allowed yet (we could allow it if we deem it useful) IM_STATIC_ASSERT(offsetof(ImGuiMultiSelectTempData, IO) == 0); // Clear() relies on that. g.CurrentMultiSelect = ms; + if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0) + flags |= ImGuiMultiSelectFlags_ScopeWindow; // FIXME: BeginFocusScope() const ImGuiID id = window->IDStack.back(); @@ -7257,6 +7277,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() IM_ASSERT(ms->FocusScopeId == g.CurrentFocusScopeId); IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow); + const ImRect scope_rect = (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) ? ImRect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin)) : window->InnerClipRect; if (ms->IsFocused) { // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here. @@ -7272,25 +7293,30 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() storage->NavIdSelected = -1; } - // Box-select: render selection rectangle - // FIXME-MULTISELECT: Scroll on box-select if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && storage->BoxSelectActive) { + // Box-select: render selection rectangle ms->Storage->BoxSelectEndPosRel = WindowPosAbsToRel(window, g.IO.MousePos); - window->DrawList->AddRectFilled(ms->BoxSelectRectCurr.Min, ms->BoxSelectRectCurr.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling - window->DrawList->AddRect(ms->BoxSelectRectCurr.Min, ms->BoxSelectRectCurr.Max, GetColorU32(ImGuiCol_NavHighlight)); // FIXME-MULTISELECT: Styling + ImRect box_select_r = ms->BoxSelectRectCurr; + box_select_r.ClipWith(scope_rect); + window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling + window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavHighlight)); // FIXME-MULTISELECT: Styling + + // Box-select: scroll + ImRect scroll_r = scope_rect; + scroll_r.Expand(g.Style.FramePadding); + if ((ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_NoBoxSelectScroll) == 0 && !scroll_r.Contains(g.IO.MousePos)) + BoxSelectScrollWithMouseDrag(window, scroll_r); } } if (ms->IsEndIO == false) ms->IO.Requests.resize(0); - const ImRect scope_rect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin)); - const bool scope_hovered = (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) ? IsMouseHoveringRect(scope_rect.Min, scope_rect.Max) : IsWindowHovered(); - // Clear selection when clicking void? // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! - if (scope_hovered && g.HoveredId == 0) + const bool scope_hovered = (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) ? scope_rect.Contains(g.IO.MousePos) : IsWindowHovered(); + if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0) { if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) if (!storage->BoxSelectActive && !storage->BoxSelectStarting && g.IO.MouseClickedCount[0] == 1) From b747d6fe591452c5d3e5c06be0c9a3ef4e97b4bc Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 6 Oct 2023 17:10:52 +0200 Subject: [PATCH 0172/2359] MultiSelect: Demo: rework and move selection adapter inside ExampleSelection. --- imgui_demo.cpp | 157 ++++++++++++++++++++++++------------------------- 1 file changed, 76 insertions(+), 81 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 46ccf7dd7..541039335 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2773,6 +2773,18 @@ static const char* ExampleNames[] = "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" }; +// [Advanced] Helper class to store multi-selection state, used by the BeginMultiSelect() demos. +// Provide an abstraction layer for the purpose of the demo showcasing different forms of underlying selection data. +// To store a single-selection: +// - You only need a single variable and don't need any of this! +// To store a multi-selection, in your real application you could: +// - A) Use external storage: e.g. std::set, std::vector, std::set, interval trees, etc. +// are generally appropriate. Even a large array of bool might work for you... +// This code here use ImGuiStorage (a simple key->value storage) as a std::set replacement to avoid external dependencies. +// - B) Or use intrusively stored selection (e.g. 'bool IsSelected' inside your object). +// - That means you cannot have multiple simultaneous views over your objects. +// - Some of our features requires you to provide the selection _size_, which with this specific strategy require additional work. +// - So we suggest using intrusive selection for multi-select is not really adequate. // Our multi-selection system doesn't make assumption about: // - how you want to identify items in multi-selection API? Indices(*) / Custom Identifiers / Pointers ? // - how you want to store persistent selection data? Indices / Custom Identifiers(*) / Pointers ? @@ -2780,44 +2792,28 @@ static const char* ExampleNames[] = // In this demo we: // - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) // - use a little extra indirection layer in order to abstract how persistent selection data is derived from an index. -// - in some cases we use Index as custom identifier, in some cases we read from some custom item data structure. +// - in some cases we use Index as custom identifier +// - in some cases we read an ID from some custom item data structure (this is closer to what you would do in your codebase) // Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. -// WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ExampleSelectionAdapter' INDIRECTION LOGIC. -// In theory, for maximum abstraction, this class could contains IndexToUserData() and UserDataToIndex() functions, +// WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THE UNNECESSARY 'AdapterIndexToStorageId()' INDIRECTION LOGIC. +// In theory, for maximum abstraction, this class could contains AdapterIndexToUserData() and AdapterUserDataToIndex() functions as well, // but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that for clarify. -struct ExampleSelectionAdapter -{ - void* Data = NULL; - ImGuiID (*IndexToStorage)(ExampleSelectionAdapter* self, int idx); // Function to convert item index to data stored in persistent selection - - ExampleSelectionAdapter() { SetupForDirectIndexes(); } - - // Example for the simplest case: Index==SelectionStorage (this adapter doesn't even need to use the item data field) - void SetupForDirectIndexes() { IndexToStorage = [](ExampleSelectionAdapter*, int idx) { return (ImGuiID)idx; }; } -}; - -// [Advanced] Helper class to store multi-selection state, used by the BeginMultiSelect() demos. -// Provide an abstraction layer for the purpose of the demo showcasing different forms of underlying selection data. -// To store a single-selection: -// - You only need a single variable and don't need any of this! -// To store a multi-selection, in your real application you could: -// - A) Use external storage: e.g. std::set, std::set, std::vector, interval trees, etc. -// are generally appropriate. Even a large array of bool might work for you... -// This code here use ImGuiStorage (a simple key->value storage) as a std::set replacement to avoid external dependencies. -// - B) Or use intrusively stored selection (e.g. 'bool IsSelected' inside your object). -// - It is simple, but it means you cannot have multiple simultaneous views over your objects. -// - Some of our features requires you to provide the selection _size_, which with this specific strategy require additional work: -// either you maintain it (which requires storage outside of objects) either you recompute (which may be costly for large sets). -// - So we suggest using intrusive selection for multi-select is not really adequate. struct ExampleSelection { // Data - ImGuiStorage Storage; // Selection set + ImGuiStorage Storage; // Selection set (think of this as similar to e.g. std::set) int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). bool QueueDeletion; // Request deleting selected items + // Adapter to convert item index to item identifier + // e.g. + // selection.AdapterData = (void*)my_items; + // selection.AdapterIndexToStorageId = [](ExampleSelection* s, int idx) { return ((MyItems**)s->AdapterData)[idx]->ID; }; + void* AdapterData; + ImGuiID (*AdapterIndexToStorageId)(ExampleSelection* self, int idx); + // Functions - ExampleSelection() { Clear(); } + ExampleSelection() { Clear(); AdapterData = NULL; AdapterIndexToStorageId = [](ExampleSelection*, int idx) { return (ImGuiID)idx; };} void Clear() { Storage.Data.resize(0); Size = 0; QueueDeletion = false; } void Swap(ExampleSelection& rhs) { Storage.Data.swap(rhs.Storage.Data); } bool Contains(ImGuiID key) const { return Storage.GetInt(key, 0) != 0; } @@ -2828,8 +2824,8 @@ struct ExampleSelection void DebugTooltip() { if (ImGui::BeginTooltip()) { for (auto& pair : Storage.Data) if (pair.val_i) ImGui::Text("0x%03X (%d)", pair.key, pair.key); ImGui::EndTooltip(); } } // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). - // - Must be done in this order! Clear->SelectAll->SetRange. Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. - // - Honoring RequestSetRange requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. + // - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. + // - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. // - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection. // - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform // a lookup in order to have some way to iterate/interpolate between two items. @@ -2844,34 +2840,34 @@ struct ExampleSelection // if (req.Type == ImGuiSelectionRequestType_SelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } // if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } // } - void ApplyRequests(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, int items_count) + void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) { - IM_ASSERT(adapter->IndexToStorage != NULL); + IM_ASSERT(AdapterIndexToStorageId != NULL); for (ImGuiSelectionRequest& req : ms_io->Requests) { - if (req.Type == ImGuiSelectionRequestType_Clear || req.Type == ImGuiSelectionRequestType_SelectAll) + if (req.Type == ImGuiSelectionRequestType_Clear) Clear(); if (req.Type == ImGuiSelectionRequestType_SelectAll) { + Storage.Data.resize(0); Storage.Data.reserve(items_count); for (int idx = 0; idx < items_count; idx++) - AddItem(adapter->IndexToStorage(adapter, idx)); + AddItem(AdapterIndexToStorageId(this, idx)); } if (req.Type == ImGuiSelectionRequestType_SetRange) for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) - UpdateItem(adapter->IndexToStorage(adapter, idx), req.RangeSelected); + UpdateItem(AdapterIndexToStorageId(this, idx), req.RangeSelected); } } // Find which item should be Focused after deletion. - // We output an index in the before-deletion-items list, that user will call SetKeyboardFocusHere() on. + // Call _before_ item submission. Retunr an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it. // The subsequent ApplyDeletionPostLoop() code will use it to apply Selection. // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. // - We don't actually manipulate the ImVector<> here, only in ApplyDeletionPostLoop(), but using similar API for consistency and flexibility. // - Important: Deletion only works if the underlying ImGuiID for your items are stable: aka not depend on their index, but on e.g. item id/ptr. // FIXME-MULTISELECT: Doesn't take account of the possibility focus target will be moved during deletion. Need refocus or offset. - template - int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, ImVector& items) + int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, int items_count) { QueueDeletion = false; @@ -2884,13 +2880,13 @@ struct ExampleSelection } // If focused item is selected: land on first unselected item after focused item. - for (int idx = focused_idx + 1; idx < items.Size; idx++) - if (!Contains(adapter->IndexToStorage(adapter, idx))) + for (int idx = focused_idx + 1; idx < items_count; idx++) + if (!Contains(AdapterIndexToStorageId(this, idx))) return idx; // If focused item is selected: otherwise return last unselected item before focused item. - for (int idx = IM_MIN(focused_idx, items.Size) - 1; idx >= 0; idx--) - if (!Contains(adapter->IndexToStorage(adapter, idx))) + for (int idx = IM_MIN(focused_idx, items_count) - 1; idx >= 0; idx--) + if (!Contains(AdapterIndexToStorageId(this, idx))) return idx; return -1; @@ -2900,7 +2896,7 @@ struct ExampleSelection // - Call after EndMultiSelect() // - We cannot provide this logic in core Dear ImGui because we don't have access to your items, nor to selection data. template - void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ExampleSelectionAdapter* adapter, ImVector& items, int item_curr_idx_to_select) + void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ImVector& items, int item_curr_idx_to_select) { // Rewrite item list (delete items) + convert old selection index (before deletion) to new selection index (after selection). // If NavId was not part of selection, we will stay on same item. @@ -2909,7 +2905,7 @@ struct ExampleSelection int item_next_idx_to_select = -1; for (int idx = 0; idx < items.Size; idx++) { - if (!Contains(adapter->IndexToStorage(adapter, idx))) + if (!Contains(AdapterIndexToStorageId(this, idx))) new_items.push_back(items[idx]); if (item_curr_idx_to_select == idx) item_next_idx_to_select = new_items.Size - 1; @@ -2919,7 +2915,7 @@ struct ExampleSelection // Update selection Clear(); if (item_next_idx_to_select != -1 && ms_io->NavIdSelected) - AddItem(adapter->IndexToStorage(adapter, item_next_idx_to_select)); + AddItem(AdapterIndexToStorageId(this, item_next_idx_to_select)); } }; @@ -2959,10 +2955,9 @@ struct ExampleDualListBox void ApplySelectionRequests(ImGuiMultiSelectIO* ms_io, int side) { // In this example we store item id in selection (instead of item index) - ExampleSelectionAdapter adapter; - adapter.Data = Items[side].Data; - adapter.IndexToStorage = [](ExampleSelectionAdapter* self, int idx) { return (ImGuiID)((ImGuiID*)self->Data)[idx]; }; - Selections[side].ApplyRequests(ms_io, &adapter, Items[side].Size); + Selections[side].AdapterData = Items[side].Data; + Selections[side].AdapterIndexToStorageId = [](ExampleSelection* self, int idx) { ImGuiID* items = (ImGuiID*)self->AdapterData; return items[idx]; }; + Selections[side].ApplyRequests(ms_io, Items[side].Size); } static int IMGUI_CDECL CompareItemsByValue(const void* lhs, const void* rhs) { @@ -3111,8 +3106,8 @@ static void ShowDemoWindowMultiSelect() IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); if (ImGui::TreeNode("Multi-Select")) { + // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection static ExampleSelection selection; - ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Tips: Use 'Debug Log->Selection' to see selection requests as they happen."); @@ -3129,7 +3124,7 @@ static void ShowDemoWindowMultiSelect() { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection.ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); + selection.ApplyRequests(ms_io, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) { @@ -3141,7 +3136,7 @@ static void ShowDemoWindowMultiSelect() } ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); + selection.ApplyRequests(ms_io, ITEMS_COUNT); ImGui::EndListBox(); } @@ -3152,8 +3147,8 @@ static void ShowDemoWindowMultiSelect() IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with clipper)"); if (ImGui::TreeNode("Multi-Select (with clipper)")) { + // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection static ExampleSelection selection; - ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Added features:"); ImGui::BulletText("Using ImGuiListClipper."); @@ -3164,7 +3159,7 @@ static void ShowDemoWindowMultiSelect() { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection.ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); + selection.ApplyRequests(ms_io, ITEMS_COUNT); ImGuiListClipper clipper; clipper.Begin(ITEMS_COUNT); @@ -3183,7 +3178,7 @@ static void ShowDemoWindowMultiSelect() } ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); + selection.ApplyRequests(ms_io, ITEMS_COUNT); ImGui::EndListBox(); } @@ -3203,9 +3198,9 @@ static void ShowDemoWindowMultiSelect() { // Intentionally separating items data from selection data! // But you may decide to store selection data inside your item (aka intrusive storage). + // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection static ImVector items; static ExampleSelection selection; - ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Adding features:"); ImGui::BulletText("Dynamic list with Delete key support."); @@ -3230,7 +3225,7 @@ static void ShowDemoWindowMultiSelect() { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection.ApplyRequests(ms_io, &selection_adapter, items.Size); + selection.ApplyRequests(ms_io, items.Size); // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. @@ -3238,7 +3233,7 @@ static void ShowDemoWindowMultiSelect() const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); int item_curr_idx_to_focus = -1; if (want_delete) - item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, &selection_adapter, items); + item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, items.Size); for (int n = 0; n < items.Size; n++) { @@ -3255,9 +3250,9 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, &selection_adapter, items.Size); + selection.ApplyRequests(ms_io, items.Size); if (want_delete) - selection.ApplyDeletionPostLoop(ms_io, &selection_adapter, items, item_curr_idx_to_focus); + selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus); ImGui::EndListBox(); } @@ -3284,10 +3279,10 @@ static void ShowDemoWindowMultiSelect() IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (multiple scopes)"); if (ImGui::TreeNode("Multi-Select (multiple scopes)")) { + // Use default select: Pass index to SetNextItemSelectionUserData(), store index in Selection const int SCOPES_COUNT = 3; const int ITEMS_COUNT = 8; // Per scope static ExampleSelection selections_data[SCOPES_COUNT]; - ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection // Use ImGuiMultiSelectFlags_ScopeRect to not affect other selections in same window. static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ScopeRect | ImGuiMultiSelectFlags_ClearOnEscape;// | ImGuiMultiSelectFlags_ClearOnClickVoid; @@ -3302,7 +3297,7 @@ static void ShowDemoWindowMultiSelect() ImGui::PushID(selection_scope_n); ExampleSelection* selection = &selections_data[selection_scope_n]; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection->ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); + selection->ApplyRequests(ms_io, ITEMS_COUNT); ImGui::SeparatorText("Selection scope"); ImGui::Text("Selection size: %d/%d", selection->GetSize(), ITEMS_COUNT); @@ -3318,7 +3313,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection->ApplyRequests(ms_io, &selection_adapter, ITEMS_COUNT); + selection->ApplyRequests(ms_io, ITEMS_COUNT); ImGui::PopID(); } ImGui::TreePop(); @@ -3376,11 +3371,11 @@ static void ShowDemoWindowMultiSelect() ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); // Initialize default list with 1000 items. + // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection static ImVector items; static int items_next_id = 0; if (items_next_id == 0) { for (int n = 0; n < 1000; n++) { items.push_back(items_next_id++); } } static ExampleSelection selection; - ExampleSelectionAdapter selection_adapter; // Use default: Pass index to SetNextItemSelectionUserData(), store index in Selection ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); @@ -3393,14 +3388,14 @@ static void ShowDemoWindowMultiSelect() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - selection.ApplyRequests(ms_io, &selection_adapter, items.Size); + selection.ApplyRequests(ms_io, items.Size); // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); int item_curr_idx_to_focus = -1; if (want_delete) - item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, &selection_adapter, items); + item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, items.Size); if (show_in_table) { @@ -3539,9 +3534,9 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, &selection_adapter, items.Size); + selection.ApplyRequests(ms_io, items.Size); if (want_delete) - selection.ApplyDeletionPostLoop(ms_io, &selection_adapter, items, item_curr_idx_to_focus); + selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus); if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); @@ -9667,10 +9662,10 @@ void ShowExampleAppDocuments(bool* p_open) struct ExampleAsset { - int ID; + ImGuiID ID; int Type; - ExampleAsset(int id, int type) { ID = id; Type = type; } + ExampleAsset(ImGuiID id, int type) { ID = id; Type = type; } static const ImGuiTableSortSpecs* s_current_sort_specs; @@ -9692,7 +9687,7 @@ struct ExampleAsset const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n]; int delta = 0; if (sort_spec->ColumnIndex == 0) - delta = (a->ID - b->ID); + delta = ((int)a->ID - (int)b->ID); else if (sort_spec->ColumnIndex == 1) delta = (a->Type - b->Type); if (delta > 0) @@ -9700,7 +9695,7 @@ struct ExampleAsset if (delta < 0) return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; } - return (a->ID - b->ID); + return ((int)a->ID - (int)b->ID); } }; const ImGuiTableSortSpecs* ExampleAsset::s_current_sort_specs = NULL; @@ -9718,7 +9713,7 @@ struct ExampleAssetsBrowser // State ImVector Items; ExampleSelection Selection; - int NextItemId = 0; + ImGuiID NextItemId = 0; bool SortDirty = false; float ZoomWheelAccum = 0.0f; @@ -9847,12 +9842,12 @@ struct ExampleAssetsBrowser ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickVoid; if (AllowDragUnselected) ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags); - ExampleSelectionAdapter selection_adapter; - selection_adapter.Data = this; - selection_adapter.IndexToStorage = [](ExampleSelectionAdapter* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->Data; return (ImGuiID)self->Items[idx].ID; }; - Selection.ApplyRequests(ms_io, &selection_adapter, Items.Size); + + // Use custom selection adapter: store ID in selection (recommended) + Selection.AdapterData = this; + Selection.AdapterIndexToStorageId = [](ExampleSelection* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->AdapterData; return self->Items[idx].ID; }; + Selection.ApplyRequests(ms_io, Items.Size); // Altering ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()... // But it is necessary for two reasons: @@ -9881,7 +9876,7 @@ struct ExampleAssetsBrowser for (int item_idx = item_min_idx_for_current_line; item_idx < item_max_idx_for_current_line; ++item_idx) { ExampleAsset* item_data = &Items[item_idx]; - ImGui::PushID(item_data->ID); + ImGui::PushID((int)item_data->ID); // Position item ImVec2 pos = ImVec2(start_pos.x + (item_idx % column_count) * (item_size.x + item_spacing), start_pos.y + (line_idx * line_height)); @@ -9946,7 +9941,7 @@ struct ExampleAssetsBrowser ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing ms_io = ImGui::EndMultiSelect(); - Selection.ApplyRequests(ms_io, &selection_adapter, Items.Size); + Selection.ApplyRequests(ms_io, Items.Size); // FIXME-MULTISELECT: Find a way to expose this in public API. This currently requires "imgui_internal.h" //ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); From 0af6fbb51d5797b9245e97ed3d061917a296302b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 26 Oct 2023 17:20:33 +0200 Subject: [PATCH 0173/2359] MultiSelect: added support for nested/stacked BeginMultiSelect(). Mimicking table logic, reusing amortized buffers. --- imgui.cpp | 3 +++ imgui.h | 3 +++ imgui_internal.h | 6 ++++-- imgui_widgets.cpp | 14 +++++++++----- 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ab9cc59b6..3128892f0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3819,6 +3819,7 @@ void ImGui::Shutdown() g.DrawChannelsTempMergeBuffer.clear(); g.MultiSelectStorage.Clear(); + g.MultiSelectTempData.clear_destruct(); g.ClipboardHandlerData.clear(); g.MenusIdSubmittedThisFrame.clear(); @@ -3930,6 +3931,8 @@ void ImGui::GcCompactTransientMiscBuffers() ImGuiContext& g = *GImGui; g.ItemFlagsStack.clear(); g.GroupStack.clear(); + g.MultiSelectTempDataStacked = 0; + g.MultiSelectTempData.clear_destruct(); TableGcCompactSettings(); } diff --git a/imgui.h b/imgui.h index bb6ab85fc..31b6bcafa 100644 --- a/imgui.h +++ b/imgui.h @@ -2811,6 +2811,9 @@ struct ImGuiSelectionRequest ImGuiSelectionRequest(ImGuiSelectionRequestType type = ImGuiSelectionRequestType_None) { Type = type; RangeSelected = false; RangeFirstItem = RangeLastItem = (ImGuiSelectionUserData)-1; } }; +// Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). +// Read the large comments block above for details. +// Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). struct ImGuiMultiSelectIO { ImVector Requests; // ms:w, app:r / ms:w app:r // Requests diff --git a/imgui_internal.h b/imgui_internal.h index 271946569..8062edad8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2200,8 +2200,9 @@ struct ImGuiContext ImVector ShrinkWidthBuffer; // Multi-Select state - ImGuiMultiSelectTempData* CurrentMultiSelect; // FIXME-MULTISELECT: We currently don't support recursing/stacking multi-select - ImGuiMultiSelectTempData MultiSelectTempData[1]; + ImGuiMultiSelectTempData* CurrentMultiSelect; + int MultiSelectTempDataStacked; // Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) + ImVector MultiSelectTempData; ImPool MultiSelectStorage; // Hover Delay system @@ -2445,6 +2446,7 @@ struct ImGuiContext TablesTempDataStacked = 0; CurrentTabBar = NULL; CurrentMultiSelect = NULL; + MultiSelectTempDataStacked = 0; HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0; HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b8b7032aa..a20ca6b4b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7156,8 +7156,10 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[0]; - IM_ASSERT(g.CurrentMultiSelect == NULL); // No recursion allowed yet (we could allow it if we deem it useful) + + if (++g.MultiSelectTempDataStacked > g.MultiSelectTempData.Size) + g.MultiSelectTempData.resize(g.MultiSelectTempDataStacked, ImGuiMultiSelectTempData()); + ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1]; IM_STATIC_ASSERT(offsetof(ImGuiMultiSelectTempData, IO) == 0); // Clear() relies on that. g.CurrentMultiSelect = ms; if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0) @@ -7276,6 +7278,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(ms->FocusScopeId == g.CurrentFocusScopeId); IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow); + IM_ASSERT(g.MultiSelectTempDataStacked > 0 && &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] == g.CurrentMultiSelect); const ImRect scope_rect = (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) ? ImRect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin)) : window->InnerClipRect; if (ms->IsFocused) @@ -7332,14 +7335,15 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() // Unwind window->DC.CursorMaxPos = ImMax(ms->BackupCursorMaxPos, window->DC.CursorMaxPos); - ms->FocusScopeId = 0; - ms->Flags = ImGuiMultiSelectFlags_None; PopFocusScope(); - g.CurrentMultiSelect = NULL; if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) DebugLogMultiSelectRequests("EndMultiSelect", &ms->IO); + ms->FocusScopeId = 0; + ms->Flags = ImGuiMultiSelectFlags_None; + g.CurrentMultiSelect = (--g.MultiSelectTempDataStacked > 0) ? &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] : NULL; + return &ms->IO; } From e0282347db70bf6817990dd114e9b20d80ebc658 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 1 Dec 2023 15:03:43 +0100 Subject: [PATCH 0174/2359] MultiSelect: remove ImGuiSelectionRequest/ImGuiMultiSelectIO details from public api to reduce confusion + comments. --- imgui.h | 56 +++++++++++++++++++++-------------------------- imgui_internal.h | 3 ++- imgui_widgets.cpp | 24 ++++++++++---------- 3 files changed, 40 insertions(+), 43 deletions(-) diff --git a/imgui.h b/imgui.h index 31b6bcafa..5f59d5ce9 100644 --- a/imgui.h +++ b/imgui.h @@ -2753,18 +2753,17 @@ enum ImGuiMultiSelectFlags_ // - In the spirit of Dear ImGui design, your code owns actual selection data. // This is designed to allow all kinds of selection storage you may use in your application: // e.g. set/map/hash (store only selected items), instructive selection (store a bool inside each object), -// external array (store an array in your view data, next to your objects), or other structures (store indices -// in an interval tree), etc. +// external array (store an array in your view data, next to your objects) etc. // - The work involved to deal with multi-selection differs whether you want to only submit visible items and // clip others, or submit all items regardless of their visibility. Clipping items is more efficient and will -// allow you to deal with large lists (1k~100k items) with no performance penalty, but requires a little more -// work on the code. -// For small selection set (<100 items), you might want to not bother with using the clipper, as the cost -// should be negligible (as least on Dear ImGui side). +// allow you to deal with large lists (1k~100k items). See "Usage flow" section below for details. // If you are not sure, always start without clipping! You can work your way to the optimized version afterwards. +// About ImGuiSelectionBasicStorage: +// - This is an optional helper to store a selection state and apply selection requests. +// - It is used by our demos and provided as a convenience if you want to quickly implement multi-selection. // About ImGuiSelectionUserData: // - This is your application-defined identifier in a selection set: -// - For each item is submitted by your calls to SetNextItemSelectionUserData(). +// - For each item is it submitted by your call to SetNextItemSelectionUserData(). // - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. // - Most applications will store an object INDEX, hence the chosen name and type. // Storing an integer index is the easiest thing to do, as RequestSetRange requests will give you two end-points @@ -2773,8 +2772,7 @@ enum ImGuiMultiSelectFlags_ // that you identify items by indices. It never attempt to iterate/interpolate between 2 ImGuiSelectionUserData values. // - As most users will want to cast this to integer, for convenience and to reduce confusion we use ImS64 instead // of void*, being syntactically easier to downcast. But feel free to reinterpret_cast a pointer into this. -// - You may store another type of (e.g. an data) but this may make your lookups and the interpolation between -// two values more cumbersome. +// - You may store another type as long as you can interpolate between two values. // - If you need to wrap this API for another language/framework, feel free to expose this as 'int' if simpler. // Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. @@ -2786,8 +2784,8 @@ enum ImGuiMultiSelectFlags_ // If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. // However it is perfectly fine to honor all steps even if you don't use a clipper. // Advanced: -// - Deletion: If you need to handle items deletion a little more work if needed for post-deletion focus and scrolling to be correct. -// refer to 'Demo->Widgets->Selection State' for demos supporting deletion. +// - Deletion: If you need to handle items deletion: more work if needed for post-deletion focus and scrolling to be correct. +// Refer to 'Demo->Widgets->Selection State' for demos supporting deletion. enum ImGuiSelectionRequestType { @@ -2797,33 +2795,29 @@ enum ImGuiSelectionRequestType ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items based on 'bool RangeSelected'. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. }; -// List of requests stored in ImGuiMultiSelectIO -// - Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. -// - Some fields are only necessary if your list is dynamic and allows deletion (handling deletion and getting "post-deletion" state right is shown in the demo) -// - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. struct ImGuiSelectionRequest { - ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r - bool RangeSelected; // / ms:w, app:r // Parameter for SetRange request (true = select range, false = unselect range) - ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) - ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) - - ImGuiSelectionRequest(ImGuiSelectionRequestType type = ImGuiSelectionRequestType_None) { Type = type; RangeSelected = false; RangeFirstItem = RangeLastItem = (ImGuiSelectionUserData)-1; } + //------------------------------------------// BeginMultiSelect / EndMultiSelect + ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. + bool RangeSelected; // / ms:w, app:r // Parameter for SetRange request (true = select range, false = unselect range) + ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) + ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) }; // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). -// Read the large comments block above for details. -// Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). +// This mainly contains a list of selection requests. Read the large comments block above for details. +// - Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. +// - Some fields are only useful if your list is dynamic and allows deletion (handling deletion and getting "post-deletion" state right is shown in the demo) +// - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. +// - Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). struct ImGuiMultiSelectIO { - ImVector Requests; // ms:w, app:r / ms:w app:r // Requests - ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be clipped! - ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). - bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). - bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). - - ImGuiMultiSelectIO() { Clear(); } - void Clear() { Requests.resize(0); RangeSrcItem = NavIdItem = (ImGuiSelectionUserData)-1; NavIdSelected = RangeSrcReset = false; } + //------------------------------------------// BeginMultiSelect / EndMultiSelect + ImVector Requests; // ms:w, app:r / ms:w app:r // Requests + ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be clipped! + ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). + bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). + bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). }; //----------------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index 8062edad8..65eb5eb89 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1738,7 +1738,8 @@ struct IMGUI_API ImGuiMultiSelectTempData bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. ImGuiMultiSelectTempData() { Clear(); } - void Clear() { size_t io_sz = sizeof(IO); IO.Clear(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); BoxSelectLastitem = -1; } // Zero-clear except IO + void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); BoxSelectLastitem = -1; } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. + void ClearIO() { IO.Requests.resize(0); IO.RangeSrcItem = IO.NavIdItem = (ImGuiSelectionUserData)-1; IO.NavIdSelected = IO.RangeSrcReset = false; } }; // Persistent storage for multi-select (as long as selection is alive) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a20ca6b4b..677e34bed 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7259,7 +7259,10 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) } if (request_clear || request_select_all) - ms->IO.Requests.push_back(ImGuiSelectionRequest(request_select_all ? ImGuiSelectionRequestType_SelectAll : ImGuiSelectionRequestType_Clear)); + { + ImGuiSelectionRequest req = { request_select_all ? ImGuiSelectionRequestType_SelectAll : ImGuiSelectionRequestType_Clear, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; + ms->IO.Requests.push_back(req); + } ms->LoopRequestClear = request_clear; ms->LoopRequestSelectAll = request_select_all; @@ -7328,8 +7331,9 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_Clear, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; ms->IO.Requests.resize(0); - ms->IO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); + ms->IO.Requests.push_back(req); } } @@ -7479,9 +7483,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr)) { selected = !selected; - ImGuiSelectionRequest req(ImGuiSelectionRequestType_SetRange); - req.RangeFirstItem = req.RangeLastItem = item_data; - req.RangeSelected = selected; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->RangeSelected == selected) prev_req->RangeLastItem = item_data; // Merge span into same request @@ -7545,12 +7547,13 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. if (request_clear) { + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_Clear, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; ms->IO.Requests.resize(0); - ms->IO.Requests.push_back(ImGuiSelectionRequest(ImGuiSelectionRequestType_Clear)); + ms->IO.Requests.push_back(req); } int range_direction; - ImGuiSelectionRequest req(ImGuiSelectionRequestType_SetRange); + bool range_selected; if (is_shift && !is_singleselect) { // Shift+Arrow always select @@ -7558,7 +7561,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) storage->RangeSrcItem = item_data; - req.RangeSelected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; + range_selected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; range_direction = ms->RangeSrcPassedBy ? +1 : -1; } else @@ -7566,12 +7569,11 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Ctrl inverts selection, otherwise always select selected = is_ctrl ? !selected : true; storage->RangeSrcItem = item_data; - req.RangeSelected = selected; + range_selected = selected; range_direction = +1; } ImGuiSelectionUserData range_dst_item = item_data; - req.RangeFirstItem = (range_direction > 0) ? storage->RangeSrcItem : range_dst_item; - req.RangeLastItem = (range_direction > 0) ? range_dst_item : storage->RangeSrcItem; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, range_selected, (range_direction > 0) ? storage->RangeSrcItem : range_dst_item, (range_direction > 0) ? range_dst_item : storage->RangeSrcItem }; ms->IO.Requests.push_back(req); } From 0f633c1d99b6097f63b2cb8f26622c7bcd0a556b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 1 Dec 2023 17:49:47 +0100 Subject: [PATCH 0175/2359] MultiSelect: move demo's ExampleSelection to main api as a convenient ImGuiSelectionBasicStorage for basic users. --- imgui.h | 53 ++++++++++++++++++++- imgui_demo.cpp | 119 ++++++++-------------------------------------- imgui_widgets.cpp | 39 +++++++++++++++ 3 files changed, 109 insertions(+), 102 deletions(-) diff --git a/imgui.h b/imgui.h index 5f59d5ce9..1361e902b 100644 --- a/imgui.h +++ b/imgui.h @@ -44,7 +44,7 @@ Index of this file: // [SECTION] ImGuiIO // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO, ImGuiSelectionBasicStorage) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) @@ -179,6 +179,7 @@ struct ImGuiMultiSelectIO; // Structure to interact with a BeginMultiSe struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame struct ImGuiPayload; // User data payload for drag and drop operations struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. +struct ImGuiSelectionBasicStorage; // Helper struct to store multi-selection state + apply multi-selection requests. struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) struct ImGuiStorage; // Helper for key->value storage (container sorted by key) struct ImGuiStoragePair; // Helper for key->value storage (pair) @@ -2720,7 +2721,7 @@ struct ImColor }; //----------------------------------------------------------------------------- -// [SECTION] Multi-Select API flags & structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO, ImGuiSelectionBasicStorage) //----------------------------------------------------------------------------- #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. @@ -2820,6 +2821,54 @@ struct ImGuiMultiSelectIO bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). }; +// Helper struct to store multi-selection state + apply multi-selection requests. +// - Used by our demos and provided as a convenience if you want to quickly implement multi-selection. +// - Provide an abstraction layer for the purpose of the demo showcasing different forms of underlying selection data. +// - USING THIS IS NOT MANDATORY. This is only a helper and is not part of the main API. Advanced users are likely to implement their own. +// To store a single-selection, you only need a single variable and don't need any of this! +// To store a multi-selection, in your real application you could: +// - A) Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. +// - B) Use your own external storage: e.g. std::set, std::vector, std::set, interval trees, etc. +// are generally appropriate. Even a large array of bool might work for you... +// - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside your object). Not recommended because: +// - it means you cannot have multiple simultaneous views over your objects. +// - some of our features requires you to provide the selection _size_, which with this specific strategy require additional work. +// Our BeginMultiSelect() api/system doesn't make assumption about: +// - how you want to identify items in multi-selection API? Indices(*) / Custom Identifiers / Pointers ? +// - how you want to store persistent selection data? Indices / Custom Identifiers(*) / Pointers ? +// (*) This is the suggested solution: pass indices to API (because easy to iterate/interpolate) + persist your custom identifiers inside selection data. +// In ImGuiSelectionBasicStorage we: +// - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) +// - use a little extra indirection layer in order to abstract how persistent selection data is derived from an index. +// - in some cases we use Index as custom identifier (default, not ideal) +// - in some cases we read an ID from some custom item data structure (better, and closer to what you would do in your codebase) +// Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. +// WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THE UNNECESSARY 'AdapterIndexToStorageId()' INDIRECTION LOGIC. +// In theory, for maximum abstraction, this class could contains AdapterIndexToUserData() and AdapterUserDataToIndex() functions as well, +// but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that for clarify. +struct ImGuiSelectionBasicStorage +{ + ImGuiStorage Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set + int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). + + // Adapter to convert item index to item identifier + void* AdapterData; // e.g. selection.AdapterData = (void*)my_items; + ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->AdapterData)[idx]->ID; }; + + // Selection storage + ImGuiSelectionBasicStorage() { Clear(); AdapterData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } + void Clear() { Storage.Data.resize(0); Size = 0; } + void Swap(ImGuiSelectionBasicStorage& r){ Storage.Data.swap(r.Storage.Data); } + bool Contains(ImGuiID key) const { return Storage.GetInt(key, 0) != 0; } + void AddItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int != 0) return; *p_int = 1; Size++; } + void RemoveItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int == 0) return; *p_int = 0; Size--; } + void UpdateItem(ImGuiID key, bool v) { if (v) { AddItem(key); } else { RemoveItem(key); } } + int GetSize() const { return Size; } + + // Request handling (apply requests coming from BeginMultiSelect() and EndMultiSelect() functions) + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count); +}; + //----------------------------------------------------------------------------- // [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 541039335..291d50e8c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2773,92 +2773,9 @@ static const char* ExampleNames[] = "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" }; -// [Advanced] Helper class to store multi-selection state, used by the BeginMultiSelect() demos. -// Provide an abstraction layer for the purpose of the demo showcasing different forms of underlying selection data. -// To store a single-selection: -// - You only need a single variable and don't need any of this! -// To store a multi-selection, in your real application you could: -// - A) Use external storage: e.g. std::set, std::vector, std::set, interval trees, etc. -// are generally appropriate. Even a large array of bool might work for you... -// This code here use ImGuiStorage (a simple key->value storage) as a std::set replacement to avoid external dependencies. -// - B) Or use intrusively stored selection (e.g. 'bool IsSelected' inside your object). -// - That means you cannot have multiple simultaneous views over your objects. -// - Some of our features requires you to provide the selection _size_, which with this specific strategy require additional work. -// - So we suggest using intrusive selection for multi-select is not really adequate. -// Our multi-selection system doesn't make assumption about: -// - how you want to identify items in multi-selection API? Indices(*) / Custom Identifiers / Pointers ? -// - how you want to store persistent selection data? Indices / Custom Identifiers(*) / Pointers ? -// (*) This is the suggested solution: pass indices to API (because easy to iterate/interpolate) + persist your custom identifiers inside selection data. -// In this demo we: -// - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) -// - use a little extra indirection layer in order to abstract how persistent selection data is derived from an index. -// - in some cases we use Index as custom identifier -// - in some cases we read an ID from some custom item data structure (this is closer to what you would do in your codebase) -// Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. -// WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THE UNNECESSARY 'AdapterIndexToStorageId()' INDIRECTION LOGIC. -// In theory, for maximum abstraction, this class could contains AdapterIndexToUserData() and AdapterUserDataToIndex() functions as well, -// but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that for clarify. -struct ExampleSelection +struct ExampleSelectionStorageWithDeletion : ImGuiSelectionBasicStorage { - // Data - ImGuiStorage Storage; // Selection set (think of this as similar to e.g. std::set) - int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). - bool QueueDeletion; // Request deleting selected items - - // Adapter to convert item index to item identifier - // e.g. - // selection.AdapterData = (void*)my_items; - // selection.AdapterIndexToStorageId = [](ExampleSelection* s, int idx) { return ((MyItems**)s->AdapterData)[idx]->ID; }; - void* AdapterData; - ImGuiID (*AdapterIndexToStorageId)(ExampleSelection* self, int idx); - - // Functions - ExampleSelection() { Clear(); AdapterData = NULL; AdapterIndexToStorageId = [](ExampleSelection*, int idx) { return (ImGuiID)idx; };} - void Clear() { Storage.Data.resize(0); Size = 0; QueueDeletion = false; } - void Swap(ExampleSelection& rhs) { Storage.Data.swap(rhs.Storage.Data); } - bool Contains(ImGuiID key) const { return Storage.GetInt(key, 0) != 0; } - void AddItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int != 0) return; *p_int = 1; Size++; } - void RemoveItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int == 0) return; *p_int = 0; Size--; } - void UpdateItem(ImGuiID key, bool v){ if (v) AddItem(key); else RemoveItem(key); } - int GetSize() const { return Size; } - void DebugTooltip() { if (ImGui::BeginTooltip()) { for (auto& pair : Storage.Data) if (pair.val_i) ImGui::Text("0x%03X (%d)", pair.key, pair.key); ImGui::EndTooltip(); } } - - // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). - // - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. - // - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. - // - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection. - // - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform - // a lookup in order to have some way to iterate/interpolate between two items. - // - A full-featured application is likely to allow search/filtering which is likely to lead to using indices - // and constructing a view index <> object id/ptr data structure anyway. - // WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ExampleSelectionAdapter' INDIRECTION LOGIC. - // Notice that with the simplest adapter (using indices everywhere), all functions return their parameters. - // The most simple implementation (using indices everywhere) would look like: - // for (ImGuiSelectionRequest& req : ms_io->Requests) - // { - // if (req.Type == ImGuiSelectionRequestType_Clear) { Clear(); } - // if (req.Type == ImGuiSelectionRequestType_SelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } - // if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } - // } - void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) - { - IM_ASSERT(AdapterIndexToStorageId != NULL); - for (ImGuiSelectionRequest& req : ms_io->Requests) - { - if (req.Type == ImGuiSelectionRequestType_Clear) - Clear(); - if (req.Type == ImGuiSelectionRequestType_SelectAll) - { - Storage.Data.resize(0); - Storage.Data.reserve(items_count); - for (int idx = 0; idx < items_count; idx++) - AddItem(AdapterIndexToStorageId(this, idx)); - } - if (req.Type == ImGuiSelectionRequestType_SetRange) - for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) - UpdateItem(AdapterIndexToStorageId(this, idx), req.RangeSelected); - } - } + bool QueueDeletion = false; // Track request deleting selected items // Find which item should be Focused after deletion. // Call _before_ item submission. Retunr an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it. @@ -2870,6 +2787,8 @@ struct ExampleSelection int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, int items_count) { QueueDeletion = false; + if (Size == 0) + return -1; // If focused item is not selected... const int focused_idx = (int)ms_io->NavIdItem; // Index of currently focused item @@ -2922,9 +2841,9 @@ struct ExampleSelection // Example: Implement dual list box storage and interface struct ExampleDualListBox { - ImVector Items[2]; // ID is index into ExampleName[] - ExampleSelection Selections[2]; // Store ExampleItemId into selection - bool OptKeepSorted = true; + ImVector Items[2]; // ID is index into ExampleName[] + ImGuiSelectionBasicStorage Selections[2]; // Store ExampleItemId into selection + bool OptKeepSorted = true; void MoveAll(int src, int dst) { @@ -2956,7 +2875,7 @@ struct ExampleDualListBox { // In this example we store item id in selection (instead of item index) Selections[side].AdapterData = Items[side].Data; - Selections[side].AdapterIndexToStorageId = [](ExampleSelection* self, int idx) { ImGuiID* items = (ImGuiID*)self->AdapterData; return items[idx]; }; + Selections[side].AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImGuiID* items = (ImGuiID*)self->AdapterData; return items[idx]; }; Selections[side].ApplyRequests(ms_io, Items[side].Size); } static int IMGUI_CDECL CompareItemsByValue(const void* lhs, const void* rhs) @@ -2986,7 +2905,7 @@ struct ExampleDualListBox // FIXME-MULTISELECT: Dual List Box: Add context menus // FIXME-NAV: Using ImGuiWindowFlags_NavFlattened exhibit many issues. ImVector& items = Items[side]; - ExampleSelection& selection = Selections[side]; + ImGuiSelectionBasicStorage& selection = Selections[side]; ImGui::TableSetColumnIndex((side == 0) ? 0 : 2); ImGui::Text("%s (%d)", (side == 0) ? "Available" : "Basket", items.Size); @@ -3107,7 +3026,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::TreeNode("Multi-Select")) { // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection - static ExampleSelection selection; + static ImGuiSelectionBasicStorage selection; ImGui::Text("Tips: Use 'Debug Log->Selection' to see selection requests as they happen."); @@ -3148,7 +3067,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::TreeNode("Multi-Select (with clipper)")) { // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection - static ExampleSelection selection; + static ImGuiSelectionBasicStorage selection; ImGui::Text("Added features:"); ImGui::BulletText("Using ImGuiListClipper."); @@ -3200,13 +3119,13 @@ static void ShowDemoWindowMultiSelect() // But you may decide to store selection data inside your item (aka intrusive storage). // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection static ImVector items; - static ExampleSelection selection; + static ExampleSelectionStorageWithDeletion selection; ImGui::Text("Adding features:"); ImGui::BulletText("Dynamic list with Delete key support."); ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); - if (ImGui::IsItemHovered() && selection.GetSize() > 0) - selection.DebugTooltip(); + //if (ImGui::IsItemHovered() && selection.GetSize() > 0) + // selection.DebugTooltip(); // Initialize default list with 50 items + button to add/remove items. static int items_next_id = 0; @@ -3282,7 +3201,7 @@ static void ShowDemoWindowMultiSelect() // Use default select: Pass index to SetNextItemSelectionUserData(), store index in Selection const int SCOPES_COUNT = 3; const int ITEMS_COUNT = 8; // Per scope - static ExampleSelection selections_data[SCOPES_COUNT]; + static ImGuiSelectionBasicStorage selections_data[SCOPES_COUNT]; // Use ImGuiMultiSelectFlags_ScopeRect to not affect other selections in same window. static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ScopeRect | ImGuiMultiSelectFlags_ClearOnEscape;// | ImGuiMultiSelectFlags_ClearOnClickVoid; @@ -3295,7 +3214,7 @@ static void ShowDemoWindowMultiSelect() for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++) { ImGui::PushID(selection_scope_n); - ExampleSelection* selection = &selections_data[selection_scope_n]; + ImGuiSelectionBasicStorage* selection = &selections_data[selection_scope_n]; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection->ApplyRequests(ms_io, ITEMS_COUNT); @@ -3375,7 +3294,7 @@ static void ShowDemoWindowMultiSelect() static ImVector items; static int items_next_id = 0; if (items_next_id == 0) { for (int n = 0; n < 1000; n++) { items.push_back(items_next_id++); } } - static ExampleSelection selection; + static ExampleSelectionStorageWithDeletion selection; ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); @@ -9712,7 +9631,7 @@ struct ExampleAssetsBrowser // State ImVector Items; - ExampleSelection Selection; + ImGuiSelectionBasicStorage Selection; ImGuiID NextItemId = 0; bool SortDirty = false; float ZoomWheelAccum = 0.0f; @@ -9846,7 +9765,7 @@ struct ExampleAssetsBrowser // Use custom selection adapter: store ID in selection (recommended) Selection.AdapterData = this; - Selection.AdapterIndexToStorageId = [](ExampleSelection* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->AdapterData; return self->Items[idx].ID; }; + Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->AdapterData; return self->Items[idx].ID; }; Selection.ApplyRequests(ms_io, Items.Size); // Altering ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()... diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 677e34bed..11ae828c9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7112,6 +7112,7 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) // - MultiSelectItemHeader() [Internal] // - MultiSelectItemFooter() [Internal] // - DebugNodeMultiSelectState() [Internal] +// - ImGuiSelectionBasicStorage //------------------------------------------------------------------------- static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io) @@ -7612,6 +7613,44 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) #endif } +// Apply requests coming from BeginMultiSelect() and EndMultiSelect(). +// - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. +// - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. +// - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection. +// - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform +// a lookup in order to have some way to iterate/interpolate between two items. +// - A full-featured application is likely to allow search/filtering which is likely to lead to using indices +// and constructing a view index <> object id/ptr data structure anyway. +// WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ImGuiSelectionBasicStorage' INDIRECTION LOGIC. +// Notice that with the simplest adapter (using indices everywhere), all functions return their parameters. +// The most simple implementation (using indices everywhere) would look like: +// for (ImGuiSelectionRequest& req : ms_io->Requests) +// { +// if (req.Type == ImGuiSelectionRequestType_Clear) { Clear(); } +// if (req.Type == ImGuiSelectionRequestType_SelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } +// if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } +// } +void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) +{ + IM_ASSERT(AdapterIndexToStorageId != NULL); + for (ImGuiSelectionRequest& req : ms_io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_Clear) + Clear(); + if (req.Type == ImGuiSelectionRequestType_SelectAll) + { + Storage.Data.resize(0); + Storage.Data.reserve(items_count); + for (int idx = 0; idx < items_count; idx++) + AddItem(AdapterIndexToStorageId(this, idx)); + } + if (req.Type == ImGuiSelectionRequestType_SetRange) + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) + UpdateItem(AdapterIndexToStorageId(this, idx), req.RangeSelected); + } +} + + //------------------------------------------------------------------------- // [SECTION] Widgets: ListBox //------------------------------------------------------------------------- From 51fe0bfcf642e7317548bd3b8f62a19dc5e13551 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 5 Dec 2023 18:36:00 +0100 Subject: [PATCH 0176/2359] MultiSelect: reworked comments in imgui.h now that we have our own section. --- imgui.h | 140 ++++++++++++++++++++++++---------------------- imgui_demo.cpp | 33 +++++------ imgui_widgets.cpp | 4 +- 3 files changed, 91 insertions(+), 86 deletions(-) diff --git a/imgui.h b/imgui.h index 1361e902b..0e7a63ce6 100644 --- a/imgui.h +++ b/imgui.h @@ -673,7 +673,7 @@ namespace ImGui // Multi-selection system for Selectable() and TreeNode() functions. // - 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. // - ImGuiSelectionUserData is often used to store your item index. - // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State' for demo. + // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); @@ -2726,46 +2726,24 @@ struct ImColor #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. -// Flags for BeginMultiSelect(). -// (we provide 'ImGuiMultiSelectFlags_SingleSelect' for consistency and flexiblity to allow a single-selection to use same code/logic, but it essentially disable the biggest purpose of BeginMultiSelect(). -// If you use 'ImGuiMultiSelectFlags_SingleSelect' you can handle single-selection in a simpler way by just calling Selectable()/TreeNode() and reacting on clicks). -enum ImGuiMultiSelectFlags_ -{ - ImGuiMultiSelectFlags_None = 0, - ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to use same code/logic is desired, but may not be very useful. - ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to set RequestSelectAll - ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_NoBoxSelectScroll = 1 << 3, // Disable scrolling when box-selecting near edges of scope. - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 4, // Clear selection when pressing Escape while scope is focused. - ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 5, // Clear selection when clicking on empty location within scope. - ImGuiMultiSelectFlags_ScopeWindow = 1 << 6, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if (use if BeginMultiSelect() covers a whole window. - ImGuiMultiSelectFlags_ScopeRect = 1 << 7, // Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. Use if multiple BeginMultiSelect() are used in the same host window. - ImGuiMultiSelectFlags_SelectOnClick = 1 << 8, // Apply selection on mouse down when clicking on unselected item. (Default) - ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 9, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. -}; - // Multi-selection system -// - Refer to 'Demo->Widgets->Selection State' for references using this. +// - Refer to 'Demo->Widgets->Selection State & Multi-Select' for references using this. // - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) -// and supports a clipper being used. Handling this manually and correctly i tricky, this is why we provide +// and supports a clipper being used. Handling this manually and correctly is tricky, this is why we provide // the functionality. If you don't need SHIFT+Mouse/Keyboard range-select + clipping, you can implement a // simple form of multi-selection yourself, by reacting to click/presses on Selectable() items. // - TreeNode() and Selectable() are supported but custom widgets may use it as well. // - In the spirit of Dear ImGui design, your code owns actual selection data. // This is designed to allow all kinds of selection storage you may use in your application: -// e.g. set/map/hash (store only selected items), instructive selection (store a bool inside each object), -// external array (store an array in your view data, next to your objects) etc. +// e.g. set/map/hash (store selected items), instructive selection (store a bool inside each object), etc. // - The work involved to deal with multi-selection differs whether you want to only submit visible items and // clip others, or submit all items regardless of their visibility. Clipping items is more efficient and will // allow you to deal with large lists (1k~100k items). See "Usage flow" section below for details. // If you are not sure, always start without clipping! You can work your way to the optimized version afterwards. -// About ImGuiSelectionBasicStorage: -// - This is an optional helper to store a selection state and apply selection requests. -// - It is used by our demos and provided as a convenience if you want to quickly implement multi-selection. // About ImGuiSelectionUserData: -// - This is your application-defined identifier in a selection set: -// - For each item is it submitted by your call to SetNextItemSelectionUserData(). -// - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. +// - This can store an application-defined identifier (e.g. index or pointer). +// - For each item is it submitted by your call to SetNextItemSelectionUserData(). +// - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. // - Most applications will store an object INDEX, hence the chosen name and type. // Storing an integer index is the easiest thing to do, as RequestSetRange requests will give you two end-points // and you will need to iterate/interpolate between them to honor range selection. @@ -2778,15 +2756,33 @@ enum ImGuiMultiSelectFlags_ // Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (2) [If using clipper] Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 6. -// - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeIndex(). If already using indices in ImGuiSelectionUserData, it is as simple as clipper.IncludeIndex((int)ms_io->RangeSrcItem); +// - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeItemByIndex(). If storing indices in ImGuiSelectionUserData, a simple clipper.IncludeItemByIndex(ms_io->RangeSrcItem) call will work. // LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (6) Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 2. -// If you submit all items (no clipper), Step 2 and 3 and will be handled by Selectable()/TreeNode on a per-item basis. -// However it is perfectly fine to honor all steps even if you don't use a clipper. +// If you submit all items (no clipper), Step 2 and 3 are optional and will be handled by each item themselves. It is perfectly fine if you honor those steps without a clipper. +// About ImGuiSelectionBasicStorage: +// - This is an optional helper to store a selection state and apply selection requests. +// - It is used by our demos and provided as a convenience if you want to quickly implement multi-selection. // Advanced: // - Deletion: If you need to handle items deletion: more work if needed for post-deletion focus and scrolling to be correct. -// Refer to 'Demo->Widgets->Selection State' for demos supporting deletion. +// Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos supporting deletion. + +// Flags for BeginMultiSelect(). +enum ImGuiMultiSelectFlags_ +{ + ImGuiMultiSelectFlags_None = 0, + ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! + ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut sending a SelectAll request. + ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_NoBoxSelectScroll = 1 << 3, // Disable scrolling when box-selecting near edges of scope. + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 4, // Clear selection when pressing Escape while scope is focused. + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 5, // Clear selection when clicking on empty location within scope. + ImGuiMultiSelectFlags_ScopeWindow = 1 << 6, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if BeginMultiSelect() covers a whole window. + ImGuiMultiSelectFlags_ScopeRect = 1 << 7, // Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. Use if multiple BeginMultiSelect() are used in the same host window. + ImGuiMultiSelectFlags_SelectOnClick = 1 << 8, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 9, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. +}; enum ImGuiSelectionRequestType { @@ -2814,58 +2810,70 @@ struct ImGuiSelectionRequest struct ImGuiMultiSelectIO { //------------------------------------------// BeginMultiSelect / EndMultiSelect - ImVector Requests; // ms:w, app:r / ms:w app:r // Requests + ImVector Requests; // ms:w, app:r / ms:w app:r // Requests to apply to your selection data. ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be clipped! ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). }; -// Helper struct to store multi-selection state + apply multi-selection requests. -// - Used by our demos and provided as a convenience if you want to quickly implement multi-selection. -// - Provide an abstraction layer for the purpose of the demo showcasing different forms of underlying selection data. -// - USING THIS IS NOT MANDATORY. This is only a helper and is not part of the main API. Advanced users are likely to implement their own. -// To store a single-selection, you only need a single variable and don't need any of this! +// Optional helper struct to store multi-selection state + apply multi-selection requests. +// - Used by our demos and provided as a convenience to easily implement basic multi-selection. +// - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. Advanced users are likely to implement their own. // To store a multi-selection, in your real application you could: // - A) Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. -// - B) Use your own external storage: e.g. std::set, std::vector, std::set, interval trees, etc. -// are generally appropriate. Even a large array of bool might work for you... -// - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside your object). Not recommended because: -// - it means you cannot have multiple simultaneous views over your objects. -// - some of our features requires you to provide the selection _size_, which with this specific strategy require additional work. +// - B) Use your own external storage: e.g. std::set, std::vector, interval trees, etc. +// - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside objects). Not recommended because you can't have multiple views +// over same objects. Also some features requires to provide selection _size_, which with this strategy requires additional work. // Our BeginMultiSelect() api/system doesn't make assumption about: -// - how you want to identify items in multi-selection API? Indices(*) / Custom Identifiers / Pointers ? -// - how you want to store persistent selection data? Indices / Custom Identifiers(*) / Pointers ? -// (*) This is the suggested solution: pass indices to API (because easy to iterate/interpolate) + persist your custom identifiers inside selection data. +// - how you want to identify items in multi-selection API? Indices(*) or Custom Ids or Pointers -> Indices is better (easy to iterate/interpolate) +// - how you want to store persistent selection data? Indices or Custom Ids(*) or Pointers -> Custom ids is better (as selection can persist) // In ImGuiSelectionBasicStorage we: // - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) -// - use a little extra indirection layer in order to abstract how persistent selection data is derived from an index. -// - in some cases we use Index as custom identifier (default, not ideal) +// - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index. +// - in some cases we use Index as custom identifier (default implementation returns Index casted as Identifier): only valid for a never changing item list. // - in some cases we read an ID from some custom item data structure (better, and closer to what you would do in your codebase) // Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. -// WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THE UNNECESSARY 'AdapterIndexToStorageId()' INDIRECTION LOGIC. +// When your application settles on a choice, you may want to get rid of this indirection layer and do your own thing. +// Minimum pseudo-code example using this helper: +// { +// static vector items; // Your items +// static ImGuiSelectionBasicStorage selection; // Your selection +// selection.AdapterData = (void*)&items; // Setup adapter so selection.ApplyRequests() function can convert indexes to identifiers. +// selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((vector*)self->AdapterData))[idx].ID; }; +// +// ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None); +// selection.ApplyRequests(ms_io, items.Size); +// for (int idx = 0; idx < items.Size; idx++) +// { +// bool item_is_selected = selection.Contains(items[idx].ID); +// ImGui::SetNextItemSelectionUserData(idx); +// ImGui::Selectable(label, item_is_selected); +// } +// ms_io = ImGui::EndMultiSelect(); +// selection.ApplyRequests(ms_io, items.Size); +// } // In theory, for maximum abstraction, this class could contains AdapterIndexToUserData() and AdapterUserDataToIndex() functions as well, -// but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that for clarify. +// but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that indirection for clarity. struct ImGuiSelectionBasicStorage { - ImGuiStorage Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set - int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). - - // Adapter to convert item index to item identifier - void* AdapterData; // e.g. selection.AdapterData = (void*)my_items; + // Members + ImGuiStorage Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set + int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). + void* AdapterData; // Adapter to convert item index to item identifier // e.g. selection.AdapterData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->AdapterData)[idx]->ID; }; - // Selection storage - ImGuiSelectionBasicStorage() { Clear(); AdapterData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } - void Clear() { Storage.Data.resize(0); Size = 0; } - void Swap(ImGuiSelectionBasicStorage& r){ Storage.Data.swap(r.Storage.Data); } - bool Contains(ImGuiID key) const { return Storage.GetInt(key, 0) != 0; } - void AddItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int != 0) return; *p_int = 1; Size++; } - void RemoveItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int == 0) return; *p_int = 0; Size--; } - void UpdateItem(ImGuiID key, bool v) { if (v) { AddItem(key); } else { RemoveItem(key); } } - int GetSize() const { return Size; } + // Methods: selection storage + ImGuiSelectionBasicStorage() { Clear(); AdapterData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } + void Clear() { Storage.Data.resize(0); Size = 0; } + void Swap(ImGuiSelectionBasicStorage& r) { Storage.Data.swap(r.Storage.Data); } + bool Contains(ImGuiID key) const { return Storage.GetInt(key, 0) != 0; } + void AddItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int != 0) return; *p_int = 1; Size++; } + void RemoveItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int == 0) return; *p_int = 0; Size--; } + void UpdateItem(ImGuiID key, bool v) { if (v) { AddItem(key); } else { RemoveItem(key); } } + int GetSize() const { return Size; } - // Request handling (apply requests coming from BeginMultiSelect() and EndMultiSelect() functions) + // Methods: apply selection requests (that are coming from BeginMultiSelect() and EndMultiSelect() functions) IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count); }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 291d50e8c..58cc4ee57 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2783,7 +2783,7 @@ struct ExampleSelectionStorageWithDeletion : ImGuiSelectionBasicStorage // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. // - We don't actually manipulate the ImVector<> here, only in ApplyDeletionPostLoop(), but using similar API for consistency and flexibility. // - Important: Deletion only works if the underlying ImGuiID for your items are stable: aka not depend on their index, but on e.g. item id/ptr. - // FIXME-MULTISELECT: Doesn't take account of the possibility focus target will be moved during deletion. Need refocus or offset. + // FIXME-MULTISELECT: Doesn't take account of the possibility focus target will be moved during deletion. Need refocus or scroll offset. int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, int items_count) { QueueDeletion = false; @@ -2890,7 +2890,7 @@ struct ExampleDualListBox } void Show() { - ImGui::Checkbox("Sorted", &OptKeepSorted); + //ImGui::Checkbox("Sorted", &OptKeepSorted); if (ImGui::BeginTable("split", 3, ImGuiTableFlags_None)) { ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Left side @@ -2964,13 +2964,15 @@ struct ExampleDualListBox if (request_move_selected != -1) MoveSelected(request_move_selected, request_move_selected ^ 1); - // FIXME-MULTISELECT: action from outside + // FIXME-MULTISELECT: Support action from outside + /* if (OptKeepSorted == false) { ImGui::NewLine(); if (ImGui::ArrowButton("MoveUp", ImGuiDir_Up)) {} if (ImGui::ArrowButton("MoveDown", ImGuiDir_Down)) {} } + */ ImGui::EndTable(); } @@ -3025,20 +3027,19 @@ static void ShowDemoWindowMultiSelect() IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); if (ImGui::TreeNode("Multi-Select")) { - // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection - static ImGuiSelectionBasicStorage selection; - - ImGui::Text("Tips: Use 'Debug Log->Selection' to see selection requests as they happen."); - ImGui::Text("Supported features:"); ImGui::BulletText("Keyboard navigation (arrows, page up/down, home/end, space)."); ImGui::BulletText("Ctrl modifier to preserve and toggle selection."); ImGui::BulletText("Shift modifier for range selection."); ImGui::BulletText("CTRL+A to select all."); + ImGui::Text("Tip: Use 'Debug Log->Selection' to see selection requests as they happen."); + + // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection + const int ITEMS_COUNT = 50; + static ImGuiSelectionBasicStorage selection; + ImGui::Text("Selection: %d/%d", selection.GetSize(), ITEMS_COUNT); // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling region). - const int ITEMS_COUNT = 50; - ImGui::Text("Selection: %d/%d", selection.GetSize(), ITEMS_COUNT); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; @@ -3124,8 +3125,6 @@ static void ShowDemoWindowMultiSelect() ImGui::Text("Adding features:"); ImGui::BulletText("Dynamic list with Delete key support."); ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); - //if (ImGui::IsItemHovered() && selection.GetSize() > 0) - // selection.DebugTooltip(); // Initialize default list with 50 items + button to add/remove items. static int items_next_id = 0; @@ -3146,10 +3145,9 @@ static void ShowDemoWindowMultiSelect() ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, items.Size); - // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. - // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. + // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to turn into 'ms_io->RequestDelete' signal -> need HasSelection passed. // FIXME-MULTISELECT: If pressing Delete + another key we have ambiguous behavior. - const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); + const bool want_delete = selection.QueueDeletion || ((selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); int item_curr_idx_to_focus = -1; if (want_delete) item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, items.Size); @@ -3309,9 +3307,8 @@ static void ShowDemoWindowMultiSelect() ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, items.Size); - // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to send a helper/optional "delete" signal. - // FIXME-MULTISELECT: may turn into 'ms_io->RequestDelete' -> need HasSelection passed. - const bool want_delete = selection.QueueDeletion || ((selection.GetSize() > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); + // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to turn into 'ms_io->RequestDelete' signal -> need HasSelection passed. + const bool want_delete = selection.QueueDeletion || ((selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); int item_curr_idx_to_focus = -1; if (want_delete) item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, items.Size); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 11ae828c9..e0b32ac86 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6858,7 +6858,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Render if (hovered || selected) { - // FIXME-MULTISELECT, FIXME-STYLE: Color for 'selected' elements? ImGuiCol_HeaderSelected + // FIXME-MULTISELECT: Styling: Color for 'selected' elements? ImGuiCol_HeaderSelected ImU32 col; if (selected && !hovered) col = GetColorU32(ImLerp(GetStyleColorVec4(ImGuiCol_Header), GetStyleColorVec4(ImGuiCol_HeaderHovered), 0.5f)); @@ -7558,7 +7558,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) if (is_shift && !is_singleselect) { // Shift+Arrow always select - // Ctrl+Shift+Arrow copy source selection state (alrady stored by BeginMultiSelect() in RangeSelected) + // Ctrl+Shift+Arrow copy source selection state (already stored by BeginMultiSelect() in storage->RangeSelected) //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) storage->RangeSrcItem = item_data; From 750e23998f528f1490992a6cb61373e251961d1d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 6 Dec 2023 16:55:55 +0100 Subject: [PATCH 0177/2359] MultiSelect: Demo: Assets Browser: added deletion support. Store ID in selection. Moved QueueDeletion to local var to emphasis that this is a user extension. --- imgui.h | 1 - imgui_demo.cpp | 170 +++++++++++++++++++++++++++---------------------- 2 files changed, 95 insertions(+), 76 deletions(-) diff --git a/imgui.h b/imgui.h index 0e7a63ce6..6de5cec7f 100644 --- a/imgui.h +++ b/imgui.h @@ -2871,7 +2871,6 @@ struct ImGuiSelectionBasicStorage void AddItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int != 0) return; *p_int = 1; Size++; } void RemoveItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int == 0) return; *p_int = 0; Size--; } void UpdateItem(ImGuiID key, bool v) { if (v) { AddItem(key); } else { RemoveItem(key); } } - int GetSize() const { return Size; } // Methods: apply selection requests (that are coming from BeginMultiSelect() and EndMultiSelect() functions) IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 58cc4ee57..aa6ecf010 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2773,10 +2773,9 @@ static const char* ExampleNames[] = "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" }; -struct ExampleSelectionStorageWithDeletion : ImGuiSelectionBasicStorage +// Extra functions to add deletion support to ImGuiSelectionBasicStorage +struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage { - bool QueueDeletion = false; // Track request deleting selected items - // Find which item should be Focused after deletion. // Call _before_ item submission. Retunr an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it. // The subsequent ApplyDeletionPostLoop() code will use it to apply Selection. @@ -2786,7 +2785,6 @@ struct ExampleSelectionStorageWithDeletion : ImGuiSelectionBasicStorage // FIXME-MULTISELECT: Doesn't take account of the possibility focus target will be moved during deletion. Need refocus or scroll offset. int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, int items_count) { - QueueDeletion = false; if (Size == 0) return -1; @@ -3032,12 +3030,13 @@ static void ShowDemoWindowMultiSelect() ImGui::BulletText("Ctrl modifier to preserve and toggle selection."); ImGui::BulletText("Shift modifier for range selection."); ImGui::BulletText("CTRL+A to select all."); - ImGui::Text("Tip: Use 'Debug Log->Selection' to see selection requests as they happen."); + ImGui::BulletText("Escape to clear selection."); + ImGui::Text("Tip: Use 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen."); // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection const int ITEMS_COUNT = 50; static ImGuiSelectionBasicStorage selection; - ImGui::Text("Selection: %d/%d", selection.GetSize(), ITEMS_COUNT); + ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling region). if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) @@ -3074,7 +3073,7 @@ static void ShowDemoWindowMultiSelect() ImGui::BulletText("Using ImGuiListClipper."); const int ITEMS_COUNT = 10000; - ImGui::Text("Selection: %d/%d", selection.GetSize(), ITEMS_COUNT); + ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; @@ -3116,24 +3115,26 @@ static void ShowDemoWindowMultiSelect() IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with deletion)"); if (ImGui::TreeNode("Multi-Select (with deletion)")) { - // Intentionally separating items data from selection data! - // But you may decide to store selection data inside your item (aka intrusive storage). - // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection - static ImVector items; - static ExampleSelectionStorageWithDeletion selection; + // Storing items data separately from selection data. + // (you may decide to store selection data inside your item (aka intrusive storage) if you don't need multiple views over same items) + // Use a custom selection.Adapter: store item identifier in Selection (instead of index) + static ImVector items; + static ExampleSelectionWithDeletion selection; + selection.AdapterData = (void*)&items; + selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImVector* p_items = (ImVector*)self->AdapterData; return (*p_items)[idx]; }; // Index -> ID - ImGui::Text("Adding features:"); + ImGui::Text("Added features:"); ImGui::BulletText("Dynamic list with Delete key support."); - ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); + ImGui::Text("Selection size: %d/%d", selection.Size, items.Size); // Initialize default list with 50 items + button to add/remove items. - static int items_next_id = 0; + static ImGuiID items_next_id = 0; if (items_next_id == 0) - for (int n = 0; n < 50; n++) + for (ImGuiID n = 0; n < 50; n++) items.push_back(items_next_id++); if (ImGui::SmallButton("Add 20 items")) { for (int n = 0; n < 20; n++) { items.push_back(items_next_id++); } } ImGui::SameLine(); - if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.RemoveItem((ImGuiID)(items.Size - 1)); items.pop_back(); } } // This is to test + if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.RemoveItem(items.back()); items.pop_back(); } } // (1) Extra to support deletion: Submit scrolling range to avoid glitches on deletion const float items_height = ImGui::GetTextLineHeightWithSpacing(); @@ -3147,18 +3148,16 @@ static void ShowDemoWindowMultiSelect() // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to turn into 'ms_io->RequestDelete' signal -> need HasSelection passed. // FIXME-MULTISELECT: If pressing Delete + another key we have ambiguous behavior. - const bool want_delete = selection.QueueDeletion || ((selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); - int item_curr_idx_to_focus = -1; - if (want_delete) - item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, items.Size); + const bool want_delete = (selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); + const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1; for (int n = 0; n < items.Size; n++) { - const int item_id = items[n]; + const ImGuiID item_id = items[n]; char label[64]; - sprintf(label, "Object %05d: %s", item_id, ExampleNames[item_id % IM_ARRAYSIZE(ExampleNames)]); + sprintf(label, "Object %05u: %s", item_id, ExampleNames[item_id % IM_ARRAYSIZE(ExampleNames)]); - bool item_is_selected = selection.Contains((ImGuiID)n); + bool item_is_selected = selection.Contains(item_id); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); if (item_curr_idx_to_focus == n) @@ -3217,7 +3216,7 @@ static void ShowDemoWindowMultiSelect() selection->ApplyRequests(ms_io, ITEMS_COUNT); ImGui::SeparatorText("Selection scope"); - ImGui::Text("Selection size: %d/%d", selection->GetSize(), ITEMS_COUNT); + ImGui::Text("Selection size: %d/%d", selection->Size, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) { @@ -3292,9 +3291,10 @@ static void ShowDemoWindowMultiSelect() static ImVector items; static int items_next_id = 0; if (items_next_id == 0) { for (int n = 0; n < 1000; n++) { items.push_back(items_next_id++); } } - static ExampleSelectionStorageWithDeletion selection; + static ExampleSelectionWithDeletion selection; + static bool request_deletion_from_menu = false; // Queue deletion triggered from context menu - ImGui::Text("Selection size: %d/%d", selection.GetSize(), items.Size); + ImGui::Text("Selection size: %d/%d", selection.Size, items.Size); const float items_height = (widget_type == WidgetType_TreeNode) ? ImGui::GetTextLineHeight() : ImGui::GetTextLineHeightWithSpacing(); ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); @@ -3308,10 +3308,9 @@ static void ShowDemoWindowMultiSelect() selection.ApplyRequests(ms_io, items.Size); // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to turn into 'ms_io->RequestDelete' signal -> need HasSelection passed. - const bool want_delete = selection.QueueDeletion || ((selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); - int item_curr_idx_to_focus = -1; - if (want_delete) - item_curr_idx_to_focus = selection.ApplyDeletionPreLoop(ms_io, items.Size); + const bool want_delete = request_deletion_from_menu || ((selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); + const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1; + request_deletion_from_menu = false; if (show_in_table) { @@ -3328,7 +3327,7 @@ static void ShowDemoWindowMultiSelect() { clipper.Begin(items.Size); if (item_curr_idx_to_focus != -1) - clipper.IncludeItemByIndex(item_curr_idx_to_focus); // Ensure focused item is not clipped + clipper.IncludeItemByIndex(item_curr_idx_to_focus); // Ensure focused item is not clipped. if (ms_io->RangeSrcItem > 0) clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. } @@ -3417,9 +3416,10 @@ static void ShowDemoWindowMultiSelect() // Right-click: context menu if (ImGui::BeginPopupContextItem()) { - ImGui::BeginDisabled(!use_deletion || selection.GetSize() == 0); - sprintf(label, "Delete %d item(s)###DeleteSelected", selection.GetSize()); - selection.QueueDeletion |= ImGui::Selectable(label); + ImGui::BeginDisabled(!use_deletion || selection.Size == 0); + sprintf(label, "Delete %d item(s)###DeleteSelected", selection.Size); + if (ImGui::Selectable(label)) + request_deletion_from_menu = true; ImGui::EndDisabled(); ImGui::Selectable("Close"); ImGui::EndPopup(); @@ -9619,19 +9619,20 @@ const ImGuiTableSortSpecs* ExampleAsset::s_current_sort_specs = NULL; struct ExampleAssetsBrowser { // Options - bool ShowTypeOverlay = true; - bool AllowDragUnselected = false; - float IconSize = 32.0f; - int IconSpacing = 10; - int IconHitSpacing = 4; // Increase hit-spacing if you want to make it possible to clear or box-select from gaps. Some spacing is required to able to amend with Shift+box-select. Value is small in Explorer. - bool StretchSpacing = true; + bool ShowTypeOverlay = true; + bool AllowDragUnselected = false; + float IconSize = 32.0f; + int IconSpacing = 10; + int IconHitSpacing = 4; // Increase hit-spacing if you want to make it possible to clear or box-select from gaps. Some spacing is required to able to amend with Shift+box-select. Value is small in Explorer. + bool StretchSpacing = true; // State - ImVector Items; - ImGuiSelectionBasicStorage Selection; - ImGuiID NextItemId = 0; - bool SortDirty = false; - float ZoomWheelAccum = 0.0f; + ImVector Items; // Our items + ExampleSelectionWithDeletion Selection; // Our selection (ImGuiSelectionBasicStorage + helper funcs to handle deletion) + ImGuiID NextItemId = 0; // Unique identifier when creating new items + bool RequestDelete = false; // Deferred deletion request + bool RequestSort = false; // Deferred sort request + float ZoomWheelAccum = 0.0f; // Mouse wheel accumulator to handle smooth wheels better // Functions ExampleAssetsBrowser() @@ -9645,7 +9646,7 @@ struct ExampleAssetsBrowser Items.reserve(Items.Size + count); for (int n = 0; n < count; n++, NextItemId++) Items.push_back(ExampleAsset(NextItemId, (NextItemId % 20) < 15 ? 0 : (NextItemId % 20) < 18 ? 1 : 2)); - SortDirty = true; + RequestSort = true; } void ClearItems() { @@ -9676,6 +9677,12 @@ struct ExampleAssetsBrowser *p_open = false; ImGui::EndMenu(); } + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Delete", "Del", false, Selection.Size > 0)) + RequestDelete = true; + ImGui::EndMenu(); + } if (ImGui::BeginMenu("Options")) { ImGui::PushItemWidth(ImGui::GetFontSize() * 10); @@ -9697,22 +9704,6 @@ struct ExampleAssetsBrowser ImGui::EndMenuBar(); } - // Zooming with CTRL+Wheel - // FIXME-MULTISELECT: Try to maintain scroll. - ImGuiIO& io = ImGui::GetIO(); - if (ImGui::IsWindowAppearing()) - ZoomWheelAccum = 0.0f; - if (io.MouseWheel != 0.0f && ImGui::IsKeyDown(ImGuiMod_Ctrl) && ImGui::IsAnyItemActive() == false) - { - ZoomWheelAccum += io.MouseWheel; - if (fabsf(ZoomWheelAccum) >= 1.0f) - { - IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum); - IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f); - ZoomWheelAccum -= (int)ZoomWheelAccum; - } - } - // Show a table with ONLY one header row to showcase the idea/possibility of using this to provide a sorting UI ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); ImGuiTableFlags table_flags_for_sort_specs = ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders; @@ -9722,10 +9713,10 @@ struct ExampleAssetsBrowser ImGui::TableSetupColumn("Type"); ImGui::TableHeadersRow(); if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs()) - if (sort_specs->SpecsDirty || SortDirty) + if (sort_specs->SpecsDirty || RequestSort) { ExampleAsset::SortWithSortSpecs(sort_specs, Items.Data, Items.Size); - sort_specs->SpecsDirty = SortDirty = false; + sort_specs->SpecsDirty = RequestSort = false; } ImGui::EndTable(); } @@ -9765,6 +9756,10 @@ struct ExampleAssetsBrowser Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->AdapterData; return self->Items[idx].ID; }; Selection.ApplyRequests(ms_io, Items.Size); + const bool want_delete = RequestDelete || ((Selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); + const int item_curr_idx_to_focus = want_delete ? Selection.ApplyDeletionPreLoop(ms_io, Items.Size) : -1; + RequestDelete = false; + // Altering ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()... // But it is necessary for two reasons: // - Selectables uses it by default to visually fill the space between two items. @@ -9781,8 +9776,10 @@ struct ExampleAssetsBrowser const float line_height = item_size.y + item_spacing; ImGuiListClipper clipper; clipper.Begin(line_count, line_height); + if (item_curr_idx_to_focus != -1) + clipper.IncludeItemByIndex(item_curr_idx_to_focus / column_count); // Ensure focused item line is not clipped. if (ms_io->RangeSrcItem != -1) - clipper.IncludeItemByIndex((int)(ms_io->RangeSrcItem / column_count)); + clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem / column_count); // Ensure RangeSrc item line is not clipped. while (clipper.Step()) { for (int line_idx = clipper.DisplayStart; line_idx < clipper.DisplayEnd; line_idx++) @@ -9812,6 +9809,10 @@ struct ExampleAssetsBrowser if (ImGui::IsItemToggledSelection()) item_is_selected = !item_is_selected; + // Focus (for after deletion) + if (item_curr_idx_to_focus == item_idx) + ImGui::SetKeyboardFocusHere(-1); + // Drag and drop if (ImGui::BeginDragDropSource()) { @@ -9825,15 +9826,6 @@ struct ExampleAssetsBrowser ImGui::EndDragDropSource(); } - // Popup menu - if (ImGui::BeginPopupContextItem()) - { - ImGui::Text("Selection: %d items", Selection.Size); - if (ImGui::Button("Close")) - ImGui::CloseCurrentPopup(); - ImGui::EndPopup(); - } - // A real app would likely display an image/thumbnail here. draw_list->AddRectFilled(box_min, box_max, icon_bg_color); if (ShowTypeOverlay && item_data->Type != 0) @@ -9856,13 +9848,41 @@ struct ExampleAssetsBrowser clipper.End(); ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing + // Context menu + if (ImGui::BeginPopupContextWindow()) + { + ImGui::Text("Selection: %d items", Selection.Size); + ImGui::Separator(); + if (ImGui::MenuItem("Delete", "Del", false, Selection.Size > 0)) + RequestDelete = true; + ImGui::EndPopup(); + } + ms_io = ImGui::EndMultiSelect(); Selection.ApplyRequests(ms_io, Items.Size); + if (want_delete) + Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus); // FIXME-MULTISELECT: Find a way to expose this in public API. This currently requires "imgui_internal.h" //ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); } + // Zooming with CTRL+Wheel + // FIXME-MULTISELECT: Try to maintain scroll. + ImGuiIO& io = ImGui::GetIO(); + if (ImGui::IsWindowAppearing()) + ZoomWheelAccum = 0.0f; + if (ImGui::IsWindowHovered() && io.MouseWheel != 0.0f && ImGui::IsKeyDown(ImGuiMod_Ctrl) && ImGui::IsAnyItemActive() == false) + { + ZoomWheelAccum += io.MouseWheel; + if (fabsf(ZoomWheelAccum) >= 1.0f) + { + IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum); + IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f); + ZoomWheelAccum -= (int)ZoomWheelAccum; + } + } + ImGui::EndChild(); ImGui::Text("Selected: %d/%d items", Selection.Size, Items.Size); ImGui::End(); From 7546a2d345c10e3ccfdb6a08afdee2aa2e52c97c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Dec 2023 17:26:02 +0100 Subject: [PATCH 0178/2359] MultiSelect: Demo: Assets Browser: track scrolling target so we can roughly land on hovered item. It's impossible to do this perfectly without some form of locking on item because as the hovered item X position changes it's easy to drift. --- imgui_demo.cpp | 114 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 76 insertions(+), 38 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index aa6ecf010..45b758436 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -9634,6 +9634,15 @@ struct ExampleAssetsBrowser bool RequestSort = false; // Deferred sort request float ZoomWheelAccum = 0.0f; // Mouse wheel accumulator to handle smooth wheels better + // Calculated sizes for layout, output of UpdateLayoutSizes(). Could be locals but our code is simpler this way. + ImVec2 LayoutItemSize; + ImVec2 LayoutItemStep; // == LayoutItemSize + LayoutItemSpacing + float LayoutItemSpacing = 0.0f; + float LayoutSelectableSpacing = 0.0f; + float LayoutOuterPadding = 0.0f; + int LayoutColumnCount = 0; + int LayoutLineCount = 0; + // Functions ExampleAssetsBrowser() { @@ -9654,6 +9663,29 @@ struct ExampleAssetsBrowser Selection.Clear(); } + // Logic would be written in the main code BeginChild() and outputing to local variables. + // We extracted it into a function so we can call it easily from multiple places. + void UpdateLayoutSizes(float avail_width) + { + // Layout: when not stretching: allow extending into right-most spacing. + LayoutItemSpacing = (float)IconSpacing; + if (StretchSpacing == false) + avail_width += floorf(LayoutItemSpacing * 0.5f); + + // Layout: calculate number of icon per line and number of lines + LayoutItemSize = ImVec2(floorf(IconSize), floorf(IconSize)); + LayoutColumnCount = IM_MAX((int)(avail_width / (LayoutItemSize.x + LayoutItemSpacing)), 1); + LayoutLineCount = (Items.Size + LayoutColumnCount - 1) / LayoutColumnCount; + + // Layout: when stretching: allocate remaining space to more spacing. Round before division, so item_spacing may be non-integer. + if (StretchSpacing && LayoutColumnCount > 1) + LayoutItemSpacing = floorf(avail_width - LayoutItemSize.x * LayoutColumnCount) / LayoutColumnCount; + + LayoutItemStep = ImVec2(LayoutItemSize.x + LayoutItemSpacing, LayoutItemSize.y + LayoutItemSpacing); + LayoutSelectableSpacing = IM_MAX(floorf(LayoutItemSpacing) - IconHitSpacing, 0.0f); + LayoutOuterPadding = floorf(LayoutItemSpacing * 0.5f); + } + void Draw(const char* title, bool* p_open) { ImGui::SetNextWindowSize(ImVec2(IconSize * 25, IconSize * 15), ImGuiCond_FirstUseEver); @@ -9722,27 +9754,18 @@ struct ExampleAssetsBrowser } ImGui::PopStyleVar(); - if (ImGui::BeginChild("Assets", ImVec2(0, -ImGui::GetTextLineHeightWithSpacing()), true, ImGuiWindowFlags_NoMove)) + ImGuiIO& io = ImGui::GetIO(); + ImGui::SetNextWindowContentSize(ImVec2(0.0f, LayoutOuterPadding + LayoutLineCount * (LayoutItemSize.x + LayoutItemSpacing))); + if (ImGui::BeginChild("Assets", ImVec2(0.0f, -ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_Border, ImGuiWindowFlags_NoMove)) { ImDrawList* draw_list = ImGui::GetWindowDrawList(); - const ImVec2 item_size(floorf(IconSize), floorf(IconSize)); - // Layout: when not stretching: allow extending into right-most spacing. - float item_spacing = (float)IconSpacing; - const float avail_width = ImGui::GetContentRegionAvail().x + (StretchSpacing ? 0.0f : floorf(item_spacing * 0.5f)); - - // Layout: calculate number of icon per line and number of lines - const int column_count = IM_MAX((int)(avail_width / (item_size.x + IconSpacing)), 1); - const int line_count = (Items.Size + column_count - 1) / column_count; - - // Layout: when stretching: allocate remaining space to more spacing. Round before division, so item_spacing may be non-integer. - if (StretchSpacing && column_count > 1) - item_spacing = floorf(avail_width - item_size.x * column_count) / column_count; + const float avail_width = ImGui::GetContentRegionAvail().x; + UpdateLayoutSizes(avail_width); // Calculate and store start position. - const float outer_padding = floorf(item_spacing * 0.5f); ImVec2 start_pos = ImGui::GetCursorScreenPos(); - start_pos = ImVec2(start_pos.x + outer_padding, start_pos.y + outer_padding); + start_pos = ImVec2(start_pos.x + LayoutOuterPadding, start_pos.y + LayoutOuterPadding); ImGui::SetCursorScreenPos(start_pos); // Multi-select @@ -9760,22 +9783,22 @@ struct ExampleAssetsBrowser const int item_curr_idx_to_focus = want_delete ? Selection.ApplyDeletionPreLoop(ms_io, Items.Size) : -1; RequestDelete = false; - // Altering ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()... + // Push LayoutSelectableSpacing (which is LayoutItemSpacing minus hit-spacing, if we decide to have hit gaps between items) + // Altering style ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()... // But it is necessary for two reasons: // - Selectables uses it by default to visually fill the space between two items. // - The vertical spacing would be measured by Clipper to calculate line height if we didn't provide it explicitly (here we do). - const float selectable_spacing = IM_MAX(floorf(item_spacing) - IconHitSpacing, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(selectable_spacing, selectable_spacing)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(LayoutSelectableSpacing, LayoutSelectableSpacing)); // Rendering parameters const ImU32 icon_bg_color = IM_COL32(48, 48, 48, 128); const ImU32 icon_type_overlay_colors[3] = { 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255) }; const ImVec2 icon_type_overlay_size = ImVec2(4.0f, 4.0f); - const bool display_label = (item_size.x >= ImGui::CalcTextSize("999").x); + const bool display_label = (LayoutItemSize.x >= ImGui::CalcTextSize("999").x); - const float line_height = item_size.y + item_spacing; + const int column_count = LayoutColumnCount; ImGuiListClipper clipper; - clipper.Begin(line_count, line_height); + clipper.Begin(LayoutLineCount, LayoutItemStep.y); if (item_curr_idx_to_focus != -1) clipper.IncludeItemByIndex(item_curr_idx_to_focus / column_count); // Ensure focused item line is not clipped. if (ms_io->RangeSrcItem != -1) @@ -9792,17 +9815,17 @@ struct ExampleAssetsBrowser ImGui::PushID((int)item_data->ID); // Position item - ImVec2 pos = ImVec2(start_pos.x + (item_idx % column_count) * (item_size.x + item_spacing), start_pos.y + (line_idx * line_height)); + ImVec2 pos = ImVec2(start_pos.x + (item_idx % column_count) * LayoutItemStep.x, start_pos.y + line_idx * LayoutItemStep.y); ImGui::SetCursorScreenPos(pos); // Draw box ImVec2 box_min(pos.x - 1, pos.y - 1); - ImVec2 box_max(box_min.x + item_size.x + 2, box_min.y + item_size.y + 2); + ImVec2 box_max(box_min.x + LayoutItemSize.x + 2, box_min.y + LayoutItemSize.y + 2); draw_list->AddRect(box_min, box_max, IM_COL32(90, 90, 90, 255)); ImGui::SetNextItemSelectionUserData(item_idx); bool item_is_selected = Selection.Contains((ImGuiID)item_data->ID); - ImGui::Selectable("", item_is_selected, ImGuiSelectableFlags_None, item_size); + ImGui::Selectable("", item_is_selected, ImGuiSelectableFlags_None, LayoutItemSize); // Update our selection state immediately (without waiting for EndMultiSelect() requests) // because we use this to alter the color of our text/icon. @@ -9865,25 +9888,40 @@ struct ExampleAssetsBrowser // FIXME-MULTISELECT: Find a way to expose this in public API. This currently requires "imgui_internal.h" //ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); - } - // Zooming with CTRL+Wheel - // FIXME-MULTISELECT: Try to maintain scroll. - ImGuiIO& io = ImGui::GetIO(); - if (ImGui::IsWindowAppearing()) - ZoomWheelAccum = 0.0f; - if (ImGui::IsWindowHovered() && io.MouseWheel != 0.0f && ImGui::IsKeyDown(ImGuiMod_Ctrl) && ImGui::IsAnyItemActive() == false) - { - ZoomWheelAccum += io.MouseWheel; - if (fabsf(ZoomWheelAccum) >= 1.0f) + // Zooming with CTRL+Wheel + if (ImGui::IsWindowAppearing()) + ZoomWheelAccum = 0.0f; + if (ImGui::IsWindowHovered() && io.MouseWheel != 0.0f && ImGui::IsKeyDown(ImGuiMod_Ctrl) && ImGui::IsAnyItemActive() == false) { - IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum); - IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f); - ZoomWheelAccum -= (int)ZoomWheelAccum; + ZoomWheelAccum += io.MouseWheel; + if (fabsf(ZoomWheelAccum) >= 1.0f) + { + // Calculate hovered item index from mouse location + // FIXME: Locking aiming on 'hovered_item_idx' (with a cool-down timer) would ensure zoom keeps on it. + const float hovered_item_nx = (io.MousePos.x - start_pos.x + LayoutItemSpacing * 0.5f) / LayoutItemStep.x; + const float hovered_item_ny = (io.MousePos.y - start_pos.y + LayoutItemSpacing * 0.5f) / LayoutItemStep.y; + const int hovered_item_idx = ((int)hovered_item_ny * LayoutColumnCount) + (int)hovered_item_nx; + //ImGui::SetTooltip("%f,%f -> item %d", hovered_item_nx, hovered_item_ny, hovered_item_idx); // Move those 4 lines in block above for easy debugging + + // Zoom + IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum); + IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f); + ZoomWheelAccum -= (int)ZoomWheelAccum; + UpdateLayoutSizes(avail_width); + + // Manipulate scroll to that we will land at the same Y location of currently hovered item. + // - Calculate next frame position of item under mouse + // - Set new scroll position to be used in next ImGui::BeginChild() call. + float hovered_item_rel_pos_y = ((float)(hovered_item_idx / LayoutColumnCount) + fmodf(hovered_item_ny, 1.0f)) * LayoutItemStep.y; + hovered_item_rel_pos_y += ImGui::GetStyle().WindowPadding.y; + float mouse_local_y = io.MousePos.y - ImGui::GetWindowPos().y; + ImGui::SetScrollY(hovered_item_rel_pos_y - mouse_local_y); + } } } - ImGui::EndChild(); + ImGui::Text("Selected: %d/%d items", Selection.Size, Items.Size); ImGui::End(); } From 1ac469b50f5c93087d3449754bc5bcbb60584037 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Dec 2023 11:34:25 +0100 Subject: [PATCH 0179/2359] MultiSelect: Box-Select: Fixed holes when using with clipper (in 1D list.) Clipper accounts for Selectable() layout oddity as BoxSelect is sensitive to it. Also tweaked scroll triggering region inward. Rename ImGuiMultiSelectFlags_NoBoxSelectScroll to ImGuiMultiSelectFlags_BoxSelectNoScroll. Fixed use with ImGuiMultiSelectFlags_SinglaSelect. --- imgui.cpp | 18 ++++++++++++++++-- imgui.h | 4 ++-- imgui_demo.cpp | 17 ++++++++++++----- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 42 ++++++++++++++++++++++++++++-------------- 5 files changed, 60 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3128892f0..bee410a72 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3079,9 +3079,23 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0)); // Add visible range + float min_y = window->ClipRect.Min.y; + float max_y = window->ClipRect.Max.y; + + // Add box selection range + if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect) + if (ms->Storage->Window == window && ms->Storage->BoxSelectActive) + { + // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos. + // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that. + // As a workaround we currently half ItemSpacing worth on each side. + min_y -= g.Style.ItemSpacing.y; + max_y += g.Style.ItemSpacing.y; + } + const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0; - data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max)); + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max)); } // Convert position ranges to item index ranges @@ -13438,7 +13452,7 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = bb; - g.DragDropTargetClipRect = window->ClipRect; // May want to be overriden by user depending on use case? + g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case? g.DragDropTargetId = id; g.DragDropWithinTarget = true; return true; diff --git a/imgui.h b/imgui.h index 6de5cec7f..63159a14b 100644 --- a/imgui.h +++ b/imgui.h @@ -2774,8 +2774,8 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut sending a SelectAll request. - ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_NoBoxSelectScroll = 1 << 3, // Disable scrolling when box-selecting near edges of scope. + ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection. Box-selection + clipper is currently only supported for 1D list (not with 2D grid). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 3, // Disable scrolling when box-selecting near edges of scope. ImGuiMultiSelectFlags_ClearOnEscape = 1 << 4, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 5, // Clear selection when clicking on empty location within scope. ImGuiMultiSelectFlags_ScopeWindow = 1 << 6, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if BeginMultiSelect() covers a whole window. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 45b758436..004f89ca1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3031,6 +3031,7 @@ static void ShowDemoWindowMultiSelect() ImGui::BulletText("Shift modifier for range selection."); ImGui::BulletText("CTRL+A to select all."); ImGui::BulletText("Escape to clear selection."); + ImGui::BulletText("Click and drag to box-select."); ImGui::Text("Tip: Use 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen."); // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection @@ -3041,7 +3042,7 @@ static void ShowDemoWindowMultiSelect() // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling region). if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, ITEMS_COUNT); @@ -3076,7 +3077,7 @@ static void ShowDemoWindowMultiSelect() ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, ITEMS_COUNT); @@ -3142,7 +3143,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) { - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape; + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, items.Size); @@ -3259,7 +3260,7 @@ static void ShowDemoWindowMultiSelect() static bool use_drag_drop = true; static bool show_in_table = false; static bool show_color_button = false; - static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; + static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; static WidgetType widget_type = WidgetType_Selectable; if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } @@ -3273,7 +3274,7 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoBoxSelectScroll", &flags, ImGuiMultiSelectFlags_NoBoxSelectScroll); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) @@ -9621,6 +9622,7 @@ struct ExampleAssetsBrowser // Options bool ShowTypeOverlay = true; bool AllowDragUnselected = false; + bool AllowBoxSelect = false; // Unsupported for 2D selection for now. float IconSize = 32.0f; int IconSpacing = 10; int IconHitSpacing = 4; // Increase hit-spacing if you want to make it possible to clear or box-select from gaps. Some spacing is required to able to amend with Shift+box-select. Value is small in Explorer. @@ -9724,6 +9726,9 @@ struct ExampleAssetsBrowser ImGui::SeparatorText("Selection Behavior"); ImGui::Checkbox("Allow dragging unselected item", &AllowDragUnselected); + ImGui::BeginDisabled(); // Unsupported for 2D selection for now. + ImGui::Checkbox("Allow box-selection", &AllowBoxSelect); + ImGui::EndDisabled(); ImGui::SeparatorText("Layout"); ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f"); @@ -9772,6 +9777,8 @@ struct ExampleAssetsBrowser ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickVoid; if (AllowDragUnselected) ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. + if (AllowBoxSelect) + ms_flags |= ImGuiMultiSelectFlags_BoxSelect; // FIXME-MULTISELECT: Box-select not yet supported for 2D selection when using clipper. ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags); // Use custom selection adapter: store ID in selection (recommended) diff --git a/imgui_internal.h b/imgui_internal.h index 65eb5eb89..0b05404e1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1724,8 +1724,8 @@ struct IMGUI_API ImGuiMultiSelectTempData ImVec2 ScopeRectMin; ImVec2 BackupCursorMaxPos; ImGuiID BoxSelectId; - ImRect BoxSelectRectCurr; // Selection rectangle in absolute coordinates (derived from Storage->BoxSelectStartPosRel + MousePos) ImRect BoxSelectRectPrev; + ImRect BoxSelectRectCurr; // Selection rectangle in absolute coordinates (derived every frame from Storage->BoxSelectStartPosRel + MousePos) ImGuiSelectionUserData BoxSelectLastitem; ImGuiKeyChord KeyMods; bool LoopRequestClear; @@ -3102,7 +3102,7 @@ namespace ImGui inline ImRect WindowRectAbsToRel(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); } inline ImRect WindowRectRelToAbs(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); } inline ImVec2 WindowPosRelToAbs(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x + off.x, p.y + off.y); } - inline ImVec2 WindowPosAbsToRel(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x - off.x, p.y - off.y); } + inline ImVec2 WindowPosAbsToRel(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x - off.x, p.y - off.y); } // Windows: Display Order and Focus Order IMGUI_API void FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags = 0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e0b32ac86..52a342e5a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6749,6 +6749,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const ImVec2 text_max(min_x + size.x, pos.y + size.y); // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable. + // FIXME: Not part of layout so not included in clipper calculation, but ItemSize currenty doesn't allow offsetting CursorPos. ImRect bb(min_x, pos.y, text_max.x, text_max.y); if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) { @@ -7135,20 +7136,22 @@ static void BoxSelectStart(ImGuiMultiSelectState* storage, ImGuiSelectionUserDat storage->BoxSelectStartPosRel = storage->BoxSelectEndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); } -static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& r) +static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& inner_r) { ImGuiContext& g = *GImGui; - for (int n = 0; n < 2; n++) + for (int n = 0; n < 2; n++) // each axis { - float dist = (g.IO.MousePos[n] > r.Max[n]) ? g.IO.MousePos[n] - r.Max[n] : (g.IO.MousePos[n] < r.Min[n]) ? g.IO.MousePos[n] - r.Min[n] : 0.0f; - if (dist == 0.0f || (dist < 0.0f && window->Scroll[n] < 0.0f) || (dist > 0.0f && window->Scroll[n] >= window->ScrollMax[n])) + const float mouse_pos = g.IO.MousePos[n]; + const float dist = (mouse_pos > inner_r.Max[n]) ? mouse_pos - inner_r.Max[n] : (mouse_pos < inner_r.Min[n]) ? mouse_pos - inner_r.Min[n] : 0.0f; + const float scroll_curr = window->Scroll[n]; + if (dist == 0.0f || (dist < 0.0f && scroll_curr < 0.0f) || (dist > 0.0f && scroll_curr >= window->ScrollMax[n])) continue; - float speed_multiplier = ImLinearRemapClamp(g.FontSize, g.FontSize * 5.0f, 1.0f, 4.0f, ImAbs(dist)); // x1 to x4 depending on distance - float scroll_step = IM_ROUND(g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime); + const float speed_multiplier = ImLinearRemapClamp(g.FontSize, g.FontSize * 5.0f, 1.0f, 4.0f, ImAbs(dist)); // x1 to x4 depending on distance + const float scroll_step = IM_ROUND(g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime); if (n == 0) - ImGui::SetScrollX(window, window->Scroll[n] + scroll_step); + ImGui::SetScrollX(window, scroll_curr + scroll_step); else - ImGui::SetScrollY(window, window->Scroll[n] + scroll_step); + ImGui::SetScrollY(window, scroll_curr + scroll_step); } } @@ -7165,6 +7168,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) g.CurrentMultiSelect = ms; if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0) flags |= ImGuiMultiSelectFlags_ScopeWindow; + if (flags & ImGuiMultiSelectFlags_SingleSelect) + flags &= ~ImGuiMultiSelectFlags_BoxSelect; // FIXME: BeginFocusScope() const ImGuiID id = window->IDStack.back(); @@ -7250,12 +7255,20 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) } if (storage->BoxSelectActive) { + // Current frame absolute prev/current rectangles are used to toggle selection. + // They are derived from positions relative to scrolling space. + const ImRect scope_rect = window->InnerClipRect; ImVec2 start_pos_abs = WindowPosRelToAbs(window, storage->BoxSelectStartPosRel); - ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, storage->BoxSelectEndPosRel); + ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, storage->BoxSelectEndPosRel); // Clamped already + ImVec2 curr_end_pos_abs = g.IO.MousePos; + if (ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow + curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max); ms->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); ms->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); - ms->BoxSelectRectCurr.Min = ImMin(start_pos_abs, g.IO.MousePos); - ms->BoxSelectRectCurr.Max = ImMax(start_pos_abs, g.IO.MousePos); + ms->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs); + ms->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs); + //GetForegroundDrawList()->AddRect(ms->BoxSelectRectPrev.Min, ms->BoxSelectRectPrev.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); + //GetForegroundDrawList()->AddRect(ms->BoxSelectRectCurr.Min, ms->BoxSelectRectCurr.Max, IM_COL32(0,255,0,200), 0.0f, 0, 1.0f); } } @@ -7303,7 +7316,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && storage->BoxSelectActive) { // Box-select: render selection rectangle - ms->Storage->BoxSelectEndPosRel = WindowPosAbsToRel(window, g.IO.MousePos); + ms->Storage->BoxSelectEndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view ImRect box_select_r = ms->BoxSelectRectCurr; box_select_r.ClipWith(scope_rect); window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling @@ -7311,8 +7324,9 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() // Box-select: scroll ImRect scroll_r = scope_rect; - scroll_r.Expand(g.Style.FramePadding); - if ((ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_NoBoxSelectScroll) == 0 && !scroll_r.Contains(g.IO.MousePos)) + scroll_r.Expand(-g.FontSize); + //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255)); + if ((ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0 && !scroll_r.Contains(g.IO.MousePos)) BoxSelectScrollWithMouseDrag(window, scroll_r); } } From 15391762ddbd4ad03c11dc1746f0603c75036edc Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Dec 2023 21:14:09 +0100 Subject: [PATCH 0180/2359] MultiSelect: Box-Select: Added ImGuiMultiSelectFlags_BoxSelect2d support. Enabled in Asset Browser. Selectable() supports it. --- imgui.cpp | 4 +++ imgui.h | 17 +++++++------ imgui_demo.cpp | 47 +++++++++++++++++----------------- imgui_internal.h | 2 ++ imgui_widgets.cpp | 65 ++++++++++++++++++++++++++++++++--------------- 5 files changed, 84 insertions(+), 51 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bee410a72..8f9a8fbc9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3091,6 +3091,10 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) // As a workaround we currently half ItemSpacing worth on each side. min_y -= g.Style.ItemSpacing.y; max_y += g.Style.ItemSpacing.y; + + // Box-select on 2D area requires different clipping. + if (ms->BoxSelectUnclipMode) + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(ms->BoxSelectUnclipRect.Min.y, ms->BoxSelectUnclipRect.Max.y, 0, 0)); } const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; diff --git a/imgui.h b/imgui.h index 63159a14b..c4b8afa69 100644 --- a/imgui.h +++ b/imgui.h @@ -2774,14 +2774,15 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut sending a SelectAll request. - ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection. Box-selection + clipper is currently only supported for 1D list (not with 2D grid). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 3, // Disable scrolling when box-selecting near edges of scope. - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 4, // Clear selection when pressing Escape while scope is focused. - ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 5, // Clear selection when clicking on empty location within scope. - ImGuiMultiSelectFlags_ScopeWindow = 1 << 6, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if BeginMultiSelect() covers a whole window. - ImGuiMultiSelectFlags_ScopeRect = 1 << 7, // Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. Use if multiple BeginMultiSelect() are used in the same host window. - ImGuiMultiSelectFlags_SelectOnClick = 1 << 8, // Apply selection on mouse down when clicking on unselected item. (Default) - ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 9, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. + ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection (only supporting 1D list when using clipper, not 2D grids). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 3, // Enable box-selection with 2D layout/grid support. This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. + ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 4, // Disable scrolling when box-selecting near edges of scope. + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 5, // Clear selection when pressing Escape while scope is focused. + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 6, // Clear selection when clicking on empty location within scope. + ImGuiMultiSelectFlags_ScopeWindow = 1 << 7, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if BeginMultiSelect() covers a whole window. + ImGuiMultiSelectFlags_ScopeRect = 1 << 8, // Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. Use if multiple BeginMultiSelect() are used in the same host window. + ImGuiMultiSelectFlags_SelectOnClick = 1 << 9, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 10, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. }; enum ImGuiSelectionRequestType diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 004f89ca1..b84a0ca9f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -9622,7 +9622,7 @@ struct ExampleAssetsBrowser // Options bool ShowTypeOverlay = true; bool AllowDragUnselected = false; - bool AllowBoxSelect = false; // Unsupported for 2D selection for now. + bool AllowBoxSelect = true; float IconSize = 32.0f; int IconSpacing = 10; int IconHitSpacing = 4; // Increase hit-spacing if you want to make it possible to clear or box-select from gaps. Some spacing is required to able to amend with Shift+box-select. Value is small in Explorer. @@ -9726,9 +9726,7 @@ struct ExampleAssetsBrowser ImGui::SeparatorText("Selection Behavior"); ImGui::Checkbox("Allow dragging unselected item", &AllowDragUnselected); - ImGui::BeginDisabled(); // Unsupported for 2D selection for now. ImGui::Checkbox("Allow box-selection", &AllowBoxSelect); - ImGui::EndDisabled(); ImGui::SeparatorText("Layout"); ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f"); @@ -9778,7 +9776,7 @@ struct ExampleAssetsBrowser if (AllowDragUnselected) ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. if (AllowBoxSelect) - ms_flags |= ImGuiMultiSelectFlags_BoxSelect; // FIXME-MULTISELECT: Box-select not yet supported for 2D selection when using clipper. + ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; // Enable box-select in 2D mode. ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags); // Use custom selection adapter: store ID in selection (recommended) @@ -9798,7 +9796,6 @@ struct ExampleAssetsBrowser ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(LayoutSelectableSpacing, LayoutSelectableSpacing)); // Rendering parameters - const ImU32 icon_bg_color = IM_COL32(48, 48, 48, 128); const ImU32 icon_type_overlay_colors[3] = { 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255) }; const ImVec2 icon_type_overlay_size = ImVec2(4.0f, 4.0f); const bool display_label = (LayoutItemSize.x >= ImGui::CalcTextSize("999").x); @@ -9825,13 +9822,9 @@ struct ExampleAssetsBrowser ImVec2 pos = ImVec2(start_pos.x + (item_idx % column_count) * LayoutItemStep.x, start_pos.y + line_idx * LayoutItemStep.y); ImGui::SetCursorScreenPos(pos); - // Draw box - ImVec2 box_min(pos.x - 1, pos.y - 1); - ImVec2 box_max(box_min.x + LayoutItemSize.x + 2, box_min.y + LayoutItemSize.y + 2); - draw_list->AddRect(box_min, box_max, IM_COL32(90, 90, 90, 255)); - ImGui::SetNextItemSelectionUserData(item_idx); bool item_is_selected = Selection.Contains((ImGuiID)item_data->ID); + bool item_is_visible = ImGui::IsRectVisible(LayoutItemSize); ImGui::Selectable("", item_is_selected, ImGuiSelectableFlags_None, LayoutItemSize); // Update our selection state immediately (without waiting for EndMultiSelect() requests) @@ -9856,19 +9849,26 @@ struct ExampleAssetsBrowser ImGui::EndDragDropSource(); } - // A real app would likely display an image/thumbnail here. - draw_list->AddRectFilled(box_min, box_max, icon_bg_color); - if (ShowTypeOverlay && item_data->Type != 0) + // Render icon (a real app would likely display an image/thumbnail here) + // Because we use ImGuiMultiSelectFlags_BoxSelect2d mode, + // clipping vertical range may occasionally be larger so we coarse-clip our rendering. + if (item_is_visible) { - ImU32 type_col = icon_type_overlay_colors[item_data->Type % IM_ARRAYSIZE(icon_type_overlay_colors)]; - draw_list->AddRectFilled(ImVec2(box_max.x - 2 - icon_type_overlay_size.x, box_min.y + 2), ImVec2(box_max.x - 2, box_min.y + 2 + icon_type_overlay_size.y), type_col); - } - if (display_label) - { - ImU32 label_col = item_is_selected ? IM_COL32(255, 255, 255, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled); - char label[32]; - sprintf(label, "%d", item_data->ID); - draw_list->AddText(ImVec2(box_min.x, box_max.y - ImGui::GetFontSize()), label_col, label); + ImVec2 box_min(pos.x - 1, pos.y - 1); + ImVec2 box_max(box_min.x + LayoutItemSize.x + 2, box_min.y + LayoutItemSize.y + 2); // Dubious + draw_list->AddRectFilled(box_min, box_max, IM_COL32(48, 48, 48, 200)); // Background color + if (ShowTypeOverlay && item_data->Type != 0) + { + ImU32 type_col = icon_type_overlay_colors[item_data->Type % IM_ARRAYSIZE(icon_type_overlay_colors)]; + draw_list->AddRectFilled(ImVec2(box_max.x - 2 - icon_type_overlay_size.x, box_min.y + 2), ImVec2(box_max.x - 2, box_min.y + 2 + icon_type_overlay_size.y), type_col); + } + if (display_label) + { + ImU32 label_col = item_is_selected ? IM_COL32(255, 255, 255, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled); + char label[32]; + sprintf(label, "%d", item_data->ID); + draw_list->AddText(ImVec2(box_min.x, box_max.y - ImGui::GetFontSize()), label_col, label); + } } ImGui::PopID(); @@ -9893,7 +9893,8 @@ struct ExampleAssetsBrowser if (want_delete) Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus); - // FIXME-MULTISELECT: Find a way to expose this in public API. This currently requires "imgui_internal.h" + // Keyboard/Gamepad Wrapping + // FIXME-MULTISELECT: Currently an imgui_internal.h API. Find a design/way to expose this in public API. //ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); // Zooming with CTRL+Wheel diff --git a/imgui_internal.h b/imgui_internal.h index 0b05404e1..968a9413f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1726,8 +1726,10 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiID BoxSelectId; ImRect BoxSelectRectPrev; ImRect BoxSelectRectCurr; // Selection rectangle in absolute coordinates (derived every frame from Storage->BoxSelectStartPosRel + MousePos) + ImRect BoxSelectUnclipRect;// Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. ImGuiSelectionUserData BoxSelectLastitem; ImGuiKeyChord KeyMods; + bool BoxSelectUnclipMode; bool LoopRequestClear; bool LoopRequestSelectAll; bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 52a342e5a..050136a88 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6775,7 +6775,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; const bool is_multi_select = (g.NextItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0; // Before ItemAdd() - const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); + const bool is_visible = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); if (span_all_columns) { @@ -6783,8 +6783,14 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl window->ClipRect.Max.x = backup_clip_rect_max_x; } - if (!item_add) - return false; + if (!is_visible) + { + if (!is_multi_select) + return false; + // Extra layer of "no logic clip" for box-select support + if (!g.CurrentMultiSelect->BoxSelectUnclipMode || !g.CurrentMultiSelect->BoxSelectUnclipRect.Overlaps(bb)) + return false; + } const bool disabled_global = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; if (disabled_item && !disabled_global) // Only testing this as an optimization @@ -6857,22 +6863,25 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render - if (hovered || selected) + if (is_visible) { - // FIXME-MULTISELECT: Styling: Color for 'selected' elements? ImGuiCol_HeaderSelected - ImU32 col; - if (selected && !hovered) - col = GetColorU32(ImLerp(GetStyleColorVec4(ImGuiCol_Header), GetStyleColorVec4(ImGuiCol_HeaderHovered), 0.5f)); - else - col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); - RenderFrame(bb.Min, bb.Max, col, false, 0.0f); - } - if (g.NavId == id) - { - ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_Compact | ImGuiNavHighlightFlags_NoRounding; - if (is_multi_select) - nav_highlight_flags |= ImGuiNavHighlightFlags_AlwaysDraw; // Always show the nav rectangle - RenderNavHighlight(bb, id, nav_highlight_flags); + if (hovered || selected) + { + // FIXME-MULTISELECT: Styling: Color for 'selected' elements? ImGuiCol_HeaderSelected + ImU32 col; + if (selected && !hovered) + col = GetColorU32(ImLerp(GetStyleColorVec4(ImGuiCol_Header), GetStyleColorVec4(ImGuiCol_HeaderHovered), 0.5f)); + else + col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + } + if (g.NavId == id) + { + ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_Compact | ImGuiNavHighlightFlags_NoRounding; + if (is_multi_select) + nav_highlight_flags |= ImGuiNavHighlightFlags_AlwaysDraw; // Always show the nav rectangle + RenderNavHighlight(bb, id, nav_highlight_flags); + } } if (span_all_columns) @@ -6883,7 +6892,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl PopColumnsBackground(); } - RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); + if (is_visible) + RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); // Automatically close popups if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.InFlags & ImGuiItemFlags_AutoClosePopups)) @@ -7169,7 +7179,9 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0) flags |= ImGuiMultiSelectFlags_ScopeWindow; if (flags & ImGuiMultiSelectFlags_SingleSelect) - flags &= ~ImGuiMultiSelectFlags_BoxSelect; + flags &= ~(ImGuiMultiSelectFlags_BoxSelect | ImGuiMultiSelectFlags_BoxSelect2d); + if (flags & ImGuiMultiSelectFlags_BoxSelect2d) + flags |= ImGuiMultiSelectFlags_BoxSelect; // FIXME: BeginFocusScope() const ImGuiID id = window->IDStack.back(); @@ -7233,6 +7245,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) } // Box-select handling: update active state. + ms->BoxSelectUnclipMode = false; if (flags & ImGuiMultiSelectFlags_BoxSelect) { ms->BoxSelectId = GetID("##BoxSelect"); @@ -7267,6 +7280,18 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) ms->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); ms->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs); ms->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs); + + // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper) + // Storing an extra rect used by widgets supporting box-select. + if (flags & ImGuiMultiSelectFlags_BoxSelect2d) + if (ms->BoxSelectRectPrev.Min.x != ms->BoxSelectRectCurr.Min.x || ms->BoxSelectRectPrev.Max.x != ms->BoxSelectRectCurr.Max.x) + { + ms->BoxSelectUnclipRect = ms->BoxSelectRectPrev; + ms->BoxSelectUnclipRect.Add(ms->BoxSelectRectCurr); + ms->BoxSelectUnclipMode = true; + } + + //GetForegroundDrawList()->AddRect(ms->BoxSelectNoClipRect.Min, ms->BoxSelectNoClipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); //GetForegroundDrawList()->AddRect(ms->BoxSelectRectPrev.Min, ms->BoxSelectRectPrev.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); //GetForegroundDrawList()->AddRect(ms->BoxSelectRectCurr.Min, ms->BoxSelectRectCurr.Max, IM_COL32(0,255,0,200), 0.0f, 0, 1.0f); } From 75bac1aac67570109d0ca4fb87bd03a73ec30fb2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Dec 2023 22:07:28 +0100 Subject: [PATCH 0181/2359] MultiSelect: Box-Select: Refactor into its own structure, designed for single-instance but closer to being reusable outside Multi-Select. Kept same member names. --- imgui.cpp | 10 ++-- imgui_internal.h | 47 ++++++++++------ imgui_widgets.cpp | 133 ++++++++++++++++++++++++++-------------------- 3 files changed, 113 insertions(+), 77 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8f9a8fbc9..d82d48c51 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3083,8 +3083,8 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) float max_y = window->ClipRect.Max.y; // Add box selection range - if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect) - if (ms->Storage->Window == window && ms->Storage->BoxSelectActive) + if (ImGuiBoxSelectState* bs = &g.BoxSelectState) + if (bs->BoxSelectActive && bs->BoxSelectWindow == window) { // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos. // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that. @@ -3093,8 +3093,8 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) max_y += g.Style.ItemSpacing.y; // Box-select on 2D area requires different clipping. - if (ms->BoxSelectUnclipMode) - data->Ranges.push_back(ImGuiListClipperRange::FromPositions(ms->BoxSelectUnclipRect.Min.y, ms->BoxSelectUnclipRect.Max.y, 0, 0)); + if (bs->BoxSelectUnclipMode) + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->BoxSelectUnclipRect.Min.y, bs->BoxSelectUnclipRect.Max.y, 0, 0)); } const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; @@ -14997,6 +14997,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Details for MultiSelect if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount())) { + ImGuiBoxSelectState* ms = &g.BoxSelectState; + Text("BoxSelect ID=0x%08X, Starting = %d, Active %d", ms->BoxSelectId, ms->BoxSelectStarting, ms->BoxSelectActive); for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++) if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n)) DebugNodeMultiSelectState(state); diff --git a/imgui_internal.h b/imgui_internal.h index 968a9413f..165e3c058 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -22,6 +22,7 @@ Index of this file: // [SECTION] Navigation support // [SECTION] Typing-select support // [SECTION] Columns support +// [SECTION] Box-select support // [SECTION] Multi-select support // [SECTION] Docking support // [SECTION] Viewport support @@ -123,6 +124,7 @@ struct ImBitVector; // Store 1-bit per value struct ImRect; // An axis-aligned rectangle (2 points) struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances +struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it struct ImGuiContext; // Main Dear ImGui context struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine @@ -1705,6 +1707,32 @@ struct ImGuiOldColumns ImGuiOldColumns() { memset(this, 0, sizeof(*this)); } }; +//----------------------------------------------------------------------------- +// [SECTION] Box-select support +//----------------------------------------------------------------------------- + +struct ImGuiBoxSelectState +{ + // Active box-selection data (persistent, 1 active at a time) + ImGuiID BoxSelectId; + bool BoxSelectActive; + bool BoxSelectStarting; + bool BoxSelectFromVoid; + ImGuiKeyChord BoxSelectKeyMods : 16; // Latched key-mods for box-select logic. + ImVec2 BoxSelectStartPosRel; // Start position in window-relative space (to support scrolling) + ImVec2 BoxSelectEndPosRel; // End position in window-relative space + ImGuiWindow* BoxSelectWindow; + + // Temporary/Transient data + bool BoxSelectUnclipMode; // Set/cleared by the BeginMultiSelect()/EndMultiSelect() owning active box-select. + ImRect BoxSelectRectPrev; // Selection rectangle in absolute coordinates (derived every frame from BoxSelectStartPosRel and MousePos) + ImRect BoxSelectRectCurr; + ImRect BoxSelectUnclipRect; // Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. + ImGuiSelectionUserData BoxSelectLastitem; + + ImGuiBoxSelectState() { memset(this, 0, sizeof(*this)); } +}; + //----------------------------------------------------------------------------- // [SECTION] Multi-select support //----------------------------------------------------------------------------- @@ -1724,12 +1752,7 @@ struct IMGUI_API ImGuiMultiSelectTempData ImVec2 ScopeRectMin; ImVec2 BackupCursorMaxPos; ImGuiID BoxSelectId; - ImRect BoxSelectRectPrev; - ImRect BoxSelectRectCurr; // Selection rectangle in absolute coordinates (derived every frame from Storage->BoxSelectStartPosRel + MousePos) - ImRect BoxSelectUnclipRect;// Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. - ImGuiSelectionUserData BoxSelectLastitem; ImGuiKeyChord KeyMods; - bool BoxSelectUnclipMode; bool LoopRequestClear; bool LoopRequestSelectAll; bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. @@ -1740,7 +1763,7 @@ struct IMGUI_API ImGuiMultiSelectTempData bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. ImGuiMultiSelectTempData() { Clear(); } - void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); BoxSelectLastitem = -1; } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. + void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. void ClearIO() { IO.Requests.resize(0); IO.RangeSrcItem = IO.NavIdItem = (ImGuiSelectionUserData)-1; IO.NavIdSelected = IO.RangeSrcReset = false; } }; @@ -1755,15 +1778,7 @@ struct IMGUI_API ImGuiMultiSelectState ImGuiSelectionUserData RangeSrcItem; // ImGuiSelectionUserData NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) - bool BoxSelectActive; - bool BoxSelectStarting; - bool BoxSelectFromVoid; - ImGuiKeyChord BoxSelectKeyMods : 16; // Latched key-mods for box-select logic. - ImVec2 BoxSelectStartPosRel; // Start position in window-relative space (to support scrolling) - ImVec2 BoxSelectEndPosRel; // End position in window-relative space - - ImGuiMultiSelectState() { Init(0); } - void Init(ImGuiID id) { Window = NULL; ID = id; LastFrameActive = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; BoxSelectActive = BoxSelectStarting = BoxSelectFromVoid = false; BoxSelectKeyMods = 0; } + ImGuiMultiSelectState() { Window = NULL; ID = 0; LastFrameActive = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT @@ -2203,6 +2218,7 @@ struct ImGuiContext ImVector ShrinkWidthBuffer; // Multi-Select state + ImGuiBoxSelectState BoxSelectState; ImGuiMultiSelectTempData* CurrentMultiSelect; int MultiSelectTempDataStacked; // Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) ImVector MultiSelectTempData; @@ -3389,6 +3405,7 @@ namespace ImGui // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); + inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.BoxSelectId == id && g.BoxSelectState.BoxSelectActive) ? &g.BoxSelectState : NULL; } // Internal 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 050136a88..7470b607e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -19,6 +19,7 @@ Index of this file: // [SECTION] Widgets: TreeNode, CollapsingHeader, etc. // [SECTION] Widgets: Selectable // [SECTION] Widgets: Typing-Select support +// [SECTION] Widgets: Box-Select support // [SECTION] Widgets: Multi-Select support // [SECTION] Widgets: ListBox // [SECTION] Widgets: PlotLines, PlotHistogram @@ -6788,7 +6789,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (!is_multi_select) return false; // Extra layer of "no logic clip" for box-select support - if (!g.CurrentMultiSelect->BoxSelectUnclipMode || !g.CurrentMultiSelect->BoxSelectUnclipRect.Overlaps(bb)) + if (!g.BoxSelectState.BoxSelectUnclipMode || !g.BoxSelectState.BoxSelectUnclipRect.Overlaps(bb)) return false; } @@ -7110,40 +7111,22 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) #endif } - //------------------------------------------------------------------------- -// [SECTION] Widgets: Multi-Select support +// [SECTION] Widgets: Box-Select support //------------------------------------------------------------------------- -// - DebugLogMultiSelectRequests() [Internal] // - BoxSelectStart() [Internal] // - BoxSelectScrollWithMouseDrag() [Internal] -// - BeginMultiSelect() -// - EndMultiSelect() -// - SetNextItemSelectionUserData() -// - MultiSelectItemHeader() [Internal] -// - MultiSelectItemFooter() [Internal] -// - DebugNodeMultiSelectState() [Internal] -// - ImGuiSelectionBasicStorage //------------------------------------------------------------------------- -static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io) +static void BoxSelectStart(ImGuiID id, ImGuiSelectionUserData clicked_item) { ImGuiContext& g = *GImGui; - for (const ImGuiSelectionRequest& req : io->Requests) - { - if (req.Type == ImGuiSelectionRequestType_Clear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: Clear\n", function); - if (req.Type == ImGuiSelectionRequestType_SelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SelectAll\n", function); - if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.RangeSelected); - } -} - -static void BoxSelectStart(ImGuiMultiSelectState* storage, ImGuiSelectionUserData clicked_item) -{ - ImGuiContext& g = *GImGui; - storage->BoxSelectStarting = true; // Consider starting box-select. - storage->BoxSelectFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid); - storage->BoxSelectKeyMods = g.IO.KeyMods; - storage->BoxSelectStartPosRel = storage->BoxSelectEndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); + ImGuiBoxSelectState* bs = &g.BoxSelectState; + bs->BoxSelectId = id; + bs->BoxSelectStarting = true; // Consider starting box-select. + bs->BoxSelectFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid); + bs->BoxSelectKeyMods = g.IO.KeyMods; + bs->BoxSelectStartPosRel = bs->BoxSelectEndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); } static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& inner_r) @@ -7165,6 +7148,31 @@ static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& inne } } + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Multi-Select support +//------------------------------------------------------------------------- +// - DebugLogMultiSelectRequests() [Internal] +// - BeginMultiSelect() +// - EndMultiSelect() +// - SetNextItemSelectionUserData() +// - MultiSelectItemHeader() [Internal] +// - MultiSelectItemFooter() [Internal] +// - DebugNodeMultiSelectState() [Internal] +// - ImGuiSelectionBasicStorage +//------------------------------------------------------------------------- + +static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io) +{ + ImGuiContext& g = *GImGui; + for (const ImGuiSelectionRequest& req : io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_Clear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: Clear\n", function); + if (req.Type == ImGuiSelectionRequestType_SelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SelectAll\n", function); + if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.RangeSelected); + } +} + // Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) { @@ -7245,50 +7253,57 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) } // Box-select handling: update active state. - ms->BoxSelectUnclipMode = false; + ImGuiBoxSelectState* bs = &g.BoxSelectState; if (flags & ImGuiMultiSelectFlags_BoxSelect) { ms->BoxSelectId = GetID("##BoxSelect"); KeepAliveID(ms->BoxSelectId); + } + if ((flags & ImGuiMultiSelectFlags_BoxSelect) && ms->BoxSelectId == bs->BoxSelectId) + { + bs->BoxSelectUnclipMode = false; // BoxSelectStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. - if (storage->BoxSelectStarting && IsMouseDragPastThreshold(0)) + if (bs->BoxSelectStarting && IsMouseDragPastThreshold(0)) { - storage->BoxSelectActive = true; - storage->BoxSelectStarting = false; + bs->BoxSelectActive = true; + bs->BoxSelectWindow = ms->Storage->Window; + bs->BoxSelectStarting = false; SetActiveID(ms->BoxSelectId, window); - if (storage->BoxSelectFromVoid && (storage->BoxSelectKeyMods & ImGuiMod_Shift) == 0) + if (bs->BoxSelectFromVoid && (bs->BoxSelectKeyMods & ImGuiMod_Shift) == 0) request_clear = true; } - else if ((storage->BoxSelectStarting || storage->BoxSelectActive) && g.IO.MouseDown[0] == false) + else if ((bs->BoxSelectStarting || bs->BoxSelectActive) && g.IO.MouseDown[0] == false) { - storage->BoxSelectActive = storage->BoxSelectStarting = false; + bs->BoxSelectId = 0; + bs->BoxSelectActive = bs->BoxSelectStarting = false; if (g.ActiveId == ms->BoxSelectId) ClearActiveID(); } - if (storage->BoxSelectActive) + if (bs->BoxSelectActive) { // Current frame absolute prev/current rectangles are used to toggle selection. // They are derived from positions relative to scrolling space. const ImRect scope_rect = window->InnerClipRect; - ImVec2 start_pos_abs = WindowPosRelToAbs(window, storage->BoxSelectStartPosRel); - ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, storage->BoxSelectEndPosRel); // Clamped already + ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->BoxSelectStartPosRel); + ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->BoxSelectEndPosRel); // Clamped already ImVec2 curr_end_pos_abs = g.IO.MousePos; if (ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max); - ms->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); - ms->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); - ms->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs); - ms->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs); + bs->BoxSelectLastitem = -1; + bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); + bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); + bs->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs); + bs->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs); // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper) // Storing an extra rect used by widgets supporting box-select. if (flags & ImGuiMultiSelectFlags_BoxSelect2d) - if (ms->BoxSelectRectPrev.Min.x != ms->BoxSelectRectCurr.Min.x || ms->BoxSelectRectPrev.Max.x != ms->BoxSelectRectCurr.Max.x) + if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x) { - ms->BoxSelectUnclipRect = ms->BoxSelectRectPrev; - ms->BoxSelectUnclipRect.Add(ms->BoxSelectRectCurr); - ms->BoxSelectUnclipMode = true; + bs->BoxSelectUnclipRect = bs->BoxSelectRectPrev; + bs->BoxSelectUnclipRect.Add(bs->BoxSelectRectCurr); + bs->BoxSelectUnclipMode = true; } //GetForegroundDrawList()->AddRect(ms->BoxSelectNoClipRect.Min, ms->BoxSelectNoClipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); @@ -7338,11 +7353,12 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() storage->NavIdSelected = -1; } - if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && storage->BoxSelectActive) + ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId); + if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && bs != NULL) { // Box-select: render selection rectangle - ms->Storage->BoxSelectEndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view - ImRect box_select_r = ms->BoxSelectRectCurr; + bs->BoxSelectEndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view + ImRect box_select_r = bs->BoxSelectRectCurr; box_select_r.ClipWith(scope_rect); window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavHighlight)); // FIXME-MULTISELECT: Styling @@ -7353,6 +7369,8 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255)); if ((ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0 && !scroll_r.Contains(g.IO.MousePos)) BoxSelectScrollWithMouseDrag(window, scroll_r); + + bs->BoxSelectUnclipMode = false; } } @@ -7365,8 +7383,8 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0) { if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) - if (!storage->BoxSelectActive && !storage->BoxSelectStarting && g.IO.MouseClickedCount[0] == 1) - BoxSelectStart(storage, ImGuiSelectionUserData_Invalid); + if (!g.BoxSelectState.BoxSelectActive && !g.BoxSelectState.BoxSelectStarting && g.IO.MouseClickedCount[0] == 1) + BoxSelectStart(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) @@ -7516,21 +7534,21 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } // Box-select handling - if (ms->Storage->BoxSelectActive) + if (ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId)) { - const bool rect_overlap_curr = ms->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect); - const bool rect_overlap_prev = ms->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect); + const bool rect_overlap_curr = bs->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect); + const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect); if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr)) { selected = !selected; ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->RangeSelected == selected) + if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == bs->BoxSelectLastitem && prev_req->RangeSelected == selected) prev_req->RangeLastItem = item_data; // Merge span into same request else ms->IO.Requests.push_back(req); } - ms->BoxSelectLastitem = item_data; + bs->BoxSelectLastitem = item_data; } // Right-click handling: this could be moved at the Selectable() level. @@ -7558,8 +7576,8 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Box-select ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) - if (selected == false && !storage->BoxSelectActive && !storage->BoxSelectStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) - BoxSelectStart(storage, item_data); + if (selected == false && !g.BoxSelectState.BoxSelectActive && !g.BoxSelectState.BoxSelectStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) + BoxSelectStart(ms->BoxSelectId, item_data); //---------------------------------------------------------------------------------------- // ACTION | Begin | Pressed/Activated | End @@ -7645,7 +7663,6 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) return; Text("RangeSrcItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), RangeSelected = %d", storage->RangeSrcItem, storage->RangeSrcItem, storage->RangeSelected); Text("NavIdItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), NavIdSelected = %d", storage->NavIdItem, storage->NavIdItem, storage->NavIdSelected); - Text("BoxSelect Starting = %d, Active %d", storage->BoxSelectStarting, storage->BoxSelectActive); TreePop(); #else IM_UNUSED(storage); From 5d9de14493c39ec1ca00eed1be4b1e02761857e4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Dec 2023 22:19:55 +0100 Subject: [PATCH 0182/2359] MultiSelect: Box-Select: Refactor: Renames. Split into two commits to facilite looking into previous one if needed. --- imgui.cpp | 26 ++++++++++----------- imgui_internal.h | 26 ++++++++++----------- imgui_widgets.cpp | 58 +++++++++++++++++++++++------------------------ 3 files changed, 55 insertions(+), 55 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d82d48c51..ffbebea7c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3083,19 +3083,19 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) float max_y = window->ClipRect.Max.y; // Add box selection range - if (ImGuiBoxSelectState* bs = &g.BoxSelectState) - if (bs->BoxSelectActive && bs->BoxSelectWindow == window) - { - // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos. - // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that. - // As a workaround we currently half ItemSpacing worth on each side. - min_y -= g.Style.ItemSpacing.y; - max_y += g.Style.ItemSpacing.y; + ImGuiBoxSelectState* bs = &g.BoxSelectState; + if (bs->IsActive && bs->Window == window) + { + // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos. + // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that. + // As a workaround we currently half ItemSpacing worth on each side. + min_y -= g.Style.ItemSpacing.y; + max_y += g.Style.ItemSpacing.y; - // Box-select on 2D area requires different clipping. - if (bs->BoxSelectUnclipMode) - data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->BoxSelectUnclipRect.Min.y, bs->BoxSelectUnclipRect.Max.y, 0, 0)); - } + // Box-select on 2D area requires different clipping. + if (bs->UnclipMode) + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0)); + } const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0; @@ -14998,7 +14998,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount())) { ImGuiBoxSelectState* ms = &g.BoxSelectState; - Text("BoxSelect ID=0x%08X, Starting = %d, Active %d", ms->BoxSelectId, ms->BoxSelectStarting, ms->BoxSelectActive); + Text("BoxSelect ID=0x%08X, Starting = %d, Active %d", ms->ID, ms->IsStarting, ms->IsActive); for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++) if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n)) DebugNodeMultiSelectState(state); diff --git a/imgui_internal.h b/imgui_internal.h index 165e3c058..8e71683f4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1714,21 +1714,21 @@ struct ImGuiOldColumns struct ImGuiBoxSelectState { // Active box-selection data (persistent, 1 active at a time) - ImGuiID BoxSelectId; - bool BoxSelectActive; - bool BoxSelectStarting; - bool BoxSelectFromVoid; - ImGuiKeyChord BoxSelectKeyMods : 16; // Latched key-mods for box-select logic. - ImVec2 BoxSelectStartPosRel; // Start position in window-relative space (to support scrolling) - ImVec2 BoxSelectEndPosRel; // End position in window-relative space - ImGuiWindow* BoxSelectWindow; + ImGuiID ID; + bool IsActive; + bool IsStarting; + bool IsStartedFromVoid; // Starting click was not from an item. + ImGuiKeyChord KeyMods : 16; // Latched key-mods for box-select logic. + ImVec2 StartPosRel; // Start position in window-contents relative space (to support scrolling) + ImVec2 EndPosRel; // End position in window-contents relative space + ImGuiWindow* Window; // Temporary/Transient data - bool BoxSelectUnclipMode; // Set/cleared by the BeginMultiSelect()/EndMultiSelect() owning active box-select. - ImRect BoxSelectRectPrev; // Selection rectangle in absolute coordinates (derived every frame from BoxSelectStartPosRel and MousePos) + bool UnclipMode; // (Temp/Transient, here in hot area). Set/cleared by the BeginMultiSelect()/EndMultiSelect() owning active box-select. + ImRect UnclipRect; // Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. + ImRect BoxSelectRectPrev; // Selection rectangle in absolute coordinates (derived every frame from BoxSelectStartPosRel and MousePos) ImRect BoxSelectRectCurr; - ImRect BoxSelectUnclipRect; // Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. - ImGuiSelectionUserData BoxSelectLastitem; + ImGuiSelectionUserData LastSubmittedItem; // Copy of last submitted item data, used to merge output ranges. ImGuiBoxSelectState() { memset(this, 0, sizeof(*this)); } }; @@ -3405,7 +3405,7 @@ namespace ImGui // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); - inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.BoxSelectId == id && g.BoxSelectState.BoxSelectActive) ? &g.BoxSelectState : NULL; } + inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.ID == id && g.BoxSelectState.IsActive) ? &g.BoxSelectState : NULL; } // Internal 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7470b607e..7f3e529ca 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6789,7 +6789,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (!is_multi_select) return false; // Extra layer of "no logic clip" for box-select support - if (!g.BoxSelectState.BoxSelectUnclipMode || !g.BoxSelectState.BoxSelectUnclipRect.Overlaps(bb)) + if (!g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(bb)) return false; } @@ -7122,11 +7122,11 @@ static void BoxSelectStart(ImGuiID id, ImGuiSelectionUserData clicked_item) { ImGuiContext& g = *GImGui; ImGuiBoxSelectState* bs = &g.BoxSelectState; - bs->BoxSelectId = id; - bs->BoxSelectStarting = true; // Consider starting box-select. - bs->BoxSelectFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid); - bs->BoxSelectKeyMods = g.IO.KeyMods; - bs->BoxSelectStartPosRel = bs->BoxSelectEndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); + bs->ID = id; + bs->IsStarting = true; // Consider starting box-select. + bs->IsStartedFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid); + bs->KeyMods = g.IO.KeyMods; + bs->StartPosRel = bs->EndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); } static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& inner_r) @@ -7259,38 +7259,38 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) ms->BoxSelectId = GetID("##BoxSelect"); KeepAliveID(ms->BoxSelectId); } - if ((flags & ImGuiMultiSelectFlags_BoxSelect) && ms->BoxSelectId == bs->BoxSelectId) + if ((flags & ImGuiMultiSelectFlags_BoxSelect) && ms->BoxSelectId == bs->ID) { - bs->BoxSelectUnclipMode = false; + bs->UnclipMode = false; // BoxSelectStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. - if (bs->BoxSelectStarting && IsMouseDragPastThreshold(0)) + if (bs->IsStarting && IsMouseDragPastThreshold(0)) { - bs->BoxSelectActive = true; - bs->BoxSelectWindow = ms->Storage->Window; - bs->BoxSelectStarting = false; + bs->IsActive = true; + bs->Window = ms->Storage->Window; + bs->IsStarting = false; SetActiveID(ms->BoxSelectId, window); - if (bs->BoxSelectFromVoid && (bs->BoxSelectKeyMods & ImGuiMod_Shift) == 0) + if (bs->IsStartedFromVoid && (bs->KeyMods & ImGuiMod_Shift) == 0) request_clear = true; } - else if ((bs->BoxSelectStarting || bs->BoxSelectActive) && g.IO.MouseDown[0] == false) + else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false) { - bs->BoxSelectId = 0; - bs->BoxSelectActive = bs->BoxSelectStarting = false; + bs->ID = 0; + bs->IsActive = bs->IsStarting = false; if (g.ActiveId == ms->BoxSelectId) ClearActiveID(); } - if (bs->BoxSelectActive) + if (bs->IsActive) { // Current frame absolute prev/current rectangles are used to toggle selection. // They are derived from positions relative to scrolling space. const ImRect scope_rect = window->InnerClipRect; - ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->BoxSelectStartPosRel); - ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->BoxSelectEndPosRel); // Clamped already + ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->StartPosRel); + ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->EndPosRel); // Clamped already ImVec2 curr_end_pos_abs = g.IO.MousePos; if (ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max); - bs->BoxSelectLastitem = -1; + bs->LastSubmittedItem = ImGuiSelectionUserData_Invalid; bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); bs->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs); @@ -7301,9 +7301,9 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (flags & ImGuiMultiSelectFlags_BoxSelect2d) if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x) { - bs->BoxSelectUnclipRect = bs->BoxSelectRectPrev; - bs->BoxSelectUnclipRect.Add(bs->BoxSelectRectCurr); - bs->BoxSelectUnclipMode = true; + bs->UnclipRect = bs->BoxSelectRectPrev; + bs->UnclipRect.Add(bs->BoxSelectRectCurr); + bs->UnclipMode = true; } //GetForegroundDrawList()->AddRect(ms->BoxSelectNoClipRect.Min, ms->BoxSelectNoClipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); @@ -7357,7 +7357,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && bs != NULL) { // Box-select: render selection rectangle - bs->BoxSelectEndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view + bs->EndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view ImRect box_select_r = bs->BoxSelectRectCurr; box_select_r.ClipWith(scope_rect); window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling @@ -7370,7 +7370,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if ((ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0 && !scroll_r.Contains(g.IO.MousePos)) BoxSelectScrollWithMouseDrag(window, scroll_r); - bs->BoxSelectUnclipMode = false; + bs->UnclipMode = false; } } @@ -7383,7 +7383,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0) { if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) - if (!g.BoxSelectState.BoxSelectActive && !g.BoxSelectState.BoxSelectStarting && g.IO.MouseClickedCount[0] == 1) + if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1) BoxSelectStart(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) @@ -7543,12 +7543,12 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = !selected; ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == bs->BoxSelectLastitem && prev_req->RangeSelected == selected) + if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == bs->LastSubmittedItem && prev_req->RangeSelected == selected) prev_req->RangeLastItem = item_data; // Merge span into same request else ms->IO.Requests.push_back(req); } - bs->BoxSelectLastitem = item_data; + bs->LastSubmittedItem = item_data; } // Right-click handling: this could be moved at the Selectable() level. @@ -7576,7 +7576,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Box-select ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) - if (selected == false && !g.BoxSelectState.BoxSelectActive && !g.BoxSelectState.BoxSelectStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) + if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) BoxSelectStart(ms->BoxSelectId, item_data); //---------------------------------------------------------------------------------------- From 907268a4305b77920a94453214a35637e981b0ab Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Dec 2023 22:31:07 +0100 Subject: [PATCH 0183/2359] MultiSelect: Box-Select: Fixed scrolling on high framerates. --- imgui_internal.h | 1 + imgui_widgets.cpp | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 8e71683f4..7c0c6aa22 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1721,6 +1721,7 @@ struct ImGuiBoxSelectState ImGuiKeyChord KeyMods : 16; // Latched key-mods for box-select logic. ImVec2 StartPosRel; // Start position in window-contents relative space (to support scrolling) ImVec2 EndPosRel; // End position in window-contents relative space + ImVec2 ScrollAccum; // Scrolling accumulator (to behave at high-frame spaces) ImGuiWindow* Window; // Temporary/Transient data diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7f3e529ca..14d4cac64 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7127,11 +7127,14 @@ static void BoxSelectStart(ImGuiID id, ImGuiSelectionUserData clicked_item) bs->IsStartedFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid); bs->KeyMods = g.IO.KeyMods; bs->StartPosRel = bs->EndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); + bs->ScrollAccum = ImVec2(0.0f, 0.0f); } static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& inner_r) { ImGuiContext& g = *GImGui; + ImGuiBoxSelectState* bs = &g.BoxSelectState; + IM_ASSERT(bs->Window == window); for (int n = 0; n < 2; n++) // each axis { const float mouse_pos = g.IO.MousePos[n]; @@ -7139,12 +7142,20 @@ static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& inne const float scroll_curr = window->Scroll[n]; if (dist == 0.0f || (dist < 0.0f && scroll_curr < 0.0f) || (dist > 0.0f && scroll_curr >= window->ScrollMax[n])) continue; + const float speed_multiplier = ImLinearRemapClamp(g.FontSize, g.FontSize * 5.0f, 1.0f, 4.0f, ImAbs(dist)); // x1 to x4 depending on distance - const float scroll_step = IM_ROUND(g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime); + const float scroll_step = g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime; + bs->ScrollAccum[n] += scroll_step; + + // Accumulate into a stored value so we can handle high-framerate + const float scroll_step_i = ImFloor(bs->ScrollAccum[n]); + if (scroll_step_i == 0.0f) + continue; if (n == 0) - ImGui::SetScrollX(window, scroll_curr + scroll_step); + ImGui::SetScrollX(window, scroll_curr + scroll_step_i); else - ImGui::SetScrollY(window, scroll_curr + scroll_step); + ImGui::SetScrollY(window, scroll_curr + scroll_step_i); + bs->ScrollAccum[n] -= scroll_step_i; } } From f3d77d8e71bdb72c9daa62942bab4ebb751222ec Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Dec 2023 22:34:50 +0100 Subject: [PATCH 0184/2359] MultiSelect: Box-Select: Further refactor to extra mode code away from multi-select function into box-select funcitons. --- imgui.cpp | 4 +- imgui_internal.h | 7 +- imgui_widgets.cpp | 178 ++++++++++++++++++++++++++-------------------- 3 files changed, 109 insertions(+), 80 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ffbebea7c..291863e6f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14997,8 +14997,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Details for MultiSelect if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount())) { - ImGuiBoxSelectState* ms = &g.BoxSelectState; - Text("BoxSelect ID=0x%08X, Starting = %d, Active %d", ms->ID, ms->IsStarting, ms->IsActive); + ImGuiBoxSelectState* bs = &g.BoxSelectState; + BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive); for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++) if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n)) DebugNodeMultiSelectState(state); diff --git a/imgui_internal.h b/imgui_internal.h index 7c0c6aa22..3659bf8cc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1718,6 +1718,7 @@ struct ImGuiBoxSelectState bool IsActive; bool IsStarting; bool IsStartedFromVoid; // Starting click was not from an item. + bool RequestClear; ImGuiKeyChord KeyMods : 16; // Latched key-mods for box-select logic. ImVec2 StartPosRel; // Start position in window-contents relative space (to support scrolling) ImVec2 EndPosRel; // End position in window-contents relative space @@ -1729,7 +1730,6 @@ struct ImGuiBoxSelectState ImRect UnclipRect; // Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. ImRect BoxSelectRectPrev; // Selection rectangle in absolute coordinates (derived every frame from BoxSelectStartPosRel and MousePos) ImRect BoxSelectRectCurr; - ImGuiSelectionUserData LastSubmittedItem; // Copy of last submitted item data, used to merge output ranges. ImGuiBoxSelectState() { memset(this, 0, sizeof(*this)); } }; @@ -1762,6 +1762,7 @@ struct IMGUI_API ImGuiMultiSelectTempData bool NavIdPassedBy; bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. + ImGuiSelectionUserData BoxSelectLastitem; // Copy of last submitted item data, used to merge output ranges. ImGuiMultiSelectTempData() { Clear(); } void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. @@ -3403,6 +3404,10 @@ namespace ImGui IMGUI_API int TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); IMGUI_API int TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data); + // Box-Select API + IMGUI_API bool BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags); + IMGUI_API void EndBoxSelect(const ImRect& scope_rect, bool enable_scroll); + // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 14d4cac64..f9dfa143e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7113,12 +7113,15 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) //------------------------------------------------------------------------- // [SECTION] Widgets: Box-Select support +// This has been extracted away from Multi-Select logic in the hope that it could eventually be used elsewhere, but hasn't been yet. //------------------------------------------------------------------------- -// - BoxSelectStart() [Internal] +// - BoxSelectStartDrag() [Internal] // - BoxSelectScrollWithMouseDrag() [Internal] +// - BeginBoxSelect() [Internal] +// - EndBoxSelect() [Internal] //------------------------------------------------------------------------- -static void BoxSelectStart(ImGuiID id, ImGuiSelectionUserData clicked_item) +static void BoxSelectStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_item) { ImGuiContext& g = *GImGui; ImGuiBoxSelectState* bs = &g.BoxSelectState; @@ -7159,6 +7162,91 @@ static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& inne } } +bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiBoxSelectState* bs = &g.BoxSelectState; + KeepAliveID(box_select_id); + if (bs->ID != box_select_id) + return false; + + bs->UnclipMode = false; + bs->RequestClear = false; + + // IsStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. + if (bs->IsStarting && IsMouseDragPastThreshold(0)) + { + bs->IsActive = true; + bs->Window = window; + bs->IsStarting = false; + SetActiveID(bs->ID, window); + if (bs->IsStartedFromVoid && (bs->KeyMods & ImGuiMod_Shift) == 0) + bs->RequestClear = true; + } + else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false) + { + bs->IsActive = bs->IsStarting = false; + if (g.ActiveId == bs->ID) + ClearActiveID(); + bs->ID = 0; + } + if (!bs->IsActive) + return false; + + // Current frame absolute prev/current rectangles are used to toggle selection. + // They are derived from positions relative to scrolling space. + const ImRect scope_rect = window->InnerClipRect; + ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->StartPosRel); + ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->EndPosRel); // Clamped already + ImVec2 curr_end_pos_abs = g.IO.MousePos; + if (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow + curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max); + bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); + bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); + bs->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs); + bs->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs); + + // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper) + // Storing an extra rect used by widgets supporting box-select. + if (ms_flags & ImGuiMultiSelectFlags_BoxSelect2d) + if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x) + { + bs->UnclipRect = bs->BoxSelectRectPrev; + bs->UnclipRect.Add(bs->BoxSelectRectCurr); + bs->UnclipMode = true; + } + + //GetForegroundDrawList()->AddRect(bs->UnclipRect.Min, bs->UnclipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); + //GetForegroundDrawList()->AddRect(bs->BoxSelectRectPrev.Min, bs->BoxSelectRectPrev.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); + //GetForegroundDrawList()->AddRect(bs->BoxSelectRectCurr.Min, bs->BoxSelectRectCurr.Max, IM_COL32(0,255,0,200), 0.0f, 0, 1.0f); + return true; +} + +void ImGui::EndBoxSelect(const ImRect& scope_rect, bool enable_scroll) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiBoxSelectState* bs = &g.BoxSelectState; + IM_ASSERT(bs->IsActive); + bs->UnclipMode = false; + + // Render selection rectangle + bs->EndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view + ImRect box_select_r = bs->BoxSelectRectCurr; + box_select_r.ClipWith(scope_rect); + window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling + window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavHighlight)); // FIXME-MULTISELECT: Styling + + // Scroll + if (enable_scroll) + { + ImRect scroll_r = scope_rect; + scroll_r.Expand(-g.FontSize); + //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255)); + if (!scroll_r.Contains(g.IO.MousePos)) + BoxSelectScrollWithMouseDrag(window, scroll_r); + } +} //------------------------------------------------------------------------- // [SECTION] Widgets: Multi-Select support @@ -7268,59 +7356,9 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (flags & ImGuiMultiSelectFlags_BoxSelect) { ms->BoxSelectId = GetID("##BoxSelect"); - KeepAliveID(ms->BoxSelectId); - } - if ((flags & ImGuiMultiSelectFlags_BoxSelect) && ms->BoxSelectId == bs->ID) - { - bs->UnclipMode = false; - - // BoxSelectStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. - if (bs->IsStarting && IsMouseDragPastThreshold(0)) - { - bs->IsActive = true; - bs->Window = ms->Storage->Window; - bs->IsStarting = false; - SetActiveID(ms->BoxSelectId, window); - if (bs->IsStartedFromVoid && (bs->KeyMods & ImGuiMod_Shift) == 0) - request_clear = true; - } - else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false) - { - bs->ID = 0; - bs->IsActive = bs->IsStarting = false; - if (g.ActiveId == ms->BoxSelectId) - ClearActiveID(); - } - if (bs->IsActive) - { - // Current frame absolute prev/current rectangles are used to toggle selection. - // They are derived from positions relative to scrolling space. - const ImRect scope_rect = window->InnerClipRect; - ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->StartPosRel); - ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->EndPosRel); // Clamped already - ImVec2 curr_end_pos_abs = g.IO.MousePos; - if (ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow - curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max); - bs->LastSubmittedItem = ImGuiSelectionUserData_Invalid; - bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); - bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); - bs->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs); - bs->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs); - - // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper) - // Storing an extra rect used by widgets supporting box-select. - if (flags & ImGuiMultiSelectFlags_BoxSelect2d) - if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x) - { - bs->UnclipRect = bs->BoxSelectRectPrev; - bs->UnclipRect.Add(bs->BoxSelectRectCurr); - bs->UnclipMode = true; - } - - //GetForegroundDrawList()->AddRect(ms->BoxSelectNoClipRect.Min, ms->BoxSelectNoClipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); - //GetForegroundDrawList()->AddRect(ms->BoxSelectRectPrev.Min, ms->BoxSelectRectPrev.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); - //GetForegroundDrawList()->AddRect(ms->BoxSelectRectCurr.Min, ms->BoxSelectRectCurr.Max, IM_COL32(0,255,0,200), 0.0f, 0, 1.0f); - } + ms->BoxSelectLastitem = ImGuiSelectionUserData_Invalid; + if (BeginBoxSelect(window, ms->BoxSelectId, flags)) + request_clear |= bs->RequestClear; } if (request_clear || request_select_all) @@ -7364,24 +7402,10 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() storage->NavIdSelected = -1; } - ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId); - if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && bs != NULL) + if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && GetBoxSelectState(ms->BoxSelectId)) { - // Box-select: render selection rectangle - bs->EndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view - ImRect box_select_r = bs->BoxSelectRectCurr; - box_select_r.ClipWith(scope_rect); - window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling - window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavHighlight)); // FIXME-MULTISELECT: Styling - - // Box-select: scroll - ImRect scroll_r = scope_rect; - scroll_r.Expand(-g.FontSize); - //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255)); - if ((ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0 && !scroll_r.Contains(g.IO.MousePos)) - BoxSelectScrollWithMouseDrag(window, scroll_r); - - bs->UnclipMode = false; + bool enable_scroll = (ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0; + EndBoxSelect(scope_rect, enable_scroll); } } @@ -7395,7 +7419,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() { if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1) - BoxSelectStart(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); + BoxSelectStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) @@ -7544,7 +7568,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = pressed = true; } - // Box-select handling + // Box-select toggle handling if (ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId)) { const bool rect_overlap_curr = bs->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect); @@ -7554,12 +7578,12 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = !selected; ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == bs->LastSubmittedItem && prev_req->RangeSelected == selected) + if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->RangeSelected == selected) prev_req->RangeLastItem = item_data; // Merge span into same request else ms->IO.Requests.push_back(req); } - bs->LastSubmittedItem = item_data; + ms->BoxSelectLastitem = item_data; } // Right-click handling: this could be moved at the Selectable() level. @@ -7588,7 +7612,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) - BoxSelectStart(ms->BoxSelectId, item_data); + BoxSelectStartDrag(ms->BoxSelectId, item_data); //---------------------------------------------------------------------------------------- // ACTION | Begin | Pressed/Activated | End From 6c4bf8e56eca5900b925aed1c57ca4179c450482 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 21 Dec 2023 14:29:01 +0100 Subject: [PATCH 0185/2359] MultiSelect: Fixed ImGuiSelectionBasicStorage::ApplyRequests() incorrectly maintaining selection size on SelectAll. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f9dfa143e..05ced948e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7730,7 +7730,7 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io, int it Clear(); if (req.Type == ImGuiSelectionRequestType_SelectAll) { - Storage.Data.resize(0); + Clear(); Storage.Data.reserve(items_count); for (int idx = 0; idx < items_count; idx++) AddItem(AdapterIndexToStorageId(this, idx)); From d439f590ab54e1a60ea62e0dfb55f5e70ea6f2e5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 21 Dec 2023 15:12:17 +0100 Subject: [PATCH 0186/2359] MultiSelect: Comments + Assets Browser : Tweak colors. --- imgui.h | 132 ++++++++++++++++++++-------------------------- imgui_demo.cpp | 67 ++++++++++++----------- imgui_widgets.cpp | 6 ++- 3 files changed, 97 insertions(+), 108 deletions(-) diff --git a/imgui.h b/imgui.h index c4b8afa69..be79eb665 100644 --- a/imgui.h +++ b/imgui.h @@ -180,6 +180,7 @@ struct ImGuiOnceUponAFrame; // Helper for running a block of code not mo struct ImGuiPayload; // User data payload for drag and drop operations struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. struct ImGuiSelectionBasicStorage; // Helper struct to store multi-selection state + apply multi-selection requests. +struct ImGuiSelectionRequest; // A selection request (stored in ImGuiMultiSelectIO) struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) struct ImGuiStorage; // Helper for key->value storage (container sorted by key) struct ImGuiStoragePair; // Helper for key->value storage (pair) @@ -268,7 +269,7 @@ typedef ImWchar16 ImWchar; // Multi-Selection item index or identifier when using BeginMultiSelect() // - Used by SetNextItemSelectionUserData() + and inside ImGuiMultiSelectIO structure. -// - Most users are likely to use this store an item INDEX but this may be used to store a POINTER as well. Read comments near ImGuiMultiSelectIO for details. +// - Most users are likely to use this store an item INDEX but this may be used to store a POINTER/ID as well. Read comments near ImGuiMultiSelectIO for details. typedef ImS64 ImGuiSelectionUserData; // Callback and functions types @@ -2727,48 +2728,45 @@ struct ImColor #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. // Multi-selection system -// - Refer to 'Demo->Widgets->Selection State & Multi-Select' for references using this. +// Also read: https://github.com/ocornut/imgui/wiki/Multi-Select +// - Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos using this. // - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) -// and supports a clipper being used. Handling this manually and correctly is tricky, this is why we provide -// the functionality. If you don't need SHIFT+Mouse/Keyboard range-select + clipping, you can implement a -// simple form of multi-selection yourself, by reacting to click/presses on Selectable() items. +// with support for clipper (skipping non-visible items), box-select and many other details. // - TreeNode() and Selectable() are supported but custom widgets may use it as well. // - In the spirit of Dear ImGui design, your code owns actual selection data. -// This is designed to allow all kinds of selection storage you may use in your application: -// e.g. set/map/hash (store selected items), instructive selection (store a bool inside each object), etc. +// This is designed to allow all kinds of selection storage you may use in your application e.g. set/map/hash. // - The work involved to deal with multi-selection differs whether you want to only submit visible items and // clip others, or submit all items regardless of their visibility. Clipping items is more efficient and will // allow you to deal with large lists (1k~100k items). See "Usage flow" section below for details. // If you are not sure, always start without clipping! You can work your way to the optimized version afterwards. +// TL;DR; +// - Identify submitted items with SetNextItemSelectionUserData(), most likely using an index into your current data-set. +// - Store and maintain actual selection data using persistent object identifiers. +// - Usage flow: +// BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. +// - (2) [If using clipper] Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 6. +// - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeItemByIndex(). If storing indices in ImGuiSelectionUserData, a simple clipper.IncludeItemByIndex(ms_io->RangeSrcItem) call will work. +// LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. +// END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. +// - (6) Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 2. +// If you submit all items (no clipper), Step 2 and 3 are optional and will be handled by each item themselves. It is fine to always honor those steps. // About ImGuiSelectionUserData: -// - This can store an application-defined identifier (e.g. index or pointer). // - For each item is it submitted by your call to SetNextItemSelectionUserData(). +// - This can store an application-defined identifier (e.g. index or pointer). // - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. // - Most applications will store an object INDEX, hence the chosen name and type. -// Storing an integer index is the easiest thing to do, as RequestSetRange requests will give you two end-points -// and you will need to iterate/interpolate between them to honor range selection. -// - However it is perfectly possible to store a POINTER inside this value! The multi-selection system never assume -// that you identify items by indices. It never attempt to iterate/interpolate between 2 ImGuiSelectionUserData values. -// - As most users will want to cast this to integer, for convenience and to reduce confusion we use ImS64 instead -// of void*, being syntactically easier to downcast. But feel free to reinterpret_cast a pointer into this. -// - You may store another type as long as you can interpolate between two values. +// Storing an integer index is the easiest thing to do, as SetRange requests will give you two end-points +// and you will need to iterate/interpolate between them to update your selection. +// - However it is perfectly possible to store a POINTER or another IDENTIFIER inside this value! +// Our system never assume that you identify items by indices, it never attempts to interpolate between two values. +// - As most users will want to store an index, for convenience and to reduce confusion we use ImS64 instead of void*, +// being syntactically easier to downcast. Feel free to reinterpret_cast and store a pointer inside. // - If you need to wrap this API for another language/framework, feel free to expose this as 'int' if simpler. -// Usage flow: -// BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (2) [If using clipper] Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 6. -// - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeItemByIndex(). If storing indices in ImGuiSelectionUserData, a simple clipper.IncludeItemByIndex(ms_io->RangeSrcItem) call will work. -// LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. -// END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (6) Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 2. -// If you submit all items (no clipper), Step 2 and 3 are optional and will be handled by each item themselves. It is perfectly fine if you honor those steps without a clipper. // About ImGuiSelectionBasicStorage: // - This is an optional helper to store a selection state and apply selection requests. // - It is used by our demos and provided as a convenience if you want to quickly implement multi-selection. -// Advanced: -// - Deletion: If you need to handle items deletion: more work if needed for post-deletion focus and scrolling to be correct. -// Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos supporting deletion. -// Flags for BeginMultiSelect(). +// Flags for BeginMultiSelect() enum ImGuiMultiSelectFlags_ { ImGuiMultiSelectFlags_None = 0, @@ -2785,29 +2783,11 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 10, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. }; -enum ImGuiSelectionRequestType -{ - ImGuiSelectionRequestType_None = 0, - ImGuiSelectionRequestType_Clear, // Request app to clear selection. - ImGuiSelectionRequestType_SelectAll, // Request app to select all. - ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items based on 'bool RangeSelected'. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. -}; - -struct ImGuiSelectionRequest -{ - //------------------------------------------// BeginMultiSelect / EndMultiSelect - ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. - bool RangeSelected; // / ms:w, app:r // Parameter for SetRange request (true = select range, false = unselect range) - ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) - ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) -}; - // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). -// This mainly contains a list of selection requests. Read the large comments block above for details. +// This mainly contains a list of selection requests. // - Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. -// - Some fields are only useful if your list is dynamic and allows deletion (handling deletion and getting "post-deletion" state right is shown in the demo) -// - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code, 'BEGIN'=BeginMultiSelect() and after, 'END'=EndMultiSelect() and after. -// - Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). +// - Some fields are only useful if your list is dynamic and allows deletion (getting post-deletion focus/state right is shown in the demo) +// - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code. struct ImGuiMultiSelectIO { //------------------------------------------// BeginMultiSelect / EndMultiSelect @@ -2818,49 +2798,49 @@ struct ImGuiMultiSelectIO bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). }; -// Optional helper struct to store multi-selection state + apply multi-selection requests. +// Selection request type +enum ImGuiSelectionRequestType +{ + ImGuiSelectionRequestType_None = 0, + ImGuiSelectionRequestType_Clear, // Request app to clear selection. + ImGuiSelectionRequestType_SelectAll, // Request app to select all. + ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items based on 'bool RangeSelected'. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. +}; + +// Selection request item +struct ImGuiSelectionRequest +{ + //------------------------------------------// BeginMultiSelect / EndMultiSelect + ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. + bool RangeSelected; // / ms:w, app:r // Parameter for SetRange request (true = select range, false = unselect range) + ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) + ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) +}; + +// Optional helper to store multi-selection state + apply multi-selection requests. // - Used by our demos and provided as a convenience to easily implement basic multi-selection. // - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. Advanced users are likely to implement their own. -// To store a multi-selection, in your real application you could: +// To store a multi-selection, in your application you could: // - A) Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. // - B) Use your own external storage: e.g. std::set, std::vector, interval trees, etc. // - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside objects). Not recommended because you can't have multiple views // over same objects. Also some features requires to provide selection _size_, which with this strategy requires additional work. -// Our BeginMultiSelect() api/system doesn't make assumption about: -// - how you want to identify items in multi-selection API? Indices(*) or Custom Ids or Pointers -> Indices is better (easy to iterate/interpolate) -// - how you want to store persistent selection data? Indices or Custom Ids(*) or Pointers -> Custom ids is better (as selection can persist) // In ImGuiSelectionBasicStorage we: // - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) // - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index. -// - in some cases we use Index as custom identifier (default implementation returns Index casted as Identifier): only valid for a never changing item list. -// - in some cases we read an ID from some custom item data structure (better, and closer to what you would do in your codebase) +// - so this helper can be used regardless of your object storage/types, and without using templates or virtual functions. +// - in some cases we read an ID from some custom item data structure (similar to what you would do in your codebase) +// - in some cases we use Index as custom identifier (default implementation returns Index cast as Identifier): only OK for a never changing item list. // Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. // When your application settles on a choice, you may want to get rid of this indirection layer and do your own thing. -// Minimum pseudo-code example using this helper: -// { -// static vector items; // Your items -// static ImGuiSelectionBasicStorage selection; // Your selection -// selection.AdapterData = (void*)&items; // Setup adapter so selection.ApplyRequests() function can convert indexes to identifiers. -// selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((vector*)self->AdapterData))[idx].ID; }; -// -// ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ImGuiMultiSelectFlags_None); -// selection.ApplyRequests(ms_io, items.Size); -// for (int idx = 0; idx < items.Size; idx++) -// { -// bool item_is_selected = selection.Contains(items[idx].ID); -// ImGui::SetNextItemSelectionUserData(idx); -// ImGui::Selectable(label, item_is_selected); -// } -// ms_io = ImGui::EndMultiSelect(); -// selection.ApplyRequests(ms_io, items.Size); -// } -// In theory, for maximum abstraction, this class could contains AdapterIndexToUserData() and AdapterUserDataToIndex() functions as well, -// but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that indirection for clarity. +// See https://github.com/ocornut/imgui/wiki/Multi-Select for minimum pseudo-code example using this helper. +// (In theory, for maximum abstraction, this class could contains AdapterIndexToUserData() and AdapterUserDataToIndex() functions as well, +// but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that indirection for clarity.) struct ImGuiSelectionBasicStorage { // Members ImGuiStorage Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set - int Size; // Number of selected items (== number of 1 in the Storage, maintained by this class). + int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. void* AdapterData; // Adapter to convert item index to item identifier // e.g. selection.AdapterData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->AdapterData)[idx]->ID; }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b84a0ca9f..0df16adb8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2977,14 +2977,16 @@ struct ExampleDualListBox } }; - +// Multi-selection demos +// Also read: https://github.com/ocornut/imgui/wiki/Multi-Select static void ShowDemoWindowMultiSelect() { IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); if (ImGui::TreeNode("Selection State & Multi-Select")) { - HelpMarker("Selections can be built under Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data."); + HelpMarker("Selections can be built using Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data."); + // Without any fancy API: manage single-selection yourself. IMGUI_DEMO_MARKER("Widgets/Selection State/Single-Select"); if (ImGui::TreeNode("Single-Select")) { @@ -3020,8 +3022,9 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } - // Demonstrate holding/updating multi-selection data using the BeginMultiSelect/EndMultiSelect API. + // Demonstrate handling proper multi-selection using the BeginMultiSelect/EndMultiSelect API. // SHIFT+Click w/ CTRL and other standard features are supported. + // We use the ImGuiSelectionBasicStorage helper which you may freely reimplement. IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); if (ImGui::TreeNode("Multi-Select")) { @@ -3105,8 +3108,7 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } - // Demonstrate holding/updating multi-selection data and using the BeginMultiSelect/EndMultiSelect API + support dynamic item list and deletion. - // SHIFT+Click w/ CTRL and other standard features are supported. + // Demonstrate dynamic item list + deletion support using the BeginMultiSelect/EndMultiSelect API. // In order to support Deletion without any glitches you need to: // - (1) If items are submitted in their own scrolling area, submit contents size SetNextWindowContentSize() ahead of time to prevent one-frame readjustment of scrolling. // - (2) Items needs to have persistent ID Stack identifier = ID needs to not depends on their index. PushID(index) = KO. PushID(item_id) = OK. This is in order to focus items reliably after a selection. @@ -3263,29 +3265,33 @@ static void ShowDemoWindowMultiSelect() static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; static WidgetType widget_type = WidgetType_Selectable; - if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } - ImGui::SameLine(); - if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } - ImGui::Checkbox("Enable clipper", &use_clipper); - ImGui::Checkbox("Enable deletion", &use_deletion); - ImGui::Checkbox("Enable drag & drop", &use_drag_drop); - ImGui::Checkbox("Show in a table", &show_in_table); - ImGui::Checkbox("Show color button", &show_color_button); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); - if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) - flags &= ~ImGuiMultiSelectFlags_ScopeRect; - if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect)) - flags &= ~ImGuiMultiSelectFlags_ScopeWindow; - if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClick", &flags, ImGuiMultiSelectFlags_SelectOnClick) && (flags & ImGuiMultiSelectFlags_SelectOnClick)) - flags &= ~ImGuiMultiSelectFlags_SelectOnClickRelease; - if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClickRelease", &flags, ImGuiMultiSelectFlags_SelectOnClickRelease) && (flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) - flags &= ~ImGuiMultiSelectFlags_SelectOnClick; - ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); + if (ImGui::TreeNode("Options")) + { + if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } + ImGui::SameLine(); + if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } + ImGui::Checkbox("Enable clipper", &use_clipper); + ImGui::Checkbox("Enable deletion", &use_deletion); + ImGui::Checkbox("Enable drag & drop", &use_drag_drop); + ImGui::Checkbox("Show in a table", &show_in_table); + ImGui::Checkbox("Show color button", &show_color_button); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow)) + flags &= ~ImGuiMultiSelectFlags_ScopeRect; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect)) + flags &= ~ImGuiMultiSelectFlags_ScopeWindow; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClick", &flags, ImGuiMultiSelectFlags_SelectOnClick) && (flags & ImGuiMultiSelectFlags_SelectOnClick)) + flags &= ~ImGuiMultiSelectFlags_SelectOnClickRelease; + if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClickRelease", &flags, ImGuiMultiSelectFlags_SelectOnClickRelease) && (flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) + flags &= ~ImGuiMultiSelectFlags_SelectOnClick; + ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection."); + ImGui::TreePop(); + } // Initialize default list with 1000 items. // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection @@ -9797,6 +9803,7 @@ struct ExampleAssetsBrowser // Rendering parameters const ImU32 icon_type_overlay_colors[3] = { 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255) }; + const ImU32 icon_bg_color = ImGui::GetColorU32(ImGuiCol_MenuBarBg); const ImVec2 icon_type_overlay_size = ImVec2(4.0f, 4.0f); const bool display_label = (LayoutItemSize.x >= ImGui::CalcTextSize("999").x); @@ -9856,7 +9863,7 @@ struct ExampleAssetsBrowser { ImVec2 box_min(pos.x - 1, pos.y - 1); ImVec2 box_max(box_min.x + LayoutItemSize.x + 2, box_min.y + LayoutItemSize.y + 2); // Dubious - draw_list->AddRectFilled(box_min, box_max, IM_COL32(48, 48, 48, 200)); // Background color + draw_list->AddRectFilled(box_min, box_max, icon_bg_color); // Background color if (ShowTypeOverlay && item_data->Type != 0) { ImU32 type_col = icon_type_overlay_colors[item_data->Type % IM_ARRAYSIZE(icon_type_overlay_colors)]; @@ -9864,7 +9871,7 @@ struct ExampleAssetsBrowser } if (display_label) { - ImU32 label_col = item_is_selected ? IM_COL32(255, 255, 255, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled); + ImU32 label_col = ImGui::GetColorU32(item_is_selected ? ImGuiCol_Text : ImGuiCol_TextDisabled); char label[32]; sprintf(label, "%d", item_data->ID); draw_list->AddText(ImVec2(box_min.x, box_max.y - ImGui::GetFontSize()), label_col, label); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 05ced948e..98569ead2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7272,7 +7272,8 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe } } -// Return ImGuiMultiSelectIO structure. Lifetime: valid until corresponding call to EndMultiSelect(). +// Return ImGuiMultiSelectIO structure. +// Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) { ImGuiContext& g = *GImGui; @@ -7375,7 +7376,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) return &ms->IO; } -// Return updated ImGuiMultiSelectIO structure. Lifetime: until EndFrame() or next BeginMultiSelect() call. +// Return updated ImGuiMultiSelectIO structure. +// Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). ImGuiMultiSelectIO* ImGui::EndMultiSelect() { ImGuiContext& g = *GImGui; From 8312c75fef0a174fa277b5538f39e4f4ef317f5f Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Jan 2024 18:41:20 +0100 Subject: [PATCH 0187/2359] MultiSelect: Added ImGuiMultiSelectFlags_NoRangeSelect. Fixed ImGuiMultiSelectFlags_ScopeRect not querying proper window hover. --- imgui.h | 19 ++++++++++--------- imgui_demo.cpp | 1 + imgui_widgets.cpp | 6 +++++- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/imgui.h b/imgui.h index be79eb665..54c4b0264 100644 --- a/imgui.h +++ b/imgui.h @@ -2772,15 +2772,16 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut sending a SelectAll request. - ImGuiMultiSelectFlags_BoxSelect = 1 << 2, // Enable box-selection (only supporting 1D list when using clipper, not 2D grids). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_BoxSelect2d = 1 << 3, // Enable box-selection with 2D layout/grid support. This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. - ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 4, // Disable scrolling when box-selecting near edges of scope. - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 5, // Clear selection when pressing Escape while scope is focused. - ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 6, // Clear selection when clicking on empty location within scope. - ImGuiMultiSelectFlags_ScopeWindow = 1 << 7, // Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). Use if BeginMultiSelect() covers a whole window. - ImGuiMultiSelectFlags_ScopeRect = 1 << 8, // Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. Use if multiple BeginMultiSelect() are used in the same host window. - ImGuiMultiSelectFlags_SelectOnClick = 1 << 9, // Apply selection on mouse down when clicking on unselected item. (Default) - ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 10, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. + ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+Click/Shift+Keyboard handling (useful for unordered 2D selection). + ImGuiMultiSelectFlags_BoxSelect = 1 << 3, // Enable box-selection (only supporting 1D list when using clipper, not 2D grids). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 4, // Enable box-selection with 2D layout/grid support. This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. + ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 5, // Disable scrolling when box-selecting near edges of scope. + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 6, // Clear selection when pressing Escape while scope is focused. + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 7, // Clear selection when clicking on empty location within scope. + ImGuiMultiSelectFlags_ScopeWindow = 1 << 8, // Use if BeginMultiSelect() covers a whole window (Default): Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). + ImGuiMultiSelectFlags_ScopeRect = 1 << 9, // Use if multiple BeginMultiSelect() are used in the same host window: Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. + ImGuiMultiSelectFlags_SelectOnClick = 1 << 10, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 11, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. }; // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0df16adb8..9f8a80f8d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3277,6 +3277,7 @@ static void ShowDemoWindowMultiSelect() ImGui::Checkbox("Show color button", &show_color_button); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoRangeSelect", &flags, ImGuiMultiSelectFlags_NoRangeSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 98569ead2..4ca36d17e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7303,6 +7303,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. ms->KeyMods = g.NavJustMovedToId ? g.NavJustMovedToKeyMods : g.IO.KeyMods; + if (flags & ImGuiMultiSelectFlags_NoRangeSelect) + ms->KeyMods &= ~ImGuiMod_Shift; // Bind storage ImGuiMultiSelectState* storage = g.MultiSelectStorage.GetOrAddByKey(id); @@ -7416,7 +7418,9 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() // Clear selection when clicking void? // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! - const bool scope_hovered = (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) ? scope_rect.Contains(g.IO.MousePos) : IsWindowHovered(); + bool scope_hovered = IsWindowHovered(); + if (scope_hovered && (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)) + scope_hovered &= scope_rect.Contains(g.IO.MousePos); if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0) { if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) From 3141d87ef810a7478c078f956ff3865152af0a78 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Jan 2024 19:13:42 +0100 Subject: [PATCH 0188/2359] MultiSelect: Box-Select: Fixed CTRL+drag from void clearing items. --- imgui_demo.cpp | 1 + imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9f8a80f8d..32e6e8f2f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -9737,6 +9737,7 @@ struct ExampleAssetsBrowser ImGui::SeparatorText("Layout"); ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f"); + ImGui::SameLine(); HelpMarker("Use CTRL+Wheel to zoom"); ImGui::SliderInt("Icon Spacing", &IconSpacing, 0, 32); ImGui::SliderInt("Icon Hit Spacing", &IconHitSpacing, 0, 32); ImGui::Checkbox("Stretch Spacing", &StretchSpacing); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4ca36d17e..f7be14160 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7180,7 +7180,7 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult bs->Window = window; bs->IsStarting = false; SetActiveID(bs->ID, window); - if (bs->IsStartedFromVoid && (bs->KeyMods & ImGuiMod_Shift) == 0) + if (bs->IsStartedFromVoid && (bs->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) bs->RequestClear = true; } else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false) From 9337151a0132c8be7020f36df86a4f6adc6d2c74 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Jan 2024 20:05:05 +0100 Subject: [PATCH 0189/2359] MultiSelect: Box-Select: Fixed initial drag from not claiming hovered id, preventing window behind to move for a frame. --- imgui_demo.cpp | 5 +++-- imgui_widgets.cpp | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 32e6e8f2f..79634d820 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3086,7 +3086,7 @@ static void ShowDemoWindowMultiSelect() ImGuiListClipper clipper; clipper.Begin(ITEMS_COUNT); - if (ms_io->RangeSrcItem > 0) + if (ms_io->RangeSrcItem != -1) clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. while (clipper.Step()) { @@ -3210,6 +3210,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect)) flags &= ~ImGuiMultiSelectFlags_ScopeWindow; ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++) { @@ -3336,7 +3337,7 @@ static void ShowDemoWindowMultiSelect() clipper.Begin(items.Size); if (item_curr_idx_to_focus != -1) clipper.IncludeItemByIndex(item_curr_idx_to_focus); // Ensure focused item is not clipped. - if (ms_io->RangeSrcItem > 0) + if (ms_io->RangeSrcItem != -1) clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f7be14160..646a72852 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7176,6 +7176,7 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult // IsStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. if (bs->IsStarting && IsMouseDragPastThreshold(0)) { + IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Started.\n", box_select_id); bs->IsActive = true; bs->Window = window; bs->IsStarting = false; @@ -7187,7 +7188,10 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult { bs->IsActive = bs->IsStarting = false; if (g.ActiveId == bs->ID) + { + IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Ended.\n", box_select_id); ClearActiveID(); + } bs->ID = 0; } if (!bs->IsActive) @@ -7424,8 +7428,13 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0) { if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) + { if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1) BoxSelectStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); + SetHoveredID(ms->BoxSelectId); + if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) + SetNavID(0, ImGuiNavLayer_Main, ms->FocusScopeId, ImRect(g.IO.MousePos, g.IO.MousePos)); // Automatically switch FocusScope for initial click from outside to box-select. + } if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) From b13a78e6b2d19773d5cf6f1006de7bc0f4bed42c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Jan 2024 12:05:03 +0100 Subject: [PATCH 0190/2359] MultiSelect: Fixed ImGuiMultiSelectFlags_SelectOnClickRelease over tree node arrow. --- imgui_widgets.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 646a72852..fecfbc4fb 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6471,6 +6471,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags { // Handle multi-select + alter button flags for it MultiSelectItemHeader(id, &selected, &button_flags); + if (is_mouse_x_over_arrow) + button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; // We absolutely need to distinguish open vs select so comes by default flags |= ImGuiTreeNodeFlags_OpenOnArrow; From f36a03c317a97da95fba9287afff64c8548f3620 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 6 Mar 2024 14:22:38 +0100 Subject: [PATCH 0191/2359] MultiSelect: (Breaking) merge ImGuiSelectionRequestType_Clear and ImGuiSelectionRequestType_SelectAll into ImGuiSelectionRequestType_SetAll., rename ImGuiSelectionRequest::RangeSelected to Selected. The reasoning is that it makes it easier/faster to write an adhoc ImGuiMultiSelectIO handler (e.g. trying to apply multi-select to checkboxes) --- imgui.h | 13 ++++++------- imgui_internal.h | 3 +-- imgui_widgets.cpp | 38 ++++++++++++++++---------------------- 3 files changed, 23 insertions(+), 31 deletions(-) diff --git a/imgui.h b/imgui.h index 54c4b0264..44990f68b 100644 --- a/imgui.h +++ b/imgui.h @@ -2744,11 +2744,11 @@ struct ImColor // - Store and maintain actual selection data using persistent object identifiers. // - Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (2) [If using clipper] Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 6. +// - (2) [If using clipper] Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 6. // - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeItemByIndex(). If storing indices in ImGuiSelectionUserData, a simple clipper.IncludeItemByIndex(ms_io->RangeSrcItem) call will work. // LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (6) Honor request list (Clear/SelectAll/SetRange requests) by updating your selection data. Same code as Step 2. +// - (6) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 2. // If you submit all items (no clipper), Step 2 and 3 are optional and will be handled by each item themselves. It is fine to always honor those steps. // About ImGuiSelectionUserData: // - For each item is it submitted by your call to SetNextItemSelectionUserData(). @@ -2771,7 +2771,7 @@ enum ImGuiMultiSelectFlags_ { ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! - ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut sending a SelectAll request. + ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to select all. ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+Click/Shift+Keyboard handling (useful for unordered 2D selection). ImGuiMultiSelectFlags_BoxSelect = 1 << 3, // Enable box-selection (only supporting 1D list when using clipper, not 2D grids). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. ImGuiMultiSelectFlags_BoxSelect2d = 1 << 4, // Enable box-selection with 2D layout/grid support. This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. @@ -2803,9 +2803,8 @@ struct ImGuiMultiSelectIO enum ImGuiSelectionRequestType { ImGuiSelectionRequestType_None = 0, - ImGuiSelectionRequestType_Clear, // Request app to clear selection. - ImGuiSelectionRequestType_SelectAll, // Request app to select all. - ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items based on 'bool RangeSelected'. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. + ImGuiSelectionRequestType_SetAll, // Request app to clear selection (if Selected==false) or select all items (if Selected==true) + ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items (inclusive) based on value of Selected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. }; // Selection request item @@ -2813,7 +2812,7 @@ struct ImGuiSelectionRequest { //------------------------------------------// BeginMultiSelect / EndMultiSelect ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. - bool RangeSelected; // / ms:w, app:r // Parameter for SetRange request (true = select range, false = unselect range) + bool Selected; // / ms:w, app:r // Parameter for SetAll/SetRange requests (true = select, false = unselect) ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) }; diff --git a/imgui_internal.h b/imgui_internal.h index 3659bf8cc..1e97b71f4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1754,8 +1754,7 @@ struct IMGUI_API ImGuiMultiSelectTempData ImVec2 BackupCursorMaxPos; ImGuiID BoxSelectId; ImGuiKeyChord KeyMods; - bool LoopRequestClear; - bool LoopRequestSelectAll; + ImS8 LoopRequestSetAll; // -1: no operation, 0: clear all, 1: select all. bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fecfbc4fb..e71f32ddd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7272,9 +7272,8 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe ImGuiContext& g = *GImGui; for (const ImGuiSelectionRequest& req : io->Requests) { - if (req.Type == ImGuiSelectionRequestType_Clear) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: Clear\n", function); - if (req.Type == ImGuiSelectionRequestType_SelectAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SelectAll\n", function); - if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.RangeSelected); + if (req.Type == ImGuiSelectionRequestType_SetAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetAll %d (= %s)\n", function, req.Selected, req.Selected ? "SelectAll" : "Clear"); + if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.Selected); } } @@ -7372,11 +7371,10 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (request_clear || request_select_all) { - ImGuiSelectionRequest req = { request_select_all ? ImGuiSelectionRequestType_SelectAll : ImGuiSelectionRequestType_Clear, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; ms->IO.Requests.push_back(req); } - ms->LoopRequestClear = request_clear; - ms->LoopRequestSelectAll = request_select_all; + ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1; if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) DebugLogMultiSelectRequests("BeginMultiSelect", &ms->IO); @@ -7441,7 +7439,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_Clear, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; ms->IO.Requests.resize(0); ms->IO.Requests.push_back(req); } @@ -7494,13 +7492,11 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); - // Apply Clear/SelectAll requests requested by BeginMultiSelect(). + // Apply SetAll (Clear/SelectAll )requests requested by BeginMultiSelect(). // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. - // If you are using a clipper (aka not submitting every element of the list) you need to process the Clear/SelectAll request after calling BeginMultiSelect() - if (ms->LoopRequestClear) - selected = false; - else if (ms->LoopRequestSelectAll) - selected = true; + // If you are using a clipper you need to process the SetAll request after calling BeginMultiSelect() + if (ms->LoopRequestSetAll != -1) + selected = (ms->LoopRequestSetAll == 1); // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function) @@ -7595,7 +7591,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = !selected; ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->RangeSelected == selected) + if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) prev_req->RangeLastItem = item_data; // Merge span into same request else ms->IO.Requests.push_back(req); @@ -7657,7 +7653,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. if (request_clear) { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_Clear, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; ms->IO.Requests.resize(0); ms->IO.Requests.push_back(req); } @@ -7734,27 +7730,25 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) // The most simple implementation (using indices everywhere) would look like: // for (ImGuiSelectionRequest& req : ms_io->Requests) // { -// if (req.Type == ImGuiSelectionRequestType_Clear) { Clear(); } -// if (req.Type == ImGuiSelectionRequestType_SelectAll) { Clear(); for (int n = 0; n < items_count; n++) { AddItem(n); } } -// if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->RangeSelected); } } +// if (req.Type == ImGuiSelectionRequestType_SetAll) { Clear(); if (req.Selected) { for (int n = 0; n < items_count; n++) { AddItem(n); } } +// if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->Selected); } } // } void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) { IM_ASSERT(AdapterIndexToStorageId != NULL); for (ImGuiSelectionRequest& req : ms_io->Requests) { - if (req.Type == ImGuiSelectionRequestType_Clear) + if (req.Type == ImGuiSelectionRequestType_SetAll) Clear(); - if (req.Type == ImGuiSelectionRequestType_SelectAll) + if (req.Type == ImGuiSelectionRequestType_SetAll && req.Selected) { - Clear(); Storage.Data.reserve(items_count); for (int idx = 0; idx < items_count; idx++) AddItem(AdapterIndexToStorageId(this, idx)); } if (req.Type == ImGuiSelectionRequestType_SetRange) for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) - UpdateItem(AdapterIndexToStorageId(this, idx), req.RangeSelected); + UpdateItem(AdapterIndexToStorageId(this, idx), req.Selected); } } From dbc67bbf23fcf57ad8271f9c2a4ea1cc4641410e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 6 Mar 2024 15:04:03 +0100 Subject: [PATCH 0192/2359] MultiSelect: Simplified ImGuiSelectionBasicStorage by using a single SetItemSelected() entry point. --- imgui.h | 22 ++++++++++------------ imgui_demo.cpp | 4 ++-- imgui_widgets.cpp | 4 ++-- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/imgui.h b/imgui.h index 44990f68b..a5a3d9265 100644 --- a/imgui.h +++ b/imgui.h @@ -2823,16 +2823,16 @@ struct ImGuiSelectionRequest // To store a multi-selection, in your application you could: // - A) Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. // - B) Use your own external storage: e.g. std::set, std::vector, interval trees, etc. -// - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside objects). Not recommended because you can't have multiple views -// over same objects. Also some features requires to provide selection _size_, which with this strategy requires additional work. +// - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside objects). Doing that, you can't have multiple views over +// your objects. Also, some features requires to provide selection _size_, which with this strategy requires additional work. // In ImGuiSelectionBasicStorage we: // - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) -// - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index. -// - so this helper can be used regardless of your object storage/types, and without using templates or virtual functions. +// - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index, +// so this helper can be used regardless of your object storage/types (it is analogous to using a virtual function): // - in some cases we read an ID from some custom item data structure (similar to what you would do in your codebase) // - in some cases we use Index as custom identifier (default implementation returns Index cast as Identifier): only OK for a never changing item list. // Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. -// When your application settles on a choice, you may want to get rid of this indirection layer and do your own thing. +// Large applications are likely to eventually want to get rid of this indirection layer and do their own thing. // See https://github.com/ocornut/imgui/wiki/Multi-Select for minimum pseudo-code example using this helper. // (In theory, for maximum abstraction, this class could contains AdapterIndexToUserData() and AdapterUserDataToIndex() functions as well, // but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that indirection for clarity.) @@ -2844,17 +2844,15 @@ struct ImGuiSelectionBasicStorage void* AdapterData; // Adapter to convert item index to item identifier // e.g. selection.AdapterData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->AdapterData)[idx]->ID; }; + // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count); + // Methods: selection storage ImGuiSelectionBasicStorage() { Clear(); AdapterData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } void Clear() { Storage.Data.resize(0); Size = 0; } void Swap(ImGuiSelectionBasicStorage& r) { Storage.Data.swap(r.Storage.Data); } - bool Contains(ImGuiID key) const { return Storage.GetInt(key, 0) != 0; } - void AddItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int != 0) return; *p_int = 1; Size++; } - void RemoveItem(ImGuiID key) { int* p_int = Storage.GetIntRef(key, 0); if (*p_int == 0) return; *p_int = 0; Size--; } - void UpdateItem(ImGuiID key, bool v) { if (v) { AddItem(key); } else { RemoveItem(key); } } - - // Methods: apply selection requests (that are coming from BeginMultiSelect() and EndMultiSelect() functions) - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count); + bool Contains(ImGuiID id) const { return Storage.GetInt(id, 0) != 0; } + void SetItemSelected(ImGuiID id, bool v) { int* p_int = Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 79634d820..7c03f5302 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2832,7 +2832,7 @@ struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage // Update selection Clear(); if (item_next_idx_to_select != -1 && ms_io->NavIdSelected) - AddItem(AdapterIndexToStorageId(this, item_next_idx_to_select)); + SetItemSelected(AdapterIndexToStorageId(this, item_next_idx_to_select), true); } }; @@ -3137,7 +3137,7 @@ static void ShowDemoWindowMultiSelect() items.push_back(items_next_id++); if (ImGui::SmallButton("Add 20 items")) { for (int n = 0; n < 20; n++) { items.push_back(items_next_id++); } } ImGui::SameLine(); - if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.RemoveItem(items.back()); items.pop_back(); } } + if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.SetItemSelected(items.back(), false); items.pop_back(); } } // (1) Extra to support deletion: Submit scrolling range to avoid glitches on deletion const float items_height = ImGui::GetTextLineHeightWithSpacing(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e71f32ddd..444fadc8b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7744,11 +7744,11 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io, int it { Storage.Data.reserve(items_count); for (int idx = 0; idx < items_count; idx++) - AddItem(AdapterIndexToStorageId(this, idx)); + SetItemSelected(AdapterIndexToStorageId(this, idx), true); } if (req.Type == ImGuiSelectionRequestType_SetRange) for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) - UpdateItem(AdapterIndexToStorageId(this, idx), req.Selected); + SetItemSelected(AdapterIndexToStorageId(this, idx), req.Selected); } } From 2111e3597bc6cc16bea20040dbfd05e38d3a4202 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 6 Mar 2024 15:33:50 +0100 Subject: [PATCH 0193/2359] MultiSelect: Comments + tweaked location for widgets to test ImGuiItemFlags_IsMultiSelect to avoid misleading into thinking doing it before ItemAdd() is necessary. --- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 47 ++++++++++++++++++++++++++++------------------- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 1e97b71f4..5fb2d568d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1757,7 +1757,7 @@ struct IMGUI_API ImGuiMultiSelectTempData ImS8 LoopRequestSetAll; // -1: no operation, 0: clear all, 1: select all. bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. - bool IsSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. + bool IsKeyboardSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. bool NavIdPassedBy; bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. @@ -1765,7 +1765,7 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiMultiSelectTempData() { Clear(); } void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. - void ClearIO() { IO.Requests.resize(0); IO.RangeSrcItem = IO.NavIdItem = (ImGuiSelectionUserData)-1; IO.NavIdSelected = IO.RangeSrcReset = false; } + void ClearIO() { IO.Requests.resize(0); IO.RangeSrcItem = IO.NavIdItem = ImGuiSelectionUserData_Invalid; IO.NavIdSelected = IO.RangeSrcReset = false; } }; // Persistent storage for multi-select (as long as selection is alive) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 444fadc8b..eef613071 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6392,7 +6392,6 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags } // Compute open and multi-select states before ItemAdd() as it clear NextItem data. - const bool is_multi_select = (g.NextItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0; // Before ItemAdd() bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); bool item_add = ItemAdd(interact_bb, id); g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; @@ -6467,6 +6466,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags const bool was_selected = selected; // Multi-selection support (header) + const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; if (is_multi_select) { // Handle multi-select + alter button flags for it @@ -6777,7 +6777,6 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl } const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; - const bool is_multi_select = (g.NextItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0; // Before ItemAdd() const bool is_visible = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); if (span_all_columns) @@ -6786,11 +6785,12 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl window->ClipRect.Max.x = backup_clip_rect_max_x; } + const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; if (!is_visible) { + // Extra layer of "no logic clip" for box-select support if (!is_multi_select) return false; - // Extra layer of "no logic clip" for box-select support if (!g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(bb)) return false; } @@ -7323,16 +7323,15 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) ms->IO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; ms->IO.Requests.resize(0); - bool request_clear = false; - bool request_select_all = false; - // Clear when using Navigation to move within the scope // (we compare FocusScopeId so it possible to use multiple selections inside a same window) + bool request_clear = false; + bool request_select_all = false; if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData) { if (ms->KeyMods & ImGuiMod_Shift) - ms->IsSetRange = true; - if (ms->IsSetRange) + ms->IsKeyboardSetRange = true; + if (ms->IsKeyboardSetRange) IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid); // Not ready -> could clear? if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) request_clear = true; @@ -7371,7 +7370,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (request_clear || request_select_all) { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; ms->IO.Requests.push_back(req); } ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1; @@ -7439,7 +7438,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; ms->IO.Requests.resize(0); ms->IO.Requests.push_back(req); } @@ -7480,6 +7479,10 @@ void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_d } } +// In charge of: +// - Applying SetAll for submitted items. +// - Applying SetRange for submitted items and record end points. +// - Altering button behavior flags to facilitate use with drag and drop. void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags) { ImGuiContext& g = *GImGui; @@ -7500,18 +7503,16 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function) - if (ms->IsSetRange) + if (ms->IsKeyboardSetRange) { IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0); const bool is_range_dst = (ms->RangeDstPassedBy == false) && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped. if (is_range_dst) - { ms->RangeDstPassedBy = true; - if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst - { - storage->RangeSrcItem = item_data; - storage->RangeSelected = selected ? 1 : 0; - } + if (is_range_dst && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst + { + storage->RangeSrcItem = item_data; + storage->RangeSelected = selected ? 1 : 0; } const bool is_range_src = storage->RangeSrcItem == item_data; if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy) @@ -7537,6 +7538,13 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags *p_button_flags = button_flags; } +// In charge of: +// - Auto-select on navigation. +// - Box-select toggle handling. +// - Right-click handling. +// - Altering selection based on Ctrl/Shift modifiers, both for keyboard and mouse. +// - Record current selection state for RangeSrc +// This is all rather complex, best to run and refer to "widgets_multiselect_xxx" tests in imgui_test_suite. void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { ImGuiContext& g = *GImGui; @@ -7557,7 +7565,8 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; - const bool is_singleselect = (ms->Flags & ImGuiMultiSelectFlags_SingleSelect) != 0; + ImGuiMultiSelectFlags flags = ms->Flags; + const bool is_singleselect = (flags & ImGuiMultiSelectFlags_SingleSelect) != 0; bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; @@ -7623,7 +7632,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { // Box-select ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; - if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) + if (flags & ImGuiMultiSelectFlags_BoxSelect) if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) BoxSelectStartDrag(ms->BoxSelectId, item_data); From a639346fbaf29a662a10c622956a6c66c06242ba Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 7 Mar 2024 15:52:30 +0100 Subject: [PATCH 0194/2359] MultiSelect: Demo: make various child windows resizable, with synched heights for the dual list box demo. --- imgui_demo.cpp | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7c03f5302..9d23d4661 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2898,6 +2898,7 @@ struct ExampleDualListBox int request_move_selected = -1; int request_move_all = -1; + float child_height_0 = 0.0f; for (int side = 0; side < 2; side++) { // FIXME-MULTISELECT: Dual List Box: Add context menus @@ -2912,7 +2913,20 @@ struct ExampleDualListBox const float items_height = ImGui::GetTextLineHeightWithSpacing(); ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); - if (ImGui::BeginChild(ImGui::GetID(side ? "1" : "0"), ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle)) + bool child_visible; + if (side == 0) + { + // Left child is resizable + ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetFrameHeightWithSpacing() * 4), ImVec2(FLT_MAX, FLT_MAX)); + child_visible = ImGui::BeginChild("0", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY); + child_height_0 = ImGui::GetWindowSize().y; + } + else + { + // Right child use same height as left one + child_visible = ImGui::BeginChild("1", ImVec2(-FLT_MIN, child_height_0), ImGuiChildFlags_FrameStyle); + } + if (child_visible) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); @@ -3042,8 +3056,8 @@ static void ShowDemoWindowMultiSelect() static ImGuiSelectionBasicStorage selection; ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); - // The BeginListBox() has no actual purpose for selection logic (other that offering a scrolling region). - if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + // The BeginChild() has no purpose for selection logic, other that offering a scrolling region. + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); @@ -3060,9 +3074,8 @@ static void ShowDemoWindowMultiSelect() ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, ITEMS_COUNT); - - ImGui::EndListBox(); } + ImGui::EndChild(); ImGui::TreePop(); } @@ -3078,7 +3091,7 @@ static void ShowDemoWindowMultiSelect() const int ITEMS_COUNT = 10000; ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); - if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); @@ -3102,9 +3115,8 @@ static void ShowDemoWindowMultiSelect() ms_io = ImGui::EndMultiSelect(); selection.ApplyRequests(ms_io, ITEMS_COUNT); - - ImGui::EndListBox(); } + ImGui::EndChild(); ImGui::TreePop(); } @@ -3143,7 +3155,7 @@ static void ShowDemoWindowMultiSelect() const float items_height = ImGui::GetTextLineHeightWithSpacing(); ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); - if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); @@ -3172,9 +3184,8 @@ static void ShowDemoWindowMultiSelect() selection.ApplyRequests(ms_io, items.Size); if (want_delete) selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus); - - ImGui::EndListBox(); } + ImGui::EndChild(); ImGui::TreePop(); } @@ -3307,7 +3318,7 @@ static void ShowDemoWindowMultiSelect() const float items_height = (widget_type == WidgetType_TreeNode) ? ImGui::GetTextLineHeight() : ImGui::GetTextLineHeightWithSpacing(); ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height)); - if (ImGui::BeginListBox("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20))) + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); if (widget_type == WidgetType_TreeNode) @@ -3465,9 +3476,8 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_TreeNode) ImGui::PopStyleVar(); - ImGui::EndListBox(); } - + ImGui::EndChild(); ImGui::TreePop(); } ImGui::TreePop(); From e7a734f78d1d87afcb845148eaa93177406d933e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 7 Mar 2024 16:26:22 +0100 Subject: [PATCH 0195/2359] MultiSelect: added ImGuiMultiSelectFlags_NoAutoSelect, ImGuiMultiSelectFlags_NoAutoClear features + added Checkbox Demo Refer to "widgets_multiselect_checkboxes" in imgui_test_suite. --- imgui.cpp | 2 +- imgui.h | 24 +++++---- imgui_demo.cpp | 51 ++++++++++++++++++ imgui_widgets.cpp | 131 ++++++++++++++++++++++++++++++++-------------- 4 files changed, 158 insertions(+), 50 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 291863e6f..ee9462a9a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4075,7 +4075,7 @@ void ImGui::MarkItemEdited(ImGuiID id) // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343) // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714) - IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id); + IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive)); //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited; diff --git a/imgui.h b/imgui.h index a5a3d9265..88445d5b7 100644 --- a/imgui.h +++ b/imgui.h @@ -2744,7 +2744,7 @@ struct ImColor // - Store and maintain actual selection data using persistent object identifiers. // - Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (2) [If using clipper] Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 6. +// - (2) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 6. // - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeItemByIndex(). If storing indices in ImGuiSelectionUserData, a simple clipper.IncludeItemByIndex(ms_io->RangeSrcItem) call will work. // LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. @@ -2773,15 +2773,17 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to select all. ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+Click/Shift+Keyboard handling (useful for unordered 2D selection). - ImGuiMultiSelectFlags_BoxSelect = 1 << 3, // Enable box-selection (only supporting 1D list when using clipper, not 2D grids). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_BoxSelect2d = 1 << 4, // Enable box-selection with 2D layout/grid support. This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. - ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 5, // Disable scrolling when box-selecting near edges of scope. - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 6, // Clear selection when pressing Escape while scope is focused. - ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 7, // Clear selection when clicking on empty location within scope. - ImGuiMultiSelectFlags_ScopeWindow = 1 << 8, // Use if BeginMultiSelect() covers a whole window (Default): Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). - ImGuiMultiSelectFlags_ScopeRect = 1 << 9, // Use if multiple BeginMultiSelect() are used in the same host window: Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. - ImGuiMultiSelectFlags_SelectOnClick = 1 << 10, // Apply selection on mouse down when clicking on unselected item. (Default) - ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 11, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. + ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) + ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing other items when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) + ImGuiMultiSelectFlags_BoxSelect = 1 << 5, // Enable box-selection (only supporting 1D list when using clipper, not 2D grids). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 6, // Enable box-selection with 2D layout/grid support. This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. + ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 7, // Disable scrolling when box-selecting near edges of scope. + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 8, // Clear selection when pressing Escape while scope is focused. + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 9, // Clear selection when clicking on empty location within scope. + ImGuiMultiSelectFlags_ScopeWindow = 1 << 10, // Use if BeginMultiSelect() covers a whole window (Default): Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). + ImGuiMultiSelectFlags_ScopeRect = 1 << 11, // Use if multiple BeginMultiSelect() are used in the same host window: Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. + ImGuiMultiSelectFlags_SelectOnClick = 1 << 12, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 13, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. }; // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). @@ -2803,7 +2805,7 @@ struct ImGuiMultiSelectIO enum ImGuiSelectionRequestType { ImGuiSelectionRequestType_None = 0, - ImGuiSelectionRequestType_SetAll, // Request app to clear selection (if Selected==false) or select all items (if Selected==true) + ImGuiSelectionRequestType_SetAll, // Request app to clear selection (if Selected==false) or select all items (if Selected==true). We cannot set RangeFirstItem/RangeLastItem as its contents is entirely up to user (not necessarily an index) ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items (inclusive) based on value of Selected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9d23d4661..f5cfa53e1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3205,6 +3205,55 @@ static void ShowDemoWindowMultiSelect() ImGui::TreePop(); } + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (checkboxes)"); + if (ImGui::TreeNode("Multi-Select (checkboxes)")) + { + ImGui::Text("In a list of checkboxes (not selectable):"); + ImGui::BulletText("Using _NoAutoSelect + _NoAutoClear flags."); + ImGui::BulletText("Shift+Click to check multiple boxes."); + ImGui::BulletText("Shift+Keyboard to copy current value to other boxes."); + + static bool values[20] = {}; + static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_ClearOnEscape; + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); + + struct Funcs + { + static void ApplyMultiSelectRequestsToBoolArray(ImGuiMultiSelectIO* ms_io, bool items[], int items_count) + { + for (ImGuiSelectionRequest& req : ms_io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_SetAll) + for (int n = 0; n < items_count; n++) + items[n] = req.Selected; + else if (req.Type == ImGuiSelectionRequestType_SetRange) + for (int n = (int)req.RangeFirstItem; n <= (int)req.RangeLastItem; n++) + items[n] = req.Selected; + } + } + }; + + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_Border | ImGuiChildFlags_ResizeY)) + { + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + Funcs::ApplyMultiSelectRequestsToBoolArray(ms_io, values, IM_ARRAYSIZE(values)); //// By specs, it could be optional to apply requests from BeginMultiSelect() if not using a clipper. + for (int n = 0; n < 20; n++) + { + char label[32]; + sprintf(label, "Item %d", n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Checkbox(label, &values[n]); + } + ms_io = ImGui::EndMultiSelect(); + Funcs::ApplyMultiSelectRequestsToBoolArray(ms_io, values, IM_ARRAYSIZE(values)); + } + ImGui::EndChild(); + + ImGui::TreePop(); + } + // Demonstrate individual selection scopes in same window IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (multiple scopes)"); if (ImGui::TreeNode("Multi-Select (multiple scopes)")) @@ -3290,6 +3339,8 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoRangeSelect", &flags, ImGuiMultiSelectFlags_NoRangeSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index eef613071..2eefe8fea 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1141,11 +1141,25 @@ bool ImGui::Checkbox(const char* label, bool* v) return false; } + // Range-Selection/Multi-selection support (header) + bool checked = *v; + const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; + if (is_multi_select) + MultiSelectItemHeader(id, &checked, NULL); + bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); - if (pressed) + + // Range-Selection/Multi-selection support (footer) + if (is_multi_select) + MultiSelectItemFooter(id, &checked, &pressed); + else if (pressed) + checked = !checked; + + if (*v != checked) { - *v = !(*v); + *v = checked; + pressed = true; // return value MarkItemEdited(id); } @@ -7333,13 +7347,13 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) ms->IsKeyboardSetRange = true; if (ms->IsKeyboardSetRange) IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid); // Not ready -> could clear? - if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) + if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0) request_clear = true; } else if (g.NavJustMovedFromFocusScopeId == ms->FocusScopeId) { // Also clear on leaving scope (may be optional?) - if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) + if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0) request_clear = true; } @@ -7517,11 +7531,15 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags const bool is_range_src = storage->RangeSrcItem == item_data; if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy) { + // Apply range-select value to visible items IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1); selected = (storage->RangeSelected != 0); } - else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0) + else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0 && (ms->Flags & ImGuiMultiSelectFlags_NoAutoClear) == 0) + { + // Clear other items selected = false; + } } *p_selected = selected; } @@ -7529,13 +7547,16 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags // Alter button behavior flags // To handle drag and drop of multiple items we need to avoid clearing selection on click. // Enabling this test makes actions using CTRL+SHIFT delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. - ImGuiButtonFlags button_flags = *p_button_flags; - button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; - if ((!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) && !(ms->Flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) - button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; - else - button_flags |= ImGuiButtonFlags_PressedOnClickRelease; - *p_button_flags = button_flags; + if (p_button_flags != NULL) + { + ImGuiButtonFlags button_flags = *p_button_flags; + button_flags |= ImGuiButtonFlags_NoHoveredOnFocus; + if ((!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) && !(ms->Flags & ImGuiMultiSelectFlags_SelectOnClickRelease)) + button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; + else + button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + *p_button_flags = button_flags; + } } // In charge of: @@ -7570,11 +7591,10 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0; bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0; + bool apply_to_range_src = false; + if (g.NavId == id && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) - { - storage->RangeSrcItem = item_data; - storage->RangeSelected = selected; // Will be updated at the end of this function anyway. - } + apply_to_range_src = true; if (ms->IsEndIO == false) { ms->IO.Requests.resize(0); @@ -7584,10 +7604,27 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Auto-select as you navigate a list if (g.NavJustMovedToId == id) { - if (is_ctrl && is_shift) - pressed = true; - else if (!is_ctrl) - selected = pressed = true; + if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0) + { + if (is_ctrl && is_shift) + pressed = true; + else if (!is_ctrl) + selected = pressed = true; + } + else + { + // With NoAutoSelect, using Shift+keyboard performs a write/copy + if (is_shift) + pressed = true; + else if (!is_ctrl) + apply_to_range_src = true; // Since if (pressed) {} main block is not running we update this + } + } + + if (apply_to_range_src) + { + storage->RangeSrcItem = item_data; + storage->RangeSelected = selected; // Will be updated at the end of this function anyway. } // Box-select toggle handling @@ -7608,9 +7645,9 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ms->BoxSelectLastitem = item_data; } - // Right-click handling: this could be moved at the Selectable() level. - // FIXME-MULTISELECT: See https://github.com/ocornut/imgui/pull/5816 - if (hovered && IsMouseClicked(1)) + // Right-click handling. + // FIXME-MULTISELECT: Currently filtered out by ImGuiMultiSelectFlags_NoAutoSelect but maybe should be moved to Selectable(). See https://github.com/ocornut/imgui/pull/5816 + if (hovered && IsMouseClicked(1) && (flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0) { if (g.ActiveId != 0 && g.ActiveId != id) ClearActiveID(); @@ -7653,36 +7690,54 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) // Mouse Pressed: Ctrl+Shift | n/a | Dst=item, Sel=!Sel => SetRange Src-Dst //---------------------------------------------------------------------------------------- - bool request_clear = false; - if (is_singleselect) - request_clear = true; - else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl) - request_clear = true; - else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl) - request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. - if (request_clear) + if ((flags & ImGuiMultiSelectFlags_NoAutoClear) == 0) { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, (ImGuiSelectionUserData)-1, (ImGuiSelectionUserData)-1 }; - ms->IO.Requests.resize(0); - ms->IO.Requests.push_back(req); + bool request_clear = false; + if (is_singleselect) + request_clear = true; + else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl) + request_clear = true; + else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl) + request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. + if (request_clear) + { + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; + ms->IO.Requests.resize(0); + ms->IO.Requests.push_back(req); + } } int range_direction; bool range_selected; if (is_shift && !is_singleselect) { - // Shift+Arrow always select - // Ctrl+Shift+Arrow copy source selection state (already stored by BeginMultiSelect() in storage->RangeSelected) //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue); if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) storage->RangeSrcItem = item_data; - range_selected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; + if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0) + { + // Shift+Arrow always select + // Ctrl+Shift+Arrow copy source selection state (already stored by BeginMultiSelect() in storage->RangeSelected) + range_selected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; + } + else + { + // Shift+Arrow copy source selection state + // Shift+Click always copy from target selection state + if (ms->IsKeyboardSetRange) + range_selected = (storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true; + else + range_selected = !selected; + } range_direction = ms->RangeSrcPassedBy ? +1 : -1; } else { // Ctrl inverts selection, otherwise always select - selected = is_ctrl ? !selected : true; + if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0) + selected = is_ctrl ? !selected : true; + else + selected = !selected; storage->RangeSrcItem = item_data; range_selected = selected; range_direction = +1; From 0be238ec587e98ee00a50c67ad826c3e8f0420bc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 18 Apr 2024 15:35:29 +0200 Subject: [PATCH 0196/2359] MultiSelect: Box-Select: fix preventing focus. amend determination of scope_hovered for decorated/non-child windows + avoid stealing NavId. (#7424) --- imgui_widgets.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2eefe8fea..1f024d0ce 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7435,7 +7435,8 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() // Clear selection when clicking void? // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection! - bool scope_hovered = IsWindowHovered(); + // The InnerRect test is necessary for non-child/decorated windows. + bool scope_hovered = IsWindowHovered() && window->InnerRect.Contains(g.IO.MousePos); if (scope_hovered && (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)) scope_hovered &= scope_rect.Contains(g.IO.MousePos); if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0) @@ -7443,10 +7444,13 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) { if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1) + { BoxSelectStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); - SetHoveredID(ms->BoxSelectId); - if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) - SetNavID(0, ImGuiNavLayer_Main, ms->FocusScopeId, ImRect(g.IO.MousePos, g.IO.MousePos)); // Automatically switch FocusScope for initial click from outside to box-select. + FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal); + SetHoveredID(ms->BoxSelectId); + if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) + SetNavID(0, ImGuiNavLayer_Main, ms->FocusScopeId, ImRect(g.IO.MousePos, g.IO.MousePos)); // Automatically switch FocusScope for initial click from void to box-select. + } } if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) From 955210ae5bf4aeeb7ca2a6bc15521f6481016624 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 May 2024 18:56:31 +0200 Subject: [PATCH 0197/2359] MultiSelect: Demo: use Shortcut(). Got rid of suggestion to move Delete signal processing to BeginMultiSelect(), seems unnecessary. --- imgui.h | 2 +- imgui_demo.cpp | 9 +++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 88445d5b7..89f016dfc 100644 --- a/imgui.h +++ b/imgui.h @@ -2814,7 +2814,7 @@ struct ImGuiSelectionRequest { //------------------------------------------// BeginMultiSelect / EndMultiSelect ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. - bool Selected; // / ms:w, app:r // Parameter for SetAll/SetRange requests (true = select, false = unselect) + bool Selected; // ms:w, app:r / ms:w, app:r // Parameter for SetAll/SetRange requests (true = select, false = unselect) ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f5cfa53e1..a8759933d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3161,9 +3161,7 @@ static void ShowDemoWindowMultiSelect() ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, items.Size); - // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to turn into 'ms_io->RequestDelete' signal -> need HasSelection passed. - // FIXME-MULTISELECT: If pressing Delete + another key we have ambiguous behavior. - const bool want_delete = (selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete); + const bool want_delete = ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0); const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1; for (int n = 0; n < items.Size; n++) @@ -3378,8 +3376,7 @@ static void ShowDemoWindowMultiSelect() ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); selection.ApplyRequests(ms_io, items.Size); - // FIXME-MULTISELECT: Shortcut(). Hard to demo this? May be helpful to turn into 'ms_io->RequestDelete' signal -> need HasSelection passed. - const bool want_delete = request_deletion_from_menu || ((selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); + const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0)) || request_deletion_from_menu; const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1; request_deletion_from_menu = false; @@ -9854,7 +9851,7 @@ struct ExampleAssetsBrowser Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->AdapterData; return self->Items[idx].ID; }; Selection.ApplyRequests(ms_io, Items.Size); - const bool want_delete = RequestDelete || ((Selection.Size > 0) && ImGui::IsWindowFocused() && ImGui::IsKeyPressed(ImGuiKey_Delete)); + const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (Selection.Size > 0)) || RequestDelete; const int item_curr_idx_to_focus = want_delete ? Selection.ApplyDeletionPreLoop(ms_io, Items.Size) : -1; RequestDelete = false; From 9435a3185affdb72a405d7257d2dc63f662c7c93 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 19 Dec 2023 14:06:58 +0100 Subject: [PATCH 0198/2359] RangeSelect/MultiSelect: (Breaking) Added current_selection_size to BeginMultiSelect(). Required for shortcut routing so we can e.g. have Escape be used to clear selection THEN to exit child window. --- imgui.h | 2 +- imgui_demo.cpp | 14 +++++++------- imgui_widgets.cpp | 10 ++++++---- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/imgui.h b/imgui.h index 89f016dfc..d5a3bda52 100644 --- a/imgui.h +++ b/imgui.h @@ -675,7 +675,7 @@ namespace ImGui // - 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. // - ImGuiSelectionUserData is often used to store your item index. // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. - IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags); + IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, int current_selection_size = -1); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); IMGUI_API bool IsItemToggledSelection(); // Was the last item selection state toggled? Useful if you need the per-item information _before_ reaching EndMultiSelect(). We only returns toggle _event_ in order to handle clipping correctly. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a8759933d..c984ee40f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2929,7 +2929,7 @@ struct ExampleDualListBox if (child_visible) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); ApplySelectionRequests(ms_io, side); for (int item_n = 0; item_n < items.Size; item_n++) @@ -3060,7 +3060,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); selection.ApplyRequests(ms_io, ITEMS_COUNT); for (int n = 0; n < ITEMS_COUNT; n++) @@ -3094,7 +3094,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); selection.ApplyRequests(ms_io, ITEMS_COUNT); ImGuiListClipper clipper; @@ -3158,7 +3158,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); selection.ApplyRequests(ms_io, items.Size); const bool want_delete = ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0); @@ -3274,7 +3274,7 @@ static void ShowDemoWindowMultiSelect() { ImGui::PushID(selection_scope_n); ImGuiSelectionBasicStorage* selection = &selections_data[selection_scope_n]; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection->Size); selection->ApplyRequests(ms_io, ITEMS_COUNT); ImGui::SeparatorText("Selection scope"); @@ -3373,7 +3373,7 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_TreeNode) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); selection.ApplyRequests(ms_io, items.Size); const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0)) || request_deletion_from_menu; @@ -9844,7 +9844,7 @@ struct ExampleAssetsBrowser ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. if (AllowBoxSelect) ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; // Enable box-select in 2D mode. - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size); // Use custom selection adapter: store ID in selection (recommended) Selection.AdapterData = this; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1f024d0ce..a85776200 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7293,7 +7293,10 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe // Return ImGuiMultiSelectIO structure. // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). -ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) +// Passing 'current_selection_size' is currently optional: +// - it is useful for shortcut routing with ImGuiMultiSelectFlags_ClearOnEscape: so we can have Escape be used to clear selection THEN to exit child window. +// - if it is costly for you to compute, but can easily tell if your selection is empty or not, you may alter the ImGuiMultiSelectFlags_ClearOnEscape flag based on that. +ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int current_selection_size) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -7360,9 +7363,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags) if (ms->IsFocused) { // Shortcut: Clear selection (Escape) - // FIXME-MULTISELECT: Only hog shortcut if selection is not null, meaning we need "has selection or "selection size" data here. - // Otherwise may be done by caller but it means Shortcut() needs to be exposed. - if (flags & ImGuiMultiSelectFlags_ClearOnEscape) + // Only claim shortcut if selection is not empty, allowing further presses on Escape to e.g. leave current child window. + if ((flags & ImGuiMultiSelectFlags_ClearOnEscape) && (current_selection_size != 0)) if (Shortcut(ImGuiKey_Escape)) request_clear = true; From 65ebc0513b2dd0eb8eec86075060fb62c43b488a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 May 2024 14:33:41 +0200 Subject: [PATCH 0199/2359] MultiSelect: Box-Select: minor refactor, tidying up. --- imgui_widgets.cpp | 94 ++++++++++++++++++++++++++--------------------- 1 file changed, 53 insertions(+), 41 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a85776200..f83fda9e2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7131,13 +7131,18 @@ void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data) // [SECTION] Widgets: Box-Select support // This has been extracted away from Multi-Select logic in the hope that it could eventually be used elsewhere, but hasn't been yet. //------------------------------------------------------------------------- -// - BoxSelectStartDrag() [Internal] +// Extra logic in MultiSelectItemFooter() and ImGuiListClipper::Step() +//------------------------------------------------------------------------- +// - BoxSelectPreStartDrag() [Internal] +// - BoxSelectActivateDrag() [Internal] +// - BoxSelectDeactivateDrag() [Internal] // - BoxSelectScrollWithMouseDrag() [Internal] // - BeginBoxSelect() [Internal] // - EndBoxSelect() [Internal] //------------------------------------------------------------------------- -static void BoxSelectStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_item) +// Call on the initial click. +static void BoxSelectPreStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_item) { ImGuiContext& g = *GImGui; ImGuiBoxSelectState* bs = &g.BoxSelectState; @@ -7149,10 +7154,33 @@ static void BoxSelectStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_item) bs->ScrollAccum = ImVec2(0.0f, 0.0f); } -static void BoxSelectScrollWithMouseDrag(ImGuiWindow* window, const ImRect& inner_r) +static void BoxSelectActivateDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Activate\n", bs->ID); + bs->IsActive = true; + bs->Window = window; + bs->IsStarting = false; + ImGui::SetActiveID(bs->ID, window); + if (bs->IsStartedFromVoid && (bs->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) + bs->RequestClear = true; +} + +static void BoxSelectDeactivateDrag(ImGuiBoxSelectState* bs) +{ + ImGuiContext& g = *GImGui; + bs->IsActive = bs->IsStarting = false; + if (g.ActiveId == bs->ID) + { + IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Deactivate\n", bs->ID); + ImGui::ClearActiveID(); + } + bs->ID = 0; +} + +static void BoxSelectScrollWithMouseDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window, const ImRect& inner_r) { ImGuiContext& g = *GImGui; - ImGuiBoxSelectState* bs = &g.BoxSelectState; IM_ASSERT(bs->Window == window); for (int n = 0; n < 2; n++) // each axis { @@ -7186,30 +7214,13 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult if (bs->ID != box_select_id) return false; + // IsStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. bs->UnclipMode = false; bs->RequestClear = false; - - // IsStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry. if (bs->IsStarting && IsMouseDragPastThreshold(0)) - { - IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Started.\n", box_select_id); - bs->IsActive = true; - bs->Window = window; - bs->IsStarting = false; - SetActiveID(bs->ID, window); - if (bs->IsStartedFromVoid && (bs->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) - bs->RequestClear = true; - } + BoxSelectActivateDrag(bs, window); else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false) - { - bs->IsActive = bs->IsStarting = false; - if (g.ActiveId == bs->ID) - { - IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Ended.\n", box_select_id); - ClearActiveID(); - } - bs->ID = 0; - } + BoxSelectDeactivateDrag(bs); if (!bs->IsActive) return false; @@ -7264,7 +7275,7 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, bool enable_scroll) scroll_r.Expand(-g.FontSize); //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255)); if (!scroll_r.Contains(g.IO.MousePos)) - BoxSelectScrollWithMouseDrag(window, scroll_r); + BoxSelectScrollWithMouseDrag(bs, window, scroll_r); } } @@ -7447,7 +7458,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() { if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1) { - BoxSelectStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); + BoxSelectPreStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid); FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal); SetHoveredID(ms->BoxSelectId); if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) @@ -7634,22 +7645,23 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } // Box-select toggle handling - if (ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId)) - { - const bool rect_overlap_curr = bs->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect); - const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect); - if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr)) + if (ms->BoxSelectId != 0) + if (ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId)) { - selected = !selected; - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; - ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) - prev_req->RangeLastItem = item_data; // Merge span into same request - else - ms->IO.Requests.push_back(req); + const bool rect_overlap_curr = bs->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect); + const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect); + if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr)) + { + selected = !selected; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; + ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; + if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) + prev_req->RangeLastItem = item_data; // Merge span into same request + else + ms->IO.Requests.push_back(req); + } + ms->BoxSelectLastitem = item_data; } - ms->BoxSelectLastitem = item_data; - } // Right-click handling. // FIXME-MULTISELECT: Currently filtered out by ImGuiMultiSelectFlags_NoAutoSelect but maybe should be moved to Selectable(). See https://github.com/ocornut/imgui/pull/5816 @@ -7677,7 +7689,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; if (flags & ImGuiMultiSelectFlags_BoxSelect) if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) - BoxSelectStartDrag(ms->BoxSelectId, item_data); + BoxSelectPreStartDrag(ms->BoxSelectId, item_data); //---------------------------------------------------------------------------------------- // ACTION | Begin | Pressed/Activated | End From dc0a1682e3b5d74c685a31649ece5d2dabedbd37 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 May 2024 15:01:52 +0200 Subject: [PATCH 0200/2359] MultiSelect: Box-Select: when dragging from void, first hit item sets NavId by simulating a press, so navigation can resume from that spot. --- imgui_internal.h | 1 + imgui_widgets.cpp | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5fb2d568d..53b0c85c4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1758,6 +1758,7 @@ struct IMGUI_API ImGuiMultiSelectTempData bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool IsKeyboardSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. + bool IsSelectionEmpty; // Set by BeginMultiSelect() based on optional info provided by user. May be false positive, never false negative. bool NavIdPassedBy; bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f83fda9e2..9eaadc2a8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7330,6 +7330,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur ms->FocusScopeId = id; ms->Flags = flags; ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId); + ms->IsSelectionEmpty = (current_selection_size == 0); ms->BackupCursorMaxPos = window->DC.CursorMaxPos; ms->ScopeRectMin = window->DC.CursorMaxPos = window->DC.CursorPos; PushFocusScope(ms->FocusScopeId); @@ -7398,6 +7399,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur if (request_clear || request_select_all) { ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; + if (!request_select_all) + ms->IsSelectionEmpty = true; ms->IO.Requests.push_back(req); } ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1; @@ -7655,10 +7658,13 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = !selected; ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) + if (ms->IsSelectionEmpty && bs->IsStartedFromVoid) + pressed = true; // First item act as a pressed: code below will emit selection request and set NavId (whatever we emit here will be overriden anyway) + else if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) prev_req->RangeLastItem = item_data; // Merge span into same request else ms->IO.Requests.push_back(req); + ms->IsSelectionEmpty = false; } ms->BoxSelectLastitem = item_data; } From 81548cb6bf3a0b3f50d7c0fbb65be1529aba68c9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 May 2024 15:22:32 +0200 Subject: [PATCH 0201/2359] MultiSelect: added GetMultiSelectState() + store LastSelectionSize as provided by user, convenient for quick debugging and testing. --- imgui_internal.h | 7 ++++--- imgui_widgets.cpp | 9 +++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 53b0c85c4..908c8f426 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1758,7 +1758,6 @@ struct IMGUI_API ImGuiMultiSelectTempData bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool IsKeyboardSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. - bool IsSelectionEmpty; // Set by BeginMultiSelect() based on optional info provided by user. May be false positive, never false negative. bool NavIdPassedBy; bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. @@ -1775,12 +1774,13 @@ struct IMGUI_API ImGuiMultiSelectState ImGuiWindow* Window; ImGuiID ID; int LastFrameActive; // Last used frame-count, for GC. + int LastSelectionSize; // Set by BeginMultiSelect() based on optional info provided by user. May be -1 if unknown. ImS8 RangeSelected; // -1 (don't have) or true/false ImS8 NavIdSelected; // -1 (don't have) or true/false ImGuiSelectionUserData RangeSrcItem; // ImGuiSelectionUserData NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) - ImGuiMultiSelectState() { Window = NULL; ID = 0; LastFrameActive = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } + ImGuiMultiSelectState() { Window = NULL; ID = 0; LastFrameActive = LastSelectionSize = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } }; #endif // #ifdef IMGUI_HAS_MULTI_SELECT @@ -3411,7 +3411,8 @@ namespace ImGui // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); - inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.ID == id && g.BoxSelectState.IsActive) ? &g.BoxSelectState : NULL; } + inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.ID == id && g.BoxSelectState.IsActive) ? &g.BoxSelectState : NULL; } + inline ImGuiMultiSelectState* GetMultiSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return g.MultiSelectStorage.GetByKey(id); } // Internal 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9eaadc2a8..d0adf2a9c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7330,7 +7330,6 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur ms->FocusScopeId = id; ms->Flags = flags; ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId); - ms->IsSelectionEmpty = (current_selection_size == 0); ms->BackupCursorMaxPos = window->DC.CursorMaxPos; ms->ScopeRectMin = window->DC.CursorMaxPos = window->DC.CursorPos; PushFocusScope(ms->FocusScopeId); @@ -7344,6 +7343,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur ImGuiMultiSelectState* storage = g.MultiSelectStorage.GetOrAddByKey(id); storage->ID = id; storage->LastFrameActive = g.FrameCount; + storage->LastSelectionSize = current_selection_size; storage->Window = window; ms->Storage = storage; @@ -7400,7 +7400,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur { ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; if (!request_select_all) - ms->IsSelectionEmpty = true; + storage->LastSelectionSize = 0; ms->IO.Requests.push_back(req); } ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1; @@ -7658,13 +7658,13 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) selected = !selected; ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (ms->IsSelectionEmpty && bs->IsStartedFromVoid) + if (storage->LastSelectionSize == 0 && bs->IsStartedFromVoid) pressed = true; // First item act as a pressed: code below will emit selection request and set NavId (whatever we emit here will be overriden anyway) else if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) prev_req->RangeLastItem = item_data; // Merge span into same request else ms->IO.Requests.push_back(req); - ms->IsSelectionEmpty = false; + storage->LastSelectionSize++; } ms->BoxSelectLastitem = item_data; } @@ -7799,6 +7799,7 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) return; Text("RangeSrcItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), RangeSelected = %d", storage->RangeSrcItem, storage->RangeSrcItem, storage->RangeSelected); Text("NavIdItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), NavIdSelected = %d", storage->NavIdItem, storage->NavIdItem, storage->NavIdSelected); + Text("LastSelectionSize = %d", storage->LastSelectionSize); // Provided by user TreePop(); #else IM_UNUSED(storage); From 1113f13f8384d9b61919ec34e209a6a7dedab7ff Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 May 2024 20:18:57 +0200 Subject: [PATCH 0202/2359] MultiSelect: Box-Select: fixed "when dragging from void" implementation messing with calling BeginMultiSelect() without a selection size. --- imgui_widgets.cpp | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d0adf2a9c..062b36452 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7529,7 +7529,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData; IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope"); - // Apply SetAll (Clear/SelectAll )requests requested by BeginMultiSelect(). + // Apply SetAll (Clear/SelectAll) requests requested by BeginMultiSelect(). // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper. // If you are using a clipper you need to process the SetAll request after calling BeginMultiSelect() if (ms->LoopRequestSetAll != -1) @@ -7655,16 +7655,21 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect); if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr)) { - selected = !selected; - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; - ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (storage->LastSelectionSize == 0 && bs->IsStartedFromVoid) - pressed = true; // First item act as a pressed: code below will emit selection request and set NavId (whatever we emit here will be overriden anyway) - else if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) - prev_req->RangeLastItem = item_data; // Merge span into same request + if (storage->LastSelectionSize <= 0 && bs->IsStartedFromVoid) + { + pressed = true; // First item act as a pressed: code below will emit selection request and set NavId (whatever we emit here will be overridden anyway) + } else - ms->IO.Requests.push_back(req); - storage->LastSelectionSize++; + { + selected = !selected; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; + ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; + if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) + prev_req->RangeLastItem = item_data; // Merge span into same request + else + ms->IO.Requests.push_back(req); + } + storage->LastSelectionSize = ImMax(storage->LastSelectionSize + 1, 1); } ms->BoxSelectLastitem = item_data; } From 2f56df483981985b60dffc4577b868375711541a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 May 2024 18:44:57 +0200 Subject: [PATCH 0203/2359] MultiSelect: (breaking) renamed ImGuiSelectionBasicStorage::AdapterData to UserData. --- imgui.h | 4 ++-- imgui_demo.cpp | 12 ++++++------ imgui_widgets.cpp | 3 ++- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index d5a3bda52..58409f611 100644 --- a/imgui.h +++ b/imgui.h @@ -2843,14 +2843,14 @@ struct ImGuiSelectionBasicStorage // Members ImGuiStorage Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. - void* AdapterData; // Adapter to convert item index to item identifier // e.g. selection.AdapterData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->AdapterData)[idx]->ID; }; + void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count); // Methods: selection storage - ImGuiSelectionBasicStorage() { Clear(); AdapterData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } + ImGuiSelectionBasicStorage() { Clear(); UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } void Clear() { Storage.Data.resize(0); Size = 0; } void Swap(ImGuiSelectionBasicStorage& r) { Storage.Data.swap(r.Storage.Data); } bool Contains(ImGuiID id) const { return Storage.GetInt(id, 0) != 0; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c984ee40f..efaf116dd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2872,8 +2872,8 @@ struct ExampleDualListBox void ApplySelectionRequests(ImGuiMultiSelectIO* ms_io, int side) { // In this example we store item id in selection (instead of item index) - Selections[side].AdapterData = Items[side].Data; - Selections[side].AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImGuiID* items = (ImGuiID*)self->AdapterData; return items[idx]; }; + Selections[side].UserData = Items[side].Data; + Selections[side].AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImGuiID* items = (ImGuiID*)self->UserData; return items[idx]; }; Selections[side].ApplyRequests(ms_io, Items[side].Size); } static int IMGUI_CDECL CompareItemsByValue(const void* lhs, const void* rhs) @@ -3135,8 +3135,8 @@ static void ShowDemoWindowMultiSelect() // Use a custom selection.Adapter: store item identifier in Selection (instead of index) static ImVector items; static ExampleSelectionWithDeletion selection; - selection.AdapterData = (void*)&items; - selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImVector* p_items = (ImVector*)self->AdapterData; return (*p_items)[idx]; }; // Index -> ID + selection.UserData = (void*)&items; + selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImVector* p_items = (ImVector*)self->UserData; return (*p_items)[idx]; }; // Index -> ID ImGui::Text("Added features:"); ImGui::BulletText("Dynamic list with Delete key support."); @@ -9847,8 +9847,8 @@ struct ExampleAssetsBrowser ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size); // Use custom selection adapter: store ID in selection (recommended) - Selection.AdapterData = this; - Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->AdapterData; return self->Items[idx].ID; }; + Selection.UserData = this; + Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->UserData; return self->Items[idx].ID; }; Selection.ApplyRequests(ms_io, Items.Size); const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (Selection.Size > 0)) || RequestDelete; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 062b36452..7602b2cd1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7306,7 +7306,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). // Passing 'current_selection_size' is currently optional: // - it is useful for shortcut routing with ImGuiMultiSelectFlags_ClearOnEscape: so we can have Escape be used to clear selection THEN to exit child window. -// - if it is costly for you to compute, but can easily tell if your selection is empty or not, you may alter the ImGuiMultiSelectFlags_ClearOnEscape flag based on that. +// - if it is costly for you to compute, but can easily tell if your selection is empty or not, you may pass 1, or use the ImGuiMultiSelectFlags_ClearOnEscape flag dynamically. ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int current_selection_size) { ImGuiContext& g = *GImGui; @@ -7347,6 +7347,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur storage->Window = window; ms->Storage = storage; + // Output to user ms->IO.RangeSrcItem = storage->RangeSrcItem; ms->IO.NavIdItem = storage->NavIdItem; ms->IO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; From 7bbbbea20045ce933b4c3c2f5dd683bb03e08930 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 May 2024 21:37:45 +0200 Subject: [PATCH 0204/2359] MultiSelect: Box-Select: fixes for checkboxes support. Comments. --- imgui.h | 4 ++-- imgui_demo.cpp | 2 +- imgui_widgets.cpp | 20 ++++++++------------ 3 files changed, 11 insertions(+), 15 deletions(-) diff --git a/imgui.h b/imgui.h index 58409f611..40ac55587 100644 --- a/imgui.h +++ b/imgui.h @@ -2775,8 +2775,8 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+Click/Shift+Keyboard handling (useful for unordered 2D selection). ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing other items when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) - ImGuiMultiSelectFlags_BoxSelect = 1 << 5, // Enable box-selection (only supporting 1D list when using clipper, not 2D grids). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_BoxSelect2d = 1 << 6, // Enable box-selection with 2D layout/grid support. This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. + ImGuiMultiSelectFlags_BoxSelect = 1 << 5, // Enable box-selection with same width and same x pos items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 6, // Enable box-selection with varying width or varying x pos items (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 7, // Disable scrolling when box-selecting near edges of scope. ImGuiMultiSelectFlags_ClearOnEscape = 1 << 8, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 9, // Clear selection when clicking on empty location within scope. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index efaf116dd..ec15e2791 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3215,7 +3215,7 @@ static void ShowDemoWindowMultiSelect() static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_ClearOnEscape; ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); // Use 2D version as checkboxes are not same width. struct Funcs { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7602b2cd1..c5e8c1f60 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1136,10 +1136,11 @@ bool ImGui::Checkbox(const char* label, bool* v) ItemSize(total_bb, style.FramePadding.y); const bool is_visible = ItemAdd(total_bb, id); if (!is_visible) - { - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); - return false; - } + if (!g.BoxSelectState.UnclipMode || (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) == 0 || !g.BoxSelectState.UnclipRect.Overlaps(total_bb)) // Extra layer of "no logic clip" for box-select support + { + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); + return false; + } // Range-Selection/Multi-selection support (header) bool checked = *v; @@ -6801,13 +6802,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; if (!is_visible) - { - // Extra layer of "no logic clip" for box-select support - if (!is_multi_select) + if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(bb)) // Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd) return false; - if (!g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(bb)) - return false; - } const bool disabled_global = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; if (disabled_item && !disabled_global) // Only testing this as an optimization @@ -7242,9 +7238,9 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult if (ms_flags & ImGuiMultiSelectFlags_BoxSelect2d) if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x) { - bs->UnclipRect = bs->BoxSelectRectPrev; - bs->UnclipRect.Add(bs->BoxSelectRectCurr); bs->UnclipMode = true; + bs->UnclipRect = bs->BoxSelectRectPrev; // FIXME-OPT: UnclipRect x coordinates could be intersection of Prev and Curr rect on X axis. + bs->UnclipRect.Add(bs->BoxSelectRectCurr); } //GetForegroundDrawList()->AddRect(bs->UnclipRect.Min, bs->UnclipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f); From f6b5caf82c718297a61127ae474290ea2e88be1a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 May 2024 21:57:10 +0200 Subject: [PATCH 0205/2359] MultiSelect: (breaking) renamed ImGuiMultiSelectFlags_BoxSelect -> ImGuiMultiSelectFlags_BoxSelect1d, ImGuiMultiSelectFlags_BoxSelect2d -> ImGuiMultiSelectFlags_BoxSelect. ImGuiMultiSelectFlags_BoxSelect1d being an optimization it is the optional flag. --- imgui.h | 4 ++-- imgui_demo.cpp | 17 +++++++++-------- imgui_widgets.cpp | 6 +++--- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index 40ac55587..4be6e6467 100644 --- a/imgui.h +++ b/imgui.h @@ -2775,8 +2775,8 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+Click/Shift+Keyboard handling (useful for unordered 2D selection). ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing other items when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) - ImGuiMultiSelectFlags_BoxSelect = 1 << 5, // Enable box-selection with same width and same x pos items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_BoxSelect2d = 1 << 6, // Enable box-selection with varying width or varying x pos items (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. + ImGuiMultiSelectFlags_BoxSelect = 1 << 5, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. only full row Selectable()). Small optimization. ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 7, // Disable scrolling when box-selecting near edges of scope. ImGuiMultiSelectFlags_ClearOnEscape = 1 << 8, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 9, // Clear selection when clicking on empty location within scope. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ec15e2791..58ceb68b3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3059,7 +3059,7 @@ static void ShowDemoWindowMultiSelect() // The BeginChild() has no purpose for selection logic, other that offering a scrolling region. if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); selection.ApplyRequests(ms_io, ITEMS_COUNT); @@ -3093,7 +3093,7 @@ static void ShowDemoWindowMultiSelect() ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); selection.ApplyRequests(ms_io, ITEMS_COUNT); @@ -3157,7 +3157,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { - ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); selection.ApplyRequests(ms_io, items.Size); @@ -3215,7 +3215,7 @@ static void ShowDemoWindowMultiSelect() static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_ClearOnEscape; ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); // Use 2D version as checkboxes are not same width. + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); // Cannot use ImGuiMultiSelectFlags_BoxSelect1d as checkboxes are varying width. struct Funcs { @@ -3268,7 +3268,7 @@ static void ShowDemoWindowMultiSelect() if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect)) flags &= ~ImGuiMultiSelectFlags_ScopeWindow; ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d); for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++) { @@ -3321,7 +3321,7 @@ static void ShowDemoWindowMultiSelect() static bool use_drag_drop = true; static bool show_in_table = false; static bool show_color_button = false; - static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect; + static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; static WidgetType widget_type = WidgetType_Selectable; if (ImGui::TreeNode("Options")) @@ -3340,6 +3340,7 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); @@ -9843,7 +9844,7 @@ struct ExampleAssetsBrowser if (AllowDragUnselected) ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. if (AllowBoxSelect) - ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; // Enable box-select in 2D mode. + ms_flags |= ImGuiMultiSelectFlags_BoxSelect; // Enable box-select in 2D mode. ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size); // Use custom selection adapter: store ID in selection (recommended) @@ -9918,7 +9919,7 @@ struct ExampleAssetsBrowser } // Render icon (a real app would likely display an image/thumbnail here) - // Because we use ImGuiMultiSelectFlags_BoxSelect2d mode, + // Because we use ImGuiMultiSelectFlags_BoxSelect (without ImGuiMultiSelectFlags_BoxSelect1d flag), // clipping vertical range may occasionally be larger so we coarse-clip our rendering. if (item_is_visible) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c5e8c1f60..bd25e1adb 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7235,7 +7235,7 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper) // Storing an extra rect used by widgets supporting box-select. - if (ms_flags & ImGuiMultiSelectFlags_BoxSelect2d) + if ((ms_flags & ImGuiMultiSelectFlags_BoxSelect) && !(ms_flags & ImGuiMultiSelectFlags_BoxSelect1d)) if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x) { bs->UnclipMode = true; @@ -7316,8 +7316,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0) flags |= ImGuiMultiSelectFlags_ScopeWindow; if (flags & ImGuiMultiSelectFlags_SingleSelect) - flags &= ~(ImGuiMultiSelectFlags_BoxSelect | ImGuiMultiSelectFlags_BoxSelect2d); - if (flags & ImGuiMultiSelectFlags_BoxSelect2d) + flags &= ~(ImGuiMultiSelectFlags_BoxSelect | ImGuiMultiSelectFlags_BoxSelect1d); + if (flags & ImGuiMultiSelectFlags_BoxSelect1d) flags |= ImGuiMultiSelectFlags_BoxSelect; // FIXME: BeginFocusScope() From 443b034895cc334dfb58fe7e0f8c5df5044adb66 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 4 Jun 2024 15:10:07 +0200 Subject: [PATCH 0206/2359] MultiSelect: mark parent child window as navigable into, with highlight. Assume user will always submit interactive items. --- imgui_demo.cpp | 1 + imgui_widgets.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 58ceb68b3..12f873b50 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3211,6 +3211,7 @@ static void ShowDemoWindowMultiSelect() ImGui::BulletText("Shift+Click to check multiple boxes."); ImGui::BulletText("Shift+Keyboard to copy current value to other boxes."); + // If you have an array of checkboxes, you may want to use NoAutoSelect + NoAutoClear and the ImGuiSelectionExternalStorage helper. static bool values[20] = {}; static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_ClearOnEscape; ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bd25e1adb..b60e73a49 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7329,6 +7329,8 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur ms->BackupCursorMaxPos = window->DC.CursorMaxPos; ms->ScopeRectMin = window->DC.CursorMaxPos = window->DC.CursorPos; PushFocusScope(ms->FocusScopeId); + if (flags & ImGuiMultiSelectFlags_ScopeWindow) // Mark parent child window as navigable into, with highlight. Assume user will always submit interactive items. + window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. ms->KeyMods = g.NavJustMovedToId ? g.NavJustMovedToKeyMods : g.IO.KeyMods; From ab995d3d4f39315ba405beb2a49861b53a8edf58 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Jun 2024 17:04:55 +0200 Subject: [PATCH 0207/2359] MultiSelect: (breaking) Added 'items_count' parameter to BeginMultiSelect(). Will enable extra features, and remove equivalent param from ImGuiSelectionBasicStorage::ApplyRequests(. --- imgui.h | 12 +++++++----- imgui_demo.cpp | 40 ++++++++++++++++++++-------------------- imgui_widgets.cpp | 29 +++++++++++++++++++---------- 3 files changed, 46 insertions(+), 35 deletions(-) diff --git a/imgui.h b/imgui.h index 4be6e6467..e358e1aeb 100644 --- a/imgui.h +++ b/imgui.h @@ -179,7 +179,7 @@ struct ImGuiMultiSelectIO; // Structure to interact with a BeginMultiSe struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame struct ImGuiPayload; // User data payload for drag and drop operations struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. -struct ImGuiSelectionBasicStorage; // Helper struct to store multi-selection state + apply multi-selection requests. +struct ImGuiSelectionBasicStorage; // Optional helper to store multi-selection state + apply multi-selection requests. struct ImGuiSelectionRequest; // A selection request (stored in ImGuiMultiSelectIO) struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) struct ImGuiStorage; // Helper for key->value storage (container sorted by key) @@ -673,9 +673,10 @@ namespace ImGui // Multi-selection system for Selectable() and TreeNode() functions. // - 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. - // - ImGuiSelectionUserData is often used to store your item index. + // - ImGuiSelectionUserData is often used to store your item index within the current view (but may store something else). // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. - IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, int current_selection_size = -1); + // - 'selection_size' and 'items_count' parameters are optional and used by a few features. If they are costly for you to compute, you may avoid them. + IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size = -1, int items_count = -1); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); IMGUI_API bool IsItemToggledSelection(); // Was the last item selection state toggled? Useful if you need the per-item information _before_ reaching EndMultiSelect(). We only returns toggle _event_ in order to handle clipping correctly. @@ -2799,6 +2800,7 @@ struct ImGuiMultiSelectIO ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). + int ItemsCount; // ms:w, app:r / app:r // 'int items_count' parameter to BeginMultiSelect() is copied here for convenience, allowing simpler calls to your ApplyRequests handler. Not used internally. }; // Selection request type @@ -2846,8 +2848,8 @@ struct ImGuiSelectionBasicStorage ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->AdapterData)[idx]->ID; }; void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; - // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count); + // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. Uses 'items_count' based to BeginMultiSelect() + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Methods: selection storage ImGuiSelectionBasicStorage() { Clear(); UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 12f873b50..7d4f04cdf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2874,7 +2874,7 @@ struct ExampleDualListBox // In this example we store item id in selection (instead of item index) Selections[side].UserData = Items[side].Data; Selections[side].AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImGuiID* items = (ImGuiID*)self->UserData; return items[idx]; }; - Selections[side].ApplyRequests(ms_io, Items[side].Size); + Selections[side].ApplyRequests(ms_io); } static int IMGUI_CDECL CompareItemsByValue(const void* lhs, const void* rhs) { @@ -2929,7 +2929,7 @@ struct ExampleDualListBox if (child_visible) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size); ApplySelectionRequests(ms_io, side); for (int item_n = 0; item_n < items.Size; item_n++) @@ -3060,8 +3060,8 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT); + selection.ApplyRequests(ms_io); for (int n = 0; n < ITEMS_COUNT; n++) { @@ -3073,7 +3073,7 @@ static void ShowDemoWindowMultiSelect() } ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + selection.ApplyRequests(ms_io); } ImGui::EndChild(); ImGui::TreePop(); @@ -3094,8 +3094,8 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT); + selection.ApplyRequests(ms_io); ImGuiListClipper clipper; clipper.Begin(ITEMS_COUNT); @@ -3114,7 +3114,7 @@ static void ShowDemoWindowMultiSelect() } ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, ITEMS_COUNT); + selection.ApplyRequests(ms_io); } ImGui::EndChild(); ImGui::TreePop(); @@ -3158,8 +3158,8 @@ static void ShowDemoWindowMultiSelect() if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); - selection.ApplyRequests(ms_io, items.Size); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size); + selection.ApplyRequests(ms_io); const bool want_delete = ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0); const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1; @@ -3179,7 +3179,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, items.Size); + selection.ApplyRequests(ms_io); if (want_delete) selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus); } @@ -3275,8 +3275,8 @@ static void ShowDemoWindowMultiSelect() { ImGui::PushID(selection_scope_n); ImGuiSelectionBasicStorage* selection = &selections_data[selection_scope_n]; - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection->Size); - selection->ApplyRequests(ms_io, ITEMS_COUNT); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection->Size, ITEMS_COUNT); + selection->ApplyRequests(ms_io); ImGui::SeparatorText("Selection scope"); ImGui::Text("Selection size: %d/%d", selection->Size, ITEMS_COUNT); @@ -3292,7 +3292,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection->ApplyRequests(ms_io, ITEMS_COUNT); + selection->ApplyRequests(ms_io); ImGui::PopID(); } ImGui::TreePop(); @@ -3375,8 +3375,8 @@ static void ShowDemoWindowMultiSelect() if (widget_type == WidgetType_TreeNode) ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size); - selection.ApplyRequests(ms_io, items.Size); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size); + selection.ApplyRequests(ms_io); const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0)) || request_deletion_from_menu; const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1; @@ -3520,7 +3520,7 @@ static void ShowDemoWindowMultiSelect() // Apply multi-select requests ms_io = ImGui::EndMultiSelect(); - selection.ApplyRequests(ms_io, items.Size); + selection.ApplyRequests(ms_io); if (want_delete) selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus); @@ -9846,12 +9846,12 @@ struct ExampleAssetsBrowser ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. if (AllowBoxSelect) ms_flags |= ImGuiMultiSelectFlags_BoxSelect; // Enable box-select in 2D mode. - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size, Items.Size); // Use custom selection adapter: store ID in selection (recommended) Selection.UserData = this; Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->UserData; return self->Items[idx].ID; }; - Selection.ApplyRequests(ms_io, Items.Size); + Selection.ApplyRequests(ms_io); const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (Selection.Size > 0)) || RequestDelete; const int item_curr_idx_to_focus = want_delete ? Selection.ApplyDeletionPreLoop(ms_io, Items.Size) : -1; @@ -9959,7 +9959,7 @@ struct ExampleAssetsBrowser } ms_io = ImGui::EndMultiSelect(); - Selection.ApplyRequests(ms_io, Items.Size); + Selection.ApplyRequests(ms_io); if (want_delete) Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b60e73a49..67ccebeae 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7300,10 +7300,13 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe // Return ImGuiMultiSelectIO structure. // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). -// Passing 'current_selection_size' is currently optional: -// - it is useful for shortcut routing with ImGuiMultiSelectFlags_ClearOnEscape: so we can have Escape be used to clear selection THEN to exit child window. -// - if it is costly for you to compute, but can easily tell if your selection is empty or not, you may pass 1, or use the ImGuiMultiSelectFlags_ClearOnEscape flag dynamically. -ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int current_selection_size) +// Passing 'selection_size' and 'items_count' parameters is currently optional. +// - 'selection_size' is useful to disable some shortcut routing: e.g. ImGuiMultiSelectFlags_ClearOnEscape won't claim Escape key when selection_size 0, +// allowing a first press to clear selection THEN the second press to leave child window and return to parent. +// - 'items_count' is stored in ImGuiMultiSelectIO which makes it a convenient way to pass the information to your ApplyRequest() handler (but you may pass it differently). +// - If they are costly for you to compute (e.g. external intrusive selection without maintaining size), you may avoid them and pass -1. +// - If you can easily tell if your selection is empty or not, you may pass 0/1, or you may enable ImGuiMultiSelectFlags_ClearOnEscape flag dynamically. +ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size, int items_count) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -7341,15 +7344,16 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur ImGuiMultiSelectState* storage = g.MultiSelectStorage.GetOrAddByKey(id); storage->ID = id; storage->LastFrameActive = g.FrameCount; - storage->LastSelectionSize = current_selection_size; + storage->LastSelectionSize = selection_size; storage->Window = window; ms->Storage = storage; // Output to user + ms->IO.Requests.resize(0); ms->IO.RangeSrcItem = storage->RangeSrcItem; ms->IO.NavIdItem = storage->NavIdItem; ms->IO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false; - ms->IO.Requests.resize(0); + ms->IO.ItemsCount = items_count; // Clear when using Navigation to move within the scope // (we compare FocusScopeId so it possible to use multiple selections inside a same window) @@ -7375,7 +7379,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int cur { // Shortcut: Clear selection (Escape) // Only claim shortcut if selection is not empty, allowing further presses on Escape to e.g. leave current child window. - if ((flags & ImGuiMultiSelectFlags_ClearOnEscape) && (current_selection_size != 0)) + if ((flags & ImGuiMultiSelectFlags_ClearOnEscape) && (selection_size != 0)) if (Shortcut(ImGuiKey_Escape)) request_clear = true; @@ -7826,17 +7830,22 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) // if (req.Type == ImGuiSelectionRequestType_SetAll) { Clear(); if (req.Selected) { for (int n = 0; n < items_count; n++) { AddItem(n); } } // if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->Selected); } } // } -void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io, int items_count) +void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) { + // For convenience we obtain ItemsCount as passed to BeginMultiSelect(), which is optional. + // It makes sense when using ImGuiSelectionBasicStorage to simply pass your items count to BeginMultiSelect(). + // Other scheme may handle SetAll differently. + IM_ASSERT(ms_io->ItemsCount != -1 && "Missing value for items_count in BeginMultiSelect() call!"); IM_ASSERT(AdapterIndexToStorageId != NULL); + for (ImGuiSelectionRequest& req : ms_io->Requests) { if (req.Type == ImGuiSelectionRequestType_SetAll) Clear(); if (req.Type == ImGuiSelectionRequestType_SetAll && req.Selected) { - Storage.Data.reserve(items_count); - for (int idx = 0; idx < items_count; idx++) + Storage.Data.reserve(ms_io->ItemsCount); + for (int idx = 0; idx < ms_io->ItemsCount; idx++) SetItemSelected(AdapterIndexToStorageId(this, idx), true); } if (req.Type == ImGuiSelectionRequestType_SetRange) From c94cf6f01fe85f475a6a02206b772743a856a55e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Jun 2024 17:16:06 +0200 Subject: [PATCH 0208/2359] MultiSelect: added ImGuiSelectionBasicStorage::GetStorageIdFromIndex() indirection to be easier on the reader. Tempting to make it a virtual. --- imgui.h | 5 +++-- imgui_demo.cpp | 8 ++++---- imgui_widgets.cpp | 4 ++-- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index e358e1aeb..9f441ed09 100644 --- a/imgui.h +++ b/imgui.h @@ -2823,7 +2823,7 @@ struct ImGuiSelectionRequest // Optional helper to store multi-selection state + apply multi-selection requests. // - Used by our demos and provided as a convenience to easily implement basic multi-selection. -// - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. Advanced users are likely to implement their own. +// - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. // To store a multi-selection, in your application you could: // - A) Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. // - B) Use your own external storage: e.g. std::set, std::vector, interval trees, etc. @@ -2845,7 +2845,7 @@ struct ImGuiSelectionBasicStorage // Members ImGuiStorage Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. - ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->AdapterData)[idx]->ID; }; + ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. Uses 'items_count' based to BeginMultiSelect() @@ -2857,6 +2857,7 @@ struct ImGuiSelectionBasicStorage void Swap(ImGuiSelectionBasicStorage& r) { Storage.Data.swap(r.Storage.Data); } bool Contains(ImGuiID id) const { return Storage.GetInt(id, 0) != 0; } void SetItemSelected(ImGuiID id, bool v) { int* p_int = Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } + ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7d4f04cdf..b3dc5ef54 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2798,12 +2798,12 @@ struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage // If focused item is selected: land on first unselected item after focused item. for (int idx = focused_idx + 1; idx < items_count; idx++) - if (!Contains(AdapterIndexToStorageId(this, idx))) + if (!Contains(GetStorageIdFromIndex(idx))) return idx; // If focused item is selected: otherwise return last unselected item before focused item. for (int idx = IM_MIN(focused_idx, items_count) - 1; idx >= 0; idx--) - if (!Contains(AdapterIndexToStorageId(this, idx))) + if (!Contains(GetStorageIdFromIndex(idx))) return idx; return -1; @@ -2822,7 +2822,7 @@ struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage int item_next_idx_to_select = -1; for (int idx = 0; idx < items.Size; idx++) { - if (!Contains(AdapterIndexToStorageId(this, idx))) + if (!Contains(GetStorageIdFromIndex(idx))) new_items.push_back(items[idx]); if (item_curr_idx_to_select == idx) item_next_idx_to_select = new_items.Size - 1; @@ -2832,7 +2832,7 @@ struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage // Update selection Clear(); if (item_next_idx_to_select != -1 && ms_io->NavIdSelected) - SetItemSelected(AdapterIndexToStorageId(this, item_next_idx_to_select), true); + SetItemSelected(GetStorageIdFromIndex(item_next_idx_to_select), true); } }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 67ccebeae..1ebabe4d1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7846,11 +7846,11 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) { Storage.Data.reserve(ms_io->ItemsCount); for (int idx = 0; idx < ms_io->ItemsCount; idx++) - SetItemSelected(AdapterIndexToStorageId(this, idx), true); + SetItemSelected(GetStorageIdFromIndex(idx), true); } if (req.Type == ImGuiSelectionRequestType_SetRange) for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) - SetItemSelected(AdapterIndexToStorageId(this, idx), req.Selected); + SetItemSelected(GetStorageIdFromIndex(idx), req.Selected); } } From f9caf4447a65b3a686051e0c449fc4b3b93a4ae5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Jun 2024 18:32:59 +0200 Subject: [PATCH 0209/2359] MultiSelect: fixed ImGuiSelectionBasicStorage::Swap() helper. --- imgui.h | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/imgui.h b/imgui.h index 9f441ed09..c0c2d0b2c 100644 --- a/imgui.h +++ b/imgui.h @@ -44,7 +44,7 @@ Index of this file: // [SECTION] ImGuiIO // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO, ImGuiSelectionBasicStorage) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) @@ -2817,8 +2817,8 @@ struct ImGuiSelectionRequest //------------------------------------------// BeginMultiSelect / EndMultiSelect ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. bool Selected; // ms:w, app:r / ms:w, app:r // Parameter for SetAll/SetRange requests (true = select, false = unselect) - ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom) - ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top) + ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom). + ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top). Inclusive! }; // Optional helper to store multi-selection state + apply multi-selection requests. @@ -2848,16 +2848,16 @@ struct ImGuiSelectionBasicStorage ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; - // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. Uses 'items_count' based to BeginMultiSelect() - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); + // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. Uses 'items_count' passed to BeginMultiSelect() + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Methods: selection storage - ImGuiSelectionBasicStorage() { Clear(); UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } - void Clear() { Storage.Data.resize(0); Size = 0; } - void Swap(ImGuiSelectionBasicStorage& r) { Storage.Data.swap(r.Storage.Data); } - bool Contains(ImGuiID id) const { return Storage.GetInt(id, 0) != 0; } - void SetItemSelected(ImGuiID id, bool v) { int* p_int = Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } - ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } + ImGuiSelectionBasicStorage() { Clear(); UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } + void Clear() { Storage.Data.resize(0); Size = 0; } + void Swap(ImGuiSelectionBasicStorage& r) { Storage.Data.swap(r.Storage.Data); int lhs_size = Size; Size = r.Size; r.Size = lhs_size; } + bool Contains(ImGuiID id) const { return Storage.GetInt(id, 0) != 0; } + void SetItemSelected(ImGuiID id, bool v) { int* p_int = Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } + ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } }; //----------------------------------------------------------------------------- From db4898cb913552af14b37099ab06b60eb17a8149 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Jun 2024 19:00:13 +0200 Subject: [PATCH 0210/2359] MultiSelect: added ImGuiSelectionExternalStorage helper. Simplify bool demo. --- imgui.h | 16 +++++++++++++++- imgui_demo.cpp | 29 ++++++++--------------------- imgui_widgets.cpp | 16 ++++++++++++++++ 3 files changed, 39 insertions(+), 22 deletions(-) diff --git a/imgui.h b/imgui.h index c0c2d0b2c..050c8bb06 100644 --- a/imgui.h +++ b/imgui.h @@ -44,7 +44,7 @@ Index of this file: // [SECTION] ImGuiIO // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage) +// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) @@ -180,6 +180,7 @@ struct ImGuiOnceUponAFrame; // Helper for running a block of code not mo struct ImGuiPayload; // User data payload for drag and drop operations struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. struct ImGuiSelectionBasicStorage; // Optional helper to store multi-selection state + apply multi-selection requests. +struct ImGuiSelectionExternalStorage;//Optional helper to apply multi-selection requests to existing randomly accessible storage. struct ImGuiSelectionRequest; // A selection request (stored in ImGuiMultiSelectIO) struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) struct ImGuiStorage; // Helper for key->value storage (container sorted by key) @@ -2860,6 +2861,19 @@ struct ImGuiSelectionBasicStorage ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } }; +// Optional helper to apply multi-selection requests to existing randomly accessible storage. +// Convenient if you want to quickly wire multi-select API on e.g. an array of bool or items storing their own selection state. +struct ImGuiSelectionExternalStorage +{ + // Members + void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); // e.g. AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int idx, bool selected) { ((MyItems**)self->UserData)[idx]->Selected = selected; } + void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; + + // Methods + ImGuiSelectionExternalStorage() { memset(this, 0, sizeof(*this)); } + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Generic function, using AdapterSetItemSelected() +}; + //----------------------------------------------------------------------------- // [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b3dc5ef54..3cd2046a1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3212,41 +3212,28 @@ static void ShowDemoWindowMultiSelect() ImGui::BulletText("Shift+Keyboard to copy current value to other boxes."); // If you have an array of checkboxes, you may want to use NoAutoSelect + NoAutoClear and the ImGuiSelectionExternalStorage helper. - static bool values[20] = {}; + static bool items[20] = {}; static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_ClearOnEscape; ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); // Cannot use ImGuiMultiSelectFlags_BoxSelect1d as checkboxes are varying width. - struct Funcs - { - static void ApplyMultiSelectRequestsToBoolArray(ImGuiMultiSelectIO* ms_io, bool items[], int items_count) - { - for (ImGuiSelectionRequest& req : ms_io->Requests) - { - if (req.Type == ImGuiSelectionRequestType_SetAll) - for (int n = 0; n < items_count; n++) - items[n] = req.Selected; - else if (req.Type == ImGuiSelectionRequestType_SetRange) - for (int n = (int)req.RangeFirstItem; n <= (int)req.RangeLastItem; n++) - items[n] = req.Selected; - } - } - }; - if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_Border | ImGuiChildFlags_ResizeY)) { - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags); - Funcs::ApplyMultiSelectRequestsToBoolArray(ms_io, values, IM_ARRAYSIZE(values)); //// By specs, it could be optional to apply requests from BeginMultiSelect() if not using a clipper. + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, -1, IM_ARRAYSIZE(items)); + ImGuiSelectionExternalStorage storage_wrapper; + storage_wrapper.UserData = (void*)items; + storage_wrapper.AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int n, bool selected) { bool* array = (bool*)self->UserData; array[n] = selected; }; + storage_wrapper.ApplyRequests(ms_io); for (int n = 0; n < 20; n++) { char label[32]; sprintf(label, "Item %d", n); ImGui::SetNextItemSelectionUserData(n); - ImGui::Checkbox(label, &values[n]); + ImGui::Checkbox(label, &items[n]); } ms_io = ImGui::EndMultiSelect(); - Funcs::ApplyMultiSelectRequestsToBoolArray(ms_io, values, IM_ARRAYSIZE(values)); + storage_wrapper.ApplyRequests(ms_io); } ImGui::EndChild(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1ebabe4d1..c85b6ff9a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7854,6 +7854,22 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) } } +// Apply requests coming from BeginMultiSelect() and EndMultiSelect(). +// We also pull 'ms_io->ItemsCount' as passed for BeginMultiSelect() for consistency with ImGuiSelectionBasicStorage +// This makes no assumption about underlying storage. +void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) +{ + IM_ASSERT(AdapterSetItemSelected); + for (ImGuiSelectionRequest& req : ms_io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_SetAll) + for (int idx = 0; idx < ms_io->ItemsCount; idx++) + AdapterSetItemSelected(this, idx, req.Selected); + if (req.Type == ImGuiSelectionRequestType_SetRange) + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) + AdapterSetItemSelected(this, idx, req.Selected); + } +} //------------------------------------------------------------------------- // [SECTION] Widgets: ListBox From c3d7aa252b39a5a4a61c02b99dd5bc5e6b7fdf1f Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Jun 2024 14:40:57 +0200 Subject: [PATCH 0211/2359] MultiSelect: comments, header tweaks., simplication (some of it on wiki). --- imgui.h | 49 +++++++++++++++++------------------------------ imgui_widgets.cpp | 27 +++++++++++++++++--------- 2 files changed, 36 insertions(+), 40 deletions(-) diff --git a/imgui.h b/imgui.h index 050c8bb06..bfaa0182e 100644 --- a/imgui.h +++ b/imgui.h @@ -2730,18 +2730,17 @@ struct ImColor #define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. // Multi-selection system -// Also read: https://github.com/ocornut/imgui/wiki/Multi-Select +// Documentation at: https://github.com/ocornut/imgui/wiki/Multi-Select // - Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos using this. // - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) // with support for clipper (skipping non-visible items), box-select and many other details. -// - TreeNode() and Selectable() are supported but custom widgets may use it as well. +// - TreeNode(), Selectable(), Checkbox() are supported but custom widgets may use it as well. // - In the spirit of Dear ImGui design, your code owns actual selection data. // This is designed to allow all kinds of selection storage you may use in your application e.g. set/map/hash. -// - The work involved to deal with multi-selection differs whether you want to only submit visible items and -// clip others, or submit all items regardless of their visibility. Clipping items is more efficient and will -// allow you to deal with large lists (1k~100k items). See "Usage flow" section below for details. -// If you are not sure, always start without clipping! You can work your way to the optimized version afterwards. -// TL;DR; +// About ImGuiSelectionBasicStorage: +// - This is an optional helper to store a selection state and apply selection requests. +// - It is used by our demos and provided as a convenience to quickly implement multi-selection. +// Usage: // - Identify submitted items with SetNextItemSelectionUserData(), most likely using an index into your current data-set. // - Store and maintain actual selection data using persistent object identifiers. // - Usage flow: @@ -2753,20 +2752,14 @@ struct ImColor // - (6) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 2. // If you submit all items (no clipper), Step 2 and 3 are optional and will be handled by each item themselves. It is fine to always honor those steps. // About ImGuiSelectionUserData: -// - For each item is it submitted by your call to SetNextItemSelectionUserData(). -// - This can store an application-defined identifier (e.g. index or pointer). +// - This can store an application-defined identifier (e.g. index or pointer) submitted via SetNextItemSelectionUserData(). // - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. -// - Most applications will store an object INDEX, hence the chosen name and type. -// Storing an integer index is the easiest thing to do, as SetRange requests will give you two end-points -// and you will need to iterate/interpolate between them to update your selection. -// - However it is perfectly possible to store a POINTER or another IDENTIFIER inside this value! +// - Most applications will store an object INDEX, hence the chosen name and type. Storing an index is natural, because +// SetRange requests will give you two end-points and you will need to iterate/interpolate between them to update your selection. +// - However it is perfectly possible to store a POINTER or another IDENTIFIER inside ImGuiSelectionUserData. // Our system never assume that you identify items by indices, it never attempts to interpolate between two values. // - As most users will want to store an index, for convenience and to reduce confusion we use ImS64 instead of void*, // being syntactically easier to downcast. Feel free to reinterpret_cast and store a pointer inside. -// - If you need to wrap this API for another language/framework, feel free to expose this as 'int' if simpler. -// About ImGuiSelectionBasicStorage: -// - This is an optional helper to store a selection state and apply selection requests. -// - It is used by our demos and provided as a convenience if you want to quickly implement multi-selection. // Flags for BeginMultiSelect() enum ImGuiMultiSelectFlags_ @@ -2774,7 +2767,7 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to select all. - ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+Click/Shift+Keyboard handling (useful for unordered 2D selection). + ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing other items when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_BoxSelect = 1 << 5, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. @@ -2828,32 +2821,26 @@ struct ImGuiSelectionRequest // To store a multi-selection, in your application you could: // - A) Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. // - B) Use your own external storage: e.g. std::set, std::vector, interval trees, etc. -// - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside objects). Doing that, you can't have multiple views over -// your objects. Also, some features requires to provide selection _size_, which with this strategy requires additional work. +// - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside objects). Cannot have multiple views over same objects. // In ImGuiSelectionBasicStorage we: // - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) -// - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index, -// so this helper can be used regardless of your object storage/types (it is analogous to using a virtual function): -// - in some cases we read an ID from some custom item data structure (similar to what you would do in your codebase) -// - in some cases we use Index as custom identifier (default implementation returns Index cast as Identifier): only OK for a never changing item list. +// - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index. // Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. // Large applications are likely to eventually want to get rid of this indirection layer and do their own thing. -// See https://github.com/ocornut/imgui/wiki/Multi-Select for minimum pseudo-code example using this helper. -// (In theory, for maximum abstraction, this class could contains AdapterIndexToUserData() and AdapterUserDataToIndex() functions as well, -// but because we always use indices in SetNextItemSelectionUserData() in the demo, we omit that indirection for clarity.) +// See https://github.com/ocornut/imgui/wiki/Multi-Select for details and pseudo-code using this helper. struct ImGuiSelectionBasicStorage { // Members ImGuiStorage Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. - ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; + ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. Uses 'items_count' passed to BeginMultiSelect() IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Methods: selection storage - ImGuiSelectionBasicStorage() { Clear(); UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } + ImGuiSelectionBasicStorage() { Size = 0; UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } void Clear() { Storage.Data.resize(0); Size = 0; } void Swap(ImGuiSelectionBasicStorage& r) { Storage.Data.swap(r.Storage.Data); int lhs_size = Size; Size = r.Size; r.Size = lhs_size; } bool Contains(ImGuiID id) const { return Storage.GetInt(id, 0) != 0; } @@ -2866,11 +2853,11 @@ struct ImGuiSelectionBasicStorage struct ImGuiSelectionExternalStorage { // Members - void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); // e.g. AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int idx, bool selected) { ((MyItems**)self->UserData)[idx]->Selected = selected; } void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; + void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); // e.g. AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int idx, bool selected) { ((MyItems**)self->UserData)[idx]->Selected = selected; } // Methods - ImGuiSelectionExternalStorage() { memset(this, 0, sizeof(*this)); } + ImGuiSelectionExternalStorage() { UserData = NULL; AdapterSetItemSelected = NULL; } IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Generic function, using AdapterSetItemSelected() }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c85b6ff9a..be02fe140 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -21,6 +21,7 @@ Index of this file: // [SECTION] Widgets: Typing-Select support // [SECTION] Widgets: Box-Select support // [SECTION] Widgets: Multi-Select support +// [SECTION] Widgets: Multi-Select helpers // [SECTION] Widgets: ListBox // [SECTION] Widgets: PlotLines, PlotHistogram // [SECTION] Widgets: Value helpers @@ -7285,7 +7286,6 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, bool enable_scroll) // - MultiSelectItemHeader() [Internal] // - MultiSelectItemFooter() [Internal] // - DebugNodeMultiSelectState() [Internal] -// - ImGuiSelectionBasicStorage //------------------------------------------------------------------------- static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io) @@ -7814,6 +7814,13 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) #endif } +//------------------------------------------------------------------------- +// [SECTION] Widgets: Multi-Select helpers +//------------------------------------------------------------------------- +// - ImGuiSelectionBasicStorage +// - ImGuiSelectionExternalStorage +//------------------------------------------------------------------------- + // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). // - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. // - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. @@ -7827,8 +7834,8 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) // The most simple implementation (using indices everywhere) would look like: // for (ImGuiSelectionRequest& req : ms_io->Requests) // { -// if (req.Type == ImGuiSelectionRequestType_SetAll) { Clear(); if (req.Selected) { for (int n = 0; n < items_count; n++) { AddItem(n); } } -// if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { UpdateItem(n, ms_io->Selected); } } +// if (req.Type == ImGuiSelectionRequestType_SetAll) { Clear(); if (req.Selected) { for (int n = 0; n < items_count; n++) { SetItemSelected(n, true); } } +// if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { SetItemSelected(n, ms_io->Selected); } } // } void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) { @@ -7841,14 +7848,16 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) for (ImGuiSelectionRequest& req : ms_io->Requests) { if (req.Type == ImGuiSelectionRequestType_SetAll) - Clear(); - if (req.Type == ImGuiSelectionRequestType_SetAll && req.Selected) { - Storage.Data.reserve(ms_io->ItemsCount); - for (int idx = 0; idx < ms_io->ItemsCount; idx++) - SetItemSelected(GetStorageIdFromIndex(idx), true); + Clear(); + if (req.Selected) + { + Storage.Data.reserve(ms_io->ItemsCount); + for (int idx = 0; idx < ms_io->ItemsCount; idx++) + SetItemSelected(GetStorageIdFromIndex(idx), true); + } } - if (req.Type == ImGuiSelectionRequestType_SetRange) + else if (req.Type == ImGuiSelectionRequestType_SetRange) for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) SetItemSelected(GetStorageIdFromIndex(idx), req.Selected); } From e1fd25051e1c4d4fef53eca80412668505a6908f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Jun 2024 17:14:00 +0200 Subject: [PATCH 0212/2359] MultiSelect: ImGuiSelectionBasicStorage: added GetNextSelectedItem() to abstract selection storage from user. Amend Assets Browser demo to handle drag and drop correctly. --- imgui.h | 34 +++++++++++++++++++--------------- imgui_demo.cpp | 31 ++++++++++++++++++++++--------- imgui_widgets.cpp | 21 ++++++++++++++++++++- 3 files changed, 61 insertions(+), 25 deletions(-) diff --git a/imgui.h b/imgui.h index bfaa0182e..93ecaf77b 100644 --- a/imgui.h +++ b/imgui.h @@ -2817,35 +2817,39 @@ struct ImGuiSelectionRequest // Optional helper to store multi-selection state + apply multi-selection requests. // - Used by our demos and provided as a convenience to easily implement basic multi-selection. +// - Iterate selection with 'void* it = NULL; while (ImGuiId id = selection.GetNextSelectedItem(&it)) { ... }' +// Or you can check 'if (Contains(id)) { ... }' for each possible object if their number is not too high to iterate. // - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. // To store a multi-selection, in your application you could: -// - A) Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. -// - B) Use your own external storage: e.g. std::set, std::vector, interval trees, etc. -// - C) Use intrusively stored selection (e.g. 'bool IsSelected' inside objects). Cannot have multiple views over same objects. +// - Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. +// - Use your own external storage: e.g. std::set, std::vector, interval trees, intrusively stored selection etc. // In ImGuiSelectionBasicStorage we: // - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) // - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index. +// - use decently optimized logic to allow queries and insertion of very large selection sets. +// - do not preserve selection order. // Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. // Large applications are likely to eventually want to get rid of this indirection layer and do their own thing. // See https://github.com/ocornut/imgui/wiki/Multi-Select for details and pseudo-code using this helper. struct ImGuiSelectionBasicStorage { // Members - ImGuiStorage Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set + ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; - // Methods: apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. Uses 'items_count' passed to BeginMultiSelect() - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); + // Methods + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io);// Apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. It uses 'items_count' passed to BeginMultiSelect() + IMGUI_API ImGuiID GetNextSelectedItem(void** opaque_it); // Iterate selection with 'void* it = NULL; while (ImGuiId id = selection.GetNextSelectedItem(&it)) { ... }' + bool Contains(ImGuiID id) const { return _Storage.GetInt(id, 0) != 0; } // Query if an item id is in selection. + ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } // Convert index to item id based on provided adapter. - // Methods: selection storage - ImGuiSelectionBasicStorage() { Size = 0; UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } - void Clear() { Storage.Data.resize(0); Size = 0; } - void Swap(ImGuiSelectionBasicStorage& r) { Storage.Data.swap(r.Storage.Data); int lhs_size = Size; Size = r.Size; r.Size = lhs_size; } - bool Contains(ImGuiID id) const { return Storage.GetInt(id, 0) != 0; } - void SetItemSelected(ImGuiID id, bool v) { int* p_int = Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } - ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } + // [Internal, rarely called directly by end-user] + ImGuiSelectionBasicStorage() { Size = 0; UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } + void Clear() { _Storage.Data.resize(0); Size = 0; } + void Swap(ImGuiSelectionBasicStorage& r) { _Storage.Data.swap(r._Storage.Data); int lhs_size = Size; Size = r.Size; r.Size = lhs_size; } + void SetItemSelected(ImGuiID id, bool v) { int* p_int = _Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } }; // Optional helper to apply multi-selection requests to existing randomly accessible storage. @@ -2857,8 +2861,8 @@ struct ImGuiSelectionExternalStorage void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); // e.g. AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int idx, bool selected) { ((MyItems**)self->UserData)[idx]->Selected = selected; } // Methods - ImGuiSelectionExternalStorage() { UserData = NULL; AdapterSetItemSelected = NULL; } - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Generic function, using AdapterSetItemSelected() + ImGuiSelectionExternalStorage() { UserData = NULL; AdapterSetItemSelected = NULL; } + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Generic function, using AdapterSetItemSelected() }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3cd2046a1..d5ff2972d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3441,24 +3441,24 @@ static void ShowDemoWindowMultiSelect() // Drag and Drop if (use_drag_drop && ImGui::BeginDragDropSource()) { - // Consider payload to be full selection OR single unselected item. + // Create payload with full selection OR single unselected item. // (the later is only possible when using ImGuiMultiSelectFlags_SelectOnClickRelease) if (ImGui::GetDragDropPayload() == NULL) { ImVector payload_items; + void* it = NULL; if (!item_is_selected) payload_items.push_back(item_id); else - for (const ImGuiStoragePair& pair : selection.Storage.Data) - if (pair.val_i) - payload_items.push_back((int)pair.key); + while (int id = (int)selection.GetNextSelectedItem(&it)) + payload_items.push_back(id); ImGui::SetDragDropPayload("MULTISELECT_DEMO_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes()); } // Display payload content in tooltip const ImGuiPayload* payload = ImGui::GetDragDropPayload(); const int* payload_items = (int*)payload->Data; - const int payload_count = (int)payload->DataSize / (int)sizeof(payload_items[0]); + const int payload_count = (int)payload->DataSize / (int)sizeof(int); if (payload_count == 1) ImGui::Text("Object %05d: %s", payload_items[0], ExampleNames[payload_items[0] % IM_ARRAYSIZE(ExampleNames)]); else @@ -9896,13 +9896,26 @@ struct ExampleAssetsBrowser // Drag and drop if (ImGui::BeginDragDropSource()) { - // Consider payload to be full selection OR single unselected item + // Create payload with full selection OR single unselected item. // (the later is only possible when using ImGuiMultiSelectFlags_SelectOnClickRelease) - int payload_size = item_is_selected ? Selection.Size : 1; if (ImGui::GetDragDropPayload() == NULL) - ImGui::SetDragDropPayload("ASSETS_BROWSER_ITEMS", "Dummy", 5); // Dummy payload + { + ImVector payload_items; + void* it = NULL; + if (!item_is_selected) + payload_items.push_back(item_data->ID); + else + while (ImGuiID id = Selection.GetNextSelectedItem(&it)) + payload_items.push_back(id); + ImGui::SetDragDropPayload("ASSETS_BROWSER_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes()); + } + + // Display payload content in tooltip, by extracting it from the payload data + // (we could read from selection, but it is more correct and reusable to read from payload) + const ImGuiPayload* payload = ImGui::GetDragDropPayload(); + const int payload_count = (int)payload->DataSize / (int)sizeof(ImGuiID); + ImGui::Text("%d assets", payload_count); - ImGui::Text("%d assets", payload_size); ImGui::EndDragDropSource(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index be02fe140..bf9c9139a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7821,6 +7821,23 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) // - ImGuiSelectionExternalStorage //------------------------------------------------------------------------- +// GetNextSelectedItem() is an abstraction allowing us to change our underlying actual storage system without impacting user. +// (e.g. store unselected vs compact down, compact down on demand, use raw ImVector instead of ImGuiStorage...) +ImGuiID ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it) +{ + ImGuiStoragePair* it = (ImGuiStoragePair*)*opaque_it; + ImGuiStoragePair* it_end = _Storage.Data.Data + _Storage.Data.Size; + if (it == NULL) + it = _Storage.Data.Data; + IM_ASSERT(it >= _Storage.Data.Data && it <= it_end); + if (it != it_end) + 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); + return has_more ? it->key : 0; +} + // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). // - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. // - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. @@ -7852,7 +7869,7 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) Clear(); if (req.Selected) { - Storage.Data.reserve(ms_io->ItemsCount); + _Storage.Data.reserve(ms_io->ItemsCount); for (int idx = 0; idx < ms_io->ItemsCount; idx++) SetItemSelected(GetStorageIdFromIndex(idx), true); } @@ -7863,6 +7880,8 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) } } +//------------------------------------------------------------------------- + // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). // We also pull 'ms_io->ItemsCount' as passed for BeginMultiSelect() for consistency with ImGuiSelectionBasicStorage // This makes no assumption about underlying storage. From e61612a6873788c9237c076c480b6182dc0e1547 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Jun 2024 18:26:22 +0200 Subject: [PATCH 0213/2359] MultiSelect: ImGuiSelectionBasicStorage: rework to accept massive selections requests without flinching. Batch modification + storage only keeps selected items. --- imgui.h | 4 +-- imgui_widgets.cpp | 71 +++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 93ecaf77b..a4162b886 100644 --- a/imgui.h +++ b/imgui.h @@ -2835,7 +2835,7 @@ struct ImGuiSelectionBasicStorage { // Members ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). - int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. + int Size; // Number of selected items, maintained by this helper. void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; @@ -2849,7 +2849,7 @@ struct ImGuiSelectionBasicStorage ImGuiSelectionBasicStorage() { Size = 0; UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } void Clear() { _Storage.Data.resize(0); Size = 0; } void Swap(ImGuiSelectionBasicStorage& r) { _Storage.Data.swap(r._Storage.Data); int lhs_size = Size; Size = r.Size; r.Size = lhs_size; } - void SetItemSelected(ImGuiID id, bool v) { int* p_int = _Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } + IMGUI_API void SetItemSelected(ImGuiID id, bool selected); }; // Optional helper to apply multi-selection requests to existing randomly accessible storage. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bf9c9139a..82d90c1b2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7830,14 +7830,65 @@ ImGuiID ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it) if (it == NULL) it = _Storage.Data.Data; IM_ASSERT(it >= _Storage.Data.Data && it <= it_end); - if (it != it_end) - 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); return has_more ? it->key : 0; } +// Basic function to update selection (for very large amounts of changes, see what ApplyRequests is doing) +void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected) +{ + ImGuiStoragePair* it = ImLowerBound(_Storage.Data.Data, _Storage.Data.Data + _Storage.Data.Size, id); + if (selected == (it != _Storage.Data.Data + _Storage.Data.Size) && (it->key == id)) + return; + if (selected) + _Storage.Data.insert(it, ImGuiStoragePair(id, 1)); + else + _Storage.Data.erase(it); + Size = _Storage.Data.Size; +} + +// Optimized for batch edits (with same value of 'selected') +static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends) +{ + ImGuiStorage* storage = &selection->_Storage; + ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id); + if (selected == (it != storage->Data.Data + size_before_amends) && (it->key == id)) + return; + if (selected) + storage->Data.push_back(ImGuiStoragePair(id, 1)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish() + else + it->val_i = 0; // Clear in-place, will be removed in SelectionMultiAmendsFinish() + selection->Size += selected ? +1 : -1; +} + +static void ImGuiSelectionBasicStorage_Compact(ImGuiSelectionBasicStorage* selection) +{ + ImGuiStorage* storage = &selection->_Storage; + ImGuiStoragePair* p_out = storage->Data.Data; + ImGuiStoragePair* p_end = storage->Data.Data + storage->Data.Size; + for (ImGuiStoragePair* p_in = p_out; p_in < p_end; p_in++) + if (p_in->val_i != 0) + { + if (p_out != p_in) + *p_out = *p_in; + p_out++; + } + storage->Data.Size = (int)(p_out - storage->Data.Data); +} + +static void ImGuiSelectionBasicStorage_BatchFinish(ImGuiSelectionBasicStorage* selection, bool selected, int size_before_amends) +{ + ImGuiStorage* storage = &selection->_Storage; + if (selection->Size == size_before_amends) + return; + if (selected) + storage->BuildSortByKey(); // When done selecting: sort everything + else + ImGuiSelectionBasicStorage_Compact(selection); // When done unselecting: compact by removing all zero values (might be done lazily when iterating selection?) + IM_ASSERT(selection->Size == storage->Data.Size); +} + // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). // - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen. // - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem. @@ -7862,6 +7913,10 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) IM_ASSERT(ms_io->ItemsCount != -1 && "Missing value for items_count in BeginMultiSelect() call!"); IM_ASSERT(AdapterIndexToStorageId != NULL); + // This is optimized/specialized to cope nicely with very large selections (e.g. 1 million items) + // - A simpler version could call SetItemSelected() directly instead of ImGuiSelectionBasicStorage_BatchSetItemSelected() + ImGuiSelectionBasicStorage_BatchFinish(). + // - Optimized select can append unsorted, then sort in a second pass. Optimized unselect can clear in-place then compact in a second pass. + // - (A more optimal version wouldn't even use ImGuiStorage but directly a ImVector to reduce bandwidth, but this is a reasonable trade off to reuse code) for (ImGuiSelectionRequest& req : ms_io->Requests) { if (req.Type == ImGuiSelectionRequestType_SetAll) @@ -7870,13 +7925,19 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) if (req.Selected) { _Storage.Data.reserve(ms_io->ItemsCount); + const int size_before_amends = _Storage.Data.Size; for (int idx = 0; idx < ms_io->ItemsCount; idx++) - SetItemSelected(GetStorageIdFromIndex(idx), true); + ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends); + ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends); } } else if (req.Type == ImGuiSelectionRequestType_SetRange) + { + const int size_before_amends = _Storage.Data.Size; for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) - SetItemSelected(GetStorageIdFromIndex(idx), req.Selected); + ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends); + ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends); + } } } From 2af3b2ac81578b3e586e8de577910df495bc3e7c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Jun 2024 18:50:30 +0200 Subject: [PATCH 0214/2359] MultiSelect: ImGuiSelectionBasicStorage: simplify by removing compacting code (compacting may be opt-in?). GetNextSelectedItem() wrapper gives us more flexibility to work on this kind of stuff now. --- imgui.h | 4 ++-- imgui_widgets.cpp | 47 +++++++++-------------------------------------- 2 files changed, 11 insertions(+), 40 deletions(-) diff --git a/imgui.h b/imgui.h index a4162b886..93ecaf77b 100644 --- a/imgui.h +++ b/imgui.h @@ -2835,7 +2835,7 @@ struct ImGuiSelectionBasicStorage { // Members ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). - int Size; // Number of selected items, maintained by this helper. + int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; @@ -2849,7 +2849,7 @@ struct ImGuiSelectionBasicStorage ImGuiSelectionBasicStorage() { Size = 0; UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } void Clear() { _Storage.Data.resize(0); Size = 0; } void Swap(ImGuiSelectionBasicStorage& r) { _Storage.Data.swap(r._Storage.Data); int lhs_size = Size; Size = r.Size; r.Size = lhs_size; } - IMGUI_API void SetItemSelected(ImGuiID id, bool selected); + void SetItemSelected(ImGuiID id, bool v) { int* p_int = _Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } }; // Optional helper to apply multi-selection requests to existing randomly accessible storage. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 82d90c1b2..bcfa92194 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7830,63 +7830,34 @@ ImGuiID ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it) if (it == NULL) it = _Storage.Data.Data; IM_ASSERT(it >= _Storage.Data.Data && it <= it_end); + if (it != it_end) + 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); return has_more ? it->key : 0; } -// Basic function to update selection (for very large amounts of changes, see what ApplyRequests is doing) -void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected) -{ - ImGuiStoragePair* it = ImLowerBound(_Storage.Data.Data, _Storage.Data.Data + _Storage.Data.Size, id); - if (selected == (it != _Storage.Data.Data + _Storage.Data.Size) && (it->key == id)) - return; - if (selected) - _Storage.Data.insert(it, ImGuiStoragePair(id, 1)); - else - _Storage.Data.erase(it); - Size = _Storage.Data.Size; -} - // Optimized for batch edits (with same value of 'selected') static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends) { ImGuiStorage* storage = &selection->_Storage; ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id); - if (selected == (it != storage->Data.Data + size_before_amends) && (it->key == id)) + const bool is_contained = (it != storage->Data.Data + size_before_amends) && (it->key == id); + if (selected == is_contained && it->val_i == 1) return; - if (selected) + if (selected && !is_contained) storage->Data.push_back(ImGuiStoragePair(id, 1)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish() - else - it->val_i = 0; // Clear in-place, will be removed in SelectionMultiAmendsFinish() + else if (is_contained) + it->val_i = selected ? 1 : 0; // Modify in-place. selection->Size += selected ? +1 : -1; } -static void ImGuiSelectionBasicStorage_Compact(ImGuiSelectionBasicStorage* selection) -{ - ImGuiStorage* storage = &selection->_Storage; - ImGuiStoragePair* p_out = storage->Data.Data; - ImGuiStoragePair* p_end = storage->Data.Data + storage->Data.Size; - for (ImGuiStoragePair* p_in = p_out; p_in < p_end; p_in++) - if (p_in->val_i != 0) - { - if (p_out != p_in) - *p_out = *p_in; - p_out++; - } - storage->Data.Size = (int)(p_out - storage->Data.Data); -} - static void ImGuiSelectionBasicStorage_BatchFinish(ImGuiSelectionBasicStorage* selection, bool selected, int size_before_amends) { ImGuiStorage* storage = &selection->_Storage; - if (selection->Size == size_before_amends) - return; - if (selected) + if (selected && selection->Size != size_before_amends) storage->BuildSortByKey(); // When done selecting: sort everything - else - ImGuiSelectionBasicStorage_Compact(selection); // When done unselecting: compact by removing all zero values (might be done lazily when iterating selection?) - IM_ASSERT(selection->Size == storage->Data.Size); } // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). From c07864f64ab1c8db0682c6b752765d7d5db959e6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Jun 2024 19:45:21 +0200 Subject: [PATCH 0215/2359] MultiSelect: ImGuiSelectionBasicStorage: move function bodies to cpp file. + make ImGuiStorage::BuildSortByKey() less affected by msvc debug mode. --- imgui.cpp | 2 ++ imgui.h | 22 ++++++++++------------ imgui_widgets.cpp | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ee9462a9a..ffcdce5f6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2567,10 +2567,12 @@ static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs) } // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. +IM_MSVC_RUNTIME_CHECKS_OFF void ImGuiStorage::BuildSortByKey() { ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID); } +IM_MSVC_RUNTIME_CHECKS_RESTORE int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { diff --git a/imgui.h b/imgui.h index 93ecaf77b..6e86b85c0 100644 --- a/imgui.h +++ b/imgui.h @@ -2840,16 +2840,14 @@ struct ImGuiSelectionBasicStorage ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; // Methods - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io);// Apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. It uses 'items_count' passed to BeginMultiSelect() - IMGUI_API ImGuiID GetNextSelectedItem(void** opaque_it); // Iterate selection with 'void* it = NULL; while (ImGuiId id = selection.GetNextSelectedItem(&it)) { ... }' - bool Contains(ImGuiID id) const { return _Storage.GetInt(id, 0) != 0; } // Query if an item id is in selection. - ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } // Convert index to item id based on provided adapter. - - // [Internal, rarely called directly by end-user] - ImGuiSelectionBasicStorage() { Size = 0; UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; } - void Clear() { _Storage.Data.resize(0); Size = 0; } - void Swap(ImGuiSelectionBasicStorage& r) { _Storage.Data.swap(r._Storage.Data); int lhs_size = Size; Size = r.Size; r.Size = lhs_size; } - void SetItemSelected(ImGuiID id, bool v) { int* p_int = _Storage.GetIntRef(id, 0); if (v && *p_int == 0) { *p_int = 1; Size++; } else if (!v && *p_int != 0) { *p_int = 0; Size--; } } + ImGuiSelectionBasicStorage(); + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. It uses 'items_count' passed to BeginMultiSelect() + IMGUI_API bool Contains(ImGuiID id) const; // Query if an item id is in selection. + IMGUI_API void Clear(); // Clear selection + IMGUI_API void Swap(ImGuiSelectionBasicStorage& r); // Swap two selections + IMGUI_API void SetItemSelected(ImGuiID id, bool selected); // Add/remove an item from selection (generally done by ApplyRequests() function) + IMGUI_API ImGuiID GetNextSelectedItem(void** opaque_it); // Iterate selection with 'void* it = NULL; while (ImGuiId id = selection.GetNextSelectedItem(&it)) { ... }' + inline ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } // Convert index to item id based on provided adapter. }; // Optional helper to apply multi-selection requests to existing randomly accessible storage. @@ -2861,8 +2859,8 @@ struct ImGuiSelectionExternalStorage void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); // e.g. AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int idx, bool selected) { ((MyItems**)self->UserData)[idx]->Selected = selected; } // Methods - ImGuiSelectionExternalStorage() { UserData = NULL; AdapterSetItemSelected = NULL; } - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Generic function, using AdapterSetItemSelected() + IMGUI_API ImGuiSelectionExternalStorage(); + IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Apply selection requests by using AdapterSetItemSelected() calls }; //----------------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bcfa92194..54b1b1f68 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7821,6 +7821,30 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) // - ImGuiSelectionExternalStorage //------------------------------------------------------------------------- +ImGuiSelectionBasicStorage::ImGuiSelectionBasicStorage() +{ + Size = 0; + UserData = NULL; + AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; +} + +void ImGuiSelectionBasicStorage::Clear() +{ + Size = 0; + _Storage.Data.resize(0); +} + +void ImGuiSelectionBasicStorage::Swap(ImGuiSelectionBasicStorage& r) +{ + ImSwap(Size, r.Size); + _Storage.Data.swap(r._Storage.Data); +} + +bool ImGuiSelectionBasicStorage::Contains(ImGuiID id) const +{ + return _Storage.GetInt(id, 0) != 0; +} + // GetNextSelectedItem() is an abstraction allowing us to change our underlying actual storage system without impacting user. // (e.g. store unselected vs compact down, compact down on demand, use raw ImVector instead of ImGuiStorage...) ImGuiID ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it) @@ -7838,6 +7862,13 @@ ImGuiID ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it) return has_more ? it->key : 0; } +void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected) +{ + int* p_int = _Storage.GetIntRef(id, 0); + if (selected && *p_int == 0) { *p_int = 1; Size++; } + else if (!selected && *p_int != 0) { *p_int = 0; Size--; } +} + // Optimized for batch edits (with same value of 'selected') static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends) { @@ -7914,6 +7945,12 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) //------------------------------------------------------------------------- +ImGuiSelectionExternalStorage::ImGuiSelectionExternalStorage() +{ + UserData = NULL; + AdapterSetItemSelected = NULL; +} + // Apply requests coming from BeginMultiSelect() and EndMultiSelect(). // We also pull 'ms_io->ItemsCount' as passed for BeginMultiSelect() for consistency with ImGuiSelectionBasicStorage // This makes no assumption about underlying storage. From f472f17054030eab44df2ad6c7aba28c47dcf1fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Jun 2024 20:56:41 +0200 Subject: [PATCH 0216/2359] Demo: Assets Browser: added a way to disable sorting and hide sorting options. This is mostly designed to showcase that on very large sets (e.g. 1 million) most of the time is likely spent on sorting. --- imgui_demo.cpp | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d5ff2972d..ec5037297 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -9676,6 +9676,7 @@ struct ExampleAssetsBrowser { // Options bool ShowTypeOverlay = true; + bool AllowSorting = true; bool AllowDragUnselected = false; bool AllowBoxSelect = true; float IconSize = 32.0f; @@ -9778,6 +9779,7 @@ struct ExampleAssetsBrowser ImGui::SeparatorText("Contents"); ImGui::Checkbox("Show Type Overlay", &ShowTypeOverlay); + ImGui::Checkbox("Allow Sorting", &AllowSorting); ImGui::SeparatorText("Selection Behavior"); ImGui::Checkbox("Allow dragging unselected item", &AllowDragUnselected); @@ -9796,22 +9798,25 @@ struct ExampleAssetsBrowser } // Show a table with ONLY one header row to showcase the idea/possibility of using this to provide a sorting UI - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); - ImGuiTableFlags table_flags_for_sort_specs = ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders; - if (ImGui::BeginTable("for_sort_specs_only", 2, table_flags_for_sort_specs, ImVec2(0.0f, ImGui::GetFrameHeight()))) + if (AllowSorting) { - ImGui::TableSetupColumn("Index"); - ImGui::TableSetupColumn("Type"); - ImGui::TableHeadersRow(); - if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs()) - if (sort_specs->SpecsDirty || RequestSort) - { - ExampleAsset::SortWithSortSpecs(sort_specs, Items.Data, Items.Size); - sort_specs->SpecsDirty = RequestSort = false; - } - ImGui::EndTable(); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + ImGuiTableFlags table_flags_for_sort_specs = ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders; + if (ImGui::BeginTable("for_sort_specs_only", 2, table_flags_for_sort_specs, ImVec2(0.0f, ImGui::GetFrameHeight()))) + { + ImGui::TableSetupColumn("Index"); + ImGui::TableSetupColumn("Type"); + ImGui::TableHeadersRow(); + if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs()) + if (sort_specs->SpecsDirty || RequestSort) + { + ExampleAsset::SortWithSortSpecs(sort_specs, Items.Data, Items.Size); + sort_specs->SpecsDirty = RequestSort = false; + } + ImGui::EndTable(); + } + ImGui::PopStyleVar(); } - ImGui::PopStyleVar(); ImGuiIO& io = ImGui::GetIO(); ImGui::SetNextWindowContentSize(ImVec2(0.0f, LayoutOuterPadding + LayoutLineCount * (LayoutItemSize.x + LayoutItemSpacing))); From 3ac367ff41b33eb7e7e6013f0132441b5cbfed35 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 17:00:52 +0200 Subject: [PATCH 0217/2359] MultiSelect: ImGuiSelectionBasicStorage: (breaking) rework GetNextSelectedItem() api to avoid ambiguity/failure when user uses a zero id. --- imgui.h | 6 +++--- imgui_demo.cpp | 8 +++++--- imgui_widgets.cpp | 5 +++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index 6e86b85c0..a66e8d84c 100644 --- a/imgui.h +++ b/imgui.h @@ -2817,7 +2817,7 @@ struct ImGuiSelectionRequest // Optional helper to store multi-selection state + apply multi-selection requests. // - Used by our demos and provided as a convenience to easily implement basic multi-selection. -// - Iterate selection with 'void* it = NULL; while (ImGuiId id = selection.GetNextSelectedItem(&it)) { ... }' +// - Iterate selection with 'void* it = NULL; ImGuiID id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' // Or you can check 'if (Contains(id)) { ... }' for each possible object if their number is not too high to iterate. // - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. // To store a multi-selection, in your application you could: @@ -2834,10 +2834,10 @@ struct ImGuiSelectionRequest struct ImGuiSelectionBasicStorage { // Members - ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; + ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). // Methods ImGuiSelectionBasicStorage(); @@ -2846,7 +2846,7 @@ struct ImGuiSelectionBasicStorage IMGUI_API void Clear(); // Clear selection IMGUI_API void Swap(ImGuiSelectionBasicStorage& r); // Swap two selections IMGUI_API void SetItemSelected(ImGuiID id, bool selected); // Add/remove an item from selection (generally done by ApplyRequests() function) - IMGUI_API ImGuiID GetNextSelectedItem(void** opaque_it); // Iterate selection with 'void* it = NULL; while (ImGuiId id = selection.GetNextSelectedItem(&it)) { ... }' + IMGUI_API bool GetNextSelectedItem(void** opaque_it, ImGuiID* out_id); // Iterate selection with 'void* it = NULL; ImGuiId id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' inline ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } // Convert index to item id based on provided adapter. }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ec5037297..690c79fda 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3447,11 +3447,12 @@ static void ShowDemoWindowMultiSelect() { ImVector payload_items; void* it = NULL; + ImGuiID id = 0; if (!item_is_selected) payload_items.push_back(item_id); else - while (int id = (int)selection.GetNextSelectedItem(&it)) - payload_items.push_back(id); + while (selection.GetNextSelectedItem(&it, &id)) + payload_items.push_back((int)id); ImGui::SetDragDropPayload("MULTISELECT_DEMO_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes()); } @@ -9907,10 +9908,11 @@ struct ExampleAssetsBrowser { ImVector payload_items; void* it = NULL; + ImGuiID id = 0; if (!item_is_selected) payload_items.push_back(item_data->ID); else - while (ImGuiID id = Selection.GetNextSelectedItem(&it)) + while (Selection.GetNextSelectedItem(&it, &id)) payload_items.push_back(id); ImGui::SetDragDropPayload("ASSETS_BROWSER_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes()); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 54b1b1f68..fccc15d14 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7847,7 +7847,7 @@ bool ImGuiSelectionBasicStorage::Contains(ImGuiID id) const // GetNextSelectedItem() is an abstraction allowing us to change our underlying actual storage system without impacting user. // (e.g. store unselected vs compact down, compact down on demand, use raw ImVector instead of ImGuiStorage...) -ImGuiID ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it) +bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* out_id) { ImGuiStoragePair* it = (ImGuiStoragePair*)*opaque_it; ImGuiStoragePair* it_end = _Storage.Data.Data + _Storage.Data.Size; @@ -7859,7 +7859,8 @@ ImGuiID ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it) it++; const bool has_more = (it != it_end); *opaque_it = has_more ? (void**)(it + 1) : (void**)(it); - return has_more ? it->key : 0; + *out_id = has_more ? it->key : 0; + return has_more; } void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected) From df664329cb57cac10e82f7b1970ca3bf1b59d907 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 18:29:30 +0200 Subject: [PATCH 0218/2359] MultiSelect: provide RangeDirection to allow selection handler to handler backward shift+click. --- imgui.h | 1 + imgui_widgets.cpp | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index a66e8d84c..6c1aac570 100644 --- a/imgui.h +++ b/imgui.h @@ -2811,6 +2811,7 @@ struct ImGuiSelectionRequest //------------------------------------------// BeginMultiSelect / EndMultiSelect ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. bool Selected; // ms:w, app:r / ms:w, app:r // Parameter for SetAll/SetRange requests (true = select, false = unselect) + ImS8 RangeDirection; // / ms:w app:r // Parameter for SetRange request: +1 when RangeFirstItem comes before RangeLastItem, -1 otherwise. Useful if you want to preserve selection order on a backward Shift+Click. ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom). ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top). Inclusive! }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fccc15d14..80b1c06fa 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7294,7 +7294,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe for (const ImGuiSelectionRequest& req : io->Requests) { if (req.Type == ImGuiSelectionRequestType_SetAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetAll %d (= %s)\n", function, req.Selected, req.Selected ? "SelectAll" : "Clear"); - if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.Selected); + if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d (dir %d)\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.Selected, req.RangeDirection); } } @@ -7401,7 +7401,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel if (request_clear || request_select_all) { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; if (!request_select_all) storage->LastSelectionSize = 0; ms->IO.Requests.push_back(req); @@ -7475,7 +7475,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; ms->IO.Requests.resize(0); ms->IO.Requests.push_back(req); } @@ -7665,7 +7665,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) else { selected = !selected; - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, item_data, item_data }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, +1, item_data, item_data }; ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) prev_req->RangeLastItem = item_data; // Merge span into same request @@ -7733,7 +7733,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. if (request_clear) { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; ms->IO.Requests.resize(0); ms->IO.Requests.push_back(req); } @@ -7775,7 +7775,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) range_direction = +1; } ImGuiSelectionUserData range_dst_item = item_data; - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, range_selected, (range_direction > 0) ? storage->RangeSrcItem : range_dst_item, (range_direction > 0) ? range_dst_item : storage->RangeSrcItem }; + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, range_selected, (ImS8)range_direction, (range_direction > 0) ? storage->RangeSrcItem : range_dst_item, (range_direction > 0) ? range_dst_item : storage->RangeSrcItem }; ms->IO.Requests.push_back(req); } @@ -7876,7 +7876,7 @@ static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicS ImGuiStorage* storage = &selection->_Storage; ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id); const bool is_contained = (it != storage->Data.Data + size_before_amends) && (it->key == id); - if (selected == is_contained && it->val_i == 1) + if (selected == is_contained && it->val_i != 0) return; if (selected && !is_contained) storage->Data.push_back(ImGuiStoragePair(id, 1)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish() From c52346850d7766727b6ba5c55ae0583672033420 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 18:41:21 +0200 Subject: [PATCH 0219/2359] MultiSelect: ImGuiSelectionBasicStorage: added PreserveOrder, maintain implicit order data in storage. Little tested but provided for completeness. --- imgui.h | 8 +++++--- imgui_widgets.cpp | 34 ++++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/imgui.h b/imgui.h index 6c1aac570..d20c0dc69 100644 --- a/imgui.h +++ b/imgui.h @@ -2835,9 +2835,11 @@ struct ImGuiSelectionRequest struct ImGuiSelectionBasicStorage { // Members - int Size; // Number of selected items (== number of 1 in the Storage), maintained by this helper. - void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; - ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; + int Size; // // Number of selected items, maintained by this helper. + bool PreserveOrder; // = false // GetNextSelectedItem() will return ordered selection (currently implemented by two additional sorts of selection. Could be improved) + void* UserData; // = NULL // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; + ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; + int _SelectionOrder;// [Internal] Increasing counter to store selection order ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). // Methods diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 80b1c06fa..d842d5d8f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7824,19 +7824,23 @@ void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) ImGuiSelectionBasicStorage::ImGuiSelectionBasicStorage() { Size = 0; + PreserveOrder = false; UserData = NULL; AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; }; + _SelectionOrder = 1; // Always >0 } void ImGuiSelectionBasicStorage::Clear() { Size = 0; + _SelectionOrder = 1; // Always >0 _Storage.Data.resize(0); } void ImGuiSelectionBasicStorage::Swap(ImGuiSelectionBasicStorage& r) { ImSwap(Size, r.Size); + ImSwap(_SelectionOrder, r._SelectionOrder); _Storage.Data.swap(r._Storage.Data); } @@ -7845,12 +7849,21 @@ bool ImGuiSelectionBasicStorage::Contains(ImGuiID id) const return _Storage.GetInt(id, 0) != 0; } +static int IMGUI_CDECL PairComparerByValueInt(const void* lhs, const void* rhs) +{ + int lhs_v = ((const ImGuiStoragePair*)lhs)->val_i; + int rhs_v = ((const ImGuiStoragePair*)rhs)->val_i; + return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0); +} + // GetNextSelectedItem() is an abstraction allowing us to change our underlying actual storage system without impacting user. // (e.g. store unselected vs compact down, compact down on demand, use raw ImVector instead of ImGuiStorage...) bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* out_id) { ImGuiStoragePair* it = (ImGuiStoragePair*)*opaque_it; ImGuiStoragePair* it_end = _Storage.Data.Data + _Storage.Data.Size; + if (PreserveOrder && it == NULL && it_end != NULL) + ImQsort(_Storage.Data.Data, (size_t)_Storage.Data.Size, sizeof(ImGuiStoragePair), PairComparerByValueInt); // ~ImGuiStorage::BuildSortByValueInt() if (it == NULL) it = _Storage.Data.Data; IM_ASSERT(it >= _Storage.Data.Data && it <= it_end); @@ -7860,18 +7873,20 @@ bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* const bool has_more = (it != it_end); *opaque_it = has_more ? (void**)(it + 1) : (void**)(it); *out_id = has_more ? it->key : 0; + if (PreserveOrder && !has_more) + _Storage.BuildSortByKey(); return has_more; } void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected) { int* p_int = _Storage.GetIntRef(id, 0); - if (selected && *p_int == 0) { *p_int = 1; Size++; } + if (selected && *p_int == 0) { *p_int = _SelectionOrder++; Size++; } else if (!selected && *p_int != 0) { *p_int = 0; Size--; } } // Optimized for batch edits (with same value of 'selected') -static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends) +static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends, int selection_order) { ImGuiStorage* storage = &selection->_Storage; ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id); @@ -7879,9 +7894,9 @@ static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicS if (selected == is_contained && it->val_i != 0) return; if (selected && !is_contained) - storage->Data.push_back(ImGuiStoragePair(id, 1)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish() + storage->Data.push_back(ImGuiStoragePair(id, selection_order)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish() else if (is_contained) - it->val_i = selected ? 1 : 0; // Modify in-place. + it->val_i = selected ? selection_order : 0; // Modify in-place. selection->Size += selected ? +1 : -1; } @@ -7929,16 +7944,19 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) { _Storage.Data.reserve(ms_io->ItemsCount); const int size_before_amends = _Storage.Data.Size; - for (int idx = 0; idx < ms_io->ItemsCount; idx++) - ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends); + for (int idx = 0; idx < ms_io->ItemsCount; idx++, _SelectionOrder++) + ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, _SelectionOrder); ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends); } } else if (req.Type == ImGuiSelectionRequestType_SetRange) { + // Use req.RangeDirection to set order field so that shift+clicking from 1 to 5 is different than shift+clicking from 5 to 1 const int size_before_amends = _Storage.Data.Size; - for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) - ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends); + int selection_order = _SelectionOrder + ((req.RangeDirection < 0) ? (int)req.RangeLastItem - (int)req.RangeFirstItem : 0); + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++, selection_order += req.RangeDirection) + ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, selection_order); + _SelectionOrder += (int)req.RangeLastItem - (int)req.RangeFirstItem + 1; ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends); } } From a8a1f29512667545da4ba4700f2e86070d54f477 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Jun 2024 20:26:06 +0200 Subject: [PATCH 0220/2359] MultiSelect: (breaking) renamed ImGuiMultiSelectFlags_BoxSelect -> ImGuiMultiSelectFlags_BoxSelect2d. Which include not assuming one flag imply the other. Amend 2024/05/31 commit. --- imgui.h | 4 ++-- imgui_demo.cpp | 9 ++++----- imgui_widgets.cpp | 16 ++++++++-------- 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/imgui.h b/imgui.h index d20c0dc69..08464802a 100644 --- a/imgui.h +++ b/imgui.h @@ -2770,8 +2770,8 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing other items when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) - ImGuiMultiSelectFlags_BoxSelect = 1 << 5, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. only full row Selectable()). Small optimization. + ImGuiMultiSelectFlags_BoxSelect1d = 1 << 5, // Enable box-selection with same width and same x pos items (e.g. only full row Selectable()). Small optimization. + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 6, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 7, // Disable scrolling when box-selecting near edges of scope. ImGuiMultiSelectFlags_ClearOnEscape = 1 << 8, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 9, // Clear selection when clicking on empty location within scope. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 690c79fda..007a64490 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3216,7 +3216,7 @@ static void ShowDemoWindowMultiSelect() static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_ClearOnEscape; ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); // Cannot use ImGuiMultiSelectFlags_BoxSelect1d as checkboxes are varying width. + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); // Cannot use ImGuiMultiSelectFlags_BoxSelect1d as checkboxes are varying width. if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_Border | ImGuiChildFlags_ResizeY)) { @@ -3327,8 +3327,8 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoRangeSelect", &flags, ImGuiMultiSelectFlags_NoRangeSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); - ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect", &flags, ImGuiMultiSelectFlags_BoxSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid); @@ -9838,7 +9838,7 @@ struct ExampleAssetsBrowser if (AllowDragUnselected) ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. if (AllowBoxSelect) - ms_flags |= ImGuiMultiSelectFlags_BoxSelect; // Enable box-select in 2D mode. + ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; // Enable box-select in 2D mode. ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size, Items.Size); // Use custom selection adapter: store ID in selection (recommended) @@ -9927,8 +9927,7 @@ struct ExampleAssetsBrowser } // Render icon (a real app would likely display an image/thumbnail here) - // Because we use ImGuiMultiSelectFlags_BoxSelect (without ImGuiMultiSelectFlags_BoxSelect1d flag), - // clipping vertical range may occasionally be larger so we coarse-clip our rendering. + // Because we use ImGuiMultiSelectFlags_BoxSelect2d, clipping vertical may occasionally be larger, so we coarse-clip our rendering as well. if (item_is_visible) { ImVec2 box_min(pos.x - 1, pos.y - 1); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d842d5d8f..25b9a8e1f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7236,7 +7236,7 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper) // Storing an extra rect used by widgets supporting box-select. - if ((ms_flags & ImGuiMultiSelectFlags_BoxSelect) && !(ms_flags & ImGuiMultiSelectFlags_BoxSelect1d)) + if (ms_flags & ImGuiMultiSelectFlags_BoxSelect2d) if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x) { bs->UnclipMode = true; @@ -7319,9 +7319,9 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0) flags |= ImGuiMultiSelectFlags_ScopeWindow; if (flags & ImGuiMultiSelectFlags_SingleSelect) - flags &= ~(ImGuiMultiSelectFlags_BoxSelect | ImGuiMultiSelectFlags_BoxSelect1d); - if (flags & ImGuiMultiSelectFlags_BoxSelect1d) - flags |= ImGuiMultiSelectFlags_BoxSelect; + flags &= ~(ImGuiMultiSelectFlags_BoxSelect2d | ImGuiMultiSelectFlags_BoxSelect1d); + if (flags & ImGuiMultiSelectFlags_BoxSelect2d) + flags &= ~ImGuiMultiSelectFlags_BoxSelect1d; // FIXME: BeginFocusScope() const ImGuiID id = window->IDStack.back(); @@ -7391,7 +7391,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel // Box-select handling: update active state. ImGuiBoxSelectState* bs = &g.BoxSelectState; - if (flags & ImGuiMultiSelectFlags_BoxSelect) + if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) { ms->BoxSelectId = GetID("##BoxSelect"); ms->BoxSelectLastitem = ImGuiSelectionUserData_Invalid; @@ -7442,7 +7442,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() storage->NavIdSelected = -1; } - if ((ms->Flags & ImGuiMultiSelectFlags_BoxSelect) && GetBoxSelectState(ms->BoxSelectId)) + if ((ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) && GetBoxSelectState(ms->BoxSelectId)) { bool enable_scroll = (ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0; EndBoxSelect(scope_rect, enable_scroll); @@ -7460,7 +7460,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() scope_hovered &= scope_rect.Contains(g.IO.MousePos); if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0) { - if (ms->Flags & ImGuiMultiSelectFlags_BoxSelect) + if (ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) { if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1) { @@ -7701,7 +7701,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { // Box-select ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse; - if (flags & ImGuiMultiSelectFlags_BoxSelect) + if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1) BoxSelectPreStartDrag(ms->BoxSelectId, item_data); From 529c73ba2182da1bff839cea798efe93673a368c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Jun 2024 19:13:19 +0200 Subject: [PATCH 0221/2359] MultiSelect: Shift+Tab doesn't enable Shift select on landing item. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 25b9a8e1f..910d8dacf 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7336,7 +7336,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame. - ms->KeyMods = g.NavJustMovedToId ? g.NavJustMovedToKeyMods : g.IO.KeyMods; + ms->KeyMods = g.NavJustMovedToId ? (g.NavJustMovedToIsTabbing ? 0 : g.NavJustMovedToKeyMods) : g.IO.KeyMods; if (flags & ImGuiMultiSelectFlags_NoRangeSelect) ms->KeyMods &= ~ImGuiMod_Shift; From 3f34c83bc6e822769ac61cbd399dd1b39e750fcc Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 11:55:22 +0200 Subject: [PATCH 0222/2359] MultiSelect: added ImGuiMultiSelectFlags_NoAutoClearOnReselect + tweak flags comments. (#7424) --- imgui.h | 21 +++++++++++---------- imgui_demo.cpp | 1 + imgui_widgets.cpp | 2 +- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/imgui.h b/imgui.h index 08464802a..569281729 100644 --- a/imgui.h +++ b/imgui.h @@ -2769,16 +2769,17 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to select all. ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) - ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing other items when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) - ImGuiMultiSelectFlags_BoxSelect1d = 1 << 5, // Enable box-selection with same width and same x pos items (e.g. only full row Selectable()). Small optimization. - ImGuiMultiSelectFlags_BoxSelect2d = 1 << 6, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 7, // Disable scrolling when box-selecting near edges of scope. - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 8, // Clear selection when pressing Escape while scope is focused. - ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 9, // Clear selection when clicking on empty location within scope. - ImGuiMultiSelectFlags_ScopeWindow = 1 << 10, // Use if BeginMultiSelect() covers a whole window (Default): Scope for _ClearOnClickVoid and _BoxSelect is whole window (Default). - ImGuiMultiSelectFlags_ScopeRect = 1 << 11, // Use if multiple BeginMultiSelect() are used in the same host window: Scope for _ClearOnClickVoid and _BoxSelect is rectangle covering submitted items. - ImGuiMultiSelectFlags_SelectOnClick = 1 << 12, // Apply selection on mouse down when clicking on unselected item. (Default) - ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 13, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. + ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) + ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1 << 5, // Disable clearing selection when clicking/selecting an already selected item + ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. only full row Selectable()). Small optimization. + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 7, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 8, // Disable scrolling when box-selecting near edges of scope. + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 9, // Clear selection when pressing Escape while scope is focused. + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 10, // Clear selection when clicking on empty location within scope. + ImGuiMultiSelectFlags_ScopeWindow = 1 << 11, // Scope for _BoxSelect and _ClearOnClickVoid is whole window (Default). Use if BeginMultiSelect() covers a whole window or used a single time in same window. + ImGuiMultiSelectFlags_ScopeRect = 1 << 12, // Scope for _BoxSelect and _ClearOnClickVoid is rectangle encompassing BeginMultiSelect()/EndMultiSelect(). Use if BeginMultiSelect() is called multiple times in same window. + ImGuiMultiSelectFlags_SelectOnClick = 1 << 13, // Apply selection on mouse down when clicking on unselected item. (Default) + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 14, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. }; // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 007a64490..ebfb5ddf5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3327,6 +3327,7 @@ static void ShowDemoWindowMultiSelect() ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoRangeSelect", &flags, ImGuiMultiSelectFlags_NoRangeSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClearOnReselect", &flags, ImGuiMultiSelectFlags_NoAutoClearOnReselect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 910d8dacf..5b2e400d1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7728,7 +7728,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) if (is_singleselect) request_clear = true; else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl) - request_clear = true; + request_clear = (flags & ImGuiMultiSelectFlags_NoAutoClearOnReselect) ? !selected : true; else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl) request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. if (request_clear) From d411c9054ad93e8e5b17cc3f451a94483b897f16 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 18:36:53 +0200 Subject: [PATCH 0223/2359] MultiSelect: minor tidying up. Checkbox() was reworked in master effectively fixing render clipping when culled by BoxSelect2d's UnclipMode. --- imgui.h | 1 + imgui_internal.h | 2 +- imgui_widgets.cpp | 12 +++++------- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index 569281729..b086caa27 100644 --- a/imgui.h +++ b/imgui.h @@ -2780,6 +2780,7 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_ScopeRect = 1 << 12, // Scope for _BoxSelect and _ClearOnClickVoid is rectangle encompassing BeginMultiSelect()/EndMultiSelect(). Use if BeginMultiSelect() is called multiple times in same window. ImGuiMultiSelectFlags_SelectOnClick = 1 << 13, // Apply selection on mouse down when clicking on unselected item. (Default) ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 14, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. + //ImGuiMultiSelectFlags_RangeSelect2d = 1 << 15, // Shift+Selection uses 2d geometry instead of linear sequence, so possible to use Shift+up/down to select vertically in grid. Analogous to what BoxSelect does. }; // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). diff --git a/imgui_internal.h b/imgui_internal.h index 908c8f426..ae3375e28 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3406,7 +3406,7 @@ namespace ImGui // Box-Select API IMGUI_API bool BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags); - IMGUI_API void EndBoxSelect(const ImRect& scope_rect, bool enable_scroll); + IMGUI_API void EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags); // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5b2e400d1..135273597 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1136,8 +1136,9 @@ bool ImGui::Checkbox(const char* label, bool* v) const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); ItemSize(total_bb, style.FramePadding.y); const bool is_visible = ItemAdd(total_bb, id); + const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; if (!is_visible) - if (!g.BoxSelectState.UnclipMode || (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) == 0 || !g.BoxSelectState.UnclipRect.Overlaps(total_bb)) // Extra layer of "no logic clip" for box-select support + if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(total_bb)) // Extra layer of "no logic clip" for box-select support { IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return false; @@ -1145,7 +1146,6 @@ bool ImGui::Checkbox(const char* label, bool* v) // Range-Selection/Multi-selection support (header) bool checked = *v; - const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; if (is_multi_select) MultiSelectItemHeader(id, &checked, NULL); @@ -7250,7 +7250,7 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult return true; } -void ImGui::EndBoxSelect(const ImRect& scope_rect, bool enable_scroll) +void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -7266,6 +7266,7 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, bool enable_scroll) window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavHighlight)); // FIXME-MULTISELECT: Styling // Scroll + const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0; if (enable_scroll) { ImRect scroll_r = scope_rect; @@ -7443,10 +7444,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() } if ((ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) && GetBoxSelectState(ms->BoxSelectId)) - { - bool enable_scroll = (ms->Flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms->Flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0; - EndBoxSelect(scope_rect, enable_scroll); - } + EndBoxSelect(scope_rect, ms->Flags); } if (ms->IsEndIO == false) From 7d4de84ee3ccc4c144fbe48236d59d7ceabdb058 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 19:01:18 +0200 Subject: [PATCH 0224/2359] MultiSelect: added courtesy ImGuiMultiSelectFlags_NavWrapX flag so we can demo this until a nav api is designed. --- imgui.h | 1 + imgui_demo.cpp | 21 ++++++++++++++------- imgui_widgets.cpp | 7 +++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index b086caa27..3aaa0981c 100644 --- a/imgui.h +++ b/imgui.h @@ -2781,6 +2781,7 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_SelectOnClick = 1 << 13, // Apply selection on mouse down when clicking on unselected item. (Default) ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 14, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. //ImGuiMultiSelectFlags_RangeSelect2d = 1 << 15, // Shift+Selection uses 2d geometry instead of linear sequence, so possible to use Shift+up/down to select vertically in grid. Analogous to what BoxSelect does. + ImGuiMultiSelectFlags_NavWrapX = 1 << 16, // [Temporary] Enable navigation wrapping on X axis. Provided as a convenience because we don't have a design for the general Nav API for this yet. When the more general feature be public we may obsolete this flag in favor of new one. }; // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ebfb5ddf5..ab2ae6b08 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -9836,10 +9836,21 @@ struct ExampleAssetsBrowser // Multi-select ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickVoid; - if (AllowDragUnselected) - ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; // To allow dragging an unselected item without altering selection. + + // - Enable box-select (in 2D mode, so that changing box-select rectangle X1/X2 boundaries will affect clipped items) if (AllowBoxSelect) - ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; // Enable box-select in 2D mode. + ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; + + // - This feature allows dragging an unselected item without selecting it (rarely used) + if (AllowDragUnselected) + ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease; + + // - Enable keyboard wrapping on X axis + // (FIXME-MULTISELECT: We haven't designed/exposed a general nav wrapping api yet, so this flag is provided as a courtesy to avoid doing: + // ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); + // When we finish implementing a more general API for this, we will obsolete this flag in favor of the new system) + ms_flags |= ImGuiMultiSelectFlags_NavWrapX; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size, Items.Size); // Use custom selection adapter: store ID in selection (recommended) @@ -9970,10 +9981,6 @@ struct ExampleAssetsBrowser if (want_delete) Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus); - // Keyboard/Gamepad Wrapping - // FIXME-MULTISELECT: Currently an imgui_internal.h API. Find a design/way to expose this in public API. - //ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); - // Zooming with CTRL+Wheel if (ImGui::IsWindowAppearing()) ZoomWheelAccum = 0.0f; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 135273597..703dcdb7a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7479,6 +7479,13 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() } } + // Courtesy nav wrapping helper flag + if (ms->Flags & ImGuiMultiSelectFlags_NavWrapX) + { + IM_ASSERT(ms->Flags & ImGuiMultiSelectFlags_ScopeWindow); // Only supported at window scope + ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX); + } + // Unwind window->DC.CursorMaxPos = ImMax(ms->BackupCursorMaxPos, window->DC.CursorMaxPos); PopFocusScope(); From 2697cfe35463aeeecfa9e7ec983f187b38fb3893 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 19:11:05 +0200 Subject: [PATCH 0225/2359] MultiSelect: Box-Select: uses SetActiveIdUsingAllKeyboardKeys() to avoid nav interference, much like most drag operations. --- imgui.cpp | 3 ++- imgui_internal.h | 2 +- imgui_widgets.cpp | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ffcdce5f6..d4a4d47f9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5539,7 +5539,8 @@ void ImGui::SetItemAllowOverlap() } #endif -// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function. +// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations. +// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed? void ImGui::SetActiveIdUsingAllKeyboardKeys() { ImGuiContext& g = *GImGui; diff --git a/imgui_internal.h b/imgui_internal.h index ae3375e28..c03839a8f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2081,7 +2081,7 @@ struct ImGuiContext ImGuiKeyOwnerData KeysOwnerData[ImGuiKey_NamedKey_COUNT]; ImGuiKeyRoutingTable KeysRoutingTable; ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) - bool ActiveIdUsingAllKeyboardKeys; // Active widget will want to read all keyboard keys inputs. (FIXME: This is a shortcut for not taking ownership of 100+ keys but perhaps best to not have the inconsistency) + bool ActiveIdUsingAllKeyboardKeys; // Active widget will want to read all keyboard keys inputs. (this is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations) ImGuiKeyChord DebugBreakInShortcutRouting; // Set to break in SetShortcutRouting()/Shortcut() calls. #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO ImU32 ActiveIdUsingNavInputMask; // If you used this. Since (IMGUI_VERSION_NUM >= 18804) : 'g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel);' becomes 'SetKeyOwner(ImGuiKey_Escape, g.ActiveId) and/or SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId);' diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 703dcdb7a..d04c1dd44 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7159,6 +7159,7 @@ static void BoxSelectActivateDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window) bs->Window = window; bs->IsStarting = false; ImGui::SetActiveID(bs->ID, window); + ImGui::SetActiveIdUsingAllKeyboardKeys(); if (bs->IsStartedFromVoid && (bs->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0) bs->RequestClear = true; } From 1b6352244659149898579575fabedbc4d27fd6bd Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Jun 2024 19:35:24 +0200 Subject: [PATCH 0226/2359] MultiSelect: Box-Select: handle Esc to disable box-select. This avoid remove a one-frame delay when finishing box-select, where Esc wouldn't be routed to selection but to child. --- imgui_widgets.cpp | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d04c1dd44..442ce2e50 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7377,20 +7377,6 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel request_clear = true; } - if (ms->IsFocused) - { - // Shortcut: Clear selection (Escape) - // Only claim shortcut if selection is not empty, allowing further presses on Escape to e.g. leave current child window. - if ((flags & ImGuiMultiSelectFlags_ClearOnEscape) && (selection_size != 0)) - if (Shortcut(ImGuiKey_Escape)) - request_clear = true; - - // Shortcut: Select all (CTRL+A) - if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) - if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) - request_select_all = true; - } - // Box-select handling: update active state. ImGuiBoxSelectState* bs = &g.BoxSelectState; if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) @@ -7401,6 +7387,28 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel request_clear |= bs->RequestClear; } + if (ms->IsFocused) + { + // Shortcut: Clear selection (Escape) + // - Only claim shortcut if selection is not empty, allowing further presses on Escape to e.g. leave current child window. + // - Box select also handle Escape and needs to pass an id to bypass ActiveIdUsingAllKeyboardKeys lock. + if (flags & ImGuiMultiSelectFlags_ClearOnEscape) + { + if (selection_size != 0 || bs->IsActive) + if (Shortcut(ImGuiKey_Escape, ImGuiInputFlags_None, bs->IsActive ? bs->ID : 0)) + { + request_clear = true; + if (bs->IsActive) + BoxSelectDeactivateDrag(bs); + } + } + + // Shortcut: Select all (CTRL+A) + if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) + if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) + request_select_all = true; + } + if (request_clear || request_select_all) { ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; From 7814518049e84860bc1b9ebd2f907dad2fca67c1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 19:54:35 +0200 Subject: [PATCH 0227/2359] MultiSelect: ImGuiSelectionBasicStorage: optimized for smaller insertion amounts in larger sets + fix caling batch select with same value. --- imgui.cpp | 2 +- imgui.h | 4 ++-- imgui_widgets.cpp | 39 +++++++++++++++++++++++++++++---------- 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d4a4d47f9..0fb4e34ca 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2558,6 +2558,7 @@ ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_ return in_p; } +IM_MSVC_RUNTIME_CHECKS_OFF static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs) { // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. @@ -2567,7 +2568,6 @@ static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs) } // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. -IM_MSVC_RUNTIME_CHECKS_OFF void ImGuiStorage::BuildSortByKey() { ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID); diff --git a/imgui.h b/imgui.h index 3aaa0981c..0ecbcbdef 100644 --- a/imgui.h +++ b/imgui.h @@ -2771,8 +2771,8 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1 << 5, // Disable clearing selection when clicking/selecting an already selected item - ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. only full row Selectable()). Small optimization. - ImGuiMultiSelectFlags_BoxSelect2d = 1 << 7, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. only full row Selectable()). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 7, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This is slower: alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 8, // Disable scrolling when box-selecting near edges of scope. ImGuiMultiSelectFlags_ClearOnEscape = 1 << 9, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 10, // Clear selection when clicking on empty location within scope. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 442ce2e50..637295e7a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7905,7 +7905,7 @@ static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicS ImGuiStorage* storage = &selection->_Storage; ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id); const bool is_contained = (it != storage->Data.Data + size_before_amends) && (it->key == id); - if (selected == is_contained && it->val_i != 0) + if (selected == (is_contained && it->val_i != 0)) return; if (selected && !is_contained) storage->Data.push_back(ImGuiStoragePair(id, selection_order)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish() @@ -7945,10 +7945,15 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) IM_ASSERT(ms_io->ItemsCount != -1 && "Missing value for items_count in BeginMultiSelect() call!"); IM_ASSERT(AdapterIndexToStorageId != NULL); - // This is optimized/specialized to cope nicely with very large selections (e.g. 1 million items) + // This is optimized/specialized to cope with very large selections (e.g. 100k+ items) // - A simpler version could call SetItemSelected() directly instead of ImGuiSelectionBasicStorage_BatchSetItemSelected() + ImGuiSelectionBasicStorage_BatchFinish(). // - Optimized select can append unsorted, then sort in a second pass. Optimized unselect can clear in-place then compact in a second pass. - // - (A more optimal version wouldn't even use ImGuiStorage but directly a ImVector to reduce bandwidth, but this is a reasonable trade off to reuse code) + // - A more optimal version wouldn't even use ImGuiStorage but directly a ImVector to reduce bandwidth, but this is a reasonable trade off to reuse code. + // - There are many ways this could be better optimized. The worse case scenario being: using BoxSelect2d in a grid, box-select scrolling down while wiggling + // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each.) + // FIXME-OPT: For each block of consecutive SetRange request: + // - add all requests to a sorted list, store ID, selected, offset in ImGuiStorage. + // - rewrite sorted storage a single time. for (ImGuiSelectionRequest& req : ms_io->Requests) { if (req.Type == ImGuiSelectionRequestType_SetAll) @@ -7965,13 +7970,27 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) } else if (req.Type == ImGuiSelectionRequestType_SetRange) { - // Use req.RangeDirection to set order field so that shift+clicking from 1 to 5 is different than shift+clicking from 5 to 1 - const int size_before_amends = _Storage.Data.Size; - int selection_order = _SelectionOrder + ((req.RangeDirection < 0) ? (int)req.RangeLastItem - (int)req.RangeFirstItem : 0); - for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++, selection_order += req.RangeDirection) - ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, selection_order); - _SelectionOrder += (int)req.RangeLastItem - (int)req.RangeFirstItem + 1; - ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends); + const int selection_changes = (int)req.RangeLastItem - (int)req.RangeFirstItem + 1; + //ImGuiContext& g = *GImGui; IMGUI_DEBUG_LOG_SELECTION("Req %d/%d: set %d to %d\n", ms_io->Requests.index_from_ptr(&req), ms_io->Requests.Size, selection_changes, req.Selected); + if (selection_changes == 1 || (selection_changes < Size / 100)) + { + // Multiple sorted insertion + copy likely to be faster. + // Technically we could do a single copy with a little more work (sort sequential SetRange requests) + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++) + SetItemSelected(GetStorageIdFromIndex(idx), req.Selected); + } + else + { + // Append insertion + single sort likely be faster. + // Use req.RangeDirection to set order field so that shift+clicking from 1 to 5 is different than shift+clicking from 5 to 1 + const int size_before_amends = _Storage.Data.Size; + int selection_order = _SelectionOrder + ((req.RangeDirection < 0) ? selection_changes - 1 : 0); + for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++, selection_order += req.RangeDirection) + ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, selection_order); + if (req.Selected) + _SelectionOrder += selection_changes; + ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends); + } } } } From 2688562fd2dc4dd9dfd4ac2c41fe97943bbe20a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 18 Jul 2024 18:05:45 +0200 Subject: [PATCH 0228/2359] MultiSelect: Better document how TreeNode() is not trivially usable yet. Will revert when the time is right. --- imgui.h | 8 ++++++-- imgui_demo.cpp | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 0ecbcbdef..5fb60300e 100644 --- a/imgui.h +++ b/imgui.h @@ -672,10 +672,12 @@ namespace ImGui 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. - // Multi-selection system for Selectable() and TreeNode() functions. + // Multi-selection system for Selectable(), Checkbox() functions* // - 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. // - ImGuiSelectionUserData is often used to store your item index within the current view (but may store something else). // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. + // - (*) TreeNode() is technically supported but... using this correctly is more complicate: you need some sort of linear/random access to your tree, + // which is suited to advanced trees setups already implementing filters and clipper. We will work toward simplifying and demoing this. // - 'selection_size' and 'items_count' parameters are optional and used by a few features. If they are costly for you to compute, you may avoid them. IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size = -1, int items_count = -1); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); @@ -2734,7 +2736,9 @@ struct ImColor // - Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos using this. // - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) // with support for clipper (skipping non-visible items), box-select and many other details. -// - TreeNode(), Selectable(), Checkbox() are supported but custom widgets may use it as well. +// - Selectable(), Checkbox() are supported but custom widgets may use it as well. +// - TreeNode() is technically supported but... using this correctly is more complicated: you need some sort of linear/random access to your tree, +// which is suited to advanced trees setups also implementing filters and clipper. We will work toward simplifying and demoing it. // - In the spirit of Dear ImGui design, your code owns actual selection data. // This is designed to allow all kinds of selection storage you may use in your application e.g. set/map/hash. // About ImGuiSelectionBasicStorage: diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ab2ae6b08..88ccce1f0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3317,6 +3317,8 @@ static void ShowDemoWindowMultiSelect() if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; } ImGui::SameLine(); if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; } + ImGui::SameLine(); + HelpMarker("TreeNode() is technically supported but... using this correctly is more complicated (you need some sort of linear/random access to your tree, which is suited to advanced trees setups already implementing filters and clipper. We will work toward simplifying and demoing this.\n\nFor now the tree demo is actually a little bit meaningless because it is an empty tree with only root nodes."); ImGui::Checkbox("Enable clipper", &use_clipper); ImGui::Checkbox("Enable deletion", &use_deletion); ImGui::Checkbox("Enable drag & drop", &use_drag_drop); From 02c31a8dd1f38b86f28b3a683cd55ebc4d8a839f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jul 2024 19:15:18 +0200 Subject: [PATCH 0229/2359] MultiSelect: added Changelog for the feature. Removed IMGUI_HAS_MULTI_SELECT. --- docs/CHANGELOG.txt | 51 ++++++++++++++++++++++++++++++++++++++++++++++ imgui.h | 6 ++---- imgui_internal.h | 4 ---- 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fea2fe5c2..ab1f0d806 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,57 @@ Other changes: Disabling this was previously possible for Selectable() via a direct flag but not for MenuItem(). (#1379, #1468, #2200, #4936, #5216, #7302, #7573) - This was mostly all previously in imgui_internal.h. +- Multi-Select: added multi-select API and demos. (#1861) + - This system implements standard multi-selection idioms (CTRL+mouse click, CTRL+keyboard moves, + SHIFT+mouse click, SHIFT+keyboard moves, etc.) with support for clipper (not submitting non-visible + items), box-selection with scrolling, and many other details. + - In the spirit of Dear ImGui design, your code owns both items and actual selection data. + This is designed to allow all kinds of selection storage you may use in your application + (e.g. set/map/hash, intrusive selection, interval trees, up to you). + - The supported widgets are Selectable(), Checkbox(). TreeNode() is also technically supported but... + using this correctly is more complicated (you need some sort of linear/random access to your tree, + which is suited to advanced trees setups already implementing filters and clipper. + We will work toward simplifying and demoing this later. + - A helper ImGuiSelectionBasicStorage is provided to facilitate getting started in a typical app. + - Documentation: + - Wiki page https://github.com/ocornut/imgui/wiki/Multi-Select for API overview. + - Demo code. + - Headers are well commented. + - Added BeginMultiSelect(), EndMultiSelect(), SetNextItemSelectionUserData(). + - Added IsItemToggledSelection() for use if you need latest selection update during currnet iteration. + - Added ImGuiMultiSelectIO and ImGuiSelectionRequest structures: + - BeginMultiSelect() and EndMultiSelect() return a ImGuiMultiSelectIO structure, which + is mostly an array of ImGuiSelectionRequest actions (clear, select all, set range, etc.) + - Other fields are helpful when using a clipper, or wanting to handle deletion nicely. + - Added ImGuiSelectionBasicStorage helper to store and maintain a selection (optional): + - This is similar to if you used e.g. a std::set to store a selection, with all the right + glue to honor ImGuiMultiSelectIO requests. Most applications can use that. + - Added ImGuiSelectionExternalStorage helper to maintain an externally stored selection (optional): + - Helpful to easily bind multi-selection to e.g. an array of checkboxes. + - Added ImGuiMultiSelectFlags options: + - ImGuiMultiSelectFlags_SingleSelect + - ImGuiMultiSelectFlags_NoSelectAll + - ImGuiMultiSelectFlags_NoRangeSelect + - ImGuiMultiSelectFlags_NoAutoSelect + - ImGuiMultiSelectFlags_NoAutoClear + - ImGuiMultiSelectFlags_NoAutoClearOnReselect (#7424) + - ImGuiMultiSelectFlags_BoxSelect1d + - ImGuiMultiSelectFlags_BoxSelect2d + - ImGuiMultiSelectFlags_BoxSelectNoScroll + - ImGuiMultiSelectFlags_ClearOnEscape + - ImGuiMultiSelectFlags_ClearOnClickVoid + - ImGuiMultiSelectFlags_ScopeWindow (default), ImGuiMultiSelectFlags_ScopeRect + - ImGuiMultiSelectFlags_SelectOnClick (default), ImGuiMultiSelectFlags_SelectOnClickRelease + - ImGuiMultiSelectFlags_NavWrapX + - Demo: Added "Examples->Assets Browser" demo. + - Demo: Added "Widgets->Selection State & Multi-Select" section, with: + - Multi-Select + - Multi-Select (with clipper) + - Multi-Select (with deletion) + - Multi-Select (dual list box) (#6648) + - Multi-Select (checkboxes) + - Multi-Select (multiple scopes) + - Multi-Select (advanced) - Clipper: added SeekCursorForItem() function. When using ImGuiListClipper::Begin(INT_MAX) you can can use the clipper without knowing the amount of items beforehand. (#1311) In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) as the end of your iteration diff --git a/imgui.h b/imgui.h index 5fb60300e..5550f1106 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19095 +#define IMGUI_VERSION_NUM 19096 #define IMGUI_HAS_TABLE /* @@ -2729,8 +2729,6 @@ struct ImColor // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO, ImGuiSelectionBasicStorage) //----------------------------------------------------------------------------- -#define IMGUI_HAS_MULTI_SELECT // Multi-Select/Range-Select WIP branch // <-- This is currently _not_ in the top of imgui.h to prevent merge conflicts. - // Multi-selection system // Documentation at: https://github.com/ocornut/imgui/wiki/Multi-Select // - Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos using this. @@ -2797,7 +2795,7 @@ struct ImGuiMultiSelectIO { //------------------------------------------// BeginMultiSelect / EndMultiSelect ImVector Requests; // ms:w, app:r / ms:w app:r // Requests to apply to your selection data. - ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (generally the first selected item when multi-selecting, which is used as a reference point) must never be clipped! + ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (often the first selected item) must never be clipped: use clipper.IncludeItemByIndex() to ensure it is submitted. ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). diff --git a/imgui_internal.h b/imgui_internal.h index c03839a8f..b44d7b258 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1741,8 +1741,6 @@ struct ImGuiBoxSelectState // We always assume that -1 is an invalid value (which works for indices and pointers) #define ImGuiSelectionUserData_Invalid ((ImGuiSelectionUserData)-1) -#ifdef IMGUI_HAS_MULTI_SELECT - // Temporary storage for multi-select struct IMGUI_API ImGuiMultiSelectTempData { @@ -1783,8 +1781,6 @@ struct IMGUI_API ImGuiMultiSelectState ImGuiMultiSelectState() { Window = NULL; ID = 0; LastFrameActive = LastSelectionSize = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } }; -#endif // #ifdef IMGUI_HAS_MULTI_SELECT - //----------------------------------------------------------------------------- // [SECTION] Docking support //----------------------------------------------------------------------------- From 2546d0a0dbe4a5088b5d5627e12760bb2cb50f84 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 19 Jul 2024 12:35:57 +0200 Subject: [PATCH 0230/2359] Demo: moved ExampleTreeNode, ExampleMemberInfo above in the demo file. Tidying up index. + change ExampleTreeNode::UID from ImGuiID to int to not suggest that the user ID needs to be of a certain type --- docs/CHANGELOG.txt | 2 +- imgui_demo.cpp | 213 ++++++++++++++++++++++++--------------------- 2 files changed, 116 insertions(+), 99 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ab1f0d806..9d919b6b9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,7 +77,7 @@ Other changes: Disabling this was previously possible for Selectable() via a direct flag but not for MenuItem(). (#1379, #1468, #2200, #4936, #5216, #7302, #7573) - This was mostly all previously in imgui_internal.h. -- Multi-Select: added multi-select API and demos. (#1861) +- Multi-Select: added multi-select API and demos. (#1861, #6518) - This system implements standard multi-selection idioms (CTRL+mouse click, CTRL+keyboard moves, SHIFT+mouse click, SHIFT+keyboard moves, etc.) with support for clipper (not submitting non-visible items), box-selection with scrolling, and many other details. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 88ccce1f0..b31443141 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -11,7 +11,7 @@ // Get the latest version at https://github.com/ocornut/imgui // How to easily locate code? -// - Use the Item Picker to debug break in code by clicking any widgets: https://github.com/ocornut/imgui/wiki/Debug-Tools +// - Use Tools->Item Picker to debug break in code by clicking any widgets: https://github.com/ocornut/imgui/wiki/Debug-Tools // - Browse an online version the demo with code linked to hovered widgets: https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html // - Find a visible string and search for it in the code! @@ -62,6 +62,7 @@ // - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. // - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. // - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. +// - You can search/grep for all sections listed in the index to find the section. /* @@ -69,14 +70,14 @@ Index of this file: // [SECTION] Forward Declarations // [SECTION] Helpers +// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) // [SECTION] Demo Window / ShowDemoWindow() -// - ShowDemoWindow() -// - sub section: ShowDemoWindowWidgets() -// - sub section: ShowDemoWindowMultiSelect() -// - sub section: ShowDemoWindowLayout() -// - sub section: ShowDemoWindowPopups() -// - sub section: ShowDemoWindowTables() -// - sub section: ShowDemoWindowInputs() +// [SECTION] ShowDemoWindowWidgets() +// [SECTION] ShowDemoWindowMultiSelect() +// [SECTION] ShowDemoWindowLayout() +// [SECTION] ShowDemoWindowPopups() +// [SECTION] ShowDemoWindowTables() +// [SECTION] ShowDemoWindowInputs() // [SECTION] About Window / ShowAboutWindow() // [SECTION] Style Editor / ShowStyleEditor() // [SECTION] User Guide / ShowUserGuide() @@ -84,7 +85,6 @@ Index of this file: // [SECTION] Example App: Debug Console / ShowExampleAppConsole() // [SECTION] Example App: Debug Log / ShowExampleAppLog() // [SECTION] Example App: Simple Layout / ShowExampleAppLayout() -// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor etc.) // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() // [SECTION] Example App: Long Text / ShowExampleAppLongText() // [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() @@ -192,7 +192,7 @@ Index of this file: #endif //----------------------------------------------------------------------------- -// [SECTION] Forward Declarations, Helpers +// [SECTION] Forward Declarations //----------------------------------------------------------------------------- #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) @@ -215,7 +215,7 @@ static void ShowExampleAppWindowTitles(bool* p_open); static void ShowExampleMenuFile(); // We split the contents of the big ShowDemoWindow() function into smaller functions -// (because the link time of very large functions grow non-linearly) +// (because the link time of very large functions tends to grow non-linearly) static void ShowDemoWindowWidgets(); static void ShowDemoWindowMultiSelect(); static void ShowDemoWindowLayout(); @@ -251,16 +251,85 @@ void* GImGuiDemoMarkerCallbackUserData = NULL; #define IMGUI_DEMO_MARKER(section) do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback(__FILE__, __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0) //----------------------------------------------------------------------------- -// [SECTION] Demo Window / ShowDemoWindow() +// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor etc.) //----------------------------------------------------------------------------- -// - ShowDemoWindow() -// - ShowDemoWindowWidgets() -// - ShowDemoWindowMultiSelect() -// - ShowDemoWindowLayout() -// - ShowDemoWindowPopups() -// - ShowDemoWindowTables() -// - ShowDemoWindowColumns() -// - ShowDemoWindowInputs() + +// Simple representation for a tree +// (this is designed to be simple to understand for our demos, not to be fancy or efficient etc.) +struct ExampleTreeNode +{ + // Tree structure + char Name[28]; + int UID = 0; + ExampleTreeNode* Parent = NULL; + ImVector Childs; + + // Leaf Data + bool HasData = false; // All leaves have data + bool DataMyBool = false; + int DataMyInt = 128; + ImVec2 DataMyVec2 = ImVec2(0.0f, 3.141592f); +}; + +// Simple representation of struct metadata/serialization data. +// (this is a minimal version of what a typical advanced application may provide) +struct ExampleMemberInfo +{ + const char* Name; // Member name + ImGuiDataType DataType; // Member type + int DataCount; // Member count (1 when scalar) + int Offset; // Offset inside parent structure +}; + +// Metadata description of ExampleTreeNode struct. +static const ExampleMemberInfo ExampleTreeNodeMemberInfos[] +{ + { "MyBool", ImGuiDataType_Bool, 1, offsetof(ExampleTreeNode, DataMyBool) }, + { "MyInt", ImGuiDataType_S32, 1, offsetof(ExampleTreeNode, DataMyInt) }, + { "MyVec2", ImGuiDataType_Float, 2, offsetof(ExampleTreeNode, DataMyVec2) }, +}; + +static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, ExampleTreeNode* parent) +{ + ExampleTreeNode* node = IM_NEW(ExampleTreeNode); + snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name); + node->UID = uid; + node->Parent = parent; + if (parent) + parent->Childs.push_back(node); + return node; +} + +// Create example tree data +static ExampleTreeNode* ExampleTree_CreateDemoTree() +{ + static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + char name_buf[32]; + int uid = 0; + ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); + for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * 2; idx_L0++) + { + snprintf(name_buf, 32, "%s %d", root_names[idx_L0 / 2], idx_L0 % 2); + ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); + const int number_of_childs = (int)strlen(node_L1->Name); + for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) + { + snprintf(name_buf, 32, "Child %d", idx_L1); + ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1); + node_L2->HasData = true; + if (idx_L1 == 0) + { + snprintf(name_buf, 32, "Sub-child %d", 0); + ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2); + node_L3->HasData = true; + } + } + } + return node_L0; +} + +//----------------------------------------------------------------------------- +// [SECTION] Demo Window / ShowDemoWindow() //----------------------------------------------------------------------------- // Demonstrate most Dear ImGui features (this is big function!) @@ -610,6 +679,10 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::End(); } +//----------------------------------------------------------------------------- +// [SECTION] ShowDemoWindowWidgets() +//----------------------------------------------------------------------------- + static void ShowDemoWindowWidgets() { IMGUI_DEMO_MARKER("Widgets"); @@ -2991,8 +3064,13 @@ struct ExampleDualListBox } }; +//----------------------------------------------------------------------------- +// [SECTION] ShowDemoWindowMultiSelect() +//----------------------------------------------------------------------------- // Multi-selection demos // Also read: https://github.com/ocornut/imgui/wiki/Multi-Select +//----------------------------------------------------------------------------- + static void ShowDemoWindowMultiSelect() { IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); @@ -3525,6 +3603,10 @@ static void ShowDemoWindowMultiSelect() } } +//----------------------------------------------------------------------------- +// [SECTION] ShowDemoWindowLayout() +//----------------------------------------------------------------------------- + static void ShowDemoWindowLayout() { IMGUI_DEMO_MARKER("Layout"); @@ -4384,6 +4466,10 @@ static void ShowDemoWindowLayout() } } +//----------------------------------------------------------------------------- +// [SECTION] ShowDemoWindowPopups() +//----------------------------------------------------------------------------- + static void ShowDemoWindowPopups() { IMGUI_DEMO_MARKER("Popups"); @@ -4844,6 +4930,10 @@ static void ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags) ImGui::CheckboxFlags("_IsHovered", &flags, ImGuiTableColumnFlags_IsHovered); } +//----------------------------------------------------------------------------- +// [SECTION] ShowDemoWindowTables() +//----------------------------------------------------------------------------- + static void ShowDemoWindowTables() { //ImGui::SetNextItemOpen(true, ImGuiCond_Once); @@ -6937,6 +7027,10 @@ static void ShowDemoWindowColumns() ImGui::TreePop(); } +//----------------------------------------------------------------------------- +// [SECTION] ShowDemoWindowInputs() +//----------------------------------------------------------------------------- + static void ShowDemoWindowInputs() { IMGUI_DEMO_MARKER("Inputs & Focus"); @@ -8484,83 +8578,6 @@ static void ShowExampleAppLayout(bool* p_open) ImGui::End(); } -//----------------------------------------------------------------------------- -// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor etc.) -//----------------------------------------------------------------------------- - -// Simple representation for a tree -// (this is designed to be simple to understand for our demos, not to be efficient etc.) -struct ExampleTreeNode -{ - char Name[28]; - ImGuiID UID = 0; - ExampleTreeNode* Parent = NULL; - ImVector Childs; - - // Data - bool HasData = false; // All leaves have data - bool DataIsEnabled = false; - int DataInt = 128; - ImVec2 DataVec2 = ImVec2(0.0f, 3.141592f); -}; - -// Simple representation of struct metadata/serialization data. -// (this is a minimal version of what a typical advanced application may provide) -struct ExampleMemberInfo -{ - const char* Name; - ImGuiDataType DataType; - int DataCount; - int Offset; -}; - -// Metadata description of ExampleTreeNode struct. -static const ExampleMemberInfo ExampleTreeNodeMemberInfos[] -{ - { "Enabled", ImGuiDataType_Bool, 1, offsetof(ExampleTreeNode, DataIsEnabled) }, - { "MyInt", ImGuiDataType_S32, 1, offsetof(ExampleTreeNode, DataInt) }, - { "MyVec2", ImGuiDataType_Float, 2, offsetof(ExampleTreeNode, DataVec2) }, -}; - -static ExampleTreeNode* ExampleTree_CreateNode(const char* name, const ImGuiID uid, ExampleTreeNode* parent) -{ - ExampleTreeNode* node = IM_NEW(ExampleTreeNode); - snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name); - node->UID = uid; - node->Parent = parent; - if (parent) - parent->Childs.push_back(node); - return node; -} - -// Create example tree data -static ExampleTreeNode* ExampleTree_CreateDemoTree() -{ - static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; - char name_buf[32]; - ImGuiID uid = 0; - ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); - for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * 2; idx_L0++) - { - snprintf(name_buf, 32, "%s %d", root_names[idx_L0 / 2], idx_L0 % 2); - ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); - const int number_of_childs = (int)strlen(node_L1->Name); - for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) - { - snprintf(name_buf, 32, "Child %d", idx_L1); - ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1); - node_L2->HasData = true; - if (idx_L1 == 0) - { - snprintf(name_buf, 32, "Sub-child %d", 0); - ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2); - node_L3->HasData = true; - } - } - } - return node_L0; -} - //----------------------------------------------------------------------------- // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() //----------------------------------------------------------------------------- @@ -8601,7 +8618,7 @@ struct ExampleAppPropertyEditor void DrawTreeNode(ExampleTreeNode* node) { // Object tree node - ImGui::PushID((int)node->UID); + ImGui::PushID(node->UID); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::AlignTextToFramePadding(); From 57eea6746e6bee19a308ba9dac1764bbf052714e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 19 Jul 2024 15:34:48 +0200 Subject: [PATCH 0231/2359] Demo: moved some fields inside a struct. --- imgui_demo.cpp | 150 +++++++++++++++++++++++++------------------------ 1 file changed, 78 insertions(+), 72 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b31443141..7d0cf5ee8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -216,8 +216,9 @@ static void ShowExampleMenuFile(); // We split the contents of the big ShowDemoWindow() function into smaller functions // (because the link time of very large functions tends to grow non-linearly) -static void ShowDemoWindowWidgets(); -static void ShowDemoWindowMultiSelect(); +struct DemoWindowData; +static void ShowDemoWindowWidgets(DemoWindowData* demo_data); +static void ShowDemoWindowMultiSelect(DemoWindowData* demo_data); static void ShowDemoWindowLayout(); static void ShowDemoWindowPopups(); static void ShowDemoWindowTables(); @@ -332,6 +333,32 @@ static ExampleTreeNode* ExampleTree_CreateDemoTree() // [SECTION] Demo Window / ShowDemoWindow() //----------------------------------------------------------------------------- +struct DemoWindowData +{ + // Examples Apps (accessible from the "Examples" menu) + bool ShowMainMenuBar = false; + bool ShowAppAssetsBrowser = false; + bool ShowAppConsole = false; + bool ShowAppCustomRendering = false; + bool ShowAppDocuments = false; + bool ShowAppLog = false; + bool ShowAppLayout = false; + bool ShowAppPropertyEditor = false; + bool ShowAppSimpleOverlay = false; + bool ShowAppAutoResize = false; + bool ShowAppConstrainedResize = false; + bool ShowAppFullscreen = false; + bool ShowAppLongText = false; + bool ShowAppWindowTitles = false; + + // Dear ImGui Tools (accessible from the "Tools" menu) + bool ShowMetrics = false; + bool ShowDebugLog = false; + bool ShowIDStackTool = false; + bool ShowStyleEditor = false; + bool ShowAbout = false; +}; + // Demonstrate most Dear ImGui features (this is big function!) // You may execute this function to experiment with the UI and understand what it does. // You may then search for keywords in the code when you are interested by a specific feature. @@ -344,58 +371,36 @@ void ImGui::ShowDemoWindow(bool* p_open) // Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues. IMGUI_CHECKVERSION(); - // Examples Apps (accessible from the "Examples" menu) - static bool show_app_main_menu_bar = false; - static bool show_app_assets_browser = false; - static bool show_app_console = false; - static bool show_app_custom_rendering = false; - static bool show_app_documents = false; - static bool show_app_log = false; - static bool show_app_layout = false; - static bool show_app_property_editor = false; - static bool show_app_simple_overlay = false; - static bool show_app_auto_resize = false; - static bool show_app_constrained_resize = false; - static bool show_app_fullscreen = false; - static bool show_app_long_text = false; - static bool show_app_window_titles = false; + // Stored data + static DemoWindowData demo; - if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); - if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); - if (show_app_assets_browser) ShowExampleAppAssetsBrowser(&show_app_assets_browser); - if (show_app_console) ShowExampleAppConsole(&show_app_console); - if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering); - if (show_app_log) ShowExampleAppLog(&show_app_log); - if (show_app_layout) ShowExampleAppLayout(&show_app_layout); - if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor); - if (show_app_simple_overlay) ShowExampleAppSimpleOverlay(&show_app_simple_overlay); - if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize); - if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize); - if (show_app_fullscreen) ShowExampleAppFullscreen(&show_app_fullscreen); - if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text); - if (show_app_window_titles) ShowExampleAppWindowTitles(&show_app_window_titles); + // Examples Apps (accessible from the "Examples" menu) + if (demo.ShowMainMenuBar) { ShowExampleAppMainMenuBar(); } + if (demo.ShowAppDocuments) { ShowExampleAppDocuments(&demo.ShowAppDocuments); } + if (demo.ShowAppAssetsBrowser) { ShowExampleAppAssetsBrowser(&demo.ShowAppAssetsBrowser); } + if (demo.ShowAppConsole) { ShowExampleAppConsole(&demo.ShowAppConsole); } + if (demo.ShowAppCustomRendering) { ShowExampleAppCustomRendering(&demo.ShowAppCustomRendering); } + if (demo.ShowAppLog) { ShowExampleAppLog(&demo.ShowAppLog); } + if (demo.ShowAppLayout) { ShowExampleAppLayout(&demo.ShowAppLayout); } + if (demo.ShowAppPropertyEditor) { ShowExampleAppPropertyEditor(&demo.ShowAppPropertyEditor); } + if (demo.ShowAppSimpleOverlay) { ShowExampleAppSimpleOverlay(&demo.ShowAppSimpleOverlay); } + if (demo.ShowAppAutoResize) { ShowExampleAppAutoResize(&demo.ShowAppAutoResize); } + if (demo.ShowAppConstrainedResize) { ShowExampleAppConstrainedResize(&demo.ShowAppConstrainedResize); } + if (demo.ShowAppFullscreen) { ShowExampleAppFullscreen(&demo.ShowAppFullscreen); } + if (demo.ShowAppLongText) { ShowExampleAppLongText(&demo.ShowAppLongText); } + if (demo.ShowAppWindowTitles) { ShowExampleAppWindowTitles(&demo.ShowAppWindowTitles); } // Dear ImGui Tools (accessible from the "Tools" menu) - static bool show_tool_metrics = false; - static bool show_tool_debug_log = false; - static bool show_tool_id_stack_tool = false; - static bool show_tool_style_editor = false; - static bool show_tool_about = false; - - if (show_tool_metrics) - ImGui::ShowMetricsWindow(&show_tool_metrics); - if (show_tool_debug_log) - ImGui::ShowDebugLogWindow(&show_tool_debug_log); - if (show_tool_id_stack_tool) - ImGui::ShowIDStackToolWindow(&show_tool_id_stack_tool); - if (show_tool_style_editor) + if (demo.ShowMetrics) { ImGui::ShowMetricsWindow(&demo.ShowMetrics); } + if (demo.ShowDebugLog) { ImGui::ShowDebugLogWindow(&demo.ShowDebugLog); } + if (demo.ShowIDStackTool) { ImGui::ShowIDStackToolWindow(&demo.ShowIDStackTool); } + if (demo.ShowAbout) { ImGui::ShowAboutWindow(&demo.ShowAbout); } + if (demo.ShowStyleEditor) { - ImGui::Begin("Dear ImGui Style Editor", &show_tool_style_editor); + ImGui::Begin("Dear ImGui Style Editor", &demo.ShowStyleEditor); ImGui::ShowStyleEditor(); ImGui::End(); } - if (show_tool_about) - ImGui::ShowAboutWindow(&show_tool_about); // Demonstrate the various window flags. Typically you would just use the default! static bool no_titlebar = false; @@ -455,24 +460,24 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::BeginMenu("Examples")) { IMGUI_DEMO_MARKER("Menu/Examples"); - ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar); + ImGui::MenuItem("Main menu bar", NULL, &demo.ShowMainMenuBar); ImGui::SeparatorText("Mini apps"); - ImGui::MenuItem("Assets Browser", NULL, &show_app_assets_browser); - ImGui::MenuItem("Console", NULL, &show_app_console); - ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering); - ImGui::MenuItem("Documents", NULL, &show_app_documents); - ImGui::MenuItem("Log", NULL, &show_app_log); - ImGui::MenuItem("Property editor", NULL, &show_app_property_editor); - ImGui::MenuItem("Simple layout", NULL, &show_app_layout); - ImGui::MenuItem("Simple overlay", NULL, &show_app_simple_overlay); + ImGui::MenuItem("Assets Browser", NULL, &demo.ShowAppAssetsBrowser); + ImGui::MenuItem("Console", NULL, &demo.ShowAppConsole); + ImGui::MenuItem("Custom rendering", NULL, &demo.ShowAppCustomRendering); + ImGui::MenuItem("Documents", NULL, &demo.ShowAppDocuments); + ImGui::MenuItem("Log", NULL, &demo.ShowAppLog); + ImGui::MenuItem("Property editor", NULL, &demo.ShowAppPropertyEditor); + ImGui::MenuItem("Simple layout", NULL, &demo.ShowAppLayout); + ImGui::MenuItem("Simple overlay", NULL, &demo.ShowAppSimpleOverlay); ImGui::SeparatorText("Concepts"); - ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize); - ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize); - ImGui::MenuItem("Fullscreen window", NULL, &show_app_fullscreen); - ImGui::MenuItem("Long text display", NULL, &show_app_long_text); - ImGui::MenuItem("Manipulating window titles", NULL, &show_app_window_titles); + ImGui::MenuItem("Auto-resizing window", NULL, &demo.ShowAppAutoResize); + ImGui::MenuItem("Constrained-resizing window", NULL, &demo.ShowAppConstrainedResize); + ImGui::MenuItem("Fullscreen window", NULL, &demo.ShowAppFullscreen); + ImGui::MenuItem("Long text display", NULL, &demo.ShowAppLongText); + ImGui::MenuItem("Manipulating window titles", NULL, &demo.ShowAppWindowTitles); ImGui::EndMenu(); } @@ -485,17 +490,17 @@ void ImGui::ShowDemoWindow(bool* p_open) #else const bool has_debug_tools = false; #endif - ImGui::MenuItem("Metrics/Debugger", NULL, &show_tool_metrics, has_debug_tools); - ImGui::MenuItem("Debug Log", NULL, &show_tool_debug_log, has_debug_tools); - ImGui::MenuItem("ID Stack Tool", NULL, &show_tool_id_stack_tool, has_debug_tools); - ImGui::MenuItem("Style Editor", NULL, &show_tool_style_editor); + ImGui::MenuItem("Metrics/Debugger", NULL, &demo.ShowMetrics, has_debug_tools); + ImGui::MenuItem("Debug Log", NULL, &demo.ShowDebugLog, has_debug_tools); + ImGui::MenuItem("ID Stack Tool", NULL, &demo.ShowIDStackTool, has_debug_tools); + ImGui::MenuItem("Style Editor", NULL, &demo.ShowStyleEditor); bool is_debugger_present = ImGui::GetIO().ConfigDebugIsDebuggerPresent; if (ImGui::MenuItem("Item Picker", NULL, false, has_debug_tools && is_debugger_present)) ImGui::DebugStartItemPicker(); if (!is_debugger_present) ImGui::SetItemTooltip("Requires io.ConfigDebugIsDebuggerPresent=true to be set.\n\nWe otherwise disable the menu option to avoid casual users crashing the application.\n\nYou can however always access the Item Picker in Metrics->Tools."); ImGui::Separator(); - ImGui::MenuItem("About Dear ImGui", NULL, &show_tool_about); + ImGui::MenuItem("About Dear ImGui", NULL, &demo.ShowAbout); ImGui::EndMenu(); } ImGui::EndMenuBar(); @@ -620,7 +625,7 @@ void ImGui::ShowDemoWindow(bool* p_open) IMGUI_DEMO_MARKER("Configuration/Style"); if (ImGui::TreeNode("Style")) { - ImGui::Checkbox("Style Editor", &show_tool_style_editor); + ImGui::Checkbox("Style Editor", &demo.ShowStyleEditor); ImGui::SameLine(); HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function."); ImGui::TreePop(); @@ -668,7 +673,7 @@ void ImGui::ShowDemoWindow(bool* p_open) } // All demo contents - ShowDemoWindowWidgets(); + ShowDemoWindowWidgets(&demo); ShowDemoWindowLayout(); ShowDemoWindowPopups(); ShowDemoWindowTables(); @@ -683,7 +688,7 @@ void ImGui::ShowDemoWindow(bool* p_open) // [SECTION] ShowDemoWindowWidgets() //----------------------------------------------------------------------------- -static void ShowDemoWindowWidgets() +static void ShowDemoWindowWidgets(DemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Widgets"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); @@ -1561,7 +1566,7 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } - ShowDemoWindowMultiSelect(); + ShowDemoWindowMultiSelect(demo_data); // To wire InputText() with std::string or any other custom string type, // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. @@ -3071,7 +3076,7 @@ struct ExampleDualListBox // Also read: https://github.com/ocornut/imgui/wiki/Multi-Select //----------------------------------------------------------------------------- -static void ShowDemoWindowMultiSelect() +static void ShowDemoWindowMultiSelect(DemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); if (ImGui::TreeNode("Selection State & Multi-Select")) @@ -3366,7 +3371,8 @@ static void ShowDemoWindowMultiSelect() // See ShowExampleAppAssetsBrowser() if (ImGui::TreeNode("Multi-Select (tiled assets browser)")) { - ImGui::BulletText("See 'Examples->Assets Browser' in menu"); + ImGui::Checkbox("Assets Browser", &demo_data->ShowAppAssetsBrowser); + ImGui::Text("(also access from 'Examples->Assets Browser' in menu)"); ImGui::TreePop(); } From 168ef39984c735ee954750ed0765c70c9fcf841b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 19 Jul 2024 15:46:51 +0200 Subject: [PATCH 0232/2359] Demo: moved menu bar code to its own function. --- imgui_demo.cpp | 130 ++++++++++++++++++++++++++----------------------- 1 file changed, 70 insertions(+), 60 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7d0cf5ee8..fb28e3d54 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -72,6 +72,7 @@ Index of this file: // [SECTION] Helpers // [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) // [SECTION] Demo Window / ShowDemoWindow() +// [SECTION] ShowDemoWindowMenuBar() // [SECTION] ShowDemoWindowWidgets() // [SECTION] ShowDemoWindowMultiSelect() // [SECTION] ShowDemoWindowLayout() @@ -217,6 +218,7 @@ static void ShowExampleMenuFile(); // We split the contents of the big ShowDemoWindow() function into smaller functions // (because the link time of very large functions tends to grow non-linearly) struct DemoWindowData; +static void ShowDemoWindowMenuBar(DemoWindowData* demo_data); static void ShowDemoWindowWidgets(DemoWindowData* demo_data); static void ShowDemoWindowMultiSelect(DemoWindowData* demo_data); static void ShowDemoWindowLayout(); @@ -443,68 +445,11 @@ void ImGui::ShowDemoWindow(bool* p_open) } // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details. - // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align) - //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); - // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. - ImGui::PushItemWidth(ImGui::GetFontSize() * -12); + ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. + //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align) // Menu Bar - if (ImGui::BeginMenuBar()) - { - if (ImGui::BeginMenu("Menu")) - { - IMGUI_DEMO_MARKER("Menu/File"); - ShowExampleMenuFile(); - ImGui::EndMenu(); - } - if (ImGui::BeginMenu("Examples")) - { - IMGUI_DEMO_MARKER("Menu/Examples"); - ImGui::MenuItem("Main menu bar", NULL, &demo.ShowMainMenuBar); - - ImGui::SeparatorText("Mini apps"); - ImGui::MenuItem("Assets Browser", NULL, &demo.ShowAppAssetsBrowser); - ImGui::MenuItem("Console", NULL, &demo.ShowAppConsole); - ImGui::MenuItem("Custom rendering", NULL, &demo.ShowAppCustomRendering); - ImGui::MenuItem("Documents", NULL, &demo.ShowAppDocuments); - ImGui::MenuItem("Log", NULL, &demo.ShowAppLog); - ImGui::MenuItem("Property editor", NULL, &demo.ShowAppPropertyEditor); - ImGui::MenuItem("Simple layout", NULL, &demo.ShowAppLayout); - ImGui::MenuItem("Simple overlay", NULL, &demo.ShowAppSimpleOverlay); - - ImGui::SeparatorText("Concepts"); - ImGui::MenuItem("Auto-resizing window", NULL, &demo.ShowAppAutoResize); - ImGui::MenuItem("Constrained-resizing window", NULL, &demo.ShowAppConstrainedResize); - ImGui::MenuItem("Fullscreen window", NULL, &demo.ShowAppFullscreen); - ImGui::MenuItem("Long text display", NULL, &demo.ShowAppLongText); - ImGui::MenuItem("Manipulating window titles", NULL, &demo.ShowAppWindowTitles); - - ImGui::EndMenu(); - } - //if (ImGui::MenuItem("MenuItem")) {} // You can also use MenuItem() inside a menu bar! - if (ImGui::BeginMenu("Tools")) - { - IMGUI_DEMO_MARKER("Menu/Tools"); -#ifndef IMGUI_DISABLE_DEBUG_TOOLS - const bool has_debug_tools = true; -#else - const bool has_debug_tools = false; -#endif - ImGui::MenuItem("Metrics/Debugger", NULL, &demo.ShowMetrics, has_debug_tools); - ImGui::MenuItem("Debug Log", NULL, &demo.ShowDebugLog, has_debug_tools); - ImGui::MenuItem("ID Stack Tool", NULL, &demo.ShowIDStackTool, has_debug_tools); - ImGui::MenuItem("Style Editor", NULL, &demo.ShowStyleEditor); - bool is_debugger_present = ImGui::GetIO().ConfigDebugIsDebuggerPresent; - if (ImGui::MenuItem("Item Picker", NULL, false, has_debug_tools && is_debugger_present)) - ImGui::DebugStartItemPicker(); - if (!is_debugger_present) - ImGui::SetItemTooltip("Requires io.ConfigDebugIsDebuggerPresent=true to be set.\n\nWe otherwise disable the menu option to avoid casual users crashing the application.\n\nYou can however always access the Item Picker in Metrics->Tools."); - ImGui::Separator(); - ImGui::MenuItem("About Dear ImGui", NULL, &demo.ShowAbout); - ImGui::EndMenu(); - } - ImGui::EndMenuBar(); - } + ShowDemoWindowMenuBar(&demo); ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); ImGui::Spacing(); @@ -684,6 +629,71 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::End(); } +//----------------------------------------------------------------------------- +// [SECTION] ShowDemoWindowMenuBar() +//----------------------------------------------------------------------------- + +static void ShowDemoWindowMenuBar(DemoWindowData* demo_data) +{ + IMGUI_DEMO_MARKER("Menu"); + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + IMGUI_DEMO_MARKER("Menu/File"); + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Examples")) + { + IMGUI_DEMO_MARKER("Menu/Examples"); + ImGui::MenuItem("Main menu bar", NULL, &demo_data->ShowMainMenuBar); + + ImGui::SeparatorText("Mini apps"); + ImGui::MenuItem("Assets Browser", NULL, &demo_data->ShowAppAssetsBrowser); + ImGui::MenuItem("Console", NULL, &demo_data->ShowAppConsole); + ImGui::MenuItem("Custom rendering", NULL, &demo_data->ShowAppCustomRendering); + ImGui::MenuItem("Documents", NULL, &demo_data->ShowAppDocuments); + ImGui::MenuItem("Log", NULL, &demo_data->ShowAppLog); + ImGui::MenuItem("Property editor", NULL, &demo_data->ShowAppPropertyEditor); + ImGui::MenuItem("Simple layout", NULL, &demo_data->ShowAppLayout); + ImGui::MenuItem("Simple overlay", NULL, &demo_data->ShowAppSimpleOverlay); + + ImGui::SeparatorText("Concepts"); + ImGui::MenuItem("Auto-resizing window", NULL, &demo_data->ShowAppAutoResize); + ImGui::MenuItem("Constrained-resizing window", NULL, &demo_data->ShowAppConstrainedResize); + ImGui::MenuItem("Fullscreen window", NULL, &demo_data->ShowAppFullscreen); + ImGui::MenuItem("Long text display", NULL, &demo_data->ShowAppLongText); + ImGui::MenuItem("Manipulating window titles", NULL, &demo_data->ShowAppWindowTitles); + + ImGui::EndMenu(); + } + //if (ImGui::MenuItem("MenuItem")) {} // You can also use MenuItem() inside a menu bar! + if (ImGui::BeginMenu("Tools")) + { + IMGUI_DEMO_MARKER("Menu/Tools"); +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + const bool has_debug_tools = true; +#else + const bool has_debug_tools = false; +#endif + ImGui::MenuItem("Metrics/Debugger", NULL, &demo_data->ShowMetrics, has_debug_tools); + ImGui::MenuItem("Debug Log", NULL, &demo_data->ShowDebugLog, has_debug_tools); + ImGui::MenuItem("ID Stack Tool", NULL, &demo_data->ShowIDStackTool, has_debug_tools); + ImGui::MenuItem("Style Editor", NULL, &demo_data->ShowStyleEditor); + bool is_debugger_present = ImGui::GetIO().ConfigDebugIsDebuggerPresent; + if (ImGui::MenuItem("Item Picker", NULL, false, has_debug_tools && is_debugger_present)) + ImGui::DebugStartItemPicker(); + if (!is_debugger_present) + ImGui::SetItemTooltip("Requires io.ConfigDebugIsDebuggerPresent=true to be set.\n\nWe otherwise disable the menu option to avoid casual users crashing the application.\n\nYou can however always access the Item Picker in Metrics->Tools."); + ImGui::Separator(); + ImGui::MenuItem("About Dear ImGui", NULL, &demo_data->ShowAbout); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } +} + //----------------------------------------------------------------------------- // [SECTION] ShowDemoWindowWidgets() //----------------------------------------------------------------------------- From b6e313bc05db184a8cb2382227cddaaf2cb7f51d Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 19 Jul 2024 16:42:06 +0200 Subject: [PATCH 0233/2359] MultiSelect: using ImGuiMultiSelectFlags_NoRangeSelect ensure never having to interpolate between two ImGuiSelectionUserData. --- imgui.h | 4 +++- imgui_widgets.cpp | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/imgui.h b/imgui.h index 5550f1106..87c5ba50e 100644 --- a/imgui.h +++ b/imgui.h @@ -2760,6 +2760,8 @@ struct ImColor // SetRange requests will give you two end-points and you will need to iterate/interpolate between them to update your selection. // - However it is perfectly possible to store a POINTER or another IDENTIFIER inside ImGuiSelectionUserData. // Our system never assume that you identify items by indices, it never attempts to interpolate between two values. +// - If you enable ImGuiMultiSelectFlags_NoRangeSelect then it is guaranteed that you will never have to interpolate +// between two ImGuiSelectionUserData, which may be a convenient way to use part of the feature with less code work. // - As most users will want to store an index, for convenience and to reduce confusion we use ImS64 instead of void*, // being syntactically easier to downcast. Feel free to reinterpret_cast and store a pointer inside. @@ -2769,7 +2771,7 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to select all. - ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). + ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). With BoxSelect is also ensure contiguous SetRange requests are not combined into one. This allows not handling interpolation in SetRange requests. ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1 << 5, // Disable clearing selection when clicking/selecting an already selected item diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 637295e7a..29635d3eb 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7680,9 +7680,10 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) { selected = !selected; ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, +1, item_data, item_data }; - ImGuiSelectionRequest* prev_req = (ms->IO.Requests.Size > 0) ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (prev_req && prev_req->Type == ImGuiSelectionRequestType_SetRange && prev_req->RangeLastItem == ms->BoxSelectLastitem && prev_req->Selected == selected) - prev_req->RangeLastItem = item_data; // Merge span into same request + // Merge continuous ranges (unless NoRangeSelect is set) + ImGuiSelectionRequest* prev = ms->IO.Requests.Size > 0 ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; + if (prev && prev->Type == ImGuiSelectionRequestType_SetRange && prev->RangeLastItem == ms->BoxSelectLastitem && prev->Selected == selected && (ms->Flags & ImGuiMultiSelectFlags_NoRangeSelect) == 0) + prev->RangeLastItem = item_data; // Merge span into same request else ms->IO.Requests.push_back(req); } From f9cda1fa245b361a0e98428d88470eebaa187e5b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 19 Jul 2024 18:39:07 +0200 Subject: [PATCH 0234/2359] Inputs: added SetItemKeyOwner(ImGuiKey key) in public API. (#456, #2637, #2620, #2891, #3370, #3724, #4828, #5108, #5242, #5641) --- docs/CHANGELOG.txt | 7 +++++++ imgui.cpp | 5 +++++ imgui.h | 10 +++++++++- imgui_internal.h | 2 +- 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9d919b6b9..2e620f79b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,13 @@ Other changes: Disabling this was previously possible for Selectable() via a direct flag but not for MenuItem(). (#1379, #1468, #2200, #4936, #5216, #7302, #7573) - This was mostly all previously in imgui_internal.h. +- Inputs: added SetItemKeyOwner(ImGuiKey key) in public API. This is a simplified version of a more + complete set of function available in imgui_internal.h. One common use-case for this is to allow + your items to disable standard inputs behaviors such as Tab or Alt handling, Mouse Wheel scrolling, + etc. (#456, #2637, #2620, #2891, #3370, #3724, #4828, #5108, #5242, #5641) + // Hovering or activating the button will disable mouse wheel default behavior to scroll + InvisibleButton(...); + SetItemKeyOwner(ImGuiKey_MouseWheelY); - Multi-Select: added multi-select API and demos. (#1861, #6518) - This system implements standard multi-selection idioms (CTRL+mouse click, CTRL+keyboard moves, SHIFT+mouse click, SHIFT+keyboard moves, etc.) with support for clipper (not submitting non-visible diff --git a/imgui.cpp b/imgui.cpp index 0fb4e34ca..6eb38f708 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9805,6 +9805,11 @@ void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags) } } +void ImGui::SetItemKeyOwner(ImGuiKey key) +{ + SetItemKeyOwner(key, ImGuiInputFlags_None); +} + // This is the only public API until we expose owner_id versions of the API as replacements. bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord) { diff --git a/imgui.h b/imgui.h index 87c5ba50e..6c49460e1 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19096 +#define IMGUI_VERSION_NUM 19097 #define IMGUI_HAS_TABLE /* @@ -984,6 +984,14 @@ namespace ImGui IMGUI_API bool Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0); IMGUI_API void SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0); + // Inputs Utilities: Key/Input Ownership [BETA] + // - One common use case would be to allow your items to disable standard inputs behaviors such + // as Tab or Alt key handling, Mouse Wheel scrolling, etc. + // e.g. Button(...); SetItemKeyOwner(ImGuiKey_MouseWheelY); to make hovering/activating a button disable wheel for scrolling. + // - Reminder ImGuiKey enum include access to mouse buttons and gamepad, so key ownership can apply to them. + // - Many related features are still in imgui_internal.h. For instance, most IsKeyXXX()/IsMouseXXX() functions have an owner-id-aware version. + IMGUI_API void SetItemKeyOwner(ImGuiKey key); // Set key owner to last item ID if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. + // Inputs Utilities: Mouse specific // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right. // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle. diff --git a/imgui_internal.h b/imgui_internal.h index b44d7b258..f2c5312ea 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3337,7 +3337,7 @@ namespace ImGui IMGUI_API ImGuiID GetKeyOwner(ImGuiKey key); IMGUI_API void SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0); IMGUI_API void SetKeyOwnersForKeyChord(ImGuiKeyChord key, ImGuiID owner_id, ImGuiInputFlags flags = 0); - IMGUI_API void SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags = 0); // Set key owner to last item if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. + IMGUI_API void SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags); // Set key owner to last item if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. IMGUI_API bool TestKeyOwner(ImGuiKey key, ImGuiID owner_id); // Test that key is either not owned, either owned by 'owner_id' inline ImGuiKeyOwnerData* GetKeyOwnerData(ImGuiContext* ctx, ImGuiKey key) { if (key & ImGuiMod_Mask_) key = ConvertSingleModFlagToKey(key); IM_ASSERT(IsNamedKey(key)); return &ctx->KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN]; } From eb72b5a8eeefd41e845dadbb4758e6f341f3f4a9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Jul 2024 10:49:22 +0200 Subject: [PATCH 0235/2359] Backends: SDL3: Update for API changes: SDL_GetGamepads() memory ownership change. (#7807) --- backends/imgui_impl_sdl3.cpp | 6 +++--- docs/CHANGELOG.txt | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 5cd852599..05718d21c 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -21,7 +21,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() string ownership change. (#7801) +// 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807) +// 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801) // 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) // 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762). // 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea(). @@ -639,7 +640,7 @@ static void ImGui_ImplSDL3_UpdateGamepads() { ImGui_ImplSDL3_CloseGamepads(); int sdl_gamepads_count = 0; - SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count); + const SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count); for (int n = 0; n < sdl_gamepads_count; n++) if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n])) { @@ -647,7 +648,6 @@ static void ImGui_ImplSDL3_UpdateGamepads() if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst) break; } - SDL_free(sdl_gamepads); bd->WantUpdateGamepadsList = false; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2e620f79b..49206df8e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -148,7 +148,8 @@ Other changes: struct description data that a real application would want to use. - Backends: Win32: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768, #4858, #2622) [@Aemony] -- Backends: SDL3: Update for API changes: SDL_GetClipboardText() string ownership change. (#7801) +- Backends: SDL3: Update for API changes: SDL_GetGamepads() memory ownership change. (#7807) +- Backends: SDL3: Update for API changes: SDL_GetClipboardText() memory ownership change. (#7801) - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) - Backends: SDL3: Update for API changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) [@wermipls] - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. From da3633632191d52f40d4dc26184c3cd9c2a0d0a7 Mon Sep 17 00:00:00 2001 From: Thomas Stehle Date: Mon, 22 Jul 2024 10:52:53 +0200 Subject: [PATCH 0236/2359] TabBar, Style: added style option for the size of the Tab-Bar Overline (#7804) Amend 21bda2e. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 5 ++++- imgui.h | 4 +++- imgui_demo.cpp | 2 ++ imgui_widgets.cpp | 4 ++-- 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 49206df8e..22f2b5e22 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -139,6 +139,8 @@ Other changes: can use the clipper without knowing the amount of items beforehand. (#1311) In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) as the end of your iteration loop to position the layout cursor correctly. This is done automatically if provided a count to Begin(). +- TabBar, Style: added style.TabBarOverlineSize / ImGuiStyleVar_TabBarOverlineSize to manipulate + thickness of the horizontal line over selectable tabs. [@DctrNoob] - Style: close button and collapse/window-menu button hover highlight made rectangular instead of round. - Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and diff --git a/imgui.cpp b/imgui.cpp index 6eb38f708..21b1cf14a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1269,12 +1269,13 @@ ImGuiStyle::ImGuiStyle() TabBorderSize = 0.0f; // Thickness of border around tabs. TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. + TabBarOverlineSize = 2.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar. TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees). TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. - SeparatorTextBorderSize = 3.0f; // Thickkness of border in SeparatorText() + SeparatorTextBorderSize = 3.0f; // Thickness of border in SeparatorText() SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). SeparatorTextPadding = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. @@ -1321,6 +1322,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX; + TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); @@ -3274,6 +3276,7 @@ static const ImGuiDataVarInfo GStyleVarInfo[] = { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize + { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign diff --git a/imgui.h b/imgui.h index 6c49460e1..993906a00 100644 --- a/imgui.h +++ b/imgui.h @@ -1711,6 +1711,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_TabBorderSize, // float TabBorderSize ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize + ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign @@ -2154,12 +2155,13 @@ struct ImGuiStyle float TabBorderSize; // Thickness of border around tabs. float TabMinWidthForCloseButton; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. float TabBarBorderSize; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. + float TabBarOverlineSize; // Thickness of tab-bar overline, which highlights the selected tab-bar. float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees). ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. - float SeparatorTextBorderSize; // Thickkness of border in SeparatorText() + float SeparatorTextBorderSize; // Thickness of border in SeparatorText() ImVec2 SeparatorTextAlign; // Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). ImVec2 SeparatorTextPadding; // Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. ImVec2 DisplayWindowPadding; // Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index fb28e3d54..e43bdc2b3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7633,6 +7633,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); + ImGui::SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 2.0f, "%.0f"); + ImGui::SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); ImGui::SeparatorText("Rounding"); ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 29635d3eb..e41f2f3cd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9917,13 +9917,13 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImDrawList* display_draw_list = window->DrawList; const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed)); TabItemBackground(display_draw_list, bb, flags, tab_col); - if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline)) + if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f) { float x_offset = IM_TRUNC(0.4f * style.TabRounding); if (x_offset < 2.0f * g.CurrentDpiScale) x_offset = 0.0f; float y_offset = 1.0f * g.CurrentDpiScale; - display_draw_list->AddLine(bb.GetTL() + ImVec2(x_offset, y_offset), bb.GetTR() + ImVec2(-x_offset, y_offset), GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline), 2.0f * g.CurrentDpiScale); + display_draw_list->AddLine(bb.GetTL() + ImVec2(x_offset, y_offset), bb.GetTR() + ImVec2(-x_offset, y_offset), GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline), style.TabBarOverlineSize); } RenderNavHighlight(bb, id); From fd994943c2dd70978d3c89c98d03fe5124e6a503 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Jul 2024 11:05:46 +0200 Subject: [PATCH 0237/2359] Added a comment hinting at how to set IMGUI_API for shared librairies on e.g. Linux, macOS (#7806) --- imconfig.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/imconfig.h b/imconfig.h index 62365fb9b..6e4c743d4 100644 --- a/imconfig.h +++ b/imconfig.h @@ -21,10 +21,11 @@ //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows // Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. -// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() -// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. -//#define IMGUI_API __declspec( dllexport ) -//#define IMGUI_API __declspec( dllimport ) +// - Windows DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() +// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. +//#define IMGUI_API __declspec(dllexport) // MSVC Windows: DLL export +//#define IMGUI_API __declspec(dllimport) // MSVC Windows: DLL import +//#define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names. //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS From c3dca77a19722d7ec0d2f7dfc1238b5166af2d46 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Jul 2024 14:06:14 +0200 Subject: [PATCH 0238/2359] Demo: rework Property Editor. --- docs/CHANGELOG.txt | 3 +- imgui.cpp | 6 ++ imgui.h | 4 +- imgui_demo.cpp | 165 +++++++++++++++++++++++++-------------------- 4 files changed, 102 insertions(+), 76 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 22f2b5e22..aad367e50 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -98,8 +98,7 @@ Other changes: - A helper ImGuiSelectionBasicStorage is provided to facilitate getting started in a typical app. - Documentation: - Wiki page https://github.com/ocornut/imgui/wiki/Multi-Select for API overview. - - Demo code. - - Headers are well commented. + - Demo code + headers are well commented. - Added BeginMultiSelect(), EndMultiSelect(), SetNextItemSelectionUserData(). - Added IsItemToggledSelection() for use if you need latest selection update during currnet iteration. - Added ImGuiMultiSelectIO and ImGuiSelectionRequest structures: diff --git a/imgui.cpp b/imgui.cpp index 21b1cf14a..c7b83d849 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15710,6 +15710,12 @@ void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); + if (flags & ImGuiWindowFlags_ChildWindow) + BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags, + (window->ChildFlags & ImGuiChildFlags_Border) ? "Border " : "", + (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "", + (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "", + (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : ""); BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : ""); BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); diff --git a/imgui.h b/imgui.h index 993906a00..0bf02b046 100644 --- a/imgui.h +++ b/imgui.h @@ -1090,7 +1090,7 @@ enum ImGuiWindowFlags_ // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90: Use ImGuiChildFlags_AlwaysUseWindowPadding in BeginChild() call. + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90.0: Use ImGuiChildFlags_AlwaysUseWindowPadding in BeginChild() call. ImGuiWindowFlags_NavFlattened = 1 << 31, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call. #endif }; @@ -1115,7 +1115,7 @@ enum ImGuiChildFlags_ ImGuiChildFlags_AutoResizeY = 1 << 5, // Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. ImGuiChildFlags_AlwaysAutoResize = 1 << 6, // Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. ImGuiChildFlags_FrameStyle = 1 << 7, // Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. - ImGuiChildFlags_NavFlattened = 1 << 8, // Share focus scope, allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. + ImGuiChildFlags_NavFlattened = 1 << 8, // [BETA] Share focus scope, allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. }; // Flags for ImGui::PushItemFlag() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e43bdc2b3..f91cc8532 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -269,7 +269,7 @@ struct ExampleTreeNode // Leaf Data bool HasData = false; // All leaves have data - bool DataMyBool = false; + bool DataMyBool = true; int DataMyInt = 128; ImVec2 DataMyVec2 = ImVec2(0.0f, 3.141592f); }; @@ -304,6 +304,7 @@ static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, Exampl } // Create example tree data +// (this allocates _many_ more times than most other code in either Dear ImGui or others demo) static ExampleTreeNode* ExampleTree_CreateDemoTree() { static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; @@ -8600,101 +8601,121 @@ static void ShowExampleAppLayout(bool* p_open) // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() //----------------------------------------------------------------------------- // Some of the interactions are a bit lack-luster: -// - We would want the table scrolling window to use NavFlattened. // - We would want pressing validating or leaving the filter to somehow restore focus. // - We may want more advanced filtering (child nodes) and clipper support: both will need extra work. +// - We would want to customize some keyboard interactions to easily keyboard navigate between the tree and the properties. //----------------------------------------------------------------------------- struct ExampleAppPropertyEditor { ImGuiTextFilter Filter; + ExampleTreeNode* VisibleNode = NULL; void Draw(ExampleTreeNode* root_node) { - ImGui::SetNextItemWidth(-FLT_MIN); - ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); - ImGui::PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); - if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_ARRAYSIZE(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) - Filter.Build(); - ImGui::PopItemFlag(); - - ImGuiTableFlags table_flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; - if (ImGui::BeginTable("##split", 2, table_flags)) + // Left side: draw tree + // - Currently using a table to benefit from RowBg feature + // - Using ImGuiChildFlags_NavFlattened exhibit a bug where clicking on root window decoration sets focus to root window + if (ImGui::BeginChild("##tree", ImVec2(300, 0), ImGuiChildFlags_ResizeX | ImGuiChildFlags_Border)) { - ImGui::TableSetupColumn("Object", ImGuiTableColumnFlags_WidthStretch, 1.0f); - ImGui::TableSetupColumn("Contents", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger - //ImGui::TableSetupScrollFreeze(0, 1); - //ImGui::TableHeadersRow(); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); + ImGui::PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); + if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_ARRAYSIZE(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) + Filter.Build(); + ImGui::PopItemFlag(); - for (ExampleTreeNode* node : root_node->Childs) - if (Filter.PassFilter(node->Name)) // Filter root node - DrawTreeNode(node); - ImGui::EndTable(); + if (ImGui::BeginTable("##bg", 1, ImGuiTableFlags_RowBg)) + { + for (ExampleTreeNode* node : root_node->Childs) + if (Filter.PassFilter(node->Name)) // Filter root node + DrawTreeNode(node); + ImGui::EndTable(); + } } + ImGui::EndChild(); + + // Right side: draw properties + ImGui::SameLine(); + + ImGui::BeginGroup(); // Lock X position + if (ExampleTreeNode* node = VisibleNode) + { + ImGui::Text("%s", node->Name); + ImGui::TextDisabled("UID: 0x%08X", node->UID); + ImGui::Separator(); + if (ImGui::BeginTable("##properties", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY)) + { + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger + + if (node && node->HasData) + { + // In a typical application, the structure description would be derived from a data-driven system. + // - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. + // - Limits and some details are hard-coded to simplify the demo. + for (const ExampleMemberInfo& field_desc : ExampleTreeNodeMemberInfos) + { + ImGui::TableNextRow(); + ImGui::PushID(field_desc.Name); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(field_desc.Name); + ImGui::TableNextColumn(); + void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset); + switch (field_desc.DataType) + { + case ImGuiDataType_Bool: + { + IM_ASSERT(field_desc.DataCount == 1); + ImGui::Checkbox("##Editor", (bool*)field_ptr); + break; + } + case ImGuiDataType_S32: + { + int v_min = INT_MIN, v_max = INT_MAX; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::DragScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, 1.0f, &v_min, &v_max); + break; + } + case ImGuiDataType_Float: + { + float v_min = 0.0f, v_max = 1.0f; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SliderScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, &v_min, &v_max); + break; + } + } + ImGui::PopID(); + } + } + ImGui::EndTable(); + } + } + ImGui::EndGroup(); } void DrawTreeNode(ExampleTreeNode* node) { - // Object tree node - ImGui::PushID(node->UID); ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::AlignTextToFramePadding(); + ImGui::TableNextColumn(); + ImGui::PushID(node->UID); ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None; - tree_flags |= ImGuiTreeNodeFlags_SpanAllColumns | ImGuiTreeNodeFlags_AllowOverlap; // Highlight whole row for visibility tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; // Standard opening mode as we are likely to want to add selection afterwards tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support - bool node_open = ImGui::TreeNodeEx("##Object", tree_flags, "%s", node->Name); - ImGui::TableSetColumnIndex(1); - ImGui::TextDisabled("UID: 0x%08X", node->UID); - - // Display child and data + if (node == VisibleNode) + tree_flags |= ImGuiTreeNodeFlags_Selected; + if (node->Childs.Size == 0) + tree_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet; + if (node->DataMyBool == false) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_TextDisabled]); + bool node_open = ImGui::TreeNodeEx("", tree_flags, "%s", node->Name); + if (node->DataMyBool == false) + ImGui::PopStyleColor(); + if (ImGui::IsItemFocused()) + VisibleNode = node; if (node_open) for (ExampleTreeNode* child : node->Childs) DrawTreeNode(child); - if (node_open && node->HasData) - { - // In a typical application, the structure description would be derived from a data-driven system. - // - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. - // - Limits and some details are hard-coded to simplify the demo. - // - Text and Selectable are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the selectable lines equal high. - for (const ExampleMemberInfo& field_desc : ExampleTreeNodeMemberInfos) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::AlignTextToFramePadding(); - ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop | ImGuiItemFlags_NoNav, true); - ImGui::Selectable(field_desc.Name, false, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); - ImGui::PopItemFlag(); - ImGui::TableSetColumnIndex(1); - ImGui::PushID(field_desc.Name); - void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset); - switch (field_desc.DataType) - { - case ImGuiDataType_Bool: - { - IM_ASSERT(field_desc.DataCount == 1); - ImGui::Checkbox("##Editor", (bool*)field_ptr); - break; - } - case ImGuiDataType_S32: - { - int v_min = INT_MIN, v_max = INT_MAX; - ImGui::SetNextItemWidth(-FLT_MIN); - ImGui::DragScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, 1.0f, &v_min, &v_max); - break; - } - case ImGuiDataType_Float: - { - float v_min = 0.0f, v_max = 1.0f; - ImGui::SetNextItemWidth(-FLT_MIN); - ImGui::SliderScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, &v_min, &v_max); - break; - } - } - ImGui::PopID(); - } - } if (node_open) ImGui::TreePop(); ImGui::PopID(); From 97ff9bd37038d2c00372eeb7438964e59cc53c7e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Jul 2024 15:04:25 +0200 Subject: [PATCH 0239/2359] Nav: fixed c licking window decorations (e.g. resize borders) from losing focused item when within a child window using ImGuiChildFlags_NavFlattened. In essence, using ImGuiFocusRequestFlags_RestoreFocusedChild here is a way to reduce changes caused by FocusWindow(), but it could be done more neatly. See amended "nav_flattened" test. --- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- imgui_widgets.cpp | 20 ++++++++++++++++---- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index aad367e50..150c2b609 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -134,6 +134,8 @@ Other changes: - Multi-Select (checkboxes) - Multi-Select (multiple scopes) - Multi-Select (advanced) +- Nav: fixed clicking window decorations (e.g. resize borders) from losing focused item when + within a child window using ImGuiChildFlags_NavFlattened. - Clipper: added SeekCursorForItem() function. When using ImGuiListClipper::Begin(INT_MAX) you can can use the clipper without knowing the amount of items beforehand. (#1311) In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) as the end of your iteration diff --git a/imgui.h b/imgui.h index 0bf02b046..fd0768a22 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19097 +#define IMGUI_VERSION_NUM 19098 #define IMGUI_HAS_TABLE /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e41f2f3cd..9a63a59bf 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -567,8 +567,14 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool SetActiveID(id, window); g.ActiveIdMouseButton = mouse_button_clicked; if (!(flags & ImGuiButtonFlags_NoNavFocus)) + { SetFocusID(id, window); - FocusWindow(window); + FocusWindow(window); + } + else + { + FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child + } } if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2)) { @@ -577,10 +583,16 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool ClearActiveID(); else SetActiveID(id, window); // Hold on ID - if (!(flags & ImGuiButtonFlags_NoNavFocus)) - SetFocusID(id, window); g.ActiveIdMouseButton = mouse_button_clicked; - FocusWindow(window); + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + { + SetFocusID(id, window); + FocusWindow(window); + } + else + { + FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child + } } } if (flags & ImGuiButtonFlags_PressedOnRelease) From 605c8d711019dd6eb98e8e1fbfe1b844410dda52 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Jul 2024 15:05:15 +0200 Subject: [PATCH 0240/2359] Demo: Property Editor: using ImGuiChildFlags_NavFlattened now that a bug is fixed. Fixed static analyzer. --- imgui_demo.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f91cc8532..7a3cdf0f4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8615,8 +8615,7 @@ struct ExampleAppPropertyEditor { // Left side: draw tree // - Currently using a table to benefit from RowBg feature - // - Using ImGuiChildFlags_NavFlattened exhibit a bug where clicking on root window decoration sets focus to root window - if (ImGui::BeginChild("##tree", ImVec2(300, 0), ImGuiChildFlags_ResizeX | ImGuiChildFlags_Border)) + if (ImGui::BeginChild("##tree", ImVec2(300, 0), ImGuiChildFlags_ResizeX | ImGuiChildFlags_Border | ImGuiChildFlags_NavFlattened)) { ImGui::SetNextItemWidth(-FLT_MIN); ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); @@ -8648,8 +8647,7 @@ struct ExampleAppPropertyEditor { ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger - - if (node && node->HasData) + if (node->HasData) { // In a typical application, the structure description would be derived from a data-driven system. // - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. @@ -8714,10 +8712,11 @@ struct ExampleAppPropertyEditor if (ImGui::IsItemFocused()) VisibleNode = node; if (node_open) + { for (ExampleTreeNode* child : node->Childs) DrawTreeNode(child); - if (node_open) ImGui::TreePop(); + } ImGui::PopID(); } }; From fe09ebbe0a1c8bb5f39f326658faa6bde75bb568 Mon Sep 17 00:00:00 2001 From: Cyao <94928179+cheyao@users.noreply.github.com> Date: Mon, 22 Jul 2024 21:10:35 +0200 Subject: [PATCH 0241/2359] Backends: OpenGL3: Fixed unsupported option warning with apple clang (#7810) --- backends/imgui_impl_opengl3.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index bbe96c420..7087a7c57 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -124,6 +124,7 @@ // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: ignore unknown flags #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used From 4d8c56c8133511b467bcba6483bc75b5a63ab985 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Jul 2024 13:40:23 +0200 Subject: [PATCH 0242/2359] Internals, TreeNode: indent all render block into its own scope (aim is to add a is_visible test there later) --- imgui.cpp | 1 + imgui_widgets.cpp | 99 ++++++++++++++++++++++++----------------------- 2 files changed, 51 insertions(+), 49 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c7b83d849..52fa2f16f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12048,6 +12048,7 @@ void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavM { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindow != NULL); + //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name); if (move_flags & ImGuiNavMoveFlags_IsTabbing) move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9a63a59bf..70ff174c2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6410,6 +6410,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanTextWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0) interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f); + // Compute open and multi-select states before ItemAdd() as it clear NextItem data. + bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); + // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. const float backup_clip_rect_min_x = window->ClipRect.Min.x; const float backup_clip_rect_max_x = window->ClipRect.Max.x; @@ -6418,18 +6421,14 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags window->ClipRect.Min.x = window->ParentWorkRect.Min.x; window->ClipRect.Max.x = window->ParentWorkRect.Max.x; } - - // Compute open and multi-select states before ItemAdd() as it clear NextItem data. - bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); - bool item_add = ItemAdd(interact_bb, id); - g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; - g.LastItemData.DisplayRect = frame_bb; - + const bool is_visible = ItemAdd(interact_bb, id); if (span_all_columns) { window->ClipRect.Min.x = backup_clip_rect_min_x; window->ClipRect.Max.x = backup_clip_rect_max_x; } + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; + g.LastItemData.DisplayRect = frame_bb; // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsBackHere enabled: // Store data for the current depth to allow returning to this node from any child item. @@ -6444,7 +6443,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags } const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; - if (!item_add) + if (!is_visible) { if (store_tree_node_stack_data && is_open) TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() @@ -6566,53 +6565,55 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render - const ImU32 text_col = GetColorU32(ImGuiCol_Text); - ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_Compact; - if (is_multi_select) - nav_highlight_flags |= ImGuiNavHighlightFlags_AlwaysDraw; // Always show the nav rectangle - if (display_frame) { - // Framed type - const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); - RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding); - RenderNavHighlight(frame_bb, id, nav_highlight_flags); - if (flags & ImGuiTreeNodeFlags_Bullet) - RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col); - else if (!is_leaf) - RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 1.0f); - else // Leaf without bullet, left-adjusted text - text_pos.x -= text_offset_x -padding.x; - if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton) - frame_bb.Max.x -= g.FontSize + style.FramePadding.x; - if (g.LogEnabled) - LogSetNextTextDecoration("###", "###"); - } - else - { - // Unframed typed for tree nodes - if (hovered || selected) + const ImU32 text_col = GetColorU32(ImGuiCol_Text); + ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_Compact; + if (is_multi_select) + nav_highlight_flags |= ImGuiNavHighlightFlags_AlwaysDraw; // Always show the nav rectangle + if (display_frame) { + // Framed type const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); - RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false); + RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding); + RenderNavHighlight(frame_bb, id, nav_highlight_flags); + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col); + else if (!is_leaf) + RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 1.0f); + else // Leaf without bullet, left-adjusted text + text_pos.x -= text_offset_x - padding.x; + if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton) + frame_bb.Max.x -= g.FontSize + style.FramePadding.x; + if (g.LogEnabled) + LogSetNextTextDecoration("###", "###"); } - RenderNavHighlight(frame_bb, id, nav_highlight_flags); - 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 - 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); + else + { + // Unframed typed for tree nodes + if (hovered || selected) + { + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false); + } + RenderNavHighlight(frame_bb, id, nav_highlight_flags); + 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 - 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); + } + + if (span_all_columns) + TablePopBackgroundChannel(); + + // Label + if (display_frame) + RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); + else + RenderText(text_pos, label, label_end, false); } - if (span_all_columns) - TablePopBackgroundChannel(); - - // Label - if (display_frame) - RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); - else - RenderText(text_pos, label, label_end, false); - if (store_tree_node_stack_data && is_open) TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) From 1230b4410cd0e0111dd85f7c20e2606208dc1a99 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Jul 2024 14:11:26 +0200 Subject: [PATCH 0243/2359] Internals, TreeNode, Selectable: tweak span_all_columns paths for clarity. --- imgui_widgets.cpp | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 70ff174c2..c01a89460 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6413,20 +6413,22 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags // Compute open and multi-select states before ItemAdd() as it clear NextItem data. bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); - // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. - const float backup_clip_rect_min_x = window->ClipRect.Min.x; - const float backup_clip_rect_max_x = window->ClipRect.Max.x; + bool is_visible; if (span_all_columns) { + // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. + 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; window->ClipRect.Max.x = window->ParentWorkRect.Max.x; - } - const bool is_visible = ItemAdd(interact_bb, id); - if (span_all_columns) - { + is_visible = ItemAdd(interact_bb, id); window->ClipRect.Min.x = backup_clip_rect_min_x; window->ClipRect.Max.x = backup_clip_rect_max_x; } + else + { + is_visible = ItemAdd(interact_bb, id); + } g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; g.LastItemData.DisplayRect = frame_bb; @@ -6796,23 +6798,24 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl } //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); } - // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. - const float backup_clip_rect_min_x = window->ClipRect.Min.x; - const float backup_clip_rect_max_x = window->ClipRect.Max.x; + const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; + const ImGuiItemFlags extra_item_flags = disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None; + bool is_visible; if (span_all_columns) { + // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. + 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; window->ClipRect.Max.x = window->ParentWorkRect.Max.x; - } - - const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; - const bool is_visible = ItemAdd(bb, id, NULL, disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None); - - if (span_all_columns) - { + is_visible = ItemAdd(bb, id, NULL, extra_item_flags); window->ClipRect.Min.x = backup_clip_rect_min_x; window->ClipRect.Max.x = backup_clip_rect_max_x; } + else + { + is_visible = ItemAdd(bb, id, NULL, extra_item_flags); + } const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; if (!is_visible) From 97c6f4047ccc01367e29f6852e9cecf1e157d26b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Jul 2024 14:16:41 +0200 Subject: [PATCH 0244/2359] CollapsingHeader: left-side outer extend matches right-side one (moved left by one pixel) Amend c3a348aa2 --- imgui_widgets.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c01a89460..068337e9c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6396,10 +6396,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags frame_bb.Max.y = window->DC.CursorPos.y + frame_height; if (display_frame) { - // Framed header expand a little outside the default padding, to the edge of InnerClipRect - // (FIXME: May remove this at some point and make InnerClipRect align with WindowPadding.x instead of WindowPadding.x*0.5f) - frame_bb.Min.x -= IM_TRUNC(window->WindowPadding.x * 0.5f - 1.0f); - frame_bb.Max.x += IM_TRUNC(window->WindowPadding.x * 0.5f); + const float outer_extend = IM_TRUNC(window->WindowPadding.x * 0.5f); // Framed header expand a little outside of current limits + frame_bb.Min.x -= outer_extend; + frame_bb.Max.x += outer_extend; } ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y); @@ -6783,7 +6782,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const ImVec2 text_max(min_x + size.x, pos.y + size.y); // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable. - // FIXME: Not part of layout so not included in clipper calculation, but ItemSize currenty doesn't allow offsetting CursorPos. + // FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos. ImRect bb(min_x, pos.y, text_max.x, text_max.y); if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) { From b67b375ae693072ba23963f7897057e76f3a7327 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Jul 2024 15:28:03 +0200 Subject: [PATCH 0245/2359] Debug Log: fixed incorrect checkbox layout when partially clipped., doesn't parse 64-bits hex value as ImGuiID lookups. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 4 ++-- imgui_internal.h | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 150c2b609..1247ef94a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -147,6 +147,7 @@ Other changes: Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. - Debug Tools: Debug Log: Added "Configure Outputs.." button. (#5855) +- Debug Tools: Debug Log: Fixed incorrect checkbox layout when partially clipped. - Demo: Reworked "Property Editor" demo in a manner that more ressemble the tree data and struct description data that a real application would want to use. - Backends: Win32: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. diff --git a/imgui.cpp b/imgui.cpp index 52fa2f16f..7b922fdd7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15827,7 +15827,7 @@ static void SameLineOrWrap(const ImVec2& size) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y); - if (window->ClipRect.Contains(ImRect(pos, pos + size))) + if (window->WorkRect.Contains(ImRect(pos, pos + size))) ImGui::SameLine(); } @@ -15921,7 +15921,7 @@ void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const cha for (const char* p = line_begin; p <= line_end - 10; p++) { ImGuiID id = 0; - if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1) + 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); diff --git a/imgui_internal.h b/imgui_internal.h index f2c5312ea..b307adcde 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -388,6 +388,7 @@ IM_MSVC_RUNTIME_CHECKS_OFF static inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; } static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } +static inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } IM_MSVC_RUNTIME_CHECKS_RESTORE // Helpers: Formatting From e3da939b86f8cbf30a4d3e39b0cab2413c67dd03 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Jul 2024 18:41:51 +0200 Subject: [PATCH 0246/2359] Groups, Tables: fixed EndGroup() failing to correctly capture current table occupied size. (#7543) See "layout_group_endtable" test. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 8 ++++---- imgui.h | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1247ef94a..fde5c5144 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -140,6 +140,7 @@ Other changes: can use the clipper without knowing the amount of items beforehand. (#1311) In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) as the end of your iteration loop to position the layout cursor correctly. This is done automatically if provided a count to Begin(). +- Groups, Tables: fixed EndGroup() failing to correctly capture current table occupied size. (#7543) - TabBar, Style: added style.TabBarOverlineSize / ImGuiStyleVar_TabBarOverlineSize to manipulate thickness of the horizontal line over selectable tabs. [@DctrNoob] - Style: close button and collapse/window-menu button hover highlight made rectangular instead of round. diff --git a/imgui.cpp b/imgui.cpp index 7b922fdd7..31f65a9d4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10686,11 +10686,11 @@ void ImGui::EndGroup() if (window->DC.IsSetPos) ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); - ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos)); - + // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543) + ImRect group_bb(group_data.BackupCursorPos, ImMax(ImMax(window->DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos)); window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine; - window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); + window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, group_bb.Max); window->DC.Indent = group_data.BackupIndent; window->DC.GroupOffset = group_data.BackupGroupOffset; window->DC.CurrLineSize = group_data.BackupCurrLineSize; @@ -10705,7 +10705,7 @@ void ImGui::EndGroup() return; } - window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ItemSize(group_bb.GetSize()); ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop); diff --git a/imgui.h b/imgui.h index fd0768a22..47626ad6f 100644 --- a/imgui.h +++ b/imgui.h @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19098 +#define IMGUI_VERSION_NUM 19099 #define IMGUI_HAS_TABLE /* From 79b77d91c98e36c1dd487516564cec716ddd94f1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Jul 2024 18:43:54 +0200 Subject: [PATCH 0247/2359] MultiSelect: sequential SetRange merging not generally handled by box-select path, useful for others. --- imgui_internal.h | 3 ++- imgui_widgets.cpp | 35 ++++++++++++++++++++++------------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index b307adcde..85aaa19bc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1751,6 +1751,7 @@ struct IMGUI_API ImGuiMultiSelectTempData ImGuiMultiSelectFlags Flags; ImVec2 ScopeRectMin; ImVec2 BackupCursorMaxPos; + ImGuiSelectionUserData LastSubmittedItem; // Copy of last submitted item data, used to merge output ranges. ImGuiID BoxSelectId; ImGuiKeyChord KeyMods; ImS8 LoopRequestSetAll; // -1: no operation, 0: clear all, 1: select all. @@ -1760,7 +1761,6 @@ struct IMGUI_API ImGuiMultiSelectTempData bool NavIdPassedBy; bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. - ImGuiSelectionUserData BoxSelectLastitem; // Copy of last submitted item data, used to merge output ranges. ImGuiMultiSelectTempData() { Clear(); } void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. @@ -3408,6 +3408,7 @@ namespace ImGui // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); + IMGUI_API void MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item); inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.ID == id && g.BoxSelectState.IsActive) ? &g.BoxSelectState : NULL; } inline ImGuiMultiSelectState* GetMultiSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return g.MultiSelectStorage.GetByKey(id); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 068337e9c..183c7fbe2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7069,7 +7069,7 @@ static int ImStrimatchlen(const char* s1, const char* s1_end, const char* s2) // When SingleCharMode is set: // - it is better to NOT display a tooltip of other on-screen display indicator. // - the index of the currently focused item is required. -// if your SetNextItemSelectionData() values are indices, you can obtain it from ImGuiMultiSelectIO::NavIdItem, otherwise from g.NavLastValidSelectionUserData. +// if your SetNextItemSelectionUserData() values are indices, you can obtain it from ImGuiMultiSelectIO::NavIdItem, otherwise from g.NavLastValidSelectionUserData. int ImGui::TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx) { if (req == NULL || req->SelectRequest == false) // Support NULL parameter so both calls can be done from same spot. @@ -7397,7 +7397,6 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) { ms->BoxSelectId = GetID("##BoxSelect"); - ms->BoxSelectLastitem = ImGuiSelectionUserData_Invalid; if (BeginBoxSelect(window, ms->BoxSelectId, flags)) request_clear |= bs->RequestClear; } @@ -7432,6 +7431,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel ms->IO.Requests.push_back(req); } ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1; + ms->LastSubmittedItem = ImGuiSelectionUserData_Invalid; if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) DebugLogMultiSelectRequests("BeginMultiSelect", &ms->IO); @@ -7694,17 +7694,10 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) else { selected = !selected; - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, +1, item_data, item_data }; - // Merge continuous ranges (unless NoRangeSelect is set) - ImGuiSelectionRequest* prev = ms->IO.Requests.Size > 0 ? &ms->IO.Requests.Data[ms->IO.Requests.Size - 1] : NULL; - if (prev && prev->Type == ImGuiSelectionRequestType_SetRange && prev->RangeLastItem == ms->BoxSelectLastitem && prev->Selected == selected && (ms->Flags & ImGuiMultiSelectFlags_NoRangeSelect) == 0) - prev->RangeLastItem = item_data; // Merge span into same request - else - ms->IO.Requests.push_back(req); + MultiSelectAddSetRange(ms, selected, +1, item_data, item_data); } storage->LastSelectionSize = ImMax(storage->LastSelectionSize + 1, 1); } - ms->BoxSelectLastitem = item_data; } // Right-click handling. @@ -7804,9 +7797,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) range_selected = selected; range_direction = +1; } - ImGuiSelectionUserData range_dst_item = item_data; - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, range_selected, (ImS8)range_direction, (range_direction > 0) ? storage->RangeSrcItem : range_dst_item, (range_direction > 0) ? range_dst_item : storage->RangeSrcItem }; - ms->IO.Requests.push_back(req); + MultiSelectAddSetRange(ms, range_selected, range_direction, storage->RangeSrcItem, item_data); } // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) @@ -7821,11 +7812,29 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } if (storage->NavIdItem == item_data) ms->NavIdPassedBy = true; + ms->LastSubmittedItem = item_data; *p_selected = selected; *p_pressed = pressed; } +void ImGui::MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item) +{ + // Merge contiguous spans into same request (unless NoRangeSelect is set which guarantees single-item ranges) + if (ms->IO.Requests.Size > 0 && first_item == last_item && (ms->Flags & ImGuiMultiSelectFlags_NoRangeSelect) == 0) + { + ImGuiSelectionRequest* prev = &ms->IO.Requests.Data[ms->IO.Requests.Size - 1]; + if (prev->Type == ImGuiSelectionRequestType_SetRange && prev->RangeLastItem == ms->LastSubmittedItem && prev->Selected == selected) + { + prev->RangeLastItem = last_item; + return; + } + } + + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, (ImS8)range_dir, (range_dir > 0) ? first_item : last_item, (range_dir > 0) ? last_item : first_item }; + ms->IO.Requests.push_back(req); // Add new request +} + void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage) { #ifndef IMGUI_DISABLE_DEBUG_TOOLS From a285835ac4a293831852b0d5dd671401fd2c7412 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Jul 2024 19:00:09 +0200 Subject: [PATCH 0248/2359] MultiSelect: add internal MultiSelectAddSetAll() helper. --- imgui_internal.h | 1 + imgui_widgets.cpp | 28 ++++++++++++---------------- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 85aaa19bc..3bcca8500 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3408,6 +3408,7 @@ namespace ImGui // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); + IMGUI_API void MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected); IMGUI_API void MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item); inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.ID == id && g.BoxSelectState.IsActive) ? &g.BoxSelectState : NULL; } inline ImGuiMultiSelectState* GetMultiSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return g.MultiSelectStorage.GetByKey(id); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 183c7fbe2..e9cf6f0f7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7424,12 +7424,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel } if (request_clear || request_select_all) - { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, request_select_all, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; - if (!request_select_all) - storage->LastSelectionSize = 0; - ms->IO.Requests.push_back(req); - } + MultiSelectAddSetAll(ms, request_select_all); ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1; ms->LastSubmittedItem = ImGuiSelectionUserData_Invalid; @@ -7496,11 +7491,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid) if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None) - { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; - ms->IO.Requests.resize(0); - ms->IO.Requests.push_back(req); - } + MultiSelectAddSetAll(ms, false); } // Courtesy nav wrapping helper flag @@ -7755,11 +7746,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl) request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again. if (request_clear) - { - ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, false, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; - ms->IO.Requests.resize(0); - ms->IO.Requests.push_back(req); - } + MultiSelectAddSetAll(ms, false); } int range_direction; @@ -7818,6 +7805,15 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) *p_pressed = pressed; } +void ImGui::MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected) +{ + ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, selected, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; + ms->IO.Requests.resize(0); // Can always clear previous requests + ms->IO.Requests.push_back(req); // Add new request + if (selected == false) + ms->Storage->LastSelectionSize = 0; +} + void ImGui::MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item) { // Merge contiguous spans into same request (unless NoRangeSelect is set which guarantees single-item ranges) From 237165a9359518573f67cabf2e2f6d648f351244 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Jul 2024 19:14:54 +0200 Subject: [PATCH 0249/2359] MultiSelect: fixed an issue caused by previous commit. Amend a285835. Breaks box-select. --- imgui_widgets.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e9cf6f0f7..7739f3036 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7424,7 +7424,11 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel } if (request_clear || request_select_all) + { MultiSelectAddSetAll(ms, request_select_all); + if (!request_select_all) + storage->LastSelectionSize = 0; + } ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1; ms->LastSubmittedItem = ImGuiSelectionUserData_Invalid; @@ -7810,8 +7814,6 @@ void ImGui::MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected) ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, selected, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid }; ms->IO.Requests.resize(0); // Can always clear previous requests ms->IO.Requests.push_back(req); // Add new request - if (selected == false) - ms->Storage->LastSelectionSize = 0; } void ImGui::MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item) From ed356dc181217439af31e5883fbe58906d0ec1cb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 25 Jul 2024 14:46:25 +0200 Subject: [PATCH 0250/2359] MultiSelect: BoxSelect: fixed box-select from void setting nav id multiple times. --- imgui_internal.h | 1 + imgui_widgets.cpp | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 3bcca8500..29420b6b6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1719,6 +1719,7 @@ struct ImGuiBoxSelectState bool IsActive; bool IsStarting; bool IsStartedFromVoid; // Starting click was not from an item. + bool IsStartedSetNavIdOnce; bool RequestClear; ImGuiKeyChord KeyMods : 16; // Latched key-mods for box-select logic. ImVec2 StartPosRel; // Start position in window-contents relative space (to support scrolling) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7739f3036..1a11e3834 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7161,6 +7161,7 @@ static void BoxSelectPreStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_ite bs->ID = id; bs->IsStarting = true; // Consider starting box-select. bs->IsStartedFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid); + bs->IsStartedSetNavIdOnce = bs->IsStartedFromVoid; bs->KeyMods = g.IO.KeyMods; bs->StartPosRel = bs->EndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos); bs->ScrollAccum = ImVec2(0.0f, 0.0f); @@ -7682,9 +7683,10 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect); if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr)) { - if (storage->LastSelectionSize <= 0 && bs->IsStartedFromVoid) + if (storage->LastSelectionSize <= 0 && bs->IsStartedSetNavIdOnce) { pressed = true; // First item act as a pressed: code below will emit selection request and set NavId (whatever we emit here will be overridden anyway) + bs->IsStartedSetNavIdOnce = false; } else { From 55f54fa512f81885cafcd2c701dcff26c328b146 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 25 Jul 2024 15:10:04 +0200 Subject: [PATCH 0251/2359] Internals: comment out obsolete g.ActiveIdUsingNavInputMask obsoleted two years ago. (#4921, #4858, #787, #1599, #323) Use SetKeyOwner(ImGuiKey_Escape, g.ActiveId); instead. Amend 8b8a61bd --- imgui.cpp | 20 -------------------- imgui_internal.h | 9 ++------- 2 files changed, 2 insertions(+), 27 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 31f65a9d4..9e93b8434 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4040,9 +4040,6 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet) g.ActiveIdUsingNavDirMask = 0x00; g.ActiveIdUsingAllKeyboardKeys = false; -#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO - g.ActiveIdUsingNavInputMask = 0x00; -#endif } void ImGui::ClearActiveID() @@ -4806,25 +4803,8 @@ void ImGui::NewFrame() { g.ActiveIdUsingNavDirMask = 0x00; g.ActiveIdUsingAllKeyboardKeys = false; -#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO - g.ActiveIdUsingNavInputMask = 0x00; -#endif } -#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO - if (g.ActiveId == 0) - g.ActiveIdUsingNavInputMask = 0; - else if (g.ActiveIdUsingNavInputMask != 0) - { - // If your custom widget code used: { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); } - // Since IMGUI_VERSION_NUM >= 18804 it should be: { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); } - if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel)) - SetKeyOwner(ImGuiKey_Escape, g.ActiveId); - if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel)) - IM_ASSERT(0); // Other values unsupported - } -#endif - // Record when we have been stationary as this state is preserved while over same item. // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values. // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function. diff --git a/imgui_internal.h b/imgui_internal.h index 29420b6b6..6fa1ee799 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2081,9 +2081,7 @@ struct ImGuiContext ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) bool ActiveIdUsingAllKeyboardKeys; // Active widget will want to read all keyboard keys inputs. (this is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations) ImGuiKeyChord DebugBreakInShortcutRouting; // Set to break in SetShortcutRouting()/Shortcut() calls. -#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO - ImU32 ActiveIdUsingNavInputMask; // If you used this. Since (IMGUI_VERSION_NUM >= 18804) : 'g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel);' becomes 'SetKeyOwner(ImGuiKey_Escape, g.ActiveId) and/or SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId);' -#endif + //ImU32 ActiveIdUsingNavInputMask; // [OBSOLETE] Since (IMGUI_VERSION_NUM >= 18804) : 'g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel);' becomes --> 'SetKeyOwner(ImGuiKey_Escape, g.ActiveId) and/or SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId);' // Next window/item data ImGuiID CurrentFocusScopeId; // Value for currently appending items == g.FocusScopeStack.back(). Not to be mistaken with g.NavFocusScopeId. @@ -2395,9 +2393,6 @@ struct ImGuiContext ActiveIdUsingNavDirMask = 0x00; ActiveIdUsingAllKeyboardKeys = false; -#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO - ActiveIdUsingNavInputMask = 0x00; -#endif CurrentFocusScopeId = 0; CurrentItemFlags = ImGuiItemFlags_None; @@ -3196,7 +3191,7 @@ namespace ImGui //#endif // Basic Accessors - inline ImGuiItemStatusFlags GetItemStatusFlags(){ ImGuiContext& g = *GImGui; return g.LastItemData.StatusFlags; } + inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.StatusFlags; } inline ImGuiItemFlags GetItemFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.InFlags; } inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } From aad86b8756b7cde30fd70ac87e6325257e1a3e27 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 25 Jul 2024 15:50:30 +0200 Subject: [PATCH 0252/2359] Obsoleted GetWindowContentRegionMin() and GetWindowContentRegionMax(). You should never need those functions. You can do everything with GetCursorScreenPos() and GetContentRegionAvail(). --- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 10 +++++++++- imgui.h | 13 +++++++------ imgui_demo.cpp | 2 +- 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fde5c5144..42c2cea37 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,12 @@ Breaking changes: - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); It is expected that for a vast majority of users this is automatically set by core library and/or platform backend so it won't have any effect. +- Obsoleted GetWindowContentRegionMin() and GetWindowContentRegionMax(). + You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail(). + Also consider that if you are using GetWindowPos() and GetCursorPos() you may also be making things + unnecessarily complicated. You can do everything with GetCursorScreenPos() and GetContentRegionAvail()!! + - GetWindowContentRegionMax().x - GetCursorPos().x --> GetContentRegionAvail().x + - GetWindowContentRegionMax().x + GetWindowPos().x --> GetCursorScreenPos().x + GetContentRegionAvail().x - Item flag changes: - Obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag()/PopItemFlag() with ImGuiItemFlags_ButtonRepeat. Kept inline redirecting functions (will obsolete). diff --git a/imgui.cpp b/imgui.cpp index 9e93b8434..626031514 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,11 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/07/25 (1.91.0) - obsoleted GetWindowContentRegionMin() and GetWindowContentRegionMax(). You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail(). + - instead of: GetWindowContentRegionMax().x - GetCursorPos().x + - you can use: GetContentRegionAvail().x + - instead of: GetWindowContentRegionMax().x + GetWindowPos().x + - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x (from left edge of window) - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573) (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors) - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag(). @@ -10609,7 +10614,9 @@ ImVec2 ImGui::GetContentRegionAvail() return GetContentRegionMaxAbs() - window->DC.CursorPos; } -// In window space (not screen space!) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()! +// They are bizarre local-coordinates which don't play well with scrolling. ImVec2 ImGui::GetWindowContentRegionMin() { ImGuiWindow* window = GImGui->CurrentWindow; @@ -10621,6 +10628,7 @@ ImVec2 ImGui::GetWindowContentRegionMax() ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentRegionRect.Max - window->Pos; } +#endif // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated. diff --git a/imgui.h b/imgui.h index 47626ad6f..26aed79bb 100644 --- a/imgui.h +++ b/imgui.h @@ -392,10 +392,10 @@ namespace ImGui IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options. IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives - IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (note: it is unlikely you need to use this. Consider using current layout pos instead, GetCursorScreenPos()) - IMGUI_API ImVec2 GetWindowSize(); // get current window size (note: it is unlikely you need to use this. Consider using GetCursorScreenPos() and e.g. GetContentRegionAvail() instead) - IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x) - IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) + IMGUI_API ImVec2 GetWindowSize(); // get current window size (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) + IMGUI_API float GetWindowWidth(); // get current window width (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().x. + IMGUI_API float GetWindowHeight(); // get current window height (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().y. // Window manipulation // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). @@ -422,8 +422,6 @@ namespace ImGui // - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion) IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates - IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min for the full window (roughly (0,0)-Scroll), in window coordinates - IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max for the full window (roughly (0,0)+Size-Scroll) where Size can be overridden with SetNextWindowContentSize(), in window coordinates // Windows Scrolling // - Any change of Scroll will be applied at the beginning of next frame in the first call to Begin(). @@ -473,6 +471,7 @@ namespace ImGui // - By "cursor" we mean the current output position. // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. + // - YOU CAN DO 99% OF WHAT YOU NEED WITH ONLY GetCursorScreenPos() and GetContentRegionAvail(). // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: // - Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. -> this is the preferred way forward. // - Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos() @@ -3504,6 +3503,8 @@ namespace ImGui static inline void PopButtonRepeat() { PopItemFlag(); } static inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } static inline void PopTabStop() { PopItemFlag(); } + IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! + IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! // OBSOLETED in 1.90.0 (from September 2023) static inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } static inline void EndChildFrame() { EndChild(); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7a3cdf0f4..8684bd0c6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3918,7 +3918,7 @@ static void ShowDemoWindowLayout() ImGui::Text("Manual wrapping:"); ImGuiStyle& style = ImGui::GetStyle(); int buttons_count = 20; - float window_visible_x2 = ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x; + float window_visible_x2 = ImGui::GetCursorScreenPos().x + ImGui::GetContentRegionAvail().x; for (int n = 0; n < buttons_count; n++) { ImGui::PushID(n); From 055b2e80fbe1f13b81ef6e092381530eaf68fc36 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 25 Jul 2024 16:02:59 +0200 Subject: [PATCH 0253/2359] Moved everyone's best friend GetContentRegionAvail() to a more prominent position. --- imgui.cpp | 1 - imgui.h | 14 +++++--------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 626031514..ace1d0276 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10315,7 +10315,6 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // - GetContentRegionMax() // - GetContentRegionMaxAbs() [Internal] // - GetContentRegionAvail(), -// - GetWindowContentRegionMin(), GetWindowContentRegionMax() // - BeginGroup() // - EndGroup() // Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns. diff --git a/imgui.h b/imgui.h index 26aed79bb..e98399371 100644 --- a/imgui.h +++ b/imgui.h @@ -417,12 +417,6 @@ namespace ImGui 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. - // Content region - // - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful. - // - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion) - IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() - IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates - // Windows Scrolling // - Any change of Scroll will be applied at the beginning of next frame in the first call to Begin(). // - You may instead use SetNextWindowScroll() prior to calling Begin() to avoid this delay, as an alternative to using SetScrollX()/SetScrollY(). @@ -474,10 +468,12 @@ namespace ImGui // - YOU CAN DO 99% OF WHAT YOU NEED WITH ONLY GetCursorScreenPos() and GetContentRegionAvail(). // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: // - Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. -> this is the preferred way forward. - // - Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos() - // - GetCursorScreenPos() = GetCursorPos() + GetWindowPos(). GetWindowPos() is almost only ever useful to convert from window-local to absolute coordinates. - IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute coordinates (prefer using this, also more useful to work with ImDrawList API). + // - Window-local coordinates: SameLine(offset), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), PushTextWrapPos() + // - GetCursorScreenPos() = GetCursorPos() + GetWindowPos(). GetWindowPos() is almost only ever useful to convert from window-local to absolute coordinates. Try not to use it. + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute coordinates. THIS IS YOUR BEST FRIEND (prefer using this rather than GetCursorPos(), also more useful to work with ImDrawList API). IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute coordinates + IMGUI_API ImVec2 GetContentRegionAvail(); // available space from current position. THIS IS YOUR BEST FRIEND. + IMGUI_API ImVec2 GetContentRegionMax(); // [window-local] current content boundaries (e.g. window boundaries including scrolling, or current column boundaries) IMGUI_API ImVec2 GetCursorPos(); // [window-local] cursor position in window coordinates (relative to window position) IMGUI_API float GetCursorPosX(); // [window-local] " IMGUI_API float GetCursorPosY(); // [window-local] " From 4227402b2fe46a24663fd16efd042a8527d2bbed Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 25 Jul 2024 16:10:18 +0200 Subject: [PATCH 0254/2359] Internals: removed GetContentRegionMaxAbs() which was only meaningfully used in place of GetContentRegionAvail(). --- imgui.cpp | 40 ++++++++++++++-------------------------- imgui_internal.h | 1 - 2 files changed, 14 insertions(+), 27 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ace1d0276..40de62165 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10313,7 +10313,6 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // - GetFrameHeight() // - GetFrameHeightWithSpacing() // - GetContentRegionMax() -// - GetContentRegionMaxAbs() [Internal] // - GetContentRegionAvail(), // - BeginGroup() // - EndGroup() @@ -10530,8 +10529,8 @@ float ImGui::CalcItemWidth() w = window->DC.ItemWidth; if (w < 0.0f) { - float region_max_x = GetContentRegionMaxAbs().x; - w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w); + float region_avail_x = GetContentRegionAvail().x; + w = ImMax(1.0f, region_avail_x + w); } w = IM_TRUNC(w); return w; @@ -10543,22 +10542,19 @@ float ImGui::CalcItemWidth() // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - - ImVec2 region_max; + ImVec2 avail; if (size.x < 0.0f || size.y < 0.0f) - region_max = GetContentRegionMaxAbs(); + avail = GetContentRegionAvail(); if (size.x == 0.0f) size.x = default_w; else if (size.x < 0.0f) - size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x); + size.x = ImMax(4.0f, avail.x + size.x); // <-- size.x is negative here so we are subtracting if (size.y == 0.0f) size.y = default_h; else if (size.y < 0.0f) - size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y); + size.y = ImMax(4.0f, avail.y + size.y); // <-- size.y is negative here so we are subtracting return size; } @@ -10587,8 +10583,15 @@ float ImGui::GetFrameHeightWithSpacing() return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; } -// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience! +ImVec2 ImGui::GetContentRegionAvail() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max; + return mx - window->DC.CursorPos; +} +// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience! // FIXME: This is in window space (not screen space!). ImVec2 ImGui::GetContentRegionMax() { @@ -10598,21 +10601,6 @@ ImVec2 ImGui::GetContentRegionMax() return mx - window->Pos; } -// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features. -ImVec2 ImGui::GetContentRegionMaxAbs() -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max; - return mx; -} - -ImVec2 ImGui::GetContentRegionAvail() -{ - ImGuiWindow* window = GImGui->CurrentWindow; - return GetContentRegionMaxAbs() - window->DC.CursorPos; -} - #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()! // They are bizarre local-coordinates which don't play well with scrolling. diff --git a/imgui_internal.h b/imgui_internal.h index 6fa1ee799..6cee07857 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3217,7 +3217,6 @@ namespace ImGui IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); IMGUI_API void PushMultiItemsWidths(int components, float width_full); - IMGUI_API ImVec2 GetContentRegionMaxAbs(); IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); // Parameter stacks (shared) From b20f62b162e5f1e44748eb768f6b126a25ec29de Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 25 Jul 2024 16:18:46 +0200 Subject: [PATCH 0255/2359] Obsoleted GetContentRegionMax(). --- docs/CHANGELOG.txt | 10 ++++++---- imgui.cpp | 21 ++++++++++----------- imgui.h | 13 +++++++------ 3 files changed, 23 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 42c2cea37..eb98554ce 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,12 +46,14 @@ Breaking changes: - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); It is expected that for a vast majority of users this is automatically set by core library and/or platform backend so it won't have any effect. -- Obsoleted GetWindowContentRegionMin() and GetWindowContentRegionMax(). - You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail(). - Also consider that if you are using GetWindowPos() and GetCursorPos() you may also be making things - unnecessarily complicated. You can do everything with GetCursorScreenPos() and GetContentRegionAvail()!! +- Obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). + You should never need those functions! You can do everything in less a confusing manner by only + using GetCursorScreenPos() and GetContentRegionAvail(). Also always consider that if you are using + GetWindowPos() and GetCursorPos() you may also be making things unnecessarily complicated. + I repeat: You can do everything with GetCursorScreenPos() and GetContentRegionAvail()!! - GetWindowContentRegionMax().x - GetCursorPos().x --> GetContentRegionAvail().x - GetWindowContentRegionMax().x + GetWindowPos().x --> GetCursorScreenPos().x + GetContentRegionAvail().x + - GetContentRegionMax() --> GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in weird local coordinates - Item flag changes: - Obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag()/PopItemFlag() with ImGuiItemFlags_ButtonRepeat. Kept inline redirecting functions (will obsolete). diff --git a/imgui.cpp b/imgui.cpp index 40de62165..a74ae56c1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,11 +430,14 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - - 2024/07/25 (1.91.0) - obsoleted GetWindowContentRegionMin() and GetWindowContentRegionMax(). You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail(). + - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). + you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way. - instead of: GetWindowContentRegionMax().x - GetCursorPos().x - you can use: GetContentRegionAvail().x - instead of: GetWindowContentRegionMax().x + GetWindowPos().x - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x (from left edge of window) + - instead of: GetContentRegionMax() + - you cna use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in weird local coordinates - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573) (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors) - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag(). @@ -10591,19 +10594,15 @@ ImVec2 ImGui::GetContentRegionAvail() return mx - window->DC.CursorPos; } -// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience! -// FIXME: This is in window space (not screen space!). -ImVec2 ImGui::GetContentRegionMax() -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max; - return mx - window->Pos; -} - #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()! // They are bizarre local-coordinates which don't play well with scrolling. +ImVec2 ImGui::GetContentRegionMax() +{ + return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos(); +} + ImVec2 ImGui::GetWindowContentRegionMin() { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui.h b/imgui.h index e98399371..0686be2ab 100644 --- a/imgui.h +++ b/imgui.h @@ -468,19 +468,19 @@ namespace ImGui // - YOU CAN DO 99% OF WHAT YOU NEED WITH ONLY GetCursorScreenPos() and GetContentRegionAvail(). // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: // - Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. -> this is the preferred way forward. - // - Window-local coordinates: SameLine(offset), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), PushTextWrapPos() + // - Window-local coordinates: SameLine(offset), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), PushTextWrapPos() + // - Window-local coordinates: GetContentRegionMax(), GetWindowContentRegionMin(), GetWindowContentRegionMax() --> all obsoleted. YOU DON'T NEED THEM. // - GetCursorScreenPos() = GetCursorPos() + GetWindowPos(). GetWindowPos() is almost only ever useful to convert from window-local to absolute coordinates. Try not to use it. - IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute coordinates. THIS IS YOUR BEST FRIEND (prefer using this rather than GetCursorPos(), also more useful to work with ImDrawList API). - IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute coordinates + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position, absolute coordinates. THIS IS YOUR BEST FRIEND (prefer using this rather than GetCursorPos(), also more useful to work with ImDrawList API). + IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position, absolute coordinates. THIS IS YOUR BEST FRIEND. IMGUI_API ImVec2 GetContentRegionAvail(); // available space from current position. THIS IS YOUR BEST FRIEND. - IMGUI_API ImVec2 GetContentRegionMax(); // [window-local] current content boundaries (e.g. window boundaries including scrolling, or current column boundaries) - IMGUI_API ImVec2 GetCursorPos(); // [window-local] cursor position in window coordinates (relative to window position) + IMGUI_API ImVec2 GetCursorPos(); // [window-local] cursor position in window-local coordinates. This is not your best friend. IMGUI_API float GetCursorPosX(); // [window-local] " IMGUI_API float GetCursorPosY(); // [window-local] " IMGUI_API void SetCursorPos(const ImVec2& local_pos); // [window-local] " IMGUI_API void SetCursorPosX(float local_x); // [window-local] " IMGUI_API void SetCursorPosY(float local_y); // [window-local] " - IMGUI_API ImVec2 GetCursorStartPos(); // [window-local] initial cursor position, in window coordinates + IMGUI_API ImVec2 GetCursorStartPos(); // [window-local] initial cursor position, in window-local coordinates // Other layout functions IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. @@ -3499,6 +3499,7 @@ namespace ImGui static inline void PopButtonRepeat() { PopItemFlag(); } static inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } static inline void PopTabStop() { PopItemFlag(); } + IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! // OBSOLETED in 1.90.0 (from September 2023) From 3f9a90e2a3c5a4662e57b5b9dec3042d3b5715ff Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 25 Jul 2024 16:59:34 +0200 Subject: [PATCH 0256/2359] Docs: added extraneous link to Getting Started section. --- backends/imgui_impl_allegro5.h | 1 + backends/imgui_impl_android.h | 1 + backends/imgui_impl_dx10.h | 1 + backends/imgui_impl_dx11.h | 1 + backends/imgui_impl_dx12.h | 2 ++ backends/imgui_impl_dx9.h | 1 + backends/imgui_impl_glfw.h | 1 + backends/imgui_impl_glut.h | 1 + backends/imgui_impl_metal.h | 2 ++ backends/imgui_impl_opengl2.h | 1 + backends/imgui_impl_opengl3.h | 2 +- backends/imgui_impl_osx.h | 2 ++ backends/imgui_impl_sdl2.h | 1 + backends/imgui_impl_sdl3.h | 1 + backends/imgui_impl_sdlrenderer2.h | 1 + backends/imgui_impl_sdlrenderer3.h | 1 + backends/imgui_impl_vulkan.h | 2 +- backends/imgui_impl_wgpu.h | 1 + backends/imgui_impl_win32.h | 1 + 19 files changed, 22 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_allegro5.h b/backends/imgui_impl_allegro5.h index 5b63654ef..f1501eca8 100644 --- a/backends/imgui_impl_allegro5.h +++ b/backends/imgui_impl_allegro5.h @@ -25,6 +25,7 @@ struct ALLEGRO_DISPLAY; union ALLEGRO_EVENT; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display); IMGUI_IMPL_API void ImGui_ImplAllegro5_Shutdown(); IMGUI_IMPL_API void ImGui_ImplAllegro5_NewFrame(); diff --git a/backends/imgui_impl_android.h b/backends/imgui_impl_android.h index 557bf0e09..92a044db0 100644 --- a/backends/imgui_impl_android.h +++ b/backends/imgui_impl_android.h @@ -28,6 +28,7 @@ struct ANativeWindow; struct AInputEvent; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window); IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event); IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown(); diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h index e7e798aa4..95759737b 100644 --- a/backends/imgui_impl_dx10.h +++ b/backends/imgui_impl_dx10.h @@ -19,6 +19,7 @@ struct ID3D10Device; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplDX10_Init(ID3D10Device* device); IMGUI_IMPL_API void ImGui_ImplDX10_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX10_NewFrame(); diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h index 20887f370..cde64ee96 100644 --- a/backends/imgui_impl_dx11.h +++ b/backends/imgui_impl_dx11.h @@ -20,6 +20,7 @@ struct ID3D11Device; struct ID3D11DeviceContext; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context); IMGUI_IMPL_API void ImGui_ImplDX11_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX11_NewFrame(); diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 8710910b4..e1fd07d6d 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -27,6 +27,8 @@ struct ID3D12GraphicsCommandList; struct D3D12_CPU_DESCRIPTOR_HANDLE; struct D3D12_GPU_DESCRIPTOR_HANDLE; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! + // cmd_list is the command list that the implementation will use to render imgui draw lists. // Before calling the render function, caller must prepare cmd_list by resetting it and setting the appropriate // render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle. diff --git a/backends/imgui_impl_dx9.h b/backends/imgui_impl_dx9.h index 3965583bd..df6a0a012 100644 --- a/backends/imgui_impl_dx9.h +++ b/backends/imgui_impl_dx9.h @@ -19,6 +19,7 @@ struct IDirect3DDevice9; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplDX9_Init(IDirect3DDevice9* device); IMGUI_IMPL_API void ImGui_ImplDX9_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame(); diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index a30ed64ca..c0eac1134 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -24,6 +24,7 @@ struct GLFWwindow; struct GLFWmonitor; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks); IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks); IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks); diff --git a/backends/imgui_impl_glut.h b/backends/imgui_impl_glut.h index 062110edd..a7479e1d7 100644 --- a/backends/imgui_impl_glut.h +++ b/backends/imgui_impl_glut.h @@ -26,6 +26,7 @@ #ifndef IMGUI_DISABLE #include "imgui.h" // IMGUI_IMPL_API +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplGLUT_Init(); IMGUI_IMPL_API void ImGui_ImplGLUT_InstallFuncs(); IMGUI_IMPL_API void ImGui_ImplGLUT_Shutdown(); diff --git a/backends/imgui_impl_metal.h b/backends/imgui_impl_metal.h index 53706d1f7..2402c02c6 100644 --- a/backends/imgui_impl_metal.h +++ b/backends/imgui_impl_metal.h @@ -25,6 +25,7 @@ @class MTLRenderPassDescriptor; @protocol MTLDevice, MTLCommandBuffer, MTLRenderCommandEncoder; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id device); IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor); @@ -51,6 +52,7 @@ IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); #include #ifndef __OBJC__ +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplMetal_Init(MTL::Device* device); IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor); diff --git a/backends/imgui_impl_opengl2.h b/backends/imgui_impl_opengl2.h index 9c756c71d..e7f7a58c1 100644 --- a/backends/imgui_impl_opengl2.h +++ b/backends/imgui_impl_opengl2.h @@ -24,6 +24,7 @@ #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOpenGL2_Init(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_NewFrame(); diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h index d66a15ebf..54545f957 100644 --- a/backends/imgui_impl_opengl3.h +++ b/backends/imgui_impl_opengl3.h @@ -29,7 +29,7 @@ #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE -// Backend API +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr); IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame(); diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h index 4033ad93e..28e133128 100644 --- a/backends/imgui_impl_osx.h +++ b/backends/imgui_impl_osx.h @@ -27,6 +27,7 @@ @class NSEvent; @class NSView; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOSX_Init(NSView* _Nonnull view); IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view); @@ -41,6 +42,7 @@ IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view); // #include #ifndef __OBJC__ +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view); IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view); diff --git a/backends/imgui_impl_sdl2.h b/backends/imgui_impl_sdl2.h index 7020a29e0..e551e52a2 100644 --- a/backends/imgui_impl_sdl2.h +++ b/backends/imgui_impl_sdl2.h @@ -27,6 +27,7 @@ struct SDL_Renderer; struct _SDL_GameController; typedef union SDL_Event SDL_Event; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window); diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h index f1c06db5d..39b7839d8 100644 --- a/backends/imgui_impl_sdl3.h +++ b/backends/imgui_impl_sdl3.h @@ -28,6 +28,7 @@ struct SDL_Renderer; struct SDL_Gamepad; typedef union SDL_Event SDL_Event; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window); diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h index aee40524d..c067eaeea 100644 --- a/backends/imgui_impl_sdlrenderer2.h +++ b/backends/imgui_impl_sdlrenderer2.h @@ -25,6 +25,7 @@ struct SDL_Renderer; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame(); diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h index 968ec0825..1a730208a 100644 --- a/backends/imgui_impl_sdlrenderer3.h +++ b/backends/imgui_impl_sdlrenderer3.h @@ -25,6 +25,7 @@ struct SDL_Renderer; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_NewFrame(); diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index fb98bfbc4..1c7f76951 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -98,7 +98,7 @@ struct ImGui_ImplVulkan_InitInfo VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. }; -// Called by user code +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 2e19ea36e..87d9580bf 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -37,6 +37,7 @@ struct ImGui_ImplWGPU_InitInfo } }; +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info); IMGUI_IMPL_API void ImGui_ImplWGPU_Shutdown(); IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame(); diff --git a/backends/imgui_impl_win32.h b/backends/imgui_impl_win32.h index be5627142..3ad1a7eaf 100644 --- a/backends/imgui_impl_win32.h +++ b/backends/imgui_impl_win32.h @@ -20,6 +20,7 @@ #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd); IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); From b3ba6b30952961bb9ec5fc6f46361c72530ff67c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 26 Jul 2024 14:07:29 +0200 Subject: [PATCH 0257/2359] Added io.ConfigNavSwapGamepadButtons to swap Activate/Cancel (A<>B) buttons, to match the typical "Nintendo/Japanese consoles" button layout when using Gamepad navigation. (#787, #5723) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui.h | 1 + imgui_internal.h | 4 ++-- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index eb98554ce..cdb136029 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,8 @@ Other changes: - IO: added io.PlatformOpenInShellFn handler to open a link/folder/file in OS shell. (#7660) Default to use ShellExecute() under Windows, and system("") under Mac/Linux/etc. Added IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS to disable default implementation. +- IO: added io.ConfigNavSwapGamepadButtons to swap Activate/Cancel (A<>B) buttons, to match tye + typical "Nintendo/Japanese consoles" button layout when using Gamepad navigation. (#787, #5723) - Added PushItemFlag()/PopItemFlags(), ImGuiItemFlags to modify shared item flags: - Added ImGuiItemFlags_NoTabStop to disable tabbing through items. - Added ImGuiItemFlags_NoNav to disable any navigation and focus of items. (#787) diff --git a/imgui.cpp b/imgui.cpp index a74ae56c1..db7964b8a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1376,6 +1376,7 @@ ImGuiIO::ImGuiIO() #else ConfigMacOSXBehaviors = false; #endif + ConfigNavSwapGamepadButtons = false; ConfigInputTrickleEventQueue = true; ConfigInputTextCursorBlink = true; ConfigInputTextEnterKeepActive = false; diff --git a/imgui.h b/imgui.h index 0686be2ab..09db7b1fe 100644 --- a/imgui.h +++ b/imgui.h @@ -2225,6 +2225,7 @@ struct ImGuiIO // Miscellaneous options bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. + bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. bool ConfigInputTrickleEventQueue; // = true // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting). bool ConfigInputTextEnterKeepActive; // = false // [BETA] Pressing Enter will keep item active and select contents (single-line only). diff --git a/imgui_internal.h b/imgui_internal.h index 6cee07857..0eaaa0f77 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1355,8 +1355,8 @@ typedef ImBitArray ImBitAr #define ImGuiKey_NavKeyboardTweakFast ImGuiMod_Shift #define ImGuiKey_NavGamepadTweakSlow ImGuiKey_GamepadL1 #define ImGuiKey_NavGamepadTweakFast ImGuiKey_GamepadR1 -#define ImGuiKey_NavGamepadActivate ImGuiKey_GamepadFaceDown -#define ImGuiKey_NavGamepadCancel ImGuiKey_GamepadFaceRight +#define ImGuiKey_NavGamepadActivate (g.IO.ConfigNavSwapGamepadButtons ? ImGuiKey_GamepadFaceRight : ImGuiKey_GamepadFaceDown) +#define ImGuiKey_NavGamepadCancel (g.IO.ConfigNavSwapGamepadButtons ? ImGuiKey_GamepadFaceDown : ImGuiKey_GamepadFaceRight) #define ImGuiKey_NavGamepadMenu ImGuiKey_GamepadFaceLeft #define ImGuiKey_NavGamepadInput ImGuiKey_GamepadFaceUp From 692bee5f2211952b8a732616b7714f95ca1ef639 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 26 Jul 2024 15:14:37 +0200 Subject: [PATCH 0258/2359] Added GetID(int) variant for consistency. (#7111) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 5 +++++ imgui.h | 1 + 3 files changed, 7 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cdb136029..f47d7d7d2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -153,6 +153,7 @@ Other changes: - Groups, Tables: fixed EndGroup() failing to correctly capture current table occupied size. (#7543) - TabBar, Style: added style.TabBarOverlineSize / ImGuiStyleVar_TabBarOverlineSize to manipulate thickness of the horizontal line over selectable tabs. [@DctrNoob] +- Misc: added GetID(int) variant for consistency. (#7111) - Style: close button and collapse/window-menu button hover highlight made rectangular instead of round. - Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and diff --git a/imgui.cpp b/imgui.cpp index db7964b8a..8640eda1a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8380,6 +8380,11 @@ ImGuiID ImGui::GetID(const void* ptr_id) return window->GetID(ptr_id); } +ImGuiID ImGui::GetID(int int_id) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->GetID(int_id); +} //----------------------------------------------------------------------------- // [SECTION] INPUTS //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 09db7b1fe..db9e59dad 100644 --- a/imgui.h +++ b/imgui.h @@ -517,6 +517,7 @@ namespace ImGui 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(const void* ptr_id); + IMGUI_API ImGuiID GetID(int int_id); // Widgets: Text IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. From d42fa46dc6b68863046c22467297933dbe39bb55 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 26 Jul 2024 15:15:46 +0200 Subject: [PATCH 0259/2359] Misc micro-optimizations related to hot-path of dealing with a large clipped tree. Halved times by two in MSVC Debug x64. --- imgui.cpp | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8640eda1a..6b545d67d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2583,12 +2583,11 @@ void ImGuiStorage::BuildSortByKey() { ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID); } -IM_MSVC_RUNTIME_CHECKS_RESTORE int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) return default_val; return it->val_i; } @@ -2601,7 +2600,7 @@ bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) return default_val; return it->val_f; } @@ -2609,7 +2608,7 @@ float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { ImGuiStoragePair* it = ImLowerBound(const_cast(Data.Data), const_cast(Data.Data + Data.Size), key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) return NULL; return it->val_p; } @@ -2618,7 +2617,7 @@ void* ImGuiStorage::GetVoidPtr(ImGuiID key) const int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_i; } @@ -2631,7 +2630,7 @@ bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_f; } @@ -2639,7 +2638,7 @@ float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_p; } @@ -2648,7 +2647,7 @@ void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) void ImGuiStorage::SetInt(ImGuiID key, int val) { ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) Data.insert(it, ImGuiStoragePair(key, val)); else it->val_i = val; @@ -2662,7 +2661,7 @@ void ImGuiStorage::SetBool(ImGuiID key, bool val) void ImGuiStorage::SetFloat(ImGuiID key, float val) { ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) Data.insert(it, ImGuiStoragePair(key, val)); else it->val_f = val; @@ -2671,7 +2670,7 @@ void ImGuiStorage::SetFloat(ImGuiID key, float val) void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key); - if (it == Data.end() || it->key != key) + if (it == Data.Data + Data.Size || it->key != key) Data.insert(it, ImGuiStoragePair(key, val)); else it->val_p = val; @@ -2682,6 +2681,7 @@ void ImGuiStorage::SetAllInt(int v) for (int i = 0; i < Data.Size; i++) Data[i].val_i = v; } +IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- // [SECTION] ImGuiTextFilter @@ -2749,7 +2749,7 @@ void ImGuiTextFilter::Build() bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { - if (Filters.empty()) + if (Filters.Size == 0) return true; if (text == NULL) @@ -8241,6 +8241,7 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) // 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 seed = IDStack.back(); @@ -8385,6 +8386,8 @@ ImGuiID ImGui::GetID(int int_id) ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(int_id); } +IM_MSVC_RUNTIME_CHECKS_RESTORE + //----------------------------------------------------------------------------- // [SECTION] INPUTS //----------------------------------------------------------------------------- From 79e83d6535291f41430d900c8d71d7fd0e9b47f0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Jul 2024 11:17:31 +0200 Subject: [PATCH 0260/2359] Docs: misc update. --- docs/BACKENDS.md | 38 +++++++++++++++++++------------------- docs/EXAMPLES.md | 45 ++++++--------------------------------------- docs/README.md | 6 +++--- 3 files changed, 28 insertions(+), 61 deletions(-) diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 88a96a6bd..55a0983dd 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -2,23 +2,10 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKE ## Dear ImGui: Backends -**The backends/ folder contains backends for popular platforms/graphics API, which you can use in -your application or engine to easily integrate Dear ImGui.** Each backend is typically self-contained in a pair of files: imgui_impl_XXXX.cpp + imgui_impl_XXXX.h. - -- The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, and windowing.
- e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), SDL2 ([imgui_impl_sdl2.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl2.cpp)), etc. - -- The 'Renderer' backends are in charge of: creating atlas texture, and rendering imgui draw data.
- e.g. DirectX11 ([imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)), OpenGL/WebGL ([imgui_impl_opengl3.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_opengl3.cpp)), Vulkan ([imgui_impl_vulkan.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_vulkan.cpp)), etc. - -- For some high-level frameworks, a single backend usually handles both 'Platform' and 'Renderer' parts.
- e.g. Allegro 5 ([imgui_impl_allegro5.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_allegro5.cpp)). If you end up creating a custom backend for your engine, you may want to do the same. - -An application usually combines one Platform backend + one Renderer backend + main Dear ImGui sources. -For example, the [example_win32_directx11](https://github.com/ocornut/imgui/tree/master/examples/example_win32_directx11) application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. There are 20+ examples in the [examples/](https://github.com/ocornut/imgui/blob/master/examples/) folder. See [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for details. - -**Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** +### Integrating backends +💡 The **[Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) wiki guide** has examples of how to integrate Dear ImGui into an existing application. +
The [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) documentation may also be worth a read. ### What are backends? @@ -38,7 +25,7 @@ Dear ImGui is highly portable and only requires a few things to run and render, - Optional: multi-viewports support. etc. -This is essentially what each backend is doing + obligatory portability cruft. Using default backends ensure you can get all those features including the ones that would be harder to implement on your side (e.g. multi-viewports support). +This is essentially what each backend is doing + obligatory portability cruft. Using standard backends ensure you can get all those features including the ones that would be harder to implement on your side (e.g. multi-viewports support). It is important to understand the difference between the core Dear ImGui library (files in the root folder) and the backends which we are describing here (backends/ folder). @@ -47,11 +34,24 @@ and the backends which we are describing here (backends/ folder). - You should be able to write backends for pretty much any platform and any 3D graphics API. e.g. you can get creative and use software rendering or render remotely on a different machine. +### Standard backends -### Integrating a backend +**The [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder contains backends for popular platforms/graphics API, which you can use in +your application or engine to easily integrate Dear ImGui.** Each backend is typically self-contained in a pair of files: imgui_impl_XXXX.cpp + imgui_impl_XXXX.h. -See "Getting Started" section of [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for more details. +- The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, and windowing.
+ e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), SDL2 ([imgui_impl_sdl2.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl2.cpp)), etc. +- The 'Renderer' backends are in charge of: creating atlas texture, and rendering imgui draw data.
+ e.g. DirectX11 ([imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)), OpenGL/WebGL ([imgui_impl_opengl3.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_opengl3.cpp)), Vulkan ([imgui_impl_vulkan.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_vulkan.cpp)), etc. + +- For some high-level frameworks, a single backend usually handles both 'Platform' and 'Renderer' parts.
+ e.g. Allegro 5 ([imgui_impl_allegro5.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_allegro5.cpp)). If you end up creating a custom backend for your engine, you may want to do the same. + +An application usually combines one Platform backend + one Renderer backend + main Dear ImGui sources. +For example, the [example_win32_directx11](https://github.com/ocornut/imgui/tree/master/examples/example_win32_directx11) application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. There are 20+ examples in the [examples/](https://github.com/ocornut/imgui/blob/master/examples/) folder. See [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for details. + +**Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** ### List of backends diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index 4aa69a671..66ad24ef7 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -35,46 +35,13 @@ At shutdown: call ImGui::DestroyContext() ``` -Example (using [backends/imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp) + [backends/imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)): +Main resource: +- Read **[Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) wiki guide** for detailed examples of how to integrate Dear ImGui in an existing application. -```cpp -// Create a Dear ImGui context, setup some options -ImGui::CreateContext(); -ImGuiIO& io = ImGui::GetIO(); -io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable some options - -// Initialize Platform + Renderer backends (here: using imgui_impl_win32.cpp + imgui_impl_dx11.cpp) -ImGui_ImplWin32_Init(my_hwnd); -ImGui_ImplDX11_Init(my_d3d_device, my_d3d_device_context); - -// Application main loop -while (true) -{ - // Beginning of frame: update Renderer + Platform backend, start Dear ImGui frame - ImGui_ImplDX11_NewFrame(); - ImGui_ImplWin32_NewFrame(); - ImGui::NewFrame(); - - // Any application code here - ImGui::Text("Hello, world!"); - - // End of frame: render Dear ImGui - ImGui::Render(); - ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); - - // Swap - g_pSwapChain->Present(1, 0); -} - -// Shutdown -ImGui_ImplDX11_Shutdown(); -ImGui_ImplWin32_Shutdown(); -ImGui::DestroyContext(); -``` - -Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. -Please read the comments and instruction at the top of each file. -Please read FAQ at https://www.dearimgui.com/faq +Additional resources: +- Read FAQ at https://www.dearimgui.com/faq +- Read 'PROGRAMMER GUIDE' section in imgui.cpp. +- Read the comments and instruction at the top of each file. If you are using any of the backends provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h) files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with its own individual diff --git a/docs/README.md b/docs/README.md index 78cf2fea0..2c976341c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,7 +13,7 @@ Businesses: support continued development and maintenance via invoiced sponsorin
  _E-mail: contact @ dearimgui dot com_
Individuals: support continued development and maintenance [here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). Also see [Funding](https://github.com/ocornut/imgui/wiki/Funding) page. -| [The Pitch](#the-pitch) - [Usage](#usage) - [How it works](#how-it-works) - [Releases & Changelogs](#releases--changelogs) - [Demo](#demo) - [Integration](#integration) | +| [The Pitch](#the-pitch) - [Usage](#usage) - [How it works](#how-it-works) - [Releases & Changelogs](#releases--changelogs) - [Demo](#demo) - [Getting Started & Integration](#getting-started--integration) | :----------------------------------------------------------: | | [Gallery](#gallery) - [Support, FAQ](#support-frequently-asked-questions-faq) - [How to help](#how-to-help) - **[Funding & Sponsors](https://github.com/ocornut/imgui/wiki/Funding)** - [Credits](#credits) - [License](#license) | | [Wiki](https://github.com/ocornut/imgui/wiki) - [Extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions) - [Languages bindings & frameworks backends](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | @@ -43,7 +43,7 @@ Dear ImGui is particularly suited to integration in game engines (for tooling), **Backends for a variety of graphics API and rendering platforms** are provided in the [backends/](https://github.com/ocornut/imgui/tree/master/backends) folder, along with example applications in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui. -See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide and [Integration](#integration) section of this document for more details. +See the [Getting Started & Integration](#getting-started--integration) section of this document for more details. After Dear ImGui is set up in your application, you can use it from \_anywhere\_ in your program loop: ```cpp @@ -114,7 +114,7 @@ You should be able to build the examples from sources. If you don't, let us know The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at a different scale and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.com/faq)). -### Integration +### Getting Started & Integration See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide for details. From 96460a8a12615f3138173996f7481cc86c70a9f1 Mon Sep 17 00:00:00 2001 From: Laurent Dufresne Date: Sun, 28 Jul 2024 09:51:20 +0200 Subject: [PATCH 0261/2359] InputText: Added '\' and '/' as word seperator. (#7824, #7704) Adding those seperators means that ctrl+(left|right)-arrows and ctrl+backspace will stop at slashes, which is more inline with how most software works and generally is very convenient when dealing with paths or urls. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f47d7d7d2..dca2d3259 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -146,6 +146,7 @@ Other changes: - Multi-Select (advanced) - Nav: fixed clicking window decorations (e.g. resize borders) from losing focused item when within a child window using ImGuiChildFlags_NavFlattened. +- InputText: added '\' and '/' as word seperator. (#7824, #7704) [@reduf] - Clipper: added SeekCursorForItem() function. When using ImGuiListClipper::Begin(INT_MAX) you can can use the clipper without knowing the amount of items beforehand. (#1311) In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) as the end of your iteration diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1a11e3834..b1ee63ce5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3897,7 +3897,7 @@ static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* ob static bool is_separator(unsigned int c) { - return c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|' || c=='\n' || c=='\r' || c=='.' || c=='!'; + return c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|' || c=='\n' || c=='\r' || c=='.' || c=='!' || c=='\\' || c=='/'; } static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx) From c7b925609777aec45326791c5105a433b3e4e3a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20H=C3=A9rilier?= Date: Fri, 26 Jul 2024 13:19:22 +0200 Subject: [PATCH 0262/2359] Selectable: added ImGuiSelectableFlags_Highlight flag to highlight items independently from the hovered state. (#7820) Demo: Make the Widget/List boxes show how to use forced highlighting. --- docs/CHANGELOG.txt | 2 ++ imgui.h | 1 + imgui_demo.cpp | 33 +++++++++++++++++++++------------ imgui_widgets.cpp | 7 ++++--- 4 files changed, 28 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dca2d3259..2ac60cd72 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -147,6 +147,8 @@ Other changes: - Nav: fixed clicking window decorations (e.g. resize borders) from losing focused item when within a child window using ImGuiChildFlags_NavFlattened. - InputText: added '\' and '/' as word seperator. (#7824, #7704) [@reduf] +- Selectable: added ImGuiSelectableFlags_Highlight flag to highlight items independently from + the hovered state. (#7820) [@rerilier] - Clipper: added SeekCursorForItem() function. When using ImGuiListClipper::Begin(INT_MAX) you can can use the clipper without knowing the amount of items beforehand. (#1311) In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) as the end of your iteration diff --git a/imgui.h b/imgui.h index db9e59dad..de7a4d2bc 100644 --- a/imgui.h +++ b/imgui.h @@ -1228,6 +1228,7 @@ enum ImGuiSelectableFlags_ ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text ImGuiSelectableFlags_AllowOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one + ImGuiSelectableFlags_Highlight = 1 << 5, // Make the item be displayed as if it is hovered #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8684bd0c6..0c61352d7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1357,18 +1357,18 @@ static void ShowDemoWindowWidgets(DemoWindowData* demo_data) // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively // stored in the object itself, etc.) const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; - static int item_current_idx = 0; // Here we store our selection data as an index. + static int item_selected_idx = 0; // Here we store our selection data as an index. // Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[]) - const char* combo_preview_value = items[item_current_idx]; + const char* combo_preview_value = items[item_selected_idx]; if (ImGui::BeginCombo("combo 1", combo_preview_value, flags)) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { - const bool is_selected = (item_current_idx == n); + const bool is_selected = (item_selected_idx == n); if (ImGui::Selectable(items[n], is_selected)) - item_current_idx = n; + item_selected_idx = n; // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if (is_selected) @@ -1410,14 +1410,22 @@ static void ShowDemoWindowWidgets(DemoWindowData* demo_data) // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively // stored in the object itself, etc.) const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; - static int item_current_idx = 0; // Here we store our selection data as an index. + static int item_selected_idx = 0; // Here we store our selected data as an index. + + static bool item_highlight = false; + int item_highlighted_idx = -1; // Here we store our highlighted data as an index. + ImGui::Checkbox("Highlight hovered item in second listbox", &item_highlight); + if (ImGui::BeginListBox("listbox 1")) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { - const bool is_selected = (item_current_idx == n); + const bool is_selected = (item_selected_idx == n); if (ImGui::Selectable(items[n], is_selected)) - item_current_idx = n; + item_selected_idx = n; + + if (item_highlight && ImGui::IsItemHovered()) + item_highlighted_idx = n; // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if (is_selected) @@ -1433,9 +1441,10 @@ static void ShowDemoWindowWidgets(DemoWindowData* demo_data) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { - const bool is_selected = (item_current_idx == n); - if (ImGui::Selectable(items[n], is_selected)) - item_current_idx = n; + bool is_selected = (item_selected_idx == n); + ImGuiSelectableFlags flags = (item_highlighted_idx == n) ? ImGuiSelectableFlags_Highlight : 0; + if (ImGui::Selectable(items[n], is_selected, flags)) + item_selected_idx = n; // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if (is_selected) @@ -1482,8 +1491,8 @@ static void ShowDemoWindowWidgets(DemoWindowData* demo_data) ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selectables/In columns"); - if (ImGui::TreeNode("In columns")) + IMGUI_DEMO_MARKER("Widgets/Selectables/In Tables"); + if (ImGui::TreeNode("In Tables")) { static bool selected[10] = {}; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b1ee63ce5..31ba7d5c7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6894,14 +6894,15 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Render if (is_visible) { - if (hovered || selected) + const bool highlighted = hovered || (flags & ImGuiSelectableFlags_Highlight); + if (highlighted || selected) { // FIXME-MULTISELECT: Styling: Color for 'selected' elements? ImGuiCol_HeaderSelected ImU32 col; - if (selected && !hovered) + if (selected && !highlighted) col = GetColorU32(ImLerp(GetStyleColorVec4(ImGuiCol_Header), GetStyleColorVec4(ImGuiCol_HeaderHovered), 0.5f)); else - col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(bb.Min, bb.Max, col, false, 0.0f); } if (g.NavId == id) From 249d5caedbe6e598958b4987141ce5a197703173 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Jul 2024 15:19:42 +0200 Subject: [PATCH 0263/2359] Tables: storing LastFrozenHeight for frozen requests that don't have actual freezing due to zero scrolling. (#7821, #5143) Amend 0b4a1a40 (ignore whitespace to view this patch easily) --- imgui_tables.cpp | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ce6fed1ea..9c8262ff8 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1996,34 +1996,37 @@ void ImGui::TableEndRow(ImGuiTable* table) // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and // get the new cursor position. if (unfreeze_rows_request) + { for (int column_n = 0; column_n < table->ColumnsCount; column_n++) table->Columns[column_n].NavLayerCurrent = ImGuiNavLayer_Main; - if (unfreeze_rows_actual) - { - IM_ASSERT(table->IsUnfrozenRows == false); const float y0 = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y); - table->IsUnfrozenRows = true; table_instance->LastFrozenHeight = y0 - table->OuterRect.Min.y; - // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect - table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, window->InnerClipRect.Max.y); - table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = window->InnerClipRect.Max.y; - table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen; - IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y); - - float row_height = table->RowPosY2 - table->RowPosY1; - table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y; - table->RowPosY1 = table->RowPosY2 - row_height; - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if (unfreeze_rows_actual) { - ImGuiTableColumn* column = &table->Columns[column_n]; - column->DrawChannelCurrent = column->DrawChannelUnfrozen; - column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y; - } + IM_ASSERT(table->IsUnfrozenRows == false); + table->IsUnfrozenRows = true; - // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y - SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect); - table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent); + // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect + table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, window->InnerClipRect.Max.y); + table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = window->InnerClipRect.Max.y; + table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen; + IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y); + + float row_height = table->RowPosY2 - table->RowPosY1; + table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y; + table->RowPosY1 = table->RowPosY2 - row_height; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + column->DrawChannelCurrent = column->DrawChannelUnfrozen; + column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y; + } + + // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y + SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent); + } } if (!(table->RowFlags & ImGuiTableRowFlags_Headers)) From b847c414372928b6b919bc93d573adb1ff950c47 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Jul 2024 15:23:24 +0200 Subject: [PATCH 0264/2359] MultiSelect: BoxSelect: fixed using in frozen table. (#7821, #5143) + added Demo. Amend 0b4a1a40 --- imgui_demo.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ imgui_internal.h | 2 +- imgui_widgets.cpp | 26 +++++++++++++++++++++----- 3 files changed, 68 insertions(+), 6 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0c61352d7..eba615e12 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3306,6 +3306,52 @@ static void ShowDemoWindowMultiSelect(DemoWindowData* demo_data) ImGui::TreePop(); } + // Demonstrate using the clipper with BeginMultiSelect()/EndMultiSelect() + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (in a table)"); + if (ImGui::TreeNode("Multi-Select (in a table)")) + { + static ImGuiSelectionBasicStorage selection; + + const int ITEMS_COUNT = 10000; + ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); + if (ImGui::BeginTable("##Basket", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter)) + { + ImGui::TableSetupColumn("Object"); + ImGui::TableSetupColumn("Action"); + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableHeadersRow(); + + ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT); + selection.ApplyRequests(ms_io); + + ImGuiListClipper clipper; + clipper.Begin(ITEMS_COUNT); + if (ms_io->RangeSrcItem != -1) + clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped. + while (clipper.Step()) + { + for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + char label[64]; + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); + bool item_is_selected = selection.Contains((ImGuiID)n); + ImGui::SetNextItemSelectionUserData(n); + ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); + ImGui::TableNextColumn(); + ImGui::SmallButton("hello"); + } + } + + ms_io = ImGui::EndMultiSelect(); + selection.ApplyRequests(ms_io); + ImGui::EndTable(); + } + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (checkboxes)"); if (ImGui::TreeNode("Multi-Select (checkboxes)")) { diff --git a/imgui_internal.h b/imgui_internal.h index 0eaaa0f77..db10a9468 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3397,7 +3397,7 @@ namespace ImGui IMGUI_API int TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data); // Box-Select API - IMGUI_API bool BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags); + IMGUI_API bool BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags); IMGUI_API void EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags); // Multi-Select API diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 31ba7d5c7..970bb067b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7221,7 +7221,7 @@ static void BoxSelectScrollWithMouseDrag(ImGuiBoxSelectState* bs, ImGuiWindow* w } } -bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags) +bool ImGui::BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags) { ImGuiContext& g = *GImGui; ImGuiBoxSelectState* bs = &g.BoxSelectState; @@ -7241,11 +7241,10 @@ bool ImGui::BeginBoxSelect(ImGuiWindow* window, ImGuiID box_select_id, ImGuiMult // Current frame absolute prev/current rectangles are used to toggle selection. // They are derived from positions relative to scrolling space. - const ImRect scope_rect = window->InnerClipRect; ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->StartPosRel); ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->EndPosRel); // Clamped already ImVec2 curr_end_pos_abs = g.IO.MousePos; - if (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow + if (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max); bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs); bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs); @@ -7299,6 +7298,7 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flag // [SECTION] Widgets: Multi-Select support //------------------------------------------------------------------------- // - DebugLogMultiSelectRequests() [Internal] +// - CalcScopeRect() [Internal] // - BeginMultiSelect() // - EndMultiSelect() // - SetNextItemSelectionUserData() @@ -7317,6 +7317,22 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe } } +static ImRect CalcScopeRect(ImGuiMultiSelectTempData* ms, ImGuiWindow* window) +{ + if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) + { + // Warning: this depends on CursorMaxPos so it means to be called by EndMultiSelect() only + return ImRect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin)); + } + else + { + // Add inner table decoration (#7821) // FIXME: Why not baking in InnerClipRect? + ImRect scope_rect = window->InnerClipRect; + scope_rect.Min = ImMin(scope_rect.Min + ImVec2(window->DecoInnerSizeX1, window->DecoInnerSizeY1), scope_rect.Max); + return scope_rect; + } +} + // Return ImGuiMultiSelectIO structure. // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect(). // Passing 'selection_size' and 'items_count' parameters is currently optional. @@ -7399,7 +7415,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) { ms->BoxSelectId = GetID("##BoxSelect"); - if (BeginBoxSelect(window, ms->BoxSelectId, flags)) + if (BeginBoxSelect(CalcScopeRect(ms, window), window, ms->BoxSelectId, flags)) request_clear |= bs->RequestClear; } @@ -7452,7 +7468,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow); IM_ASSERT(g.MultiSelectTempDataStacked > 0 && &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] == g.CurrentMultiSelect); - const ImRect scope_rect = (ms->Flags & ImGuiMultiSelectFlags_ScopeRect) ? ImRect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin)) : window->InnerClipRect; + ImRect scope_rect = CalcScopeRect(ms, window); if (ms->IsFocused) { // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here. From df387049268775acb9b69438632a5f5fce58a674 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Jul 2024 22:08:06 +0200 Subject: [PATCH 0265/2359] Added SetNextItemStorageID() for tree nodes. (#7553, #6990, #3823, #1131) Undo/amend 7c6d4ff. --- docs/CHANGELOG.txt | 3 +++ imgui.h | 1 + imgui_internal.h | 4 +++- imgui_widgets.cpp | 25 ++++++++++++++++++------- 4 files changed, 25 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2ac60cd72..9fbd8b4f2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -147,6 +147,9 @@ Other changes: - Nav: fixed clicking window decorations (e.g. resize borders) from losing focused item when within a child window using ImGuiChildFlags_NavFlattened. - InputText: added '\' and '/' as word seperator. (#7824, #7704) [@reduf] +- TreeNode: added SetNextItemStorageID() to specify/override the identifier used for persisting + open/close storage. Useful if needing to often read/write from storage without manipulating + the ID stack. (#7553, #6990, #3823, #1131) - Selectable: added ImGuiSelectableFlags_Highlight flag to highlight items independently from the hovered state. (#7820) [@rerilier] - Clipper: added SeekCursorForItem() function. When using ImGuiListClipper::Begin(INT_MAX) you can diff --git a/imgui.h b/imgui.h index de7a4d2bc..898308bb5 100644 --- a/imgui.h +++ b/imgui.h @@ -661,6 +661,7 @@ namespace ImGui 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 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). // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. diff --git a/imgui_internal.h b/imgui_internal.h index db10a9468..7e9b22607 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1215,6 +1215,7 @@ enum ImGuiNextItemDataFlags_ ImGuiNextItemDataFlags_HasOpen = 1 << 1, ImGuiNextItemDataFlags_HasShortcut = 1 << 2, ImGuiNextItemDataFlags_HasRefVal = 1 << 3, + ImGuiNextItemDataFlags_HasStorageID = 1 << 4, }; struct ImGuiNextItemData @@ -1230,6 +1231,7 @@ struct ImGuiNextItemData bool OpenVal; // Set by SetNextItemOpen() ImU8 OpenCond; // Set by SetNextItemOpen() ImGuiDataTypeStorage RefVal; // Not exposed yet, for ImGuiInputTextFlags_ParseEmptyAsRefVal + ImGuiID StorageId; // Set by SetNextItemStorageID() ImGuiNextItemData() { memset(this, 0, sizeof(*this)); SelectionUserData = -1; } inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; ItemFlags = ImGuiItemFlags_None; } // Also cleared manually by ItemAdd()! @@ -3546,7 +3548,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, ImGuiID storage_id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API void TreePushOverrideID(ImGuiID id); IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 970bb067b..8e35df662 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6226,7 +6226,7 @@ bool ImGui::TreeNode(const char* label) if (window->SkipItems) return false; ImGuiID id = window->GetID(label); - return TreeNodeBehavior(id, id, ImGuiTreeNodeFlags_None, label, NULL); + return TreeNodeBehavior(id, ImGuiTreeNodeFlags_None, label, NULL); } bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) @@ -6245,7 +6245,7 @@ bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) if (window->SkipItems) return false; ImGuiID id = window->GetID(label); - return TreeNodeBehavior(id, id, flags, label, NULL); + return TreeNodeBehavior(id, flags, label, NULL); } bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) @@ -6275,7 +6275,7 @@ bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char ImGuiID id = window->GetID(str_id); const char* label, *label_end; ImFormatStringToTempBufferV(&label, &label_end, fmt, args); - return TreeNodeBehavior(id, id, flags, label, label_end); + return TreeNodeBehavior(id, flags, label, label_end); } bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) @@ -6287,7 +6287,7 @@ bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char ImGuiID id = window->GetID(ptr_id); const char* label, *label_end; ImFormatStringToTempBufferV(&label, &label_end, fmt, args); - return TreeNodeBehavior(id, id, flags, label, label_end); + return TreeNodeBehavior(id, flags, label, label_end); } bool ImGui::TreeNodeGetOpen(ImGuiID storage_id) @@ -6367,7 +6367,7 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags) } // When using public API, currently 'id == storage_id' is always true, but we separate the values to facilitate advanced user code doing storage queries outside of UI loop. -bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -6410,6 +6410,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiID storage_id, ImGuiTreeNodeFlags interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f); // Compute open and multi-select states before ItemAdd() as it clear NextItem data. + ImGuiID storage_id = (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasStorageID) ? g.NextItemData.StorageId : id; bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); bool is_visible; @@ -6694,6 +6695,16 @@ void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond) g.NextItemData.OpenCond = (ImU8)(cond ? cond : ImGuiCond_Always); } +// Set next TreeNode/CollapsingHeader storage id. +void ImGui::SetNextItemStorageID(ImGuiID storage_id) +{ + ImGuiContext& g = *GImGui; + if (g.CurrentWindow->SkipItems) + return; + g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasStorageID; + g.NextItemData.StorageId = 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) @@ -6702,7 +6713,7 @@ bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) if (window->SkipItems) return false; ImGuiID id = window->GetID(label); - return TreeNodeBehavior(id, id, flags | ImGuiTreeNodeFlags_CollapsingHeader, label); + return TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader, label); } // p_visible == NULL : regular collapsing header @@ -6722,7 +6733,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFl flags |= ImGuiTreeNodeFlags_CollapsingHeader; if (p_visible) flags |= ImGuiTreeNodeFlags_AllowOverlap | (ImGuiTreeNodeFlags)ImGuiTreeNodeFlags_ClipLabelForTrailingButton; - bool is_open = TreeNodeBehavior(id, id, flags, label); + bool is_open = TreeNodeBehavior(id, flags, label); if (p_visible != NULL) { // Create a small overlapping close button From c2a3d5e47b08d7900b0fc7a12f1761510022a4d8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Jul 2024 22:34:34 +0200 Subject: [PATCH 0266/2359] Comments, minor tweaks to ImGuiTextFilter. --- docs/CHANGELOG.txt | 9 +++++---- imgui.cpp | 10 ++++++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9fbd8b4f2..1c4bd71a1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,10 +50,11 @@ Breaking changes: You should never need those functions! You can do everything in less a confusing manner by only using GetCursorScreenPos() and GetContentRegionAvail(). Also always consider that if you are using GetWindowPos() and GetCursorPos() you may also be making things unnecessarily complicated. - I repeat: You can do everything with GetCursorScreenPos() and GetContentRegionAvail()!! - - GetWindowContentRegionMax().x - GetCursorPos().x --> GetContentRegionAvail().x - - GetWindowContentRegionMax().x + GetWindowPos().x --> GetCursorScreenPos().x + GetContentRegionAvail().x - - GetContentRegionMax() --> GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in weird local coordinates + I repeat: You can do everything with GetCursorScreenPos() and GetContentRegionAvail()! + - GetWindowContentRegionMax().x - GetCursorPos().x --> GetContentRegionAvail().x + - GetWindowContentRegionMax().x + GetWindowPos().x --> GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window + - GetContentRegionMax() --> GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates + - GetWindowContentRegionMax().x - GetWindowContentRegionMin().x --> GetContentRegionAvail() // when called from left edge of window - Item flag changes: - Obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag()/PopItemFlag() with ImGuiItemFlags_ButtonRepeat. Kept inline redirecting functions (will obsolete). diff --git a/imgui.cpp b/imgui.cpp index 6b545d67d..6bd0c052a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -435,9 +435,11 @@ CODE - instead of: GetWindowContentRegionMax().x - GetCursorPos().x - you can use: GetContentRegionAvail().x - instead of: GetWindowContentRegionMax().x + GetWindowPos().x - - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x (from left edge of window) + - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window - instead of: GetContentRegionMax() - - you cna use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in weird local coordinates + - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates + - instead of: GetWindowContentRegionMax().x - GetWindowContentRegionMin().x + - you can use: GetContentRegionAvail() // when called from left edge of window - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573) (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors) - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag(). @@ -2753,11 +2755,11 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const return true; if (text == NULL) - text = ""; + text = text_end = ""; for (const ImGuiTextRange& f : Filters) { - if (f.empty()) + if (f.b == f.e) continue; if (f.b[0] == '-') { From ce3a8d7c79f2490b7db1a55f19030654f9a6f600 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Aug 2023 11:26:19 +0200 Subject: [PATCH 0267/2359] Demo: MultiSelect: added tree demo. (#6990, #3823, #1861) --- imgui_demo.cpp | 160 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 158 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index eba615e12..08798e181 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -262,13 +262,14 @@ void* GImGuiDemoMarkerCallbackUserData = NULL; struct ExampleTreeNode { // Tree structure - char Name[28]; + char Name[28] = ""; int UID = 0; ExampleTreeNode* Parent = NULL; ImVector Childs; + unsigned short IndexInParent = 0; // Maintaining this allows us to implement linear traversal more easily // Leaf Data - bool HasData = false; // All leaves have data + bool HasData = false; // All leaves have data bool DataMyBool = true; int DataMyInt = 128; ImVec2 DataMyVec2 = ImVec2(0.0f, 3.141592f); @@ -298,6 +299,7 @@ static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, Exampl snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name); node->UID = uid; node->Parent = parent; + node->IndexInParent = parent ? (unsigned short)parent->Childs.Size : 0; if (parent) parent->Childs.push_back(node); return node; @@ -3442,6 +3444,160 @@ static void ShowDemoWindowMultiSelect(DemoWindowData* demo_data) ImGui::TreePop(); } + // Demonstrate supporting multiple-selection in a tree. + // - We don't use linear indices for selection user data, but our ExampleTreeNode* pointer directly! + // This showcase how SetNextItemSelectionUserData() never assume indices! + // - The difficulty here is to "interpolate" from RangeSrcItem to RangeDstItem in the SetAll/SetRange request. + // We want this interpolation to match what the user sees: in visible order, skipping closed nodes. + // This is implemented by our TreeGetNextNodeInVisibleOrder() user-space helper. + // - Important: In a real codebase aiming to implement full-featured selectable tree with custom filtering, you + // are more likely to build an array mapping sequential indices to visible tree nodes, since your + // filtering/search + clipping process will benefit from it. Having this will make this interpolation much easier. + // - Consider this a prototype: we are working toward simplifying some of it. + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (trees)"); + if (ImGui::TreeNode("Multi-Select (trees)")) + { + HelpMarker( + "This is rather advanced and experimental. If you are getting started with multi-select," + "please don't start by looking at how to use it for a tree!\n\n" + "Future versions will try to simplify and formalize some of this."); + + struct ExampleTreeFuncs + { + static void DrawNode(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection) + { + ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; + tree_node_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Enable pressing left to jump to parent + if (node->Childs.Size == 0) + tree_node_flags |= ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_Leaf; + if (selection->Contains((ImGuiID)node->UID)) + tree_node_flags |= ImGuiTreeNodeFlags_Selected; + + // Using SetNextItemStorageID() to specify storage id, so we can easily peek into + // the storage holding open/close stage, using our TreeNodeGetOpen/TreeNodeSetOpen() functions. + ImGui::SetNextItemSelectionUserData((ImGuiSelectionUserData)(intptr_t)node); + ImGui::SetNextItemStorageID((ImGuiID)node->UID); + if (ImGui::TreeNodeEx(node->Name, tree_node_flags)) + { + for (ExampleTreeNode* child : node->Childs) + DrawNode(child, selection); + ImGui::TreePop(); + } + else if (ImGui::IsItemToggledOpen()) + { + TreeCloseAndUnselectChildNodes(node, selection); + } + } + + static bool TreeNodeGetOpen(ExampleTreeNode* node) + { + return ImGui::GetStateStorage()->GetBool((ImGuiID)node->UID); + } + + static void TreeNodeSetOpen(ExampleTreeNode* node, bool open) + { + ImGui::GetStateStorage()->SetBool((ImGuiID)node->UID, open); + } + + // When closing a node: 1) close and unselect all child nodes, 2) select parent if any child was selected. + // FIXME: This is currently handled by user logic but I'm hoping to eventually provide tree node + // features to do this automatically, e.g. a ImGuiTreeNodeFlags_AutoCloseChildNodes etc. + static int TreeCloseAndUnselectChildNodes(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection, int depth = 0) + { + // Recursive close (the test for depth == 0 is because we call this on a node that was just closed!) + int unselected_count = selection->Contains((ImGuiID)node->UID) ? 1 : 0; + if (depth == 0 || TreeNodeGetOpen(node)) + { + for (ExampleTreeNode* child : node->Childs) + unselected_count += TreeCloseAndUnselectChildNodes(child, selection, depth + 1); + TreeNodeSetOpen(node, false); + } + + // Select root node if any of its child was selected, otherwise unselect + selection->SetItemSelected((ImGuiID)node->UID, (depth == 0 && unselected_count > 0)); + return unselected_count; + } + + // Apply multi-selection requests + static void ApplySelectionRequests(ImGuiMultiSelectIO* ms_io, ExampleTreeNode* tree, ImGuiSelectionBasicStorage* selection) + { + for (ImGuiSelectionRequest& req : ms_io->Requests) + { + if (req.Type == ImGuiSelectionRequestType_SetAll) + { + if (req.Selected) + TreeSetAllInOpenNodes(tree, selection, req.Selected); + else + selection->Clear(); + } + else if (req.Type == ImGuiSelectionRequestType_SetRange) + { + ExampleTreeNode* first_node = (ExampleTreeNode*)(intptr_t)req.RangeFirstItem; + ExampleTreeNode* last_node = (ExampleTreeNode*)(intptr_t)req.RangeLastItem; + for (ExampleTreeNode* node = first_node; node != NULL; node = TreeGetNextNodeInVisibleOrder(node, last_node)) + selection->SetItemSelected((ImGuiID)node->UID, req.Selected); + } + } + } + + static void TreeSetAllInOpenNodes(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection, bool selected) + { + if (node->Parent != NULL) // Root node isn't visible nor selectable in our scheme + selection->SetItemSelected((ImGuiID)node->UID, selected); + if (node->Parent == NULL || TreeNodeGetOpen(node)) + for (ExampleTreeNode* child : node->Childs) + TreeSetAllInOpenNodes(child, selection, selected); + } + + // Interpolate in *user-visible order* AND only *over opened nodes*. + // If you have a sequential mapping tables (e.g. generated after a filter/search pass) this would be simpler. + // Here the tricks are that: + // - we store/maintain ExampleTreeNode::IndexInParent which allows implementing a linear iterator easily, without searches, without recursion. + // this could be replaced by a search in parent, aka 'int index_in_parent = curr_node->Parent->Childs.find_index(curr_node)' + // which would only be called when crossing from child to a parent, aka not too much. + // - we call SetNextItemStorageID() before our TreeNode() calls with an ID which doesn't relate to UI stack, + // making it easier to call TreeNodeGetOpen()/TreeNodeSetOpen() from any location. + static ExampleTreeNode* TreeGetNextNodeInVisibleOrder(ExampleTreeNode* curr_node, ExampleTreeNode* last_node) + { + // Reached last node + if (curr_node == last_node) + return NULL; + + // Recurse into childs. Query storage to tell if the node is open. + if (curr_node->Childs.Size > 0 && TreeNodeGetOpen(curr_node)) + return curr_node->Childs[0]; + + // Next sibling, then into our own parent + while (curr_node->Parent != NULL) + { + if (curr_node->IndexInParent + 1 < curr_node->Parent->Childs.Size) + return curr_node->Parent->Childs[curr_node->IndexInParent + 1]; + curr_node = curr_node->Parent; + } + return NULL; + } + + }; // ExampleTreeFuncs + + static ImGuiSelectionBasicStorage selection; + static ExampleTreeNode* tree = ExampleTree_CreateDemoTree(); // Create tree once + ImGui::Text("Selection size: %d", selection.Size); + + if (ImGui::BeginChild("##Tree", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) + { + ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect2d; + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, selection.Size, -1); + ExampleTreeFuncs::ApplySelectionRequests(ms_io, tree, &selection); + for (ExampleTreeNode* node : tree->Childs) + ExampleTreeFuncs::DrawNode(node, &selection); + ms_io = ImGui::EndMultiSelect(); + ExampleTreeFuncs::ApplySelectionRequests(ms_io, tree, &selection); + } + ImGui::EndChild(); + + ImGui::TreePop(); + } + // Advanced demonstration of BeginMultiSelect() // - Showcase clipping. // - Showcase deletion. From 1f634f1d94e16feb3d0b15ad79e8bc44cccc184d Mon Sep 17 00:00:00 2001 From: SPeak Date: Tue, 30 Jul 2024 05:55:02 +0800 Subject: [PATCH 0268/2359] Eaxmples: Android: Fix build failed issue. (#7832) set android:exported to true (IntentFilter) Signed-off-by: Sunrisepeak --- .../android/app/src/main/AndroidManifest.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml b/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml index a87b95b4f..5a1e2d9e5 100644 --- a/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml +++ b/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml @@ -11,7 +11,7 @@ android:name="imgui.example.android.MainActivity" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:configChanges="orientation|keyboardHidden|screenSize" - android:exported="false"> + android:exported="true"> From 1b44e4044491b96c7bc30989f8d8c356bc57bada Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 30 Jul 2024 11:44:13 +0200 Subject: [PATCH 0269/2359] Demo: re-use tree data. Fix property editor vertical alignment. Tweak recent memory allocation monitor. --- imgui.cpp | 7 +++- imgui_demo.cpp | 93 +++++++++++++++++++++++++++----------------------- 2 files changed, 57 insertions(+), 43 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6bd0c052a..97ee6fe1a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15070,7 +15070,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) for (int n = buf_size - 1; n >= 0; n--) { ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size]; - BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : ""); + BulletText("Frame %06d: %+3d ( %2d alloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount); + if (n == 0) + { + SameLine(); + Text("<- %d frames ago", g.FrameCount - entry->FrameCount); + } } TreePop(); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 08798e181..a5f7408c2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -199,6 +199,7 @@ Index of this file: #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) // Forward Declarations +struct ImGuiDemoWindowData; static void ShowExampleAppMainMenuBar(); static void ShowExampleAppAssetsBrowser(bool* p_open); static void ShowExampleAppConsole(bool* p_open); @@ -206,7 +207,7 @@ static void ShowExampleAppCustomRendering(bool* p_open); static void ShowExampleAppDocuments(bool* p_open); static void ShowExampleAppLog(bool* p_open); static void ShowExampleAppLayout(bool* p_open); -static void ShowExampleAppPropertyEditor(bool* p_open); +static void ShowExampleAppPropertyEditor(bool* p_open, ImGuiDemoWindowData* demo_data); static void ShowExampleAppSimpleOverlay(bool* p_open); static void ShowExampleAppAutoResize(bool* p_open); static void ShowExampleAppConstrainedResize(bool* p_open); @@ -217,10 +218,9 @@ static void ShowExampleMenuFile(); // We split the contents of the big ShowDemoWindow() function into smaller functions // (because the link time of very large functions tends to grow non-linearly) -struct DemoWindowData; -static void ShowDemoWindowMenuBar(DemoWindowData* demo_data); -static void ShowDemoWindowWidgets(DemoWindowData* demo_data); -static void ShowDemoWindowMultiSelect(DemoWindowData* demo_data); +static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data); +static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data); +static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data); static void ShowDemoWindowLayout(); static void ShowDemoWindowPopups(); static void ShowDemoWindowTables(); @@ -309,13 +309,14 @@ static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, Exampl // (this allocates _many_ more times than most other code in either Dear ImGui or others demo) static ExampleTreeNode* ExampleTree_CreateDemoTree() { - static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" }; char name_buf[32]; int uid = 0; ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); - for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * 2; idx_L0++) + const int root_items_multiplier = 2; + for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * root_items_multiplier; idx_L0++) { - snprintf(name_buf, 32, "%s %d", root_names[idx_L0 / 2], idx_L0 % 2); + snprintf(name_buf, 32, "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier); ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); const int number_of_childs = (int)strlen(node_L1->Name); for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) @@ -338,7 +339,8 @@ static ExampleTreeNode* ExampleTree_CreateDemoTree() // [SECTION] Demo Window / ShowDemoWindow() //----------------------------------------------------------------------------- -struct DemoWindowData +// Data to be shared accross different functions of the demo. +struct ImGuiDemoWindowData { // Examples Apps (accessible from the "Examples" menu) bool ShowMainMenuBar = false; @@ -362,6 +364,9 @@ struct DemoWindowData bool ShowIDStackTool = false; bool ShowStyleEditor = false; bool ShowAbout = false; + + // Other data + ExampleTreeNode* DemoTree = NULL; }; // Demonstrate most Dear ImGui features (this is big function!) @@ -377,32 +382,32 @@ void ImGui::ShowDemoWindow(bool* p_open) IMGUI_CHECKVERSION(); // Stored data - static DemoWindowData demo; + static ImGuiDemoWindowData demo_data; // Examples Apps (accessible from the "Examples" menu) - if (demo.ShowMainMenuBar) { ShowExampleAppMainMenuBar(); } - if (demo.ShowAppDocuments) { ShowExampleAppDocuments(&demo.ShowAppDocuments); } - if (demo.ShowAppAssetsBrowser) { ShowExampleAppAssetsBrowser(&demo.ShowAppAssetsBrowser); } - if (demo.ShowAppConsole) { ShowExampleAppConsole(&demo.ShowAppConsole); } - if (demo.ShowAppCustomRendering) { ShowExampleAppCustomRendering(&demo.ShowAppCustomRendering); } - if (demo.ShowAppLog) { ShowExampleAppLog(&demo.ShowAppLog); } - if (demo.ShowAppLayout) { ShowExampleAppLayout(&demo.ShowAppLayout); } - if (demo.ShowAppPropertyEditor) { ShowExampleAppPropertyEditor(&demo.ShowAppPropertyEditor); } - if (demo.ShowAppSimpleOverlay) { ShowExampleAppSimpleOverlay(&demo.ShowAppSimpleOverlay); } - if (demo.ShowAppAutoResize) { ShowExampleAppAutoResize(&demo.ShowAppAutoResize); } - if (demo.ShowAppConstrainedResize) { ShowExampleAppConstrainedResize(&demo.ShowAppConstrainedResize); } - if (demo.ShowAppFullscreen) { ShowExampleAppFullscreen(&demo.ShowAppFullscreen); } - if (demo.ShowAppLongText) { ShowExampleAppLongText(&demo.ShowAppLongText); } - if (demo.ShowAppWindowTitles) { ShowExampleAppWindowTitles(&demo.ShowAppWindowTitles); } + if (demo_data.ShowMainMenuBar) { ShowExampleAppMainMenuBar(); } + if (demo_data.ShowAppDocuments) { ShowExampleAppDocuments(&demo_data.ShowAppDocuments); } + if (demo_data.ShowAppAssetsBrowser) { ShowExampleAppAssetsBrowser(&demo_data.ShowAppAssetsBrowser); } + if (demo_data.ShowAppConsole) { ShowExampleAppConsole(&demo_data.ShowAppConsole); } + if (demo_data.ShowAppCustomRendering) { ShowExampleAppCustomRendering(&demo_data.ShowAppCustomRendering); } + if (demo_data.ShowAppLog) { ShowExampleAppLog(&demo_data.ShowAppLog); } + if (demo_data.ShowAppLayout) { ShowExampleAppLayout(&demo_data.ShowAppLayout); } + if (demo_data.ShowAppPropertyEditor) { ShowExampleAppPropertyEditor(&demo_data.ShowAppPropertyEditor, &demo_data); } + if (demo_data.ShowAppSimpleOverlay) { ShowExampleAppSimpleOverlay(&demo_data.ShowAppSimpleOverlay); } + if (demo_data.ShowAppAutoResize) { ShowExampleAppAutoResize(&demo_data.ShowAppAutoResize); } + if (demo_data.ShowAppConstrainedResize) { ShowExampleAppConstrainedResize(&demo_data.ShowAppConstrainedResize); } + if (demo_data.ShowAppFullscreen) { ShowExampleAppFullscreen(&demo_data.ShowAppFullscreen); } + if (demo_data.ShowAppLongText) { ShowExampleAppLongText(&demo_data.ShowAppLongText); } + if (demo_data.ShowAppWindowTitles) { ShowExampleAppWindowTitles(&demo_data.ShowAppWindowTitles); } // Dear ImGui Tools (accessible from the "Tools" menu) - if (demo.ShowMetrics) { ImGui::ShowMetricsWindow(&demo.ShowMetrics); } - if (demo.ShowDebugLog) { ImGui::ShowDebugLogWindow(&demo.ShowDebugLog); } - if (demo.ShowIDStackTool) { ImGui::ShowIDStackToolWindow(&demo.ShowIDStackTool); } - if (demo.ShowAbout) { ImGui::ShowAboutWindow(&demo.ShowAbout); } - if (demo.ShowStyleEditor) + if (demo_data.ShowMetrics) { ImGui::ShowMetricsWindow(&demo_data.ShowMetrics); } + if (demo_data.ShowDebugLog) { ImGui::ShowDebugLogWindow(&demo_data.ShowDebugLog); } + if (demo_data.ShowIDStackTool) { ImGui::ShowIDStackToolWindow(&demo_data.ShowIDStackTool); } + if (demo_data.ShowAbout) { ImGui::ShowAboutWindow(&demo_data.ShowAbout); } + if (demo_data.ShowStyleEditor) { - ImGui::Begin("Dear ImGui Style Editor", &demo.ShowStyleEditor); + ImGui::Begin("Dear ImGui Style Editor", &demo_data.ShowStyleEditor); ImGui::ShowStyleEditor(); ImGui::End(); } @@ -452,7 +457,7 @@ void ImGui::ShowDemoWindow(bool* p_open) //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align) // Menu Bar - ShowDemoWindowMenuBar(&demo); + ShowDemoWindowMenuBar(&demo_data); ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); ImGui::Spacing(); @@ -573,7 +578,7 @@ void ImGui::ShowDemoWindow(bool* p_open) IMGUI_DEMO_MARKER("Configuration/Style"); if (ImGui::TreeNode("Style")) { - ImGui::Checkbox("Style Editor", &demo.ShowStyleEditor); + ImGui::Checkbox("Style Editor", &demo_data.ShowStyleEditor); ImGui::SameLine(); HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function."); ImGui::TreePop(); @@ -621,7 +626,7 @@ void ImGui::ShowDemoWindow(bool* p_open) } // All demo contents - ShowDemoWindowWidgets(&demo); + ShowDemoWindowWidgets(&demo_data); ShowDemoWindowLayout(); ShowDemoWindowPopups(); ShowDemoWindowTables(); @@ -636,7 +641,7 @@ void ImGui::ShowDemoWindow(bool* p_open) // [SECTION] ShowDemoWindowMenuBar() //----------------------------------------------------------------------------- -static void ShowDemoWindowMenuBar(DemoWindowData* demo_data) +static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Menu"); if (ImGui::BeginMenuBar()) @@ -701,7 +706,7 @@ static void ShowDemoWindowMenuBar(DemoWindowData* demo_data) // [SECTION] ShowDemoWindowWidgets() //----------------------------------------------------------------------------- -static void ShowDemoWindowWidgets(DemoWindowData* demo_data) +static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Widgets"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); @@ -3098,7 +3103,7 @@ struct ExampleDualListBox // Also read: https://github.com/ocornut/imgui/wiki/Multi-Select //----------------------------------------------------------------------------- -static void ShowDemoWindowMultiSelect(DemoWindowData* demo_data) +static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); if (ImGui::TreeNode("Selection State & Multi-Select")) @@ -3580,11 +3585,13 @@ static void ShowDemoWindowMultiSelect(DemoWindowData* demo_data) }; // ExampleTreeFuncs static ImGuiSelectionBasicStorage selection; - static ExampleTreeNode* tree = ExampleTree_CreateDemoTree(); // Create tree once + if (demo_data->DemoTree == NULL) + demo_data->DemoTree = ExampleTree_CreateDemoTree(); // Create tree once ImGui::Text("Selection size: %d", selection.Size); if (ImGui::BeginChild("##Tree", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY)) { + ExampleTreeNode* tree = demo_data->DemoTree; ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect2d; ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, selection.Size, -1); ExampleTreeFuncs::ApplySelectionRequests(ms_io, tree, &selection); @@ -4597,8 +4604,8 @@ static void ShowDemoWindowLayout() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Layout/Clipping"); - if (ImGui::TreeNode("Clipping")) + IMGUI_DEMO_MARKER("Layout/Text Clipping"); + if (ImGui::TreeNode("Text Clipping")) { static ImVec2 size(100.0f, 100.0f); static ImVec2 offset(30.0f, 30.0f); @@ -8868,6 +8875,7 @@ struct ExampleAppPropertyEditor ImGui::TableNextRow(); ImGui::PushID(field_desc.Name); ImGui::TableNextColumn(); + ImGui::AlignTextToFramePadding(); ImGui::TextUnformatted(field_desc.Name); ImGui::TableNextColumn(); void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset); @@ -8933,7 +8941,7 @@ struct ExampleAppPropertyEditor }; // Demonstrate creating a simple property editor. -static void ShowExampleAppPropertyEditor(bool* p_open) +static void ShowExampleAppPropertyEditor(bool* p_open, ImGuiDemoWindowData* demo_data) { ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver); if (!ImGui::Begin("Example: Property editor", p_open)) @@ -8944,8 +8952,9 @@ static void ShowExampleAppPropertyEditor(bool* p_open) IMGUI_DEMO_MARKER("Examples/Property Editor"); static ExampleAppPropertyEditor property_editor; - static ExampleTreeNode* tree_data = ExampleTree_CreateDemoTree(); - property_editor.Draw(tree_data); + if (demo_data->DemoTree == NULL) + demo_data->DemoTree = ExampleTree_CreateDemoTree(); + property_editor.Draw(demo_data->DemoTree); ImGui::End(); } From ec9a4ef487acde06cf1840b1b13310a6c0ba7d62 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 30 Jul 2024 12:22:29 +0200 Subject: [PATCH 0270/2359] Clipper: accept that no item have been submitted if in indeterminate Begin(INT_MAX) mode. (#1311, #3823) --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 97ee6fe1a..728fc0832 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3062,7 +3062,8 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y); if (affected_by_floating_point_precision) clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries. - + if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode. + return false; IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!"); calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards. } From 8199457a7d9e453f8d3d9cadc14683fb54a858b5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 30 Jul 2024 14:49:07 +0200 Subject: [PATCH 0271/2359] Version 1.91.0 --- docs/CHANGELOG.txt | 110 ++++++++++++++++++++++++--------------------- imgui.cpp | 4 +- imgui.h | 22 ++++----- imgui_demo.cpp | 4 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 78 insertions(+), 70 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1c4bd71a1..8c83dadff 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.91.0 WIP (In Progress) + VERSION 1.91.0 (Released 2024-07-30) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.0 + Breaking changes: - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness. @@ -46,7 +48,7 @@ Breaking changes: - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); It is expected that for a vast majority of users this is automatically set by core library and/or platform backend so it won't have any effect. -- Obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). +- Obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (#7838) You should never need those functions! You can do everything in less a confusing manner by only using GetCursorScreenPos() and GetContentRegionAvail(). Also always consider that if you are using GetWindowPos() and GetCursorPos() you may also be making things unnecessarily complicated. @@ -69,32 +71,24 @@ Breaking changes: - Commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456) - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc. - Backends: GLFW+Emscripten: Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to - ImGui_ImplGlfw_InstallEmscriptenCallbacks(), with additional GLFWWindow* parameter. (#7647) [@ypujante] + ImGui_ImplGlfw_InstallEmscriptenCallbacks(), with an additional GLFWWindow* parameter. (#7647) [@ypujante] Other changes: - Added TextLink(), TextLinkOpenURL() hyperlink widgets. (#7660) - IO: added io.PlatformOpenInShellFn handler to open a link/folder/file in OS shell. (#7660) - Default to use ShellExecute() under Windows, and system("") under Mac/Linux/etc. - Added IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS to disable default implementation. -- IO: added io.ConfigNavSwapGamepadButtons to swap Activate/Cancel (A<>B) buttons, to match tye + Added IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS to disable default Windows/Linux/Mac implementations. +- IO: added io.ConfigNavSwapGamepadButtons to swap Activate/Cancel (A<>B) buttons, to match the typical "Nintendo/Japanese consoles" button layout when using Gamepad navigation. (#787, #5723) - Added PushItemFlag()/PopItemFlags(), ImGuiItemFlags to modify shared item flags: - - Added ImGuiItemFlags_NoTabStop to disable tabbing through items. - - Added ImGuiItemFlags_NoNav to disable any navigation and focus of items. (#787) - - Added ImGuiItemFlags_NoNavDefaultFocus to disable item being default focus. (#787) - - Added ImGuiItemFlags_ButtonRepeat to enable repeat on any button-like behavior. - - Added ImGuiItemFlags_AutoClosePopups to disable menu items/selection auto closing parent popups. - Disabling this was previously possible for Selectable() via a direct flag but not for MenuItem(). - (#1379, #1468, #2200, #4936, #5216, #7302, #7573) - - This was mostly all previously in imgui_internal.h. -- Inputs: added SetItemKeyOwner(ImGuiKey key) in public API. This is a simplified version of a more - complete set of function available in imgui_internal.h. One common use-case for this is to allow - your items to disable standard inputs behaviors such as Tab or Alt handling, Mouse Wheel scrolling, - etc. (#456, #2637, #2620, #2891, #3370, #3724, #4828, #5108, #5242, #5641) - // Hovering or activating the button will disable mouse wheel default behavior to scroll - InvisibleButton(...); - SetItemKeyOwner(ImGuiKey_MouseWheelY); + - Added ImGuiItemFlags_NoTabStop to disable tabbing through items. + - Added ImGuiItemFlags_NoNav to disable any navigation and focus of items. (#787) + - Added ImGuiItemFlags_NoNavDefaultFocus to disable item being default focus. (#787) + - Added ImGuiItemFlags_ButtonRepeat to enable repeat on any button-like behavior. + - Added ImGuiItemFlags_AutoClosePopups to disable menu items/selection auto closing parent popups. + Disabling this was previously possible for Selectable() via a direct flag but not for MenuItem(). + (#1379, #1468, #2200, #4936, #5216, #7302, #7573) + - This was mostly all previously in imgui_internal.h. - Multi-Select: added multi-select API and demos. (#1861, #6518) - This system implements standard multi-selection idioms (CTRL+mouse click, CTRL+keyboard moves, SHIFT+mouse click, SHIFT+keyboard moves, etc.) with support for clipper (not submitting non-visible @@ -103,15 +97,16 @@ Other changes: This is designed to allow all kinds of selection storage you may use in your application (e.g. set/map/hash, intrusive selection, interval trees, up to you). - The supported widgets are Selectable(), Checkbox(). TreeNode() is also technically supported but... - using this correctly is more complicated (you need some sort of linear/random access to your tree, + using this correctly is more complicated. You need some sort of linear/random access to your tree, which is suited to advanced trees setups already implementing filters and clipper. - We will work toward simplifying and demoing this later. - - A helper ImGuiSelectionBasicStorage is provided to facilitate getting started in a typical app. + We will work toward simplifying our existing demo for trees. + - A helper ImGuiSelectionBasicStorage is provided to facilitate getting started in a typical app + (likely to suit a majority of users). - Documentation: - Wiki page https://github.com/ocornut/imgui/wiki/Multi-Select for API overview. - Demo code + headers are well commented. - Added BeginMultiSelect(), EndMultiSelect(), SetNextItemSelectionUserData(). - - Added IsItemToggledSelection() for use if you need latest selection update during currnet iteration. + - Added IsItemToggledSelection() for use if you need latest selection update during current iteration. - Added ImGuiMultiSelectIO and ImGuiSelectionRequest structures: - BeginMultiSelect() and EndMultiSelect() return a ImGuiMultiSelectIO structure, which is mostly an array of ImGuiSelectionRequest actions (clear, select all, set range, etc.) @@ -142,12 +137,23 @@ Other changes: - Multi-Select (with clipper) - Multi-Select (with deletion) - Multi-Select (dual list box) (#6648) + - Multi-Select (in a table) - Multi-Select (checkboxes) - Multi-Select (multiple scopes) + - Multi-Select (tiled assert browser) + - Multi-Select (trees) (#1861) - Multi-Select (advanced) +- Inputs: added SetItemKeyOwner(ImGuiKey key) in public API. + This is a simplified version of a more complete set of function available in imgui_internal.h. + One common use-case for this is to allow your widgets to disable standard inputs behaviors such + as Tab or Alt handling, Mouse Wheel scrolling, etc. + (#456, #2637, #2620, #2891, #3370, #3724, #4828, #5108, #5242, #5641) + // Hovering or activating the button will disable mouse wheel default behavior to scroll + InvisibleButton(...); + SetItemKeyOwner(ImGuiKey_MouseWheelY); - Nav: fixed clicking window decorations (e.g. resize borders) from losing focused item when within a child window using ImGuiChildFlags_NavFlattened. -- InputText: added '\' and '/' as word seperator. (#7824, #7704) [@reduf] +- InputText: added '\' and '/' as word separator. (#7824, #7704) [@reduf] - TreeNode: added SetNextItemStorageID() to specify/override the identifier used for persisting open/close storage. Useful if needing to often read/write from storage without manipulating the ID stack. (#7553, #6990, #3823, #1131) @@ -155,35 +161,37 @@ Other changes: the hovered state. (#7820) [@rerilier] - Clipper: added SeekCursorForItem() function. When using ImGuiListClipper::Begin(INT_MAX) you can can use the clipper without knowing the amount of items beforehand. (#1311) - In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) as the end of your iteration + In this situation, call ImGuiListClipper::SeekCursorForItem(items_count) at the end of your iteration loop to position the layout cursor correctly. This is done automatically if provided a count to Begin(). - Groups, Tables: fixed EndGroup() failing to correctly capture current table occupied size. (#7543) -- TabBar, Style: added style.TabBarOverlineSize / ImGuiStyleVar_TabBarOverlineSize to manipulate - thickness of the horizontal line over selectable tabs. [@DctrNoob] -- Misc: added GetID(int) variant for consistency. (#7111) +- Style, TabBar: added style.TabBarOverlineSize / ImGuiStyleVar_TabBarOverlineSize to manipulate + thickness of the horizontal line over selected tabs. [@DctrNoob] - Style: close button and collapse/window-menu button hover highlight made rectangular instead of round. -- Debug Tools: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) - Debug log entries add a imgui frame counter prefix + are redirected to ShowDebugLogWindow() and - other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. -- Debug Tools: Debug Log: Added "Configure Outputs.." button. (#5855) -- Debug Tools: Debug Log: Fixed incorrect checkbox layout when partially clipped. -- Demo: Reworked "Property Editor" demo in a manner that more ressemble the tree data and +- Misc: added GetID(int) variant for consistency. (#7111) +- Debug Tools: + - Debug Log: Added IMGUI_DEBUG_LOG(), ImGui::DebugLog() in public API. (#5855) + Printed entries include imgui frame counter prefix + are redirected to ShowDebugLogWindow() and + other configurable locations. Always call IMGUI_DEBUG_LOG() for maximum stripping in caller code. + - Debug Log: Added "Configure Outputs.." button. (#5855) + - Debug Log: Fixed incorrect checkbox layout when partially clipped. +- Demo: Reworked "Property Editor" demo in a manner that more resemble the tree data and struct description data that a real application would want to use. -- Backends: Win32: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. - (#7768, #4858, #2622) [@Aemony] -- Backends: SDL3: Update for API changes: SDL_GetGamepads() memory ownership change. (#7807) -- Backends: SDL3: Update for API changes: SDL_GetClipboardText() memory ownership change. (#7801) -- Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) -- Backends: SDL3: Update for API changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) [@wermipls] -- Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. -- Backends: GLFW,SDL2: Added io.PlatformOpenInShellFn handler for web/Emscripten versions. (#7660) - [@ypujante, @ocornut] -- Backends; GLFW+Emscripten: Added support for GLFW3 contrib port which fixes many of the things - not supported by the embedded GLFW: gamepad support, mouse cursor shapes, copy to clipboard, - workaround for Super/Meta key, different ways of resizing, multi-window (glfw/canvas) support. - (#7647) [@ypujante] -- Backends: GLFW+Emscripten: Fixed Emscripten warning when using mouse wheel on some setups - "Unable to preventDefault inside passive event listener". (#7647, #7600) [@ypujante] +- Backends: + - Backends: Win32: Fixed ImGuiMod_Super being mapped to VK_APPS instead of (VK_LWIN || VK_RWIN). + (#7768, #4858, #2622) [@Aemony] + - Backends: SDL3: Update for API changes: SDL_GetGamepads() memory ownership change. (#7807) + - Backends: SDL3: Update for API changes: SDL_GetClipboardText() memory ownership change. (#7801) + - Backends: SDL3: Update for API changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762) + - Backends: SDL3: Update for API changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) [@wermipls] + - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. + - Backends: GLFW,SDL2: Added io.PlatformOpenInShellFn handler for web/Emscripten versions. (#7660) + [@ypujante, @ocornut] + - Backends; GLFW+Emscripten: Added support for GLFW3 contrib port which fixes many of the things + not supported by the embedded GLFW: gamepad support, mouse cursor shapes, copy to clipboard, + workaround for Super/Meta key, different ways of resizing, multi-window (glfw/canvas) support. + (#7647) [@ypujante] + - Backends: GLFW+Emscripten: Fixed Emscripten warning when using mouse wheel on some setups + "Unable to preventDefault inside passive event listener". (#7647, #7600) [@ypujante] ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 728fc0832..2c8611266 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 WIP +// dear imgui, v1.91.0 // (main code and documentation) // Help: @@ -430,7 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). + - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info) you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way. - instead of: GetWindowContentRegionMax().x - GetCursorPos().x - you can use: GetContentRegionAvail().x diff --git a/imgui.h b/imgui.h index 898308bb5..05e48a175 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 WIP +// dear imgui, v1.91.0 // (headers) // Help: @@ -27,8 +27,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.0 WIP" -#define IMGUI_VERSION_NUM 19099 +#define IMGUI_VERSION "1.91.0" +#define IMGUI_VERSION_NUM 19100 #define IMGUI_HAS_TABLE /* @@ -480,7 +480,7 @@ namespace ImGui IMGUI_API void SetCursorPos(const ImVec2& local_pos); // [window-local] " IMGUI_API void SetCursorPosX(float local_x); // [window-local] " IMGUI_API void SetCursorPosY(float local_y); // [window-local] " - IMGUI_API ImVec2 GetCursorStartPos(); // [window-local] initial cursor position, in window-local coordinates + IMGUI_API ImVec2 GetCursorStartPos(); // [window-local] initial cursor position, in window-local coordinates. Call GetCursorScreenPos() after Begin() to get the absolute coordinates version. // Other layout functions IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. @@ -669,12 +669,12 @@ namespace ImGui 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. - // Multi-selection system for Selectable(), Checkbox() functions* + // 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. // - ImGuiSelectionUserData is often used to store your item index within the current view (but may store something else). // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. - // - (*) TreeNode() is technically supported but... using this correctly is more complicate: you need some sort of linear/random access to your tree, - // which is suited to advanced trees setups already implementing filters and clipper. We will work toward simplifying and demoing this. + // - TreeNode() is technically supported but... using this correctly is more complicated. You need some sort of linear/random access to your tree, + // which is suited to advanced trees setups already implementing filters and clipper. We will work simplifying the current demo. // - 'selection_size' and 'items_count' parameters are optional and used by a few features. If they are costly for you to compute, you may avoid them. IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size = -1, int items_count = -1); IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); @@ -2781,10 +2781,10 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to select all. ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). With BoxSelect is also ensure contiguous SetRange requests are not combined into one. This allows not handling interpolation in SetRange requests. - ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes) - ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes) - ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1 << 5, // Disable clearing selection when clicking/selecting an already selected item - ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. only full row Selectable()). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. + ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes). + ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes). + ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1 << 5, // Disable clearing selection when clicking/selecting an already selected item. + ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. full row Selectable()). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. ImGuiMultiSelectFlags_BoxSelect2d = 1 << 7, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This is slower: alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 8, // Disable scrolling when box-selecting near edges of scope. ImGuiMultiSelectFlags_ClearOnEscape = 1 << 9, // Clear selection when pressing Escape while scope is focused. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a5f7408c2..4d6c2bbf2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 WIP +// dear imgui, v1.91.0 // (demo code) // Help: @@ -3621,7 +3621,7 @@ static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) static bool use_deletion = true; static bool use_drag_drop = true; static bool show_in_table = false; - static bool show_color_button = false; + static bool show_color_button = true; static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d; static WidgetType widget_type = WidgetType_Selectable; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 69e4f854c..57486a6e2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 WIP +// dear imgui, v1.91.0 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 7e9b22607..ab43922ba 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 WIP +// dear imgui, v1.91.0 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 9c8262ff8..37dd70304 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 WIP +// dear imgui, v1.91.0 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8e35df662..2aa24efe8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 WIP +// dear imgui, v1.91.0 // (widgets code) /* From dcf54782d4be1070bab4821f06cdaf9181bfc528 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 31 Jul 2024 16:34:08 +0200 Subject: [PATCH 0272/2359] Version 1.91.WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8c83dadff..877cd8584 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.91.1 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking changes: + +Other changes: + + ----------------------------------------------------------------------- VERSION 1.91.0 (Released 2024-07-30) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 2c8611266..94c59e7ea 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 +// dear imgui, v1.91.1 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 05e48a175..5b22dfe71 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 +// dear imgui, v1.91.1 WIP // (headers) // Help: @@ -27,8 +27,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.0" -#define IMGUI_VERSION_NUM 19100 +#define IMGUI_VERSION "1.91.1 WIP" +#define IMGUI_VERSION_NUM 19101 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4d6c2bbf2..2800e9518 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 +// dear imgui, v1.91.1 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 57486a6e2..854ad4012 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 +// dear imgui, v1.91.1 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index ab43922ba..0e39b0874 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 +// dear imgui, v1.91.1 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 37dd70304..92c62949e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 +// dear imgui, v1.91.1 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2aa24efe8..5ca9a9d3c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.0 +// dear imgui, v1.91.1 WIP // (widgets code) /* From 887478793b8f61c5385131d823dbb8ad8e8e900f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 31 Jul 2024 16:55:17 +0200 Subject: [PATCH 0273/2359] Examples: SDL2 (all), SDL3 (all), Win32+OpenGL3: Rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) --- docs/CHANGELOG.txt | 4 ++++ examples/example_sdl2_directx11/main.cpp | 5 +++++ examples/example_sdl2_opengl2/main.cpp | 5 +++++ examples/example_sdl2_opengl3/main.cpp | 5 +++++ examples/example_sdl2_sdlrenderer2/main.cpp | 5 +++++ examples/example_sdl2_vulkan/main.cpp | 5 +++++ examples/example_sdl3_opengl3/main.cpp | 5 +++++ examples/example_sdl3_sdlrenderer3/main.cpp | 5 +++++ examples/example_win32_opengl3/main.cpp | 5 +++++ 9 files changed, 44 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 877cd8584..7c0eb2050 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,10 @@ Breaking changes: Other changes: +- Examples: SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle + minimization without burning CPU or GPU by running unthrottled code. (#7844) + + ----------------------------------------------------------------------- VERSION 1.91.0 (Released 2024-07-30) diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index 3275bafde..47c852d27 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -126,6 +126,11 @@ int main(int, char**) CreateRenderTarget(); } } + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplDX11_NewFrame(); diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index efb28edbc..a70edd225 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -105,6 +105,11 @@ int main(int, char**) if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) done = true; } + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplOpenGL2_NewFrame(); diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index d748c1360..2a4d7b9e7 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -140,6 +140,11 @@ int main(int, char**) if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) done = true; } + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 8bb309920..b186b6268 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -107,6 +107,11 @@ int main(int, char**) if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) done = true; } + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplSDLRenderer2_NewFrame(); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index afcebf1b9..cb116b76e 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -492,6 +492,11 @@ int main(int, char**) if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) done = true; } + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } // Resize swap chain? int fb_width, fb_height; diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index c4eee77d4..e6aba8809 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -136,6 +136,11 @@ int main(int, char**) if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) done = true; } + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 607d00b6b..951141548 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -111,6 +111,11 @@ int main(int, char**) if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) done = true; } + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplSDLRenderer3_NewFrame(); diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 594931dca..8ecd27a20 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -108,6 +108,11 @@ int main(int, char**) } if (done) break; + if (::IsIconic(hwnd)) + { + ::Sleep(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); From 71ee2ce3673c8182871cb0b8554f9caf089a5334 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 31 Jul 2024 17:33:24 +0200 Subject: [PATCH 0274/2359] Examples: GLFW: rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper. --- backends/imgui_impl_glfw.cpp | 14 ++++++++++++++ backends/imgui_impl_glfw.h | 3 +++ docs/CHANGELOG.txt | 6 ++++-- examples/example_glfw_opengl2/main.cpp | 5 +++++ examples/example_glfw_opengl3/main.cpp | 5 +++++ examples/example_glfw_vulkan/main.cpp | 5 +++++ 6 files changed, 36 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 305891624..df581537b 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-07-31: Added ImGui_ImplGlfw_Sleep() helper function for usage by our examples app, since GLFW doesn't provide one. // 2024-07-08: *BREAKING* Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWWindow* parameter. // 2024-07-08: Emscripten: Added support for GLFW3 contrib port (GLFW 3.4.0 features + bug fixes): to enable, replace -sUSE_GLFW=3 with --use-port=contrib.glfw3 (requires emscripten 3.1.59+) (https://github.com/pongasoft/emscripten-glfw) // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. @@ -99,6 +100,9 @@ #endif #include // for glfwGetCocoaWindow() #endif +#ifndef _WIN32 +#include // for usleep() +#endif #ifdef __EMSCRIPTEN__ #include @@ -825,6 +829,16 @@ void ImGui_ImplGlfw_NewFrame() ImGui_ImplGlfw_UpdateGamepads(); } +// GLFW doesn't provide a portable sleep function +void ImGui_ImplGlfw_Sleep(int milliseconds) +{ +#ifdef _WIN32 + ::Sleep(milliseconds); +#else + usleep(milliseconds * 1000); +#endif +} + #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 static EM_BOOL ImGui_ImplGlfw_OnCanvasSizeChange(int event_type, const EmscriptenUiEvent* event, void* user_data) { diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index c0eac1134..60b95bd99 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -57,4 +57,7 @@ IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event); +// GLFW helpers +IMGUI_IMPL_API void ImGui_ImplGlfw_Sleep(int milliseconds); + #endif // #ifndef IMGUI_DISABLE diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7c0eb2050..b265121e3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,8 +43,10 @@ Breaking changes: Other changes: -- Examples: SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle - minimization without burning CPU or GPU by running unthrottled code. (#7844) +- Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not + provide a way to do a portable sleep. (#7844) +- Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop + to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 5e47b0008..1fcec2b2a 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -91,6 +91,11 @@ int main(int, char**) // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); + if (glfwGetWindowAttrib(window, GLFW_ICONIFIED) != 0) + { + ImGui_ImplGlfw_Sleep(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplOpenGL2_NewFrame(); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 22ef79eb7..3afe251e3 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -127,6 +127,11 @@ int main(int, char**) // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); + if (glfwGetWindowAttrib(window, GLFW_ICONIFIED) != 0) + { + ImGui_ImplGlfw_Sleep(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index e1f099e3d..901b46c4c 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -494,6 +494,11 @@ int main(int, char**) g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } + if (glfwGetWindowAttrib(window, GLFW_ICONIFIED) != 0) + { + ImGui_ImplGlfw_Sleep(10); + continue; + } // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); From fd57b252ac1932760160947ca82b55b884f92600 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 31 Jul 2024 17:47:38 +0200 Subject: [PATCH 0275/2359] Examples: Fix for Emscripten. GLFW+WGPU: rework examples main loop to handle minimization. (#7844) Amend 8874787, 71ee2ce Amend ea39841f (emscripten_mainloop_stub.h) --- examples/example_glfw_wgpu/main.cpp | 5 +++++ examples/example_sdl3_sdlrenderer3/main.cpp | 3 +++ examples/libs/emscripten/emscripten_mainloop_stub.h | 7 ++++--- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index c5872bd85..f510987ed 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -151,6 +151,11 @@ int main(int, char**) // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); + if (glfwGetWindowAttrib(window, GLFW_ICONIFIED) != 0) + { + ImGui_ImplGlfw_Sleep(10); + continue; + } // React to changes in screen size int width, height; diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 951141548..6efd2754a 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -167,6 +167,9 @@ int main(int, char**) ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData(), renderer); SDL_RenderPresent(renderer); } +#ifdef __EMSCRIPTEN__ + EMSCRIPTEN_MAINLOOP_END; +#endif // Cleanup ImGui_ImplSDLRenderer3_Shutdown(); diff --git a/examples/libs/emscripten/emscripten_mainloop_stub.h b/examples/libs/emscripten/emscripten_mainloop_stub.h index 05cf60fed..8c4c48ecf 100644 --- a/examples/libs/emscripten/emscripten_mainloop_stub.h +++ b/examples/libs/emscripten/emscripten_mainloop_stub.h @@ -17,20 +17,21 @@ // - So the next logical step was to refactor all examples to follow that layout of using a "main loop" function. // This worked, but it made us lose all the nice things we had... -// Since only about 3 examples really need to run with Emscripten, here's our solution: +// Since only about 4 examples really need to run with Emscripten, here's our solution: // - Use some weird macros and capturing lambda to turn a loop in main() into a function. // - Hide all that crap in this file so it doesn't make our examples unusually ugly. // As a stance and principle of Dear ImGui development we don't use C++ headers and we don't // want to suggest to the newcomer that we would ever use C++ headers as this would affect // the initial judgment of many of our target audience. // - Technique is based on this idea: https://github.com/ocornut/imgui/pull/2492/ +// - The do { } while (0) is to allow our code calling continue in the main loop. #ifdef __EMSCRIPTEN__ #include #include static std::function MainLoopForEmscriptenP; static void MainLoopForEmscripten() { MainLoopForEmscriptenP(); } -#define EMSCRIPTEN_MAINLOOP_BEGIN MainLoopForEmscriptenP = [&]() -#define EMSCRIPTEN_MAINLOOP_END ; emscripten_set_main_loop(MainLoopForEmscripten, 0, true) +#define EMSCRIPTEN_MAINLOOP_BEGIN MainLoopForEmscriptenP = [&]() { do +#define EMSCRIPTEN_MAINLOOP_END while (0); }; emscripten_set_main_loop(MainLoopForEmscripten, 0, true) #else #define EMSCRIPTEN_MAINLOOP_BEGIN #define EMSCRIPTEN_MAINLOOP_END From 5e7dc72c926b489450e9ea82ea62fd3a6432d5aa Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Thu, 1 Aug 2024 00:04:34 +0200 Subject: [PATCH 0276/2359] Examples: SDL3: Update readme to use SDL3_DIR (#7846) --- examples/example_sdl3_opengl3/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/example_sdl3_opengl3/README.md b/examples/example_sdl3_opengl3/README.md index 5828e4bfc..a032f8752 100644 --- a/examples/example_sdl3_opengl3/README.md +++ b/examples/example_sdl3_opengl3/README.md @@ -9,11 +9,11 @@ Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) i Use build_win32.bat or directly: ``` -set SDL2_DIR=path_to_your_sdl3_folder -cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl3_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL3.lib opengl32.lib /subsystem:console +set SDL3_DIR=path_to_your_sdl3_folder +cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL3_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl3_opengl3.exe /FoDebug/ /link /libpath:%SDL3_DIR%\lib\x86 SDL3.lib opengl32.lib /subsystem:console # ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries # or for 64-bit: -cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl3_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL3.lib SDL2mainopengl32.lib /subsystem:console +cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL3_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl3_opengl3.exe /FoDebug/ /link /libpath:%SDL3_DIR%\lib\x64 SDL3.lib SDL2mainopengl32.lib /subsystem:console ``` ## Linux and similar Unixes From 2981a10c537cbc329e5b4e58af1e1a1146d55ea4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Aug 2024 17:16:13 +0200 Subject: [PATCH 0277/2359] MultiSelect, TreeNode, Drag and Drop: fixed an issue where carrying a drag and drop payload over an already open tree node would select it. (#7850) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b265121e3..3f0d9c4ea 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking changes: Other changes: +- MultiSelect, TreeNode, Drag and Drop: fixed an issue where carrying a drag and drop + payload over an already open tree node would incorrectly select it. (#7850) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5ca9a9d3c..0f0134b9d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6531,6 +6531,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold); if (!is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. toggled = true; + else + pressed = false; // Cancel press so it doesn't trigger selection. } if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open) From 9f8f5e11455e87cce4ebdefa422661951701dfae Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Aug 2024 17:28:47 +0200 Subject: [PATCH 0278/2359] MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow when used in a multi-select context without any OpenOnXXX flags set. (#7850) --- docs/CHANGELOG.txt | 4 +++- imgui.h | 4 ++-- imgui_internal.h | 1 + imgui_widgets.cpp | 14 +++++++------- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3f0d9c4ea..a495cd5d3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,8 +43,10 @@ Breaking changes: Other changes: -- MultiSelect, TreeNode, Drag and Drop: fixed an issue where carrying a drag and drop +- MultiSelect+TreeNode+Drag and Drop: fixed an issue where carrying a drag and drop payload over an already open tree node would incorrectly select it. (#7850) +- MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow + when used in a multi-select context without any OpenOnXXX flags set. (#7850) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop diff --git a/imgui.h b/imgui.h index 5b22dfe71..6d4f51388 100644 --- a/imgui.h +++ b/imgui.h @@ -1177,8 +1177,8 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open - ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node - ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding() before the node. diff --git a/imgui_internal.h b/imgui_internal.h index 0e39b0874..5b6d4c195 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -970,6 +970,7 @@ enum ImGuiTreeNodeFlagsPrivate_ { ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader() ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, but reversed trees (#6517) + ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, }; enum ImGuiSeparatorFlags_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0f0134b9d..11f1cdf60 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6475,6 +6475,10 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x; const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2); + const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; + if (is_multi_select) // We absolutely need to distinguish open vs select so _OpenOnArrow comes by default + flags |= (flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 ? ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick : ImGuiTreeNodeFlags_OpenOnArrow; + // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0) @@ -6495,16 +6499,12 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const bool was_selected = selected; // Multi-selection support (header) - const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0; if (is_multi_select) { // Handle multi-select + alter button flags for it MultiSelectItemHeader(id, &selected, &button_flags); if (is_mouse_x_over_arrow) button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease; - - // We absolutely need to distinguish open vs select so comes by default - flags |= ImGuiTreeNodeFlags_OpenOnArrow; } else { @@ -6519,12 +6519,12 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l { if (pressed && g.DragDropHoldJustPressedId != id) { - if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id && !is_multi_select)) - toggled = true; + if ((flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 || (g.NavActivateId == id && !is_multi_select)) + toggled = true; // Single click if (flags & ImGuiTreeNodeFlags_OpenOnArrow) toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2) - toggled = true; + toggled = true; // Double click } else if (pressed && g.DragDropHoldJustPressedId == id) { From 531364d72896f41c973730c2fbc0478da4ba64c6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Aug 2024 22:26:12 +0200 Subject: [PATCH 0279/2359] Window refresh policy: fixed child window of skiprefresh windows not displaying. (#7797) Amend d4495446d. (#3515, #4763, #7556, #5116 , #4076, #2749, #2268) --- imgui.cpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 94c59e7ea..edbf15069 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6531,6 +6531,17 @@ void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window) } } +static void SetWindowActiveForSkipRefresh(ImGuiWindow* window) +{ + window->Active = true; + for (ImGuiWindow* child : window->DC.ChildWindows) + if (!child->Hidden) + { + child->Active = child->SkipRefresh = true; + SetWindowActiveForSkipRefresh(child); + } +} + // 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. @@ -7233,7 +7244,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { // Skip refresh always mark active if (window->SkipRefresh) - window->Active = true; + SetWindowActiveForSkipRefresh(window); // Append SetCurrentWindow(window); From 6864a7f839ce78419d5db57a46c25c4216e9c712 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Aug 2024 22:40:09 +0200 Subject: [PATCH 0280/2359] Window refresh policy: extend tests to any window in the begin stack. (#7797) --- imgui.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index edbf15069..d1da2886e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6522,10 +6522,12 @@ void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window) return; if (window->Hidden) // If was hidden (previous frame) return; - if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow && window->RootWindow == g.HoveredWindow->RootWindow) - return; - if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow && window->RootWindow == g.NavWindow->RootWindow) - return; + if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow) + if (window->RootWindow == g.HoveredWindow->RootWindow || IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, window)) + return; + if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow) + if (window->RootWindow == g.NavWindow->RootWindow || IsWindowWithinBeginStackOf(g.NavWindow->RootWindow, window)) + return; window->DrawList = NULL; window->SkipRefresh = true; } From 8cc6eee295871bc8852c12372860a50b950d3f56 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 3 Aug 2024 15:25:47 +0200 Subject: [PATCH 0281/2359] Fonts: amend assert when glyph range data seems incorrect. (#7856) --- imgui_draw.cpp | 5 +++-- misc/freetype/imgui_freetype.cpp | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 854ad4012..32cf64353 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2815,8 +2815,9 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) { // Check for valid range. This may also help detect *some* dangling pointers, because a common - // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent. - IM_ASSERT(src_range[0] <= src_range[1]); + // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent, + // or to forget to zero-terminate the glyph range array. + IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?"); src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]); } dst_tmp.SrcCount++; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 68e38ed95..d97605b25 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -480,8 +480,9 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) { // Check for valid range. This may also help detect *some* dangling pointers, because a common - // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent. - IM_ASSERT(src_range[0] <= src_range[1]); + // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent, + // or to forget to zero-terminate the glyph range array. + IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?"); src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]); } dst_tmp.SrcCount++; From 4b654db9040851228857528b44e195e358868e9a Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Tue, 6 Aug 2024 20:27:23 +0200 Subject: [PATCH 0282/2359] CI: Build example_sdl2_sdlrenderer2 with msbuild (#7864) --- .github/workflows/build.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 48082d056..b223d2261 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -123,6 +123,11 @@ jobs: run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj /p:Platform=Win32 /p:Configuration=Release' if: github.event_name == 'workflow_run' + - name: Build Win32 example_sdl2_sdlrenderer2 + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + - name: Build Win32 example_sdl2_vulkan shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj /p:Platform=Win32 /p:Configuration=Release' @@ -168,6 +173,11 @@ jobs: shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' + - name: Build x64 example_sdl2_sdlrenderer2 + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj /p:Platform=x64 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + - name: Build x64 example_sdl2_vulkan shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' From 3232070d3abaec531d75e060fab14a26cb36ab55 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 Aug 2024 12:47:03 +0200 Subject: [PATCH 0283/2359] Demo: Fixed truncation warning. (#7857) --- imgui_demo.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2800e9518..264df8af4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -310,23 +310,24 @@ static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, Exampl static ExampleTreeNode* ExampleTree_CreateDemoTree() { static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" }; - char name_buf[32]; + const size_t NAME_MAX_LEN = sizeof(ExampleTreeNode::Name); + char name_buf[NAME_MAX_LEN]; int uid = 0; ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); const int root_items_multiplier = 2; for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * root_items_multiplier; idx_L0++) { - snprintf(name_buf, 32, "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier); + snprintf(name_buf, IM_ARRAYSIZE(name_buf), "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier); ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); const int number_of_childs = (int)strlen(node_L1->Name); for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) { - snprintf(name_buf, 32, "Child %d", idx_L1); + snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Child %d", idx_L1); ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1); node_L2->HasData = true; if (idx_L1 == 0) { - snprintf(name_buf, 32, "Sub-child %d", 0); + snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Sub-child %d", 0); ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2); node_L3->HasData = true; } From 45e7f7827a52462d83895d36c62d00e6eb33c266 Mon Sep 17 00:00:00 2001 From: lunarlattice <18731514+lunarlattice0@users.noreply.github.com> Date: Fri, 9 Aug 2024 03:27:38 -0700 Subject: [PATCH 0284/2359] Examples: SDL2+SDLRenderer: fixed return value. (#7876) --- examples/example_sdl2_sdlrenderer2/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index b186b6268..31fa3f9bf 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -47,7 +47,7 @@ int main(int, char**) if (renderer == nullptr) { SDL_Log("Error creating SDL_Renderer!"); - return 0; + return -1; } //SDL_RendererInfo info; //SDL_GetRendererInfo(renderer, &info); From 29fadad1939ab62adcc5cd9339db7a784de90120 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 13 Aug 2024 14:30:16 +0200 Subject: [PATCH 0285/2359] TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 3 +++ 2 files changed, 4 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a495cd5d3..386d330c8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,7 @@ Other changes: payload over an already open tree node would incorrectly select it. (#7850) - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow when used in a multi-select context without any OpenOnXXX flags set. (#7850) +- TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 11f1cdf60..d5c9fa077 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1425,6 +1425,9 @@ bool ImGui::TextLink(const char* label) bool pressed = ButtonBehavior(bb, id, &hovered, &held); RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_None); + if (hovered) + SetMouseCursor(ImGuiMouseCursor_Hand); + ImVec4 text_colf = g.Style.Colors[ImGuiCol_TextLink]; ImVec4 line_colf = text_colf; { From 591a18a9c4bf421de05a0eee7e85dea25f64209d Mon Sep 17 00:00:00 2001 From: Anonymous Maarten Date: Fri, 2 Aug 2024 00:05:51 +0200 Subject: [PATCH 0286/2359] Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) --- backends/imgui_impl_sdl2.cpp | 12 ++++++++++++ backends/imgui_impl_sdl3.cpp | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 15db0a843..2b115f360 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -321,6 +321,8 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) { case SDL_MOUSEMOTION: { + if (event->motion.windowID != SDL_GetWindowID(bd->Window)) + return false; ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); @@ -328,6 +330,8 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } case SDL_MOUSEWHEEL: { + if (event->wheel.windowID != SDL_GetWindowID(bd->Window)) + return false; //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); #if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten! float wheel_x = -event->wheel.preciseX; @@ -346,6 +350,8 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { + if (event->button.windowID != SDL_GetWindowID(bd->Window)) + return false; int mouse_button = -1; if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; } @@ -361,12 +367,16 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } case SDL_TEXTINPUT: { + if (event->text.windowID != SDL_GetWindowID(bd->Window)) + return false; io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_KEYDOWN: case SDL_KEYUP: { + if (event->key.windowID != SDL_GetWindowID(bd->Window)) + return false; ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod); ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode); io.AddKeyEvent(key, (event->type == SDL_KEYDOWN)); @@ -375,6 +385,8 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } case SDL_WINDOWEVENT: { + if (event->window.windowID != SDL_GetWindowID(bd->Window)) + return false; // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right. // - However we won't get a correct LEAVE event for a captured window. // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 05718d21c..a74a316d2 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -307,6 +307,8 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) { case SDL_EVENT_MOUSE_MOTION: { + if (event->motion.windowID != SDL_GetWindowID(bd->Window)) + return false; ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); @@ -314,6 +316,8 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) } case SDL_EVENT_MOUSE_WHEEL: { + if (event->wheel.windowID != SDL_GetWindowID(bd->Window)) + return false; //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); float wheel_x = -event->wheel.x; float wheel_y = event->wheel.y; @@ -327,6 +331,8 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) case SDL_EVENT_MOUSE_BUTTON_DOWN: case SDL_EVENT_MOUSE_BUTTON_UP: { + if (event->button.windowID != SDL_GetWindowID(bd->Window)) + return false; int mouse_button = -1; if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; } @@ -342,12 +348,16 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) } case SDL_EVENT_TEXT_INPUT: { + if (event->text.windowID != SDL_GetWindowID(bd->Window)) + return false; io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: { + if (event->key.windowID != SDL_GetWindowID(bd->Window)) + return false; //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod); ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode); @@ -357,6 +367,8 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) } case SDL_EVENT_WINDOW_MOUSE_ENTER: { + if (event->window.windowID != SDL_GetWindowID(bd->Window)) + return false; bd->MouseWindowID = event->window.windowID; bd->MousePendingLeaveFrame = 0; return true; @@ -367,13 +379,19 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) // FIXME: Unconfirmed whether this is still needed with SDL3. case SDL_EVENT_WINDOW_MOUSE_LEAVE: { + if (event->window.windowID != SDL_GetWindowID(bd->Window)) + return false; bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1; return true; } case SDL_EVENT_WINDOW_FOCUS_GAINED: + if (event->window.windowID != SDL_GetWindowID(bd->Window)) + return false; io.AddFocusEvent(true); return true; case SDL_EVENT_WINDOW_FOCUS_LOST: + if (event->window.windowID != SDL_GetWindowID(bd->Window)) + return false; io.AddFocusEvent(false); return true; case SDL_EVENT_GAMEPAD_ADDED: From 1b61d55079a66692207562c4d8d711527954f514 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Aug 2024 13:57:08 +0200 Subject: [PATCH 0287/2359] Backends: SDL2, SDL3: ignore events of other SDL windows, amends + wrapping into a function as it'll be convenient for multi-viewport check. (#7853) + Misc typo fix. --- backends/imgui_impl_sdl2.cpp | 21 +++++++++++++++------ backends/imgui_impl_sdl3.cpp | 34 +++++++++++++++++++++------------- docs/CHANGELOG.txt | 1 + imgui.h | 2 +- 4 files changed, 38 insertions(+), 20 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 2b115f360..9fff2ab56 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-19: ImGui_ImplSDL2_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. // 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode(). @@ -110,6 +111,7 @@ struct ImGui_ImplSDL2_Data { SDL_Window* Window; + Uint32 WindowID; SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; @@ -306,6 +308,12 @@ static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0); } +static ImGuiViewport* ImGui_ImplSDL2_GetViewportForWindowID(Uint32 window_id) +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : NULL; +} + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. @@ -321,7 +329,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) { case SDL_MOUSEMOTION: { - if (event->motion.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == NULL) return false; ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); @@ -330,7 +338,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } case SDL_MOUSEWHEEL: { - if (event->wheel.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == NULL) return false; //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); #if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten! @@ -350,7 +358,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { - if (event->button.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == NULL) return false; int mouse_button = -1; if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } @@ -367,7 +375,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } case SDL_TEXTINPUT: { - if (event->text.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == NULL) return false; io.AddInputCharactersUTF8(event->text.text); return true; @@ -375,7 +383,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) case SDL_KEYDOWN: case SDL_KEYUP: { - if (event->key.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID) == NULL) return false; ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod); ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode); @@ -385,7 +393,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } case SDL_WINDOWEVENT: { - if (event->window.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID) == NULL) return false; // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right. // - However we won't get a correct LEAVE event for a captured window. @@ -445,6 +453,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Window = window; + bd->WindowID = SDL_GetWindowID(window); bd->Renderer = renderer; bd->MouseCanUseGlobalState = mouse_can_use_global_state; diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index a74a316d2..5a58c9688 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807) // 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801) // 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) @@ -80,6 +81,7 @@ struct ImGui_ImplSDL3_Data { SDL_Window* Window; + SDL_WindowID WindowID; SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; @@ -292,6 +294,13 @@ static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0); } + +static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : NULL; +} + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. @@ -307,7 +316,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) { case SDL_EVENT_MOUSE_MOTION: { - if (event->motion.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == NULL) return false; ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); @@ -316,7 +325,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) } case SDL_EVENT_MOUSE_WHEEL: { - if (event->wheel.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == NULL) return false; //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); float wheel_x = -event->wheel.x; @@ -331,7 +340,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) case SDL_EVENT_MOUSE_BUTTON_DOWN: case SDL_EVENT_MOUSE_BUTTON_UP: { - if (event->button.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == NULL) return false; int mouse_button = -1; if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } @@ -348,7 +357,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) } case SDL_EVENT_TEXT_INPUT: { - if (event->text.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == NULL) return false; io.AddInputCharactersUTF8(event->text.text); return true; @@ -356,7 +365,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: { - if (event->key.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == NULL) return false; //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod); ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); @@ -367,7 +376,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) } case SDL_EVENT_WINDOW_MOUSE_ENTER: { - if (event->window.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) return false; bd->MouseWindowID = event->window.windowID; bd->MousePendingLeaveFrame = 0; @@ -379,21 +388,19 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) // FIXME: Unconfirmed whether this is still needed with SDL3. case SDL_EVENT_WINDOW_MOUSE_LEAVE: { - if (event->window.windowID != SDL_GetWindowID(bd->Window)) + if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) return false; bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1; return true; } case SDL_EVENT_WINDOW_FOCUS_GAINED: - if (event->window.windowID != SDL_GetWindowID(bd->Window)) - return false; - io.AddFocusEvent(true); - return true; case SDL_EVENT_WINDOW_FOCUS_LOST: - if (event->window.windowID != SDL_GetWindowID(bd->Window)) + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) return false; - io.AddFocusEvent(false); + io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED); return true; + } case SDL_EVENT_GAMEPAD_ADDED: case SDL_EVENT_GAMEPAD_REMOVED: { @@ -441,6 +448,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Window = window; + bd->WindowID = SDL_GetWindowID(window); bd->Renderer = renderer; bd->MouseCanUseGlobalState = mouse_can_use_global_state; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 386d330c8..e272b19ec 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,7 @@ Other changes: - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) +- Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) diff --git a/imgui.h b/imgui.h index 6d4f51388..9080bb1b5 100644 --- a/imgui.h +++ b/imgui.h @@ -3385,7 +3385,7 @@ struct ImFontAtlas struct ImFont { // Members: Hot ~20/24 bytes (for CalcTextSize) - ImVector IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI). + ImVector IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) From 2d99052d1d43bd17a72bce0531c605b30aa6bc0b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Aug 2024 14:07:25 +0200 Subject: [PATCH 0288/2359] Backends: SDL2, SDL3: storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. (#7853) This will be used to support filtering of events with multi-viewports. --- backends/imgui_impl_sdl2.cpp | 3 ++- backends/imgui_impl_sdl3.cpp | 6 ++++-- docs/CHANGELOG.txt | 1 + 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 9fff2ab56..c4724969d 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-19: Storing SDL's Uint32 WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. // 2024-08-19: ImGui_ImplSDL2_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. @@ -483,7 +484,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void // Set platform dependent data in viewport // Our mouse update function expect PlatformHandle to be filled for the main viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - main_viewport->PlatformHandle = (void*)window; + main_viewport->PlatformHandle = (void*)(intptr_t)bd->WindowID; main_viewport->PlatformHandleRaw = nullptr; SDL_SysWMinfo info; SDL_VERSION(&info.version); diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 5a58c9688..24627347b 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. // 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807) // 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801) @@ -133,7 +134,8 @@ static void ImGui_ImplSDL3_SetClipboardText(void*, const char* text) static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); - SDL_Window* window = (SDL_Window*)viewport->PlatformHandle; + SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle; + SDL_Window* window = SDL_GetWindowFromID(window_id); if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != NULL) { SDL_StopTextInput(bd->ImeWindow); @@ -413,7 +415,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window) { - viewport->PlatformHandle = window; + viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(window); viewport->PlatformHandleRaw = nullptr; #if defined(_WIN32) && !defined(__WINRT__) viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e272b19ec..24f6c640c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other changes: - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) - Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] +- Backends: SDL2, SDL3: storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) From 61313a75891c6cdb9ad313bd0f6e11eb6fde2c67 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Aug 2024 16:31:49 +0200 Subject: [PATCH 0289/2359] Docs: better promote IMGUI_DEFINE_MATH_OPERATORS. (#6164, #6137, #5966, #2832) --- imgui.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 9080bb1b5..b531bebc6 100644 --- a/imgui.h +++ b/imgui.h @@ -5,6 +5,7 @@ // - See links below. // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // - Read top of imgui.cpp for more details, links and comments. +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. // Resources: // - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) @@ -280,8 +281,8 @@ typedef void* (*ImGuiMemAllocFunc)(size_t sz, void* user_data); typedef void (*ImGuiMemFreeFunc)(void* ptr, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() // ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] -// This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type. -// Add '#define IMGUI_DEFINE_MATH_OPERATORS' in your imconfig.h file to benefit from courtesy maths operators for those types. +// - This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type. +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. IM_MSVC_RUNTIME_CHECKS_OFF struct ImVec2 { @@ -2664,7 +2665,7 @@ struct ImGuiListClipper // Helpers: ImVec2/ImVec4 operators // - It is important that we are keeping those disabled by default so they don't leak in user space. // - This is in order to allow user enabling implicit cast operators between ImVec2/ImVec4 and their own types (using IM_VEC2_CLASS_EXTRA in imconfig.h) -// - You can use '#define IMGUI_DEFINE_MATH_OPERATORS' to import our operators, provided as a courtesy. +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. #ifdef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED IM_MSVC_RUNTIME_CHECKS_OFF From fabceaf03695ec0d8044d58b15460edd171cf7ea Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Aug 2024 18:28:56 +0200 Subject: [PATCH 0290/2359] Internals: renamed IsModKey() -> IsLRModKey() and GetModForModKey() -> GetModForLRModKey() to be more explicit. --- imgui.cpp | 12 ++++++------ imgui_internal.h | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d1da2886e..74236c1a4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8407,7 +8407,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- // [SECTION] INPUTS //----------------------------------------------------------------------------- -// - GetModForModKey() [Internal] +// - GetModForLRModKey() [Internal] // - FixupKeyChord() [Internal] // - GetKeyData() [Internal] // - GetKeyIndex() [Internal] @@ -8470,7 +8470,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // - Shortcut() [Internal] //----------------------------------------------------------------------------- -static ImGuiKeyChord GetModForModKey(ImGuiKey key) +static ImGuiKeyChord GetModForLRModKey(ImGuiKey key) { if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl) return ImGuiMod_Ctrl; @@ -8487,8 +8487,8 @@ ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord) { // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified. ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); - if (IsModKey(key)) - key_chord |= GetModForModKey(key); + if (IsLRModKey(key)) + key_chord |= GetModForLRModKey(key); return key_chord; } @@ -8579,8 +8579,8 @@ const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord) ImGuiContext& g = *GImGui; const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); - if (IsModKey(key)) - key_chord &= ~GetModForModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift" + if (IsLRModKey(key)) + key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift" ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s", (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "", (key_chord & ImGuiMod_Shift) ? "Shift+" : "", diff --git a/imgui_internal.h b/imgui_internal.h index 5b6d4c195..339a4e3a6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3298,7 +3298,7 @@ namespace ImGui inline bool IsGamepadKey(ImGuiKey key) { return key >= ImGuiKey_Gamepad_BEGIN && key < ImGuiKey_Gamepad_END; } inline bool IsMouseKey(ImGuiKey key) { return key >= ImGuiKey_Mouse_BEGIN && key < ImGuiKey_Mouse_END; } inline bool IsAliasKey(ImGuiKey key) { return key >= ImGuiKey_Aliases_BEGIN && key < ImGuiKey_Aliases_END; } - inline bool IsModKey(ImGuiKey key) { return key >= ImGuiKey_LeftCtrl && key <= ImGuiKey_RightSuper; } + inline bool IsLRModKey(ImGuiKey key) { return key >= ImGuiKey_LeftCtrl && key <= ImGuiKey_RightSuper; } ImGuiKeyChord FixupKeyChord(ImGuiKeyChord key_chord); inline ImGuiKey ConvertSingleModFlagToKey(ImGuiKey key) { From 092c88dc7bdd6e736f0313fc366f7d20c18da519 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Aug 2024 19:02:27 +0200 Subject: [PATCH 0291/2359] IO: rework interleaved keys<>char trickling: only trickle for keys known to be likely to input characters. (#7889, #4921, #4858) Amend fa2b318d. Refer to regression test "inputs_io_inputqueue" amended for IMGUI_VERSION_NUM >= 19102 --- imgui.cpp | 26 +++++++++++++++++++------- imgui.h | 2 +- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 74236c1a4..ed7983542 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8780,8 +8780,9 @@ static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInput return 0; } -// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active -// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be. +// - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active +// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be. +// - This is also used by UpdateInputEvents() to avoid trickling in the most common case of e.g. pressing ImGuiKey_G also emitting a G character. static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord) { // Mimic 'ignore_char_inputs' logic in InputText() @@ -8795,6 +8796,8 @@ static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord) // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered. ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); + if (key == ImGuiKey_None) + return false; return g.KeysMayBeCharInput.TestBit(key); } @@ -9599,9 +9602,9 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) // Only trickle chars<>key when working with InputText() // FIXME: InputText() could parse event trail? // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters) - const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1); + const bool trickle_interleaved_nonchar_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1); - bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false; + bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false; int mouse_button_changed = 0x00; ImBitArray key_changed_mask; @@ -9653,12 +9656,19 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) IM_ASSERT(key != ImGuiKey_None); ImGuiKeyData* key_data = GetKeyData(key); const int key_data_index = (int)(key_data - g.IO.KeysData); - if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0)) + if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || mouse_button_changed != 0)) break; + + const bool key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(GetMergedModsFromKeys() | key); + if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input)) + break; + key_data->Down = e->Key.Down; key_data->AnalogValue = e->Key.AnalogValue; key_changed = true; key_changed_mask.SetBit(key_data_index); + if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input) + key_changed_nonchar = true; // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO @@ -9672,11 +9682,13 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) continue; // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with - if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled)) + if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_moved || mouse_wheeled)) + break; + if (trickle_interleaved_nonchar_keys_and_text && key_changed_nonchar) break; unsigned int c = e->Text.Char; io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID); - if (trickle_interleaved_keys_and_text) + if (trickle_interleaved_nonchar_keys_and_text) text_inputted = true; } else if (e->Type == ImGuiInputEventType_Focus) diff --git a/imgui.h b/imgui.h index b531bebc6..1d7759199 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.1 WIP" -#define IMGUI_VERSION_NUM 19101 +#define IMGUI_VERSION_NUM 19102 #define IMGUI_HAS_TABLE /* From ecb1962013d280499c047e4523ceabd4a223d629 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Aug 2024 19:10:03 +0200 Subject: [PATCH 0292/2359] IO, InputText: missing changelog entry (amend 092c88d) + readme note on missing features. --- docs/CHANGELOG.txt | 3 +++ docs/README.md | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 24f6c640c..40b651f42 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- IO, InputText: fixed an issue where typing text in a InputText() would defer character + processing by one frame, because of the trickling input queue. Reworked interleaved + keys<>char trickling to take account for keys known to input characters. (#7889, #4921, #4858) - MultiSelect+TreeNode+Drag and Drop: fixed an issue where carrying a drag and drop payload over an already open tree node would incorrectly select it. (#7850) - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow diff --git a/docs/README.md b/docs/README.md index 2c976341c..a1807abac 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,7 +22,7 @@ Businesses: support continued development and maintenance via invoiced sponsorin Dear ImGui is a **bloat-free graphical user interface library for C++**. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline-enabled application. It is fast, portable, renderer agnostic, and self-contained (no external dependencies). -Dear ImGui is designed to **enable fast iterations** and to **empower programmers** to create **content creation tools and visualization / debug tools** (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal and lacks certain features commonly found in more high-level libraries. +Dear ImGui is designed to **enable fast iterations** and to **empower programmers** to create **content creation tools and visualization / debug tools** (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal and lacks certain features commonly found in more high-level libraries. Among other things, full internationalization (right-to-left text, bidirectional text, text shaping etc.) and accessibility features are not supported. Dear ImGui is particularly suited to integration in game engines (for tooling), real-time 3D applications, fullscreen applications, embedded applications, or any applications on console platforms where operating system features are non-standard. From eb7201b9026a8812d02b3421b43b61c050b81151 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 20 Aug 2024 15:34:14 +0200 Subject: [PATCH 0293/2359] Fonts: Made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 21 ++++++++++++++++----- imgui.h | 1 + imgui_draw.cpp | 11 +++++++++-- 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 40b651f42..dc30091c0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other changes: - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow when used in a multi-select context without any OpenOnXXX flags set. (#7850) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) +- Fonts: Made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) - Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index ed7983542..ed7522b27 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5068,6 +5068,8 @@ static void InitViewportDrawData(ImGuiViewportP* viewport) // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): // some frequently called functions which to modify both channels and clipping simultaneously tend to use the // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds. +// - This is analoguous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack, +// which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); @@ -7574,22 +7576,31 @@ void ImGui::SetCurrentFont(ImFont* font) g.DrawListSharedData.FontScale = g.FontScale; } +// Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authorative against window-local ImDrawList. +// - Whereas ImDrawList::PushTextureID()/PopTextureID() is not to be used across Begin() calls. +// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... +// - Some code paths never really fully worked with multiple atlas textures. +// - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID() +// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem +// because we have a concrete need and a test bed for multiple atlas textures. void ImGui::PushFont(ImFont* font) { ImGuiContext& g = *GImGui; - if (!font) + if (font == NULL) font = GetDefaultFont(); - SetCurrentFont(font); g.FontStack.push_back(font); - g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); + SetCurrentFont(font); + g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { ImGuiContext& g = *GImGui; - g.CurrentWindow->DrawList->PopTextureID(); + IM_ASSERT(g.FontStack.Size > 0); g.FontStack.pop_back(); - SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); + ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); + SetCurrentFont(font); + g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); } void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) diff --git a/imgui.h b/imgui.h index 1d7759199..b8aa34072 100644 --- a/imgui.h +++ b/imgui.h @@ -3152,6 +3152,7 @@ struct ImDrawList IMGUI_API void _OnChangedClipRect(); IMGUI_API void _OnChangedTextureID(); IMGUI_API void _OnChangedVtxOffset(); + IMGUI_API void _SetTextureID(ImTextureID texture_id); IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 32cf64353..65d68708d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -526,7 +526,6 @@ void ImDrawList::_OnChangedClipRect() CmdBuffer.pop_back(); return; } - curr_cmd->ClipRect = _CmdHeader.ClipRect; } @@ -549,7 +548,6 @@ void ImDrawList::_OnChangedTextureID() CmdBuffer.pop_back(); return; } - curr_cmd->TextureId = _CmdHeader.TextureId; } @@ -625,6 +623,15 @@ void ImDrawList::PopTextureID() _OnChangedTextureID(); } +// This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTextureID()/PopTextureID(). +void ImDrawList::_SetTextureID(ImTextureID texture_id) +{ + if (_CmdHeader.TextureId == texture_id) + return; + _CmdHeader.TextureId = texture_id; + _OnChangedTextureID(); +} + // Reserve space for a number of vertices and indices. // You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or // submit the intermediate results. PrimUnreserve() can be used to release unused allocations. From e471206b0889948c436f144669beb9b8875110c8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 20 Aug 2024 17:54:42 +0200 Subject: [PATCH 0294/2359] Windows: adjust default ClipRect to better match rendering of thick borders. (#7887, #7888 + #3312, #7540, #3756, #6170, #6365) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 12 ++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dc30091c0..d12bb58d1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,9 @@ Other changes: - IO, InputText: fixed an issue where typing text in a InputText() would defer character processing by one frame, because of the trickling input queue. Reworked interleaved keys<>char trickling to take account for keys known to input characters. (#7889, #4921, #4858) +- Windows: adjust default ClipRect to better match rendering of thick borders (which are in + theory not supported). Compensate for the fact that borders are centered around the windows + edge rather than inner. (#7887, #7888 + #3312, #7540, #3756, #6170, #6365) - MultiSelect+TreeNode+Drag and Drop: fixed an issue where carrying a drag and drop payload over an already open tree node would incorrectly select it. (#7850) - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow diff --git a/imgui.cpp b/imgui.cpp index ed7522b27..ede9f4b84 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7066,10 +7066,14 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Affected by window/frame border size. Used by: // - Begin() initial clip rect float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); - window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize); - window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size); - window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - window->WindowBorderSize); - window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize); + + // Try to match the fact that our border is drawn centered over the window rectangle, rather than inner. + // This is why we do a *0.5f here. We don't currently even technically support large values for WindowBorderSize, + // see e.g #7887 #7888, but may do after we move the window border to become an inner border (and then we can remove the 0.5f here). + window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize * 0.5f); + window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size * 0.5f); + window->InnerClipRect.Max.x = ImFloor(window->InnerRect.Max.x - window->WindowBorderSize * 0.5f); + window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f); window->InnerClipRect.ClipWithFull(host_rect); // Default item width. Make it proportional to window size if window manually resizes From 59e69dc6df758e59f318e38a8db5bc4c8a8164c1 Mon Sep 17 00:00:00 2001 From: Pavel Rojtberg Date: Wed, 21 Aug 2024 09:14:52 +0200 Subject: [PATCH 0295/2359] ImGuiSelectionBasicStorage constructor needs visibility (#7906) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index b8aa34072..c55f5dda6 100644 --- a/imgui.h +++ b/imgui.h @@ -2860,7 +2860,7 @@ struct ImGuiSelectionBasicStorage ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). // Methods - ImGuiSelectionBasicStorage(); + IMGUI_API ImGuiSelectionBasicStorage(); IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. It uses 'items_count' passed to BeginMultiSelect() IMGUI_API bool Contains(ImGuiID id) const; // Query if an item id is in selection. IMGUI_API void Clear(); // Clear selection From 8a946b69e98d819e9123963122d3b8b10df52e78 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 21 Aug 2024 13:25:45 +0200 Subject: [PATCH 0296/2359] InputText: allow callback to update buffer while in read-only mode (fix for imgui_memory_editor 0.54 in read-only mode). See https://github.com/ocornut/imgui_club/pull/46 --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d12bb58d1..228e84dd1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,7 @@ Other changes: payload over an already open tree node would incorrectly select it. (#7850) - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow when used in a multi-select context without any OpenOnXXX flags set. (#7850) +- InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) - Fonts: Made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d5c9fa077..5aa70bdc2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4912,7 +4912,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb.select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb.select_start : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } if (buf_dirty) { - IM_ASSERT(!is_readonly); + // Callback may update buffer and thus set buf_dirty even in read-only mode. IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! InputTextReconcileUndoStateAfterUserCallback(state, callback_data.Buf, callback_data.BufTextLen); // FIXME: Move the rest of this block inside function and rename to InputTextReconcileStateAfterUserCallback() ? if (callback_data.BufTextLen > backup_current_text_length && is_resizable) From 521f84a3a9f21aa93d12a49823d589b560f899a5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 21 Aug 2024 14:26:53 +0200 Subject: [PATCH 0297/2359] InputText: fixed an issue programmatically refocusing a multi-line input which was just active. (#4761, #7870) Amend 66f0fb986, c5db276521 --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 228e84dd1..7b20e0033 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,7 @@ Other changes: - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow when used in a multi-select context without any OpenOnXXX flags set. (#7850) - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) +- InputText: fixed an issue programmatically refocusing a multi-line input which was just active. (#4761, #7870) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) - Fonts: Made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5aa70bdc2..e8d5f9683 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5194,7 +5194,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_multiline) { - // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (ref issue #4761)... + // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)... Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y)); g.NextItemData.ItemFlags |= ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop; EndChild(); @@ -5203,7 +5203,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // ...and then we need to undo the group overriding last item data, which gets a bit messy as EndGroup() tries to forward scrollbar being active... // FIXME: This quite messy/tricky, should attempt to get rid of the child window. EndGroup(); - if (g.LastItemData.ID == 0) + if (g.LastItemData.ID == 0 || g.LastItemData.ID != GetWindowScrollbarID(draw_window, ImGuiAxis_Y)) { g.LastItemData.ID = id; g.LastItemData.InFlags = item_data_backup.InFlags; From bf75504d7a42ca9fc6f71fce558eca1f4a6f0201 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 13:46:54 +0200 Subject: [PATCH 0298/2359] Style: added PushStyleVarX(), PushStyleVarY() helpers to modify only one component of a ImVec2 var. + tweak existing function to early out on error. --- docs/CHANGELOG.txt | 3 ++- docs/TODO.txt | 1 - imgui.cpp | 48 ++++++++++++++++++++++++++++++++++++---------- imgui.h | 6 ++++-- imgui_demo.cpp | 10 +++++----- imgui_widgets.cpp | 6 +++--- 6 files changed, 52 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7b20e0033..6ba4c4dad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,7 +56,8 @@ Other changes: - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) - InputText: fixed an issue programmatically refocusing a multi-line input which was just active. (#4761, #7870) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) -- Fonts: Made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) +- Style: added PushStyleVarX(), PushStyleVarY() helpers to modify only one component of a ImVec2 var. +- Fonts: made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) - Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] diff --git a/docs/TODO.txt b/docs/TODO.txt index eecce6b42..cd992784d 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -194,7 +194,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - settings/persistence: helpers to make TreeNodeBehavior persist (even during dev!) - may need to store some semantic and/or data type in ImGuiStoragePair - style: better default styles. (#707) - - style: PushStyleVar: allow direct access to individual float X/Y elements. - style: add a highlighted text color (for headers, etc.) - style: border types: out-screen, in-screen, etc. (#447) - style: add window shadow (fading away from the window. Paint-style calculation of vertices alpha after drawlist would be easier) diff --git a/imgui.cpp b/imgui.cpp index ede9f4b84..bb7e55c82 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3309,28 +3309,56 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { ImGuiContext& g = *GImGui; const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) + if (var_info->Type != ImGuiDataType_Float || var_info->Count != 1) { - float* pvar = (float*)var_info->GetVarPtr(&g.Style); - g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); - *pvar = val; + IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); return; } - IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); + float* pvar = (float*)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; +} + +void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x) +{ + ImGuiContext& g = *GImGui; + const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2) + { + IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); + return; + } + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + pvar->x = val_x; +} + +void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y) +{ + ImGuiContext& g = *GImGui; + const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2) + { + IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); + return; + } + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + pvar->y = val_y; } void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { ImGuiContext& g = *GImGui; const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) + if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2) { - ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); - g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); - *pvar = val; + IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); return; } - IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; } void ImGui::PopStyleVar(int count) diff --git a/imgui.h b/imgui.h index c55f5dda6..0289e798b 100644 --- a/imgui.h +++ b/imgui.h @@ -438,8 +438,10 @@ namespace ImGui IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); IMGUI_API void PopStyleColor(int count = 1); - IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame(). - IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. always use this if you modify the style after NewFrame(). + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame()! + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. " + IMGUI_API void PushStyleVarX(ImGuiStyleVar idx, float val_x); // modify X component of a style ImVec2 variable. " + IMGUI_API void PushStyleVarY(ImGuiStyleVar idx, float val_y); // modify Y component of a style ImVec2 variable. " IMGUI_API void PopStyleVar(int count = 1); IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); // modify specified shared item flag, e.g. PushItemFlag(ImGuiItemFlags_NoTabStop, true) IMGUI_API void PopItemFlag(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 264df8af4..ddc8f9b2a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3677,7 +3677,7 @@ static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) { ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize()); if (widget_type == WidgetType_TreeNode) - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); + ImGui::PushStyleVarY(ImGuiStyleVar_ItemSpacing, 0.0f); ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size); selection.ApplyRequests(ms_io); @@ -3693,7 +3693,7 @@ static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX); ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f); ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f); - //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 0.0f)); + //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacingY, 0.0f); } ImGuiListClipper clipper; @@ -5082,8 +5082,8 @@ const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL; static void PushStyleCompact() { ImGuiStyle& style = ImGui::GetStyle(); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, (float)(int)(style.FramePadding.y * 0.60f))); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, (float)(int)(style.ItemSpacing.y * 0.60f))); + ImGui::PushStyleVarY(ImGuiStyleVar_FramePadding, (float)(int)(style.FramePadding.y * 0.60f)); + ImGui::PushStyleVarY(ImGuiStyleVar_ItemSpacing, (float)(int)(style.ItemSpacing.y * 0.60f)); } static void PopStyleCompact() @@ -6117,7 +6117,7 @@ static void ShowDemoWindowTables() for (int row = 0; row < 8; row++) { if ((row % 3) == 2) - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(style.CellPadding.x, 20.0f)); + ImGui::PushStyleVarY(ImGuiStyleVar_CellPadding, 20.0f); ImGui::TableNextRow(ImGuiTableRowFlags_None); ImGui::TableNextColumn(); ImGui::Text("CellPadding.y = %.2f", style.CellPadding.y); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e8d5f9683..36cc2d6d2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1944,7 +1944,7 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags // We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx() ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove; - PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(g.Style.FramePadding.x, g.Style.WindowPadding.y)); // Horizontally align ourselves with the framed text + PushStyleVarX(ImGuiStyleVar_WindowPadding, g.Style.FramePadding.x); // Horizontally align ourselves with the framed text bool ret = Begin(name, NULL, window_flags); PopStyleVar(); if (!ret) @@ -8688,7 +8688,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin() popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight); window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f); - PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y)); + PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f); float w = label_size.x; ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, label_size.y)); @@ -8895,7 +8895,7 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut float w = label_size.x; window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f); ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); - PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y)); + PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f); pressed = Selectable("", selected, selectable_flags, ImVec2(w, 0.0f)); PopStyleVar(); if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) From 8e401047952fa7e1ea80f7c3d390f7203697583b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 18:13:34 +0200 Subject: [PATCH 0299/2359] Backends: GLFW: passing null window to glfwGetClipboardString()/glfwSetClipboardString(). --- backends/imgui_impl_glfw.cpp | 9 ++++----- docs/CHANGELOG.txt | 2 ++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index df581537b..73aae768d 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -176,14 +176,14 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() } // Functions -static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data) +static const char* ImGui_ImplGlfw_GetClipboardText(void*) { - return glfwGetClipboardString((GLFWwindow*)user_data); + return glfwGetClipboardString(NULL); } -static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text) +static void ImGui_ImplGlfw_SetClipboardText(void*, const char* text) { - glfwSetClipboardString((GLFWwindow*)user_data, text); + glfwSetClipboardString(NULL, text); } static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key) @@ -588,7 +588,6 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText; - io.ClipboardUserData = bd->Window; #ifdef __EMSCRIPTEN__ io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; }; #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ba4c4dad..1cfe8ef8e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,8 @@ Other changes: provide a way to do a portable sleep. (#7844) - Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] - Backends: SDL2, SDL3: storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. +- Backends: GLFW: passing null window to glfwGetClipboardString()/glfwSetClipboardString() + since GLFW own tests are doing that and it seems unnecessary. - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) From e6460722ea14f61b2eff6cbfdd6770d9e4874454 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 16:31:10 +0200 Subject: [PATCH 0300/2359] IO: Added GetPlatformIO(), ImGuiPlatformIO, currently empty. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 16 ++++++++++++++-- imgui.h | 18 ++++++++++++++---- imgui_internal.h | 1 + 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1cfe8ef8e..4b02e8f36 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- IO: Added GetPlatformIO() and ImGuiPlatformIO, pulled from 'docking' branch, which + is a centralized spot to connect os/platform/renderer related functions. + Clipboard, IME and OpenInShell hooks are moved here. (#7660) - IO, InputText: fixed an issue where typing text in a InputText() would defer character processing by one frame, because of the trickling input queue. Reworked interleaved keys<>char trickling to take account for keys known to input characters. (#7889, #4921, #4858) diff --git a/imgui.cpp b/imgui.cpp index bb7e55c82..9f4d38df7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -63,7 +63,7 @@ CODE // [SECTION] INCLUDES // [SECTION] FORWARD DECLARATIONS // [SECTION] CONTEXT AND MEMORY ALLOCATORS -// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) +// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO) // [SECTION] MISC HELPERS/UTILITIES (Geometry functions) // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) // [SECTION] MISC HELPERS/UTILITIES (File functions) @@ -1244,7 +1244,7 @@ static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper; static void* GImAllocatorUserData = NULL; //----------------------------------------------------------------------------- -// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) +// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO) //----------------------------------------------------------------------------- ImGuiStyle::ImGuiStyle() @@ -1762,6 +1762,12 @@ void ImGuiIO::AddFocusEvent(bool focused) g.InputEventsQueue.push_back(e); } +ImGuiPlatformIO::ImGuiPlatformIO() +{ + // Most fields are initialized with zero + memset(this, 0, sizeof(*this)); +} + //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (Geometry functions) //----------------------------------------------------------------------------- @@ -4461,6 +4467,12 @@ ImGuiIO& ImGui::GetIO() return GImGui->IO; } +ImGuiPlatformIO& ImGui::GetPlatformIO() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?"); + return GImGui->PlatformIO; +} + // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { diff --git a/imgui.h b/imgui.h index 0289e798b..eaffc7417 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.1 WIP" -#define IMGUI_VERSION_NUM 19102 +#define IMGUI_VERSION_NUM 19103 #define IMGUI_HAS_TABLE /* @@ -49,7 +49,7 @@ Index of this file: // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) -// [SECTION] Platform Dependent Interfaces (ImGuiPlatformImeData) +// [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformImeData) // [SECTION] Obsolete functions and types */ @@ -172,13 +172,14 @@ struct ImFontGlyph; // A single font glyph (code point + coordin struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h) -struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiIO; // Main configuration and I/O between your application and ImGui (also see: ImGuiPlatformIO) struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. struct ImGuiListClipper; // Helper to manually clip large list of items struct ImGuiMultiSelectIO; // Structure to interact with a BeginMultiSelect()/EndMultiSelect() block struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame struct ImGuiPayload; // User data payload for drag and drop operations +struct ImGuiPlatformIO; // Interface between platform/renderer backends and ImGui (e.g. Clipboard, IME hooks). Extends ImGuiIO. In docking branch, this gets extended to support multi-viewports. struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. struct ImGuiSelectionBasicStorage; // Optional helper to store multi-selection state + apply multi-selection requests. struct ImGuiSelectionExternalStorage;//Optional helper to apply multi-selection requests to existing randomly accessible storage. @@ -325,7 +326,8 @@ namespace ImGui IMGUI_API void SetCurrentContext(ImGuiContext* ctx); // Main - IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) + IMGUI_API ImGuiIO& GetIO(); // access the ImGuiIO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) + IMGUI_API ImGuiPlatformIO& GetPlatformIO(); // access the ImGuiPlatformIO structure (mostly hooks/functions to connect to platform/renderer and OS Clipboard, IME etc.) IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleColor(), PushStyleVar() to modify style mid-frame! IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! @@ -2196,6 +2198,8 @@ struct ImGuiStyle // - initialization: backends and user code writes to ImGuiIO. // - main loop: backends writes to ImGuiIO, user code and imgui code reads from ImGuiIO. //----------------------------------------------------------------------------- +// Also see ImGui::GetPlatformIO() and ImGuiPlatformIO struct for OS/platform related functions: clipboard, IME etc. +//----------------------------------------------------------------------------- // [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. // If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. @@ -3483,6 +3487,12 @@ struct ImGuiViewport // [SECTION] Platform Dependent Interfaces //----------------------------------------------------------------------------- +// Access via ImGui::GetPlatformIO() +struct ImGuiPlatformIO +{ + IMGUI_API ImGuiPlatformIO(); +}; + // (Optional) Support for IME (Input Method Editor) via the io.PlatformSetImeDataFn() function. struct ImGuiPlatformImeData { diff --git a/imgui_internal.h b/imgui_internal.h index 339a4e3a6..29099cd04 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1994,6 +1994,7 @@ struct ImGuiContext bool Initialized; bool FontAtlasOwnedByContext; // IO.Fonts-> is owned by the ImGuiContext and will be destructed along with it. ImGuiIO IO; + ImGuiPlatformIO PlatformIO; ImGuiStyle Style; ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. From ba2f4a2cd56e33d99798b084dc4229efb2fa1140 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 16:42:57 +0200 Subject: [PATCH 0301/2359] IO: (BREAKING) moved GetIO().PlatformOpenInShellFn to GetPlatformIO(.Platform_OpenInShellFn. (#7660) --- backends/imgui_impl_glfw.cpp | 5 ++++- backends/imgui_impl_sdl2.cpp | 5 ++++- docs/CHANGELOG.txt | 5 +++++ imconfig.h | 2 +- imgui.cpp | 15 +++++++++------ imgui.h | 14 +++++++++----- imgui_widgets.cpp | 4 ++-- 7 files changed, 34 insertions(+), 16 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 73aae768d..776396786 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -20,6 +20,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: +// - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn // 2024-07-31: Added ImGui_ImplGlfw_Sleep() helper function for usage by our examples app, since GLFW doesn't provide one. // 2024-07-08: *BREAKING* Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWWindow* parameter. // 2024-07-08: Emscripten: Added support for GLFW3 contrib port (GLFW 3.4.0 features + bug fixes): to enable, replace -sUSE_GLFW=3 with --use-port=contrib.glfw3 (requires emscripten 3.1.59+) (https://github.com/pongasoft/emscripten-glfw) @@ -586,10 +588,11 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw bd->Window = window; bd->Time = 0.0; + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText; #ifdef __EMSCRIPTEN__ - io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; }; + platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; }; #endif // Create mouse cursors diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index c4724969d..d9ba69d16 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: +// - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn // 2024-08-19: Storing SDL's Uint32 WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. // 2024-08-19: ImGui_ImplSDL2_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. @@ -458,12 +460,13 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->Renderer = renderer; bd->MouseCanUseGlobalState = mouse_can_use_global_state; + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; io.ClipboardUserData = nullptr; io.PlatformSetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; #ifdef __EMSCRIPTEN__ - io.PlatformOpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; + platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; #endif // Gamepad handling diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4b02e8f36..4cbeb025c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,10 @@ HOW TO UPDATE? Breaking changes: +- IO: moved some functions from ImGuiIO to ImGuiPlatformIO: + - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn. (#7660) + - access those via GetPlatformIO() instead of GetIO(). + Other changes: - IO: Added GetPlatformIO() and ImGuiPlatformIO, pulled from 'docking' branch, which @@ -114,6 +118,7 @@ Other changes: - Added TextLink(), TextLinkOpenURL() hyperlink widgets. (#7660) - IO: added io.PlatformOpenInShellFn handler to open a link/folder/file in OS shell. (#7660) + (*EDIT* From next version 1.91.1 we moved this to platform_io.Platform_OpenInShellFn *EDIT**) Added IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS to disable default Windows/Linux/Mac implementations. - IO: added io.ConfigNavSwapGamepadButtons to swap Activate/Cancel (A<>B) buttons, to match the typical "Nintendo/Japanese consoles" button layout when using Gamepad navigation. (#787, #5723) diff --git a/imconfig.h b/imconfig.h index 6e4c743d4..b8d55842b 100644 --- a/imconfig.h +++ b/imconfig.h @@ -43,7 +43,7 @@ //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME). //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). -//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default io.PlatformOpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). +//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) diff --git a/imgui.cpp b/imgui.cpp index 9f4d38df7..d4eb59b9b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,10 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure: + - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn. (#7660) + - access those via GetPlatformIO() instead of GetIO(). + some were introduced very recently and often automatically setup by core library and backends, so for those we are exceptionally not maintaining a legacy redirection symbol. - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info) you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way. - instead of: GetWindowContentRegionMax().x - GetCursorPos().x @@ -1144,7 +1148,7 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSetti static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx); static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text); static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); -static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); +static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); namespace ImGui { @@ -1393,7 +1397,6 @@ ImGuiIO::ImGuiIO() // Note: Initialize() will setup default clipboard/ime handlers. BackendPlatformName = BackendRendererName = NULL; BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL; - PlatformOpenInShellUserData = NULL; PlatformLocaleDecimalPoint = '.'; // Input (NB: we already have memset zero the entire structure!) @@ -3805,7 +3808,7 @@ void ImGui::Initialize() g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function) - g.IO.PlatformOpenInShellFn = PlatformOpenInShellFn_DefaultImpl; + g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl; g.IO.PlatformSetImeDataFn = PlatformSetImeDataFn_DefaultImpl; // Create default viewport @@ -14477,14 +14480,14 @@ static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text #ifdef _MSC_VER #pragma comment(lib, "shell32") #endif -static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) +static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32; } #else #include #include -static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) +static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { #if defined(__APPLE__) const char* args[] { "open", "--", path, NULL }; @@ -14508,7 +14511,7 @@ static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) } #endif #else -static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; } +static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; } #endif // Default shell handlers //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index eaffc7417..9a745dd90 100644 --- a/imgui.h +++ b/imgui.h @@ -2295,11 +2295,6 @@ struct ImGuiIO void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; - // Optional: Open link/folder/file in OS Shell - // (default to use ShellExecuteA() on Windows, system() on Linux/Mac) - bool (*PlatformOpenInShellFn)(ImGuiContext* ctx, const char* path); - void* PlatformOpenInShellUserData; - // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) // (default to use native imm32 api on Windows) void (*PlatformSetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); @@ -3491,6 +3486,15 @@ struct ImGuiViewport struct ImGuiPlatformIO { IMGUI_API ImGuiPlatformIO(); + + //------------------------------------------------------------------ + // Inputs - Interface with OS/backends + //------------------------------------------------------------------ + + // Optional: Open link/folder/file in OS Shell + // (default to use ShellExecuteA() on Windows, system() on Linux/Mac) + bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); + void* Platform_OpenInShellUserData; }; // (Optional) Support for IME (Input Method Editor) via the io.PlatformSetImeDataFn() function. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 36cc2d6d2..f064a5dd8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1462,8 +1462,8 @@ void ImGui::TextLinkOpenURL(const char* label, const char* url) if (url == NULL) url = label; if (TextLink(label)) - if (g.IO.PlatformOpenInShellFn != NULL) - g.IO.PlatformOpenInShellFn(&g, url); + if (g.PlatformIO.Platform_OpenInShellFn != NULL) + g.PlatformIO.Platform_OpenInShellFn(&g, url); SetItemTooltip("%s", url); // It is more reassuring for user to _always_ display URL when we same as label if (BeginPopupContextItem()) { From 9ff60ae31d5d2328c0081ae17024d4057ad8a22a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 16:55:14 +0200 Subject: [PATCH 0302/2359] IO: (BREAKING) moved GetIO().PlatformSetImeDataFn to GetPlatformIO(.Platform_SetImeDataFn. (#7660) --- backends/imgui_impl_osx.mm | 5 ++++- backends/imgui_impl_sdl2.cpp | 3 ++- backends/imgui_impl_sdl3.cpp | 5 ++++- docs/CHANGELOG.txt | 4 ++++ docs/FAQ.md | 2 +- imgui.cpp | 17 +++++++++-------- imgui.h | 13 +++++++------ imgui_internal.h | 2 +- 8 files changed, 32 insertions(+), 19 deletions(-) diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index ab0e0ecc6..30f4ab24a 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -29,6 +29,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: +// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen. // 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen. @@ -465,7 +467,8 @@ bool ImGui_ImplOSX_Init(NSView* view) [view addSubview:bd->KeyEventResponder]; ImGui_ImplOSX_AddTrackingArea(view); - io.PlatformSetImeDataFn = [](ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Platform_SetImeDataFn = [](ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void { ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); if (data->WantVisible) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index d9ba69d16..c30fe6d81 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -23,6 +23,7 @@ // (minor and older changes stripped away, please see git history for details) // 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn +// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn // 2024-08-19: Storing SDL's Uint32 WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. // 2024-08-19: ImGui_ImplSDL2_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. @@ -464,7 +465,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; io.ClipboardUserData = nullptr; - io.PlatformSetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; + platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; #endif diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 24627347b..37ab21c24 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -21,6 +21,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: +// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn // 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. // 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807) @@ -454,10 +456,11 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->Renderer = renderer; bd->MouseCanUseGlobalState = mouse_can_use_global_state; + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); io.SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; io.ClipboardUserData = nullptr; - io.PlatformSetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; + platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; // Gamepad handling bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4cbeb025c..85e3cb04d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,7 +43,11 @@ Breaking changes: - IO: moved some functions from ImGuiIO to ImGuiPlatformIO: - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn. (#7660) + - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn. - access those via GetPlatformIO() instead of GetIO(). + (Because PlatformOpenInShellFn and PlatformSetImeDataFn were introduced very recently and + often automatically set by core library and backends, we are exceptionally not maintaining + a legacy redirection symbol for those two.) Other changes: diff --git a/docs/FAQ.md b/docs/FAQ.md index e120e8cd6..d104c30bc 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -639,7 +639,7 @@ The applications in examples/ are doing that. Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode). You may also use `MultiByteToWideChar()` or `ToUnicode()` to retrieve Unicode codepoints from MultiByte characters or keyboard state. Windows: if your language is relying on an Input Method Editor (IME), you can write your HWND to ImGui::GetMainViewport()->PlatformHandleRaw -for the default implementation of io.PlatformSetImeDataFn() to set your Microsoft IME position correctly. +for the default implementation of GetPlatformIO().Platform_SetImeDataFn() to set your Microsoft IME position correctly. ##### [Return to Index](#index) diff --git a/imgui.cpp b/imgui.cpp index d4eb59b9b..e7615b1c5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -431,7 +431,8 @@ CODE You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure: - - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn. (#7660) + - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660) + - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn - access those via GetPlatformIO() instead of GetIO(). some were introduced very recently and often automatically setup by core library and backends, so for those we are exceptionally not maintaining a legacy redirection symbol. - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info) @@ -1147,7 +1148,7 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSetti // Platform Dependents default implementation for IO functions static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx); static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text); -static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); +static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); namespace ImGui @@ -3809,7 +3810,7 @@ void ImGui::Initialize() g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function) g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl; - g.IO.PlatformSetImeDataFn = PlatformSetImeDataFn_DefaultImpl; + g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl; // Create default viewport ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)(); @@ -5226,11 +5227,11 @@ void ImGui::EndFrame() // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) ImGuiPlatformImeData* ime_data = &g.PlatformImeData; - if (g.IO.PlatformSetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) + if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) { - IMGUI_DEBUG_LOG_IO("[io] Calling io.PlatformSetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y); + IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y); ImGuiViewport* viewport = GetMainViewport(); - g.IO.PlatformSetImeDataFn(&g, viewport, ime_data); + g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data); } // Hide implicit/fallback "Debug" window if it hasn't been used @@ -14524,7 +14525,7 @@ static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { ret #pragma comment(lib, "imm32") #endif -static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) +static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) { // Notify OS Input Method Editor of text input position HWND hwnd = (HWND)viewport->PlatformHandleRaw; @@ -14550,7 +14551,7 @@ static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewp #else -static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {} +static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {} #endif // Default IME handlers diff --git a/imgui.h b/imgui.h index 9a745dd90..0400abdcd 100644 --- a/imgui.h +++ b/imgui.h @@ -2295,11 +2295,6 @@ struct ImGuiIO void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; - // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) - // (default to use native imm32 api on Windows) - void (*PlatformSetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); - //void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); // [Renamed to io.PlatformSetImeDataFn in 1.91.0] - // Optional: Platform locale ImWchar PlatformLocaleDecimalPoint; // '.' // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point @@ -3495,9 +3490,15 @@ struct ImGuiPlatformIO // (default to use ShellExecuteA() on Windows, system() on Linux/Mac) bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); void* Platform_OpenInShellUserData; + + // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) + // (default to use native imm32 api on Windows) + void (*Platform_SetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); + void* Platform_ImeUserData; + //void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); // [Renamed to platform_io.PlatformSetImeDataFn in 1.91.1] }; -// (Optional) Support for IME (Input Method Editor) via the io.PlatformSetImeDataFn() function. +// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. struct ImGuiPlatformImeData { bool WantVisible; // A widget wants the IME to be visible diff --git a/imgui_internal.h b/imgui_internal.h index 29099cd04..6bd2aa457 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2275,7 +2275,7 @@ struct ImGuiContext // Platform support ImGuiPlatformImeData PlatformImeData; // Data updated by current frame - ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the io.PlatformSetImeDataFn() handler. + ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. // Settings bool SettingsLoaded; From e54f240ea0aad351ee7971e2cb7afe8881120dde Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 17:18:16 +0200 Subject: [PATCH 0303/2359] IO: (BREAKING) moved io.PlatformLocaleDecimalPoint to platform_io.Platform_LocaleDecimalPoint. (#7389, #6719, #2278) --- docs/CHANGELOG.txt | 5 +++-- imgui.cpp | 7 ++++--- imgui.h | 7 ++++--- imgui_widgets.cpp | 4 ++-- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 85e3cb04d..a061e71c8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,8 +42,9 @@ HOW TO UPDATE? Breaking changes: - IO: moved some functions from ImGuiIO to ImGuiPlatformIO: - - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn. (#7660) - - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn. + - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn. (#7660) + - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn. + - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint. (#7389, #6719, #2278) - access those via GetPlatformIO() instead of GetIO(). (Because PlatformOpenInShellFn and PlatformSetImeDataFn were introduced very recently and often automatically set by core library and backends, we are exceptionally not maintaining diff --git a/imgui.cpp b/imgui.cpp index e7615b1c5..deed85399 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -431,8 +431,9 @@ CODE You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure: - - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660) - - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn + - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660) + - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn + - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278) - access those via GetPlatformIO() instead of GetIO(). some were introduced very recently and often automatically setup by core library and backends, so for those we are exceptionally not maintaining a legacy redirection symbol. - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info) @@ -1398,7 +1399,6 @@ ImGuiIO::ImGuiIO() // Note: Initialize() will setup default clipboard/ime handlers. BackendPlatformName = BackendRendererName = NULL; BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL; - PlatformLocaleDecimalPoint = '.'; // Input (NB: we already have memset zero the entire structure!) MousePos = ImVec2(-FLT_MAX, -FLT_MAX); @@ -1770,6 +1770,7 @@ ImGuiPlatformIO::ImGuiPlatformIO() { // Most fields are initialized with zero memset(this, 0, sizeof(*this)); + Platform_LocaleDecimalPoint = '.'; } //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 0400abdcd..a1ccfd73d 100644 --- a/imgui.h +++ b/imgui.h @@ -2295,9 +2295,6 @@ struct ImGuiIO void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; - // Optional: Platform locale - ImWchar PlatformLocaleDecimalPoint; // '.' // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point - //------------------------------------------------------------------ // Input - Call before calling NewFrame() //------------------------------------------------------------------ @@ -3496,6 +3493,10 @@ struct ImGuiPlatformIO void (*Platform_SetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); void* Platform_ImeUserData; //void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); // [Renamed to platform_io.PlatformSetImeDataFn in 1.91.1] + + // Optional: Platform locale + // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point + ImWchar Platform_LocaleDecimalPoint; // '.' }; // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f064a5dd8..f4625f2a7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4132,10 +4132,10 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im // The standard mandate that programs starts in the "C" locale where the decimal point is '.'. // We don't really intend to provide widespread support for it, but out of empathy for people stuck with using odd API, we support the bare minimum aka overriding the decimal point. // Change the default decimal_point with: - // ImGui::GetIO()->PlatformLocaleDecimalPoint = *localeconv()->decimal_point; + // ImGui::GetPlatformIO()->Platform_LocaleDecimalPoint = *localeconv()->decimal_point; // Users of non-default decimal point (in particular ',') may be affected by word-selection logic (is_word_boundary_from_right/is_word_boundary_from_left) functions. ImGuiContext& g = *ctx; - const unsigned c_decimal_point = (unsigned int)g.IO.PlatformLocaleDecimalPoint; + const unsigned c_decimal_point = (unsigned int)g.PlatformIO.Platform_LocaleDecimalPoint; if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint)) if (c == '.' || c == ',') c = c_decimal_point; From 214977e5fd1ba25d8c77824b2993450b63cdc075 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 17:50:10 +0200 Subject: [PATCH 0304/2359] IO: (BREAKING) moved io.GetClipboardTextFn, io.SetClipboardTextFn to platform_io.Platform_GetClipboardTextFn, platform_io.Platform_SetClipboardTextFn. --- backends/imgui_impl_allegro5.cpp | 13 +++++---- backends/imgui_impl_glfw.cpp | 4 ++- backends/imgui_impl_osx.mm | 10 ++++--- backends/imgui_impl_sdl2.cpp | 14 +++++---- backends/imgui_impl_sdl3.cpp | 13 +++++---- docs/CHANGELOG.txt | 18 +++++++++--- imgui.cpp | 49 +++++++++++++++++++------------- imgui.h | 20 +++++++++---- imgui_widgets.cpp | 2 +- 9 files changed, 90 insertions(+), 53 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index db366fa74..e41f02140 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -20,6 +20,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // 2022-11-30: Renderer: Restoring using al_draw_indexed_prim() when Allegro version is >= 5.2.5. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). @@ -291,7 +294,7 @@ void ImGui_ImplAllegro5_InvalidateDeviceObjects() } #if ALLEGRO_HAS_CLIPBOARD -static const char* ImGui_ImplAllegro5_GetClipboardText(void*) +static const char* ImGui_ImplAllegro5_GetClipboardText(ImGuiContext*) { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); if (bd->ClipboardTextData) @@ -300,7 +303,7 @@ static const char* ImGui_ImplAllegro5_GetClipboardText(void*) return bd->ClipboardTextData; } -static void ImGui_ImplAllegro5_SetClipboardText(void*, const char* text) +static void ImGui_ImplAllegro5_SetClipboardText(ImGuiContext*, const char* text) { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); al_set_clipboard_text(bd->Display, text); @@ -447,9 +450,9 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro)); #if ALLEGRO_HAS_CLIPBOARD - io.SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText; - io.GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText; - io.ClipboardUserData = nullptr; + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Platform_SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText; + platform_io.Platform_GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText; #endif return true; diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 776396786..66b71c5e7 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -20,7 +20,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: +// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn // 2024-07-31: Added ImGui_ImplGlfw_Sleep() helper function for usage by our examples app, since GLFW doesn't provide one. // 2024-07-08: *BREAKING* Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWWindow* parameter. diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 30f4ab24a..870038d85 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -29,7 +29,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: +// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen. @@ -395,6 +397,7 @@ IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view) { bool ImGui_ImplOSX_Init(NSView* view) { ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); @@ -425,14 +428,14 @@ bool ImGui_ImplOSX_Init(NSView* view) // Note that imgui.cpp also include default OSX clipboard handlers which can be enabled // by adding '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h and adding '-framework ApplicationServices' to your linker command-line. // Since we are already in ObjC land here, it is easy for us to add a clipboard handler using the NSPasteboard api. - io.SetClipboardTextFn = [](void*, const char* str) -> void + platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* str) -> void { NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; [pasteboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil]; [pasteboard setString:[NSString stringWithUTF8String:str] forType:NSPasteboardTypeString]; }; - io.GetClipboardTextFn = [](void*) -> const char* + platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) -> const char* { NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; NSString* available = [pasteboard availableTypeFromArray: [NSArray arrayWithObject:NSPasteboardTypeString]]; @@ -467,7 +470,6 @@ bool ImGui_ImplOSX_Init(NSView* view) [view addSubview:bd->KeyEventResponder]; ImGui_ImplOSX_AddTrackingArea(view); - ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); platform_io.Platform_SetImeDataFn = [](ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void { ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index c30fe6d81..b1cc8c9e6 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,7 +21,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: +// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn // 2024-08-19: Storing SDL's Uint32 WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. @@ -146,7 +148,7 @@ static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData() } // Functions -static const char* ImGui_ImplSDL2_GetClipboardText(void*) +static const char* ImGui_ImplSDL2_GetClipboardText(ImGuiContext*) { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); if (bd->ClipboardTextData) @@ -155,7 +157,7 @@ static const char* ImGui_ImplSDL2_GetClipboardText(void*) return bd->ClipboardTextData; } -static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text) +static void ImGui_ImplSDL2_SetClipboardText(ImGuiContext*, const char* text) { SDL_SetClipboardText(text); } @@ -462,9 +464,9 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->MouseCanUseGlobalState = mouse_can_use_global_state; ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; - io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; - io.ClipboardUserData = nullptr; + platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; + platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; + platform_io.Platform_ClipboardUserData = nullptr; platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 37ab21c24..deb8c7925 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -21,7 +21,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-08-22: Follow up on function pointers moved from ImGuiIO to ImGuiPlatformIO: +// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn // 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. // 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853) @@ -118,7 +120,7 @@ static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData() } // Functions -static const char* ImGui_ImplSDL3_GetClipboardText(void*) +static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); if (bd->ClipboardTextData) @@ -128,7 +130,7 @@ static const char* ImGui_ImplSDL3_GetClipboardText(void*) return bd->ClipboardTextData; } -static void ImGui_ImplSDL3_SetClipboardText(void*, const char* text) +static void ImGui_ImplSDL3_SetClipboardText(ImGuiContext*, const char* text) { SDL_SetClipboardText(text); } @@ -457,9 +459,8 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->MouseCanUseGlobalState = mouse_can_use_global_state; ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - io.SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; - io.GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; - io.ClipboardUserData = nullptr; + platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; + platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; // Gamepad handling diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a061e71c8..25cd2b8c7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,10 +41,18 @@ HOW TO UPDATE? Breaking changes: -- IO: moved some functions from ImGuiIO to ImGuiPlatformIO: - - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn. (#7660) - - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn. - - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint. (#7389, #6719, #2278) +- IO: moved clipboard functions from ImGuiIO to ImGuiPlatformIO: + - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + - in function signatures, changed 'void* user_data' to 'ImGuiContext* ctx' for consistency + with other functions. Pull your user data from platform_io.ClipboardUserData if used. + - as this is will affect all users of custom engines/backends, we are providing proper + legacy redirection (will obsolete). +- IO: moved other functions from ImGuiIO to ImGuiPlatformIO: + - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660) + - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn + - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278) + - clipboard function signature changed: - access those via GetPlatformIO() instead of GetIO(). (Because PlatformOpenInShellFn and PlatformSetImeDataFn were introduced very recently and often automatically set by core library and backends, we are exceptionally not maintaining @@ -76,6 +84,8 @@ Other changes: - Backends: SDL2, SDL3: storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. - Backends: GLFW: passing null window to glfwGetClipboardString()/glfwSetClipboardString() since GLFW own tests are doing that and it seems unnecessary. +- Backends: SDL2, SDL3, GLFW, OSX, Allegro: update to set function handlers in ImGuiPlatformIO + instead of ImGuiIO. - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) diff --git a/imgui.cpp b/imgui.cpp index deed85399..381ffb259 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -431,6 +431,8 @@ CODE You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure: + - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData. + - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line. - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660) - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278) @@ -1146,9 +1148,9 @@ static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSetti static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); -// Platform Dependents default implementation for IO functions -static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx); -static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text); +// Platform Dependents default implementation for ImGuiPlatformIO functions +static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx); +static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text); static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path); @@ -3806,10 +3808,9 @@ void ImGui::Initialize() // Setup default localization table LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS)); - // Setup default platform clipboard/IME handlers. - g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations - g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; - g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function) + // Setup default ImGuiPlatformIO clipboard/IME handlers. + g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations + g.PlatformIO.Platform_SetClipboardTextFn = Platform_SetClipboardTextFn_DefaultImpl; g.PlatformIO.Platform_OpenInShellFn = Platform_OpenInShellFn_DefaultImpl; g.PlatformIO.Platform_SetImeDataFn = Platform_SetImeDataFn_DefaultImpl; @@ -4451,14 +4452,14 @@ void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr const char* ImGui::GetClipboardText() { ImGuiContext& g = *GImGui; - return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : ""; + return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : ""; } void ImGui::SetClipboardText(const char* text) { ImGuiContext& g = *GImGui; - if (g.IO.SetClipboardTextFn) - g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text); + if (g.PlatformIO.Platform_SetClipboardTextFn != NULL) + g.PlatformIO.Platform_SetClipboardTextFn(&g, text); } const char* ImGui::GetVersion() @@ -10096,6 +10097,14 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1) IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); #endif + + // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl)) + g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); }; + if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl)) + g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); }; +#endif } static void ImGui::ErrorCheckEndFrameSanityChecks() @@ -14347,9 +14356,9 @@ static void ImGui::UpdateViewportsNewFrame() // Win32 clipboard implementation // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown() -static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx) +static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx) { - ImGuiContext& g = *(ImGuiContext*)user_data_ctx; + ImGuiContext& g = *ctx; g.ClipboardHandlerData.clear(); if (!::OpenClipboard(NULL)) return NULL; @@ -14370,7 +14379,7 @@ static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx) return g.ClipboardHandlerData.Data; } -static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text) { if (!::OpenClipboard(NULL)) return; @@ -14397,7 +14406,7 @@ static PasteboardRef main_clipboard = 0; // OSX clipboard implementation // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line! -static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* text) { if (!main_clipboard) PasteboardCreate(kPasteboardClipboard, &main_clipboard); @@ -14410,9 +14419,9 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text) } } -static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx) +static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx) { - ImGuiContext& g = *(ImGuiContext*)user_data_ctx; + ImGuiContext& g = *ctx; if (!main_clipboard) PasteboardCreate(kPasteboardClipboard, &main_clipboard); PasteboardSynchronize(main_clipboard); @@ -14446,15 +14455,15 @@ static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx) #else // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers. -static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx) +static const char* Platform_GetClipboardTextFn_DefaultImpl(ImGuiContext* ctx) { - ImGuiContext& g = *(ImGuiContext*)user_data_ctx; + ImGuiContext& g = *ctx; return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin(); } -static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text) +static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const char* text) { - ImGuiContext& g = *(ImGuiContext*)user_data_ctx; + ImGuiContext& g = *ctx; g.ClipboardHandlerData.clear(); const char* text_end = text + strlen(text); g.ClipboardHandlerData.resize((int)(text_end - text) + 1); diff --git a/imgui.h b/imgui.h index a1ccfd73d..2825cc60c 100644 --- a/imgui.h +++ b/imgui.h @@ -2289,12 +2289,6 @@ struct ImGuiIO void* BackendRendererUserData; // = NULL // User data for renderer backend void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend - // Optional: Access OS clipboard - // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) - const char* (*GetClipboardTextFn)(void* user_data); - void (*SetClipboardTextFn)(void* user_data, const char* text); - void* ClipboardUserData; - //------------------------------------------------------------------ // Input - Call before calling NewFrame() //------------------------------------------------------------------ @@ -2396,6 +2390,14 @@ struct ImGuiIO //void* ImeWindowHandle; // [Obsoleted in 1.87] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. #endif + // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. + // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; +#endif + IMGUI_API ImGuiIO(); }; @@ -3483,6 +3485,12 @@ struct ImGuiPlatformIO // Inputs - Interface with OS/backends //------------------------------------------------------------------ + // Optional: Access OS clipboard + // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + const char* (*Platform_GetClipboardTextFn)(ImGuiContext* ctx); + void (*Platform_SetClipboardTextFn)(ImGuiContext* ctx, const char* text); + void* Platform_ClipboardUserData; + // Optional: Open link/folder/file in OS Shell // (default to use ShellExecuteA() on Windows, system() on Linux/Mac) bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f4625f2a7..2d96ed909 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4740,7 +4740,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else if (is_cut || is_copy) { // Cut, Copy - if (io.SetClipboardTextFn) + if (g.PlatformIO.Platform_SetClipboardTextFn != NULL) { const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; From 5de7f69cbb9d52dc2cebb27261dfadcf0da3840d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 19:53:49 +0200 Subject: [PATCH 0305/2359] (BREAKING) Commented out obsolete ImageButton(). (#5533, #4471, #2464, #1390) --- docs/CHANGELOG.txt | 5 +++++ docs/TODO.txt | 1 + imgui.cpp | 5 +++++ imgui.h | 4 ++-- imgui_widgets.cpp | 20 ++++++++------------ 5 files changed, 21 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 25cd2b8c7..181cccfc1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,6 +57,11 @@ Breaking changes: (Because PlatformOpenInShellFn and PlatformSetImeDataFn were introduced very recently and often automatically set by core library and backends, we are exceptionally not maintaining a legacy redirection symbol for those two.) +- Commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). (#5533, #4471, #2464, #1390) + - old ImageButton() used ImTextureId as item id (created issue with e.g. multiple buttons in same scope, transient texture id values, opaque computation of ID) + - new ImageButton() requires an explicit 'const char* str_id' + - old ImageButton() had frame_padding' override argument. + - new ImageButton() always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar(). Other changes: diff --git a/docs/TODO.txt b/docs/TODO.txt index cd992784d..84a00bc6e 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -190,6 +190,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tree node/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height? format only %s/%c to be able to count height?) - settings: write more decent code to allow saving/loading new fields: columns, selected tree nodes? + - settings: facilitate extension lazily calling AddSettingsHandler() while running and still getting their data call the ReadXXX handlers immediately. - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file (#437) - settings/persistence: helpers to make TreeNodeBehavior persist (even during dev!) - may need to store some semantic and/or data type in ImGuiStoragePair diff --git a/imgui.cpp b/imgui.cpp index 381ffb259..457fc2031 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -438,6 +438,11 @@ CODE - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278) - access those via GetPlatformIO() instead of GetIO(). some were introduced very recently and often automatically setup by core library and backends, so for those we are exceptionally not maintaining a legacy redirection symbol. + - commented the old ImageButton() signature obsoleted in 1.89 (~August 2022). As a reminder: + - old ImageButton() before 1.89 used ImTextureId as item id (created issue with e.g. multiple buttons in same scope, transient texture id values, opaque computation of ID) + - new ImageButton() since 1.89 requires an explicit 'const char* str_id' + - old ImageButton() before 1.89 had frame_padding' override argument. + - new ImageButton() since 1.89 always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar(). - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax(). (see #7838 on GitHub for more info) you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way. - instead of: GetWindowContentRegionMax().x - GetCursorPos().x diff --git a/imgui.h b/imgui.h index 2825cc60c..1aea4c811 100644 --- a/imgui.h +++ b/imgui.h @@ -3547,13 +3547,13 @@ namespace ImGui // OBSOLETED in 1.89.4 (from March 2023) static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } static inline void PopAllowKeyboardFocus() { PopItemFlag(); } - // OBSOLETED in 1.89 (from August 2022) - IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // Use new ImageButton() signature (explicit item id, regular FramePadding) // OBSOLETED in 1.87 (from February 2022 but more formally obsoleted April 2024) IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value! //static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; } // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + //-- OBSOLETED in 1.89 (from August 2022) + //IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // --> Use new ImageButton() signature (explicit item id, regular FramePadding). Refer to code in 1.91 if you want to grab a copy of this version. //-- OBSOLETED in 1.88 (from May 2022) //static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. //static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2d96ed909..5b7898edd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1108,28 +1108,24 @@ bool ImGui::ImageButton(const char* str_id, ImTextureID user_texture_id, const I #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy API obsoleted in 1.89. Two differences with new ImageButton() -// - new ImageButton() requires an explicit 'const char* str_id' Old ImageButton() used opaque imTextureId (created issue with: multiple buttons with same image, transient texture id values, opaque computation of ID) -// - new ImageButton() always use style.FramePadding Old ImageButton() had an override argument. -// If you need to change padding with new ImageButton() you can use PushStyleVar(ImGuiStyleVar_FramePadding, value), consistent with other Button functions. +// - old ImageButton() used ImTextureId as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID) +// - new ImageButton() requires an explicit 'const char* str_id' +// - old ImageButton() had frame_padding' override argument. +// - new ImageButton() always use style.FramePadding. +/* bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - if (window->SkipItems) - return false; - // Default to using texture ID as ID. User can still push string/integer prefixes. PushID((void*)(intptr_t)user_texture_id); - const ImGuiID id = window->GetID("#image"); - PopID(); - if (frame_padding >= 0) PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2((float)frame_padding, (float)frame_padding)); - bool ret = ImageButtonEx(id, user_texture_id, size, uv0, uv1, bg_col, tint_col); + bool ret = ImageButton("", user_texture_id, size, uv0, uv1, bg_col, tint_col); if (frame_padding >= 0) PopStyleVar(); + PopID(); return ret; } +*/ #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS bool ImGui::Checkbox(const char* label, bool* v) From d15da2c47d98a8bf5a09219ea6d310710972f8bc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Aug 2024 20:27:50 +0200 Subject: [PATCH 0306/2359] Backends: GLFW: undo accidentally not committing use of Platform_SetClipboardTextFn as I was testing the legacy path (amend 214977e). --- backends/imgui_impl_glfw.cpp | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 66b71c5e7..ee230ee1b 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -180,16 +180,6 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() } // Functions -static const char* ImGui_ImplGlfw_GetClipboardText(void*) -{ - return glfwGetClipboardString(NULL); -} - -static void ImGui_ImplGlfw_SetClipboardText(void*, const char* text) -{ - glfwSetClipboardString(NULL, text); -} - static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key) { switch (key) @@ -591,8 +581,8 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw bd->Time = 0.0; ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText; - io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText; + platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(NULL, text); }; + platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(NULL); }; #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; }; #endif From d474ed7f78c505308a54c70dd51c24c6965f605f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Aug 2024 12:47:40 +0200 Subject: [PATCH 0307/2359] InputText: Internals: store Scroll.y as it seems sane to (internally) expose it in a way that's agnostic of our use of a child window (#7913, #383) --- imgui.h | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 20 ++++++++++++-------- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/imgui.h b/imgui.h index 1aea4c811..028adafb8 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.1 WIP" -#define IMGUI_VERSION_NUM 19103 +#define IMGUI_VERSION_NUM 19104 #define IMGUI_HAS_TABLE /* diff --git a/imgui_internal.h b/imgui_internal.h index 6bd2aa457..537f51329 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1121,7 +1121,7 @@ struct IMGUI_API ImGuiInputTextState ImVector InitialTextA; // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered) bool TextAIsValid; // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument) int BufCapacityA; // end-user buffer capacity - float ScrollX; // horizontal scrolling/offset + ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) ImStb::STB_TexteditState Stb; // state for stb_textedit.h float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5b7898edd..63c4b21cd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4407,7 +4407,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } else { - state->ScrollX = 0.0f; + state->Scroll = ImVec2(0.0f, 0.0f); stb_textedit_initialize_state(&state->Stb, !is_multiline); } @@ -4459,6 +4459,10 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // FIXME: May be a problem to always steal Alt on OSX, would ideally still allow an uninterrupted Alt down-up to toggle menu if (is_osx) SetKeyOwner(ImGuiMod_Alt, id); + + // Expose scroll in a manner that is agnostic to us using a child window + if (is_multiline) + state->Scroll.y = draw_window->Scroll.y; } // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function) @@ -4522,7 +4526,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ g.ActiveIdAllowOverlap = !io.MouseDown[0]; // Edit in progress - const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX; + const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->Scroll.x; const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y) : (g.FontSize * 0.5f)); if (select_all) @@ -5078,14 +5082,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { const float scroll_increment_x = inner_size.x * 0.25f; const float visible_width = inner_size.x - style.FramePadding.x; - if (cursor_offset.x < state->ScrollX) - state->ScrollX = IM_TRUNC(ImMax(0.0f, cursor_offset.x - scroll_increment_x)); - else if (cursor_offset.x - visible_width >= state->ScrollX) - state->ScrollX = IM_TRUNC(cursor_offset.x - visible_width + scroll_increment_x); + if (cursor_offset.x < state->Scroll.x) + state->Scroll.x = IM_TRUNC(ImMax(0.0f, cursor_offset.x - scroll_increment_x)); + else if (cursor_offset.x - visible_width >= state->Scroll.x) + state->Scroll.x = IM_TRUNC(cursor_offset.x - visible_width + scroll_increment_x); } else { - state->ScrollX = 0.0f; + state->Scroll.y = 0.0f; } // Vertical scroll @@ -5106,7 +5110,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } // Draw selection - const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f); + const ImVec2 draw_scroll = ImVec2(state->Scroll.x, 0.0f); if (render_selection) { const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); From ce484301c0f9c1aeedb5427b186ab7dd2dc4b9a3 Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Fri, 23 Aug 2024 14:12:18 +0200 Subject: [PATCH 0308/2359] CI: Add manual trigger for 'workflow_run' builds (#7865) --- .github/workflows/build.yml | 1 + .github/workflows/manual.yml | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 .github/workflows/manual.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b223d2261..4320a2025 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -8,6 +8,7 @@ on: # "scheduled" workflow, while maintaining ability to perform local CI builds. workflows: - scheduled + - manual branches: - master - docking diff --git a/.github/workflows/manual.yml b/.github/workflows/manual.yml new file mode 100644 index 000000000..3c472f1bf --- /dev/null +++ b/.github/workflows/manual.yml @@ -0,0 +1,12 @@ +# +# This is a dummy workflow used to trigger full builds manually. +# +name: manual + +on: workflow_dispatch + +jobs: + manual: + runs-on: ubuntu-latest + steps: + - run: exit 0 From 438f9e1a3e7f7d63d0d20b50cc199e5f714895f2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Aug 2024 14:14:07 +0200 Subject: [PATCH 0309/2359] InputText: amend d474ed7 for static analysis. (#7913) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 63c4b21cd..c55e95500 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4461,7 +4461,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ SetKeyOwner(ImGuiMod_Alt, id); // Expose scroll in a manner that is agnostic to us using a child window - if (is_multiline) + if (is_multiline && state != NULL) state->Scroll.y = draw_window->Scroll.y; } From 088e6fc04715dde2969cd584073c5150521b148a Mon Sep 17 00:00:00 2001 From: BillKek <51540758+BillKek@users.noreply.github.com> Date: Thu, 22 Jun 2023 17:44:00 +0300 Subject: [PATCH 0310/2359] Examples: Win32+OpenGL3: added batch. file for msys2/mingw build. (#6544) --- examples/example_win32_opengl3/build_mingw.bat | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 examples/example_win32_opengl3/build_mingw.bat diff --git a/examples/example_win32_opengl3/build_mingw.bat b/examples/example_win32_opengl3/build_mingw.bat new file mode 100644 index 000000000..767218585 --- /dev/null +++ b/examples/example_win32_opengl3/build_mingw.bat @@ -0,0 +1,8 @@ +@REM Build for MINGW64 or 32 from MSYS2. +@set OUT_DIR=Debug +@set OUT_EXE=example_win32_opengl3 +@set INCLUDES=-I../.. -I../../backends +@set SOURCES=main.cpp ../../backends/imgui_impl_opengl3.cpp ../../backends/imgui_impl_win32.cpp ../../imgui*.cpp +@set LIBS=-lopengl32 -lgdi32 -ldwmapi +mkdir %OUT_DIR% +g++ -DUNICODE %INCLUDES% %SOURCES% -o %OUT_DIR%/%OUT_EXE%.exe --static -mwindows %LIBS% %LIBS% From 1e939fcc32af81c755c31edb9db3357f9fb50d19 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Aug 2024 14:55:27 +0200 Subject: [PATCH 0311/2359] Tooltips, Drag and Drop: made it possible to override BeginTooltip() position while inside a drag and drop source or target. (#6973) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 181cccfc1..692c48f1a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,8 @@ Other changes: - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) - InputText: fixed an issue programmatically refocusing a multi-line input which was just active. (#4761, #7870) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) +- Tooltips, Drag and Drop: made it possible to override BeginTooltip() position while inside + a drag and drop source or target: a SetNextWindowPos() call won't be overriden. (#6973) - Style: added PushStyleVarX(), PushStyleVarY() helpers to modify only one component of a ImVec2 var. - Fonts: made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not diff --git a/imgui.cpp b/imgui.cpp index 457fc2031..17f19bc22 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11096,7 +11096,8 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones). //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale; - SetNextWindowPos(tooltip_pos); + if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) + SetNextWindowPos(tooltip_pos); SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f); //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :( tooltip_flags |= ImGuiTooltipFlags_OverridePrevious; @@ -15937,7 +15938,7 @@ static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags) void ImGui::ShowDebugLogWindow(bool* p_open) { ImGuiContext& g = *GImGui; - if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)) + if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0) SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver); if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1) { @@ -16254,7 +16255,7 @@ static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_f void ImGui::ShowIDStackToolWindow(bool* p_open) { ImGuiContext& g = *GImGui; - if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)) + if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0) SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver); if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1) { From 0b9adc2c799f5ed6b33fefd7cdb3c68d10751a29 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Aug 2024 15:24:22 +0200 Subject: [PATCH 0312/2359] BeginChild: (BREAKING) renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders. Amend 7713c2925 + renamed similar argument in other functions. --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 18 ++++++++++-------- imgui.h | 19 ++++++++++++------- imgui_demo.cpp | 36 ++++++++++++++++++------------------ imgui_internal.h | 2 +- imgui_tables.cpp | 4 ++-- imgui_widgets.cpp | 4 ++-- 7 files changed, 49 insertions(+), 38 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 692c48f1a..a05f91b88 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ HOW TO UPDATE? Breaking changes: +- BeginChild(): renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. [@cfillion] + Kept inline redirection flag (will obsolete). - IO: moved clipboard functions from ImGuiIO to ImGuiPlatformIO: - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn @@ -845,6 +847,7 @@ Breaking changes: Before: BeginChild("Name", size, false) After: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None) Existing code will still work as 'ImGuiChildFlags_Border == true', but you are encouraged to update call sites. + **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'** - BeginChild(): Added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for use with BeginChild() anyhow, passing it to Begin() had no effect. Now that we accept @@ -894,6 +897,7 @@ Other changes: child windows from the bottom/right border (toward layout direction). Resized child windows settings are saved and persistent in .ini file. (#1710) - BeginChild(): Added ImGuiChildFlags_Border as a replacement for 'bool border = true' parameter. + **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'** - BeginChild(): Added ImGuiChildFlags_AutoResizeX and ImGuiChildFlags_AutoResizeY to auto-resize on one axis, while generally providing a size on the other axis. (#1666, #1395, #1496, #1710) e.g. BeginChild("name", {-FLT_MIN, 0.0f}, ImGuiChildFlags_AutoResizeY); diff --git a/imgui.cpp b/imgui.cpp index 17f19bc22..fbf067879 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag. - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure: - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData. - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn + same as above line. @@ -514,6 +515,7 @@ CODE - new: BeginChild("Name", size, ImGuiChildFlags_Border) - old: BeginChild("Name", size, false) - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None) + **AMEND FROM THE FUTURE: from 1.91.1, 'ImGuiChildFlags_Border' is called 'ImGuiChildFlags_Borders'** - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow. - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding); - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0); @@ -3637,13 +3639,13 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con } // Render a rectangle shaped with optional rounding and borders -void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) +void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders, float rounding) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); const float border_size = g.Style.FrameBorderSize; - if (border && border_size > 0.0f) + if (borders && border_size > 0.0f) { window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size); @@ -5623,7 +5625,7 @@ ImVec2 ImGui::GetItemRectSize() } // Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. -// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! +// 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) { ImGuiID id = GetCurrentWindow()->GetID(str_id); @@ -5642,7 +5644,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I IM_ASSERT(id != 0); // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. - const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened; + const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened; IM_UNUSED(ImGuiChildFlags_SupportedMask_); IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?"); IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!"); @@ -5677,7 +5679,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding); PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize); PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding); - child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding; + child_flags |= ImGuiChildFlags_Borders | ImGuiChildFlags_AlwaysUseWindowPadding; window_flags |= ImGuiWindowFlags_NoMove; } @@ -5707,7 +5709,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I // Set style const float backup_border_size = g.Style.ChildBorderSize; - if ((child_flags & ImGuiChildFlags_Border) == 0) + if ((child_flags & ImGuiChildFlags_Borders) == 0) g.Style.ChildBorderSize = 0.0f; // Begin into window @@ -15804,7 +15806,7 @@ void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); if (flags & ImGuiWindowFlags_ChildWindow) BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags, - (window->ChildFlags & ImGuiChildFlags_Border) ? "Border " : "", + (window->ChildFlags & ImGuiChildFlags_Borders) ? "Borders " : "", (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "", (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "", (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : ""); @@ -15983,7 +15985,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open) EndPopup(); } - BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); + BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags; g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper; diff --git a/imgui.h b/imgui.h index 028adafb8..cc89955d0 100644 --- a/imgui.h +++ b/imgui.h @@ -369,10 +369,10 @@ namespace ImGui // Child Windows // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. // - Before 1.90 (November 2023), the "ImGuiChildFlags child_flags = 0" parameter was "bool border = false". - // This API is backward compatible with old code, as we guarantee that ImGuiChildFlags_Border == true. + // This API is backward compatible with old code, as we guarantee that ImGuiChildFlags_Borders == true. // Consider updating your old code: // BeginChild("Name", size, false) -> Begin("Name", size, 0); or Begin("Name", size, ImGuiChildFlags_None); - // BeginChild("Name", size, true) -> Begin("Name", size, ImGuiChildFlags_Border); + // BeginChild("Name", size, true) -> Begin("Name", size, ImGuiChildFlags_Borders); // - Manual sizing (each axis can use a different setting e.g. ImVec2(0.0f, 400.0f)): // == 0.0f: use remaining parent window size for this axis. // > 0.0f: use specified size for this axis. @@ -843,7 +843,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 border = true); + IMGUI_API void Columns(int count = 1, const char* id = NULL, 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 @@ -1098,7 +1098,7 @@ enum ImGuiWindowFlags_ }; // Flags for ImGui::BeginChild() -// (Legacy: bit 0 must always correspond to ImGuiChildFlags_Border to be backward compatible with old API using 'bool border = false'. +// (Legacy: bit 0 must always correspond to ImGuiChildFlags_Borders to be backward compatible with old API using 'bool border = false'. // About using AutoResizeX/AutoResizeY flags: // - May be combined with SetNextWindowSizeConstraints() to set a min/max size for each axis (see "Demo->Child->Auto-resize with Constraints"). // - Size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing. @@ -1109,7 +1109,7 @@ enum ImGuiWindowFlags_ enum ImGuiChildFlags_ { ImGuiChildFlags_None = 0, - ImGuiChildFlags_Border = 1 << 0, // Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) + ImGuiChildFlags_Borders = 1 << 0, // Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) ImGuiChildFlags_AlwaysUseWindowPadding = 1 << 1, // Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) ImGuiChildFlags_ResizeX = 1 << 2, // Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags_NoSavedSettings passed to window flags) ImGuiChildFlags_ResizeY = 1 << 3, // Allow resize from bottom border (layout direction). " @@ -1118,6 +1118,11 @@ enum ImGuiChildFlags_ ImGuiChildFlags_AlwaysAutoResize = 1 << 6, // Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. ImGuiChildFlags_FrameStyle = 1 << 7, // Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. ImGuiChildFlags_NavFlattened = 1 << 8, // [BETA] Share focus scope, allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. + + // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiChildFlags_Border = ImGuiChildFlags_Borders, // Renamed in 1.91.1 (August 2024) for consistency. +#endif }; // Flags for ImGui::PushItemFlag() @@ -3537,8 +3542,8 @@ namespace ImGui // OBSOLETED in 1.90.0 (from September 2023) static inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } static inline void EndChildFrame() { EndChild(); } - //static inline bool BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags window_flags){ return BeginChild(str_id, size_arg, border ? ImGuiChildFlags_Border : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Border - //static inline bool BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags window_flags) { return BeginChild(id, size_arg, border ? ImGuiChildFlags_Border : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Border + //static 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 + //static 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 static inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } 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); 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); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ddc8f9b2a..a729e45b2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2762,7 +2762,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) static bool embed_all_inside_a_child_window = false; ImGui::Checkbox("Embed everything inside a child window for testing _RootWindow flag.", &embed_all_inside_a_child_window); if (embed_all_inside_a_child_window) - ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), ImGuiChildFlags_Border); + ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), ImGuiChildFlags_Borders); // Testing IsWindowFocused() function with its various flags. ImGui::BulletText( @@ -2810,7 +2810,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow), ImGui::IsWindowHovered(ImGuiHoveredFlags_Stationary)); - ImGui::BeginChild("child", ImVec2(0, 50), ImGuiChildFlags_Border); + ImGui::BeginChild("child", ImVec2(0, 50), ImGuiChildFlags_Borders); ImGui::Text("This is another child window for testing the _ChildWindows flag."); ImGui::EndChild(); if (embed_all_inside_a_child_window) @@ -3375,7 +3375,7 @@ static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); // Cannot use ImGuiMultiSelectFlags_BoxSelect1d as checkboxes are varying width. - if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_Border | ImGuiChildFlags_ResizeY)) + if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) { ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, -1, IM_ARRAYSIZE(items)); ImGuiSelectionExternalStorage storage_wrapper; @@ -3881,7 +3881,7 @@ static void ShowDemoWindowLayout() if (!disable_menu) window_flags |= ImGuiWindowFlags_MenuBar; ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); - ImGui::BeginChild("ChildR", ImVec2(0, 260), ImGuiChildFlags_Border, window_flags); + ImGui::BeginChild("ChildR", ImVec2(0, 260), ImGuiChildFlags_Borders, window_flags); if (!disable_menu && ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Menu")) @@ -3911,7 +3911,7 @@ static void ShowDemoWindowLayout() { HelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents."); ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg)); - if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_Border | 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(); @@ -3929,7 +3929,7 @@ static void ShowDemoWindowLayout() ImGui::DragInt("Max Height (in Lines)", &max_height_in_lines, 0.2f); 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_Border | ImGuiChildFlags_AutoResizeY)) + 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); ImGui::EndChild(); @@ -3947,11 +3947,11 @@ static void ShowDemoWindowLayout() { static int offset_x = 0; static bool override_bg_color = true; - static ImGuiChildFlags child_flags = ImGuiChildFlags_Border | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY; + static ImGuiChildFlags child_flags = ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY; 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_Border", &child_flags, ImGuiChildFlags_Border); + ImGui::CheckboxFlags("ImGuiChildFlags_Borders", &child_flags, ImGuiChildFlags_Borders); ImGui::CheckboxFlags("ImGuiChildFlags_AlwaysUseWindowPadding", &child_flags, ImGuiChildFlags_AlwaysUseWindowPadding); ImGui::CheckboxFlags("ImGuiChildFlags_ResizeX", &child_flags, ImGuiChildFlags_ResizeX); ImGui::CheckboxFlags("ImGuiChildFlags_ResizeY", &child_flags, ImGuiChildFlags_ResizeY); @@ -4361,7 +4361,7 @@ static void ShowDemoWindowLayout() const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0; const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); - const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), ImGuiChildFlags_Border, child_flags); + const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), ImGuiChildFlags_Borders, child_flags); if (ImGui::BeginMenuBar()) { ImGui::TextUnformatted("abc"); @@ -4408,7 +4408,7 @@ static void ShowDemoWindowLayout() float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f; ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0); ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); - bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), ImGuiChildFlags_Border, child_flags); + bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), ImGuiChildFlags_Borders, child_flags); if (scroll_to_off) ImGui::SetScrollX(scroll_to_off_px); if (scroll_to_pos) @@ -4450,7 +4450,7 @@ static void ShowDemoWindowLayout() ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30); - ImGui::BeginChild("scrolling", scrolling_child_size, ImGuiChildFlags_Border, ImGuiWindowFlags_HorizontalScrollbar); + ImGui::BeginChild("scrolling", scrolling_child_size, ImGuiChildFlags_Borders, ImGuiWindowFlags_HorizontalScrollbar); for (int line = 0; line < lines; line++) { // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() @@ -4596,7 +4596,7 @@ static void ShowDemoWindowLayout() } if (show_child) { - ImGui::BeginChild("child", ImVec2(0, 0), ImGuiChildFlags_Border); + ImGui::BeginChild("child", ImVec2(0, 0), ImGuiChildFlags_Borders); ImGui::EndChild(); } ImGui::End(); @@ -7942,7 +7942,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "Right-click to open edit options menu."); ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); - ImGui::BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Border | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); + ImGui::BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); ImGui::PushItemWidth(ImGui::GetFontSize() * -12); for (int i = 0; i < ImGuiCol_COUNT; i++) { @@ -8176,7 +8176,7 @@ static void ShowExampleMenuFile() { static bool enabled = true; ImGui::MenuItem("Enabled", "", &enabled); - ImGui::BeginChild("child", ImVec2(0, 60), ImGuiChildFlags_Border); + ImGui::BeginChild("child", ImVec2(0, 60), ImGuiChildFlags_Borders); for (int i = 0; i < 10; i++) ImGui::Text("Scrolling Text %d", i); ImGui::EndChild(); @@ -8773,7 +8773,7 @@ static void ShowExampleAppLayout(bool* p_open) // Left static int selected = 0; { - ImGui::BeginChild("left pane", ImVec2(150, 0), ImGuiChildFlags_Border | ImGuiChildFlags_ResizeX); + ImGui::BeginChild("left pane", ImVec2(150, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX); for (int i = 0; i < 100; i++) { // FIXME: Good candidate to use ImGuiSelectableFlags_SelectOnNav @@ -8834,7 +8834,7 @@ struct ExampleAppPropertyEditor { // Left side: draw tree // - Currently using a table to benefit from RowBg feature - if (ImGui::BeginChild("##tree", ImVec2(300, 0), ImGuiChildFlags_ResizeX | ImGuiChildFlags_Border | ImGuiChildFlags_NavFlattened)) + if (ImGui::BeginChild("##tree", ImVec2(300, 0), ImGuiChildFlags_ResizeX | ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened)) { ImGui::SetNextItemWidth(-FLT_MIN); ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); @@ -9448,7 +9448,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) // To use a child window instead we could use, e.g: // ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Disable padding // ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); // Set a background color - // ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_NoMove); + // ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove); // ImGui::PopStyleColor(); // ImGui::PopStyleVar(); // [...] @@ -10100,7 +10100,7 @@ struct ExampleAssetsBrowser ImGuiIO& io = ImGui::GetIO(); ImGui::SetNextWindowContentSize(ImVec2(0.0f, LayoutOuterPadding + LayoutLineCount * (LayoutItemSize.x + LayoutItemSpacing))); - if (ImGui::BeginChild("Assets", ImVec2(0.0f, -ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_Border, ImGuiWindowFlags_NoMove)) + if (ImGui::BeginChild("Assets", ImVec2(0.0f, -ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove)) { ImDrawList* draw_list = ImGui::GetWindowDrawList(); diff --git a/imgui_internal.h b/imgui_internal.h index 537f51329..884c85a19 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3508,7 +3508,7 @@ namespace ImGui 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 clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); - IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); + 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 RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); IMGUI_API void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_None); // Navigation highlight diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 92c62949e..3d757fd98 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -4428,12 +4428,12 @@ void ImGui::EndColumns() NavUpdateCurrentWindowIsScrollPushableX(); } -void ImGui::Columns(int columns_count, const char* id, bool border) +void ImGui::Columns(int columns_count, const char* id, bool borders) { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); - ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder); + ImGuiOldColumnFlags flags = (borders ? 0 : ImGuiOldColumnFlags_NoBorder); //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior ImGuiOldColumns* columns = window->DC.CurrentColumns; if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c55e95500..ce80cfd87 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4312,7 +4312,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges - bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Border, ImGuiWindowFlags_NoMove); + bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove); g.NavActivateId = backup_activate_id; PopStyleVar(3); PopStyleColor(); @@ -5242,7 +5242,7 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state) Text("CurLenW: %d, CurLenA: %d, Cursor: %d, Selection: %d..%d", state->CurLenW, state->CurLenA, stb_state->cursor, stb_state->select_start, stb_state->select_end); Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x); Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point); - if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Border | ImGuiChildFlags_ResizeY)) // Visualize undo state + if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state { PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); for (int n = 0; n < IMSTB_TEXTEDIT_UNDOSTATECOUNT; n++) From a131c3e6111952d0e8fd898763fe7cd3b2172ee3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Aug 2024 18:24:44 +0200 Subject: [PATCH 0313/2359] Tables: revert a34071876 extending outer bottom/right border by 1, this is not the right solution. (#6765, #3752) --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a05f91b88..e4584d686 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,6 +80,8 @@ Other changes: payload over an already open tree node would incorrectly select it. (#7850) - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow when used in a multi-select context without any OpenOnXXX flags set. (#7850) +- Tables: revert 1.90 extension of bottom-most and right-most outer border offset by one. + This is not the right solution. (#6765, #3752) - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) - InputText: fixed an issue programmatically refocusing a multi-line input which was just active. (#4761, #7870) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 3d757fd98..92ab79a7f 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2743,7 +2743,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const ImU32 outer_col = table->BorderColorStrong; if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) { - inner_drawlist->AddRect(outer_border.Min, outer_border.Max + ImVec2(1, 1), outer_col, 0.0f, 0, border_size); + inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, 0, border_size); } else if (table->Flags & ImGuiTableFlags_BordersOuterV) { From 864a2bf6b824f9c1329d8493386208d4b0fd311c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Aug 2024 19:12:54 +0200 Subject: [PATCH 0314/2359] Tables: another attempt at making contents not overlap the bottom and right border in a scrolling table. (#6765, #3752, #7428) --- docs/CHANGELOG.txt | 5 +++-- imgui_tables.cpp | 17 ++++++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e4584d686..d19e8f39e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,8 +80,9 @@ Other changes: payload over an already open tree node would incorrectly select it. (#7850) - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow when used in a multi-select context without any OpenOnXXX flags set. (#7850) -- Tables: revert 1.90 extension of bottom-most and right-most outer border offset by one. - This is not the right solution. (#6765, #3752) +- Tables: fixes/revert a 1.90 change were outer border would be moved bottom and right + by an extra pixel + rework the change so that contents doesn't overlap the bottom and + right border in a scrolling table. (#6765, #3752, #7428) - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) - InputText: fixed an issue programmatically refocusing a multi-line input which was just active. (#4761, #7870) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 92ab79a7f..fd7e6da57 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -460,16 +460,27 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size; inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); - // Make left and top borders not overlap our contents by offsetting HostClipRect (#6765) + // 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). if (inner_window != outer_window) { + // 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(). if (flags & ImGuiTableFlags_BordersOuterV) + { table->HostClipRect.Min.x = ImMin(table->HostClipRect.Min.x + TABLE_BORDER_SIZE, table->HostClipRect.Max.x); + if (inner_window->DecoOuterSizeX2 == 0.0f) + table->HostClipRect.Max.x = ImMax(table->HostClipRect.Max.x - TABLE_BORDER_SIZE, table->HostClipRect.Min.x); + } if (flags & ImGuiTableFlags_BordersOuterH) + { table->HostClipRect.Min.y = ImMin(table->HostClipRect.Min.y + TABLE_BORDER_SIZE, table->HostClipRect.Max.y); + if (inner_window->DecoOuterSizeY2 == 0.0f) + table->HostClipRect.Max.y = ImMax(table->HostClipRect.Max.y - TABLE_BORDER_SIZE, table->HostClipRect.Min.y); + } } // Padding and Spacing @@ -497,7 +508,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG 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) : inner_window->ClipRect.Max.y; + 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() @@ -1249,7 +1260,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (table->Flags & ImGuiTableFlags_NoClip) table->DrawSplitter->SetCurrentChannel(inner_window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP); else - inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false); + inner_window->DrawList->PushClipRect(inner_window->InnerClipRect.Min, inner_window->InnerClipRect.Max, false); } // Process hit-testing on resizing borders. Actual size change will be applied in EndTable() From 1d88609043fd7a25df7f5f4acd7aa3cc4aaf8033 Mon Sep 17 00:00:00 2001 From: tanoxyz <36295026+tanoxyz@users.noreply.github.com> Date: Sun, 1 Sep 2024 11:40:48 +0200 Subject: [PATCH 0315/2359] Changed call from cosf to ImCos (#7939) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index fbf067879..2b4099966 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14757,7 +14757,7 @@ void ImGui::UpdateDebugToolFlashStyleColor() ImGuiContext& g = *GImGui; if (g.DebugFlashStyleColorTime <= 0.0f) return; - ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z); + ColorConvertHSVtoRGB(ImCos(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z); g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f; if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f) DebugFlashStyleColorStop(); From 28caa223567cef70c295d58ec23fefc6125e4bbe Mon Sep 17 00:00:00 2001 From: James Wrigley Date: Tue, 3 Sep 2024 00:50:20 +0200 Subject: [PATCH 0316/2359] Fix minor typo (#7943) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index cc89955d0..f6b7a7d0b 100644 --- a/imgui.h +++ b/imgui.h @@ -460,7 +460,7 @@ namespace ImGui // - Use the ShowStyleEditor() function to interactively see/edit the colors. IMGUI_API ImFont* GetFont(); // get current font IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied - IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a white pixel, useful to draw custom shapes via the ImDrawList API IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList IMGUI_API ImU32 GetColorU32(ImU32 col, float alpha_mul = 1.0f); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList From 4a06fe59b4d2dcd14ab9f79b7644ebad9a6d007a Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 3 Sep 2024 15:32:40 +0200 Subject: [PATCH 0317/2359] Update FONTS.md (#7944) --- docs/FONTS.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index df8b610e5..c451af61c 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -50,7 +50,9 @@ All loaded fonts glyphs are rendered into a single texture atlas ahead of time. ### (4) Font atlas texture fails to upload to GPU. -This is often of byproduct of point 3. If you have large number of glyphs or multiple fonts, the texture may become too big for your graphics API. **The typical result of failing to upload a texture is if every glyph or everything appears as empty black or white rectangle.** Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. +This is often of byproduct of point 3. If you have large number of glyphs or multiple fonts, the texture may become too big for your graphics API. **The typical result of failing to upload a texture is if every glyph or everything appears as empty white rectangles.** Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. + +![empty squares](https://github.com/user-attachments/assets/68b50fb5-8b9d-4c38-baec-6ac384f06d26) Some solutions: - You may reduce oversampling, e.g. `font_config.OversampleH = 1`, this will half your texture size for a quality loss. @@ -60,6 +62,8 @@ Some solutions: - Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. - Set `io.Fonts.TexDesiredWidth` to specify a texture width to reduce maximum texture height (see comment in `ImFontAtlas::Build()` function). +Future versions of Dear ImGui should solve this problem. + ##### [Return to Index](#index) --------------------------------------- From ee9e3a2ed66bd618ca17ebcba18088e4c9c64bd2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Aug 2024 19:40:47 +0200 Subject: [PATCH 0318/2359] Tabs: avoid queuing a refocus when tab is already focused, which would have the side-effect of e.g. closing popup on a mouse release. (#7914) + Debug Log: add details about closed popups. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 3 +++ imgui_widgets.cpp | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d19e8f39e..028f12d4c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,6 +83,8 @@ Other changes: - Tables: fixes/revert a 1.90 change were outer border would be moved bottom and right by an extra pixel + rework the change so that contents doesn't overlap the bottom and right border in a scrolling table. (#6765, #3752, #7428) +- Tabs: avoid queuing a refocus when tab is already focused, which would have the + side-effect of e.g. closing popup on a mouse release. (#7914) - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) - InputText: fixed an issue programmatically refocusing a multi-line input which was just active. (#4761, #7870) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) diff --git a/imgui.cpp b/imgui.cpp index 2b4099966..dfa74d994 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11370,6 +11370,9 @@ void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_ ImGuiContext& g = *GImGui; IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup); IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); + if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup) + for (int n = remaining; n < g.OpenPopupStack.Size; n++) + IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"\n", g.OpenPopupStack[n].PopupId, g.OpenPopupStack[n].Window ? g.OpenPopupStack[n].Window->Name : NULL); // Trim open popup stack ImGuiPopupData prev_popup = g.OpenPopupStack[remaining]; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ce80cfd87..436d81b0a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9986,7 +9986,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); - if (hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button) + if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button) TabBarQueueFocus(tab_bar, tab); if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) From 6a7319543c4b0bfdf3b6b06ce8a14d762aba985e Mon Sep 17 00:00:00 2001 From: Matt Guerrette Date: Sun, 25 Aug 2024 13:07:10 -0400 Subject: [PATCH 0319/2359] Backends: SDL3: following SDL3 reverting their change, result of SDL_GetGamepads must be freed. (#7918, #7898, #7807) --- backends/imgui_impl_sdl3.cpp | 4 +++- docs/CHANGELOG.txt | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index deb8c7925..0387b155c 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn @@ -672,7 +673,7 @@ static void ImGui_ImplSDL3_UpdateGamepads() { ImGui_ImplSDL3_CloseGamepads(); int sdl_gamepads_count = 0; - const SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count); + SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count); for (int n = 0; n < sdl_gamepads_count; n++) if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n])) { @@ -681,6 +682,7 @@ static void ImGui_ImplSDL3_UpdateGamepads() break; } bd->WantUpdateGamepadsList = false; + SDL_free(sdl_gamepads); } // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 028f12d4c..dbb0917ff 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -96,6 +96,8 @@ Other changes: provide a way to do a portable sleep. (#7844) - Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] - Backends: SDL2, SDL3: storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. +- Backends: SDL3: Update for API changes: SDL_GetGamepads() memory ownership logic was reverted back + by SDL3 on July 27. (#7918, #7898, #7807) [@cheyao, @MattGuerrette] - Backends: GLFW: passing null window to glfwGetClipboardString()/glfwSetClipboardString() since GLFW own tests are doing that and it seems unnecessary. - Backends: SDL2, SDL3, GLFW, OSX, Allegro: update to set function handlers in ImGuiPlatformIO @@ -103,7 +105,7 @@ Other changes: - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) - +Backends: SDL3: following SDL3 reverting their change, result of SDL_GetGamepads must be freed. (#7918, #7898) ----------------------------------------------------------------------- VERSION 1.91.0 (Released 2024-07-30) From 4832027eb6a313dedb4c4d0a04c6352a0e68e83f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Sep 2024 19:05:32 +0200 Subject: [PATCH 0320/2359] Examples: SDL3: Update for API changes: SDL_Init() returns 0 on failure. --- backends/imgui_impl_sdl3.cpp | 2 +- backends/imgui_impl_sdl3.h | 2 +- backends/imgui_impl_sdlrenderer3.cpp | 2 ++ backends/imgui_impl_sdlrenderer3.h | 2 ++ docs/CHANGELOG.txt | 27 ++++++++++++--------- examples/example_sdl3_opengl3/main.cpp | 2 +- examples/example_sdl3_sdlrenderer3/main.cpp | 2 +- 7 files changed, 23 insertions(+), 16 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 0387b155c..540b6931a 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -2,7 +2,7 @@ // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) -// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN**) +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) // Implemented features: // [X] Platform: Clipboard support. diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h index 39b7839d8..880ba9615 100644 --- a/backends/imgui_impl_sdl3.h +++ b/backends/imgui_impl_sdl3.h @@ -2,7 +2,7 @@ // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) -// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN**) +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) // Implemented features: // [X] Platform: Clipboard support. diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 8ba262548..d3926c2fb 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -1,6 +1,8 @@ // dear imgui: Renderer Backend for SDL_Renderer for SDL3 // (Requires: SDL 3.0.0+) +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) + // Note how SDL_Renderer is an _optional_ component of SDL3. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h index 1a730208a..6c23deca9 100644 --- a/backends/imgui_impl_sdlrenderer3.h +++ b/backends/imgui_impl_sdlrenderer3.h @@ -1,6 +1,8 @@ // dear imgui: Renderer Backend for SDL_Renderer for SDL3 // (Requires: SDL 3.0.0+) +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) + // Note how SDL_Renderer is an _optional_ component of SDL3. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dbb0917ff..9065b46ee 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -92,18 +92,21 @@ Other changes: a drag and drop source or target: a SetNextWindowPos() call won't be overriden. (#6973) - Style: added PushStyleVarX(), PushStyleVarY() helpers to modify only one component of a ImVec2 var. - Fonts: made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) -- Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not - provide a way to do a portable sleep. (#7844) -- Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] -- Backends: SDL2, SDL3: storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. -- Backends: SDL3: Update for API changes: SDL_GetGamepads() memory ownership logic was reverted back - by SDL3 on July 27. (#7918, #7898, #7807) [@cheyao, @MattGuerrette] -- Backends: GLFW: passing null window to glfwGetClipboardString()/glfwSetClipboardString() - since GLFW own tests are doing that and it seems unnecessary. -- Backends: SDL2, SDL3, GLFW, OSX, Allegro: update to set function handlers in ImGuiPlatformIO - instead of ImGuiIO. -- Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop - to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) +- Backends: + - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not + provide a way to do a portable sleep. (#7844) + - Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] + - Backends: SDL2, SDL3: storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. + - Backends: SDL3: Update for API changes: SDL_GetGamepads() memory ownership logic was reverted back + by SDL3 on July 27. (#7918, #7898, #7807) [@cheyao, @MattGuerrette] + - Backends: GLFW: passing null window to glfwGetClipboardString()/glfwSetClipboardString() + since GLFW own tests are doing that and it seems unnecessary. + - Backends: SDL2, SDL3, GLFW, OSX, Allegro: update to set function handlers in ImGuiPlatformIO + instead of ImGuiIO. +- Examples: + - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop + to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) + - Examples: SDL3: Update for API changes: SDL_Init() returns 0 on failure. Backends: SDL3: following SDL3 reverting their change, result of SDL_GetGamepads must be freed. (#7918, #7898) diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index e6aba8809..0ba09dc93 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -27,7 +27,7 @@ int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD) != 0) + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); return -1; diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 6efd2754a..ef98d752d 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -25,7 +25,7 @@ int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD) != 0) + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); return -1; From 07be01767afd005372035e471f8ac6e85e200001 Mon Sep 17 00:00:00 2001 From: Yan Pujante Date: Fri, 23 Aug 2024 10:05:38 -0700 Subject: [PATCH 0321/2359] Demo: added emscripten version. (#7915) --- imgui_demo.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a729e45b2..fe38ebf2e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -116,6 +116,9 @@ Index of this file: #if !defined(_MSC_VER) || _MSC_VER >= 1800 #include // PRId64/PRIu64, not avail in some MinGW headers. #endif +#ifdef __EMSCRIPTEN__ +#include // __EMSCRIPTEN_major__ etc. +#endif // Visual Studio warnings #ifdef _MSC_VER @@ -7688,6 +7691,7 @@ void ImGui::ShowAboutWindow(bool* p_open) #endif #ifdef __EMSCRIPTEN__ ImGui::Text("define: __EMSCRIPTEN__"); + ImGui::Text("Emscripten: %d.%d.%d", __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__); #endif ImGui::Separator(); ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL"); From 30dcdcbe736f551c0d7bc87ce5ed43edc835d7a2 Mon Sep 17 00:00:00 2001 From: Yan Pujante Date: Fri, 23 Aug 2024 09:56:02 -0700 Subject: [PATCH 0322/2359] Backends: GLFW: Emscripten: use OpenURL() when available and using EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3. Fixes popup blocked in some browsers. (#7915, #7660) --- backends/imgui_impl_glfw.cpp | 6 +++++- docs/CHANGELOG.txt | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index ee230ee1b..06b5142a1 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -560,7 +560,11 @@ void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows) } #ifdef __EMSCRIPTEN__ -EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); +#if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 3'4'0'20240817 +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'); }); +#endif #endif static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9065b46ee..6bedd7173 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -95,6 +95,8 @@ Other changes: - Backends: - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) + - Backends: GLFW+Emscripten: Use OpenURL() from GLFW3 contrib port when available and using + the contrib port instead of Emscripten own GLFW3 implementation. (#7647, #7915, #7660) [@ypujante] - Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853) [@madebr, @ocornut] - Backends: SDL2, SDL3: storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. - Backends: SDL3: Update for API changes: SDL_GetGamepads() memory ownership logic was reverted back @@ -103,6 +105,7 @@ Other changes: since GLFW own tests are doing that and it seems unnecessary. - Backends: SDL2, SDL3, GLFW, OSX, Allegro: update to set function handlers in ImGuiPlatformIO instead of ImGuiIO. + - Examples: - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) @@ -262,7 +265,7 @@ Other changes: - Backends: SDL2,SDL3,OSX: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() rename. - Backends: GLFW,SDL2: Added io.PlatformOpenInShellFn handler for web/Emscripten versions. (#7660) [@ypujante, @ocornut] - - Backends; GLFW+Emscripten: Added support for GLFW3 contrib port which fixes many of the things + - Backends: GLFW+Emscripten: Added support for GLFW3 contrib port which fixes many of the things not supported by the embedded GLFW: gamepad support, mouse cursor shapes, copy to clipboard, workaround for Super/Meta key, different ways of resizing, multi-window (glfw/canvas) support. (#7647) [@ypujante] From a93f7db875cbda4abe50f3e347879508c8490be4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Sep 2024 20:55:00 +0200 Subject: [PATCH 0323/2359] Misc merge/small stuff from docking to reduce drift. Among other things: - merged cfd23957 (#7940, #7823), also see ac64b6563 (#6716): moved above on 2023/08/14 in both branches. - moving the RenderDimmedBackgrounds() call, from f422e782, see 676497fe intently undoing ac64b65 -> confusing. (#6716) --- docs/CHANGELOG.txt | 3 --- imgui.cpp | 49 +++++++++++++++++++++++++--------------------- imgui.h | 4 ++-- imgui_internal.h | 24 ++++++++++++++--------- imgui_widgets.cpp | 4 ++-- 5 files changed, 46 insertions(+), 38 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6bedd7173..22df64e0f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -105,14 +105,11 @@ Other changes: since GLFW own tests are doing that and it seems unnecessary. - Backends: SDL2, SDL3, GLFW, OSX, Allegro: update to set function handlers in ImGuiPlatformIO instead of ImGuiIO. - - Examples: - Examples: GLFW (all), SDL2 (all), SDL3 (all), Win32+OpenGL3: rework examples main loop to handle minimization without burning CPU or GPU by running unthrottled code. (#7844) - Examples: SDL3: Update for API changes: SDL_Init() returns 0 on failure. -Backends: SDL3: following SDL3 reverting their change, result of SDL_GetGamepads must be freed. (#7918, #7898) - ----------------------------------------------------------------------- VERSION 1.91.0 (Released 2024-07-30) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index dfa74d994..deb006e09 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1380,12 +1380,6 @@ ImGuiIO::ImGuiIO() FontAllowUserScaling = false; DisplayFramebufferScale = ImVec2(1.0f, 1.0f); - MouseDoubleClickTime = 0.30f; - MouseDoubleClickMaxDist = 6.0f; - MouseDragThreshold = 6.0f; - KeyRepeatDelay = 0.275f; - KeyRepeatRate = 0.050f; - // Miscellaneous options MouseDrawCursor = false; #ifdef __APPLE__ @@ -1404,6 +1398,13 @@ ImGuiIO::ImGuiIO() ConfigDebugBeginReturnValueOnce = false; ConfigDebugBeginReturnValueLoop = false; + // Inputs Behaviors + MouseDoubleClickTime = 0.30f; + MouseDoubleClickMaxDist = 6.0f; + MouseDragThreshold = 6.0f; + KeyRepeatDelay = 0.275f; + KeyRepeatRate = 0.050f; + // Platform Functions // Note: Initialize() will setup default clipboard/ime handlers. BackendPlatformName = BackendRendererName = NULL; @@ -4229,8 +4230,9 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) // Test if another item is active (e.g. being dragged) const ImGuiID id = g.LastItemData.ID; if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0) - if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId) - return false; + if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) + if (g.ActiveId != window->MoveId) + return false; // Test if interactions on this window are blocked by an active popup or modal. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. @@ -4242,7 +4244,8 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) return false; // Special handling for calling after Begin() which represent the title bar or tab. - // When the window is skipped/collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. + // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin) + // will never be overwritten so we need to detect the case. if (id == window->MoveId && window->WriteAccessed) return false; @@ -4640,9 +4643,10 @@ void ImGui::UpdateMouseMovingWindowEndFrame() StartMouseMovingWindow(g.HoveredWindow); //-V595 // Cancel moving if clicked outside of title bar - if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) - if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) - g.MovingWindow = NULL; + if (g.IO.ConfigWindowsMoveFromTitleBarOnly) + if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) + if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) + g.MovingWindow = NULL; // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already) if (g.HoveredIdIsDisabled) @@ -5200,7 +5204,7 @@ static void ImGui::RenderDimmedBackgrounds() } else if (dim_bg_for_window_list) { - // Draw dimming behind CTRL+Tab target window + // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio)); // Draw border around CTRL+Tab target window @@ -5325,9 +5329,6 @@ void ImGui::Render() g.IO.MetricsRenderWindows = 0; CallContextHooks(&g, ImGuiContextHookType_RenderPre); - // Draw modal/window whitening backgrounds - RenderDimmedBackgrounds(); - // Add background ImDrawList (for each active viewport) for (ImGuiViewportP* viewport : g.Viewports) { @@ -5336,6 +5337,9 @@ void ImGui::Render() AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport)); } + // Draw modal/window whitening backgrounds + RenderDimmedBackgrounds(); + // Add ImDrawList to render ImGuiWindow* windows_to_render_top_most[2]; windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; @@ -14335,10 +14339,11 @@ static void ImGui::UpdateViewportsNewFrame() for (ImGuiViewportP* viewport : g.Viewports) { - // Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again. - viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin; - viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax; - viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f); + // Lock down space taken by menu bars and status bars + // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc. + viewport->WorkInsetMin = viewport->BuildWorkInsetMin; + viewport->WorkInsetMax = viewport->BuildWorkInsetMax; + viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f); viewport->UpdateWorkRect(); } } @@ -15762,9 +15767,9 @@ void ImGui::DebugNodeViewport(ImGuiViewportP* viewport) if (open) { ImGuiWindowFlags flags = viewport->Flags; - BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f", + BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f", viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y, - viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y); + viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y); BulletText("Flags: 0x%04X =%s%s%s", viewport->Flags, (flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "", diff --git a/imgui.h b/imgui.h index f6b7a7d0b..3ded051f1 100644 --- a/imgui.h +++ b/imgui.h @@ -3447,7 +3447,7 @@ enum ImGuiViewportFlags_ ImGuiViewportFlags_None = 0, ImGuiViewportFlags_IsPlatformWindow = 1 << 0, // Represent a Platform Window ImGuiViewportFlags_IsPlatformMonitor = 1 << 1, // Represent a Platform Monitor (unused yet) - ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: is created/managed by the application (rather than a dear imgui backend) + ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: Is created/managed by the application (rather than a dear imgui backend) }; // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. @@ -3487,7 +3487,7 @@ struct ImGuiPlatformIO IMGUI_API ImGuiPlatformIO(); //------------------------------------------------------------------ - // Inputs - Interface with OS/backends + // Input - Interface with OS/backends //------------------------------------------------------------------ // Optional: Access OS clipboard diff --git a/imgui_internal.h b/imgui_internal.h index 884c85a19..70f7e4dca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -94,6 +94,7 @@ Index of this file: #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #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 "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated #endif // In 1.89.4, we moved the implementation of "courtesy maths operators" from imgui_internal.h in imgui.h @@ -1806,23 +1807,28 @@ struct ImGuiViewportP : public ImGuiViewport ImDrawList* BgFgDrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. ImDrawData DrawDataP; ImDrawDataBuilder DrawDataBuilder; // Temporary data while building final ImDrawData - ImVec2 WorkOffsetMin; // Work Area: Offset from Pos to top-left corner of Work Area. Generally (0,0) or (0,+main_menu_bar_height). Work Area is Full Area but without menu-bars/status-bars (so WorkArea always fit inside Pos/Size!) - ImVec2 WorkOffsetMax; // Work Area: Offset from Pos+Size to bottom-right corner of Work Area. Generally (0,0) or (0,-status_bar_height). - ImVec2 BuildWorkOffsetMin; // Work Area: Offset being built during current frame. Generally >= 0.0f. - ImVec2 BuildWorkOffsetMax; // Work Area: Offset being built during current frame. Generally <= 0.0f. + + // Per-viewport work area + // - Insets are >= 0.0f values, distance from viewport corners to work area. + // - BeginMainMenuBar() and DockspaceOverViewport() tend to use work area to avoid stepping over existing contents. + // - Generally 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. + ImVec2 WorkInsetMin; // Work Area inset locked for the frame. GetWorkRect() always fits within GetMainRect(). + ImVec2 WorkInsetMax; // " + ImVec2 BuildWorkInsetMin; // Work Area inset accumulator for current frame, to become next frame's WorkInset + ImVec2 BuildWorkInsetMax; // " ImGuiViewportP() { BgFgDrawListsLastFrame[0] = BgFgDrawListsLastFrame[1] = -1; BgFgDrawLists[0] = BgFgDrawLists[1] = NULL; } ~ImGuiViewportP() { if (BgFgDrawLists[0]) IM_DELETE(BgFgDrawLists[0]); if (BgFgDrawLists[1]) IM_DELETE(BgFgDrawLists[1]); } // Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) - ImVec2 CalcWorkRectPos(const ImVec2& off_min) const { return ImVec2(Pos.x + off_min.x, Pos.y + off_min.y); } - ImVec2 CalcWorkRectSize(const ImVec2& off_min, const ImVec2& off_max) const { return ImVec2(ImMax(0.0f, Size.x - off_min.x + off_max.x), ImMax(0.0f, Size.y - off_min.y + off_max.y)); } - void UpdateWorkRect() { WorkPos = CalcWorkRectPos(WorkOffsetMin); WorkSize = CalcWorkRectSize(WorkOffsetMin, WorkOffsetMax); } // Update public fields + ImVec2 CalcWorkRectPos(const ImVec2& inset_min) const { return ImVec2(Pos.x + inset_min.x, Pos.y + inset_min.y); } + ImVec2 CalcWorkRectSize(const ImVec2& inset_min, const ImVec2& inset_max) const { return ImVec2(ImMax(0.0f, Size.x - inset_min.x - inset_max.x), ImMax(0.0f, Size.y - inset_min.y - inset_max.y)); } + void UpdateWorkRect() { WorkPos = CalcWorkRectPos(WorkInsetMin); WorkSize = CalcWorkRectSize(WorkInsetMin, WorkInsetMax); } // Update public fields // Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry) ImRect GetMainRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } ImRect GetWorkRect() const { return ImRect(WorkPos.x, WorkPos.y, WorkPos.x + WorkSize.x, WorkPos.y + WorkSize.y); } - ImRect GetBuildWorkRect() const { ImVec2 pos = CalcWorkRectPos(BuildWorkOffsetMin); ImVec2 size = CalcWorkRectSize(BuildWorkOffsetMin, BuildWorkOffsetMax); return ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); } + ImRect GetBuildWorkRect() const { ImVec2 pos = CalcWorkRectPos(BuildWorkInsetMin); ImVec2 size = CalcWorkRectSize(BuildWorkInsetMin, BuildWorkInsetMax); return ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); } }; //----------------------------------------------------------------------------- @@ -2612,7 +2618,7 @@ struct IMGUI_API ImGuiWindow ImVec2 WindowPadding; // Window padding at the time of Begin(). float WindowRounding; // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. float WindowBorderSize; // Window border size at the time of Begin(). - float TitleBarHeight, MenuBarHeight; + float TitleBarHeight, MenuBarHeight; // Note that those used to be function before 2024/05/28. If you have old code calling TitleBarHeight() you can change it to TitleBarHeight. float DecoOuterSizeX1, DecoOuterSizeY1; // Left/Up offsets. Sum of non-scrolling outer decorations (X1 generally == 0.0f. Y1 generally = TitleBarHeight + MenuBarHeight). Locked during Begin(). float DecoOuterSizeX2, DecoOuterSizeY2; // Right/Down offsets (X2 generally == ScrollbarSize.x, Y2 == ScrollbarSizes.y). float DecoInnerSizeX1, DecoInnerSizeY1; // Applied AFTER/OVER InnerRect. Specialized for Tables as they use specialized form of clipping and frozen rows/columns are inside InnerRect (and not part of regular decoration sizes). diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 436d81b0a..b550e8d84 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8557,9 +8557,9 @@ bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, Im // Report our size into work area (for next frame) using actual window size if (dir == ImGuiDir_Up || dir == ImGuiDir_Left) - viewport->BuildWorkOffsetMin[axis] += axis_size; + viewport->BuildWorkInsetMin[axis] += axis_size; else if (dir == ImGuiDir_Down || dir == ImGuiDir_Right) - viewport->BuildWorkOffsetMax[axis] -= axis_size; + viewport->BuildWorkInsetMax[axis] += axis_size; } window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; From f99febfd6fa16d44ca73832d20a9367d433783d7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Sep 2024 21:19:25 +0200 Subject: [PATCH 0324/2359] Made BeginItemTooltip() and IsItemHovered() with delay flag infer an implicit ID using Pos only. (#7945, #1485, #143) Perhaps a better approach would be to: store last non-zero ID + count successive zero ID and combine then. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 12 +++++++++++- imgui.h | 2 +- imgui_internal.h | 3 ++- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 22df64e0f..066a61f02 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,8 @@ Other changes: - Windows: adjust default ClipRect to better match rendering of thick borders (which are in theory not supported). Compensate for the fact that borders are centered around the windows edge rather than inner. (#7887, #7888 + #3312, #7540, #3756, #6170, #6365) +- Made BeginItemTooltip() and IsItemHovered() with delay flag infer an implicit ID (for + ID-less items such as Text element) in a way that works when item resizes. (#7945, #1485) - MultiSelect+TreeNode+Drag and Drop: fixed an issue where carrying a drag and drop payload over an already open tree node would incorrectly select it. (#7850) - MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow diff --git a/imgui.cpp b/imgui.cpp index deb006e09..767dbf70d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4261,7 +4261,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) const float delay = CalcDelayFromHoveredFlags(flags); if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary)) { - ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect); + ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromPos(g.LastItemData.Rect.Min); if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id)) g.HoverItemDelayTimer = 0.0f; g.HoverItemDelayId = hover_delay_id; @@ -8367,6 +8367,16 @@ ImGuiID ImGuiWindow::GetID(int n) } // This is only used in rare/specific situations to manufacture an ID out of nowhere. +// FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those? +ImGuiID ImGuiWindow::GetIDFromPos(const ImVec2& p_abs) +{ + ImGuiID seed = IDStack.back(); + ImVec2 p_rel = ImGui::WindowPosAbsToRel(this, p_abs); + ImGuiID id = ImHashData(&p_rel, sizeof(p_rel), seed); + return id; +} + +// " ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) { ImGuiID seed = IDStack.back(); diff --git a/imgui.h b/imgui.h index 3ded051f1..f7b1f3a29 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.1 WIP" -#define IMGUI_VERSION_NUM 19104 +#define IMGUI_VERSION_NUM 19105 #define IMGUI_HAS_TABLE /* diff --git a/imgui_internal.h b/imgui_internal.h index 70f7e4dca..59d8af7eb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2715,6 +2715,7 @@ public: ImGuiID GetID(const char* str, const char* str_end = NULL); ImGuiID GetID(const void* ptr); ImGuiID GetID(int n); + ImGuiID GetIDFromPos(const ImVec2& p_abs); ImGuiID GetIDFromRectangle(const ImRect& r_abs); // We don't use g.FontSize because the window may be != g.CurrentWindow. @@ -3124,8 +3125,8 @@ namespace ImGui inline void SetWindowParentWindowForFocusRoute(ImGuiWindow* window, ImGuiWindow* parent_window) { window->ParentWindowForFocusRoute = parent_window; } inline ImRect WindowRectAbsToRel(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); } inline ImRect WindowRectRelToAbs(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); } - inline ImVec2 WindowPosRelToAbs(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x + off.x, p.y + off.y); } inline ImVec2 WindowPosAbsToRel(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x - off.x, p.y - off.y); } + inline ImVec2 WindowPosRelToAbs(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x + off.x, p.y + off.y); } // Windows: Display Order and Focus Order IMGUI_API void FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags = 0); From afb15e9795888a704ca2c8d0eba6ae4dbd7ded11 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Sep 2024 21:49:35 +0200 Subject: [PATCH 0325/2359] PlotHistogram, PlotLines: register item ID in a more idiomatic manner. (#7935, #3072) --- docs/CHANGELOG.txt | 2 ++ imgui_demo.cpp | 5 +++++ imgui_widgets.cpp | 2 +- 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 066a61f02..54b3e8cca 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -92,6 +92,8 @@ Other changes: - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) - Tooltips, Drag and Drop: made it possible to override BeginTooltip() position while inside a drag and drop source or target: a SetNextWindowPos() call won't be overriden. (#6973) +- PlotHistogram, PlotLines: register item ID in a more idiomatic manner, fixes preventing + e.g. GetItemID() and other ID-based helper to work. (#7935, #3072) - Style: added PushStyleVarX(), PushStyleVarY() helpers to modify only one component of a ImVec2 var. - Fonts: made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) - Backends: diff --git a/imgui_demo.cpp b/imgui_demo.cpp index fe38ebf2e..b83cf2987 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2004,6 +2004,10 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); ImGui::Separator(); + ImGui::Text("Need better plotting and graphing? Consider using ImPlot:"); + ImGui::TextLinkOpenURL("https://github.com/epezent/implot"); + ImGui::Separator(); + ImGui::TreePop(); } @@ -6448,6 +6452,7 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("_ScrollX", &table_flags, ImGuiTableFlags_ScrollX); ImGui::CheckboxFlags("_ScrollY", &table_flags, ImGuiTableFlags_ScrollY); ImGui::CheckboxFlags("_Resizable", &table_flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("_Sortable", &table_flags, ImGuiTableFlags_Sortable); ImGui::CheckboxFlags("_NoBordersInBody", &table_flags, ImGuiTableFlags_NoBordersInBody); ImGui::CheckboxFlags("_HighlightHoveredColumn", &table_flags, ImGuiTableFlags_HighlightHoveredColumn); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b550e8d84..99992a717 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8224,7 +8224,7 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); 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)); ItemSize(total_bb, style.FramePadding.y); - if (!ItemAdd(total_bb, 0, &frame_bb)) + if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_NoNav)) return -1; const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags); From 776813416b5af283280250c08cc45af53fed066c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Sep 2024 21:55:26 +0200 Subject: [PATCH 0326/2359] PlotHistogram, PlotLines: use ButtonBehavior() to be idiomatic. (#7935, #3072) --- docs/CHANGELOG.txt | 4 ++-- imgui_widgets.cpp | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 54b3e8cca..d76a04042 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -92,8 +92,8 @@ Other changes: - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) - Tooltips, Drag and Drop: made it possible to override BeginTooltip() position while inside a drag and drop source or target: a SetNextWindowPos() call won't be overriden. (#6973) -- PlotHistogram, PlotLines: register item ID in a more idiomatic manner, fixes preventing - e.g. GetItemID() and other ID-based helper to work. (#7935, #3072) +- PlotHistogram, PlotLines: register item ID and use button behavior in a more idiomatic manner, + fixes preventing e.g. GetItemID() and other ID-based helper to work. (#7935, #3072) - Style: added PushStyleVarX(), PushStyleVarY() helpers to modify only one component of a ImVec2 var. - Fonts: made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) - Backends: diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 99992a717..fd52c93cd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8226,7 +8226,8 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_NoNav)) return -1; - const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags); + bool hovered; + ButtonBehavior(frame_bb, id, &hovered, NULL); // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) From 722a2a12fb2dc32d01fe28f226ec2d2e4e908498 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Sep 2024 14:41:22 +0200 Subject: [PATCH 0327/2359] Tables: comments. (#7937) --- imgui.h | 2 +- imgui_demo.cpp | 7 ++++++- imgui_tables.cpp | 9 +++++---- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/imgui.h b/imgui.h index f7b1f3a29..cfee0fcc7 100644 --- a/imgui.h +++ b/imgui.h @@ -1948,7 +1948,7 @@ enum ImGuiTableColumnFlags_ ImGuiTableColumnFlags_NoSort = 1 << 9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). ImGuiTableColumnFlags_NoSortAscending = 1 << 10, // Disable ability to sort in the ascending direction. ImGuiTableColumnFlags_NoSortDescending = 1 << 11, // Disable ability to sort in the descending direction. - ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will not submit horizontal label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. + ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, // Disable header text width contribution to automatic column width. ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, // Make the initial sort direction Ascending when first sorting on this column (default). ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, // Make the initial sort direction Descending when first sorting on this column. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b83cf2987..5c9bcd3b4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6403,7 +6403,11 @@ static void ShowDemoWindowTables() // FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox. static bool column_selected[3] = {}; - // Instead of calling TableHeadersRow() we'll submit custom headers ourselves + // Instead of calling TableHeadersRow() we'll submit custom headers ourselves. + // (A different approach is also possible: + // - Specify ImGuiTableColumnFlags_NoHeaderLabel in some TableSetupColumn() call. + // - Call TableHeadersRow() normally. This will submit TableHeader() with no name. + // - Then call TableSetColumnIndex() to position yourself in the column and submit your stuff e.g. Checkbox().) ImGui::TableNextRow(ImGuiTableRowFlags_Headers); for (int column = 0; column < COLUMNS_COUNT; column++) { @@ -6418,6 +6422,7 @@ static void ShowDemoWindowTables() ImGui::PopID(); } + // Submit table contents for (int row = 0; row < 5; row++) { ImGui::TableNextRow(); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index fd7e6da57..69d1322bd 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3018,7 +3018,8 @@ float ImGui::TableGetHeaderAngledMaxLabelWidth() // The intent is that advanced users willing to create customized headers would not need to use this helper // and can create their own! For example: TableHeader() may be preceded by Checkbox() or other custom widgets. // See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this. -// This code is constructed to not make much use of internal functions, as it is intended to be a template to copy. +// This code is intentionally written to not make much use of internal functions, to give you better direction +// if you need to write your own. // FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public. void ImGui::TableHeadersRow() { @@ -3026,7 +3027,8 @@ void ImGui::TableHeadersRow() ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!"); - // Layout if not already done (this is automatically done by TableNextRow, we do it here solely to facilitate stepping in debugger as it is frequent to step in TableUpdateLayout) + // Call layout if not already done. This is automatically done by TableNextRow: we do it here _only_ to make + // it easier to debug-step in TableUpdateLayout(). Your own version of this function doesn't need this. if (!table->IsLayoutLocked) TableUpdateLayout(table); @@ -3043,8 +3045,7 @@ void ImGui::TableHeadersRow() if (!TableSetColumnIndex(column_n)) continue; - // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them) - // In your own code you may omit the PushID/PopID all-together, provided you know they won't collide. + // Push an id to allow empty/unnamed headers. This is also idiomatic as it ensure there is a consistent ID path to access columns (for e.g. automation) const char* name = (TableGetColumnFlags(column_n) & ImGuiTableColumnFlags_NoHeaderLabel) ? "" : TableGetColumnName(column_n); PushID(column_n); TableHeader(name); From 8dd33839f026ddd154c550b72f21a70746e6cab5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Sep 2024 15:15:48 +0200 Subject: [PATCH 0328/2359] Tables: fixed an issue detecting hovering column/row when using multiple synched instances layed out at different X positions. (#7933) Was reading ClipRect from last frame. --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 11 ++++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d76a04042..95745581a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,8 @@ Other changes: - Tables: fixes/revert a 1.90 change were outer border would be moved bottom and right by an extra pixel + rework the change so that contents doesn't overlap the bottom and right border in a scrolling table. (#6765, #3752, #7428) +- Tables: fixed an issue detecting hovering column/row when using multiple synched instances, + layed out at different X positions. (#7932) - Tabs: avoid queuing a refocus when tab is already focused, which would have the side-effect of e.g. closing popup on a mouse release. (#7914) - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 69d1322bd..9ee70fc50 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1070,10 +1070,6 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) continue; } - // Detect hovered column - if (is_hovering_table && mouse_skewed_x >= column->ClipRect.Min.x && mouse_skewed_x < column->ClipRect.Max.x) - table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n; - // Lock start position column->MinX = offset_x; @@ -1128,8 +1124,13 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->Flags |= ImGuiTableColumnFlags_IsVisible; if (column->SortOrder != -1) column->Flags |= ImGuiTableColumnFlags_IsSorted; - if (table->HoveredColumnBody == column_n) + + // Detect hovered column + if (is_hovering_table && mouse_skewed_x >= column->ClipRect.Min.x && mouse_skewed_x < column->ClipRect.Max.x) + { column->Flags |= ImGuiTableColumnFlags_IsHovered; + table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n; + } // Alignment // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in From f75cf62d2f36a66fcdc7be7161a3798bea926509 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Sep 2024 15:31:39 +0200 Subject: [PATCH 0329/2359] Tables: fixed resizing columns when using multiple synched instances that are layed out at different X positions. (#7933) TableGetMaxColumnWidth() was using MinX from previous column. Storing info in column. Still incorrect interleaved data for multi-instances but it covers majority of use cases. --- docs/CHANGELOG.txt | 4 ++-- imgui_internal.h | 3 ++- imgui_tables.cpp | 10 +++++----- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 95745581a..4c2537a8c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,8 +85,8 @@ Other changes: - Tables: fixes/revert a 1.90 change were outer border would be moved bottom and right by an extra pixel + rework the change so that contents doesn't overlap the bottom and right border in a scrolling table. (#6765, #3752, #7428) -- Tables: fixed an issue detecting hovering column/row when using multiple synched instances, - layed out at different X positions. (#7932) +- Tables: fixed an issue resizing columns or querying hovered column/row when using multiple + synched instances that are layed out at different X positions. (#7933) - Tabs: avoid queuing a refocus when tab is already focused, which would have the side-effect of e.g. closing popup on a mouse release. (#7914) - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) diff --git a/imgui_internal.h b/imgui_internal.h index 59d8af7eb..cb7923c64 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2827,6 +2827,7 @@ struct ImGuiTableColumn float MaxX; float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from StretchWeight in TableUpdateLayout() float WidthAuto; // Automatic width + float WidthMax; // Maximum width (FIXME: overwritten by each instance) float StretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially. float InitStretchWeightOrWidth; // Value passed to TableSetupColumn(). For Width it is a content width (_without padding_). ImRect ClipRect; // Clipping rectangle for the column @@ -3470,7 +3471,7 @@ namespace ImGui IMGUI_API ImRect TableGetCellBgRect(const ImGuiTable* table, int column_n); IMGUI_API const char* TableGetColumnName(const ImGuiTable* table, int column_n); IMGUI_API ImGuiID TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no = 0); - IMGUI_API float TableGetMaxColumnWidth(const ImGuiTable* table, int column_n); + IMGUI_API float TableCalcMaxColumnWidth(const ImGuiTable* table, int column_n); IMGUI_API void TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n); IMGUI_API void TableSetColumnWidthAutoAll(ImGuiTable* table); IMGUI_API void TableRemove(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 9ee70fc50..aaa40de81 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1074,8 +1074,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->MinX = offset_x; // Lock width based on start position and minimum/maximum width for this position - float max_width = TableGetMaxColumnWidth(table, column_n); - column->WidthGiven = ImMin(column->WidthGiven, max_width); + column->WidthMax = TableCalcMaxColumnWidth(table, column_n); + column->WidthGiven = ImMin(column->WidthGiven, column->WidthMax); column->WidthGiven = ImMax(column->WidthGiven, ImMin(column->WidthRequest, table->MinColumnWidth)); column->MaxX = offset_x + column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f; @@ -2207,8 +2207,8 @@ void ImGui::TableEndCell(ImGuiTable* table) // Note that actual columns widths are computed in TableUpdateLayout(). //------------------------------------------------------------------------- -// Maximum column content width given current layout. Use column->MinX so this value on a per-column basis. -float ImGui::TableGetMaxColumnWidth(const ImGuiTable* table, int column_n) +// Maximum column content width given current layout. Use column->MinX so this value differs on a per-column basis. +float ImGui::TableCalcMaxColumnWidth(const ImGuiTable* table, int column_n) { const ImGuiTableColumn* column = &table->Columns[column_n]; float max_width = FLT_MAX; @@ -2270,7 +2270,7 @@ void ImGui::TableSetColumnWidth(int column_n, float width) // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) IM_ASSERT(table->MinColumnWidth > 0.0f); const float min_width = table->MinColumnWidth; - const float max_width = ImMax(min_width, TableGetMaxColumnWidth(table, column_n)); + const float max_width = ImMax(min_width, column_0->WidthMax); // Don't use TableCalcMaxColumnWidth() here as it would rely on MinX from last instance (#7933) column_0_width = ImClamp(column_0_width, min_width, max_width); if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width) return; From 1dfbb100d6ca6e7d813102e979c07f66a56546bb Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Sep 2024 16:17:30 +0200 Subject: [PATCH 0330/2359] Version 1.91.1 --- docs/CHANGELOG.txt | 24 +++++++++++++----------- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 22 insertions(+), 20 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4c2537a8c..d7fec4cff 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.91.1 WIP (In Progress) + VERSION 1.91.1 (Released 2024-09-04) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.1 + Breaking changes: - BeginChild(): renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. [@cfillion] @@ -54,7 +56,6 @@ Breaking changes: - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn (#7660) - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn - io.PlatformLocaleDecimalPoint -> platform_io.Platform_LocaleDecimalPoint (#7389, #6719, #2278) - - clipboard function signature changed: - access those via GetPlatformIO() instead of GetIO(). (Because PlatformOpenInShellFn and PlatformSetImeDataFn were introduced very recently and often automatically set by core library and backends, we are exceptionally not maintaining @@ -63,14 +64,14 @@ Breaking changes: - old ImageButton() used ImTextureId as item id (created issue with e.g. multiple buttons in same scope, transient texture id values, opaque computation of ID) - new ImageButton() requires an explicit 'const char* str_id' - old ImageButton() had frame_padding' override argument. - - new ImageButton() always use style.FramePadding, which you can freely override with PushStyleVar()/PopStyleVar(). + - new ImageButton() always use style.FramePadding, which you can modify using PushStyleVar()/PopStyleVar(). Other changes: - IO: Added GetPlatformIO() and ImGuiPlatformIO, pulled from 'docking' branch, which is a centralized spot to connect os/platform/renderer related functions. Clipboard, IME and OpenInShell hooks are moved here. (#7660) -- IO, InputText: fixed an issue where typing text in a InputText() would defer character +- IO, InputText: fixed an issue where typing text in an InputText() would defer character processing by one frame, because of the trickling input queue. Reworked interleaved keys<>char trickling to take account for keys known to input characters. (#7889, #4921, #4858) - Windows: adjust default ClipRect to better match rendering of thick borders (which are in @@ -78,10 +79,10 @@ Other changes: edge rather than inner. (#7887, #7888 + #3312, #7540, #3756, #6170, #6365) - Made BeginItemTooltip() and IsItemHovered() with delay flag infer an implicit ID (for ID-less items such as Text element) in a way that works when item resizes. (#7945, #1485) -- MultiSelect+TreeNode+Drag and Drop: fixed an issue where carrying a drag and drop - payload over an already open tree node would incorrectly select it. (#7850) -- MultiSelect+TreeNode: default open behavior is OpenOnDoubleClick + OpenOnArrow - when used in a multi-select context without any OpenOnXXX flags set. (#7850) +- MultiSelect+TreeNode+Drag and Drop: fixed an issue where carrying a drag and drop payload + over an already open tree node using multi-select would incorrectly select it. (#7850) +- MultiSelect+TreeNode: default open behavior is _OpenOnDoubleClick + _OpenOnArrow when + used in a multi-select context without any ImGuiTreeNode_OpenOnXXX flags set. (#7850) - Tables: fixes/revert a 1.90 change were outer border would be moved bottom and right by an extra pixel + rework the change so that contents doesn't overlap the bottom and right border in a scrolling table. (#6765, #3752, #7428) @@ -93,11 +94,12 @@ Other changes: - InputText: fixed an issue programmatically refocusing a multi-line input which was just active. (#4761, #7870) - TextLink(), TextLinkOpenURL(): change mouse cursor to Hand shape when hovered. (#7885, #7660) - Tooltips, Drag and Drop: made it possible to override BeginTooltip() position while inside - a drag and drop source or target: a SetNextWindowPos() call won't be overriden. (#6973) + a drag and drop source or target: a SetNextWindowPos() call won't be overridden. (#6973) - PlotHistogram, PlotLines: register item ID and use button behavior in a more idiomatic manner, fixes preventing e.g. GetItemID() and other ID-based helper to work. (#7935, #3072) -- Style: added PushStyleVarX(), PushStyleVarY() helpers to modify only one component of a ImVec2 var. -- Fonts: made it possible to use PushFont()/PopFont() calls accross Begin() calls. (#3224, #3875, #6398, #7903) +- Style: added PushStyleVarX(), PushStyleVarY() helpers to conveniently modify only + one component of a ImVec2 var. +- Fonts: made it possible to use PushFont()/PopFont() calls across Begin() calls. (#3224, #3875, #6398, #7903) - Backends: - Backends: GLFW: added ImGui_ImplGlfw_Sleep() helper function because GLFW does not provide a way to do a portable sleep. (#7844) diff --git a/imgui.cpp b/imgui.cpp index 767dbf70d..ac76ddd19 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 WIP +// dear imgui, v1.91.1 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index cfee0fcc7..a6766e2d6 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 WIP +// dear imgui, v1.91.1 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.1 WIP" -#define IMGUI_VERSION_NUM 19105 +#define IMGUI_VERSION "1.91.1" +#define IMGUI_VERSION_NUM 19110 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5c9bcd3b4..9ca73806d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 WIP +// dear imgui, v1.91.1 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 65d68708d..e033c357c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 WIP +// dear imgui, v1.91.1 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index cb7923c64..a99cb2652 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 WIP +// dear imgui, v1.91.1 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index aaa40de81..5685c2ace 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 WIP +// dear imgui, v1.91.1 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fd52c93cd..7f2b12711 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 WIP +// dear imgui, v1.91.1 // (widgets code) /* From 41eebc87a06d15979ed0088a4f5ec5673ccc2f6c Mon Sep 17 00:00:00 2001 From: CrackedMatter <81803926+CrackedMatter@users.noreply.github.com> Date: Thu, 5 Sep 2024 12:04:28 +0200 Subject: [PATCH 0331/2359] Fixed C++26 invalid enum operation (#7954) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7f2b12711..b9e2ca2ce 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5196,7 +5196,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)... Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y)); - g.NextItemData.ItemFlags |= ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop; + g.NextItemData.ItemFlags |= (ImGuiItemFlags)ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop; EndChild(); item_data_backup.StatusFlags |= (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredWindow); From e3cb016328468e5902127777fc08b0c249039aaa Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Sep 2024 15:15:49 +0200 Subject: [PATCH 0332/2359] CI: upgrade Ubuntu version to get newer Clang. Add C++26 build test. (#7954) --- .github/workflows/build.yml | 17 ++++++++++++++--- examples/example_null/Makefile | 2 +- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4320a2025..4539ecbf6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -218,7 +218,7 @@ jobs: run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' Linux: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -433,6 +433,17 @@ jobs: EOF clang++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (single file build, c++26) + run: | + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + clang++ -I. -std=c++26 -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (without c++ runtime) run: | cat > example_single_file.cpp <<'EOF' @@ -481,7 +492,7 @@ jobs: xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_ios CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO Emscripten: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -508,7 +519,7 @@ jobs: make -C examples/example_glfw_wgpu -f Makefile.emscripten Android: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index 9ceb35349..4a67cecd8 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -1,6 +1,6 @@ # # Cross Platform Makefile -# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1+ and Mac OS X # # Important: This is a "null backend" application, with no visible output or interaction! # This is used for testing purpose and continuous integration, and has little use for end-user. From 943fd216ecadedd4ca59bb3ec56730c73bb9295c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Sep 2024 15:19:04 +0200 Subject: [PATCH 0333/2359] CI: Amend e3cb016. --- .github/workflows/build.yml | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4539ecbf6..7c7f7471f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -324,6 +324,18 @@ jobs: EOF g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (with C++26) + run: | + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_DISABLE_OBSOLETE_KEYIO + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++26 -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (with IMGUI_DISABLE_DEMO_WINDOWS and IMGUI_DISABLE_DEBUG_TOOLS) run: | cat > example_single_file.cpp <<'EOF' @@ -433,7 +445,7 @@ jobs: EOF clang++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - - name: Build example_null (single file build, c++26) + - name: Build example_null (single file build, c++20) run: | cat > example_single_file.cpp <<'EOF' @@ -442,7 +454,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - clang++ -I. -std=c++26 -Wall -Wformat -o example_single_file example_single_file.cpp + clang++ -I. -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (without c++ runtime) run: | From 4a1a38f7ed0ab89aa506dcba346e90d698d1a8d2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Sep 2024 15:28:41 +0200 Subject: [PATCH 0334/2359] CI: Amend 943fd21. --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7c7f7471f..702e281bf 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -324,7 +324,7 @@ jobs: EOF g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - - name: Build example_null (with C++26) + - name: Build example_null (with C++20) run: | cat > example_single_file.cpp <<'EOF' @@ -334,7 +334,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++26 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_DEMO_WINDOWS and IMGUI_DISABLE_DEBUG_TOOLS) run: | From d0b742efdee1d09ff0e87a8a1419e08f7f84174c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Sep 2024 15:30:29 +0200 Subject: [PATCH 0335/2359] CI: build with Clang C++26 on Linux. (#7954) --- .github/workflows/build.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 702e281bf..1d43da032 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -393,6 +393,18 @@ jobs: EOF g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (C++26, Clang) + run: | + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_IMPLEMENTATION + #define IMGUI_DISABLE_DEMO_WINDOWS + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + clang++ -I. -std=c++26 -Wall -Wformat -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + - name: Build example_null (without c++ runtime, Clang) run: | cat > example_single_file.cpp <<'EOF' From 193c1e2366857dbfdbc3dd98c5b95f47b881f122 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Sep 2024 20:03:23 +0200 Subject: [PATCH 0336/2359] Version 1.91.2 WIP --- docs/CHANGELOG.txt | 8 ++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d7fec4cff..0136b45a7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,14 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.91.2 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking changes: + +Other changes: + ----------------------------------------------------------------------- VERSION 1.91.1 (Released 2024-09-04) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index ac76ddd19..6706135e3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 +// dear imgui, v1.91.2 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index a6766e2d6..0eeba4af0 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 +// dear imgui, v1.91.2 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.1" -#define IMGUI_VERSION_NUM 19110 +#define IMGUI_VERSION "1.91.2 WIP" +#define IMGUI_VERSION_NUM 19111 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9ca73806d..aabb220d6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 +// dear imgui, v1.91.2 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e033c357c..a681059bb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 +// dear imgui, v1.91.2 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index a99cb2652..a0b110904 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 +// dear imgui, v1.91.2 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 5685c2ace..f247ed6d3 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 +// dear imgui, v1.91.2 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b9e2ca2ce..3b0fcc52f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.1 +// dear imgui, v1.91.2 WIP // (widgets code) /* From d16cb171c6667c6b7e8d0bd89389a968492c14ce Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Sep 2024 20:16:37 +0200 Subject: [PATCH 0337/2359] Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439, extend #370, #369) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0136b45a7..f425dc60e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking changes: Other changes: +- Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439) + ----------------------------------------------------------------------- VERSION 1.91.1 (Released 2024-09-04) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 6706135e3..fd018802a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13182,9 +13182,11 @@ static void ImGui::NavUpdateWindowing() // Keyboard: Press and Release ALT to toggle menu layer const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt }; + bool windowing_toggle_layer_start = false; for (ImGuiKey windowing_toggle_key : windowing_toggle_keys) if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner)) { + windowing_toggle_layer_start = true; g.NavWindowingToggleLayer = true; g.NavWindowingToggleKey = windowing_toggle_key; g.NavInputSource = ImGuiInputSource_Keyboard; @@ -13198,7 +13200,9 @@ static void ImGui::NavUpdateWindowing() // We cancel toggling nav layer if an owner has claimed the key. if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper) g.NavWindowingToggleLayer = false; - if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false) + else if (windowing_toggle_layer_start == false && g.LastKeyboardKeyPressTime == g.Time) + g.NavWindowingToggleLayer = false; + else if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false) g.NavWindowingToggleLayer = false; // Apply layer toggle on Alt release From a5cf4fe374d491c882974d492a05117ef4bcc102 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Sep 2024 20:45:07 +0200 Subject: [PATCH 0338/2359] InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 21 +++++++++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f425dc60e..82c7a60b6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,7 @@ Breaking changes: Other changes: - Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439) +- InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow. ----------------------------------------------------------------------- VERSION 1.91.1 (Released 2024-09-04) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3b0fcc52f..2f998a649 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3894,9 +3894,18 @@ static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* ob r->num_chars = (int)(text_remaining - (text + line_start_idx)); } -static bool is_separator(unsigned int c) +static bool ImCharIsSeparatorW(unsigned int c) { - return c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|' || c=='\n' || c=='\r' || c=='.' || c=='!' || c=='\\' || c=='/'; + static const unsigned int separator_list[] = + { + ',', 0x3001, '.', 0x3002, ';', 0xFF1B, '(', 0xFF08, ')', 0xFF09, '{', 0xFF5B, '}', 0xFF5D, + '[', 0x300C, ']', 0x300D, '|', 0xFF5C, '!', 0xFF01, '\\', 0xFFE5, '/', 0x30FB, 0xFF0F, + '\n', '\r', + }; + for (unsigned int separator : separator_list) + if (c == separator) + return true; + return false; } static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx) @@ -3906,9 +3915,9 @@ static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx) return 0; bool prev_white = ImCharIsBlankW(obj->TextW[idx - 1]); - bool prev_separ = is_separator(obj->TextW[idx - 1]); + bool prev_separ = ImCharIsSeparatorW(obj->TextW[idx - 1]); bool curr_white = ImCharIsBlankW(obj->TextW[idx]); - bool curr_separ = is_separator(obj->TextW[idx]); + bool curr_separ = ImCharIsSeparatorW(obj->TextW[idx]); return ((prev_white || prev_separ) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ); } static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx) @@ -3917,9 +3926,9 @@ static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx) return 0; bool prev_white = ImCharIsBlankW(obj->TextW[idx]); - bool prev_separ = is_separator(obj->TextW[idx]); + bool prev_separ = ImCharIsSeparatorW(obj->TextW[idx]); bool curr_white = ImCharIsBlankW(obj->TextW[idx - 1]); - bool curr_separ = is_separator(obj->TextW[idx - 1]); + bool curr_separ = ImCharIsSeparatorW(obj->TextW[idx - 1]); return ((prev_white) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ); } static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } From a2366f902249107f1533a85d3d1f93ec193f52f0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 6 Sep 2024 11:38:48 +0200 Subject: [PATCH 0339/2359] TextLinkOpenURL: display a verb in front the link. Update Gallery & other links. (#7885, #7660) --- docs/BACKENDS.md | 2 +- docs/CHANGELOG.txt | 1 + docs/FAQ.md | 10 +++++----- docs/README.md | 6 +++--- imgui.cpp | 7 ++++--- imgui.h | 2 +- imgui_internal.h | 1 + imgui_widgets.cpp | 2 +- 8 files changed, 17 insertions(+), 14 deletions(-) diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 55a0983dd..de5cd6697 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -135,7 +135,7 @@ Generally: It is unlikely you will add value to your project by creating your own backend. Also: -The [multi-viewports feature](https://github.com/ocornut/imgui/issues/1542) of the 'docking' branch allows +The [multi-viewports feature](https://github.com/ocornut/imgui/wiki/Multi-Viewports) of the 'docking' branch allows Dear ImGui windows to be seamlessly detached from the main application window. This is achieved using an extra layer to the Platform and Renderer backends, which allows Dear ImGui to communicate platform-specific requests such as: "create an additional OS window", "create a render context", "get the OS position of this diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 82c7a60b6..70b7424e9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,7 @@ Other changes: - Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439) - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow. +- TextLinkOpenURL(): modified tooltip to display a verb "Open 'xxxx'". (#7885, #7660) ----------------------------------------------------------------------- VERSION 1.91.1 (Released 2024-09-04) diff --git a/docs/FAQ.md b/docs/FAQ.md index d104c30bc..d53a5a099 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -77,9 +77,9 @@ or view this file with any Markdown viewer. ### Q: Which version should I get? I occasionally tag [Releases](https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. -You may use the [docking](https://github.com/ocornut/imgui/tree/docking) branch which includes: -- [Docking features](https://github.com/ocornut/imgui/issues/2109) -- [Multi-viewport features](https://github.com/ocornut/imgui/issues/1542) +You may use the ['docking'](https://github.com/ocornut/imgui/tree/docking) branch which includes: +- [Docking features](https://github.com/ocornut/imgui/wiki/Docking) +- [Multi-viewport features](https://github.com/ocornut/imgui/wiki/Multi-Viewports) Many projects are using this branch and it is kept in sync with master regularly. @@ -654,7 +654,7 @@ You may take a look at: - [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [Funding & Sponsors](https://github.com/ocornut/imgui/wiki/Funding) -- [Gallery](https://github.com/ocornut/imgui/issues/7503) +- [Gallery](https://github.com/ocornut/imgui/issues?q=label%3Agallery) ##### [Return to Index](#index) @@ -700,7 +700,7 @@ There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/ci - Individuals: you can support continued maintenance and development via PayPal donations. See [README](https://github.com/ocornut/imgui/blob/master/docs/README.md). - If you are experienced with Dear ImGui and C++, look at [GitHub Issues](https://github.com/ocornut/imgui/issues), [GitHub Discussions](https://github.com/ocornut/imgui/discussions), the [Wiki](https://github.com/ocornut/imgui/wiki), read [docs/TODO.txt](https://github.com/ocornut/imgui/blob/master/docs/TODO.txt), and see how you want to help and can help! - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere, etc. -You may post screenshots or links in the [gallery threads](https://github.com/ocornut/imgui/issues/7503). Visuals are ideal as they inspire other programmers. Disclosing your use of Dear ImGui helps the library grow credibility, and helps other teams and programmers with taking decisions. +You may post screenshots or links in the [gallery threads](https://github.com/ocornut/imgui/issues?q=label%3Agallery). Visuals are ideal as they inspire other programmers. Disclosing your use of Dear ImGui helps the library grow credibility, and helps other teams and programmers with taking decisions. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues or sometimes incomplete PR. ##### [Return to Index](#index) diff --git a/docs/README.md b/docs/README.md index a1807abac..0968727f1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -141,7 +141,7 @@ Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. Examples projects using Dear ImGui: [Tracy](https://github.com/wolfpld/tracy) (profiler), [ImHex](https://github.com/WerWolv/ImHex) (hex editor/data analysis), [RemedyBG](https://remedybg.itch.io/remedybg) (debugger) and [hundreds of others](https://github.com/ocornut/imgui/wiki/Software-using-Dear-ImGui). -For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues/7503)! +For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues?q=label%3Agallery)! For a list of third-party widgets and extensions, check out the [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page. @@ -170,11 +170,11 @@ Private support is available for paying business customers (E-mail: _contact @ d **Which version should I get?** -We occasionally tag [Releases](https://github.com/ocornut/imgui/releases) (with nice releases notes) but it is generally safe and recommended to sync to latest `master` or `docking` branch. The library is fairly stable and regressions tend to be fixed fast when reported. Advanced users may want to use the `docking` branch with [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features. This branch is kept in sync with master regularly. +We occasionally tag [Releases](https://github.com/ocornut/imgui/releases) (with nice releases notes) but it is generally safe and recommended to sync to latest `master` or `docking` branch. The library is fairly stable and regressions tend to be fixed fast when reported. Advanced users may want to use the `docking` branch with [Multi-Viewport](https://github.com/ocornut/imgui/wiki/Multi-Viewports) and [Docking](https://github.com/ocornut/imgui/wiki/Docking) features. This branch is kept in sync with master regularly. **Who uses Dear ImGui?** -See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes), [Funding & Sponsors](https://github.com/ocornut/imgui/wiki/Funding), and [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also, see the [Gallery Threads](https://github.com/ocornut/imgui/issues/7503)! +See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes), [Funding & Sponsors](https://github.com/ocornut/imgui/wiki/Funding), and [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also, see the [Gallery Threads](https://github.com/ocornut/imgui/issues?q=label%3Agallery)! How to help ----------- diff --git a/imgui.cpp b/imgui.cpp index fd018802a..1d9d8b899 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10,7 +10,7 @@ // - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) // - Homepage ................... https://github.com/ocornut/imgui // - Releases & changelog ....... https://github.com/ocornut/imgui/releases -// - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!) +// - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) // - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) // - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) // - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) @@ -3780,7 +3780,7 @@ void ImGui::DestroyContext(ImGuiContext* ctx) IM_DELETE(ctx); } -// IMPORTANT: ###xxx suffixes must be same in ALL languages to allow for automation. +// IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation. static const ImGuiLocEntry GLocalizationEntriesEnUS[] = { { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" }, @@ -3791,7 +3791,8 @@ static const ImGuiLocEntry GLocalizationEntriesEnUS[] = { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" }, { ImGuiLocKey_WindowingPopup, "(Popup)" }, { ImGuiLocKey_WindowingUntitled, "(Untitled)" }, - { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" }, + { ImGuiLocKey_OpenLink_s, "Open '%s'" }, + { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" }, }; void ImGui::Initialize() diff --git a/imgui.h b/imgui.h index 0eeba4af0..0394967ee 100644 --- a/imgui.h +++ b/imgui.h @@ -11,7 +11,7 @@ // - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) // - Homepage ................... https://github.com/ocornut/imgui // - Releases & changelog ....... https://github.com/ocornut/imgui/releases -// - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!) +// - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) // - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) // - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) // - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) diff --git a/imgui_internal.h b/imgui_internal.h index a0b110904..5d23ebfef 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1882,6 +1882,7 @@ enum ImGuiLocKey : int ImGuiLocKey_WindowingMainMenuBar, ImGuiLocKey_WindowingPopup, ImGuiLocKey_WindowingUntitled, + ImGuiLocKey_OpenLink_s, ImGuiLocKey_CopyLink, ImGuiLocKey_COUNT }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2f998a649..7b86fb8be 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1460,7 +1460,7 @@ void ImGui::TextLinkOpenURL(const char* label, const char* url) if (TextLink(label)) if (g.PlatformIO.Platform_OpenInShellFn != NULL) g.PlatformIO.Platform_OpenInShellFn(&g, url); - SetItemTooltip("%s", url); // It is more reassuring for user to _always_ display URL when we same as label + SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url); // It is more reassuring for user to _always_ display URL when we same as label if (BeginPopupContextItem()) { if (MenuItem(LocalizeGetMsg(ImGuiLocKey_CopyLink))) From 21d03edcb0cdad9e870f94f55ebb1d6deb54bc30 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Sep 2024 16:22:55 +0200 Subject: [PATCH 0340/2359] InputText: renamed namespace from stb_texture structure and added an indirection. --- imgui_internal.h | 27 +++++++------- imgui_widgets.cpp | 90 +++++++++++++++++++++++++++-------------------- 2 files changed, 66 insertions(+), 51 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5d23ebfef..ab7cbc1f3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -216,6 +216,8 @@ namespace ImStb } // namespace ImStb +typedef ImStb::STB_TexteditState ImStbTexteditState; + //----------------------------------------------------------------------------- // [SECTION] Macros //----------------------------------------------------------------------------- @@ -1110,11 +1112,13 @@ struct IMGUI_API ImGuiInputTextDeactivatedState ImGuiInputTextDeactivatedState() { memset(this, 0, sizeof(*this)); } void ClearFreeMemory() { ID = 0; TextA.clear(); } }; + // Internal state of the currently focused/edited text input box // For a given item ID, access with ImGui::GetInputTextState() struct IMGUI_API ImGuiInputTextState { ImGuiContext* Ctx; // parent UI context (needs to be set explicitly by parent). + ImStbTexteditState* Stb; // State for stb_textedit.h ImGuiID ID; // widget id owning the text state int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 length is valid even if TextA is not. ImVector TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. @@ -1123,7 +1127,7 @@ struct IMGUI_API ImGuiInputTextState bool TextAIsValid; // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument) int BufCapacityA; // end-user buffer capacity ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) - ImStb::STB_TexteditState Stb; // state for stb_textedit.h + float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection @@ -1133,22 +1137,21 @@ struct IMGUI_API ImGuiInputTextState int ReloadSelectionStart; // POSITIONS ARE IN IMWCHAR units *NOT* UTF-8 this is why this is not exposed yet. int ReloadSelectionEnd; - ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } + ImGuiInputTextState(); + ~ImGuiInputTextState(); void ClearText() { CurLenW = CurLenA = 0; TextW[0] = 0; TextA[0] = 0; CursorClamp(); } void ClearFreeMemory() { TextW.clear(); TextA.clear(); InitialTextA.clear(); } - int GetUndoAvailCount() const { return Stb.undostate.undo_point; } - int GetRedoAvailCount() const { return IMSTB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; } void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation // Cursor & Selection void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking - void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); } - bool HasSelection() const { return Stb.select_start != Stb.select_end; } - void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; } - int GetCursorPos() const { return Stb.cursor; } - int GetSelectionStart() const { return Stb.select_start; } - int GetSelectionEnd() const { return Stb.select_end; } - void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } + void CursorClamp() { Stb->cursor = ImMin(Stb->cursor, CurLenW); Stb->select_start = ImMin(Stb->select_start, CurLenW); Stb->select_end = ImMin(Stb->select_end, CurLenW); } + bool HasSelection() const { return Stb->select_start != Stb->select_end; } + void ClearSelection() { Stb->select_start = Stb->select_end = Stb->cursor; } + int GetCursorPos() const { return Stb->cursor; } + int GetSelectionStart() const { return Stb->select_start; } + int GetSelectionEnd() const { return Stb->select_end; } + void SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = CurLenW; Stb->has_preferred_x = 0; } // Reload user buf (WIP #2890) // If you modify underlying user-passed const char* while active you need to call this (InputText V2 may lift this) @@ -1156,7 +1159,7 @@ struct IMGUI_API ImGuiInputTextState // if (ImGuiInputTextState* state = ImGui::GetInputTextState(id)) // id may be ImGui::GetItemID() is last item // state->ReloadUserBufAndSelectAll(); void ReloadUserBufAndSelectAll() { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; } - void ReloadUserBufAndKeepSelection() { ReloadUserBuf = true; ReloadSelectionStart = Stb.select_start; ReloadSelectionEnd = Stb.select_end; } + void ReloadUserBufAndKeepSelection() { ReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; } void ReloadUserBufAndMoveToEnd() { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; } }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7b86fb8be..f35927727 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4029,9 +4029,21 @@ static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* st } // namespace ImStb +// We added an extra indirection where 'Stb' is heap-allocated, in order facilitate the work of bindings generators. +ImGuiInputTextState::ImGuiInputTextState() +{ + memset(this, 0, sizeof(*this)); + Stb = IM_NEW(ImStbTexteditState); +} + +ImGuiInputTextState::~ImGuiInputTextState() +{ + IM_DELETE(Stb); +} + void ImGuiInputTextState::OnKeyPressed(int key) { - stb_textedit_key(this, &Stb, key); + stb_textedit_key(this, Stb, key); CursorFollow = true; CursorAnimReset(); } @@ -4229,7 +4241,7 @@ static void InputTextReconcileUndoStateAfterUserCallback(ImGuiInputTextState* st const int insert_len = new_last_diff - first_diff + 1; const int delete_len = old_last_diff - first_diff + 1; if (insert_len > 0 || delete_len > 0) - if (IMSTB_TEXTEDIT_CHARTYPE* p = stb_text_createundo(&state->Stb.undostate, first_diff, delete_len, insert_len)) + if (IMSTB_TEXTEDIT_CHARTYPE* p = stb_text_createundo(&state->Stb->undostate, first_diff, delete_len, insert_len)) for (int i = 0; i < delete_len; i++) p[i] = ImStb::STB_TEXTEDIT_GETCHAR(state, first_diff + i); } @@ -4371,7 +4383,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX; const bool init_reload_from_user_buf = (state != NULL && state->ReloadUserBuf); - const bool init_changed_specs = (state != NULL && state->Stb.single_line != !is_multiline); // state != NULL means its our state. + const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state. const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav); const bool init_state = (init_make_active || user_scroll_active); if ((init_state && g.ActiveId != id) || init_changed_specs || init_reload_from_user_buf) @@ -4417,13 +4429,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else { state->Scroll = ImVec2(0.0f, 0.0f); - stb_textedit_initialize_state(&state->Stb, !is_multiline); + stb_textedit_initialize_state(state->Stb, !is_multiline); } if (init_reload_from_user_buf) { - state->Stb.select_start = state->ReloadSelectionStart; - state->Stb.cursor = state->Stb.select_end = state->ReloadSelectionEnd; + state->Stb->select_start = state->ReloadSelectionStart; + state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd; state->CursorClamp(); } else if (!is_multiline) @@ -4437,7 +4449,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } if (flags & ImGuiInputTextFlags_AlwaysOverwrite) - state->Stb.insert_mode = 1; // stb field name is indeed incorrect (see #2863) + state->Stb->insert_mode = 1; // stb field name is indeed incorrect (see #2863) } const bool is_osx = io.ConfigMacOSXBehaviors; @@ -4545,34 +4557,34 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } else if (hovered && io.MouseClickedCount[0] >= 2 && !io.KeyShift) { - stb_textedit_click(state, &state->Stb, mouse_x, mouse_y); + stb_textedit_click(state, state->Stb, mouse_x, mouse_y); const int multiclick_count = (io.MouseClickedCount[0] - 2); if ((multiclick_count % 2) == 0) { // Double-click: Select word // We always use the "Mac" word advance for double-click select vs CTRL+Right which use the platform dependent variant: // FIXME: There are likely many ways to improve this behavior, but there's no "right" behavior (depends on use-case, software, OS) - const bool is_bol = (state->Stb.cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb.cursor - 1) == '\n'; - if (STB_TEXT_HAS_SELECTION(&state->Stb) || !is_bol) + const bool is_bol = (state->Stb->cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor - 1) == '\n'; + if (STB_TEXT_HAS_SELECTION(state->Stb) || !is_bol) state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); //state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); - if (!STB_TEXT_HAS_SELECTION(&state->Stb)) - ImStb::stb_textedit_prep_selection_at_cursor(&state->Stb); - state->Stb.cursor = ImStb::STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state->Stb.cursor); - state->Stb.select_end = state->Stb.cursor; - ImStb::stb_textedit_clamp(state, &state->Stb); + if (!STB_TEXT_HAS_SELECTION(state->Stb)) + ImStb::stb_textedit_prep_selection_at_cursor(state->Stb); + state->Stb->cursor = ImStb::STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state->Stb->cursor); + state->Stb->select_end = state->Stb->cursor; + ImStb::stb_textedit_clamp(state, state->Stb); } else { // Triple-click: Select line - const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb.cursor) == '\n'; + const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor) == '\n'; state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART); state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT); state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT); if (!is_eol && is_multiline) { - ImSwap(state->Stb.select_start, state->Stb.select_end); - state->Stb.cursor = state->Stb.select_end; + ImSwap(state->Stb->select_start, state->Stb->select_end); + state->Stb->cursor = state->Stb->select_end; } state->CursorFollow = false; } @@ -4583,15 +4595,15 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (hovered) { if (io.KeyShift) - stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y); + stb_textedit_drag(state, state->Stb, mouse_x, mouse_y); else - stb_textedit_click(state, &state->Stb, mouse_x, mouse_y); + stb_textedit_click(state, state->Stb, mouse_x, mouse_y); state->CursorAnimReset(); } } else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) { - stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y); + stb_textedit_drag(state, state->Stb, mouse_x, mouse_y); state->CursorAnimReset(); state->CursorFollow = true; } @@ -4644,7 +4656,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(state != NULL); const int row_count_per_page = ImMax((int)((inner_size.y - style.FramePadding.y) / g.FontSize), 1); - state->Stb.row_count_per_page = row_count_per_page; + state->Stb->row_count_per_page = row_count_per_page; const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl @@ -4751,8 +4763,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Cut, Copy if (g.PlatformIO.Platform_SetClipboardTextFn != NULL) { - const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; - const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; + const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0; + const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->CurLenW; const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1; char* clipboard_data = (char*)IM_ALLOC(clipboard_data_len * sizeof(char)); ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie); @@ -4764,7 +4776,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (!state->HasSelection()) state->SelectAll(); state->CursorFollow = true; - stb_textedit_cut(state, &state->Stb); + stb_textedit_cut(state, state->Stb); } } else if (is_paste) @@ -4786,7 +4798,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ clipboard_filtered[clipboard_filtered_len] = 0; if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation { - stb_textedit_paste(state, &state->Stb, clipboard_filtered, clipboard_filtered_len); + stb_textedit_paste(state, state->Stb, clipboard_filtered, clipboard_filtered_len); state->CursorFollow = true; } MemFree(clipboard_filtered); @@ -4813,7 +4825,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ apply_new_text_length = 0; value_changed = true; IMSTB_TEXTEDIT_CHARTYPE empty_string; - stb_textedit_replace(state, &state->Stb, &empty_string, 0); + stb_textedit_replace(state, state->Stb, &empty_string, 0); } else if (strcmp(buf, state->InitialTextA.Data) != 0) { @@ -4828,7 +4840,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ w_text.resize(ImTextCountCharsFromUtf8(apply_new_text, apply_new_text + apply_new_text_length) + 1); ImTextStrFromUtf8(w_text.Data, w_text.Size, apply_new_text, apply_new_text + apply_new_text_length); } - stb_textedit_replace(state, &state->Stb, w_text.Data, (apply_new_text_length > 0) ? (w_text.Size - 1) : 0); + stb_textedit_replace(state, state->Stb, w_text.Data, (apply_new_text_length > 0) ? (w_text.Size - 1) : 0); } } @@ -4903,9 +4915,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) ImWchar* text = state->TextW.Data; - const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb.cursor); - const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_start); - const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_end); + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb->cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb->select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb->select_end); // Call user code callback(&callback_data); @@ -4916,9 +4928,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(callback_data.BufSize == state->BufCapacityA); IM_ASSERT(callback_data.Flags == flags); const bool buf_dirty = callback_data.BufDirty; - if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } - if (callback_data.SelectionStart != utf8_selection_start || buf_dirty) { state->Stb.select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb.cursor : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } - if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb.select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb.select_start : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } + if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb->cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } + if (callback_data.SelectionStart != utf8_selection_start || buf_dirty) { state->Stb->select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb->cursor : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } + if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb->select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb->select_start : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } if (buf_dirty) { // Callback may update buffer and thus set buf_dirty even in read-only mode. @@ -5040,13 +5052,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ int searches_remaining = 0; if (render_cursor) { - searches_input_ptr[0] = text_begin + state->Stb.cursor; + searches_input_ptr[0] = text_begin + state->Stb->cursor; searches_result_line_no[0] = -1; searches_remaining++; } if (render_selection) { - searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); + searches_input_ptr[1] = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end); searches_result_line_no[1] = -1; searches_remaining++; } @@ -5122,8 +5134,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const ImVec2 draw_scroll = ImVec2(state->Scroll.x, 0.0f); if (render_selection) { - const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); - const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end); + const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end); + const ImWchar* text_selected_end = text_begin + ImMax(state->Stb->select_start, state->Stb->select_end); ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. @@ -5244,7 +5256,7 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state) { #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *GImGui; - ImStb::STB_TexteditState* stb_state = &state->Stb; + ImStb::STB_TexteditState* stb_state = state->Stb; ImStb::StbUndoState* undo_state = &stb_state->undostate; Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId); DebugLocateItemOnHover(state->ID); From ca5701d45807ff7bdc71ccb85d9f1030cc8e917d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Sep 2024 16:29:47 +0200 Subject: [PATCH 0341/2359] InputText: moved all ImGuiInputTextState functions to not be inline. --- imgui.h | 2 +- imgui_internal.h | 24 +++++++++++------------- imgui_widgets.cpp | 13 +++++++++++++ 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/imgui.h b/imgui.h index 0394967ee..18efaff42 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.2 WIP" -#define IMGUI_VERSION_NUM 19111 +#define IMGUI_VERSION_NUM 19112 #define IMGUI_HAS_TABLE /* diff --git a/imgui_internal.h b/imgui_internal.h index ab7cbc1f3..7748f0703 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1127,7 +1127,6 @@ struct IMGUI_API ImGuiInputTextState bool TextAIsValid; // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument) int BufCapacityA; // end-user buffer capacity ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) - float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection @@ -1144,24 +1143,23 @@ struct IMGUI_API ImGuiInputTextState void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation // Cursor & Selection - void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking - void CursorClamp() { Stb->cursor = ImMin(Stb->cursor, CurLenW); Stb->select_start = ImMin(Stb->select_start, CurLenW); Stb->select_end = ImMin(Stb->select_end, CurLenW); } - bool HasSelection() const { return Stb->select_start != Stb->select_end; } - void ClearSelection() { Stb->select_start = Stb->select_end = Stb->cursor; } - int GetCursorPos() const { return Stb->cursor; } - int GetSelectionStart() const { return Stb->select_start; } - int GetSelectionEnd() const { return Stb->select_end; } - void SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = CurLenW; Stb->has_preferred_x = 0; } + void CursorAnimReset(); + void CursorClamp(); + bool HasSelection() const; + void ClearSelection(); + int GetCursorPos() const; + int GetSelectionStart() const; + int GetSelectionEnd() const; + void SelectAll(); // Reload user buf (WIP #2890) // If you modify underlying user-passed const char* while active you need to call this (InputText V2 may lift this) // strcpy(my_buf, "hello"); // if (ImGuiInputTextState* state = ImGui::GetInputTextState(id)) // id may be ImGui::GetItemID() is last item // state->ReloadUserBufAndSelectAll(); - void ReloadUserBufAndSelectAll() { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; } - void ReloadUserBufAndKeepSelection() { ReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; } - void ReloadUserBufAndMoveToEnd() { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; } - + void ReloadUserBufAndSelectAll(); + void ReloadUserBufAndKeepSelection(); + void ReloadUserBufAndMoveToEnd(); }; enum ImGuiWindowRefreshFlags_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f35927727..877dbd108 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4048,6 +4048,19 @@ void ImGuiInputTextState::OnKeyPressed(int key) CursorAnimReset(); } +// Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header. +void ImGuiInputTextState::CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking +void ImGuiInputTextState::CursorClamp() { Stb->cursor = ImMin(Stb->cursor, CurLenW); Stb->select_start = ImMin(Stb->select_start, CurLenW); Stb->select_end = ImMin(Stb->select_end, CurLenW); } +bool ImGuiInputTextState::HasSelection() const { return Stb->select_start != Stb->select_end; } +void ImGuiInputTextState::ClearSelection() { Stb->select_start = Stb->select_end = Stb->cursor; } +int ImGuiInputTextState::GetCursorPos() const { return Stb->cursor; } +int ImGuiInputTextState::GetSelectionStart() const { return Stb->select_start; } +int ImGuiInputTextState::GetSelectionEnd() const { return Stb->select_end; } +void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = CurLenW; Stb->has_preferred_x = 0; } +void ImGuiInputTextState::ReloadUserBufAndSelectAll() { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; } +void ImGuiInputTextState::ReloadUserBufAndKeepSelection() { ReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; } +void ImGuiInputTextState::ReloadUserBufAndMoveToEnd() { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; } + ImGuiInputTextCallbackData::ImGuiInputTextCallbackData() { memset(this, 0, sizeof(*this)); From 15cb7d61f98de0bcde9fb3ddfdcb25fdccc8b7c7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Sep 2024 16:52:16 +0200 Subject: [PATCH 0342/2359] InputText: moved imstb_textedit.h include to imgui_widgets.cpp --- imgui_internal.h | 31 +++++++++++-------------------- imgui_widgets.cpp | 6 ++++++ imstb_textedit.h | 3 ++- 3 files changed, 19 insertions(+), 21 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 7748f0703..1aa94ff3b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -198,26 +198,6 @@ typedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...); extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #endif -//------------------------------------------------------------------------- -// [SECTION] STB libraries includes -//------------------------------------------------------------------------- - -namespace ImStb -{ - -#undef IMSTB_TEXTEDIT_STRING -#undef IMSTB_TEXTEDIT_CHARTYPE -#define IMSTB_TEXTEDIT_STRING ImGuiInputTextState -#define IMSTB_TEXTEDIT_CHARTYPE ImWchar -#define IMSTB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f) -#define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99 -#define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999 -#include "imstb_textedit.h" - -} // namespace ImStb - -typedef ImStb::STB_TexteditState ImStbTexteditState; - //----------------------------------------------------------------------------- // [SECTION] Macros //----------------------------------------------------------------------------- @@ -1113,6 +1093,17 @@ struct IMGUI_API ImGuiInputTextDeactivatedState void ClearFreeMemory() { ID = 0; TextA.clear(); } }; +// Forward declare imstb_textedit.h structure + make its main configuration define accessible +#undef IMSTB_TEXTEDIT_STRING +#undef IMSTB_TEXTEDIT_CHARTYPE +#define IMSTB_TEXTEDIT_STRING ImGuiInputTextState +#define IMSTB_TEXTEDIT_CHARTYPE ImWchar +#define IMSTB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f) +#define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99 +#define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999 +namespace ImStb { struct STB_TexteditState; } +typedef ImStb::STB_TexteditState ImStbTexteditState; + // Internal state of the currently focused/edited text input box // For a given item ID, access with ImGui::GetInputTextState() struct IMGUI_API ImGuiInputTextState diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 877dbd108..10cdf3428 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3786,6 +3786,7 @@ bool ImGui::InputDouble(const char* label, double* v, double step, double step_f //------------------------------------------------------------------------- // [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint //------------------------------------------------------------------------- +// - imstb_textedit.h include // - InputText() // - InputTextWithHint() // - InputTextMultiline() @@ -3796,6 +3797,11 @@ bool ImGui::InputDouble(const char* label, double* v, double step, double step_f // - DebugNodeInputTextState() [Internal] //------------------------------------------------------------------------- +namespace ImStb +{ +#include "imstb_textedit.h" +} + bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() diff --git a/imstb_textedit.h b/imstb_textedit.h index 783054ab9..faaf518f4 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -3,6 +3,7 @@ // Those changes would need to be pushed into nothings/stb: // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) // - 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. // Grep for [DEAR IMGUI] to find the changes. // - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* @@ -318,7 +319,7 @@ typedef struct int undo_char_point, redo_char_point; } StbUndoState; -typedef struct +typedef struct STB_TexteditState { ///////////////////// // From 4236bc088fd360a02064652069ed9bf04f013507 Mon Sep 17 00:00:00 2001 From: scribam Date: Sun, 8 Sep 2024 12:19:51 +0200 Subject: [PATCH 0343/2359] Backends: SDL2: use SDL_Vulkan_GetDrawableSize with Vulkan instead of SDL_GL_GetDrawableSize. (#7967, #3190) --- backends/imgui_impl_sdl2.cpp | 8 ++++++++ docs/CHANGELOG.txt | 1 + 2 files changed, 9 insertions(+) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index b1cc8c9e6..027dff9f2 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn @@ -112,6 +113,9 @@ #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 #endif #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) +#if SDL_HAS_VULKAN +extern "C" { extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window* window, int* w, int* h); } +#endif // SDL Data struct ImGui_ImplSDL2_Data @@ -760,6 +764,10 @@ void ImGui_ImplSDL2_NewFrame() w = h = 0; if (bd->Renderer != nullptr) SDL_GetRendererOutputSize(bd->Renderer, &display_w, &display_h); +#if SDL_HAS_VULKAN + else if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_VULKAN) + SDL_Vulkan_GetDrawableSize(bd->Window, &display_w, &display_h); +#endif else SDL_GL_GetDrawableSize(bd->Window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 70b7424e9..d915d9510 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,7 @@ Other changes: - Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439) - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow. - TextLinkOpenURL(): modified tooltip to display a verb "Open 'xxxx'". (#7885, #7660) +- Backends: SDL2: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) [@scribam] ----------------------------------------------------------------------- VERSION 1.91.1 (Released 2024-09-04) From a8eec244056b8880f459d2073333fca4da5a917a Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Mon, 9 Sep 2024 21:07:10 +0200 Subject: [PATCH 0344/2359] Demo: fix some id conflicts. (#7961) --- imgui_demo.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index aabb220d6..652049513 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -547,7 +547,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Checkbox("io.ConfigDebugIsDebuggerPresent", &io.ConfigDebugIsDebuggerPresent); ImGui::SameLine(); HelpMarker("Enable various tools calling IM_DEBUG_BREAK().\n\nRequires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application."); ImGui::BeginDisabled(); - ImGui::Checkbox("io.ConfigDebugBeginReturnValueOnce", &io.ConfigDebugBeginReturnValueOnce); // . + ImGui::Checkbox("io.ConfigDebugBeginReturnValueOnce", &io.ConfigDebugBeginReturnValueOnce); ImGui::EndDisabled(); ImGui::SameLine(); HelpMarker("First calls to Begin()/BeginChild() will return false.\n\nTHIS OPTION IS DISABLED because it needs to be set at application boot-time to make sense. Showing the disabled option is a way to make this feature easier to discover."); ImGui::Checkbox("io.ConfigDebugBeginReturnValueLoop", &io.ConfigDebugBeginReturnValueLoop); @@ -2000,8 +2000,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::SameLine(); ImGui::SliderInt("Sample count", &display_count, 1, 400); float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; - ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); - ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); ImGui::Separator(); ImGui::Text("Need better plotting and graphing? Consider using ImPlot:"); @@ -2596,6 +2596,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)"); if (ImGui::TreeNode("Drag to reorder items (simple)")) { + // FIXME: temporary ID Conflict during reordering as a same item may be submitting twice. + // Simple reordering HelpMarker( "We don't use the drag and drop api at all here! " @@ -4225,7 +4227,7 @@ static void ShowDemoWindowLayout() // down by FramePadding.y ahead of time) ImGui::AlignTextToFramePadding(); ImGui::Text("OK Blahblah"); ImGui::SameLine(); - ImGui::Button("Some framed item"); ImGui::SameLine(); + ImGui::Button("Some framed item##2"); ImGui::SameLine(); HelpMarker("We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y"); // SmallButton() uses the same vertical padding as Text @@ -7148,12 +7150,14 @@ static void ShowDemoWindowColumns() { if (h_borders && ImGui::GetColumnIndex() == 0) ImGui::Separator(); + ImGui::PushID(i); ImGui::Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i); ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x); ImGui::Text("Offset %.2f", ImGui::GetColumnOffset()); ImGui::Text("Long text that is likely to clip"); ImGui::Button("Button", ImVec2(-FLT_MIN, 0.0f)); + ImGui::PopID(); ImGui::NextColumn(); } ImGui::Columns(1); From 67cd4ead6505b3386d4ef9c713c98546e86e26ca Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Sep 2024 15:28:40 +0200 Subject: [PATCH 0345/2359] Added io.ConfigDebugHighlightIdConflicts debug feature! (#7961, #7669) Also #74, #96, #480, #501, #647, #654, #719, #843, #894, #1057, #1173, #1390, #1414, #1556, #1768, #2041, #2116, #2330, #2475, #2562, #2667, #2807, #2885, #3102, #3375, #3526, #3964, #4008, #4070, #4158, #4172, #4199, #4375, #4395, #4471, #4548, #4612, #4631, #4657, #4796, #5210, #5303, #5360, #5393, #5533, #5692, #5707, #5729, #5773, #5787, #5884, #6046, #6093, #6186, #6223, #6364, #6387, #6567, #6692, #6724, #6939, #6984, #7246, #7270, #7375, #7421, #7434, #7472, #7581, #7724, #7926, #7937 and probably more.. Tagging to increase visibility! --- docs/CHANGELOG.txt | 19 +++++++++++++++++++ docs/FAQ.md | 5 +++-- imgui.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ imgui.h | 11 ++++++++++- imgui_demo.cpp | 18 ++++++++++++++---- imgui_internal.h | 4 ++++ imgui_widgets.cpp | 3 +++ 7 files changed, 95 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d915d9510..35c4c6743 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,25 @@ Breaking changes: Other changes: +- Added io.ConfigDebugHighlightIdConflicts debug feature! (#7961, #7669) + THIS DETECTS THE MOST COMMON USER ERROR BY FIRST-TIME DEAR IMGUI PROGRAMMERS! + - The tool detects when multiple items are sharing the same identifier, due to not + using PushID/PopID in loops, or not using ID stack facilities such as "##" suffixes. + Very frequently it happens when using empty "" labels. + - When hovering an item with a conflicting ID, all visible items with the same ID will + be highlighted and an explanatory tooltip is made visible. + - The feature may be disabled and is exposed in Demo->Tools menu. + - I've been wanting to add this tool for a long time, but was stalled by finding a way to + not make it spammy + make it practically zero cost. After @pthom made various proposals to + solve the same problem (thanks for pushing me!), I decided it was time to finish it. + - Added ImGuiItemFlags_AllowDuplicateId to use with PushItemFlag/PopItemFlag() if for some + reason you intend to have duplicate identifiers. + - (#74, #96, #480, #501, #647, #654, #719, #843, #894, #1057, #1173, #1390, #1414, #1556, #1768, + #2041, #2116, #2330, #2475, #2562, #2667, #2807, #2885, #3102, #3375, #3526, #3964, #4008, + #4070, #4158, #4172, #4199, #4375, #4395, #4471, #4548, #4612, #4631, #4657, #4796, #5210, + #5303, #5360, #5393, #5533, #5692, #5707, #5729, #5773, #5787, #5884, #6046, #6093, #6186, + #6223, #6364, #6387, #6567, #6692, #6724, #6939, #6984, #7246, #7270, #7375, #7421, #7434, + #7472, #7581, #7724, #7926, #7937 and probably more..) - Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439) - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow. - TextLinkOpenURL(): modified tooltip to display a verb "Open 'xxxx'". (#7885, #7660) diff --git a/docs/FAQ.md b/docs/FAQ.md index d53a5a099..4e2a42576 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -204,10 +204,11 @@ ctx->RSSetScissorRects(1, &r); ### Q: How can I have multiple widgets with the same label? ### Q: How can I have multiple windows with the same label? -**USING THE SAME LABEL+ID IS THE MOST COMMON USER MISTAKE:** +**USING THE SAME LABEL+ID IS THE MOST COMMON USER MISTAKE!** +
**USING AN EMPTY LABEL IS THE SAME AS USING THE SAME LABEL AS YOUR PARENT WIDGET!** - + - +
 ImGui::Begin("Incorrect!");
diff --git a/imgui.cpp b/imgui.cpp
index 1d9d8b899..e6cf5ca45 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1395,6 +1395,8 @@ ImGuiIO::ImGuiIO()
     ConfigWindowsResizeFromEdges = true;
     ConfigWindowsMoveFromTitleBarOnly = false;
     ConfigMemoryCompactTimer = 60.0f;
+    ConfigDebugIsDebuggerPresent = false;
+    ConfigDebugHighlightIdConflicts = true;
     ConfigDebugBeginReturnValueOnce = false;
     ConfigDebugBeginReturnValueLoop = false;
 
@@ -4290,6 +4292,17 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag
 {
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = g.CurrentWindow;
+
+    // Detect ID conflicts
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
+    if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0)
+    {
+        g.HoveredIdPreviousFrameItemCount++;
+        if (g.DebugDrawIdConflicts == id)
+            window->DrawList->AddRect(bb.Min - ImVec2(1,1), bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f);
+    }
+#endif
+
     if (g.HoveredWindow != window)
         return false;
     if (!IsMouseHoveringRect(bb.Min, bb.Max))
@@ -4833,6 +4846,11 @@ void ImGui::NewFrame()
     if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
         KeepAliveID(g.DragDropPayload.SourceId);
 
+    // [DEBUG]
+    g.DebugDrawIdConflicts = 0;
+    if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
+        g.DebugDrawIdConflicts = g.HoveredIdPreviousFrame;
+
     // Update HoveredId data
     if (!g.HoveredIdPreviousFrame)
         g.HoveredIdTimer = 0.0f;
@@ -4843,6 +4861,7 @@ void ImGui::NewFrame()
     if (g.HoveredId && g.ActiveId != g.HoveredId)
         g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
     g.HoveredIdPreviousFrame = g.HoveredId;
+    g.HoveredIdPreviousFrameItemCount = 0;
     g.HoveredId = 0;
     g.HoveredIdAllowOverlap = false;
     g.HoveredIdIsDisabled = false;
@@ -5235,6 +5254,29 @@ void ImGui::EndFrame()
         return;
     IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
 
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
+    if (g.DebugDrawIdConflicts != 0)
+    {
+        PushStyleColor(ImGuiCol_PopupBg, ImLerp(g.Style.Colors[ImGuiCol_PopupBg], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.10f));
+        if (g.DebugItemPickerActive == false && BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
+        {
+            SeparatorText("MESSAGE FROM DEAR IMGUI");
+            Text("Programmer error: %d visible items with conflicting ID!", g.HoveredIdPreviousFrameItemCount);
+            BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
+            BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
+            BulletText("Press F1 to open \"FAQ -> About the ID Stack System\" and read details.");
+            BulletText("Press CTRL+P to activate Item Picker and debug-break in item call-stack.");
+            BulletText("Set io.ConfigDebugDetectIdConflicts=false to disable this warning in non-programmers builds.");
+            EndTooltip();
+        }
+        PopStyleColor();
+        if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_P, ImGuiInputFlags_RouteGlobal))
+            DebugStartItemPicker();
+        if (Shortcut(ImGuiKey_F1, ImGuiInputFlags_RouteGlobal) && g.PlatformIO.Platform_OpenInShellFn != NULL)
+            g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
+    }
+#endif
+
     CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
 
     ErrorCheckEndFrameSanityChecks();
diff --git a/imgui.h b/imgui.h
index 18efaff42..ebb156d4b 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.2 WIP"
-#define IMGUI_VERSION_NUM   19112
+#define IMGUI_VERSION_NUM   19113
 #define IMGUI_HAS_TABLE
 
 /*
@@ -1135,6 +1135,7 @@ enum ImGuiItemFlags_
     ImGuiItemFlags_NoNavDefaultFocus        = 1 << 2,   // false    // Disable item being a candidate for default focus (e.g. used by title bar items).
     ImGuiItemFlags_ButtonRepeat             = 1 << 3,   // false    // Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held.
     ImGuiItemFlags_AutoClosePopups          = 1 << 4,   // true     // MenuItem()/Selectable() automatically close their parent popup window.
+    ImGuiItemFlags_AllowDuplicateId         = 1 << 5,   // false    // Allow submitting an item with the same identifier as an item already submitted this frame without triggering a warning tooltip if io.ConfigDebugHighlightIdConflicts is set.
 };
 
 // Flags for ImGui::InputText()
@@ -2231,6 +2232,7 @@ struct ImGuiIO
     const char* LogFilename;                    // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified).
     void*       UserData;                       // = NULL           // Store your own data.
 
+    // Font system
     ImFontAtlas*Fonts;                          //            // Font atlas: load, rasterize and pack one or more fonts into a single texture.
     float       FontGlobalScale;                // = 1.0f           // Global scale all fonts
     bool        FontAllowUserScaling;           // = false          // Allow user scaling text of individual window with CTRL+Wheel.
@@ -2238,6 +2240,7 @@ struct ImGuiIO
     ImVec2      DisplayFramebufferScale;        // = (1, 1)         // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale.
 
     // Miscellaneous options
+    // (you can visualize and interact with all options in 'Demo->Configuration')
     bool        MouseDrawCursor;                // = false          // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
     bool        ConfigMacOSXBehaviors;          // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
     bool        ConfigNavSwapGamepadButtons;    // = false          // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
@@ -2267,6 +2270,12 @@ struct ImGuiIO
     //   e.g. io.ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent() on Win32, or refer to ImOsIsDebuggerPresent() imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version).
     bool        ConfigDebugIsDebuggerPresent;   // = false          // Enable various tools calling IM_DEBUG_BREAK().
 
+    // Tools to detect code submitting items with conflicting/duplicate IDs
+    // - Code should use PushID()/PopID() in loops, or append "##xx" to same-label identifiers.
+    // - Empty label e.g. Button("") == same ID as parent widget/node. Use Button("##xx") instead!
+    // - See FAQ https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-about-the-id-stack-system
+    bool        ConfigDebugHighlightIdConflicts;// = true           // Highlight and show an error message when multiple items have conflicting identifiers.
+
     // Tools to test correct Begin/End and BeginChild/EndChild behaviors.
     // - Presently Begin()/End() and BeginChild()/EndChild() needs to ALWAYS be called in tandem, regardless of return value of BeginXXX()
     // - This is inconsistent with other BeginXXX functions and create confusion for many users.
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 652049513..8c9745dfb 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -546,6 +546,8 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::SeparatorText("Debug");
             ImGui::Checkbox("io.ConfigDebugIsDebuggerPresent", &io.ConfigDebugIsDebuggerPresent);
             ImGui::SameLine(); HelpMarker("Enable various tools calling IM_DEBUG_BREAK().\n\nRequires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application.");
+            ImGui::Checkbox("io.ConfigDebugHighlightIdConflicts", &io.ConfigDebugHighlightIdConflicts);
+            ImGui::SameLine(); HelpMarker("Highlight and show an error message when multiple items have conflicting identifiers.");
             ImGui::BeginDisabled();
             ImGui::Checkbox("io.ConfigDebugBeginReturnValueOnce", &io.ConfigDebugBeginReturnValueOnce);
             ImGui::EndDisabled();
@@ -684,6 +686,7 @@ static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data)
         if (ImGui::BeginMenu("Tools"))
         {
             IMGUI_DEMO_MARKER("Menu/Tools");
+            ImGuiIO& io = ImGui::GetIO();
 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
             const bool has_debug_tools = true;
 #else
@@ -692,14 +695,16 @@ static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data)
             ImGui::MenuItem("Metrics/Debugger", NULL, &demo_data->ShowMetrics, has_debug_tools);
             ImGui::MenuItem("Debug Log", NULL, &demo_data->ShowDebugLog, has_debug_tools);
             ImGui::MenuItem("ID Stack Tool", NULL, &demo_data->ShowIDStackTool, has_debug_tools);
-            ImGui::MenuItem("Style Editor", NULL, &demo_data->ShowStyleEditor);
-            bool is_debugger_present = ImGui::GetIO().ConfigDebugIsDebuggerPresent;
+            bool is_debugger_present = io.ConfigDebugIsDebuggerPresent;
             if (ImGui::MenuItem("Item Picker", NULL, false, has_debug_tools && is_debugger_present))
                 ImGui::DebugStartItemPicker();
             if (!is_debugger_present)
                 ImGui::SetItemTooltip("Requires io.ConfigDebugIsDebuggerPresent=true to be set.\n\nWe otherwise disable the menu option to avoid casual users crashing the application.\n\nYou can however always access the Item Picker in Metrics->Tools.");
-            ImGui::Separator();
+            ImGui::MenuItem("Style Editor", NULL, &demo_data->ShowStyleEditor);
             ImGui::MenuItem("About Dear ImGui", NULL, &demo_data->ShowAbout);
+
+            ImGui::SeparatorText("Debug Options");
+            ImGui::MenuItem("Highlight ID Conflicts", NULL, &io.ConfigDebugHighlightIdConflicts, has_debug_tools);
             ImGui::EndMenu();
         }
         ImGui::EndMenuBar();
@@ -2596,7 +2601,10 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data)
         IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)");
         if (ImGui::TreeNode("Drag to reorder items (simple)"))
         {
-            // FIXME: temporary ID Conflict during reordering as a same item may be submitting twice.
+            // FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice.
+            // This code was always slightly faulty but in a way which was not easily noticeable.
+            // Until we fix this, enable ImGuiItemFlags_AllowDuplicateId to disable detecting the issue.
+            ImGui::PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true);
 
             // Simple reordering
             HelpMarker(
@@ -2619,6 +2627,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data)
                     }
                 }
             }
+
+            ImGui::PopItemFlag();
             ImGui::TreePop();
         }
 
diff --git a/imgui_internal.h b/imgui_internal.h
index 1aa94ff3b..04dfba3b3 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2042,9 +2042,11 @@ struct ImGuiContext
     ImVec2                  WheelingAxisAvg;
 
     // Item/widgets state and tracking information
+    ImGuiID                 DebugDrawIdConflicts;               // Set when we detect multiple items with the same identifier
     ImGuiID                 DebugHookIdInfo;                    // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line]
     ImGuiID                 HoveredId;                          // Hovered widget, filled during the frame
     ImGuiID                 HoveredIdPreviousFrame;
+    int                     HoveredIdPreviousFrameItemCount;    // Count numbers of items using the same ID as last frame's hovered id
     float                   HoveredIdTimer;                     // Measure contiguous hovering time
     float                   HoveredIdNotActiveTimer;            // Measure contiguous hovering time where the item has not been active
     bool                    HoveredIdAllowOverlap;
@@ -2365,8 +2367,10 @@ struct ImGuiContext
         WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
         WheelingWindowReleaseTimer = 0.0f;
 
+        DebugDrawIdConflicts = 0;
         DebugHookIdInfo = 0;
         HoveredId = HoveredIdPreviousFrame = 0;
+        HoveredIdPreviousFrameItemCount = 0;
         HoveredIdAllowOverlap = false;
         HoveredIdIsDisabled = false;
         HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 10cdf3428..33af0686e 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3551,6 +3551,8 @@ 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)
 // FIXME: Facilitate using this in variety of other situations.
+// FIXME: Among other things, setting ImGuiItemFlags_AllowDuplicateId in LastItemData is currently correct but
+// the expected relationship between TempInputXXX functions and LastItemData is a little fishy.
 bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags)
 {
     // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id.
@@ -3561,6 +3563,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char*
         ClearActiveID();
 
     g.CurrentWindow->DC.CursorPos = bb.Min;
+    g.LastItemData.InFlags |= ImGuiItemFlags_AllowDuplicateId;
     bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags | ImGuiInputTextFlags_MergedItem);
     if (init)
     {

From abd07f6d30736c00fba899d41043a78a5de0f765 Mon Sep 17 00:00:00 2001
From: alektron 
Date: Tue, 27 Aug 2024 01:37:50 +0200
Subject: [PATCH 0346/2359] InputText: added native support for UTF-8 text
 editing and god rid of the wchar buffer. (#7925)

WIP (requires subsequent commits for fixes)
---
 imgui.cpp         |   2 +-
 imgui_internal.h  |  11 +-
 imgui_widgets.cpp | 278 +++++++++++++++++++++++++---------------------
 imstb_textedit.h  |  54 +++++----
 4 files changed, 189 insertions(+), 156 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index e6cf5ca45..71b1b1011 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1975,7 +1975,7 @@ const char* ImStreolRange(const char* str, const char* str_end)
     return p ? p : str_end;
 }
 
-const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
+const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line
 {
     while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
         buf_mid_line--;
diff --git a/imgui_internal.h b/imgui_internal.h
index 04dfba3b3..ec4c069eb 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -366,7 +366,7 @@ IMGUI_API const char*   ImStristr(const char* haystack, const char* haystack_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 ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin);   // Find beginning-of-line (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
 static inline char      ImToUpper(char c)               { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; }
 static inline bool      ImCharIsBlankA(char c)          { return c == ' ' || c == '\t'; }
@@ -1097,7 +1097,7 @@ struct IMGUI_API ImGuiInputTextDeactivatedState
 #undef IMSTB_TEXTEDIT_STRING
 #undef IMSTB_TEXTEDIT_CHARTYPE
 #define IMSTB_TEXTEDIT_STRING             ImGuiInputTextState
-#define IMSTB_TEXTEDIT_CHARTYPE           ImWchar
+#define IMSTB_TEXTEDIT_CHARTYPE           char
 #define IMSTB_TEXTEDIT_GETWIDTH_NEWLINE   (-1.0f)
 #define IMSTB_TEXTEDIT_UNDOSTATECOUNT     99
 #define IMSTB_TEXTEDIT_UNDOCHARCOUNT      999
@@ -1111,8 +1111,7 @@ struct IMGUI_API ImGuiInputTextState
     ImGuiContext*           Ctx;                    // parent UI context (needs to be set explicitly by parent).
     ImStbTexteditState*     Stb;                    // State for stb_textedit.h
     ImGuiID                 ID;                     // widget id owning the text state
-    int                     CurLenW, CurLenA;       // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 length is valid even if TextA is not.
-    ImVector       TextW;                  // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer.
+    int                     CurLenA;                // UTF-8 length of the string in TextA (in bytes)
     ImVector          TextA;                  // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity.
     ImVector          InitialTextA;           // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
     bool                    TextAIsValid;           // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument)
@@ -1129,8 +1128,8 @@ struct IMGUI_API ImGuiInputTextState
 
     ImGuiInputTextState();
     ~ImGuiInputTextState();
-    void        ClearText()                 { CurLenW = CurLenA = 0; TextW[0] = 0; TextA[0] = 0; CursorClamp(); }
-    void        ClearFreeMemory()           { TextW.clear(); TextA.clear(); InitialTextA.clear(); }
+    void        ClearText()                 { CurLenA = 0; TextA[0] = 0; CursorClamp(); }
+    void        ClearFreeMemory()           { TextA.clear(); InitialTextA.clear(); }
     void        OnKeyPressed(int key);      // Cannot be inline because we call in code in stb_textedit.h implementation
 
     // Cursor & Selection
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 33af0686e..5a8721c78 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -128,7 +128,7 @@ static const ImU64          IM_U64_MAX = (2ULL * 9223372036854775807LL + 1);
 // For InputTextEx()
 static bool     InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false);
 static int      InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
-static ImVec2   InputTextCalcTextSizeW(ImGuiContext* ctx, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
+static ImVec2   InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
 
 //-------------------------------------------------------------------------
 // [SECTION] Widgets: Text, etc.
@@ -3836,7 +3836,7 @@ static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char**
     return line_count;
 }
 
-static ImVec2 InputTextCalcTextSizeW(ImGuiContext* ctx, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
+static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining, ImVec2* out_offset, bool stop_on_new_line)
 {
     ImGuiContext& g = *ctx;
     ImFont* font = g.Font;
@@ -3846,10 +3846,11 @@ static ImVec2 InputTextCalcTextSizeW(ImGuiContext* ctx, const ImWchar* text_begi
     ImVec2 text_size = ImVec2(0, 0);
     float line_width = 0.0f;
 
-    const ImWchar* s = text_begin;
+    const char* s = text_begin;
     while (s < text_end)
     {
-        unsigned int c = (unsigned int)(*s++);
+        unsigned int c;
+        s += ImTextCharFromUtf8(&c, s, text_end);
         if (c == '\n')
         {
             text_size.x = ImMax(text_size.x, line_width);
@@ -3885,22 +3886,21 @@ static ImVec2 InputTextCalcTextSizeW(ImGuiContext* ctx, const ImWchar* text_begi
 namespace ImStb
 {
 
-static int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->CurLenW; }
-static ImWchar STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->CurLenW); return obj->TextW[idx]; }
-static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance(c) * g.FontScale; }
+static int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->CurLenA; }
+static char    STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->CurLenA); return obj->TextA[idx]; }
+static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->TextA.Size); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
 static int     STB_TEXTEDIT_KEYTOTEXT(int key)                                                    { return key >= 0x200000 ? 0 : key; }
-static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
+static char    STB_TEXTEDIT_NEWLINE = '\n';
 static void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
 {
-    const ImWchar* text = obj->TextW.Data;
-    const ImWchar* text_remaining = NULL;
-    const ImVec2 size = InputTextCalcTextSizeW(obj->Ctx, text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
+    const char* text_remaining = NULL;
+    const ImVec2 size = InputTextCalcTextSize(obj->Ctx, obj->TextA.Data + line_start_idx, obj->TextA.Data + obj->CurLenA, &text_remaining, NULL, true);
     r->x0 = 0.0f;
     r->x1 = size.x;
     r->baseline_y_delta = size.y;
     r->ymin = 0.0f;
     r->ymax = size.y;
-    r->num_chars = (int)(text_remaining - (text + line_start_idx));
+    r->num_chars = (int)(text_remaining - (obj->TextA.Data + line_start_idx));
 }
 
 static bool ImCharIsSeparatorW(unsigned int c)
@@ -3923,10 +3923,14 @@ static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
     if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
         return 0;
 
-    bool prev_white = ImCharIsBlankW(obj->TextW[idx - 1]);
-    bool prev_separ = ImCharIsSeparatorW(obj->TextW[idx - 1]);
-    bool curr_white = ImCharIsBlankW(obj->TextW[idx]);
-    bool curr_separ = ImCharIsSeparatorW(obj->TextW[idx]);
+    const char* prevPtr = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, obj->TextA.Data + idx);
+    unsigned int curr; ImTextCharFromUtf8(&curr, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
+    unsigned int prev; ImTextCharFromUtf8(&prev, prevPtr, obj->TextA.Data + obj->TextA.Size);
+
+    bool prev_white = ImCharIsBlankW(prev);
+    bool prev_separ = ImCharIsSeparatorW(prev);
+    bool curr_white = ImCharIsBlankW(curr);
+    bool curr_separ = ImCharIsSeparatorW(curr);
     return ((prev_white || prev_separ) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
 }
 static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
@@ -3934,63 +3938,108 @@ static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
     if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
         return 0;
 
-    bool prev_white = ImCharIsBlankW(obj->TextW[idx]);
-    bool prev_separ = ImCharIsSeparatorW(obj->TextW[idx]);
-    bool curr_white = ImCharIsBlankW(obj->TextW[idx - 1]);
-    bool curr_separ = ImCharIsSeparatorW(obj->TextW[idx - 1]);
+    const char* prevPtr = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, obj->TextA.Data + idx);
+    unsigned int prev; ImTextCharFromUtf8(&prev, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
+    unsigned int curr; ImTextCharFromUtf8(&curr, prevPtr, obj->TextA.Data + obj->TextA.Size);
+
+    bool prev_white = ImCharIsBlankW(prev);
+    bool prev_separ = ImCharIsSeparatorW(prev);
+    bool curr_white = ImCharIsBlankW(curr);
+    bool curr_separ = ImCharIsSeparatorW(curr);
     return ((prev_white) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
 }
 static int  STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)   { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
-static int  STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
-static int  STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
+static int  STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenA; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
+static int  STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenA; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
 static int  STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx)  { ImGuiContext& g = *obj->Ctx; if (g.IO.ConfigMacOSXBehaviors) return STB_TEXTEDIT_MOVEWORDRIGHT_MAC(obj, idx); else return STB_TEXTEDIT_MOVEWORDRIGHT_WIN(obj, idx); }
 #define STB_TEXTEDIT_MOVEWORDLEFT   STB_TEXTEDIT_MOVEWORDLEFT_IMPL  // They need to be #define for stb_textedit.h
 #define STB_TEXTEDIT_MOVEWORDRIGHT  STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
+#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX  IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL
+#define IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX  IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX_IMPL
+
+static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
+{
+    unsigned int c;
+    return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
+}
+
+static int CountLeadingHighBits(unsigned char b)
+{
+    for (int i = 0; i < (int)sizeof(b) * 8; i++)
+    {
+        bool set = (b >> (7 - i)) & 1;
+        if (!set)
+            return i;
+    }
+
+    return sizeof(b) * 8;
+}
+
+static int IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
+{
+    //Backwards check/count for UTF-8 multi byte sequence
+    int num_seq_bytes = 0;
+    for (int i = idx - 1; i >= 0; i -= 1)
+    {
+        bool is_seq_byte = (obj->TextA.Data[i] & 0x80) == 0x80 && (obj->TextA.Data[i] & 0x40) == 0;
+        num_seq_bytes += is_seq_byte;
+        if (!is_seq_byte)
+        {
+            if (num_seq_bytes > 0)
+            {
+                char initial_byte = obj->TextA.Data[i];
+                char num_leading_bits = (char)CountLeadingHighBits(initial_byte);
+                bool is_multi_byte_seq = num_leading_bits == num_seq_bytes + 1;
+                if (is_multi_byte_seq)
+                {
+                    return idx - (num_seq_bytes + 1);
+                }
+            }
+            break;
+        }
+    }
+    return idx - 1;
+}
 
 static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
 {
-    ImWchar* dst = obj->TextW.Data + pos;
+    char* dst = obj->TextA.Data + pos;
 
-    // We maintain our buffer length in both UTF-8 and wchar formats
     obj->Edited = true;
-    obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
-    obj->CurLenW -= n;
+    obj->CurLenA -= n;
 
     // Offset remaining text (FIXME-OPT: Use memmove)
-    const ImWchar* src = obj->TextW.Data + pos + n;
-    while (ImWchar c = *src++)
+    const char* src = obj->TextA.Data + pos + n;
+    while (char c = *src++)
         *dst++ = c;
     *dst = '\0';
 }
 
-static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ImWchar* new_text, int new_text_len)
+static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len)
 {
     const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0;
-    const int text_len = obj->CurLenW;
+    const int text_len = obj->CurLenA;
     IM_ASSERT(pos <= text_len);
 
-    const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
-    if (!is_resizable && (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufCapacityA))
+    if (!is_resizable && (new_text_len + obj->CurLenA + 1 > obj->BufCapacityA))
         return false;
 
     // Grow internal buffer if needed
-    if (new_text_len + text_len + 1 > obj->TextW.Size)
+    if (new_text_len + text_len + 1 > obj->TextA.Size)
     {
         if (!is_resizable)
             return false;
-        IM_ASSERT(text_len < obj->TextW.Size);
-        obj->TextW.resize(text_len + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1);
+        obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1);
     }
 
-    ImWchar* text = obj->TextW.Data;
+    char* text = obj->TextA.Data;
     if (pos != text_len)
-        memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
-    memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
+        memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos));
+    memcpy(text + pos, new_text, (size_t)new_text_len);
 
     obj->Edited = true;
-    obj->CurLenW += new_text_len;
-    obj->CurLenA += new_text_len_utf8;
-    obj->TextW[obj->CurLenW] = '\0';
+    obj->CurLenA += new_text_len;
+    obj->TextA[obj->CurLenA] = '\0';
 
     return true;
 }
@@ -4022,8 +4071,8 @@ static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const Im
 // the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?)
 static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len)
 {
-    stb_text_makeundo_replace(str, state, 0, str->CurLenW, text_len);
-    ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->CurLenW);
+    stb_text_makeundo_replace(str, state, 0, str->CurLenA, text_len);
+    ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->CurLenA);
     state->cursor = state->select_start = state->select_end = 0;
     if (text_len <= 0)
         return;
@@ -4052,20 +4101,25 @@ ImGuiInputTextState::~ImGuiInputTextState()
 
 void ImGuiInputTextState::OnKeyPressed(int key)
 {
-    stb_textedit_key(this, Stb, key);
+    //We prematurely convert the key to a UTF8 byte sequence, even for keys where that doesn't even make sense (e.g. arrow keys).
+    //Not optimal but stb_textedit_key will only use the UTF8 values for valid character keys anyways.
+    //The changes we had to make to stb_textedit_key make it very much UTF8 specific which is not too great.
+    char utf8[5];
+    ImTextCharToUtf8(utf8, key);
+    stb_textedit_key(this, Stb, key, utf8, (int)strlen(utf8));
     CursorFollow = true;
     CursorAnimReset();
 }
 
 // Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header.
 void ImGuiInputTextState::CursorAnimReset()                 { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
-void ImGuiInputTextState::CursorClamp()                     { Stb->cursor = ImMin(Stb->cursor, CurLenW); Stb->select_start = ImMin(Stb->select_start, CurLenW); Stb->select_end = ImMin(Stb->select_end, CurLenW); }
+void ImGuiInputTextState::CursorClamp()                     { Stb->cursor = ImMin(Stb->cursor, CurLenA); Stb->select_start = ImMin(Stb->select_start, CurLenA); Stb->select_end = ImMin(Stb->select_end, CurLenA); }
 bool ImGuiInputTextState::HasSelection() const              { return Stb->select_start != Stb->select_end; }
 void ImGuiInputTextState::ClearSelection()                  { Stb->select_start = Stb->select_end = Stb->cursor; }
 int  ImGuiInputTextState::GetCursorPos() const              { return Stb->cursor; }
 int  ImGuiInputTextState::GetSelectionStart() const         { return Stb->select_start; }
 int  ImGuiInputTextState::GetSelectionEnd() const           { return Stb->select_end; }
-void ImGuiInputTextState::SelectAll()                       { Stb->select_start = 0; Stb->cursor = Stb->select_end = CurLenW; Stb->has_preferred_x = 0; }
+void ImGuiInputTextState::SelectAll()                       { Stb->select_start = 0; Stb->cursor = Stb->select_end = CurLenA; Stb->has_preferred_x = 0; }
 void ImGuiInputTextState::ReloadUserBufAndSelectAll()       { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
 void ImGuiInputTextState::ReloadUserBufAndKeepSelection()   { ReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
 void ImGuiInputTextState::ReloadUserBufAndMoveToEnd()       { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
@@ -4238,26 +4292,21 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im
 // FIXME: Ideally we should transition toward (1) making InsertChars()/DeleteChars() update undo-stack (2) discourage (and keep reconcile) or obsolete (and remove reconcile) accessing buffer directly.
 static void InputTextReconcileUndoStateAfterUserCallback(ImGuiInputTextState* state, const char* new_buf_a, int new_length_a)
 {
-    ImGuiContext& g = *GImGui;
-    const ImWchar* old_buf = state->TextW.Data;
-    const int old_length = state->CurLenW;
-    const int new_length = ImTextCountCharsFromUtf8(new_buf_a, new_buf_a + new_length_a);
-    g.TempBuffer.reserve_discard((new_length + 1) * sizeof(ImWchar));
-    ImWchar* new_buf = (ImWchar*)(void*)g.TempBuffer.Data;
-    ImTextStrFromUtf8(new_buf, new_length + 1, new_buf_a, new_buf_a + new_length_a);
+    const char* old_buf = state->TextA.Data;
+    const int old_length = state->CurLenA;
 
-    const int shorter_length = ImMin(old_length, new_length);
+    const int shorter_length = ImMin(old_length, new_length_a);
     int first_diff;
     for (first_diff = 0; first_diff < shorter_length; first_diff++)
-        if (old_buf[first_diff] != new_buf[first_diff])
+        if (old_buf[first_diff] != new_buf_a[first_diff])
             break;
-    if (first_diff == old_length && first_diff == new_length)
+    if (first_diff == old_length && first_diff == new_length_a)
         return;
 
-    int old_last_diff = old_length - 1;
-    int new_last_diff = new_length - 1;
+    int old_last_diff = old_length   - 1;
+    int new_last_diff = new_length_a - 1;
     for (; old_last_diff >= first_diff && new_last_diff >= first_diff; old_last_diff--, new_last_diff--)
-        if (old_buf[old_last_diff] != new_buf[new_last_diff])
+        if (old_buf[old_last_diff] != new_buf_a[new_last_diff])
             break;
 
     const int insert_len = new_last_diff - first_diff + 1;
@@ -4434,13 +4483,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             recycle_state = false;
 
         // Start edition
-        const char* buf_end = NULL;
         state->ID = id;
-        state->TextW.resize(buf_size + 1);          // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string.
-        state->TextA.resize(0);
-        state->TextAIsValid = false;                // TextA is not valid yet (we will display buf until then)
-        state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end);
-        state->CurLenA = (int)(buf_end - buf);      // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
+        state->TextA.resize(buf_size + 1);          // we use +1 to make sure that .Data is always pointing to at least an empty string.
+        state->TextAIsValid = true;
+        state->CurLenA = (int)strlen(buf);
+        memcpy(state->TextA.Data, buf, state->CurLenA + 1);
 
         if (recycle_state)
         {
@@ -4522,18 +4569,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     bool value_changed = false;
     bool validated = false;
 
-    // When read-only we always use the live data passed to the function
-    // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :(
-    if (is_readonly && state != NULL && (render_cursor || render_selection))
-    {
-        const char* buf_end = NULL;
-        state->TextW.resize(buf_size + 1);
-        state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end);
-        state->CurLenA = (int)(buf_end - buf);
-        state->CursorClamp();
-        render_selection &= state->HasSelection();
-    }
-
     // Select the buffer to render.
     const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid;
     const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
@@ -4786,12 +4821,12 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
             {
                 const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0;
-                const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->CurLenW;
-                const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1;
-                char* clipboard_data = (char*)IM_ALLOC(clipboard_data_len * sizeof(char));
-                ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie);
-                SetClipboardText(clipboard_data);
-                MemFree(clipboard_data);
+                const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->CurLenA;
+
+                char backup = state->TextA.Data[ie];
+                state->TextA.Data[ie] = 0; // A bit of a hack since SetClipboardText only takes null terminated strings
+                SetClipboardText(state->TextA.Data + ib);
+                state->TextA.Data[ie] = backup;
             }
             if (is_cut)
             {
@@ -4807,15 +4842,17 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             {
                 // Filter pasted buffer
                 const int clipboard_len = (int)strlen(clipboard);
-                ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len + 1) * sizeof(ImWchar));
+                char* clipboard_filtered = (char*)IM_ALLOC((clipboard_len + 1));
                 int clipboard_filtered_len = 0;
                 for (const char* s = clipboard; *s != 0; )
                 {
                     unsigned int c;
-                    s += ImTextCharFromUtf8(&c, s, NULL);
+                    int len = ImTextCharFromUtf8(&c, s, NULL);
                     if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true))
                         continue;
-                    clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
+                    memcpy(clipboard_filtered + clipboard_filtered_len, s, len);
+                    clipboard_filtered_len += len;
+                    s += len;
                 }
                 clipboard_filtered[clipboard_filtered_len] = 0;
                 if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
@@ -4851,27 +4888,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             }
             else if (strcmp(buf, state->InitialTextA.Data) != 0)
             {
-                // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
-                // Push records into the undo stack so we can CTRL+Z the revert operation itself
                 apply_new_text = state->InitialTextA.Data;
                 apply_new_text_length = state->InitialTextA.Size - 1;
-                value_changed = true;
-                ImVector w_text;
-                if (apply_new_text_length > 0)
-                {
-                    w_text.resize(ImTextCountCharsFromUtf8(apply_new_text, apply_new_text + apply_new_text_length) + 1);
-                    ImTextStrFromUtf8(w_text.Data, w_text.Size, apply_new_text, apply_new_text + apply_new_text_length);
-                }
-                stb_textedit_replace(state, state->Stb, w_text.Data, (apply_new_text_length > 0) ? (w_text.Size - 1) : 0);
-            }
-        }
 
-        // Apply ASCII value
-        if (!is_readonly)
-        {
-            state->TextAIsValid = true;
-            state->TextA.resize(state->TextW.Size * 4 + 1);
-            ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL);
+                // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
+                // Push records into the undo stack so we can CTRL+Z the revert operation itself
+                value_changed = true;
+                stb_textedit_replace(state, state->Stb, state->InitialTextA.Data, state->InitialTextA.Size - 1);
+            }
         }
 
         // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer
@@ -4935,11 +4959,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     callback_data.BufSize = state->BufCapacityA;
                     callback_data.BufDirty = false;
 
-                    // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)
-                    ImWchar* text = state->TextW.Data;
-                    const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb->cursor);
-                    const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb->select_start);
-                    const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb->select_end);
+                    const int utf8_cursor_pos = callback_data.CursorPos = state->Stb->cursor;
+                    const int utf8_selection_start = callback_data.SelectionStart = state->Stb->select_start;
+                    const int utf8_selection_end = state->Stb->select_end;
 
                     // Call user code
                     callback(&callback_data);
@@ -4950,17 +4972,18 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     IM_ASSERT(callback_data.BufSize == state->BufCapacityA);
                     IM_ASSERT(callback_data.Flags == flags);
                     const bool buf_dirty = callback_data.BufDirty;
-                    if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty)            { state->Stb->cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; }
-                    if (callback_data.SelectionStart != utf8_selection_start || buf_dirty)  { state->Stb->select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb->cursor : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); }
-                    if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty)      { state->Stb->select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb->select_start : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); }
+                    if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty)            { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; }
+                    if (callback_data.SelectionStart != utf8_selection_start || buf_dirty)  { state->Stb->select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb->cursor : callback_data.SelectionStart; }
+                    if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty)      { state->Stb->select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb->select_start : callback_data.SelectionEnd; }
                     if (buf_dirty)
                     {
                         // Callback may update buffer and thus set buf_dirty even in read-only mode.
                         IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
                         InputTextReconcileUndoStateAfterUserCallback(state, callback_data.Buf, callback_data.BufTextLen); // FIXME: Move the rest of this block inside function and rename to InputTextReconcileStateAfterUserCallback() ?
                         if (callback_data.BufTextLen > backup_current_text_length && is_resizable)
-                            state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length)); // Worse case scenario resize
-                        state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL);
+                            state->TextA.resize(state->TextA.Size + (callback_data.BufTextLen - backup_current_text_length)); // Worse case scenario resize
+
+                        memcpy(state->TextA.Data, callback_data.Buf, callback_data.BufTextLen);
                         state->CurLenA = callback_data.BufTextLen;  // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
                         state->CursorAnimReset();
                     }
@@ -5064,12 +5087,12 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         // - Measure text height (for scrollbar)
         // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
         // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
-        const ImWchar* text_begin = state->TextW.Data;
+        const char* text_begin = state->TextA.Data;
         ImVec2 cursor_offset, select_start_offset;
 
         {
             // Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions.
-            const ImWchar* searches_input_ptr[2] = { NULL, NULL };
+            const char* searches_input_ptr[2] = { NULL, NULL };
             int searches_result_line_no[2] = { -1000, -1000 };
             int searches_remaining = 0;
             if (render_cursor)
@@ -5090,7 +5113,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             searches_remaining += is_multiline ? 1 : 0;
             int line_count = 0;
             //for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\n')) != NULL; s++)  // FIXME-OPT: Could use this when wchar_t are 16-bit
-            for (const ImWchar* s = text_begin; *s != 0; s++)
+            for (const char* s = text_begin; *s != 0; s++)
                 if (*s == '\n')
                 {
                     line_count++;
@@ -5104,11 +5127,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                 searches_result_line_no[1] = line_count;
 
             // Calculate 2d position by finding the beginning of the line and measuring distance
-            cursor_offset.x = InputTextCalcTextSizeW(&g, ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
+            cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
             cursor_offset.y = searches_result_line_no[0] * g.FontSize;
             if (searches_result_line_no[1] >= 0)
             {
-                select_start_offset.x = InputTextCalcTextSizeW(&g, ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
+                select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
                 select_start_offset.y = searches_result_line_no[1] * g.FontSize;
             }
 
@@ -5156,14 +5179,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         const ImVec2 draw_scroll = ImVec2(state->Scroll.x, 0.0f);
         if (render_selection)
         {
-            const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end);
-            const ImWchar* text_selected_end = text_begin + ImMax(state->Stb->select_start, state->Stb->select_end);
+            const char* text_selected_begin = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end);
+            const char* text_selected_end = text_begin + ImMax(state->Stb->select_start, state->Stb->select_end);
 
             ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.
             float bg_offy_up = is_multiline ? 0.0f : -1.0f;    // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
             float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
             ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll;
-            for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
+            for (const char* p = text_selected_begin; p < text_selected_end; )
             {
                 if (rect_pos.y > clip_rect.w + g.FontSize)
                     break;
@@ -5177,7 +5200,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                 }
                 else
                 {
-                    ImVec2 rect_size = InputTextCalcTextSizeW(&g, p, text_selected_end, &p, NULL, true);
+                    ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, &p, NULL, true);
                     if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
                     ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn));
                     rect.ClipWith(clip_rect);
@@ -5282,7 +5305,7 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
     ImStb::StbUndoState* undo_state = &stb_state->undostate;
     Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId);
     DebugLocateItemOnHover(state->ID);
-    Text("CurLenW: %d, CurLenA: %d, Cursor: %d, Selection: %d..%d", state->CurLenW, state->CurLenA, stb_state->cursor, stb_state->select_start, stb_state->select_end);
+    Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->CurLenA, stb_state->cursor, stb_state->select_start, stb_state->select_end);
     Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x);
     Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point);
     if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state
@@ -5294,11 +5317,8 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
             const char undo_rec_type = (n < undo_state->undo_point) ? 'u' : (n >= undo_state->redo_point) ? 'r' : ' ';
             if (undo_rec_type == ' ')
                 BeginDisabled();
-            char buf[64] = "";
-            if (undo_rec_type != ' ' && undo_rec->char_storage != -1)
-                ImTextStrToUtf8(buf, IM_ARRAYSIZE(buf), undo_state->undo_char + undo_rec->char_storage, undo_state->undo_char + undo_rec->char_storage + undo_rec->insert_length);
-            Text("%c [%02d] where %03d, insert %03d, delete %03d, char_storage %03d \"%s\"",
-                undo_rec_type, n, undo_rec->where, undo_rec->insert_length, undo_rec->delete_length, undo_rec->char_storage, buf);
+            Text("%c [%02d] where %03d, insert %03d, delete %03d, char_storage %03d \"%.*s\"",
+                undo_rec_type, n, undo_rec->where, undo_rec->insert_length, undo_rec->delete_length, undo_rec->char_storage, undo_rec->insert_length, undo_state->undo_char + undo_rec->char_storage);
             if (undo_rec_type == ' ')
                 EndDisabled();
         }
diff --git a/imstb_textedit.h b/imstb_textedit.h
index faaf518f4..28508607b 100644
--- a/imstb_textedit.h
+++ b/imstb_textedit.h
@@ -4,6 +4,7 @@
 // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321)
 // - 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 UTF8 support https://github.com/nothings/stb/issues/188
 // Grep for [DEAR IMGUI] to find the changes.
 // - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_*
 
@@ -439,13 +440,13 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y)
    if (x < r.x1) {
       // search characters in row for one that straddles 'x'
       prev_x = r.x0;
-      for (k=0; k < r.num_chars; ++k) {
+      for (k=0; k < r.num_chars; k = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k) - i) {
          float w = STB_TEXTEDIT_GETWIDTH(str, i, k);
          if (x < prev_x+w) {
             if (x < prev_x+w/2)
                return k+i;
             else
-               return k+i+1;
+               return IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k);
          }
          prev_x += w;
       }
@@ -564,7 +565,7 @@ static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING
 
    // now scan to find xpos
    find->x = r.x0;
-   for (i=0; first+i < n; ++i)
+   for (i=0; first+i < n; i = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, first + i) - first)
       find->x += STB_TEXTEDIT_GETWIDTH(str, first, i);
 }
 
@@ -641,6 +642,17 @@ static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditSt
    }
 }
 
+//[DEAR IMGUI]
+//Functions must be implemented for UTF8 support
+//Code in this file that uses them, 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_GETPREVIOUSCHARINDEX
+#define IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX(obj, idx) idx - 1
+#endif
+#ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX
+#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx) idx + 1
+#endif
+
 #ifdef STB_TEXTEDIT_IS_SPACE
 static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx )
 {
@@ -722,15 +734,16 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS
 #endif
 
 // API key: process a keyboard input
-static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)
+//[DEAR IMGUI] In addition to the key we also pass in the decoded UTF8 byte sequence, if it is a character key.
+//This is a bit ugly and only makes sense for UTF8. One could think of other solutions that wouldn't make this function so UTF8 specific.
+//If the idea is to push the changes upstream to stb_textedit it might be worth thinking about but since this is just for [DEAR IMGUI], it might not be worth the complication
+static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key, const IMSTB_TEXTEDIT_CHARTYPE* decoded, int decoded_size)
 {
 retry:
    switch (key) {
       default: {
          int c = STB_TEXTEDIT_KEYTOTEXT(key);
          if (c > 0) {
-            IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE) c;
-
             // can't add newline in single-line mode
             if (c == '\n' && state->single_line)
                break;
@@ -738,15 +751,15 @@ retry:
             if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {
                stb_text_makeundo_replace(str, state, state->cursor, 1, 1);
                STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);
-               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {
-                  ++state->cursor;
+               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, decoded, decoded_size)) {
+                  state->cursor += decoded_size;
                   state->has_preferred_x = 0;
                }
             } else {
                stb_textedit_delete_selection(str,state); // implicitly clamps
-               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {
-                  stb_text_makeundo_insert(state, state->cursor, 1);
-                  ++state->cursor;
+               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, decoded, decoded_size)) {
+                  stb_text_makeundo_insert(state, state->cursor, decoded_size);
+                  state->cursor += decoded_size;
                   state->has_preferred_x = 0;
                }
             }
@@ -776,7 +789,7 @@ retry:
             stb_textedit_move_to_first(state);
          else
             if (state->cursor > 0)
-               --state->cursor;
+               state->cursor = IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX(str, state->cursor);
          state->has_preferred_x = 0;
          break;
 
@@ -785,7 +798,7 @@ retry:
          if (STB_TEXT_HAS_SELECTION(state))
             stb_textedit_move_to_last(str, state);
          else
-            ++state->cursor;
+            state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);
          stb_textedit_clamp(str, state);
          state->has_preferred_x = 0;
          break;
@@ -795,7 +808,7 @@ retry:
          stb_textedit_prep_selection_at_cursor(state);
          // move selection left
          if (state->select_end > 0)
-            --state->select_end;
+            state->select_end = IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX(str, state->select_end);
          state->cursor = state->select_end;
          state->has_preferred_x = 0;
          break;
@@ -845,7 +858,7 @@ retry:
       case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT:
          stb_textedit_prep_selection_at_cursor(state);
          // move selection right
-         ++state->select_end;
+         state->select_end = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->select_end);
          stb_textedit_clamp(str, state);
          state->cursor = state->select_end;
          state->has_preferred_x = 0;
@@ -901,7 +914,7 @@ retry:
                x += dx;
                if (x > goal_x)
                   break;
-               ++state->cursor;
+               state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);
             }
             stb_textedit_clamp(str, state);
 
@@ -963,7 +976,7 @@ retry:
                x += dx;
                if (x > goal_x)
                   break;
-               ++state->cursor;
+               state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);
             }
             stb_textedit_clamp(str, state);
 
@@ -991,7 +1004,7 @@ retry:
          else {
             int n = STB_TEXTEDIT_STRINGLEN(str);
             if (state->cursor < n)
-               stb_textedit_delete(str, state, state->cursor, 1);
+               stb_textedit_delete(str, state, state->cursor, IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor) - state->cursor);
          }
          state->has_preferred_x = 0;
          break;
@@ -1003,8 +1016,9 @@ retry:
          else {
             stb_textedit_clamp(str, state);
             if (state->cursor > 0) {
-               stb_textedit_delete(str, state, state->cursor-1, 1);
-               --state->cursor;
+               int prev = IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX(str, state->cursor);
+               stb_textedit_delete(str, state, prev, state->cursor - prev);
+               state->cursor = prev;
             }
          }
          state->has_preferred_x = 0;

From d1b7817959245230e0ef24f8c9886c0e6d0d1396 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 5 Sep 2024 15:25:30 +0200
Subject: [PATCH 0347/2359] InputText: amends: renames, coding style. (#7925)

---
 imgui.h           |  2 +-
 imgui_internal.h  |  1 -
 imgui_widgets.cpp | 17 ++++++++---------
 imstb_textedit.h  | 22 +++++++++++-----------
 4 files changed, 20 insertions(+), 22 deletions(-)

diff --git a/imgui.h b/imgui.h
index ebb156d4b..095c25002 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.2 WIP"
-#define IMGUI_VERSION_NUM   19113
+#define IMGUI_VERSION_NUM   19114
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index ec4c069eb..4dfcfce9a 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1114,7 +1114,6 @@ struct IMGUI_API ImGuiInputTextState
     int                     CurLenA;                // UTF-8 length of the string in TextA (in bytes)
     ImVector          TextA;                  // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity.
     ImVector          InitialTextA;           // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
-    bool                    TextAIsValid;           // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument)
     int                     BufCapacityA;           // end-user buffer capacity
     ImVec2                  Scroll;                 // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y)
     float                   CursorAnim;             // timer for cursor blink, reset on every user action so the cursor reappears immediately
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 5a8721c78..64e701407 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3952,10 +3952,10 @@ static int  STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)
 static int  STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenA; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
 static int  STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenA; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
 static int  STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx)  { ImGuiContext& g = *obj->Ctx; if (g.IO.ConfigMacOSXBehaviors) return STB_TEXTEDIT_MOVEWORDRIGHT_MAC(obj, idx); else return STB_TEXTEDIT_MOVEWORDRIGHT_WIN(obj, idx); }
-#define STB_TEXTEDIT_MOVEWORDLEFT   STB_TEXTEDIT_MOVEWORDLEFT_IMPL  // They need to be #define for stb_textedit.h
-#define STB_TEXTEDIT_MOVEWORDRIGHT  STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
+#define STB_TEXTEDIT_MOVEWORDLEFT       STB_TEXTEDIT_MOVEWORDLEFT_IMPL  // They need to be #define for stb_textedit.h
+#define STB_TEXTEDIT_MOVEWORDRIGHT      STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
 #define IMSTB_TEXTEDIT_GETNEXTCHARINDEX  IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL
-#define IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX  IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX_IMPL
+#define IMSTB_TEXTEDIT_GETPREVCHARINDEX  IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL
 
 static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
 {
@@ -3975,9 +3975,9 @@ static int CountLeadingHighBits(unsigned char b)
     return sizeof(b) * 8;
 }
 
-static int IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
+static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
 {
-    //Backwards check/count for UTF-8 multi byte sequence
+    // Backwards check/count for UTF-8 multi byte sequence
     int num_seq_bytes = 0;
     for (int i = idx - 1; i >= 0; i -= 1)
     {
@@ -4479,13 +4479,12 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         // Preserve cursor position and undo/redo stack if we come back to same widget
         // FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
         bool recycle_state = (state->ID == id && !init_changed_specs && !init_reload_from_user_buf);
-        if (recycle_state && (state->CurLenA != buf_len || (state->TextAIsValid && strncmp(state->TextA.Data, buf, buf_len) != 0)))
+        if (recycle_state && (state->CurLenA != buf_len || (strncmp(state->TextA.Data, buf, buf_len) != 0)))
             recycle_state = false;
 
         // Start edition
         state->ID = id;
         state->TextA.resize(buf_size + 1);          // we use +1 to make sure that .Data is always pointing to at least an empty string.
-        state->TextAIsValid = true;
         state->CurLenA = (int)strlen(buf);
         memcpy(state->TextA.Data, buf, state->CurLenA + 1);
 
@@ -4570,7 +4569,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     bool validated = false;
 
     // Select the buffer to render.
-    const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid;
+    const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state;
     const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
 
     // Password pushes a temporary font with only a fallback glyph
@@ -4842,7 +4841,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             {
                 // Filter pasted buffer
                 const int clipboard_len = (int)strlen(clipboard);
-                char* clipboard_filtered = (char*)IM_ALLOC((clipboard_len + 1));
+                char* clipboard_filtered = (char*)IM_ALLOC(clipboard_len + 1);
                 int clipboard_filtered_len = 0;
                 for (const char* s = clipboard; *s != 0; )
                 {
diff --git a/imstb_textedit.h b/imstb_textedit.h
index 28508607b..22122c08b 100644
--- a/imstb_textedit.h
+++ b/imstb_textedit.h
@@ -4,7 +4,7 @@
 // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321)
 // - 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 UTF8 support https://github.com/nothings/stb/issues/188
+// - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925)
 // Grep for [DEAR IMGUI] to find the changes.
 // - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_*
 
@@ -642,15 +642,15 @@ static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditSt
    }
 }
 
-//[DEAR IMGUI]
-//Functions must be implemented for UTF8 support
-//Code in this file that uses them, 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_GETPREVIOUSCHARINDEX
-#define IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX(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
+#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx) (idx + 1)
 #endif
 
 #ifdef STB_TEXTEDIT_IS_SPACE
@@ -789,7 +789,7 @@ retry:
             stb_textedit_move_to_first(state);
          else
             if (state->cursor > 0)
-               state->cursor = IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX(str, state->cursor);
+               state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor);
          state->has_preferred_x = 0;
          break;
 
@@ -808,7 +808,7 @@ retry:
          stb_textedit_prep_selection_at_cursor(state);
          // move selection left
          if (state->select_end > 0)
-            state->select_end = IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX(str, state->select_end);
+            state->select_end = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->select_end);
          state->cursor = state->select_end;
          state->has_preferred_x = 0;
          break;
@@ -1016,7 +1016,7 @@ retry:
          else {
             stb_textedit_clamp(str, state);
             if (state->cursor > 0) {
-               int prev = IMSTB_TEXTEDIT_GETPREVIOUSCHARINDEX(str, state->cursor);
+               int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor);
                stb_textedit_delete(str, state, prev, state->cursor - prev);
                state->cursor = prev;
             }

From 1674fe96ff57e4540b6c1860e61aa7fcc06642fe Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 5 Sep 2024 16:31:41 +0200
Subject: [PATCH 0348/2359] InputText: amends: add stb_textedit_text() api.
 (#7925)

It seems sensible to push this change in stb_textedit repo eventually.
---
 imgui_internal.h  |  1 +
 imgui_widgets.cpp | 23 +++++++++++-------
 imstb_textedit.h  | 61 ++++++++++++++++++++++++++++-------------------
 3 files changed, 52 insertions(+), 33 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index 4dfcfce9a..e6f3f8ec5 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1130,6 +1130,7 @@ struct IMGUI_API ImGuiInputTextState
     void        ClearText()                 { CurLenA = 0; TextA[0] = 0; CursorClamp(); }
     void        ClearFreeMemory()           { TextA.clear(); InitialTextA.clear(); }
     void        OnKeyPressed(int key);      // Cannot be inline because we call in code in stb_textedit.h implementation
+    void        OnCharPressed(unsigned int c);
 
     // Cursor & Selection
     void        CursorAnimReset();
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 64e701407..f35563119 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3889,7 +3889,6 @@ namespace ImStb
 static int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->CurLenA; }
 static char    STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->CurLenA); return obj->TextA[idx]; }
 static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->TextA.Size); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
-static int     STB_TEXTEDIT_KEYTOTEXT(int key)                                                    { return key >= 0x200000 ? 0 : key; }
 static char    STB_TEXTEDIT_NEWLINE = '\n';
 static void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
 {
@@ -4101,12 +4100,18 @@ ImGuiInputTextState::~ImGuiInputTextState()
 
 void ImGuiInputTextState::OnKeyPressed(int key)
 {
-    //We prematurely convert the key to a UTF8 byte sequence, even for keys where that doesn't even make sense (e.g. arrow keys).
-    //Not optimal but stb_textedit_key will only use the UTF8 values for valid character keys anyways.
-    //The changes we had to make to stb_textedit_key make it very much UTF8 specific which is not too great.
+    stb_textedit_key(this, Stb, key);
+    CursorFollow = true;
+    CursorAnimReset();
+}
+
+void ImGuiInputTextState::OnCharPressed(unsigned int c)
+{
+    // Convert the key to a UTF8 byte sequence.
+    // The changes we had to make to stb_textedit_key made it very much UTF-8 specific which is not too great.
     char utf8[5];
-    ImTextCharToUtf8(utf8, key);
-    stb_textedit_key(this, Stb, key, utf8, (int)strlen(utf8));
+    ImTextCharToUtf8(utf8, c);
+    stb_textedit_text(this, Stb, utf8, (int)strlen(utf8));
     CursorFollow = true;
     CursorAnimReset();
 }
@@ -4674,7 +4679,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             {
                 unsigned int c = '\t'; // Insert TAB
                 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
-                    state->OnKeyPressed((int)c);
+                    state->OnCharPressed(c);
             }
             // FIXME: Implement Shift+Tab
             /*
@@ -4697,7 +4702,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     if (c == '\t') // Skip Tab, see above.
                         continue;
                     if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
-                        state->OnKeyPressed((int)c);
+                        state->OnCharPressed(c);
                 }
 
             // Consume characters
@@ -4781,7 +4786,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             {
                 unsigned int c = '\n'; // Insert new line
                 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
-                    state->OnKeyPressed((int)c);
+                    state->OnCharPressed(c);
             }
         }
         else if (is_cancel)
diff --git a/imstb_textedit.h b/imstb_textedit.h
index 22122c08b..b7a761c85 100644
--- a/imstb_textedit.h
+++ b/imstb_textedit.h
@@ -211,6 +211,7 @@
 //    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_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.
@@ -245,7 +246,12 @@
 //          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
-//          anything other type you wante 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: [DEAR IMGUI] added 2024-09
+//          call this to text inputs sent to the textfield.
 //
 //
 //   When rendering, you can read the cursor position and selection state from
@@ -733,37 +739,44 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS
 #define STB_TEXTEDIT_KEYTYPE int
 #endif
 
+// [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] == '\n' && state->single_line)
+      return;
+
+   if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {
+      stb_text_makeundo_replace(str, state, state->cursor, 1, 1);
+      STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);
+      if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) {
+         state->cursor += text_len;
+         state->has_preferred_x = 0;
+      }
+   }
+   else {
+      stb_textedit_delete_selection(str, state); // implicitly clamps
+      if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) {
+         stb_text_makeundo_insert(state, state->cursor, text_len);
+         state->cursor += text_len;
+         state->has_preferred_x = 0;
+      }
+   }
+}
+
 // API key: process a keyboard input
-//[DEAR IMGUI] In addition to the key we also pass in the decoded UTF8 byte sequence, if it is a character key.
-//This is a bit ugly and only makes sense for UTF8. One could think of other solutions that wouldn't make this function so UTF8 specific.
-//If the idea is to push the changes upstream to stb_textedit it might be worth thinking about but since this is just for [DEAR IMGUI], it might not be worth the complication
-static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key, const IMSTB_TEXTEDIT_CHARTYPE* decoded, int decoded_size)
+static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)
 {
 retry:
    switch (key) {
       default: {
+#ifdef STB_TEXTEDIT_KEYTOTEXT
          int c = STB_TEXTEDIT_KEYTOTEXT(key);
          if (c > 0) {
-            // can't add newline in single-line mode
-            if (c == '\n' && state->single_line)
-               break;
-
-            if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {
-               stb_text_makeundo_replace(str, state, state->cursor, 1, 1);
-               STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);
-               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, decoded, decoded_size)) {
-                  state->cursor += decoded_size;
-                  state->has_preferred_x = 0;
-               }
-            } else {
-               stb_textedit_delete_selection(str,state); // implicitly clamps
-               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, decoded, decoded_size)) {
-                  stb_text_makeundo_insert(state, state->cursor, decoded_size);
-                  state->cursor += decoded_size;
-                  state->has_preferred_x = 0;
-               }
-            }
+            IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c;
+            stb_textedit_text(str, state, &ch, 1);
          }
+#endif
          break;
       }
 

From e240bc151a3650be8af0ea9d426d4fb44914c7e0 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 5 Sep 2024 16:29:30 +0200
Subject: [PATCH 0349/2359] InputText: amends: add note about
 STB_TEXTEDIT_GETCHAR. tweak InputTextCalcTextSize() to use similar
 debug-friendly logic as ImFont:CalcTextSizeA(). misc small tidying up.
 (#7925)

---
 imgui_widgets.cpp | 51 ++++++++++++++++++++++++++++-------------------
 1 file changed, 31 insertions(+), 20 deletions(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index f35563119..6d701d03b 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3836,6 +3836,7 @@ static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char**
     return line_count;
 }
 
+// FIXME: Ideally we'd share code with ImFont::CalcTextSizeA()
 static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining, ImVec2* out_offset, bool stop_on_new_line)
 {
     ImGuiContext& g = *ctx;
@@ -3849,8 +3850,12 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c
     const char* s = text_begin;
     while (s < text_end)
     {
-        unsigned int c;
-        s += ImTextCharFromUtf8(&c, s, text_end);
+        unsigned int c = (unsigned int)*s;
+        if (c < 0x80)
+            s += 1;
+        else
+            s += ImTextCharFromUtf8(&c, s, text_end);
+
         if (c == '\n')
         {
             text_size.x = ImMax(text_size.x, line_width);
@@ -3863,7 +3868,7 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c
         if (c == '\r')
             continue;
 
-        const float char_width = font->GetCharAdvance((ImWchar)c) * scale;
+        const float char_width = ((int)c < font->IndexAdvanceX.Size ? font->IndexAdvanceX.Data[c] : font->FallbackAdvanceX) * scale;
         line_width += char_width;
     }
 
@@ -3883,23 +3888,27 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c
 }
 
 // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
+// With our UTF-8 use of stb_textedit:
+// - STB_TEXTEDIT_GETCHAR is nothing more than a a "GETBYTE". It's only used to compare to ascii or to copy blocks of text so we are fine.
+// - One exception is the STB_TEXTEDIT_IS_SPACE feature which would expect a full char in order to handle full-width space such as 0x3000 (see ImCharIsBlankW).
+// - ...but we don't use that feature.
 namespace ImStb
 {
-
 static int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->CurLenA; }
 static char    STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->CurLenA); return obj->TextA[idx]; }
 static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->TextA.Size); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
 static char    STB_TEXTEDIT_NEWLINE = '\n';
 static void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
 {
+    const char* text = obj->TextA.Data;
     const char* text_remaining = NULL;
-    const ImVec2 size = InputTextCalcTextSize(obj->Ctx, obj->TextA.Data + line_start_idx, obj->TextA.Data + obj->CurLenA, &text_remaining, NULL, true);
+    const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->CurLenA, &text_remaining, NULL, true);
     r->x0 = 0.0f;
     r->x1 = size.x;
     r->baseline_y_delta = size.y;
     r->ymin = 0.0f;
     r->ymax = size.y;
-    r->num_chars = (int)(text_remaining - (obj->TextA.Data + line_start_idx));
+    r->num_chars = (int)(text_remaining - (text + line_start_idx));
 }
 
 static bool ImCharIsSeparatorW(unsigned int c)
@@ -3922,14 +3931,15 @@ static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
     if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
         return 0;
 
-    const char* prevPtr = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, obj->TextA.Data + idx);
-    unsigned int curr; ImTextCharFromUtf8(&curr, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
-    unsigned int prev; ImTextCharFromUtf8(&prev, prevPtr, obj->TextA.Data + obj->TextA.Size);
+    const char* curr_p = obj->TextA.Data + idx;
+    const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
+    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextA.Data + obj->TextA.Size);
+    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextA.Data + obj->TextA.Size);
 
-    bool prev_white = ImCharIsBlankW(prev);
-    bool prev_separ = ImCharIsSeparatorW(prev);
-    bool curr_white = ImCharIsBlankW(curr);
-    bool curr_separ = ImCharIsSeparatorW(curr);
+    bool prev_white = ImCharIsBlankW(prev_c);
+    bool prev_separ = ImCharIsSeparatorW(prev_c);
+    bool curr_white = ImCharIsBlankW(curr_c);
+    bool curr_separ = ImCharIsSeparatorW(curr_c);
     return ((prev_white || prev_separ) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
 }
 static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
@@ -3937,14 +3947,15 @@ static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
     if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
         return 0;
 
-    const char* prevPtr = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, obj->TextA.Data + idx);
-    unsigned int prev; ImTextCharFromUtf8(&prev, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
-    unsigned int curr; ImTextCharFromUtf8(&curr, prevPtr, obj->TextA.Data + obj->TextA.Size);
+    const char* curr_p = obj->TextA.Data + idx;
+    const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
+    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextA.Data + obj->TextA.Size);
+    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextA.Data + obj->TextA.Size);
 
-    bool prev_white = ImCharIsBlankW(prev);
-    bool prev_separ = ImCharIsSeparatorW(prev);
-    bool curr_white = ImCharIsBlankW(curr);
-    bool curr_separ = ImCharIsSeparatorW(curr);
+    bool prev_white = ImCharIsBlankW(prev_c);
+    bool prev_separ = ImCharIsSeparatorW(prev_c);
+    bool curr_white = ImCharIsBlankW(curr_c);
+    bool curr_separ = ImCharIsSeparatorW(curr_c);
     return ((prev_white) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
 }
 static int  STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)   { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }

From 3d1e593b5b1c6842001a5cf9db1845c93df07689 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 5 Sep 2024 19:56:12 +0200
Subject: [PATCH 0350/2359] InputText: amends: fixed next/prev word
 implementation. (#7925)

+ replace IMSTB_TEXTEDIT_GETPREVCHARINDEX code with ImTextFindPreviousUtf8Codepoint().
---
 imgui_widgets.cpp | 91 ++++++++++++++++++++++-------------------------
 1 file changed, 42 insertions(+), 49 deletions(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 6d701d03b..24d1fda7e 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3911,6 +3911,25 @@ static void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* ob
     r->num_chars = (int)(text_remaining - (text + line_start_idx));
 }
 
+#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX  IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL
+#define IMSTB_TEXTEDIT_GETPREVCHARINDEX  IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL
+
+static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
+{
+    if (idx >= obj->CurLenA)
+        return obj->CurLenA + 1;
+    unsigned int c;
+    return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
+}
+
+static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
+{
+    if (idx <= 0)
+        return -1;
+    const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, obj->TextA.Data + idx);
+    return (int)(p - obj->TextA.Data);
+}
+
 static bool ImCharIsSeparatorW(unsigned int c)
 {
     static const unsigned int separator_list[] =
@@ -3958,58 +3977,32 @@ static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
     bool curr_separ = ImCharIsSeparatorW(curr_c);
     return ((prev_white) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
 }
-static int  STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)   { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
-static int  STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenA; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
-static int  STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenA; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
+static int  STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)
+{
+    idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx);
+    while (idx >= 0 && !is_word_boundary_from_right(obj, idx))
+        idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx);
+    return idx < 0 ? 0 : idx;
+}
+static int  STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)
+{
+    int len = obj->CurLenA;
+    idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
+    while (idx < len && !is_word_boundary_from_left(obj, idx))
+        idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
+    return idx > len ? len : idx;
+}
+static int  STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)
+{
+    idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
+    int len = obj->CurLenA;
+    while (idx < len && !is_word_boundary_from_right(obj, idx))
+        idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
+    return idx > len ? len : idx;
+}
 static int  STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx)  { ImGuiContext& g = *obj->Ctx; if (g.IO.ConfigMacOSXBehaviors) return STB_TEXTEDIT_MOVEWORDRIGHT_MAC(obj, idx); else return STB_TEXTEDIT_MOVEWORDRIGHT_WIN(obj, idx); }
 #define STB_TEXTEDIT_MOVEWORDLEFT       STB_TEXTEDIT_MOVEWORDLEFT_IMPL  // They need to be #define for stb_textedit.h
 #define STB_TEXTEDIT_MOVEWORDRIGHT      STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
-#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX  IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL
-#define IMSTB_TEXTEDIT_GETPREVCHARINDEX  IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL
-
-static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
-{
-    unsigned int c;
-    return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
-}
-
-static int CountLeadingHighBits(unsigned char b)
-{
-    for (int i = 0; i < (int)sizeof(b) * 8; i++)
-    {
-        bool set = (b >> (7 - i)) & 1;
-        if (!set)
-            return i;
-    }
-
-    return sizeof(b) * 8;
-}
-
-static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
-{
-    // Backwards check/count for UTF-8 multi byte sequence
-    int num_seq_bytes = 0;
-    for (int i = idx - 1; i >= 0; i -= 1)
-    {
-        bool is_seq_byte = (obj->TextA.Data[i] & 0x80) == 0x80 && (obj->TextA.Data[i] & 0x40) == 0;
-        num_seq_bytes += is_seq_byte;
-        if (!is_seq_byte)
-        {
-            if (num_seq_bytes > 0)
-            {
-                char initial_byte = obj->TextA.Data[i];
-                char num_leading_bits = (char)CountLeadingHighBits(initial_byte);
-                bool is_multi_byte_seq = num_leading_bits == num_seq_bytes + 1;
-                if (is_multi_byte_seq)
-                {
-                    return idx - (num_seq_bytes + 1);
-                }
-            }
-            break;
-        }
-    }
-    return idx - 1;
-}
 
 static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
 {

From 19accb14a9e52f515624485ef8ea6eba8dbab7c3 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 11 Sep 2024 12:57:54 +0200
Subject: [PATCH 0351/2359] InputText: amends: fixed undo-stack reconcile.
 fixed metrics crash. fixes character filtering. (#7925)

Refer to imgui_test_suite for tests.
---
 imgui_internal.h  |  3 ++-
 imgui_widgets.cpp | 31 ++++++++++++++++---------------
 2 files changed, 18 insertions(+), 16 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index e6f3f8ec5..b54848635 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1112,8 +1112,9 @@ struct IMGUI_API ImGuiInputTextState
     ImStbTexteditState*     Stb;                    // State for stb_textedit.h
     ImGuiID                 ID;                     // widget id owning the text state
     int                     CurLenA;                // UTF-8 length of the string in TextA (in bytes)
-    ImVector          TextA;                  // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity.
+    ImVector          TextA;                  // main UTF8 buffer.
     ImVector          InitialTextA;           // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
+    ImVector          CallbackTextBackup;     // temporary storage for callback to support automatic reconcile of undo-stack
     int                     BufCapacityA;           // end-user buffer capacity
     ImVec2                  Scroll;                 // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y)
     float                   CursorAnim;             // timer for cursor blink, reset on every user action so the cursor reappears immediately
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 24d1fda7e..b5c69e73e 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4301,8 +4301,8 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im
 // FIXME: Ideally we should transition toward (1) making InsertChars()/DeleteChars() update undo-stack (2) discourage (and keep reconcile) or obsolete (and remove reconcile) accessing buffer directly.
 static void InputTextReconcileUndoStateAfterUserCallback(ImGuiInputTextState* state, const char* new_buf_a, int new_length_a)
 {
-    const char* old_buf = state->TextA.Data;
-    const int old_length = state->CurLenA;
+    const char* old_buf = state->CallbackTextBackup.Data;
+    const int old_length = state->CallbackTextBackup.Size - 1;
 
     const int shorter_length = ImMin(old_length, new_length_a);
     int first_diff;
@@ -4323,7 +4323,7 @@ static void InputTextReconcileUndoStateAfterUserCallback(ImGuiInputTextState* st
     if (insert_len > 0 || delete_len > 0)
         if (IMSTB_TEXTEDIT_CHARTYPE* p = stb_text_createundo(&state->Stb->undostate, first_diff, delete_len, insert_len))
             for (int i = 0; i < delete_len; i++)
-                p[i] = ImStb::STB_TEXTEDIT_GETCHAR(state, first_diff + i);
+                p[i] = old_buf[first_diff + i];
 }
 
 // As InputText() retain textual data and we currently provide a path for user to not retain it (via local variables)
@@ -4598,11 +4598,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     }
 
     // Process mouse inputs and character inputs
-    int backup_current_text_length = 0;
     if (g.ActiveId == id)
     {
         IM_ASSERT(state != NULL);
-        backup_current_text_length = state->CurLenA;
         state->Edited = false;
         state->BufCapacityA = buf_size;
         state->Flags = flags;
@@ -4856,11 +4854,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                 {
                     unsigned int c;
                     int len = ImTextCharFromUtf8(&c, s, NULL);
+                    s += len;
                     if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true))
                         continue;
-                    memcpy(clipboard_filtered + clipboard_filtered_len, s, len);
+                    memcpy(clipboard_filtered + clipboard_filtered_len, s - len, len);
                     clipboard_filtered_len += len;
-                    s += len;
                 }
                 clipboard_filtered[clipboard_filtered_len] = 0;
                 if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
@@ -4960,6 +4958,10 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     callback_data.Flags = flags;
                     callback_data.UserData = callback_user_data;
 
+                    // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925
+                    state->CallbackTextBackup.resize(state->CurLenA + 1);
+                    memcpy(state->CallbackTextBackup.Data, state->TextA.Data, state->CurLenA + 1);
+
                     char* callback_buf = is_readonly ? buf : state->TextA.Data;
                     callback_data.EventKey = event_key;
                     callback_data.Buf = callback_buf;
@@ -4988,11 +4990,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                         // Callback may update buffer and thus set buf_dirty even in read-only mode.
                         IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
                         InputTextReconcileUndoStateAfterUserCallback(state, callback_data.Buf, callback_data.BufTextLen); // FIXME: Move the rest of this block inside function and rename to InputTextReconcileStateAfterUserCallback() ?
-                        if (callback_data.BufTextLen > backup_current_text_length && is_resizable)
-                            state->TextA.resize(state->TextA.Size + (callback_data.BufTextLen - backup_current_text_length)); // Worse case scenario resize
-
-                        memcpy(state->TextA.Data, callback_data.Buf, callback_data.BufTextLen);
                         state->CurLenA = callback_data.BufTextLen;  // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
+                        state->TextA.Size = state->CurLenA + 1;
                         state->CursorAnimReset();
                     }
                 }
@@ -5024,9 +5023,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     // Copy result to user buffer. This can currently only happen when (g.ActiveId == id)
     if (apply_new_text != NULL)
     {
-        // We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size
-        // of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used
-        // without any storage on user's side.
+        //// We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size
+        //// of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used
+        //// without any storage on user's side.
         IM_ASSERT(apply_new_text_length >= 0);
         if (is_resizable)
         {
@@ -5325,8 +5324,10 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
             const char undo_rec_type = (n < undo_state->undo_point) ? 'u' : (n >= undo_state->redo_point) ? 'r' : ' ';
             if (undo_rec_type == ' ')
                 BeginDisabled();
+            const int buf_preview_len = (undo_rec_type != ' ' && undo_rec->char_storage != -1) ? undo_rec->insert_length : 0;
+            const char* buf_preview_str = undo_state->undo_char + undo_rec->char_storage;
             Text("%c [%02d] where %03d, insert %03d, delete %03d, char_storage %03d \"%.*s\"",
-                undo_rec_type, n, undo_rec->where, undo_rec->insert_length, undo_rec->delete_length, undo_rec->char_storage, undo_rec->insert_length, undo_state->undo_char + undo_rec->char_storage);
+                undo_rec_type, n, undo_rec->where, undo_rec->insert_length, undo_rec->delete_length, undo_rec->char_storage, buf_preview_len, buf_preview_str);
             if (undo_rec_type == ' ')
                 EndDisabled();
         }

From 8807b01b28883dfbf7b971a4aa6c1199e4dea827 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 11 Sep 2024 14:15:23 +0200
Subject: [PATCH 0352/2359] InputText: amends: now can use memchr()/strchr()
 for line counting. Much faster! (#7925)

---
 docs/CHANGELOG.txt |  4 ++++
 docs/TODO.txt      |  1 -
 imgui_widgets.cpp  | 24 ++++++++++--------------
 3 files changed, 14 insertions(+), 15 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 35c4c6743..1611bf59b 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -63,6 +63,10 @@ Other changes:
      #6223, #6364, #6387, #6567, #6692, #6724, #6939, #6984, #7246, #7270, #7375, #7421, #7434,
      #7472, #7581, #7724, #7926, #7937 and probably more..)
 - Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439)
+- InputText: internal refactoring to simplify and optimize the code. The ImWchar buffer has been
+  removed. Simplifications allowed to implement new optimizations for handling very large text buffers
+  (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
+  This is the first step toward more refactorig. (#7925) [@alektron, @ocornut]
 - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow.
 - TextLinkOpenURL(): modified tooltip to display a verb "Open 'xxxx'". (#7885, #7660)
 - Backends: SDL2: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) [@scribam]
diff --git a/docs/TODO.txt b/docs/TODO.txt
index 84a00bc6e..ddceb3b3d 100644
--- a/docs/TODO.txt
+++ b/docs/TODO.txt
@@ -65,7 +65,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
  - selectable: generic BeginSelectable()/EndSelectable() mechanism. (work out alongside range-select branch)
  - selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection)
 
- - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. (WIP branch)
  - input text: preserve scrolling when unfocused?
  - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541)
  - input text: expose CursorPos in char filter event (#816)
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index b5c69e73e..94e1abff6 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -5119,14 +5119,12 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
             searches_remaining += is_multiline ? 1 : 0;
             int line_count = 0;
-            //for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\n')) != NULL; s++)  // FIXME-OPT: Could use this when wchar_t are 16-bit
-            for (const char* s = text_begin; *s != 0; s++)
-                if (*s == '\n')
-                {
-                    line_count++;
-                    if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; }
-                    if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; }
-                }
+            for (const char* s = text_begin; (s = strchr(s, '\n')) != NULL; s++) // FIXME-OPT: memchr() would be faster?
+            {
+                line_count++;
+                if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; }
+                if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; }
+            }
             line_count++;
             if (searches_result_line_no[0] == -1)
                 searches_result_line_no[0] = line_count;
@@ -5199,11 +5197,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     break;
                 if (rect_pos.y < clip_rect.y)
                 {
-                    //p = (const ImWchar*)wmemchr((const wchar_t*)p, '\n', text_selected_end - p);  // FIXME-OPT: Could use this when wchar_t are 16-bit
-                    //p = p ? p + 1 : text_selected_end;
-                    while (p < text_selected_end)
-                        if (*p++ == '\n')
-                            break;
+                    p = (const char*)memchr((void*)p, '\n', text_selected_end - p);
+                    p = p ? p + 1 : text_selected_end;
                 }
                 else
                 {
@@ -5213,13 +5208,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     rect.ClipWith(clip_rect);
                     if (rect.Overlaps(clip_rect))
                         draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
+                    rect_pos.x = draw_pos.x - draw_scroll.x;
                 }
-                rect_pos.x = draw_pos.x - draw_scroll.x;
                 rect_pos.y += g.FontSize;
             }
         }
 
         // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.
+        // FIXME-OPT: Multiline could submit a smaller amount of contents to AddText() since we already iterated through it.
         if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
         {
             ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);

From dc6346b763e4c92fe57887ee1cb4fe557517d4fa Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 12 Sep 2024 19:22:09 +0200
Subject: [PATCH 0353/2359] Fonts: fixed ellipsis "..." rendering width
 miscalculation bug introduced in 1.91.0. (#7976)

Amend 0f63d3e9
---
 docs/CHANGELOG.txt | 1 +
 imgui.cpp          | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 1611bf59b..28b3cae26 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -68,6 +68,7 @@ Other changes:
   (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
   This is the first step toward more refactorig. (#7925) [@alektron, @ocornut]
 - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow.
+- Fonts: fixed ellipsis "..." rendering width miscalculation bug introduced in 1.91.0. (#7976) [@DDeimos]
 - TextLinkOpenURL(): modified tooltip to display a verb "Open 'xxxx'". (#7885, #7660)
 - Backends: SDL2: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) [@scribam]
 
diff --git a/imgui.cpp b/imgui.cpp
index 71b1b1011..3c2fd6658 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4007,7 +4007,7 @@ static void SetCurrentWindow(ImGuiWindow* window)
     if (window)
     {
         g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
-        g.FontScale = g.FontSize / g.Font->FontSize;
+        g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
         ImGui::NavUpdateCurrentWindowIsScrollPushableX();
     }
 }

From 52a6ab44b1f0387922ec802ad909cf32a5283f24 Mon Sep 17 00:00:00 2001
From: David Briscoe <43559+idbrii@users.noreply.github.com>
Date: Thu, 12 Sep 2024 10:24:37 -0700
Subject: [PATCH 0354/2359] Doc: Fix typo. (#7974)

---
 imgui.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui.cpp b/imgui.cpp
index 3c2fd6658..59a918e86 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -9046,7 +9046,7 @@ bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
     return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
 }
 
-// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
+// Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
 bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
 {
     const ImGuiKeyData* key_data = GetKeyData(key);

From ac2ad79812e8f17ed4d76b8645c3f10e385018c8 Mon Sep 17 00:00:00 2001
From: Yan Pujante 
Date: Sat, 7 Sep 2024 10:22:45 -0700
Subject: [PATCH 0355/2359] Backends: GLFW+Emscripten: use OSX behaviors
 automatically when using contrib glfw port. (#7965, #7915)

---
 backends/imgui_impl_glfw.cpp              | 22 +++++++++++++++++++++-
 docs/CHANGELOG.txt                        |  2 ++
 examples/example_glfw_wgpu/CMakeLists.txt |  1 -
 3 files changed, 23 insertions(+), 2 deletions(-)

diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp
index 06b5142a1..9c6722f78 100644
--- a/backends/imgui_impl_glfw.cpp
+++ b/backends/imgui_impl_glfw.cpp
@@ -18,6 +18,11 @@
 // - Documentation        https://dearimgui.com/docs (same as your local docs/ folder).
 // - Introduction, links and more at the top of imgui.cpp
 
+// About Emscripten support:
+// - Emscripten provides its own GLFW (3.2.1) implementation (syntax: "-sUSE_GLFW=3"), but Joystick is broken and several features are not supported (multiple windows, clipboard, timer, etc.)
+// - A third-party Emscripten GLFW (3.4.0) implementation (syntax: "--use-port=contrib.glfw3") fixes the Joystick issue and implements all relevant features for the browser.
+// See https://github.com/pongasoft/emscripten-glfw/blob/master/docs/Comparison.md for details.
+
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
 //  2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
@@ -560,7 +565,7 @@ void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows)
 }
 
 #ifdef __EMSCRIPTEN__
-#if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 3'4'0'20240817
+#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'); });
@@ -639,6 +644,21 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw
     ::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
+    // to override io.ConfigMacOSXBehaviors from its default (which is always false in Emscripten).
+#if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817
+    if (emscripten::glfw3::IsRuntimePlatformApple())
+    {
+        ImGui::GetIO().ConfigMacOSXBehaviors = true;
+
+        // Due to how the browser (poorly) handles the Meta Key, this line essentially disables repeats when used.
+        // This means that Meta + V only registers a single key-press, even if the keys are held.
+        // This is a compromise for dealing with this issue in ImGui since ImGui implements key repeat itself.
+        // See https://github.com/pongasoft/emscripten-glfw/blob/v3.4.0.20240817/docs/Usage.md#the-problem-of-the-super-key
+        emscripten::glfw3::SetSuperPlusKeyTimeouts(10, 10);
+    }
+#endif
+
     bd->ClientApi = client_api;
     return true;
 }
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 28b3cae26..2189f2584 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -71,6 +71,8 @@ Other changes:
 - Fonts: fixed ellipsis "..." rendering width miscalculation bug introduced in 1.91.0. (#7976) [@DDeimos]
 - TextLinkOpenURL(): modified tooltip to display a verb "Open 'xxxx'". (#7885, #7660)
 - Backends: SDL2: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) [@scribam]
+- Backends: GLFW+Emscripten: use OSX behaviors automatically when using contrib glfw port. (#7965, #7915)
+  [@ypujante]
 
 -----------------------------------------------------------------------
  VERSION 1.91.1 (Released 2024-09-04)
diff --git a/examples/example_glfw_wgpu/CMakeLists.txt b/examples/example_glfw_wgpu/CMakeLists.txt
index 77b492fdc..6be95af44 100644
--- a/examples/example_glfw_wgpu/CMakeLists.txt
+++ b/examples/example_glfw_wgpu/CMakeLists.txt
@@ -91,7 +91,6 @@ if(EMSCRIPTEN)
   if("${IMGUI_EMSCRIPTEN_GLFW3}" STREQUAL "--use-port=contrib.glfw3")
     target_compile_options(example_glfw_wgpu PUBLIC
         "${IMGUI_EMSCRIPTEN_GLFW3}"
-        "-DEMSCRIPTEN_USE_PORT_CONTRIB_GLFW3" # unnecessary beyond emscripten 3.1.59
     )
   endif()
   message(STATUS "Using ${IMGUI_EMSCRIPTEN_GLFW3} GLFW implementation")

From 6dcb7be35f8e9b54d4a3e3c75a97ab09589e4f38 Mon Sep 17 00:00:00 2001
From: Yan Pujante 
Date: Sat, 7 Sep 2024 10:23:20 -0700
Subject: [PATCH 0356/2359] CI: amend build tests for emscripten (#7965)

+ Backends: GLFW: minor preemptive fix.
---
 .github/workflows/build.yml  | 16 +++++++++++++++-
 backends/imgui_impl_glfw.cpp |  2 ++
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 1d43da032..f95ff43c8 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -527,6 +527,7 @@ jobs:
         emsdk-master/emsdk update
         emsdk-master/emsdk install latest
         emsdk-master/emsdk activate latest
+        sudo apt-get install build-essential
 
     - name: Build example_sdl2_opengl3 with Emscripten
       run: |
@@ -535,13 +536,26 @@ jobs:
         popd
         make -C examples/example_sdl2_opengl3 -f Makefile.emscripten
 
-    - name: Build example_glfw_wgpu
+    # This build compiles example_glfw_wgpu using Makefile.emscripten and Emscripten GLFW built-in implementation (-sUSE_GLFW=3)
+    # This ensures 2 things: the make build works, and the GLFW built-in implementation is tested
+    - name: Build example_glfw_wgpu with Emscripten/Makefile
       run: |
         pushd emsdk-master
         source ./emsdk_env.sh
         popd
         make -C examples/example_glfw_wgpu -f Makefile.emscripten
 
+    # This build compiles example_glfw_wgpu using CMakeLists.txt and Emscripten GLFW contrib port (--use-port=contrib.glfw3)
+    # This ensures 2 things: the CMake build works, and the GLFW contrib port is tested
+    - name: Build example_glfw_wgpu with Emscripten/CMake
+      run: |
+        pushd emsdk-master
+        source ./emsdk_env.sh
+        popd
+        emcc -v
+        emcmake cmake -B build -DCMAKE_BUILD_TYPE=Release examples/example_glfw_wgpu
+        cmake --build build
+
   Android:
     runs-on: ubuntu-24.04
     steps:
diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp
index 9c6722f78..30afaf4f0 100644
--- a/backends/imgui_impl_glfw.cpp
+++ b/backends/imgui_impl_glfw.cpp
@@ -646,6 +646,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw
 
     // Emscripten: the same application can run on various platforms, so we detect the Apple platform at runtime
     // to override io.ConfigMacOSXBehaviors from its default (which is always false in Emscripten).
+#ifdef __EMSCRIPTEN__
 #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817
     if (emscripten::glfw3::IsRuntimePlatformApple())
     {
@@ -657,6 +658,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw
         // See https://github.com/pongasoft/emscripten-glfw/blob/v3.4.0.20240817/docs/Usage.md#the-problem-of-the-super-key
         emscripten::glfw3::SetSuperPlusKeyTimeouts(10, 10);
     }
+#endif
 #endif
 
     bd->ClientApi = client_api;

From 4d00bf8add44155a4f6b489538bd77d6214a4432 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 12 Sep 2024 23:13:32 +0200
Subject: [PATCH 0357/2359] MultiSelect+Tables: fixed an issue where box-select
 would skip items while drag-scrolling in a table with outer borders. (#7970,
 #7821).

See "widgets_multiselect_boxselect_2" test.
---
 docs/CHANGELOG.txt | 2 ++
 imgui_widgets.cpp  | 7 ++++++-
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 2189f2584..903af40c3 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -63,6 +63,8 @@ Other changes:
      #6223, #6364, #6387, #6567, #6692, #6724, #6939, #6984, #7246, #7270, #7375, #7421, #7434,
      #7472, #7581, #7724, #7926, #7937 and probably more..)
 - Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439)
+- MultiSelect+Tables: fixed an issue where box-select would skip items while drag-scrolling
+  in a table with outer borders. (#7970, #7821).
 - InputText: internal refactoring to simplify and optimize the code. The ImWchar buffer has been
   removed. Simplifications allowed to implement new optimizations for handling very large text buffers
   (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 94e1abff6..14c5af3e4 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -7403,6 +7403,7 @@ static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSe
 
 static ImRect CalcScopeRect(ImGuiMultiSelectTempData* ms, ImGuiWindow* window)
 {
+    ImGuiContext& g = *GImGui;
     if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)
     {
         // Warning: this depends on CursorMaxPos so it means to be called by EndMultiSelect() only
@@ -7410,8 +7411,12 @@ static ImRect CalcScopeRect(ImGuiMultiSelectTempData* ms, ImGuiWindow* window)
     }
     else
     {
-        // Add inner table decoration (#7821) // FIXME: Why not baking in InnerClipRect?
+        // When a table, pull HostClipRect, which allows us to predict ClipRect before first row/layout is performed. (#7970)
         ImRect scope_rect = window->InnerClipRect;
+        if (g.CurrentTable != NULL)
+            scope_rect = g.CurrentTable->HostClipRect;
+
+        // Add inner table decoration (#7821) // FIXME: Why not baking in InnerClipRect?
         scope_rect.Min = ImMin(scope_rect.Min + ImVec2(window->DecoInnerSizeX1, window->DecoInnerSizeY1), scope_rect.Max);
         return scope_rect;
     }

From dab63231d888f4a39c4d5729e14296c30cef2bc7 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 16 Sep 2024 11:19:05 +0200
Subject: [PATCH 0358/2359] Misc: Made it accepted to call SetMouseCursor()
 with any out-of-bound value, as a way to allow hacking in custom cursors if
 desirable.

---
 docs/CHANGELOG.txt |  2 ++
 imgui.cpp          | 10 +++++++---
 imgui_demo.cpp     |  3 ++-
 imgui_tables.cpp   |  2 +-
 imgui_widgets.cpp  |  2 +-
 5 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 903af40c3..b91d55530 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -70,6 +70,8 @@ Other changes:
   (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
   This is the first step toward more refactorig. (#7925) [@alektron, @ocornut]
 - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow.
+- Misc: Made it accepted to call SetMouseCursor() with any out-of-bound value, as a way to allow
+  hacking in custom cursors if desirable.
 - Fonts: fixed ellipsis "..." rendering width miscalculation bug introduced in 1.91.0. (#7976) [@DDeimos]
 - TextLinkOpenURL(): modified tooltip to display a verb "Open 'xxxx'". (#7885, #7660)
 - Backends: SDL2: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) [@scribam]
diff --git a/imgui.cpp b/imgui.cpp
index 59a918e86..bdeda3fe7 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3702,7 +3702,8 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl
 void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
 {
     ImGuiContext& g = *GImGui;
-    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
+    if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values.
+        mouse_cursor = ImGuiMouseCursor_Arrow;
     ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
     for (ImGuiViewportP* viewport : g.Viewports)
     {
@@ -6198,7 +6199,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
         ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
         //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
         if (hovered || held)
-            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
+            SetMouseCursor((resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE);
 
         if (held && g.IO.MouseDoubleClicked[0])
         {
@@ -6244,7 +6245,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
         if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
             hovered = false;
         if (hovered || held)
-            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
+            SetMouseCursor((axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS);
         if (held && g.IO.MouseDoubleClicked[0])
         {
             // Double-clicking bottom or right border auto-fit on this axis
@@ -9296,6 +9297,9 @@ ImGuiMouseCursor ImGui::GetMouseCursor()
     return g.MouseCursor;
 }
 
+// We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value.
+// Custom cursors may be handled by custom backends. If you are using a standard backend and want to hack in a custom cursor, you may
+// handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags_NoMouseCursorChange during the backend _NewFrame() call.
 void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
 {
     ImGuiContext& g = *GImGui;
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 8c9745dfb..cc21099a8 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -7490,7 +7490,8 @@ static void ShowDemoWindowInputs()
             IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT);
 
             ImGuiMouseCursor current = ImGui::GetMouseCursor();
-            ImGui::Text("Current mouse cursor = %d: %s", current, mouse_cursors_names[current]);
+            const char* cursor_name = (current >= ImGuiMouseCursor_Arrow) && (current < ImGuiMouseCursor_COUNT) ? mouse_cursors_names[current] : "N/A";
+            ImGui::Text("Current mouse cursor = %d: %s", current, cursor_name);
             ImGui::BeginDisabled(true);
             ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &io.BackendFlags, ImGuiBackendFlags_HasMouseCursors);
             ImGui::EndDisabled();
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index f247ed6d3..9a6e06a2d 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -4409,7 +4409,7 @@ void ImGui::EndColumns()
             {
                 ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
                 if (hovered || held)
-                    g.MouseCursor = ImGuiMouseCursor_ResizeEW;
+                    SetMouseCursor(ImGuiMouseCursor_ResizeEW);
                 if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize))
                     dragging_column = n;
             }
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 14c5af3e4..3576d31fa 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4438,7 +4438,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     }
     const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags);
     if (hovered)
-        g.MouseCursor = ImGuiMouseCursor_TextInput;
+        SetMouseCursor(ImGuiMouseCursor_TextInput);
 
     // We are only allowed to access the state if we are already the active widget.
     ImGuiInputTextState* state = GetInputTextState(id);

From 510b6adc9bb0cfea012f513e358f3df962fe91b7 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 16 Sep 2024 12:09:02 +0200
Subject: [PATCH 0359/2359] CI: disable month-long PVS Studio warning about
 expiring licence.

---
 .github/workflows/static-analysis.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml
index 69df5cdf8..99b058c91 100644
--- a/.github/workflows/static-analysis.yml
+++ b/.github/workflows/static-analysis.yml
@@ -42,5 +42,5 @@ jobs:
           fi
           cd examples/example_null
           pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1
-          pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log
+          pvs-studio-analyzer analyze --disableLicenseExpirationCheck -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log
           plog-converter -a 'GA:1,2;OP:1' -d V1071 -t errorfile -w pvs-studio.log

From b53d91a4c40b69ec1d7e95e44863c8c921ed2f11 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 16 Sep 2024 14:15:43 +0200
Subject: [PATCH 0360/2359] InputText: optimization for large text: using
 memchr() instead of strchr() shaves 0.2 ms on 865k multi-line text case.
 Approximately 20%. (#7925)

---
 docs/CHANGELOG.txt | 2 +-
 imgui_widgets.cpp  | 3 ++-
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index b91d55530..069b60388 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -68,7 +68,7 @@ Other changes:
 - InputText: internal refactoring to simplify and optimize the code. The ImWchar buffer has been
   removed. Simplifications allowed to implement new optimizations for handling very large text buffers
   (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
-  This is the first step toward more refactorig. (#7925) [@alektron, @ocornut]
+  This is the first step toward more refactoring. (#7925) [@alektron, @ocornut]
 - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow.
 - Misc: Made it accepted to call SetMouseCursor() with any out-of-bound value, as a way to allow
   hacking in custom cursors if desirable.
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 3576d31fa..64156b40d 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -5095,6 +5095,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
         // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
         const char* text_begin = state->TextA.Data;
+        const char* text_end = text_begin + state->CurLenA;
         ImVec2 cursor_offset, select_start_offset;
 
         {
@@ -5119,7 +5120,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
             searches_remaining += is_multiline ? 1 : 0;
             int line_count = 0;
-            for (const char* s = text_begin; (s = strchr(s, '\n')) != NULL; s++) // FIXME-OPT: memchr() would be faster?
+            for (const char* s = text_begin; (s = (const char*)memchr(s, '\n', (size_t)(text_end - s))) != NULL; s++)
             {
                 line_count++;
                 if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; }

From aef07aea27472b9a678967404d06ea7ab6d71fb9 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 16 Sep 2024 14:36:25 +0200
Subject: [PATCH 0361/2359] InputText: minor tidying up of selection search
 loop (no need to imply it runs in single line mode)

---
 imgui_widgets.cpp | 23 ++++++++++-------------
 1 file changed, 10 insertions(+), 13 deletions(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 64156b40d..26f617806 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -5100,33 +5100,30 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
 
         {
             // Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions.
-            const char* searches_input_ptr[2] = { NULL, NULL };
             int searches_result_line_no[2] = { -1000, -1000 };
-            int searches_remaining = 0;
+            const char* searches_input_ptr[2] = { NULL, NULL };
             if (render_cursor)
             {
                 searches_input_ptr[0] = text_begin + state->Stb->cursor;
                 searches_result_line_no[0] = -1;
-                searches_remaining++;
             }
             if (render_selection)
             {
                 searches_input_ptr[1] = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end);
                 searches_result_line_no[1] = -1;
-                searches_remaining++;
             }
 
-            // Iterate all lines to find our line numbers
-            // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
-            searches_remaining += is_multiline ? 1 : 0;
-            int line_count = 0;
-            for (const char* s = text_begin; (s = (const char*)memchr(s, '\n', (size_t)(text_end - s))) != NULL; s++)
+            // Count lines and find line number for cursor and selection ends
+            int line_count = 1;
+            if (is_multiline)
             {
-                line_count++;
-                if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; }
-                if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; }
+                for (const char* s = text_begin; (s = (const char*)memchr(s, '\n', (size_t)(text_end - s))) != NULL; s++)
+                {
+                    if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; }
+                    if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; }
+                    line_count++;
+                }
             }
-            line_count++;
             if (searches_result_line_no[0] == -1)
                 searches_result_line_no[0] = line_count;
             if (searches_result_line_no[1] == -1)

From 7ac50bf77d08aaf569acc00feacd7eb44785f241 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 16 Sep 2024 14:42:58 +0200
Subject: [PATCH 0362/2359] InputText: more tidying up of selection search
 loop.

---
 imgui_widgets.cpp | 40 ++++++++++++++++------------------------
 1 file changed, 16 insertions(+), 24 deletions(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 26f617806..c5ee2734a 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -5099,19 +5099,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         ImVec2 cursor_offset, select_start_offset;
 
         {
-            // Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions.
-            int searches_result_line_no[2] = { -1000, -1000 };
-            const char* searches_input_ptr[2] = { NULL, NULL };
-            if (render_cursor)
-            {
-                searches_input_ptr[0] = text_begin + state->Stb->cursor;
-                searches_result_line_no[0] = -1;
-            }
-            if (render_selection)
-            {
-                searches_input_ptr[1] = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end);
-                searches_result_line_no[1] = -1;
-            }
+            // Find lines numbers straddling cursor and selection min position
+            int cursor_line_no = render_cursor ? -1 : -1000;
+            int selmin_line_no = render_selection ? -1 : -1000;
+            const char* cursor_ptr = render_cursor ? text_begin + state->Stb->cursor : NULL;
+            const char* selmin_ptr = render_selection ? text_begin + ImMin(state->Stb->select_start, state->Stb->select_end) : NULL;
 
             // Count lines and find line number for cursor and selection ends
             int line_count = 1;
@@ -5119,23 +5111,23 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             {
                 for (const char* s = text_begin; (s = (const char*)memchr(s, '\n', (size_t)(text_end - s))) != NULL; s++)
                 {
-                    if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; }
-                    if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; }
+                    if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_no = line_count; }
+                    if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_no = line_count; }
                     line_count++;
                 }
             }
-            if (searches_result_line_no[0] == -1)
-                searches_result_line_no[0] = line_count;
-            if (searches_result_line_no[1] == -1)
-                searches_result_line_no[1] = line_count;
+            if (cursor_line_no == -1)
+                cursor_line_no = line_count;
+            if (selmin_line_no == -1)
+                selmin_line_no = line_count;
 
             // Calculate 2d position by finding the beginning of the line and measuring distance
-            cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
-            cursor_offset.y = searches_result_line_no[0] * g.FontSize;
-            if (searches_result_line_no[1] >= 0)
+            cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(cursor_ptr, text_begin), cursor_ptr).x;
+            cursor_offset.y = cursor_line_no * g.FontSize;
+            if (selmin_line_no >= 0)
             {
-                select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
-                select_start_offset.y = searches_result_line_no[1] * g.FontSize;
+                select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(selmin_ptr, text_begin), selmin_ptr).x;
+                select_start_offset.y = selmin_line_no * g.FontSize;
             }
 
             // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)

From 4925695ae882f628d149ebcc8bd17471dd2c3efb Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 16 Sep 2024 14:52:42 +0200
Subject: [PATCH 0363/2359] InputText: optimize
 InputTextCalcTextLenAndLineCount() for inactive multiline path. (#7925)

---
 imgui_widgets.cpp | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index c5ee2734a..4156ce8af 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3822,16 +3822,22 @@ bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, si
     return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
 }
 
+// This is only used in the path where the multiline widget is inactivate.
 static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
 {
     int line_count = 0;
     const char* s = text_begin;
-    while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
-        if (c == '\n')
-            line_count++;
-    s--;
-    if (s[0] != '\n' && s[0] != '\r')
+    while (true)
+    {
+        const char* s_eol = strchr(s, '\n');
         line_count++;
+        if (s_eol == NULL)
+        {
+            s = s + strlen(s);
+            break;
+        }
+        s = s_eol + 1;
+    }
     *out_text_end = s;
     return line_count;
 }

From 1ac162f2b083819663fe12b7217c40abdaf501cb Mon Sep 17 00:00:00 2001
From: Aaron C Gaudette 
Date: Mon, 16 Sep 2024 16:07:02 +0200
Subject: [PATCH 0364/2359] Backends: WGPU: add
 IMGUI_IMPL_WEBGPU_BACKEND_DAWN/IMGUI_IMPL_WEBGPU_BACKEND_WGPU to support more
 targets. (#7977, #7969, #6602, #6188, #7523)

---
 backends/imgui_impl_wgpu.cpp              | 29 +++++++++++++++++++++++
 backends/imgui_impl_wgpu.h                |  7 ++++++
 docs/CHANGELOG.txt                        |  2 ++
 examples/example_glfw_wgpu/CMakeLists.txt |  5 ++++
 4 files changed, 43 insertions(+)

diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index bf741e1a4..503ac8efd 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -16,6 +16,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-09-16: Added support for optional IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU define to handle ever-changing native implementations. (#7977)
 //  2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
 //  2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
 //  2024-01-22: Fixed pipeline layout leak. (#7245)
@@ -35,6 +36,18 @@
 //  2021-02-18: Change blending equation to preserve alpha in output buffer.
 //  2021-01-28: Initial version.
 
+// When targeting native platforms (i.e. NOT emscripten), one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+// or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details.
+#ifndef __EMSCRIPTEN__
+    #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
+    #error exactly one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be defined!
+    #endif
+#else
+    #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
+    #error neither IMGUI_IMPL_WEBGPU_BACKEND_DAWN nor IMGUI_IMPL_WEBGPU_BACKEND_WGPU may be defined if targeting emscripten!
+    #endif
+#endif
+
 #include "imgui.h"
 #ifndef IMGUI_DISABLE
 #include "imgui_impl_wgpu.h"
@@ -245,7 +258,11 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c
     ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
 
     WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
+#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+    wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
+#else
     wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
+#endif
     wgsl_desc.code = wgsl_source;
 
     WGPUShaderModuleDescriptor desc = {};
@@ -660,7 +677,11 @@ bool ImGui_ImplWGPU_CreateDeviceObjects()
     // Create depth-stencil State
     WGPUDepthStencilState depth_stencil_state = {};
     depth_stencil_state.format = bd->depthStencilFormat;
+#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+    depth_stencil_state.depthWriteEnabled = WGPUOptionalBool_False;
+#else
     depth_stencil_state.depthWriteEnabled = false;
+#endif
     depth_stencil_state.depthCompare = WGPUCompareFunction_Always;
     depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always;
     depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep;
@@ -730,7 +751,15 @@ bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info)
     // Setup backend capabilities flags
     ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)();
     io.BackendRendererUserData = (void*)bd;
+#if defined(__EMSCRIPTEN__)
+    io.BackendRendererName = "imgui_impl_webgpu_emscripten";
+#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
+    io.BackendRendererName = "imgui_impl_webgpu_dawn";
+#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
+    io.BackendRendererName = "imgui_impl_webgpu_wgpu";
+#else
     io.BackendRendererName = "imgui_impl_webgpu";
+#endif
     io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;  // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
 
     bd->initInfo = *init_info;
diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h
index 87d9580bf..e6835dee9 100644
--- a/backends/imgui_impl_wgpu.h
+++ b/backends/imgui_impl_wgpu.h
@@ -2,6 +2,13 @@
 // This needs to be used along with a Platform Binding (e.g. GLFW)
 // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.)
 
+// Important note to dawn and/or wgpu users: when targeting native platforms (i.e. NOT emscripten),
+// one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided.
+// Add #define to your imconfig.h file, or as a compilation flag in your build system.
+// This requirement will be removed once WebGPU stabilizes and backends converge on a unified interface.
+//#define IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+//#define IMGUI_IMPL_WEBGPU_BACKEND_WGPU
+
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 069b60388..95df895c4 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -77,6 +77,8 @@ Other changes:
 - Backends: SDL2: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) [@scribam]
 - Backends: GLFW+Emscripten: use OSX behaviors automatically when using contrib glfw port. (#7965, #7915)
   [@ypujante]
+- Backends: WebGPU: Added support for optional IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU
+  defines to handle ever-changing native implementations. (#7977, #7969, #6602, #6188, #7523) [@acgaudette]
 
 -----------------------------------------------------------------------
  VERSION 1.91.1 (Released 2024-09-04)
diff --git a/examples/example_glfw_wgpu/CMakeLists.txt b/examples/example_glfw_wgpu/CMakeLists.txt
index 6be95af44..8e164e488 100644
--- a/examples/example_glfw_wgpu/CMakeLists.txt
+++ b/examples/example_glfw_wgpu/CMakeLists.txt
@@ -79,6 +79,11 @@ add_executable(example_glfw_wgpu
   ${IMGUI_DIR}/imgui_tables.cpp
   ${IMGUI_DIR}/imgui_widgets.cpp
 )
+IF(NOT EMSCRIPTEN)
+  target_compile_definitions(example_glfw_wgpu PUBLIC
+    "IMGUI_IMPL_WEBGPU_BACKEND_DAWN"
+  )
+endif()
 target_include_directories(example_glfw_wgpu PUBLIC
   ${IMGUI_DIR}
   ${IMGUI_DIR}/backends

From 08b1496b7e566eecf1b870bce1eed57522c6593c Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 16 Sep 2024 17:22:31 +0200
Subject: [PATCH 0365/2359] Backends: Win32: fixed an issue where a viewport
 destroyed while clicking would hog mouse tracking and temporary lead to
 incorrect update of HoveredWindow. (#7971)

# Conflicts:
#	backends/imgui_impl_win32.cpp
#	docs/CHANGELOG.txt
---
 backends/imgui_impl_win32.cpp | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index 0e48d8636..758e70d01 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -107,7 +107,7 @@ struct ImGui_ImplWin32_Data
 {
     HWND                        hWnd;
     HWND                        MouseHwnd;
-    int                         MouseTrackedArea;   // 0: not tracked, 1: client are, 2: non-client area
+    int                         MouseTrackedArea;   // 0: not tracked, 1: client area, 2: non-client area
     int                         MouseButtonsDown;
     INT64                       Time;
     INT64                       TicksPerSecond;
@@ -629,6 +629,16 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
         }
         return 0;
     }
+    case WM_DESTROY:
+        if (bd->MouseHwnd == hwnd && bd->MouseTrackedArea != 0)
+        {
+            TRACKMOUSEEVENT tme_cancel = { sizeof(tme_cancel), TME_CANCEL, hwnd, 0 };
+            ::TrackMouseEvent(&tme_cancel);
+            bd->MouseHwnd = nullptr;
+            bd->MouseTrackedArea = 0;
+            io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
+        }
+        return 0;
     case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
     case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
     case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:

From 6ce26ef11d52d57845d0f06d84dcbfbc0f8d006b Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 17 Sep 2024 12:25:21 +0200
Subject: [PATCH 0366/2359] AddFont: added assert to better detect
 uninitialized struct. (#7993)

---
 imgui_draw.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index a681059bb..79270f1a1 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -2499,13 +2499,14 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
 {
     IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
     IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0);
-    IM_ASSERT(font_cfg->SizePixels > 0.0f);
+    IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?");
+    IM_ASSERT(font_cfg->OversampleH > 0 && font_cfg->OversampleV > 0 && "Is ImFontConfig struct correctly initialized?");
 
     // Create new font
     if (!font_cfg->MergeMode)
         Fonts.push_back(IM_NEW(ImFont));
     else
-        IM_ASSERT(!Fonts.empty() && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font.
+        IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font.
 
     ConfigData.push_back(*font_cfg);
     ImFontConfig& new_font_cfg = ConfigData.back();

From 11fba027e506beca7a2a726b73577b5e8938d64d Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 17 Sep 2024 16:35:55 +0200
Subject: [PATCH 0367/2359] Tables: using table->InnerClipRect more
 consistently. Fixes an assertion with tables with borders when clipped by
 parent. (#6765, #3752, #7428)

---
 docs/CHANGELOG.txt | 1 +
 imgui_tables.cpp   | 8 ++++----
 2 files changed, 5 insertions(+), 4 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 95df895c4..8d640533c 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -70,6 +70,7 @@ Other changes:
   (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
   This is the first step toward more refactoring. (#7925) [@alektron, @ocornut]
 - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow.
+- Tables: fixes an assertion with tables with borders when clipped by parent. (#6765, #3752, #7428)
 - Misc: Made it accepted to call SetMouseCursor() with any out-of-bound value, as a way to allow
   hacking in custom cursors if desirable.
 - Fonts: fixed ellipsis "..." rendering width miscalculation bug introduced in 1.91.0. (#7976) [@DDeimos]
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 9a6e06a2d..e82e8777f 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1261,7 +1261,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table)
     if (table->Flags & ImGuiTableFlags_NoClip)
         table->DrawSplitter->SetCurrentChannel(inner_window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);
     else
-        inner_window->DrawList->PushClipRect(inner_window->InnerClipRect.Min, inner_window->InnerClipRect.Max, false);
+        inner_window->DrawList->PushClipRect(inner_window->InnerClipRect.Min, inner_window->InnerClipRect.Max, false); // FIXME: use table->InnerClipRect?
 }
 
 // Process hit-testing on resizing borders. Actual size change will be applied in EndTable()
@@ -2011,7 +2011,7 @@ void ImGui::TableEndRow(ImGuiTable* table)
     {
         for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
             table->Columns[column_n].NavLayerCurrent = ImGuiNavLayer_Main;
-        const float y0 = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y);
+        const float y0 = ImMax(table->RowPosY2 + 1, table->InnerClipRect.Min.y);
         table_instance->LastFrozenHeight = y0 - table->OuterRect.Min.y;
 
         if (unfreeze_rows_actual)
@@ -2020,8 +2020,8 @@ void ImGui::TableEndRow(ImGuiTable* table)
             table->IsUnfrozenRows = true;
 
             // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect
-            table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, window->InnerClipRect.Max.y);
-            table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = window->InnerClipRect.Max.y;
+            table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, table->InnerClipRect.Max.y);
+            table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = table->InnerClipRect.Max.y;
             table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen;
             IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y);
 

From 71714eab5367d2fa119e36be30148278e0d5974f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 17 Sep 2024 18:09:02 +0200
Subject: [PATCH 0368/2359] Tables: fixed assertion related to inconsistent
 outer clipping when sizes are not rounded. (#7957)

---
 docs/CHANGELOG.txt | 3 ++-
 imgui.h            | 2 +-
 imgui_tables.cpp   | 2 +-
 3 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 8d640533c..566e42608 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -70,7 +70,8 @@ Other changes:
   (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
   This is the first step toward more refactoring. (#7925) [@alektron, @ocornut]
 - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow.
-- Tables: fixes an assertion with tables with borders when clipped by parent. (#6765, #3752, #7428)
+- Tables: fixed assertion related to inconsistent outer clipping when sizes are not rounded. (#7957) [@eclbtownsend]
+- Tables: fixed assertion with tables with borders when clipped by parent. (#6765, #3752, #7428)
 - Misc: Made it accepted to call SetMouseCursor() with any out-of-bound value, as a way to allow
   hacking in custom cursors if desirable.
 - Fonts: fixed ellipsis "..." rendering width miscalculation bug introduced in 1.91.0. (#7976) [@DDeimos]
diff --git a/imgui.h b/imgui.h
index 095c25002..854d210e1 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.2 WIP"
-#define IMGUI_VERSION_NUM   19114
+#define IMGUI_VERSION_NUM   19115
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index e82e8777f..d9844586b 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -328,7 +328,7 @@ bool    ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
     // - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[].
     const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0;
     const ImVec2 avail_size = GetContentRegionAvail();
-    const ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f);
+    const ImVec2 actual_outer_size = ImTrunc(CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f));
     const ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size);
     const bool outer_window_is_measuring_size = (outer_window->AutoFitFramesX > 0) || (outer_window->AutoFitFramesY > 0); // Doesn't apply to AlwaysAutoResize windows!
     if (use_child_window && IsClippedEx(outer_rect, 0) && !outer_window_is_measuring_size)

From dad9f45e3ed9968b7873f3ed4a41ac0339befafa Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 17 Sep 2024 18:27:31 +0200
Subject: [PATCH 0369/2359] Windows: fixed an issue where double-click to
 collapse could be triggered even while another item is active. (#7841, #7369)

---
 docs/CHANGELOG.txt | 2 ++
 imgui.cpp          | 5 +++--
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 566e42608..9e31a1011 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -72,6 +72,8 @@ Other changes:
 - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow.
 - Tables: fixed assertion related to inconsistent outer clipping when sizes are not rounded. (#7957) [@eclbtownsend]
 - Tables: fixed assertion with tables with borders when clipped by parent. (#6765, #3752, #7428)
+- Windows: fixed an issue where double-click to collapse could be triggered even while another
+  item is active, if the item didn't use the left mouse button. (#7841)
 - Misc: Made it accepted to call SetMouseCursor() with any out-of-bound value, as a way to allow
   hacking in custom cursors if desirable.
 - Fonts: fixed ellipsis "..." rendering width miscalculation bug introduced in 1.91.0. (#7976) [@DDeimos]
diff --git a/imgui.cpp b/imgui.cpp
index bdeda3fe7..369e582d7 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -6948,9 +6948,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
         // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
         if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
         {
-            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
+            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed),
+            // so verify that we don't have items over the title bar.
             ImRect title_bar_rect = window->TitleBarRect();
-            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
+            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && g.ActiveId == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
                 if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
                     window->WantCollapseToggle = true;
             if (window->WantCollapseToggle)

From 6aade6912a107204d15ebe7171434ee21a91c629 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 17 Sep 2024 18:52:12 +0200
Subject: [PATCH 0370/2359] Inputs: SetNextItemShortcut() with
 ImGuiInputFlags_Tooltip doesn't show tooltip when item is active.

---
 docs/CHANGELOG.txt | 1 +
 imgui.cpp          | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 9e31a1011..475daa596 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -65,6 +65,7 @@ Other changes:
 - Nav: pressing any keyboard key while holding Alt disable toggling nav layer on Alt release. (#4439)
 - MultiSelect+Tables: fixed an issue where box-select would skip items while drag-scrolling
   in a table with outer borders. (#7970, #7821).
+- Inputs: SetNextItemShortcut() with ImGuiInputFlags_Tooltip doesn't show tooltip when item is active.
 - InputText: internal refactoring to simplify and optimize the code. The ImWchar buffer has been
   removed. Simplifications allowed to implement new optimizations for handling very large text buffers
   (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
diff --git a/imgui.cpp b/imgui.cpp
index 369e582d7..9dddb55c2 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4343,7 +4343,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag
 
         // Display shortcut (only works with mouse)
         // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
-        if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut))
+        if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut) && g.ActiveId != id)
             if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
                 SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
     }

From e648dbb59d24c29a2e2ac964777822e96befd808 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 17 Sep 2024 20:34:54 +0200
Subject: [PATCH 0371/2359] Tables: fixed auto-width columns when using
 synced-instances of same table. (#7218)

Amend d3c3514a5
---
 docs/CHANGELOG.txt | 2 ++
 imgui_tables.cpp   | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 475daa596..de022c1ae 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -71,6 +71,8 @@ Other changes:
   (e.g. in our testing, handling of a 1 MB text buffer is now 3 times faster in VS2022 Debug build).
   This is the first step toward more refactoring. (#7925) [@alektron, @ocornut]
 - InputText: added CJK double-width punctuation to list of separators considered for CTRL+Arrow.
+- Tables: fixed auto-width columns when using synced-instances of same table. The previous fix
+  done in v1.90.5 was incomplete. (#7218)
 - Tables: fixed assertion related to inconsistent outer clipping when sizes are not rounded. (#7957) [@eclbtownsend]
 - Tables: fixed assertion with tables with borders when clipped by parent. (#6765, #3752, #7428)
 - Windows: fixed an issue where double-click to collapse could be triggered even while another
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index d9844586b..c3fb531ef 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -866,7 +866,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table)
 
         // Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping)
         // Combine width from regular rows + width from headers unless requested not to.
-        if (!column->IsPreserveWidthAuto)
+        if (!column->IsPreserveWidthAuto && table->InstanceCurrent == 0)
             column->WidthAuto = TableGetColumnWidthAuto(table, column);
 
         // Non-resizable columns keep their requested width (apply user value regardless of IsPreserveWidthAuto)

From f7ba6453980824aa4a7d096841576285efa7f6ec Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 17 Sep 2024 21:07:15 +0200
Subject: [PATCH 0372/2359] InputText: fixed not filling callback's
 SelectionEnd. (#7925)

Broken by abd07f6
---
 imgui_widgets.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 4156ce8af..27610228d 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4977,7 +4977,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
 
                     const int utf8_cursor_pos = callback_data.CursorPos = state->Stb->cursor;
                     const int utf8_selection_start = callback_data.SelectionStart = state->Stb->select_start;
-                    const int utf8_selection_end = state->Stb->select_end;
+                    const int utf8_selection_end = callback_data.SelectionEnd = state->Stb->select_end;
 
                     // Call user code
                     callback(&callback_data);

From cfae5ac71b903d8b5d04cce8f6329765e64af185 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 19 Sep 2024 14:09:45 +0200
Subject: [PATCH 0373/2359] Backends: make ImGui_ImplSDL2_KeyEventToImGuiKey(),
 ImGui_ImplSDL3_KeyEventToImGuiKey(), ImGui_ImplGlfw_KeyToImGuiKey(),
 ImGui_ImplWin32_KeyEventToImGuiKey(), ImGui_ImplAllegro5_KeyCodeToImGuiKey(),
 ImGui_ImplOSX_KeyCodeToImGuiKey(), non-static. (#7997)

Backends: Win32: Refactor ImGui_ImplWin32_KeyEventToImGuiKey() logic.
Ref #7672
---
 backends/imgui_impl_allegro5.cpp |  3 ++-
 backends/imgui_impl_glfw.cpp     | 10 +++++++---
 backends/imgui_impl_osx.mm       |  4 +++-
 backends/imgui_impl_sdl2.cpp     |  3 ++-
 backends/imgui_impl_sdl3.cpp     |  3 ++-
 backends/imgui_impl_win32.cpp    | 20 +++++++++-----------
 6 files changed, 25 insertions(+), 18 deletions(-)

diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp
index e41f02140..bf1019e2c 100644
--- a/backends/imgui_impl_allegro5.cpp
+++ b/backends/imgui_impl_allegro5.cpp
@@ -310,7 +310,8 @@ static void ImGui_ImplAllegro5_SetClipboardText(ImGuiContext*, const char* text)
 }
 #endif
 
-static ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code)
+// Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code)
 {
     switch (key_code)
     {
diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp
index 30afaf4f0..7134d3e55 100644
--- a/backends/imgui_impl_glfw.cpp
+++ b/backends/imgui_impl_glfw.cpp
@@ -185,9 +185,12 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData()
 }
 
 // Functions
-static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key)
+
+// Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode)
 {
-    switch (key)
+    IM_UNUSED(scancode);
+    switch (keycode)
     {
         case GLFW_KEY_TAB: return ImGuiKey_Tab;
         case GLFW_KEY_LEFT: return ImGuiKey_LeftArrow;
@@ -355,6 +358,7 @@ void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yo
     io.AddMouseWheelEvent((float)xoffset, (float)yoffset);
 }
 
+// FIXME: should this be baked into ImGui_ImplGlfw_KeyToImGuiKey()? then what about the values passed to io.SetKeyEventNativeData()?
 static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode)
 {
 #if GLFW_HAS_GETKEYNAME && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3)
@@ -402,7 +406,7 @@ void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, i
     keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode);
 
     ImGuiIO& io = ImGui::GetIO();
-    ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode);
+    ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode, scancode);
     io.AddKeyEvent(imgui_key, (action == GLFW_PRESS));
     io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code)
 }
diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm
index 870038d85..3115bf1c2 100644
--- a/backends/imgui_impl_osx.mm
+++ b/backends/imgui_impl_osx.mm
@@ -259,7 +259,9 @@ static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view);
 @end
 
 // Functions
-static ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code)
+
+// Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code)
 {
     switch (key_code)
     {
diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp
index 027dff9f2..6d98a697e 100644
--- a/backends/imgui_impl_sdl2.cpp
+++ b/backends/imgui_impl_sdl2.cpp
@@ -180,7 +180,8 @@ static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImG
     }
 }
 
-static ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
+// Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
 {
     IM_UNUSED(scancode);
     switch (keycode)
diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp
index 540b6931a..6819f546d 100644
--- a/backends/imgui_impl_sdl3.cpp
+++ b/backends/imgui_impl_sdl3.cpp
@@ -159,7 +159,8 @@ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view
     }
 }
 
-static ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
+// Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
 {
     // Keypad doesn't have individual key values in SDL3
     switch (scancode)
diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index 758e70d01..0e9164efe 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -419,12 +419,14 @@ void    ImGui_ImplWin32_NewFrame()
     ImGui_ImplWin32_UpdateGamepads();
 }
 
-// There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED, we assign it an arbitrary value to make code more readable (VK_ codes go up to 255)
-#define IM_VK_KEYPAD_ENTER      (VK_RETURN + 256)
-
 // Map VK_xxx to ImGuiKey_xxx.
-static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam)
+// Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam)
 {
+    // There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED.
+    if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED))
+        return ImGuiKey_KeypadEnter;
+
     switch (wParam)
     {
         case VK_TAB: return ImGuiKey_Tab;
@@ -473,7 +475,6 @@ static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam)
         case VK_MULTIPLY: return ImGuiKey_KeypadMultiply;
         case VK_SUBTRACT: return ImGuiKey_KeypadSubtract;
         case VK_ADD: return ImGuiKey_KeypadAdd;
-        case IM_VK_KEYPAD_ENTER: return ImGuiKey_KeypadEnter;
         case VK_LSHIFT: return ImGuiKey_LeftShift;
         case VK_LCONTROL: return ImGuiKey_LeftCtrl;
         case VK_LMENU: return ImGuiKey_LeftAlt;
@@ -692,12 +693,9 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
             // Submit modifiers
             ImGui_ImplWin32_UpdateKeyModifiers();
 
-            // Obtain virtual key code
-            // (keypad enter doesn't have its own... VK_RETURN with KF_EXTENDED flag means keypad enter, see IM_VK_KEYPAD_ENTER definition for details, it is mapped to ImGuiKey_KeyPadEnter.)
-            int vk = (int)wParam;
-            if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED))
-                vk = IM_VK_KEYPAD_ENTER;
-            const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk);
+            // Obtain virtual key code and convert to ImGuiKey
+            const ImGuiKey key = ImGui_ImplWin32_KeyEventToImGuiKey(wParam, lParam);
+            const int vk = (int)wParam;
             const int scancode = (int)LOBYTE(HIWORD(lParam));
 
             // Special behavior for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit the key down event.

From a9f72ab6818c3e55544378aa44c7659de7e5510f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 19 Sep 2024 14:33:03 +0200
Subject: [PATCH 0374/2359] Version 1.91.2

---
 docs/CHANGELOG.txt | 6 +++---
 imgui.cpp          | 2 +-
 imgui.h            | 6 +++---
 imgui_demo.cpp     | 2 +-
 imgui_draw.cpp     | 2 +-
 imgui_internal.h   | 2 +-
 imgui_tables.cpp   | 2 +-
 imgui_widgets.cpp  | 2 +-
 8 files changed, 12 insertions(+), 12 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index de022c1ae..6971e3e4a 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -36,10 +36,10 @@ HOW TO UPDATE?
 - Please report any issue!
 
 -----------------------------------------------------------------------
- VERSION 1.91.2 WIP (In Progress)
+ VERSION 1.91.2 (Released 2024-09-19)
 -----------------------------------------------------------------------
 
-Breaking changes:
+Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.2
 
 Other changes:
 
@@ -54,7 +54,7 @@ Other changes:
   - I've been wanting to add this tool for a long time, but was stalled by finding a way to
     not make it spammy + make it practically zero cost. After @pthom made various proposals to
     solve the same problem (thanks for pushing me!), I decided it was time to finish it.
-  - Added ImGuiItemFlags_AllowDuplicateId to use with PushItemFlag/PopItemFlag() if for some
+  - Added ImGuiItemFlags_AllowDuplicateId to use with PushItemFlag()/PopItemFlag() if for some
     reason you intend to have duplicate identifiers.
   - (#74, #96, #480, #501, #647, #654, #719, #843, #894, #1057, #1173, #1390, #1414, #1556, #1768,
      #2041, #2116, #2330, #2475, #2562, #2667, #2807, #2885, #3102, #3375, #3526, #3964, #4008,
diff --git a/imgui.cpp b/imgui.cpp
index 9dddb55c2..cfce32aca 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2 WIP
+// dear imgui, v1.91.2
 // (main code and documentation)
 
 // Help:
diff --git a/imgui.h b/imgui.h
index 854d210e1..a75f32b34 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2 WIP
+// dear imgui, v1.91.2
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.2 WIP"
-#define IMGUI_VERSION_NUM   19115
+#define IMGUI_VERSION       "1.91.2"
+#define IMGUI_VERSION_NUM   19120
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index cc21099a8..ebcc64f9d 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2 WIP
+// dear imgui, v1.91.2
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 79270f1a1..80bef6fe0 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2 WIP
+// dear imgui, v1.91.2
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index b54848635..b50b965f6 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2 WIP
+// dear imgui, v1.91.2
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index c3fb531ef..023e3f32a 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2 WIP
+// dear imgui, v1.91.2
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 27610228d..348a3dce0 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2 WIP
+// dear imgui, v1.91.2
 // (widgets code)
 
 /*

From faca859043cf42fb31f74a435def167b64a52516 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 19 Sep 2024 15:51:06 +0200
Subject: [PATCH 0375/2359] Version 1.91.3 WIP

---
 docs/CHANGELOG.txt | 9 +++++++++
 imgui.cpp          | 3 ++-
 imgui.h            | 6 +++---
 imgui_demo.cpp     | 2 +-
 imgui_draw.cpp     | 2 +-
 imgui_internal.h   | 4 ++--
 imgui_tables.cpp   | 2 +-
 imgui_widgets.cpp  | 2 +-
 8 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 6971e3e4a..cd1c80d9c 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -35,6 +35,15 @@ HOW TO UPDATE?
   and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users.
 - Please report any issue!
 
+-----------------------------------------------------------------------
+ VERSION 1.91.3 WIP (In Progress)
+-----------------------------------------------------------------------
+
+Breaking changes:
+
+Other changes:
+
+
 -----------------------------------------------------------------------
  VERSION 1.91.2 (Released 2024-09-19)
 -----------------------------------------------------------------------
diff --git a/imgui.cpp b/imgui.cpp
index cfce32aca..e82826792 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2
+// dear imgui, v1.91.3 WIP
 // (main code and documentation)
 
 // Help:
@@ -7736,6 +7736,7 @@ void ImGui::PopItemFlag()
 // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
 // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
 // - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
+// - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
 void ImGui::BeginDisabled(bool disabled)
 {
     ImGuiContext& g = *GImGui;
diff --git a/imgui.h b/imgui.h
index a75f32b34..a2aab8a63 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2
+// dear imgui, v1.91.3 WIP
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.2"
-#define IMGUI_VERSION_NUM   19120
+#define IMGUI_VERSION       "1.91.3 WIP"
+#define IMGUI_VERSION_NUM   19121
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index ebcc64f9d..5eb64e470 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2
+// dear imgui, v1.91.3 WIP
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 80bef6fe0..b7a00285f 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2
+// dear imgui, v1.91.3 WIP
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index b50b965f6..cb4046457 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2
+// dear imgui, v1.91.3 WIP
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
@@ -834,7 +834,7 @@ enum ImGuiDataTypePrivate_
 enum ImGuiItemFlagsPrivate_
 {
     // Controlled by user
-    ImGuiItemFlags_Disabled                 = 1 << 10, // false     // Disable interactions (DOES NOT affect visuals, see BeginDisabled()/EndDisabled() for full disable feature, and github #211).
+    ImGuiItemFlags_Disabled                 = 1 << 10, // false     // Disable interactions (DOES NOT affect visuals. DO NOT mix direct use of this with BeginDisabled(). See BeginDisabled()/EndDisabled() for full disable feature, and github #211).
     ImGuiItemFlags_ReadOnly                 = 1 << 11, // false     // [ALPHA] Allow hovering interactions but underlying value is not changed.
     ImGuiItemFlags_MixedValue               = 1 << 12, // false     // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets)
     ImGuiItemFlags_NoWindowHoverableCheck   = 1 << 13, // false     // Disable hoverable check in ItemHoverable()
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 023e3f32a..dc7f21098 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2
+// dear imgui, v1.91.3 WIP
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 348a3dce0..f2c5b8a0c 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.2
+// dear imgui, v1.91.3 WIP
 // (widgets code)
 
 /*

From 0af2c4ef765ff37004f1ee6e4ee5a40429f68fb9 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 19 Sep 2024 16:02:23 +0200
Subject: [PATCH 0376/2359] Backends: SDL3: Update for API changes: SDL_bool
 removal. SDL_INIT_TIMER removal. (#7999)

---
 backends/imgui_impl_sdl3.cpp                | 2 +-
 backends/imgui_impl_sdlrenderer3.cpp        | 4 ++--
 docs/CHANGELOG.txt                          | 2 ++
 examples/example_sdl3_opengl3/main.cpp      | 2 +-
 examples/example_sdl3_sdlrenderer3/main.cpp | 2 +-
 5 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp
index 6819f546d..599d3fc44 100644
--- a/backends/imgui_impl_sdl3.cpp
+++ b/backends/imgui_impl_sdl3.cpp
@@ -564,7 +564,7 @@ static void ImGui_ImplSDL3_UpdateMouseData()
     // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below)
 #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
     // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside
-    SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE);
+    SDL_CaptureMouse(bd->MouseButtonsDown != 0);
     SDL_Window* focused_window = SDL_GetKeyboardFocus();
     const bool is_app_focused = (bd->Window == focused_window);
 #else
diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp
index d3926c2fb..30f967bd3 100644
--- a/backends/imgui_impl_sdlrenderer3.cpp
+++ b/backends/imgui_impl_sdlrenderer3.cpp
@@ -158,8 +158,8 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
         SDL_Rect    ClipRect;
     };
     BackupSDLRendererState old = {};
-    old.ViewportEnabled = SDL_RenderViewportSet(renderer) == SDL_TRUE;
-    old.ClipEnabled = SDL_RenderClipEnabled(renderer) == SDL_TRUE;
+    old.ViewportEnabled = SDL_RenderViewportSet(renderer);
+    old.ClipEnabled = SDL_RenderClipEnabled(renderer);
     SDL_GetRenderViewport(renderer, &old.Viewport);
     SDL_GetRenderClipRect(renderer, &old.ClipRect);
 
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index cd1c80d9c..8c1a815e9 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,8 @@ Breaking changes:
 
 Other changes:
 
+- Backends: SDL3: Update for API changes: SDL_bool removal. SDL_INIT_TIMER removal.
+
 
 -----------------------------------------------------------------------
  VERSION 1.91.2 (Released 2024-09-19)
diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp
index 0ba09dc93..e7f239f47 100644
--- a/examples/example_sdl3_opengl3/main.cpp
+++ b/examples/example_sdl3_opengl3/main.cpp
@@ -27,7 +27,7 @@
 int main(int, char**)
 {
     // Setup SDL
-    if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD))
+    if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD))
     {
         printf("Error: SDL_Init(): %s\n", SDL_GetError());
         return -1;
diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp
index ef98d752d..4b9b86e9b 100644
--- a/examples/example_sdl3_sdlrenderer3/main.cpp
+++ b/examples/example_sdl3_sdlrenderer3/main.cpp
@@ -25,7 +25,7 @@
 int main(int, char**)
 {
     // Setup SDL
-    if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD))
+    if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD))
     {
         printf("Error: SDL_Init(): %s\n", SDL_GetError());
         return -1;

From d0750ee4e7d9de2605ad3f2fe60f9089dd03a4c1 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 19 Sep 2024 16:13:21 +0200
Subject: [PATCH 0377/2359] Error check: clarified that carriage returns are
 emitted by our code. Added helper default callback. Comments. (#1651)

(doesn't affect test engine hook for it as trailing \n are trimmed anyhow)
---
 imgui.cpp        | 52 ++++++++++++++++++++++++++++++++----------------
 imgui_internal.h |  8 ++++++--
 2 files changed, 41 insertions(+), 19 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index e82826792..45f6ce36d 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -79,7 +79,7 @@ CODE
 // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
 // [SECTION] ID STACK
 // [SECTION] INPUTS
-// [SECTION] ERROR CHECKING
+// [SECTION] ERROR CHECKING, STATE RECOVERY
 // [SECTION] ITEM SUBMISSION
 // [SECTION] LAYOUT
 // [SECTION] SCROLLING
@@ -7734,7 +7734,8 @@ void ImGui::PopItemFlag()
 // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
 // - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
 // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
-// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
+// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions.
+//   (as a micro-optimisation if you can avoid calling BeginDisabled(false)/EndDisabled() tens of thousands of times by doing a local check, it won't hurt)
 // - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
 // - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
 void ImGui::BeginDisabled(bool disabled)
@@ -10069,7 +10070,15 @@ bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID own
 
 
 //-----------------------------------------------------------------------------
-// [SECTION] ERROR CHECKING
+// [SECTION] ERROR CHECKING, STATE RECOVERY
+//-----------------------------------------------------------------------------
+// - DebugCheckVersionAndDataLayout() (called via IMGUI_CHECKVERSION() macros)
+// - ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
+// - ErrorCheckNewFrameSanityChecks()
+// - ErrorCheckEndFrameSanityChecks()
+// - ErrorCheckEndFrameRecover()
+// - ErrorCheckEndWindowRecover()
+// - ImGuiStackSizes
 //-----------------------------------------------------------------------------
 
 // Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
@@ -10215,6 +10224,15 @@ static void ImGui::ErrorCheckEndFrameSanityChecks()
     IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
 }
 
+// Default implementation of ImGuiErrorLogCallback that pipe errors to DebugLog: appears in tty + Tools->DebugLog
+void    ImGui::ErrorLogCallbackToDebugLog(void*, const char* fmt, ...)
+{
+    va_list args;
+    va_start(args, fmt);
+    ImGui::DebugLogV(fmt, args);
+    va_end(args);
+}
+
 // Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
 // Must be called during or before EndFrame().
 // This is generally flawed as we are not necessarily End/Popping things in the right order.
@@ -10235,12 +10253,12 @@ void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, voi
         }
         if (window->Flags & ImGuiWindowFlags_ChildWindow)
         {
-            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
+            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'\n", window->Name);
             EndChild();
         }
         else
         {
-            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
+            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'\n", window->Name);
             End();
         }
     }
@@ -10252,7 +10270,7 @@ void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, vo
     ImGuiContext& g = *GImGui;
     while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'\n", g.CurrentTable->OuterWindow->Name);
         EndTable();
     }
 
@@ -10261,32 +10279,32 @@ void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, vo
     IM_ASSERT(window != NULL);
     while (g.CurrentTabBar != NULL) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'\n", window->Name);
         EndTabBar();
     }
     while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndMultiSelect() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing EndMultiSelect() in '%s'\n", window->Name);
         EndMultiSelect();
     }
     while (window->DC.TreeDepth > 0)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'\n", window->Name);
         TreePop();
     }
     while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'\n", window->Name);
         EndGroup();
     }
     while (window->IDStack.Size > 1)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'\n", window->Name);
         PopID();
     }
     while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'\n", window->Name);
         if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
             EndDisabled();
         else
@@ -10297,27 +10315,27 @@ void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, vo
     }
     while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
+        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s\n", window->Name, GetStyleColorName(g.ColorStack.back().Col));
         PopStyleColor();
     }
     while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'\n", window->Name);
         PopItemFlag();
     }
     while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'\n", window->Name);
         PopStyleVar();
     }
     while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'\n", window->Name);
         PopFont();
     }
     while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
+        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'\n", window->Name);
         PopFocusScope();
     }
 }
diff --git a/imgui_internal.h b/imgui_internal.h
index cb4046457..14b56e8a0 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1259,6 +1259,7 @@ struct ImGuiTreeNodeStackData
     ImRect                  NavRect;    // Used for nav landing
 };
 
+// sizeof() = 18
 struct IMGUI_API ImGuiStackSizes
 {
     short   SizeOfIDStack;
@@ -3606,11 +3607,14 @@ namespace ImGui
     IMGUI_API void          GcCompactTransientWindowBuffers(ImGuiWindow* window);
     IMGUI_API void          GcAwakeTransientWindowBuffers(ImGuiWindow* window);
 
-    // Debug Tools
-    IMGUI_API void          DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size); // size >= 0 : alloc, size = -1 : free
+    // Error Checking, State Recovery
+    IMGUI_API void          ErrorLogCallbackToDebugLog(void* user_data, const char* fmt, ...);
     IMGUI_API void          ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);
     IMGUI_API void          ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);
     IMGUI_API void          ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
+
+    // Debug Tools
+    IMGUI_API void          DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size); // size >= 0 : alloc, size = -1 : free
     IMGUI_API void          DebugDrawCursorPos(ImU32 col = IM_COL32(255, 0, 0, 255));
     IMGUI_API void          DebugDrawLineExtents(ImU32 col = IM_COL32(255, 0, 0, 255));
     IMGUI_API void          DebugDrawItemRect(ImU32 col = IM_COL32(255, 0, 0, 255));

From 4aeae5d71891bffe270f4bdd181796962d183bda Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 20 Sep 2024 17:27:51 +0200
Subject: [PATCH 0378/2359] Error check: fixed build when using
 IMGUI_DISABLE_DEBUG_TOOLS.

---
 imgui.cpp | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/imgui.cpp b/imgui.cpp
index 45f6ce36d..4b9daf9d2 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -10227,10 +10227,14 @@ static void ImGui::ErrorCheckEndFrameSanityChecks()
 // Default implementation of ImGuiErrorLogCallback that pipe errors to DebugLog: appears in tty + Tools->DebugLog
 void    ImGui::ErrorLogCallbackToDebugLog(void*, const char* fmt, ...)
 {
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
     va_list args;
     va_start(args, fmt);
-    ImGui::DebugLogV(fmt, args);
+    DebugLogV(fmt, args);
     va_end(args);
+#else
+    IM_UNUSED(fmt);
+#endif
 }
 
 // Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.

From a727332e7727a912586c2ded504a0be1eabfa5dc Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 20 Sep 2024 18:08:13 +0200
Subject: [PATCH 0379/2359] Scrollbar: Shift+Click always use absolute
 positionning scroll. (#8002, #7328)

---
 docs/CHANGELOG.txt | 2 ++
 imgui_widgets.cpp  | 4 ++--
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 8c1a815e9..99ca1f134 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,8 @@ Breaking changes:
 
 Other changes:
 
+- Scrollbar: Shift+Click always use absolute positionning scroll (which was the default
+  before 1.90.8). (#8002, #7328)
 - Backends: SDL3: Update for API changes: SDL_bool removal. SDL_INIT_TIMER removal.
 
 
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index f2c5b8a0c..e50452eb6 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1000,8 +1000,8 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6
         if (g.ActiveIdIsJustActivated)
         {
             // On initial click calculate the distance between mouse and the center of the grab
-            g.ScrollbarSeekMode = (short)held_dir;
-            g.ScrollbarClickDeltaToGrabCenter = (g.ScrollbarSeekMode == 0.0f) ? clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f : 0.0f;
+            g.ScrollbarSeekMode = g.IO.KeyShift ? 0 : (short)held_dir;
+            g.ScrollbarClickDeltaToGrabCenter = (g.ScrollbarSeekMode == 0 && !g.IO.KeyShift) ? clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f : 0.0f;
         }
 
         // Apply scroll (p_scroll_v will generally point on one member of window->Scroll)

From fb410463e6a27c4486ac262c3f246543154a49e0 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 20 Sep 2024 18:40:32 +0200
Subject: [PATCH 0380/2359] Scrollbar: added io.ConfigScrollbarScrollByPage
 setting. (#8002, #7328)

---
 docs/CHANGELOG.txt | 5 +++--
 imgui.cpp          | 1 +
 imgui.h            | 1 +
 imgui_demo.cpp     | 2 ++
 imgui_internal.h   | 4 ++--
 imgui_widgets.cpp  | 7 ++++---
 6 files changed, 13 insertions(+), 7 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 99ca1f134..fac869de6 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,8 +43,9 @@ Breaking changes:
 
 Other changes:
 
-- Scrollbar: Shift+Click always use absolute positionning scroll (which was the default
-  before 1.90.8). (#8002, #7328)
+- Scrollbar: Shift+Click scroll to clicked location (pre-1.90.8 default). (#8002, #7328)
+- Scrollbar: added io.ConfigScrollbarScrollByPage setting (default to true). (#8002, #7328)
+  Set io.ConfigScrollbarScrollByPage=false to enforce always scrolling to clicked location.
 - Backends: SDL3: Update for API changes: SDL_bool removal. SDL_INIT_TIMER removal.
 
 
diff --git a/imgui.cpp b/imgui.cpp
index 4b9daf9d2..bbe78dc54 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1394,6 +1394,7 @@ ImGuiIO::ImGuiIO()
     ConfigDragClickToInputText = false;
     ConfigWindowsResizeFromEdges = true;
     ConfigWindowsMoveFromTitleBarOnly = false;
+    ConfigScrollbarScrollByPage = true;
     ConfigMemoryCompactTimer = 60.0f;
     ConfigDebugIsDebuggerPresent = false;
     ConfigDebugHighlightIdConflicts = true;
diff --git a/imgui.h b/imgui.h
index a2aab8a63..b97a4097e 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2250,6 +2250,7 @@ struct ImGuiIO
     bool        ConfigDragClickToInputText;     // = false          // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
     bool        ConfigWindowsResizeFromEdges;   // = true           // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
     bool        ConfigWindowsMoveFromTitleBarOnly; // = false       // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.
+    bool        ConfigScrollbarScrollByPage;    // = true           // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location.
     float       ConfigMemoryCompactTimer;       // = 60.0f          // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
 
     // Inputs Behaviors
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 5eb64e470..c2d110dd1 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -539,6 +539,8 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges);
             ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback.");
             ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly);
+            ImGui::Checkbox("io.ConfigScrollbarScrollByPage", &io.ConfigScrollbarScrollByPage);
+            ImGui::SameLine(); HelpMarker("Enable scrolling page by page when clicking outside the scrollbar grab.\nWhen disabled, always scroll to clicked location.\nWhen enabled, Shift+Click scrolls to clicked location.");
             ImGui::Checkbox("io.ConfigMacOSXBehaviors", &io.ConfigMacOSXBehaviors);
             ImGui::SameLine(); HelpMarker("Swap Cmd<>Ctrl keys, enable various MacOS style behaviors.");
             ImGui::Text("Also see Style->Rendering for rendering options.");
diff --git a/imgui_internal.h b/imgui_internal.h
index 14b56e8a0..664648427 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2259,8 +2259,8 @@ struct ImGuiContext
     ImGuiComboPreviewData   ComboPreviewData;
     ImRect                  WindowResizeBorderExpectedRect;     // Expected border rect, switch to relative edit if moving
     bool                    WindowResizeRelativeMode;
-    short                   ScrollbarSeekMode;                  // 0: relative, -1/+1: prev/next page.
-    float                   ScrollbarClickDeltaToGrabCenter;    // Distance between mouse and center of grab box, normalized in parent space. Use storage?
+    short                   ScrollbarSeekMode;                  // 0: scroll to clicked location, -1/+1: prev/next page.
+    float                   ScrollbarClickDeltaToGrabCenter;    // When scrolling to mouse location: distance between mouse and center of grab box, normalized in parent space.
     float                   SliderGrabClickOffset;
     float                   SliderCurrentAccum;                 // Accumulated slider delta when using navigation controls.
     bool                    SliderCurrentAccumDirty;            // Has the accumulated slider delta changed since last time we tried to apply it?
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index e50452eb6..91328d211 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -999,9 +999,10 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6
         const int held_dir = (clicked_v_norm < grab_v_norm) ? -1 : (clicked_v_norm > grab_v_norm + grab_h_norm) ? +1 : 0;
         if (g.ActiveIdIsJustActivated)
         {
-            // On initial click calculate the distance between mouse and the center of the grab
-            g.ScrollbarSeekMode = g.IO.KeyShift ? 0 : (short)held_dir;
-            g.ScrollbarClickDeltaToGrabCenter = (g.ScrollbarSeekMode == 0 && !g.IO.KeyShift) ? clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f : 0.0f;
+            // On initial click when held_dir == 0 (clicked over grab): calculate the distance between mouse and the center of the grab
+            const bool scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false || g.IO.KeyShift || held_dir == 0);
+            g.ScrollbarSeekMode = scroll_to_clicked_location ? 0 : (short)held_dir;
+            g.ScrollbarClickDeltaToGrabCenter = (held_dir == 0 && !g.IO.KeyShift) ? clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f : 0.0f;
         }
 
         // Apply scroll (p_scroll_v will generally point on one member of window->Scroll)

From 7f81fbc54261cd8579e3db8d2c5c7a0155dad58d Mon Sep 17 00:00:00 2001
From: Mark Sibly 
Date: Sun, 22 Sep 2024 16:05:28 +1200
Subject: [PATCH 0381/2359] Backends: WGPU: Fix new WGPUStringView breaks
 shader compilation. (#8009, #8010)

---
 backends/imgui_impl_wgpu.cpp | 6 ++++--
 docs/CHANGELOG.txt           | 3 ++-
 2 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index 503ac8efd..4109e392e 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -257,13 +257,15 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c
 {
     ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
 
-    WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+	WGPUShaderSourceWGSL wgsl_desc = {};
     wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
+	wgsl_desc.code = { wgsl_source, WGPU_STRLEN };
 #else
+	WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
     wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
+	wgsl_desc.code = wgsl_source;
 #endif
-    wgsl_desc.code = wgsl_source;
 
     WGPUShaderModuleDescriptor desc = {};
     desc.nextInChain = reinterpret_cast(&wgsl_desc);
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index fac869de6..1d7232d9c 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -47,7 +47,8 @@ Other changes:
 - Scrollbar: added io.ConfigScrollbarScrollByPage setting (default to true). (#8002, #7328)
   Set io.ConfigScrollbarScrollByPage=false to enforce always scrolling to clicked location.
 - Backends: SDL3: Update for API changes: SDL_bool removal. SDL_INIT_TIMER removal.
-
+- Backends: WebGPU: Fixed DAWN api change using WGPUStringView in WGPUShaderSourceWGSL.
+  (#8009, #8010) [@blitz-research]
 
 -----------------------------------------------------------------------
  VERSION 1.91.2 (Released 2024-09-19)

From bc77041b57893fb3d04d4df503b483bcc3884e3a Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 23 Sep 2024 16:44:16 +0200
Subject: [PATCH 0382/2359] Error Handling: fixed an issue
 ErrorCheckEndWindowRecover() when aborting in a child inside a tab bar.
 (#1651)

---
 imgui.cpp         | 5 ++---
 imgui_internal.h  | 3 ++-
 imgui_widgets.cpp | 1 +
 3 files changed, 5 insertions(+), 4 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index bbe78dc54..ae614f95d 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -10242,7 +10242,6 @@ void    ImGui::ErrorLogCallbackToDebugLog(void*, const char* fmt, ...)
 // Must be called during or before EndFrame().
 // This is generally flawed as we are not necessarily End/Popping things in the right order.
 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
-// FIXME: Can't recover from interleaved BeginTabBar/Begin
 void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
 {
     // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
@@ -10273,7 +10272,7 @@ void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, voi
 void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
 {
     ImGuiContext& g = *GImGui;
-    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
+    while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
     {
         if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'\n", g.CurrentTable->OuterWindow->Name);
         EndTable();
@@ -10282,7 +10281,7 @@ void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, vo
     ImGuiWindow* window = g.CurrentWindow;
     ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
     IM_ASSERT(window != NULL);
-    while (g.CurrentTabBar != NULL) //-V1044
+    while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
     {
         if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'\n", window->Name);
         EndTabBar();
diff --git a/imgui_internal.h b/imgui_internal.h
index 664648427..013e29b25 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2762,9 +2762,10 @@ struct ImGuiTabItem
     ImGuiTabItem()      { memset(this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; }
 };
 
-// Storage for a tab bar (sizeof() 152 bytes)
+// Storage for a tab bar (sizeof() 160 bytes)
 struct IMGUI_API ImGuiTabBar
 {
+    ImGuiWindow*        Window;
     ImVector Tabs;
     ImGuiTabBarFlags    Flags;
     ImGuiID             ID;                     // Zero for tab-bars used by docking
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 91328d211..59a912dbd 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -9146,6 +9146,7 @@ bool    ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG
     // Add to stack
     g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar));
     g.CurrentTabBar = tab_bar;
+    tab_bar->Window = window;
 
     // Append with multiple BeginTabBar()/EndTabBar() pairs.
     tab_bar->BackupCursorPos = window->DC.CursorPos;

From 44a73be6eaf477b5c9a8b6957b789df6fa191a3e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 24 Sep 2024 20:22:16 +0200
Subject: [PATCH 0383/2359] TestEngine: log calls don't need testing hook
 active.

Docs: tweak comments on BeginDisabled(false)/EndDisabled() pairs.
---
 imgui.cpp        | 5 ++---
 imgui.h          | 2 +-
 imgui_internal.h | 2 +-
 3 files changed, 4 insertions(+), 5 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index ae614f95d..cc0be6992 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -7735,9 +7735,8 @@ void ImGui::PopItemFlag()
 // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
 // - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
 // - Feedback welcome at https://github.com/ocornut/imgui/issues/211
-// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions.
-//   (as a micro-optimisation if you can avoid calling BeginDisabled(false)/EndDisabled() tens of thousands of times by doing a local check, it won't hurt)
-// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
+// - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions.
+//   (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls)
 // - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags_Disabled) is currently NOT SUPPORTED.
 void ImGui::BeginDisabled(bool disabled)
 {
diff --git a/imgui.h b/imgui.h
index b97a4097e..f03b7aa1d 100644
--- a/imgui.h
+++ b/imgui.h
@@ -888,7 +888,7 @@ namespace ImGui
     // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors)
     // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
     // - Tooltips windows by exception are opted out of disabling.
-    // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
+    // - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls)
     IMGUI_API void          BeginDisabled(bool disabled = true);
     IMGUI_API void          EndDisabled();
 
diff --git a/imgui_internal.h b/imgui_internal.h
index 013e29b25..226d545ee 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -3703,7 +3703,7 @@ extern const char*  ImGuiTestEngine_FindItemDebugLabel(ImGuiContext* ctx, ImGuiI
 // In IMGUI_VERSION_NUM >= 18934: changed IMGUI_TEST_ENGINE_ITEM_ADD(bb,id) to IMGUI_TEST_ENGINE_ITEM_ADD(id,bb,item_data);
 #define IMGUI_TEST_ENGINE_ITEM_ADD(_ID,_BB,_ITEM_DATA)      if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _ID, _BB, _ITEM_DATA)    // Register item bounding box
 #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS)      if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS)    // Register item label and status flags (optional)
-#define IMGUI_TEST_ENGINE_LOG(_FMT,...)                     if (g.TestEngineHookItems) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__)           // Custom log entry from user land into test log
+#define IMGUI_TEST_ENGINE_LOG(_FMT,...)                     ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__)                                      // Custom log entry from user land into test log
 #else
 #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID)                 ((void)0)
 #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS)      ((void)g)

From 726aad8e0884b1502ebceb62254a5de73609cd2f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 24 Sep 2024 20:24:51 +0200
Subject: [PATCH 0384/2359] Refactor: moved ImGuiContext contructor to
 imgui.cpp

---
 imgui.cpp        | 205 +++++++++++++++++++++++++++++++++++++++++++++++
 imgui_internal.h | 205 +----------------------------------------------
 2 files changed, 206 insertions(+), 204 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index cc0be6992..a0683e671 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3799,6 +3799,211 @@ static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
     { ImGuiLocKey_CopyLink,             "Copy Link###CopyLink"                  },
 };
 
+ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
+{
+    IO.Ctx = this;
+    InputTextState.Ctx = this;
+
+    Initialized = false;
+    FontAtlasOwnedByContext = shared_font_atlas ? false : true;
+    Font = NULL;
+    FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f;
+    IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
+    Time = 0.0f;
+    FrameCount = 0;
+    FrameCountEnded = FrameCountRendered = -1;
+    WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false;
+    GcCompactAll = false;
+    TestEngineHookItems = false;
+    TestEngine = NULL;
+    memset(ContextName, 0, sizeof(ContextName));
+
+    InputEventsNextMouseSource = ImGuiMouseSource_Mouse;
+    InputEventsNextEventId = 1;
+
+    WindowsActiveCount = 0;
+    CurrentWindow = NULL;
+    HoveredWindow = NULL;
+    HoveredWindowUnderMovingWindow = NULL;
+    HoveredWindowBeforeClear = NULL;
+    MovingWindow = NULL;
+    WheelingWindow = NULL;
+    WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
+    WheelingWindowReleaseTimer = 0.0f;
+
+    DebugDrawIdConflicts = 0;
+    DebugHookIdInfo = 0;
+    HoveredId = HoveredIdPreviousFrame = 0;
+    HoveredIdPreviousFrameItemCount = 0;
+    HoveredIdAllowOverlap = false;
+    HoveredIdIsDisabled = false;
+    HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
+    ItemUnclipByLog = false;
+    ActiveId = 0;
+    ActiveIdIsAlive = 0;
+    ActiveIdTimer = 0.0f;
+    ActiveIdIsJustActivated = false;
+    ActiveIdAllowOverlap = false;
+    ActiveIdNoClearOnFocusLoss = false;
+    ActiveIdHasBeenPressedBefore = false;
+    ActiveIdHasBeenEditedBefore = false;
+    ActiveIdHasBeenEditedThisFrame = false;
+    ActiveIdFromShortcut = false;
+    ActiveIdClickOffset = ImVec2(-1, -1);
+    ActiveIdWindow = NULL;
+    ActiveIdSource = ImGuiInputSource_None;
+    ActiveIdMouseButton = -1;
+    ActiveIdPreviousFrame = 0;
+    ActiveIdPreviousFrameIsAlive = false;
+    ActiveIdPreviousFrameHasBeenEditedBefore = false;
+    ActiveIdPreviousFrameWindow = NULL;
+    LastActiveId = 0;
+    LastActiveIdTimer = 0.0f;
+
+    LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0;
+
+    ActiveIdUsingNavDirMask = 0x00;
+    ActiveIdUsingAllKeyboardKeys = false;
+
+    CurrentFocusScopeId = 0;
+    CurrentItemFlags = ImGuiItemFlags_None;
+    DebugShowGroupRects = false;
+
+    NavWindow = NULL;
+    NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
+    NavLayer = ImGuiNavLayer_Main;
+    NavNextActivateId = 0;
+    NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
+    NavHighlightActivatedId = 0;
+    NavHighlightActivatedTimer = 0.0f;
+    NavInputSource = ImGuiInputSource_Keyboard;
+    NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
+    NavIdIsAlive = false;
+    NavMousePosDirty = false;
+    NavDisableHighlight = true;
+    NavDisableMouseHover = false;
+
+    NavAnyRequest = false;
+    NavInitRequest = false;
+    NavInitRequestFromMove = false;
+    NavMoveSubmitted = false;
+    NavMoveScoringItems = false;
+    NavMoveForwardToNextFrame = false;
+    NavMoveFlags = ImGuiNavMoveFlags_None;
+    NavMoveScrollFlags = ImGuiScrollFlags_None;
+    NavMoveKeyMods = ImGuiMod_None;
+    NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;
+    NavScoringDebugCount = 0;
+    NavTabbingDir = 0;
+    NavTabbingCounter = 0;
+
+    NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0;
+    NavJustMovedToKeyMods = ImGuiMod_None;
+    NavJustMovedToIsTabbing = false;
+    NavJustMovedToHasSelectionData = false;
+
+    // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
+    // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
+    ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
+    ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
+    NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
+    NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
+    NavWindowingToggleLayer = false;
+    NavWindowingToggleKey = ImGuiKey_None;
+
+    DimBgRatio = 0.0f;
+
+    DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
+    DragDropSourceFlags = ImGuiDragDropFlags_None;
+    DragDropSourceFrameCount = -1;
+    DragDropMouseButton = -1;
+    DragDropTargetId = 0;
+    DragDropAcceptFlags = ImGuiDragDropFlags_None;
+    DragDropAcceptIdCurrRectSurface = 0.0f;
+    DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
+    DragDropAcceptFrameCount = -1;
+    DragDropHoldJustPressedId = 0;
+    memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
+
+    ClipperTempDataStacked = 0;
+
+    CurrentTable = NULL;
+    TablesTempDataStacked = 0;
+    CurrentTabBar = NULL;
+    CurrentMultiSelect = NULL;
+    MultiSelectTempDataStacked = 0;
+
+    HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0;
+    HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f;
+
+    MouseCursor = ImGuiMouseCursor_Arrow;
+    MouseStationaryTimer = 0.0f;
+
+    TempInputId = 0;
+    memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue));
+    BeginMenuDepth = BeginComboDepth = 0;
+    ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_;
+    ColorEditCurrentID = ColorEditSavedID = 0;
+    ColorEditSavedHue = ColorEditSavedSat = 0.0f;
+    ColorEditSavedColor = 0;
+    WindowResizeRelativeMode = false;
+    ScrollbarSeekMode = 0;
+    ScrollbarClickDeltaToGrabCenter = 0.0f;
+    SliderGrabClickOffset = 0.0f;
+    SliderCurrentAccum = 0.0f;
+    SliderCurrentAccumDirty = false;
+    DragCurrentAccumDirty = false;
+    DragCurrentAccum = 0.0f;
+    DragSpeedDefaultRatio = 1.0f / 100.0f;
+    DisabledAlphaBackup = 0.0f;
+    DisabledStackSize = 0;
+    LockMarkEdited = 0;
+    TooltipOverrideCount = 0;
+
+    PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
+    PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
+
+    SettingsLoaded = false;
+    SettingsDirtyTimer = 0.0f;
+    HookIdNext = 0;
+
+    memset(LocalizationTable, 0, sizeof(LocalizationTable));
+
+    LogEnabled = false;
+    LogType = ImGuiLogType_None;
+    LogNextPrefix = LogNextSuffix = NULL;
+    LogFile = NULL;
+    LogLinePosY = FLT_MAX;
+    LogLineFirstItem = false;
+    LogDepthRef = 0;
+    LogDepthToExpand = LogDepthToExpandDefault = 2;
+
+    DebugLogFlags = ImGuiDebugLogFlags_OutputToTTY;
+    DebugLocateId = 0;
+    DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
+    DebugLogAutoDisableFrames = 0;
+    DebugLocateFrames = 0;
+    DebugBeginReturnValueCullDepth = -1;
+    DebugItemPickerActive = false;
+    DebugItemPickerMouseButton = ImGuiMouseButton_Left;
+    DebugItemPickerBreakId = 0;
+    DebugFlashStyleColorTime = 0.0f;
+    DebugFlashStyleColorIdx = ImGuiCol_COUNT;
+
+    // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations
+    DebugBreakInWindow = 0;
+    DebugBreakInTable = 0;
+    DebugBreakInLocateId = false;
+    DebugBreakKeyChord = ImGuiKey_Pause;
+    DebugBreakInShortcutRouting = ImGuiKey_None;
+
+    memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
+    FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;
+    FramerateSecPerFrameAccum = 0.0f;
+    WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
+    memset(TempKeychordName, 0, sizeof(TempKeychordName));
+}
+
 void ImGui::Initialize()
 {
     ImGuiContext& g = *GImGui;
diff --git a/imgui_internal.h b/imgui_internal.h
index 226d545ee..e6ebec2c6 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2336,210 +2336,7 @@ struct ImGuiContext
     ImVector          TempBuffer;                         // Temporary text buffer
     char                    TempKeychordName[64];
 
-    ImGuiContext(ImFontAtlas* shared_font_atlas)
-    {
-        IO.Ctx = this;
-        InputTextState.Ctx = this;
-
-        Initialized = false;
-        FontAtlasOwnedByContext = shared_font_atlas ? false : true;
-        Font = NULL;
-        FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f;
-        IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
-        Time = 0.0f;
-        FrameCount = 0;
-        FrameCountEnded = FrameCountRendered = -1;
-        WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false;
-        GcCompactAll = false;
-        TestEngineHookItems = false;
-        TestEngine = NULL;
-        memset(ContextName, 0, sizeof(ContextName));
-
-        InputEventsNextMouseSource = ImGuiMouseSource_Mouse;
-        InputEventsNextEventId = 1;
-
-        WindowsActiveCount = 0;
-        CurrentWindow = NULL;
-        HoveredWindow = NULL;
-        HoveredWindowUnderMovingWindow = NULL;
-        HoveredWindowBeforeClear = NULL;
-        MovingWindow = NULL;
-        WheelingWindow = NULL;
-        WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1;
-        WheelingWindowReleaseTimer = 0.0f;
-
-        DebugDrawIdConflicts = 0;
-        DebugHookIdInfo = 0;
-        HoveredId = HoveredIdPreviousFrame = 0;
-        HoveredIdPreviousFrameItemCount = 0;
-        HoveredIdAllowOverlap = false;
-        HoveredIdIsDisabled = false;
-        HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
-        ItemUnclipByLog = false;
-        ActiveId = 0;
-        ActiveIdIsAlive = 0;
-        ActiveIdTimer = 0.0f;
-        ActiveIdIsJustActivated = false;
-        ActiveIdAllowOverlap = false;
-        ActiveIdNoClearOnFocusLoss = false;
-        ActiveIdHasBeenPressedBefore = false;
-        ActiveIdHasBeenEditedBefore = false;
-        ActiveIdHasBeenEditedThisFrame = false;
-        ActiveIdFromShortcut = false;
-        ActiveIdClickOffset = ImVec2(-1, -1);
-        ActiveIdWindow = NULL;
-        ActiveIdSource = ImGuiInputSource_None;
-        ActiveIdMouseButton = -1;
-        ActiveIdPreviousFrame = 0;
-        ActiveIdPreviousFrameIsAlive = false;
-        ActiveIdPreviousFrameHasBeenEditedBefore = false;
-        ActiveIdPreviousFrameWindow = NULL;
-        LastActiveId = 0;
-        LastActiveIdTimer = 0.0f;
-
-        LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0;
-
-        ActiveIdUsingNavDirMask = 0x00;
-        ActiveIdUsingAllKeyboardKeys = false;
-
-        CurrentFocusScopeId = 0;
-        CurrentItemFlags = ImGuiItemFlags_None;
-        DebugShowGroupRects = false;
-
-        NavWindow = NULL;
-        NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
-        NavLayer = ImGuiNavLayer_Main;
-        NavNextActivateId = 0;
-        NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
-        NavHighlightActivatedId = 0;
-        NavHighlightActivatedTimer = 0.0f;
-        NavInputSource = ImGuiInputSource_Keyboard;
-        NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
-        NavIdIsAlive = false;
-        NavMousePosDirty = false;
-        NavDisableHighlight = true;
-        NavDisableMouseHover = false;
-
-        NavAnyRequest = false;
-        NavInitRequest = false;
-        NavInitRequestFromMove = false;
-        NavMoveSubmitted = false;
-        NavMoveScoringItems = false;
-        NavMoveForwardToNextFrame = false;
-        NavMoveFlags = ImGuiNavMoveFlags_None;
-        NavMoveScrollFlags = ImGuiScrollFlags_None;
-        NavMoveKeyMods = ImGuiMod_None;
-        NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;
-        NavScoringDebugCount = 0;
-        NavTabbingDir = 0;
-        NavTabbingCounter = 0;
-
-        NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0;
-        NavJustMovedToKeyMods = ImGuiMod_None;
-        NavJustMovedToIsTabbing = false;
-        NavJustMovedToHasSelectionData = false;
-
-        // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac...
-        // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this..
-        ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab);
-        ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab);
-        NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
-        NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
-        NavWindowingToggleLayer = false;
-        NavWindowingToggleKey = ImGuiKey_None;
-
-        DimBgRatio = 0.0f;
-
-        DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
-        DragDropSourceFlags = ImGuiDragDropFlags_None;
-        DragDropSourceFrameCount = -1;
-        DragDropMouseButton = -1;
-        DragDropTargetId = 0;
-        DragDropAcceptFlags = ImGuiDragDropFlags_None;
-        DragDropAcceptIdCurrRectSurface = 0.0f;
-        DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
-        DragDropAcceptFrameCount = -1;
-        DragDropHoldJustPressedId = 0;
-        memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
-
-        ClipperTempDataStacked = 0;
-
-        CurrentTable = NULL;
-        TablesTempDataStacked = 0;
-        CurrentTabBar = NULL;
-        CurrentMultiSelect = NULL;
-        MultiSelectTempDataStacked = 0;
-
-        HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0;
-        HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f;
-
-        MouseCursor = ImGuiMouseCursor_Arrow;
-        MouseStationaryTimer = 0.0f;
-
-        TempInputId = 0;
-        memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue));
-        BeginMenuDepth = BeginComboDepth = 0;
-        ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_;
-        ColorEditCurrentID = ColorEditSavedID = 0;
-        ColorEditSavedHue = ColorEditSavedSat = 0.0f;
-        ColorEditSavedColor = 0;
-        WindowResizeRelativeMode = false;
-        ScrollbarSeekMode = 0;
-        ScrollbarClickDeltaToGrabCenter = 0.0f;
-        SliderGrabClickOffset = 0.0f;
-        SliderCurrentAccum = 0.0f;
-        SliderCurrentAccumDirty = false;
-        DragCurrentAccumDirty = false;
-        DragCurrentAccum = 0.0f;
-        DragSpeedDefaultRatio = 1.0f / 100.0f;
-        DisabledAlphaBackup = 0.0f;
-        DisabledStackSize = 0;
-        LockMarkEdited = 0;
-        TooltipOverrideCount = 0;
-
-        PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
-        PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
-
-        SettingsLoaded = false;
-        SettingsDirtyTimer = 0.0f;
-        HookIdNext = 0;
-
-        memset(LocalizationTable, 0, sizeof(LocalizationTable));
-
-        LogEnabled = false;
-        LogType = ImGuiLogType_None;
-        LogNextPrefix = LogNextSuffix = NULL;
-        LogFile = NULL;
-        LogLinePosY = FLT_MAX;
-        LogLineFirstItem = false;
-        LogDepthRef = 0;
-        LogDepthToExpand = LogDepthToExpandDefault = 2;
-
-        DebugLogFlags = ImGuiDebugLogFlags_OutputToTTY;
-        DebugLocateId = 0;
-        DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
-        DebugLogAutoDisableFrames = 0;
-        DebugLocateFrames = 0;
-        DebugBeginReturnValueCullDepth = -1;
-        DebugItemPickerActive = false;
-        DebugItemPickerMouseButton = ImGuiMouseButton_Left;
-        DebugItemPickerBreakId = 0;
-        DebugFlashStyleColorTime = 0.0f;
-        DebugFlashStyleColorIdx = ImGuiCol_COUNT;
-
-        // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations
-        DebugBreakInWindow = 0;
-        DebugBreakInTable = 0;
-        DebugBreakInLocateId = false;
-        DebugBreakKeyChord = ImGuiKey_Pause;
-        DebugBreakInShortcutRouting = ImGuiKey_None;
-
-        memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
-        FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;
-        FramerateSecPerFrameAccum = 0.0f;
-        WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
-        memset(TempKeychordName, 0, sizeof(TempKeychordName));
-    }
+    ImGuiContext(ImFontAtlas* shared_font_atlas);
 };
 
 //-----------------------------------------------------------------------------

From d0107f5da2343004cd0a9b23402d8620b8387e03 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 24 Sep 2024 21:53:25 +0200
Subject: [PATCH 0385/2359] Internals: misc tweaks to facilitate branch
 merging.

---
 imgui_internal.h | 43 +++++++++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 18 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index e6ebec2c6..93decabaf 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -28,6 +28,7 @@ Index of this file:
 // [SECTION] Viewport support
 // [SECTION] Settings support
 // [SECTION] Localization support
+// [SECTION] Error handling, State recovery support
 // [SECTION] Metrics, Debug tools
 // [SECTION] Generic context hooks
 // [SECTION] ImGuiContext (main imgui context)
@@ -173,7 +174,7 @@ typedef int ImGuiLayoutType;            // -> enum ImGuiLayoutType_         // E
 // Flags
 typedef int ImGuiActivateFlags;         // -> enum ImGuiActivateFlags_      // Flags: for navigation/focus function (will be for ActivateItem() later)
 typedef int ImGuiDebugLogFlags;         // -> enum ImGuiDebugLogFlags_      // Flags: for ShowDebugLogWindow(), g.DebugLogFlags
-typedef int ImGuiFocusRequestFlags;     // -> enum ImGuiFocusRequestFlags_  // Flags: for FocusWindow();
+typedef int ImGuiFocusRequestFlags;     // -> enum ImGuiFocusRequestFlags_  // Flags: for FocusWindow()
 typedef int ImGuiItemStatusFlags;       // -> enum ImGuiItemStatusFlags_    // Flags: for g.LastItemData.StatusFlags
 typedef int ImGuiOldColumnFlags;        // -> enum ImGuiOldColumnFlags_     // Flags: for BeginColumns()
 typedef int ImGuiNavHighlightFlags;     // -> enum ImGuiNavHighlightFlags_  // Flags: for RenderNavHighlight()
@@ -187,8 +188,6 @@ typedef int ImGuiTooltipFlags;          // -> enum ImGuiTooltipFlags_       // F
 typedef int ImGuiTypingSelectFlags;     // -> enum ImGuiTypingSelectFlags_  // Flags: for GetTypingSelectRequest()
 typedef int ImGuiWindowRefreshFlags;    // -> enum ImGuiWindowRefreshFlags_ // Flags: for SetNextWindowRefreshPolicy()
 
-typedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...);
-
 //-----------------------------------------------------------------------------
 // [SECTION] Context pointer
 // See implementation of this variable in imgui.cpp for comments and details.
@@ -239,12 +238,6 @@ extern IMGUI_API ImGuiContext* GImGui;  // Current implicit context pointer
 #define IM_ASSERT_PARANOID(_EXPR)
 #endif
 
-// Error handling
-// Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults.
-#ifndef IM_ASSERT_USER_ERROR
-#define IM_ASSERT_USER_ERROR(_EXP,_MSG) IM_ASSERT((_EXP) && _MSG)   // Recoverable User Error
-#endif
-
 // Misc Macros
 #define IM_PI                           3.14159265358979323846f
 #ifdef _WIN32
@@ -1886,6 +1879,17 @@ struct ImGuiLocEntry
     const char*     Text;
 };
 
+//-----------------------------------------------------------------------------
+// [SECTION] Error handling, State recovery support
+//-----------------------------------------------------------------------------
+
+// Macros used by Recoverable Error handling
+// Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults.
+#ifndef IM_ASSERT_USER_ERROR
+#define IM_ASSERT_USER_ERROR(_EXPR,_MSG)    IM_ASSERT((_EXPR) && _MSG)
+#endif
+
+typedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...);
 
 //-----------------------------------------------------------------------------
 // [SECTION] Metrics, Debug Tools
@@ -1895,16 +1899,19 @@ enum ImGuiDebugLogFlags_
 {
     // Event types
     ImGuiDebugLogFlags_None                 = 0,
-    ImGuiDebugLogFlags_EventActiveId        = 1 << 0,
-    ImGuiDebugLogFlags_EventFocus           = 1 << 1,
-    ImGuiDebugLogFlags_EventPopup           = 1 << 2,
-    ImGuiDebugLogFlags_EventNav             = 1 << 3,
-    ImGuiDebugLogFlags_EventClipper         = 1 << 4,
-    ImGuiDebugLogFlags_EventSelection       = 1 << 5,
-    ImGuiDebugLogFlags_EventIO              = 1 << 6,
-    ImGuiDebugLogFlags_EventInputRouting    = 1 << 7,
+    ImGuiDebugLogFlags_EventError           = 1 << 0,   // Error submitted by IM_ASSERT_USER_ERROR()
+    ImGuiDebugLogFlags_EventActiveId        = 1 << 1,
+    ImGuiDebugLogFlags_EventFocus           = 1 << 2,
+    ImGuiDebugLogFlags_EventPopup           = 1 << 3,
+    ImGuiDebugLogFlags_EventNav             = 1 << 4,
+    ImGuiDebugLogFlags_EventClipper         = 1 << 5,
+    ImGuiDebugLogFlags_EventSelection       = 1 << 6,
+    ImGuiDebugLogFlags_EventIO              = 1 << 7,
+    ImGuiDebugLogFlags_EventInputRouting    = 1 << 8,
+    ImGuiDebugLogFlags_EventDocking         = 1 << 9,   // Unused in this branch
+    ImGuiDebugLogFlags_EventViewport        = 1 << 10,  // Unused in this branch
 
-    ImGuiDebugLogFlags_EventMask_           = ImGuiDebugLogFlags_EventActiveId  | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventInputRouting,
+    ImGuiDebugLogFlags_EventMask_           = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport,
     ImGuiDebugLogFlags_OutputToTTY          = 1 << 20,  // Also send output to TTY
     ImGuiDebugLogFlags_OutputToTestEngine   = 1 << 21,  // Also send output to Test Engine
 };

From 9644c5118357cd0c0ba0ea957b3328ff49cf6260 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 25 Sep 2024 18:59:08 +0200
Subject: [PATCH 0386/2359] Error handling: rework error tooltip logic (will be
 reused by upcoming feature). (#7961, #7669, #1651)

+ Comments
---
 imgui.cpp         | 85 ++++++++++++++++++++++++++++++++++-------------
 imgui_internal.h  |  9 ++++-
 imgui_widgets.cpp |  8 +++++
 3 files changed, 77 insertions(+), 25 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index a0683e671..3833109bb 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3978,6 +3978,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     LogDepthRef = 0;
     LogDepthToExpand = LogDepthToExpandDefault = 2;
 
+    DebugDrawIdConflictsCount = 0;
     DebugLogFlags = ImGuiDebugLogFlags_OutputToTTY;
     DebugLocateId = 0;
     DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
@@ -5054,7 +5055,8 @@ void ImGui::NewFrame()
         KeepAliveID(g.DragDropPayload.SourceId);
 
     // [DEBUG]
-    g.DebugDrawIdConflicts = 0;
+    if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL
+        g.DebugDrawIdConflicts = 0;
     if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1)
         g.DebugDrawIdConflicts = g.HoveredIdPreviousFrame;
 
@@ -5461,32 +5463,10 @@ void ImGui::EndFrame()
         return;
     IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
 
-#ifndef IMGUI_DISABLE_DEBUG_TOOLS
-    if (g.DebugDrawIdConflicts != 0)
-    {
-        PushStyleColor(ImGuiCol_PopupBg, ImLerp(g.Style.Colors[ImGuiCol_PopupBg], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.10f));
-        if (g.DebugItemPickerActive == false && BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
-        {
-            SeparatorText("MESSAGE FROM DEAR IMGUI");
-            Text("Programmer error: %d visible items with conflicting ID!", g.HoveredIdPreviousFrameItemCount);
-            BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
-            BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
-            BulletText("Press F1 to open \"FAQ -> About the ID Stack System\" and read details.");
-            BulletText("Press CTRL+P to activate Item Picker and debug-break in item call-stack.");
-            BulletText("Set io.ConfigDebugDetectIdConflicts=false to disable this warning in non-programmers builds.");
-            EndTooltip();
-        }
-        PopStyleColor();
-        if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_P, ImGuiInputFlags_RouteGlobal))
-            DebugStartItemPicker();
-        if (Shortcut(ImGuiKey_F1, ImGuiInputFlags_RouteGlobal) && g.PlatformIO.Platform_OpenInShellFn != NULL)
-            g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
-    }
-#endif
-
     CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
 
     ErrorCheckEndFrameSanityChecks();
+    ErrorCheckEndFrameFinalizeErrorTooltip();
 
     // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
     ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
@@ -10587,6 +10567,63 @@ void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
     IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
 }
 
+void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
+{
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
+    ImGuiContext& g = *GImGui;
+    if (g.DebugDrawIdConflicts != 0 && g.IO.KeyCtrl == false)
+        g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount;
+    if (g.DebugDrawIdConflicts != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip())
+    {
+        Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
+        BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
+        BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
+        BulletText("Set io.ConfigDebugDetectIdConflicts=false to disable this warning in non-programmers builds.");
+        Separator();
+        Text("(Hold CTRL and: use");
+        SameLine();
+        if (SmallButton("Item Picker"))
+            DebugStartItemPicker();
+        SameLine();
+        Text("to break in item call-stack, or");
+        SameLine();
+        if (SmallButton("Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL)
+            g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
+        EndErrorTooltip();
+    }
+#endif
+}
+
+// Pseudo-tooltip. Follow mouse until CTRL is held. When CTRL is held we lock position, allowing to click it.
+bool ImGui::BeginErrorTooltip()
+{
+    ImGuiContext& g = *GImGui;
+    ImGuiWindow* window = FindWindowByName("##Tooltip_Error");
+    const bool use_locked_pos = (g.IO.KeyCtrl && window && window->WasActive);
+    PushStyleColor(ImGuiCol_PopupBg, ImLerp(g.Style.Colors[ImGuiCol_PopupBg], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.15f));
+    if (use_locked_pos)
+        SetNextWindowPos(g.ErrorTooltipLockedPos);
+    bool is_visible = Begin("##Tooltip_Error", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
+    PopStyleColor();
+    if (is_visible && g.CurrentWindow->BeginCount == 1)
+    {
+        SeparatorText("MESSAGE FROM DEAR IMGUI");
+        BringWindowToDisplayFront(g.CurrentWindow);
+        BringWindowToFocusFront(g.CurrentWindow);
+        g.ErrorTooltipLockedPos = GetWindowPos();
+    }
+    else if (!is_visible)
+    {
+        End();
+    }
+    return is_visible;
+}
+
+void ImGui::EndErrorTooltip()
+{
+    End();
+}
+
 //-----------------------------------------------------------------------------
 // [SECTION] ITEM SUBMISSION
 //-----------------------------------------------------------------------------
diff --git a/imgui_internal.h b/imgui_internal.h
index 93decabaf..37c182b55 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2312,8 +2312,12 @@ struct ImGuiContext
     int                     LogDepthToExpand;
     int                     LogDepthToExpandDefault;            // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call.
 
+    // Error handling
+    ImVec2                  ErrorTooltipLockedPos;
+
     // Debug Tools
     // (some of the highly frequently used data are interleaved in other structures above: DebugBreakXXX fields, DebugHookIdInfo, DebugLocateId etc.)
+    int                     DebugDrawIdConflictsCount;          // Locked count (preserved when holding CTRL)
     ImGuiDebugLogFlags      DebugLogFlags;
     ImGuiTextBuffer         DebugLogBuf;
     ImGuiTextIndex          DebugLogIndex;
@@ -3412,11 +3416,14 @@ namespace ImGui
     IMGUI_API void          GcCompactTransientWindowBuffers(ImGuiWindow* window);
     IMGUI_API void          GcAwakeTransientWindowBuffers(ImGuiWindow* window);
 
-    // Error Checking, State Recovery
+    // Error handling, State Recovery
     IMGUI_API void          ErrorLogCallbackToDebugLog(void* user_data, const char* fmt, ...);
     IMGUI_API void          ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);
     IMGUI_API void          ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);
     IMGUI_API void          ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
+    IMGUI_API void          ErrorCheckEndFrameFinalizeErrorTooltip();
+    IMGUI_API bool          BeginErrorTooltip();
+    IMGUI_API void          EndErrorTooltip();
 
     // Debug Tools
     IMGUI_API void          DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size); // size >= 0 : alloc, size = -1 : free
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 59a912dbd..5641134ff 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -7391,6 +7391,7 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flag
 static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io)
 {
     ImGuiContext& g = *GImGui;
+    IM_UNUSED(function);
     for (const ImGuiSelectionRequest& req : io->Requests)
     {
         if (req.Type == ImGuiSelectionRequestType_SetAll)    IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetAll %d (= %s)\n", function, req.Selected, req.Selected ? "SelectAll" : "Clear");
@@ -8157,6 +8158,13 @@ void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
 //-------------------------------------------------------------------------
 
 // This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
+// This handle some subtleties with capturing info from the label, but for 99% uses it could essentially be rewritten as:
+//    if (ImGui::BeginChild("...", ImVec2(ImGui::CalcItemWidth(), ImGui::GetTextLineHeight() * 7.5f), ImGuiChildFlags_FrameStyle))
+//        { .... }
+//    ImGui::EndChild();
+//    ImGui::SameLine();
+//    ImGui::AlignTextToFramePadding();
+//    ImGui::Text("Label");
 // 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.25 * item_height).
 bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg)

From 797101a882b3eebef6815685cb521e47b15b4255 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 26 Sep 2024 14:58:56 +0200
Subject: [PATCH 0387/2359] Windows: BeginChild(): made it possible to call
 SetNextWindowSize() on a child window using
 ImGuiChildFlags_ResizeX/ImGuiChildFlags_ResizeY. (#1710, #8020)

---
 docs/CHANGELOG.txt |  3 +++
 imgui.cpp          | 27 ++++++++++++++++++++++-----
 imgui.h            |  2 +-
 imgui_demo.cpp     |  3 +++
 4 files changed, 29 insertions(+), 6 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 1d7232d9c..c7c0a47e2 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,9 @@ Breaking changes:
 
 Other changes:
 
+- Windows: BeginChild(): made it possible to call SetNextWindowSize() on a child window
+  using ImGuiChildFlags_ResizeX,ImGuiChildFlags_ResizeY in order to override its current
+  size. (#1710, #8020)
 - Scrollbar: Shift+Click scroll to clicked location (pre-1.90.8 default). (#8002, #7328)
 - Scrollbar: added io.ConfigScrollbarScrollByPage setting (default to true). (#8002, #7328)
   Set io.ConfigScrollbarScrollByPage=false to enforce always scrolling to clicked location.
diff --git a/imgui.cpp b/imgui.cpp
index 3833109bb..f176aa855 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -5917,18 +5917,35 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I
         window_flags |= ImGuiWindowFlags_NoMove;
     }
 
-    // Forward child flags
-    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
-    g.NextWindowData.ChildFlags = child_flags;
-
     // Forward size
     // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
     // (the alternative would to store conditional flags per axis, which is possible but more code)
     const ImVec2 size_avail = GetContentRegionAvail();
     const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
-    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
+    ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
+
+    // A SetNextWindowSize() call always has priority (#8020)
+    // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
+    // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
+    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0)
+    {
+        if (g.NextWindowData.SizeVal.x > 0.0f)
+        {
+            size.x = g.NextWindowData.SizeVal.x;
+            child_flags &= ~ImGuiChildFlags_ResizeX;
+        }
+        if (g.NextWindowData.SizeVal.y > 0.0f)
+        {
+            size.y = g.NextWindowData.SizeVal.y;
+            child_flags &= ~ImGuiChildFlags_ResizeY;
+        }
+    }
     SetNextWindowSize(size);
 
+    // Forward child flags
+    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
+    g.NextWindowData.ChildFlags = child_flags;
+
     // 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.
diff --git a/imgui.h b/imgui.h
index f03b7aa1d..f86efc428 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.3 WIP"
-#define IMGUI_VERSION_NUM   19121
+#define IMGUI_VERSION_NUM   19122
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index c2d110dd1..8fb410d9b 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -3931,6 +3931,9 @@ static void ShowDemoWindowLayout()
         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 200"))
+            //    ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 200.0f));
+
             ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
             if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY))
                 for (int n = 0; n < 10; n++)

From 26785fd873193770eb30fd716d44703cb94cf35b Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 27 Sep 2024 15:06:05 +0200
Subject: [PATCH 0388/2359] Internals: NewFrame: move the window reset loop
 higher up, namely before UpdateHoveredWindowAndCaptureFlags() ->
 FindHoveredWindowEx().

This allows using FindHoveredWindowEx() from anywhere in the frame.
---
 imgui.cpp | 35 ++++++++++++++++++-----------------
 1 file changed, 18 insertions(+), 17 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index f176aa855..0081a8aff 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -5158,8 +5158,25 @@ void ImGui::NewFrame()
     // Update mouse input state
     UpdateMouseInputs();
 
+    // Mark all windows as not visible and compact unused memory.
+    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
+    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
+    for (ImGuiWindow* window : g.Windows)
+    {
+        window->WasActive = window->Active;
+        window->Active = false;
+        window->WriteAccessed = false;
+        window->BeginCountPreviousFrame = window->BeginCount;
+        window->BeginCount = 0;
+
+        // Garbage collect transient buffers of recently unused windows
+        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
+            GcCompactTransientWindowBuffers(window);
+    }
+
     // Find hovered window
     // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
+    // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active)
     UpdateHoveredWindowAndCaptureFlags();
 
     // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
@@ -5181,22 +5198,6 @@ void ImGui::NewFrame()
     // Mouse wheel scrolling, scale
     UpdateMouseWheel();
 
-    // Mark all windows as not visible and compact unused memory.
-    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
-    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
-    for (ImGuiWindow* window : g.Windows)
-    {
-        window->WasActive = window->Active;
-        window->Active = false;
-        window->WriteAccessed = false;
-        window->BeginCountPreviousFrame = window->BeginCount;
-        window->BeginCount = 0;
-
-        // Garbage collect transient buffers of recently unused windows
-        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
-            GcCompactTransientWindowBuffers(window);
-    }
-
     // Garbage collect transient buffers of recently unused tables
     for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
         if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
@@ -5660,7 +5661,7 @@ void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_vi
     {
         ImGuiWindow* window = g.Windows[i];
         IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
-        if (!window->Active || window->Hidden)
+        if (!window->WasActive || window->Hidden)
             continue;
         if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
             continue;

From 2360061520e7346688b05188eafe72dabac71cf1 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 24 Sep 2024 15:58:09 +0200
Subject: [PATCH 0389/2359] Error Handling, Debug Log: added
 IMGUI_DEBUG_LOG_ERROR() with special handling. (#5855, #1651, #5654)

---
 imgui.cpp        | 19 +++++++++++++++++--
 imgui_internal.h |  2 ++
 2 files changed, 19 insertions(+), 2 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 0081a8aff..fbb4c4d8c 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3979,8 +3979,9 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     LogDepthToExpand = LogDepthToExpandDefault = 2;
 
     DebugDrawIdConflictsCount = 0;
-    DebugLogFlags = ImGuiDebugLogFlags_OutputToTTY;
+    DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY;
     DebugLocateId = 0;
+    DebugLogSkippedErrors = 0;
     DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
     DebugLogAutoDisableFrames = 0;
     DebugLocateFrames = 0;
@@ -16281,12 +16282,24 @@ static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
     ImGuiContext& g = *GImGui;
     ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
     SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
+
+    bool highlight_errors = (flags == ImGuiDebugLogFlags_EventError && g.DebugLogSkippedErrors > 0);
+    if (highlight_errors)
+        ImGui::PushStyleColor(ImGuiCol_Text, ImLerp(g.Style.Colors[ImGuiCol_Text], ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 0.30f));
     if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
     {
         g.DebugLogAutoDisableFrames = 2;
         g.DebugLogAutoDisableFlags |= flags;
     }
-    ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
+    if (highlight_errors)
+    {
+        ImGui::PopStyleColor();
+        ImGui::SetItemTooltip("%d past errors skipped.", g.DebugLogSkippedErrors);
+    }
+    else
+    {
+        ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
+    }
 }
 
 void ImGui::ShowDebugLogWindow(bool* p_open)
@@ -16304,6 +16317,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open)
     CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
     SetItemTooltip("(except InputRouting which is spammy)");
 
+    ShowDebugLogFlag("Errors", ImGuiDebugLogFlags_EventError);
     ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
     ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
     ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
@@ -16317,6 +16331,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open)
     {
         g.DebugLogBuf.clear();
         g.DebugLogIndex.clear();
+        g.DebugLogSkippedErrors = 0;
     }
     SameLine();
     if (SmallButton("Copy"))
diff --git a/imgui_internal.h b/imgui_internal.h
index 37c182b55..e204d0880 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -217,6 +217,7 @@ extern IMGUI_API ImGuiContext* GImGui;  // Current implicit context pointer
 #else
 #define IMGUI_DEBUG_LOG(...)            ((void)0)
 #endif
+#define IMGUI_DEBUG_LOG_ERROR(...)      do { ImGuiContext& g2 = *GImGui; if (g2.DebugLogFlags & ImGuiDebugLogFlags_EventError) IMGUI_DEBUG_LOG(__VA_ARGS__); else g2.DebugLogSkippedErrors++; } while (0)
 #define IMGUI_DEBUG_LOG_ACTIVEID(...)   do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventActiveId)    IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
 #define IMGUI_DEBUG_LOG_FOCUS(...)      do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFocus)       IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
 #define IMGUI_DEBUG_LOG_POPUP(...)      do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup)       IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
@@ -2321,6 +2322,7 @@ struct ImGuiContext
     ImGuiDebugLogFlags      DebugLogFlags;
     ImGuiTextBuffer         DebugLogBuf;
     ImGuiTextIndex          DebugLogIndex;
+    int                     DebugLogSkippedErrors;
     ImGuiDebugLogFlags      DebugLogAutoDisableFlags;
     ImU8                    DebugLogAutoDisableFrames;
     ImU8                    DebugLocateFrames;                  // For DebugLocateItemOnHover(). This is used together with DebugLocateId which is in a hot/cached spot above.

From 718a594b1e10cf51a0b6a85bdf39aec5d4929e77 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 24 Sep 2024 15:59:54 +0200
Subject: [PATCH 0390/2359] Error Handling: rewired asserts in PopID(),
 PopFont(), PopItemFlag(), EndDisabled(), PopTextWrapPos(), PopFocusScope(),
 PopItemWidth() to use IM_ASSERT_USER_ERROR().  (#1651, #5654)

---
 docs/CHANGELOG.txt |  2 ++
 imgui.cpp          | 58 +++++++++++++++++++++++++++++++++-------------
 2 files changed, 44 insertions(+), 16 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index c7c0a47e2..51ef272c5 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,8 @@ Breaking changes:
 
 Other changes:
 
+- Error Handling: rewired asserts in PopID(), PopFont(), PopItemFlag(), EndDisabled(),
+  PopTextWrapPos(), PopFocusScope(), PopItemWidth() to use IM_ASSERT_USER_ERROR(). (#1651)
 - Windows: BeginChild(): made it possible to call SetNextWindowSize() on a child window
   using ImGuiChildFlags_ResizeX,ImGuiChildFlags_ResizeY in order to override its current
   size. (#1710, #8020)
diff --git a/imgui.cpp b/imgui.cpp
index fbb4c4d8c..5b41fe37f 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3273,7 +3273,7 @@ void ImGui::PopStyleColor(int count)
     ImGuiContext& g = *GImGui;
     if (g.ColorStack.Size < count)
     {
-        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
+        IM_ASSERT_USER_ERROR(0, "Calling PopStyleColor() too many times!");
         count = g.ColorStack.Size;
     }
     while (count > 0)
@@ -3390,7 +3390,7 @@ void ImGui::PopStyleVar(int count)
     ImGuiContext& g = *GImGui;
     if (g.StyleVarStack.Size < count)
     {
-        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
+        IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!");
         count = g.StyleVarStack.Size;
     }
     while (count > 0)
@@ -7907,7 +7907,11 @@ void ImGui::PushFont(ImFont* font)
 void  ImGui::PopFont()
 {
     ImGuiContext& g = *GImGui;
-    IM_ASSERT(g.FontStack.Size > 0);
+    if (g.FontStack.Size <= 0)
+    {
+        IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!");
+        return;
+    }
     g.FontStack.pop_back();
     ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back();
     SetCurrentFont(font);
@@ -7930,7 +7934,11 @@ void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
 void ImGui::PopItemFlag()
 {
     ImGuiContext& g = *GImGui;
-    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
+    if (g.ItemFlagsStack.Size <= 1)
+    {
+        IM_ASSERT_USER_ERROR(0, "Calling PopItemFlag() too many times!");
+        return;
+    }
     g.ItemFlagsStack.pop_back();
     g.CurrentItemFlags = g.ItemFlagsStack.back();
 }
@@ -7960,7 +7968,11 @@ void ImGui::BeginDisabled(bool disabled)
 void ImGui::EndDisabled()
 {
     ImGuiContext& g = *GImGui;
-    IM_ASSERT(g.DisabledStackSize > 0);
+    if (g.DisabledStackSize <= 0)
+    {
+        IM_ASSERT_USER_ERROR(0, "Calling EndDisabled() too many times!");
+        return;
+    }
     g.DisabledStackSize--;
     bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
     //PopItemFlag();
@@ -7995,14 +8007,21 @@ void ImGui::EndDisabledOverrideReenable()
 
 void ImGui::PushTextWrapPos(float wrap_pos_x)
 {
-    ImGuiWindow* window = GetCurrentWindow();
+    ImGuiContext& g = *GImGui;
+    ImGuiWindow* window = g.CurrentWindow;
     window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
     window->DC.TextWrapPos = wrap_pos_x;
 }
 
 void ImGui::PopTextWrapPos()
 {
-    ImGuiWindow* window = GetCurrentWindow();
+    ImGuiContext& g = *GImGui;
+    ImGuiWindow* window = g.CurrentWindow;
+    if (window->DC.TextWrapPosStack.Size <= 0)
+    {
+        IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!");
+        return;
+    }
     window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
     window->DC.TextWrapPosStack.pop_back();
 }
@@ -8435,9 +8454,9 @@ void ImGui::PushFocusScope(ImGuiID id)
 void ImGui::PopFocusScope()
 {
     ImGuiContext& g = *GImGui;
-    if (g.FocusScopeStack.Size == 0)
+    if (g.FocusScopeStack.Size <= 0)
     {
-        IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
+        IM_ASSERT_USER_ERROR(0, "Calling PopFocusScope() too many times!");
         return;
     }
     g.FocusScopeStack.pop_back();
@@ -8708,7 +8727,11 @@ ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
 void ImGui::PopID()
 {
     ImGuiWindow* window = GImGui->CurrentWindow;
-    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
+    if (window->IDStack.Size <= 1)
+    {
+        IM_ASSERT_USER_ERROR(0, "Too many PopID(), or popping from wrong window?");
+        return;
+    }
     window->IDStack.pop_back();
 }
 
@@ -10424,6 +10447,8 @@ static void ImGui::ErrorCheckEndFrameSanityChecks()
             IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
         }
     }
+    if (g.CurrentWindowStack.Size >= 1)
+        IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
 
     IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
 }
@@ -10453,11 +10478,6 @@ void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, voi
     {
         ErrorCheckEndWindowRecover(log_callback, user_data);
         ImGuiWindow* window = g.CurrentWindow;
-        if (g.CurrentWindowStack.Size == 1)
-        {
-            IM_ASSERT(window->IsFallbackWindow);
-            break;
-        }
         if (window->Flags & ImGuiWindowFlags_ChildWindow)
         {
             if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'\n", window->Name);
@@ -10972,7 +10992,13 @@ void ImGui::PushMultiItemsWidths(int components, float w_full)
 
 void ImGui::PopItemWidth()
 {
-    ImGuiWindow* window = GetCurrentWindow();
+    ImGuiContext& g = *GImGui;
+    ImGuiWindow* window = g.CurrentWindow;
+    if (window->DC.ItemWidthStack.Size <= 0)
+    {
+        IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!");
+        return;
+    }
     window->DC.ItemWidth = window->DC.ItemWidthStack.back();
     window->DC.ItemWidthStack.pop_back();
 }

From 8776678a462ede913327ab5f3711fddcb2ecdb8a Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 24 Sep 2024 17:31:04 +0200
Subject: [PATCH 0391/2359] Error Handling: replaced log callback in recovery
 functions with calls to IM_ASSERT_USER_ERROR(). (#1651, #5654)

This commit is not meant to be functional as-is (it will break test engine recovery). This is mostly to reduce/remove noise from upcoming commits.
---
 imgui.cpp        | 79 +++++++++++++++++++++++-------------------------
 imgui_internal.h |  5 ++-
 2 files changed, 39 insertions(+), 45 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 5b41fe37f..cb84751f5 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -8729,7 +8729,7 @@ void ImGui::PopID()
     ImGuiWindow* window = GImGui->CurrentWindow;
     if (window->IDStack.Size <= 1)
     {
-        IM_ASSERT_USER_ERROR(0, "Too many PopID(), or popping from wrong window?");
+        IM_ASSERT_USER_ERROR(0, "Calling PopID() too many times!");
         return;
     }
     window->IDStack.pop_back();
@@ -10415,14 +10415,13 @@ static void ImGui::ErrorCheckNewFrameSanityChecks()
 
 static void ImGui::ErrorCheckEndFrameSanityChecks()
 {
-    ImGuiContext& g = *GImGui;
-
     // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
     // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
     // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
     // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
     // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
     // while still correctly asserting on mid-frame key press events.
+    ImGuiContext& g = *GImGui;
     const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
     IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
     IM_UNUSED(key_mods);
@@ -10453,85 +10452,80 @@ static void ImGui::ErrorCheckEndFrameSanityChecks()
     IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
 }
 
-// Default implementation of ImGuiErrorLogCallback that pipe errors to DebugLog: appears in tty + Tools->DebugLog
-void    ImGui::ErrorLogCallbackToDebugLog(void*, const char* fmt, ...)
-{
-#ifndef IMGUI_DISABLE_DEBUG_TOOLS
-    va_list args;
-    va_start(args, fmt);
-    DebugLogV(fmt, args);
-    va_end(args);
-#else
-    IM_UNUSED(fmt);
-#endif
-}
-
 // Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
 // Must be called during or before EndFrame().
 // This is generally flawed as we are not necessarily End/Popping things in the right order.
 // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
-void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
+void    ImGui::ErrorCheckEndFrameRecover()
 {
     // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
     ImGuiContext& g = *GImGui;
     while (g.CurrentWindowStack.Size > 0) //-V1044
     {
-        ErrorCheckEndWindowRecover(log_callback, user_data);
+        ErrorCheckEndWindowRecover();
+        // Recap:
+        // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped.
+        // - Always call a matching End() for each Begin() call, regardless of its return value!
+        // - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS.
+        // - We will fix that in a future major update.
         ImGuiWindow* window = g.CurrentWindow;
         if (window->Flags & ImGuiWindowFlags_ChildWindow)
         {
-            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'\n", window->Name);
+            IM_ASSERT_USER_ERROR(0, "Missing EndChild()");
             EndChild();
         }
         else
         {
-            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'\n", window->Name);
+            IM_ASSERT_USER_ERROR(0, "Missing End()");
             End();
         }
     }
 }
 
 // Must be called before End()/EndChild()
-void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
+void    ImGui::ErrorCheckEndWindowRecover()
 {
     ImGuiContext& g = *GImGui;
     while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'\n", g.CurrentTable->OuterWindow->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
         EndTable();
     }
 
     ImGuiWindow* window = g.CurrentWindow;
-    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
     IM_ASSERT(window != NULL);
+    ImGuiStackSizes* state_in = &g.CurrentWindowStack.back().StackSizesOnBegin;
+
+    // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
     while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()");
         EndTabBar();
     }
     while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndMultiSelect() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
         EndMultiSelect();
     }
     while (window->DC.TreeDepth > 0)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
         TreePop();
     }
-    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
+    while (g.GroupStack.Size > state_in->SizeOfGroupStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing EndGroup()");
         EndGroup();
     }
+    IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack);
     while (window->IDStack.Size > 1)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing PopID()");
         PopID();
     }
-    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
+    while (g.DisabledStackSize > state_in->SizeOfDisabledStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing EndDisabled()");
         if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
             EndDisabled();
         else
@@ -10540,29 +10534,30 @@ void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, vo
             g.CurrentWindowStack.back().DisabledOverrideReenable = false;
         }
     }
-    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
+    IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack);
+    while (g.ColorStack.Size > state_in->SizeOfColorStack)
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s\n", window->Name, GetStyleColorName(g.ColorStack.back().Col));
+        IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()");
         PopStyleColor();
     }
-    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
+    while (g.ItemFlagsStack.Size > state_in->SizeOfItemFlagsStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing PopItemFlag()");
         PopItemFlag();
     }
-    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
+    while (g.StyleVarStack.Size > state_in->SizeOfStyleVarStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing PopStyleVar()");
         PopStyleVar();
     }
-    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
+    while (g.FontStack.Size > state_in->SizeOfFontStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing PopFont()");
         PopFont();
     }
-    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
+    while (g.FocusScopeStack.Size > state_in->SizeOfFocusScopeStack) //-V1044
     {
-        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'\n", window->Name);
+        IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()");
         PopFocusScope();
     }
 }
@@ -10996,7 +10991,7 @@ void ImGui::PopItemWidth()
     ImGuiWindow* window = g.CurrentWindow;
     if (window->DC.ItemWidthStack.Size <= 0)
     {
-        IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!");
+        IM_ASSERT_USER_ERROR(0, "Calling PopItemWidth() too many times!");
         return;
     }
     window->DC.ItemWidth = window->DC.ItemWidthStack.back();
diff --git a/imgui_internal.h b/imgui_internal.h
index e204d0880..a00a675bd 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -3419,10 +3419,9 @@ namespace ImGui
     IMGUI_API void          GcAwakeTransientWindowBuffers(ImGuiWindow* window);
 
     // Error handling, State Recovery
-    IMGUI_API void          ErrorLogCallbackToDebugLog(void* user_data, const char* fmt, ...);
-    IMGUI_API void          ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);
-    IMGUI_API void          ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);
     IMGUI_API void          ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
+    IMGUI_API void          ErrorCheckEndFrameRecover();
+    IMGUI_API void          ErrorCheckEndWindowRecover();
     IMGUI_API void          ErrorCheckEndFrameFinalizeErrorTooltip();
     IMGUI_API bool          BeginErrorTooltip();
     IMGUI_API void          EndErrorTooltip();

From 30c29d291fbb4428055de676775ad591296a2bf2 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 24 Sep 2024 20:51:51 +0200
Subject: [PATCH 0392/2359] Error Handling: enabled experimental recovery
 systems. (#1651, #5654)

Setup a couple of features to configure them, including ways to display error tooltips instead of assserting.
---
 docs/CHANGELOG.txt |  18 ++++-
 imgui.cpp          | 196 ++++++++++++++++++++++++++++-----------------
 imgui.h            |  21 ++++-
 imgui_demo.cpp     |  16 ++++
 imgui_internal.h   |  44 ++++++----
 imgui_tables.cpp   |   2 +
 imgui_widgets.cpp  |   2 +-
 7 files changed, 203 insertions(+), 96 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 51ef272c5..511901085 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,8 +43,22 @@ Breaking changes:
 
 Other changes:
 
-- Error Handling: rewired asserts in PopID(), PopFont(), PopItemFlag(), EndDisabled(),
-  PopTextWrapPos(), PopFocusScope(), PopItemWidth() to use IM_ASSERT_USER_ERROR(). (#1651)
+- Error Handling: Enabled/improved error recovery systems. (#1651, #5654)
+  - Error recovery is not perfect nor guaranteed! It is a feature to ease development.
+  - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT().
+  - You not are not supposed to rely on it in the course of a normal application run.
+  - Possible usage: facilitate recovery from errors triggered from a scripting language or
+    after specific exceptions handlers. Surface errors to programmers in less agressive ways.
+  - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled
+    when making direct imgui API calls! Otherwise it would severely hinder your ability to
+    catch and correct mistakes!
+  - Added io.ConfigErrorRecovery to enable error recovery support.
+  - Added io.ConfigErrorRecoveryEnableAssert to assert on recoverable errors.
+  - Added io.ConfigErrorRecoveryEnableDebugLog to output to debug log on recoverable errors.
+  - Added io.ConfigErrorRecoveryEnableTooltip to enable displaying an error tooltip on recoverable errors.
+    The tooltip include a way to enable asserts if they were disabled.
+  - All options are enabled by default.
+  - Read https://github.com/ocornut/imgui/wiki/Error-Handling for a bit more details.
 - Windows: BeginChild(): made it possible to call SetNextWindowSize() on a child window
   using ImGuiChildFlags_ResizeX,ImGuiChildFlags_ResizeY in order to override its current
   size. (#1710, #8020)
diff --git a/imgui.cpp b/imgui.cpp
index cb84751f5..306a730ce 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1401,6 +1401,11 @@ ImGuiIO::ImGuiIO()
     ConfigDebugBeginReturnValueOnce = false;
     ConfigDebugBeginReturnValueLoop = false;
 
+    ConfigErrorRecovery = true;
+    ConfigErrorRecoveryEnableAssert = true;
+    ConfigErrorRecoveryEnableDebugLog = true;
+    ConfigErrorRecoveryEnableTooltip = true;
+
     // Inputs Behaviors
     MouseDoubleClickTime = 0.30f;
     MouseDoubleClickMaxDist = 6.0f;
@@ -3978,6 +3983,12 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     LogDepthRef = 0;
     LogDepthToExpand = LogDepthToExpandDefault = 2;
 
+    ErrorCallback = NULL;
+    ErrorCallbackUserData = NULL;
+    ErrorFirst = true;
+    ErrorCountCurrentFrame = 0;
+    StackSizesInBeginForCurrentWindow = NULL;
+
     DebugDrawIdConflictsCount = 0;
     DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY;
     DebugLocateId = 0;
@@ -4211,6 +4222,7 @@ static void SetCurrentWindow(ImGuiWindow* window)
 {
     ImGuiContext& g = *GImGui;
     g.CurrentWindow = window;
+    g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL;
     g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
     g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking
     if (window)
@@ -5249,6 +5261,10 @@ void ImGui::NewFrame()
     Begin("Debug##Default");
     IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
 
+    // Store stack sizes
+    g.ErrorCountCurrentFrame = 0;
+    ErrorRecoveryStoreState(&g.StackSizesInNewFrame);
+
     // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
     // allowing to validate correct Begin/End behavior in user code.
 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
@@ -5467,6 +5483,9 @@ void ImGui::EndFrame()
 
     CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
 
+    // [EXPERIMENTAL] Recover from errors
+    if (g.IO.ConfigErrorRecovery)
+        ErrorRecoveryTryToRecoverState(&g.StackSizesInNewFrame);
     ErrorCheckEndFrameSanityChecks();
     ErrorCheckEndFrameFinalizeErrorTooltip();
 
@@ -6960,12 +6979,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
 
     // Add to stack
     g.CurrentWindow = window;
-    ImGuiWindowStackData window_stack_data;
+    g.CurrentWindowStack.resize(g.CurrentWindowStack.Size + 1);
+    ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
     window_stack_data.Window = window;
     window_stack_data.ParentLastItemDataBackup = g.LastItemData;
-    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
     window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
-    g.CurrentWindowStack.push_back(window_stack_data);
+    ErrorRecoveryStoreState(&window_stack_data.StackSizesInBegin);
+    g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin;
     if (flags & ImGuiWindowFlags_ChildMenu)
         g.BeginMenuDepth++;
 
@@ -7693,7 +7713,11 @@ void ImGui::End()
         g.BeginMenuDepth--;
     if (window->Flags & ImGuiWindowFlags_Popup)
         g.BeginPopupStack.pop_back();
-    window_stack_data.StackSizesOnBegin.CompareWithContextState(&g);
+
+    // Error handling, state recovery
+    if (g.IO.ConfigErrorRecovery)
+        ErrorRecoveryTryToRecoverWindowState(&window_stack_data.StackSizesInBegin);
+
     g.CurrentWindowStack.pop_back();
     SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
 }
@@ -8454,7 +8478,7 @@ void ImGui::PushFocusScope(ImGuiID id)
 void ImGui::PopFocusScope()
 {
     ImGuiContext& g = *GImGui;
-    if (g.FocusScopeStack.Size <= 0)
+    if (g.FocusScopeStack.Size <= g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack)
     {
         IM_ASSERT_USER_ERROR(0, "Calling PopFocusScope() too many times!");
         return;
@@ -10303,9 +10327,10 @@ bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID own
 // - ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
 // - ErrorCheckNewFrameSanityChecks()
 // - ErrorCheckEndFrameSanityChecks()
-// - ErrorCheckEndFrameRecover()
-// - ErrorCheckEndWindowRecover()
-// - ImGuiStackSizes
+// - ErrorRecoveryStoreState()
+// - ErrorRecoveryTryToRecoverState()
+// - ErrorRecoveryTryToRecoverWindowState()
+// - ErrorLog()
 //-----------------------------------------------------------------------------
 
 // Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
@@ -10404,6 +10429,10 @@ static void ImGui::ErrorCheckNewFrameSanityChecks()
         IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
 #endif
 
+    // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
+    if (g.IO.ConfigErrorRecovery)
+        IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
+
     // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
     if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
@@ -10426,43 +10455,35 @@ static void ImGui::ErrorCheckEndFrameSanityChecks()
     IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
     IM_UNUSED(key_mods);
 
-    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
-    //ErrorCheckEndFrameRecover();
-
-    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
-    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
-    if (g.CurrentWindowStack.Size != 1)
-    {
-        if (g.CurrentWindowStack.Size > 1)
-        {
-            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
-            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
-            IM_UNUSED(window);
-            while (g.CurrentWindowStack.Size > 1)
-                End();
-        }
-        else
-        {
-            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
-        }
-    }
-    if (g.CurrentWindowStack.Size >= 1)
-        IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
-
-    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
+    IM_ASSERT(g.CurrentWindowStack.Size == 1);
+    IM_ASSERT(g.CurrentWindowStack[0].Window->IsFallbackWindow);
 }
 
-// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
-// Must be called during or before EndFrame().
-// This is generally flawed as we are not necessarily End/Popping things in the right order.
-// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
-void    ImGui::ErrorCheckEndFrameRecover()
+// Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery.
+void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out)
+{
+    ImGuiContext& g = *GImGui;
+    state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size;
+    state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size;
+    state_out->SizeOfColorStack = (short)g.ColorStack.Size;
+    state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
+    state_out->SizeOfFontStack = (short)g.FontStack.Size;
+    state_out->SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
+    state_out->SizeOfGroupStack = (short)g.GroupStack.Size;
+    state_out->SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
+    state_out->SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
+    state_out->SizeOfDisabledStack = (short)g.DisabledStackSize;
+}
+
+// Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery.
+// Called by e.g. EndFrame() but may be called for manual recovery.
+// Attempt to recover full window stack.
+void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in)
 {
     // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
     ImGuiContext& g = *GImGui;
-    while (g.CurrentWindowStack.Size > 0) //-V1044
+    while (g.CurrentWindowStack.Size > state_in->SizeOfWindowStack) //-V1044
     {
-        ErrorCheckEndWindowRecover();
         // Recap:
         // - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped.
         // - Always call a matching End() for each Begin() call, regardless of its return value!
@@ -10480,12 +10501,17 @@ void    ImGui::ErrorCheckEndFrameRecover()
             End();
         }
     }
+    if (g.CurrentWindowStack.Size == state_in->SizeOfWindowStack)
+        ErrorRecoveryTryToRecoverWindowState(state_in);
 }
 
-// Must be called before End()/EndChild()
-void    ImGui::ErrorCheckEndWindowRecover()
+// Called by e.g. End() but may be called for manual recovery.
+// Read '// Error Handling [BETA]' block in imgui_internal.h for details.
+// Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
+void    ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in)
 {
     ImGuiContext& g = *GImGui;
+
     while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
     {
         IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
@@ -10493,8 +10519,6 @@ void    ImGui::ErrorCheckEndWindowRecover()
     }
 
     ImGuiWindow* window = g.CurrentWindow;
-    IM_ASSERT(window != NULL);
-    ImGuiStackSizes* state_in = &g.CurrentWindowStack.back().StackSizesOnBegin;
 
     // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
     while (g.CurrentTabBar != NULL && g.CurrentTabBar->Window == window) //-V1044
@@ -10560,45 +10584,52 @@ void    ImGui::ErrorCheckEndWindowRecover()
         IM_ASSERT_USER_ERROR(0, "Missing PopFocusScope()");
         PopFocusScope();
     }
+    //IM_ASSERT(g.FocusScopeStack.Size == state_in->SizeOfFocusScopeStack);
 }
 
-// Save current stack sizes for later compare
-void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
+bool    ImGui::ErrorLog(const char* msg)
 {
-    ImGuiContext& g = *ctx;
+    ImGuiContext& g = *GImGui;
+
+    // Output to debug log
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
     ImGuiWindow* window = g.CurrentWindow;
-    SizeOfIDStack = (short)window->IDStack.Size;
-    SizeOfColorStack = (short)g.ColorStack.Size;
-    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
-    SizeOfFontStack = (short)g.FontStack.Size;
-    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
-    SizeOfGroupStack = (short)g.GroupStack.Size;
-    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
-    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
-    SizeOfDisabledStack = (short)g.DisabledStackSize;
-}
 
-// Compare to detect usage errors
-void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
-{
-    ImGuiContext& g = *ctx;
-    ImGuiWindow* window = g.CurrentWindow;
-    IM_UNUSED(window);
+    if (g.IO.ConfigErrorRecoveryEnableDebugLog)
+    {
+        if (g.ErrorFirst)
+            IMGUI_DEBUG_LOG_ERROR("[imgui-error] (current settings: Assert=%d, Log=%d, Tooltip=%d)\n",
+                g.IO.ConfigErrorRecoveryEnableAssert, g.IO.ConfigErrorRecoveryEnableDebugLog, g.IO.ConfigErrorRecoveryEnableTooltip);
+        IMGUI_DEBUG_LOG_ERROR("[imgui-error] In window '%s': %s\n", window ? window->Name : "NULL", msg);
+    }
+    g.ErrorFirst = false;
 
-    // Window stacks
-    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
-    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
+    // Output to tooltip
+    if (g.IO.ConfigErrorRecoveryEnableTooltip)
+    {
+        if (BeginErrorTooltip())
+        {
+            if (g.ErrorCountCurrentFrame < 20)
+            {
+                Text("In window '%s': %s", window ? window->Name : "NULL", msg);
+                if (window && (!window->IsFallbackWindow || window->WasActive))
+                    GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 0, 0, 255));
+            }
+            if (g.ErrorCountCurrentFrame == 20)
+                Text("(and more errors)");
+            // EndFrame() will amend debug buttons to this window, after all errors have been submitted.
+            EndErrorTooltip();
+        }
+        g.ErrorCountCurrentFrame++;
+    }
+#endif
 
-    // Global stacks
-    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
-    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
-    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
-    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
-    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
-    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
-    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
-    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
-    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
+    // Output to callback
+    if (g.ErrorCallback != NULL)
+        g.ErrorCallback(&g, g.ErrorCallbackUserData, msg);
+
+    // Return whether we should assert
+    return g.IO.ConfigErrorRecoveryEnableAssert;
 }
 
 void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
@@ -10625,6 +10656,21 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
             g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage");
         EndErrorTooltip();
     }
+
+    if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame
+    {
+        Separator();
+        Text("(Hold CTRL and:");
+        SameLine();
+        if (SmallButton("Enable Asserts"))
+            g.IO.ConfigErrorRecoveryEnableAssert = true;
+        //SameLine();
+        //if (SmallButton("Hide Error Tooltips"))
+        //    g.IO.ConfigErrorRecoveryEnableTooltip = false; // Too dangerous
+        SameLine(0, 0);
+        Text(")");
+        EndErrorTooltip();
+    }
 #endif
 }
 
diff --git a/imgui.h b/imgui.h
index f86efc428..4ab39be3f 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.3 WIP"
-#define IMGUI_VERSION_NUM   19122
+#define IMGUI_VERSION_NUM   19123
 #define IMGUI_HAS_TABLE
 
 /*
@@ -2265,6 +2265,23 @@ struct ImGuiIO
     // Debug options
     //------------------------------------------------------------------
 
+    // Options to configure how we handle recoverable errors [EXPERIMENTAL]
+    // - Error recovery is not perfect nor guaranteed! It is a feature to ease development.
+    // - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT().
+    // - You not are not supposed to rely on it in the course of a normal application run.
+    // - Possible usage: facilitate recovery from errors triggered from a scripting language or after specific exceptions handlers.
+    // - Always ensure that on programmers seat you have at minimum Asserts or Tooltips enabled when making direct imgui API calls!
+    //   Otherwise it would severely hinder your ability to catch and correct mistakes!
+    // Read https://github.com/ocornut/imgui/wiki/Error-Handling for details about typical usage scenarios:
+    // - Programmer seats: keep asserts (default), or disable asserts and keep error tooltips (new and nice!)
+    // - Non-programmer seats: maybe disable asserts, but make sure errors are resurfaced (visible log entries, use callback etc.)
+    // - Recovery after error from scripting language: record stack sizes before running script, disable assert, trigger breakpoint from ErrorCallback, recover with ErrorRecoveryTryToRecoverState(), restore settings.
+    // - Recovery after an exception handler:  record stack sizes before try {} block, disable assert, set log callback, recover with ErrorRecoveryTryToRecoverState(), restore settings.
+    bool        ConfigErrorRecovery;                // = true       // Enable error recovery support. Some errors won't be detected and lead to direct crashes if recovery is disabled.
+    bool        ConfigErrorRecoveryEnableAssert;    // = true       // Enable asserts on recoverable error. By default call IM_ASSERT() when returning from a failing IM_ASSERT_USER_ERROR()
+    bool        ConfigErrorRecoveryEnableDebugLog;  // = true       // Enable debug log output on recoverable errors.
+    bool        ConfigErrorRecoveryEnableTooltip;   // = true       // Enable tooltip on recoverable errors. The tooltip include a way to enable asserts if they were disabled.
+
     // Option to enable various debug tools showing buttons that will call the IM_DEBUG_BREAK() macro.
     // - The Item Picker tool will be available regardless of this being enabled, in order to maximize its discoverability.
     // - Requires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application.
@@ -2293,7 +2310,7 @@ struct ImGuiIO
     bool        ConfigDebugIniSettings;         // = false          // Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower)
 
     //------------------------------------------------------------------
-    // Platform Functions
+    // Platform Identifiers
     // (the imgui_impl_xxxx backend files are setting those up for you)
     //------------------------------------------------------------------
 
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 8fb410d9b..60d944657 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -545,6 +545,22 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::SameLine(); HelpMarker("Swap Cmd<>Ctrl keys, enable various MacOS style behaviors.");
             ImGui::Text("Also see Style->Rendering for rendering options.");
 
+            // Read https://github.com/ocornut/imgui/wiki/Error-Handling
+            ImGui::SeparatorText("Error Handling");
+            ImGui::Checkbox("io.ConfigErrorRecovery", &io.ConfigErrorRecovery);
+            ImGui::SameLine(); HelpMarker(
+                "Options to configure how we handle recoverable errors.\n"
+                "- Error recovery is not perfect nor guaranteed! It is a feature to ease development.\n"
+                "- You not are not supposed to rely on it in the course of a normal application run.\n"
+                "- Possible usage: facilitate recovery from errors triggered from a scripting language or after specific exceptions handlers.\n"
+                "- Always ensure that on programmers seat you have at minimum Asserts or Tooltips enabled when making direct imgui API call!"
+                "Otherwise it would severely hinder your ability to catch and correct mistakes!");
+            ImGui::Checkbox("io.ConfigErrorRecoveryEnableAssert", &io.ConfigErrorRecoveryEnableAssert);
+            ImGui::Checkbox("io.ConfigErrorRecoveryEnableDebugLog", &io.ConfigErrorRecoveryEnableDebugLog);
+            ImGui::Checkbox("io.ConfigErrorRecoveryEnableTooltip", &io.ConfigErrorRecoveryEnableTooltip);
+            if (!io.ConfigErrorRecoveryEnableAssert && !io.ConfigErrorRecoveryEnableDebugLog && !io.ConfigErrorRecoveryEnableTooltip)
+                io.ConfigErrorRecoveryEnableAssert = io.ConfigErrorRecoveryEnableDebugLog = io.ConfigErrorRecoveryEnableTooltip = true;
+
             ImGui::SeparatorText("Debug");
             ImGui::Checkbox("io.ConfigDebugIsDebuggerPresent", &io.ConfigDebugIsDebuggerPresent);
             ImGui::SameLine(); HelpMarker("Enable various tools calling IM_DEBUG_BREAK().\n\nRequires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application.");
diff --git a/imgui_internal.h b/imgui_internal.h
index a00a675bd..52664a1c5 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -132,6 +132,7 @@ struct ImGuiContext;                // Main Dear ImGui context
 struct ImGuiContextHook;            // Hook for extensions like ImGuiTestEngine
 struct ImGuiDataVarInfo;            // Variable information (e.g. to access style variables from an enum)
 struct ImGuiDataTypeInfo;           // Type information associated to a ImGuiDataType enum
+struct ImGuiErrorRecoveryState;     // Storage of stack sizes for error handling and recovery
 struct ImGuiGroupData;              // Stacked storage data for BeginGroup()/EndGroup()
 struct ImGuiInputTextState;         // Internal state of the currently focused/edited text input box
 struct ImGuiInputTextDeactivateData;// Short term storage to backup text of a deactivating InputText() while another is stealing active id
@@ -148,7 +149,6 @@ struct ImGuiOldColumnData;          // Storage data for a single column for lega
 struct ImGuiOldColumns;             // Storage data for a columns set for legacy Columns() api
 struct ImGuiPopupData;              // Storage for current popup stack
 struct ImGuiSettingsHandler;        // Storage for one type registered in the .ini file
-struct ImGuiStackSizes;             // Storage of stack sizes for debugging/asserting
 struct ImGuiStyleMod;               // Stacked style modifier, backup of modified data so we can restore it
 struct ImGuiTabBar;                 // Storage for a tab bar
 struct ImGuiTabItem;                // Storage for a tab item (within a tab bar)
@@ -1253,9 +1253,10 @@ struct ImGuiTreeNodeStackData
     ImRect                  NavRect;    // Used for nav landing
 };
 
-// sizeof() = 18
-struct IMGUI_API ImGuiStackSizes
+// sizeof() = 20
+struct IMGUI_API ImGuiErrorRecoveryState
 {
+    short   SizeOfWindowStack;
     short   SizeOfIDStack;
     short   SizeOfColorStack;
     short   SizeOfStyleVarStack;
@@ -1266,18 +1267,16 @@ struct IMGUI_API ImGuiStackSizes
     short   SizeOfBeginPopupStack;
     short   SizeOfDisabledStack;
 
-    ImGuiStackSizes() { memset(this, 0, sizeof(*this)); }
-    void SetToContextState(ImGuiContext* ctx);
-    void CompareWithContextState(ImGuiContext* ctx);
+    ImGuiErrorRecoveryState() { memset(this, 0, sizeof(*this)); }
 };
 
 // Data saved for each window pushed into the stack
 struct ImGuiWindowStackData
 {
-    ImGuiWindow*        Window;
-    ImGuiLastItemData   ParentLastItemDataBackup;
-    ImGuiStackSizes     StackSizesOnBegin;          // Store size of various stacks for asserting
-    bool                DisabledOverrideReenable;   // Non-child window override disabled flag
+    ImGuiWindow*            Window;
+    ImGuiLastItemData       ParentLastItemDataBackup;
+    ImGuiErrorRecoveryState StackSizesInBegin;          // Store size of various stacks for asserting
+    bool                    DisabledOverrideReenable;   // Non-child window override disabled flag
 };
 
 struct ImGuiShrinkWidthItem
@@ -1885,12 +1884,17 @@ struct ImGuiLocEntry
 //-----------------------------------------------------------------------------
 
 // Macros used by Recoverable Error handling
-// Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults.
+// - Only dispatch error if _EXPR: evaluate as assert (similar to an assert macro).
+// - The message will always be a string literal, in order to increase likelihood of being display by an assert handler.
+// - The intent is that you may rewire this macro to dispatch dynamically:
+//   - On programmers machines, when debugger is attached, on direct imgui API usage error: always assert!
+//   - On exception recovery and script language recovery: you may decide to error log.
 #ifndef IM_ASSERT_USER_ERROR
-#define IM_ASSERT_USER_ERROR(_EXPR,_MSG)    IM_ASSERT((_EXPR) && _MSG)
+#define IM_ASSERT_USER_ERROR(_EXPR,_MSG)    do { if (!(_EXPR) && ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } } while (0)    // Recoverable User Error
 #endif
 
-typedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...);
+
+typedef void    (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const char* msg); // Function signature for g.ErrorCallback
 
 //-----------------------------------------------------------------------------
 // [SECTION] Metrics, Debug Tools
@@ -2313,8 +2317,14 @@ struct ImGuiContext
     int                     LogDepthToExpand;
     int                     LogDepthToExpandDefault;            // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call.
 
-    // Error handling
+    // Error Handling
+    ImGuiErrorCallback      ErrorCallback;                      // = NULL. May be exposed in public API eventually.
+    void*                   ErrorCallbackUserData;              // = NULL
     ImVec2                  ErrorTooltipLockedPos;
+    bool                    ErrorFirst;
+    int                     ErrorCountCurrentFrame;             // [Internal] Number of errors submitted this frame.
+    ImGuiErrorRecoveryState StackSizesInNewFrame;               // [Internal]
+    ImGuiErrorRecoveryState*StackSizesInBeginForCurrentWindow;  // [Internal]
 
     // Debug Tools
     // (some of the highly frequently used data are interleaved in other structures above: DebugBreakXXX fields, DebugHookIdInfo, DebugLocateId etc.)
@@ -3419,9 +3429,11 @@ namespace ImGui
     IMGUI_API void          GcAwakeTransientWindowBuffers(ImGuiWindow* window);
 
     // Error handling, State Recovery
+    IMGUI_API bool          ErrorLog(const char* msg);
+    IMGUI_API void          ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out);
+    IMGUI_API void          ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in);
+    IMGUI_API void          ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in);
     IMGUI_API void          ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
-    IMGUI_API void          ErrorCheckEndFrameRecover();
-    IMGUI_API void          ErrorCheckEndWindowRecover();
     IMGUI_API void          ErrorCheckEndFrameFinalizeErrorTooltip();
     IMGUI_API bool          BeginErrorTooltip();
     IMGUI_API void          EndErrorTooltip();
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index dc7f21098..4a6fbed7c 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1484,7 +1484,9 @@ void    ImGui::EndTable()
     {
         short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask;
         inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.
+        g.CurrentTable = NULL; // To avoid error recovery recursing
         EndChild();
+        g.CurrentTable = table;
         inner_window->DC.NavLayersActiveMask = backup_nav_layers_active_mask;
     }
     else
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 5641134ff..22ff7a9e5 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -7551,7 +7551,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect()
     ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
     ImGuiMultiSelectState* storage = ms->Storage;
     ImGuiWindow* window = g.CurrentWindow;
-    IM_ASSERT(ms->FocusScopeId == g.CurrentFocusScopeId);
+    IM_ASSERT_USER_ERROR(ms->FocusScopeId == g.CurrentFocusScopeId, "EndMultiSelect() FocusScope mismatch!");
     IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow);
     IM_ASSERT(g.MultiSelectTempDataStacked > 0 && &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] == g.CurrentMultiSelect);
 

From 199a44e31e20f7620fc1d67b69107b3c2a8eda8a Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 26 Sep 2024 17:51:46 +0200
Subject: [PATCH 0393/2359] Error Handling: fixed not rewinding to recorded
 tree and id stack size (#1651)

---
 imgui.cpp        | 5 +++--
 imgui_internal.h | 1 +
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 306a730ce..5379248c8 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -10465,6 +10465,7 @@ void ImGui::ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out)
     ImGuiContext& g = *GImGui;
     state_out->SizeOfWindowStack = (short)g.CurrentWindowStack.Size;
     state_out->SizeOfIDStack = (short)g.CurrentWindow->IDStack.Size;
+    state_out->SizeOfTreeStack = (short)g.CurrentWindow->DC.TreeDepth; // NOT g.TreeNodeStack.Size which is a partial stack!
     state_out->SizeOfColorStack = (short)g.ColorStack.Size;
     state_out->SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
     state_out->SizeOfFontStack = (short)g.FontStack.Size;
@@ -10531,7 +10532,7 @@ void    ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryStat
         IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
         EndMultiSelect();
     }
-    while (window->DC.TreeDepth > 0)
+    while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044
     {
         IM_ASSERT_USER_ERROR(0, "Missing TreePop()");
         TreePop();
@@ -10542,7 +10543,7 @@ void    ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryStat
         EndGroup();
     }
     IM_ASSERT(g.GroupStack.Size == state_in->SizeOfGroupStack);
-    while (window->IDStack.Size > 1)
+    while (window->IDStack.Size > state_in->SizeOfIDStack) //-V1044
     {
         IM_ASSERT_USER_ERROR(0, "Missing PopID()");
         PopID();
diff --git a/imgui_internal.h b/imgui_internal.h
index 52664a1c5..cb9071478 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1258,6 +1258,7 @@ struct IMGUI_API ImGuiErrorRecoveryState
 {
     short   SizeOfWindowStack;
     short   SizeOfIDStack;
+    short   SizeOfTreeStack;
     short   SizeOfColorStack;
     short   SizeOfStyleVarStack;
     short   SizeOfFontStack;

From ba14c70b020038bd580ab72da5181f03df4eb872 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 27 Sep 2024 19:23:41 +0200
Subject: [PATCH 0394/2359] Comments. Fixed warnings.

---
 imgui.cpp        | 2 ++
 imgui_demo.cpp   | 5 ++++-
 imgui_internal.h | 9 ++++-----
 3 files changed, 10 insertions(+), 6 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 5379248c8..0bfbff945 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -10452,6 +10452,8 @@ static void ImGui::ErrorCheckEndFrameSanityChecks()
     // while still correctly asserting on mid-frame key press events.
     ImGuiContext& g = *GImGui;
     const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
+    IM_UNUSED(g);
+    IM_UNUSED(key_mods);
     IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
     IM_UNUSED(key_mods);
 
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 60d944657..feaee3be9 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -545,8 +545,9 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::SameLine(); HelpMarker("Swap Cmd<>Ctrl keys, enable various MacOS style behaviors.");
             ImGui::Text("Also see Style->Rendering for rendering options.");
 
-            // Read https://github.com/ocornut/imgui/wiki/Error-Handling
+            // Also read: https://github.com/ocornut/imgui/wiki/Error-Handling
             ImGui::SeparatorText("Error Handling");
+
             ImGui::Checkbox("io.ConfigErrorRecovery", &io.ConfigErrorRecovery);
             ImGui::SameLine(); HelpMarker(
                 "Options to configure how we handle recoverable errors.\n"
@@ -561,6 +562,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
             if (!io.ConfigErrorRecoveryEnableAssert && !io.ConfigErrorRecoveryEnableDebugLog && !io.ConfigErrorRecoveryEnableTooltip)
                 io.ConfigErrorRecoveryEnableAssert = io.ConfigErrorRecoveryEnableDebugLog = io.ConfigErrorRecoveryEnableTooltip = true;
 
+            // Also read: https://github.com/ocornut/imgui/wiki/Debug-Tools
             ImGui::SeparatorText("Debug");
             ImGui::Checkbox("io.ConfigDebugIsDebuggerPresent", &io.ConfigDebugIsDebuggerPresent);
             ImGui::SameLine(); HelpMarker("Enable various tools calling IM_DEBUG_BREAK().\n\nRequires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application.");
@@ -595,6 +597,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos",       &io.BackendFlags, ImGuiBackendFlags_HasSetMousePos);
             ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &io.BackendFlags, ImGuiBackendFlags_RendererHasVtxOffset);
             ImGui::EndDisabled();
+
             ImGui::TreePop();
             ImGui::Spacing();
         }
diff --git a/imgui_internal.h b/imgui_internal.h
index cb9071478..80bba6903 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1887,15 +1887,14 @@ struct ImGuiLocEntry
 // Macros used by Recoverable Error handling
 // - Only dispatch error if _EXPR: evaluate as assert (similar to an assert macro).
 // - The message will always be a string literal, in order to increase likelihood of being display by an assert handler.
-// - The intent is that you may rewire this macro to dispatch dynamically:
-//   - On programmers machines, when debugger is attached, on direct imgui API usage error: always assert!
-//   - On exception recovery and script language recovery: you may decide to error log.
+// - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling.
+// - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling.
 #ifndef IM_ASSERT_USER_ERROR
 #define IM_ASSERT_USER_ERROR(_EXPR,_MSG)    do { if (!(_EXPR) && ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } } while (0)    // Recoverable User Error
 #endif
 
-
-typedef void    (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const char* msg); // Function signature for g.ErrorCallback
+// The error callback is currently not public, as it is expected that only advanced users will rely on it.
+typedef void (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const char* msg); // Function signature for g.ErrorCallback
 
 //-----------------------------------------------------------------------------
 // [SECTION] Metrics, Debug Tools

From 29cff2be06860cadbc7557cc64f29159468213e2 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Sat, 28 Sep 2024 16:54:45 +0200
Subject: [PATCH 0395/2359] Silence PVS Studio static analyzer false positives.

---
 imgui.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 0bfbff945..5af8a024f 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -10515,7 +10515,7 @@ void    ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryStat
 {
     ImGuiContext& g = *GImGui;
 
-    while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow)
+    while (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) //-V1044
     {
         IM_ASSERT_USER_ERROR(0, "Missing EndTable()");
         EndTable();
@@ -10529,7 +10529,7 @@ void    ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryStat
         IM_ASSERT_USER_ERROR(0, "Missing EndTabBar()");
         EndTabBar();
     }
-    while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window)
+    while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window) //-V1044
     {
         IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()");
         EndMultiSelect();
@@ -10562,7 +10562,7 @@ void    ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryStat
         }
     }
     IM_ASSERT(g.DisabledStackSize == state_in->SizeOfDisabledStack);
-    while (g.ColorStack.Size > state_in->SizeOfColorStack)
+    while (g.ColorStack.Size > state_in->SizeOfColorStack) //-V1044
     {
         IM_ASSERT_USER_ERROR(0, "Missing PopStyleColor()");
         PopStyleColor();

From 03f007d4cd106ef5ce16a40a2f24147ddb48674c Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 30 Sep 2024 12:04:48 +0200
Subject: [PATCH 0396/2359] Comments (#1651)

---
 docs/CHANGELOG.txt |  8 +++++++-
 imgui.cpp          |  2 +-
 imgui.h            | 18 ++++++++++--------
 3 files changed, 18 insertions(+), 10 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 511901085..db13bc9b1 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -44,9 +44,15 @@ Breaking changes:
 Other changes:
 
 - Error Handling: Enabled/improved error recovery systems. (#1651, #5654)
+  - Error recovery is provided as a way to facilitate:
+    - Recovery after a programming error. Native code or scripting language (the later
+      tends to facilitate iterating on code while running).
+    - Recovery after running an exception handler or any error processing which may skip code
+      after an error has been detected.
   - Error recovery is not perfect nor guaranteed! It is a feature to ease development.
+    You not are not supposed to rely on it in the course of a normal application run.
   - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT().
-  - You not are not supposed to rely on it in the course of a normal application run.
+  - By design, we do not allow error recovery to be 100% silent. One of the options needs to be enabled!
   - Possible usage: facilitate recovery from errors triggered from a scripting language or
     after specific exceptions handlers. Surface errors to programmers in less agressive ways.
   - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled
diff --git a/imgui.cpp b/imgui.cpp
index 5af8a024f..5f0c8281b 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -15240,7 +15240,7 @@ void ImGui::ShowMetricsWindow(bool* p_open)
     DebugBreakClearData();
 
     // Basic info
-    Text("Dear ImGui %s", GetVersion());
+    Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
     if (g.ContextName[0] != 0)
     {
         SameLine();
diff --git a/imgui.h b/imgui.h
index 4ab39be3f..59ea4baac 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2265,18 +2265,20 @@ struct ImGuiIO
     // Debug options
     //------------------------------------------------------------------
 
-    // Options to configure how we handle recoverable errors [EXPERIMENTAL]
+    // Options to configure Error Handling and how we handle recoverable errors [EXPERIMENTAL]
+    // - Error recovery is provided as a way to facilitate:
+    //    - Recovery after a programming error (native code or scripting language - the later tends to facilitate iterating on code while running).
+    //    - Recovery after running an exception handler or any error processing which may skip code after an error has been detected.
     // - Error recovery is not perfect nor guaranteed! It is a feature to ease development.
+    //   You not are not supposed to rely on it in the course of a normal application run.
     // - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT().
-    // - You not are not supposed to rely on it in the course of a normal application run.
-    // - Possible usage: facilitate recovery from errors triggered from a scripting language or after specific exceptions handlers.
-    // - Always ensure that on programmers seat you have at minimum Asserts or Tooltips enabled when making direct imgui API calls!
+    // - By design, we do NOT allow error recovery to be 100% silent. One of the three options needs to be checked!
+    // - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled when making direct imgui API calls!
     //   Otherwise it would severely hinder your ability to catch and correct mistakes!
-    // Read https://github.com/ocornut/imgui/wiki/Error-Handling for details about typical usage scenarios:
+    // Read https://github.com/ocornut/imgui/wiki/Error-Handling for details.
     // - Programmer seats: keep asserts (default), or disable asserts and keep error tooltips (new and nice!)
-    // - Non-programmer seats: maybe disable asserts, but make sure errors are resurfaced (visible log entries, use callback etc.)
-    // - Recovery after error from scripting language: record stack sizes before running script, disable assert, trigger breakpoint from ErrorCallback, recover with ErrorRecoveryTryToRecoverState(), restore settings.
-    // - Recovery after an exception handler:  record stack sizes before try {} block, disable assert, set log callback, recover with ErrorRecoveryTryToRecoverState(), restore settings.
+    // - Non-programmer seats: maybe disable asserts, but make sure errors are resurfaced (tooltips, visible log entries, use callback etc.)
+    // - Recovery after error/exception: record stack sizes with ErrorRecoveryStoreState(), disable assert, set log callback (to e.g. trigger high-level breakpoint), recover with ErrorRecoveryTryToRecoverState(), restore settings.
     bool        ConfigErrorRecovery;                // = true       // Enable error recovery support. Some errors won't be detected and lead to direct crashes if recovery is disabled.
     bool        ConfigErrorRecoveryEnableAssert;    // = true       // Enable asserts on recoverable error. By default call IM_ASSERT() when returning from a failing IM_ASSERT_USER_ERROR()
     bool        ConfigErrorRecoveryEnableDebugLog;  // = true       // Enable debug log output on recoverable errors.

From 655fcf82870a8ecdf51aced1d6f685bce373a38e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 30 Sep 2024 19:36:58 +0200
Subject: [PATCH 0397/2359] TabBar: added TabBarQueueFocus() by name for
 non-docking tab bars. (#8029, #6681)

---
 imgui_internal.h  | 1 +
 imgui_widgets.cpp | 7 +++++++
 2 files changed, 8 insertions(+)

diff --git a/imgui_internal.h b/imgui_internal.h
index 80bba6903..113b05426 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -3318,6 +3318,7 @@ namespace ImGui
     IMGUI_API void          TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id);
     IMGUI_API void          TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);
     IMGUI_API void          TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);
+    IMGUI_API void          TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name);
     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);
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 22ff7a9e5..46c418356 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -9627,6 +9627,13 @@ void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
     tab_bar->NextSelectedTabId = tab->ID;
 }
 
+void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name)
+{
+    IM_ASSERT((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0); // Only supported for manual/explicit tab bars
+    ImGuiID tab_id = TabBarCalcTabID(tab_bar, tab_name);
+    tab_bar->NextSelectedTabId = tab_id;
+}
+
 void ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset)
 {
     IM_ASSERT(offset != 0);

From 004f03945f3c09b89078af8e31e59875de37d107 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 30 Sep 2024 20:01:06 +0200
Subject: [PATCH 0398/2359] TabBar: added TabBarQueueFocus() by name for
 non-docking tab bars. (#8029, #6681)

Amend 655fcf8
---
 imgui_widgets.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 46c418356..9192dbcba 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -9630,7 +9630,7 @@ void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
 void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name)
 {
     IM_ASSERT((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0); // Only supported for manual/explicit tab bars
-    ImGuiID tab_id = TabBarCalcTabID(tab_bar, tab_name);
+    ImGuiID tab_id = TabBarCalcTabID(tab_bar, tab_name, NULL);
     tab_bar->NextSelectedTabId = tab_id;
 }
 

From f0575411c0137c3524fa40fad63d8eb24b8558ee Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 2 Oct 2024 15:23:54 +0200
Subject: [PATCH 0399/2359] Tooltips, Drag and Drop: Fixed an issue where the
 fallback drag and drop payload tooltip appeared during drag and drop release.

E.g. it would otherwise appear when releasing a color button payload.
---
 docs/CHANGELOG.txt | 2 ++
 imgui.cpp          | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index db13bc9b1..f9fb75866 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -71,6 +71,8 @@ Other changes:
 - Scrollbar: Shift+Click scroll to clicked location (pre-1.90.8 default). (#8002, #7328)
 - Scrollbar: added io.ConfigScrollbarScrollByPage setting (default to true). (#8002, #7328)
   Set io.ConfigScrollbarScrollByPage=false to enforce always scrolling to clicked location.
+- Tooltips, Drag and Drop: Fixed an issue where the fallback drag and drop payload tooltip
+  appeared during drag and drop release.
 - Backends: SDL3: Update for API changes: SDL_bool removal. SDL_INIT_TIMER removal.
 - Backends: WebGPU: Fixed DAWN api change using WGPUStringView in WGPUShaderSourceWGSL.
   (#8009, #8010) [@blitz-research]
diff --git a/imgui.cpp b/imgui.cpp
index 5f0c8281b..059a7ec56 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -5521,7 +5521,7 @@ void ImGui::EndFrame()
     // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
     // (e.g. end of your item loop, or before EndFrame) by reading payload data.
     // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
-    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
+    if (g.DragDropActive && g.DragDropSourceFrameCount + 1 < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
     {
         g.DragDropWithinSource = true;
         SetTooltip("...");

From 014b722963f3ca2184b594439d6184ece4078de0 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 2 Oct 2024 18:26:02 +0200
Subject: [PATCH 0400/2359] Tooltips, Drag and Drop: Stabilized name of drag
 and drop tooltip window. (#8036)

---
 docs/CHANGELOG.txt |  3 +++
 imgui.cpp          | 28 +++++++++++++++++-----------
 imgui.h            |  2 +-
 imgui_internal.h   |  1 +
 4 files changed, 22 insertions(+), 12 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index f9fb75866..489d010d8 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -73,6 +73,9 @@ Other changes:
   Set io.ConfigScrollbarScrollByPage=false to enforce always scrolling to clicked location.
 - Tooltips, Drag and Drop: Fixed an issue where the fallback drag and drop payload tooltip
   appeared during drag and drop release.
+- Tooltips, Drag and Drop: Stabilized name of drag and drop tooltip window so that
+  transitioning from an item tooltip to a drag tooltip doesn't leak window auto-sizing
+  info from one to the other. (#8036)
 - Backends: SDL3: Update for API changes: SDL_bool removal. SDL_INIT_TIMER removal.
 - Backends: WebGPU: Fixed DAWN api change using WGPUStringView in WGPUShaderSourceWGSL.
   (#8009, #8010) [@blitz-research]
diff --git a/imgui.cpp b/imgui.cpp
index 059a7ec56..eae120fd7 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3964,6 +3964,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     DisabledStackSize = 0;
     LockMarkEdited = 0;
     TooltipOverrideCount = 0;
+    TooltipPreviousWindow = NULL;
 
     PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);
     PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission
@@ -5152,6 +5153,7 @@ void ImGui::NewFrame()
     g.DragDropWithinSource = false;
     g.DragDropWithinTarget = false;
     g.DragDropHoldJustPressedId = 0;
+    g.TooltipPreviousWindow = NULL;
 
     // Close popups on focus lost (currently wip/opt-in)
     //if (g.IO.AppFocusLost)
@@ -7549,6 +7551,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
         // Clear hit test shape every frame
         window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
 
+        if (flags & ImGuiWindowFlags_Tooltip)
+            g.TooltipPreviousWindow = window;
+
         // Pressing CTRL+C while holding on a window copy its content to the clipboard
         // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
         // Maybe we can support CTRL+C on every element?
@@ -11504,7 +11509,8 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext
 {
     ImGuiContext& g = *GImGui;
 
-    if (g.DragDropWithinSource || g.DragDropWithinTarget)
+    const bool is_dragdrop_tooltip = g.DragDropWithinSource || g.DragDropWithinTarget;
+    if (is_dragdrop_tooltip)
     {
         // Drag and Drop tooltips are positioning differently than other tooltips:
         // - offset visibility to increase visibility around mouse.
@@ -11520,16 +11526,16 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext
         tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
     }
 
-    char window_name[16];
-    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
-    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
-        if (ImGuiWindow* window = FindWindowByName(window_name))
-            if (window->Active)
-            {
-                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
-                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
-                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
-            }
+    const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d";
+    char window_name[32];
+    ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, g.TooltipOverrideCount);
+    if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active)
+    {
+        // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
+        //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name);
+        SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow);
+        ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, ++g.TooltipOverrideCount);
+    }
     ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
     Begin(window_name, NULL, flags | extra_window_flags);
     // 2023-03-09: Added bool return value to the API, but currently always returning true.
diff --git a/imgui.h b/imgui.h
index 59ea4baac..0eebcafb3 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.3 WIP"
-#define IMGUI_VERSION_NUM   19123
+#define IMGUI_VERSION_NUM   19124
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index 113b05426..044ff18c2 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2283,6 +2283,7 @@ struct ImGuiContext
     short                   DisabledStackSize;
     short                   LockMarkEdited;
     short                   TooltipOverrideCount;
+    ImGuiWindow*            TooltipPreviousWindow;              // Window of last tooltip submitted during the frame
     ImVector          ClipboardHandlerData;               // If no custom clipboard handler is defined
     ImVector       MenusIdSubmittedThisFrame;          // A list of menu IDs that were rendered at least once
     ImGuiTypingSelectState  TypingSelectState;                  // State for GetTypingSelectRequest()

From 5109a77f6974bc993bb5cc2f69951f12ba7c59c2 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 2 Oct 2024 18:39:17 +0200
Subject: [PATCH 0401/2359] Tooltips: Tooltips triggered from touch inputs are
 positionned above the item. (#8036)

---
 docs/CHANGELOG.txt |  1 +
 imgui.cpp          | 31 +++++++++++++++++++++++++------
 2 files changed, 26 insertions(+), 6 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 489d010d8..34cba0c1a 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -76,6 +76,7 @@ Other changes:
 - Tooltips, Drag and Drop: Stabilized name of drag and drop tooltip window so that
   transitioning from an item tooltip to a drag tooltip doesn't leak window auto-sizing
   info from one to the other. (#8036)
+- Tooltips: Tooltips triggered from touch inputs are positionned above the item. (#8036)
 - Backends: SDL3: Update for API changes: SDL_bool removal. SDL_INIT_TIMER removal.
 - Backends: WebGPU: Fixed DAWN api change using WGPUStringView in WGPUShaderSourceWGSL.
   (#8009, #8010) [@blitz-research]
diff --git a/imgui.cpp b/imgui.cpp
index eae120fd7..91250b23d 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1136,7 +1136,9 @@ static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduc
 static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
 
 // Tooltip offset
-static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
+static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10);      // Multiplied by g.Style.MouseCursorScale
+static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20);      // Multiplied by g.Style.MouseCursorScale
+static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f);   // Multiplied by g.Style.MouseCursorScale
 
 //-------------------------------------------------------------------------
 // [SECTION] FORWARD DECLARATIONS
@@ -11518,9 +11520,14 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext
         // We call SetNextWindowPos() to enforce position and disable clamping.
         // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
         //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
-        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
+        const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen);
         if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
-            SetNextWindowPos(tooltip_pos);
+        {
+            ImVec2 tooltip_pos = is_touchscreen ? (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * g.Style.MouseCursorScale) : (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * g.Style.MouseCursorScale);
+            ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f);
+            SetNextWindowPos(tooltip_pos, ImGuiCond_None, tooltip_pivot);
+        }
+
         SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
         //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
         tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
@@ -12126,18 +12133,30 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
     if (window->Flags & ImGuiWindowFlags_Tooltip)
     {
         // Position tooltip (always follows mouse + clamp within outer boundaries)
-        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
-        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
+        // FIXME:
+        // - Too many paths. One problem is that FindBestWindowPosForPopupEx() doesn't allow passing a suggested position (so touch screen path doesn't use it by default).
+        // - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
+        // - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
+        //   as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
         IM_ASSERT(g.CurrentWindow == window);
         const float scale = g.Style.MouseCursorScale;
         const ImVec2 ref_pos = NavCalcPreferredRefPos();
-        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
+
+        if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen)
+        {
+            ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
+            if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size)))
+                return tooltip_pos;
+        }
+
+        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
         ImRect r_avoid;
         if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
         else
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
         //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
+
         return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
     }
     IM_ASSERT(0);

From b3c87475a5a93a04d453d6b7144427d9d8ea6b5b Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 3 Oct 2024 16:17:45 +0200
Subject: [PATCH 0402/2359] Drags, Slider: added ImGuiSliderFlags_ClampOnInput,
 ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)

---
 docs/CHANGELOG.txt | 14 ++++++++++++++
 imgui.cpp          |  3 +++
 imgui.h            | 27 +++++++++++++--------------
 imgui_demo.cpp     |  7 ++++++-
 imgui_internal.h   |  1 +
 imgui_widgets.cpp  | 28 +++++++++++++++++++++-------
 6 files changed, 58 insertions(+), 22 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 34cba0c1a..20142608c 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -41,6 +41,13 @@ HOW TO UPDATE?
 
 Breaking changes:
 
+- Drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is still a special
+  value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)
+- Drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange.
+  It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed).
+  Although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f
+  to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76)
+
 Other changes:
 
 - Error Handling: Enabled/improved error recovery systems. (#1651, #5654)
@@ -71,6 +78,13 @@ Other changes:
 - Scrollbar: Shift+Click scroll to clicked location (pre-1.90.8 default). (#8002, #7328)
 - Scrollbar: added io.ConfigScrollbarScrollByPage setting (default to true). (#8002, #7328)
   Set io.ConfigScrollbarScrollByPage=false to enforce always scrolling to clicked location.
+- Drags: ImGuiSliderFlags_AlwaysClamp split into two distinct flags: (#7968, #3361, #76)
+  - ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput + ImGuiSliderFlags_ClampZeroRange.
+  - Previously _AlwaysClamp only did the equivalent of _ClampOnInput.
+  - Added ImGuiSliderFlags_ClampOnInput which is now a subset of AlwaysClamp.
+    (note that it was the old name of AlwaysClamp, but we are reintroducing that name).
+  - Added ImGuiSliderFlags_ClampZeroRange to enforce clamping even when v_min==v_max==0.0f
+    in drag functions. Sliders are not affected.
 - Tooltips, Drag and Drop: Fixed an issue where the fallback drag and drop payload tooltip
   appeared during drag and drop release.
 - Tooltips, Drag and Drop: Stabilized name of drag and drop tooltip window so that
diff --git a/imgui.cpp b/imgui.cpp
index 91250b23d..2ae59486d 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -430,6 +430,9 @@ CODE
  When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  You can read releases logs https://github.com/ocornut/imgui/releases for more details.
 
+ - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)
+                       - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed).
+                         although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76)
  - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
  - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
                             - io.GetClipboardTextFn         -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData.
diff --git a/imgui.h b/imgui.h
index 0eebcafb3..5c362a6a2 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.3 WIP"
-#define IMGUI_VERSION_NUM   19124
+#define IMGUI_VERSION_NUM   19125
 #define IMGUI_HAS_TABLE
 
 /*
@@ -1788,19 +1788,18 @@ enum ImGuiColorEditFlags_
 
 // Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.
 // 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.
-// (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigDragClickToInputText)
+// (Those are per-item flags. There is shared behavior flag too: ImGuiIO: io.ConfigDragClickToInputText)
 enum ImGuiSliderFlags_
 {
-    ImGuiSliderFlags_None                   = 0,
-    ImGuiSliderFlags_AlwaysClamp            = 1 << 4,       // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.
-    ImGuiSliderFlags_Logarithmic            = 1 << 5,       // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits.
-    ImGuiSliderFlags_NoRoundToFormat        = 1 << 6,       // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits).
-    ImGuiSliderFlags_NoInput                = 1 << 7,       // Disable CTRL+Click or Enter key allowing to input text directly into the widget.
-    ImGuiSliderFlags_WrapAround             = 1 << 8,       // Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions for now.
-    ImGuiSliderFlags_InvalidMask_           = 0x7000000F,   // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed.
-
-    // Obsolete names
-    //ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp, // [renamed in 1.79]
+    ImGuiSliderFlags_None               = 0,
+    ImGuiSliderFlags_Logarithmic        = 1 << 5,       // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits.
+    ImGuiSliderFlags_NoRoundToFormat    = 1 << 6,       // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits).
+    ImGuiSliderFlags_NoInput            = 1 << 7,       // Disable CTRL+Click or Enter key allowing to input text directly into the widget.
+    ImGuiSliderFlags_WrapAround         = 1 << 8,       // Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now.
+    ImGuiSliderFlags_ClampOnInput       = 1 << 9,       // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.
+    ImGuiSliderFlags_ClampZeroRange     = 1 << 10,      // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it.
+    ImGuiSliderFlags_AlwaysClamp        = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange,
+    ImGuiSliderFlags_InvalidMask_       = 0x7000000F,   // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed.
 };
 
 // Identify a mouse button.
@@ -3170,8 +3169,8 @@ struct ImDrawList
     //inline  void  AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024)
     //inline  void  AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); }                        // OBSOLETED in 1.90.5 (Mar 2024)
     //inline  void  PathEllipticalArcTo(const ImVec2& center, float radius_x, float radius_y, float rot, float a_min, float a_max, int num_segments = 0) { PathEllipticalArcTo(center, ImVec2(radius_x, radius_y), rot, a_min, a_max, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024)
-    //inline  void  AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021)
-    //inline  void  PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021)
+    //inline  void  AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); }                         // OBSOLETED in 1.80 (Jan 2021)
+    //inline  void  PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); }                                                                                // OBSOLETED in 1.80 (Jan 2021)
 
     // [Internal helpers]
     IMGUI_API void  _ResetForNewFrame();
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index feaee3be9..dc2f4d39b 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -2265,7 +2265,10 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data)
         // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same!
         static ImGuiSliderFlags flags = ImGuiSliderFlags_None;
         ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp);
-        ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click.");
+        ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", &flags, ImGuiSliderFlags_ClampOnInput);
+        ImGui::SameLine(); HelpMarker("Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.");
+        ImGui::CheckboxFlags("ImGuiSliderFlags_ClampZeroRange", &flags, ImGuiSliderFlags_ClampZeroRange);
+        ImGui::SameLine(); HelpMarker("Clamp even if min==max==0.0f. Otherwise DragXXX functions don't clamp.");
         ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic);
         ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values).");
         ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat);
@@ -2283,6 +2286,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data)
         ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags);
         ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags);
         ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags);
+        //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);
 
         // Sliders
diff --git a/imgui_internal.h b/imgui_internal.h
index 044ff18c2..f8b4d9d21 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -3402,6 +3402,7 @@ namespace ImGui
     IMGUI_API bool          DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format, void* p_data_when_empty = NULL);
     IMGUI_API int           DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2);
     IMGUI_API bool          DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max);
+    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);
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 9192dbcba..891fcad23 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -2351,6 +2351,12 @@ bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_m
     return false;
 }
 
+bool ImGui::DataTypeIsZero(ImGuiDataType data_type, const void* p_data)
+{
+    ImGuiContext& g = *GImGui;
+    return DataTypeCompare(data_type, p_data, &g.DataTypeZeroValue) == 0;
+}
+
 static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
 {
     static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
@@ -2409,7 +2415,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
 {
     ImGuiContext& g = *GImGui;
     const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
-    const bool is_bounded = (v_min < v_max);
+    const bool is_bounded = (v_min < v_max) || ((v_min == v_max) && (v_min != 0.0f || (flags & ImGuiSliderFlags_ClampZeroRange)));
     const bool is_wrapped = is_bounded && (flags & ImGuiSliderFlags_WrapAround);
     const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;
     const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
@@ -2632,9 +2638,17 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data,
 
     if (temp_input_is_active)
     {
-        // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set
-        const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0);
-        return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL);
+        // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp)
+        bool clamp_enabled = false;
+        if ((flags & ImGuiSliderFlags_ClampOnInput) && (p_min != NULL || p_max != NULL))
+        {
+            const int clamp_range_dir = (p_min != NULL && p_max != NULL) ? DataTypeCompare(data_type, p_min, p_max) : 0; // -1 when *p_min < *p_max, == 0 when *p_min == *p_max
+            if (p_min == NULL || p_max == NULL || clamp_range_dir < 0)
+                clamp_enabled = true;
+            else if ((p_min != NULL && p_max != NULL) && clamp_range_dir == 0)
+                clamp_enabled = DataTypeIsZero(data_type, p_min) ? ((flags & ImGuiSliderFlags_ClampZeroRange) != 0) : true;
+        }
+        return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);
     }
 
     // Draw frame
@@ -3214,9 +3228,9 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat
 
     if (temp_input_is_active)
     {
-        // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set
-        const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0;
-        return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL);
+        // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp)
+        const bool clamp_enabled = (flags & ImGuiSliderFlags_ClampOnInput) != 0;
+        return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);
     }
 
     // Draw frame

From 3d399bcecabc5c260073e700cbd674cc36b6e6ab Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 3 Oct 2024 16:49:38 +0200
Subject: [PATCH 0403/2359] Docs: amend docs to explain case of using multiple
 overlayed ButtonBehavior(). (#8030, #7961, #7669)

---
 docs/CHANGELOG.txt |  8 ++++++++
 imgui.cpp          |  7 +++++--
 imgui_widgets.cpp  | 11 ++++++++---
 3 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 20142608c..d800975c4 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -101,6 +101,14 @@ Other changes:
 
 Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.2
 
+Breaking changes:
+
+ - Internals: using multiple overlayed ButtonBehavior() with same ID will now have the
+   io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030)
+   It was one of the rare case where using same ID is legal. Workarounds:
+   - use single ButtonBehavior() call with multiple _MouseButton flags
+   - or surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
+
 Other changes:
 
 - Added io.ConfigDebugHighlightIdConflicts debug feature! (#7961, #7669)
diff --git a/imgui.cpp b/imgui.cpp
index 2ae59486d..9faec405c 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -433,6 +433,8 @@ CODE
  - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)
                        - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed).
                          although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76)
+ - 2024/09/10 (1.91.2) - internals: using multiple overlayed ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030)
+                         it was one of the rare case where using same ID is legal. workarounds: (1) use single ButtonBehavior() call with multiple _MouseButton flags, or (2) surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
  - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag.
  - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure:
                             - io.GetClipboardTextFn         -> platform_io.Platform_GetClipboardTextFn + changed 'void* user_data' to 'ImGuiContext* ctx'. Pull your user data from platform_io.ClipboardUserData.
@@ -10656,9 +10658,10 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
         Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount);
         BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
         BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
+        //BulletText("Code intending to use duplicate ID may use e.g. PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()"); // Not making this too visible for fear of it being abused.
         BulletText("Set io.ConfigDebugDetectIdConflicts=false to disable this warning in non-programmers builds.");
         Separator();
-        Text("(Hold CTRL and: use");
+        Text("(Hold CTRL to: use");
         SameLine();
         if (SmallButton("Item Picker"))
             DebugStartItemPicker();
@@ -10673,7 +10676,7 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
     if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame
     {
         Separator();
-        Text("(Hold CTRL and:");
+        Text("(Hold CTRL to:");
         SameLine();
         if (SmallButton("Enable Asserts"))
             g.IO.ConfigErrorRecoveryEnableAssert = true;
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 891fcad23..1e24b4ebc 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -482,9 +482,14 @@ void ImGui::BulletTextV(const char* fmt, va_list args)
 //   Frame N + RepeatDelay + RepeatRate*N   true                     true              -                   true
 //-------------------------------------------------------------------------------------------------------------------------------------------------
 
-// FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc.
-// And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);'
-// For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading.
+// - FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc.
+//   And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);'
+//   For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading.
+// - Since v1.91.2 (Sept 2024) we included io.ConfigDebugHighlightIdConflicts feature.
+//   One idiom which was previously valid which will now emit a warning is when using multiple overlayed ButtonBehavior()
+//   with same ID and different MouseButton (see #8030). You can fix it by:
+//       (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags.
+//    or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
 bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
 {
     ImGuiContext& g = *GImGui;

From 8db126188df82282c193f894c5e5ba390869c836 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 3 Oct 2024 17:32:05 +0200
Subject: [PATCH 0404/2359] Fixed static analyser warning. Amend b3c8747

---
 imgui_widgets.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 1e24b4ebc..8f16f6ec0 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -2650,7 +2650,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data,
             const int clamp_range_dir = (p_min != NULL && p_max != NULL) ? DataTypeCompare(data_type, p_min, p_max) : 0; // -1 when *p_min < *p_max, == 0 when *p_min == *p_max
             if (p_min == NULL || p_max == NULL || clamp_range_dir < 0)
                 clamp_enabled = true;
-            else if ((p_min != NULL && p_max != NULL) && clamp_range_dir == 0)
+            else if (clamp_range_dir == 0)
                 clamp_enabled = DataTypeIsZero(data_type, p_min) ? ((flags & ImGuiSliderFlags_ClampZeroRange) != 0) : true;
         }
         return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);

From cb16568fca5297512ff6a8f3b877f461c4323fbe Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 4 Oct 2024 14:06:33 +0200
Subject: [PATCH 0405/2359] Version 1.91.3

---
 docs/CHANGELOG.txt | 10 ++++++----
 imgui.cpp          |  2 +-
 imgui.h            |  6 +++---
 imgui_demo.cpp     |  2 +-
 imgui_draw.cpp     |  2 +-
 imgui_internal.h   |  2 +-
 imgui_tables.cpp   |  2 +-
 imgui_widgets.cpp  |  2 +-
 8 files changed, 15 insertions(+), 13 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index d800975c4..8c91d1300 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -36,9 +36,11 @@ HOW TO UPDATE?
 - Please report any issue!
 
 -----------------------------------------------------------------------
- VERSION 1.91.3 WIP (In Progress)
+ VERSION 1.91.3 (Released 2024-10-04)
 -----------------------------------------------------------------------
 
+Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.3
+
 Breaking changes:
 
 - Drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is still a special
@@ -61,7 +63,7 @@ Other changes:
   - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT().
   - By design, we do not allow error recovery to be 100% silent. One of the options needs to be enabled!
   - Possible usage: facilitate recovery from errors triggered from a scripting language or
-    after specific exceptions handlers. Surface errors to programmers in less agressive ways.
+    after specific exceptions handlers. Surface errors to programmers in less aggressive ways.
   - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled
     when making direct imgui API calls! Otherwise it would severely hinder your ability to
     catch and correct mistakes!
@@ -78,7 +80,7 @@ Other changes:
 - Scrollbar: Shift+Click scroll to clicked location (pre-1.90.8 default). (#8002, #7328)
 - Scrollbar: added io.ConfigScrollbarScrollByPage setting (default to true). (#8002, #7328)
   Set io.ConfigScrollbarScrollByPage=false to enforce always scrolling to clicked location.
-- Drags: ImGuiSliderFlags_AlwaysClamp split into two distinct flags: (#7968, #3361, #76)
+- Drags: split ImGuiSliderFlags_AlwaysClamp into two distinct flags: (#7968, #3361, #76)
   - ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput + ImGuiSliderFlags_ClampZeroRange.
   - Previously _AlwaysClamp only did the equivalent of _ClampOnInput.
   - Added ImGuiSliderFlags_ClampOnInput which is now a subset of AlwaysClamp.
@@ -90,7 +92,7 @@ Other changes:
 - Tooltips, Drag and Drop: Stabilized name of drag and drop tooltip window so that
   transitioning from an item tooltip to a drag tooltip doesn't leak window auto-sizing
   info from one to the other. (#8036)
-- Tooltips: Tooltips triggered from touch inputs are positionned above the item. (#8036)
+- Tooltips: Tooltips triggered from touch inputs are positioned above the item. (#8036)
 - Backends: SDL3: Update for API changes: SDL_bool removal. SDL_INIT_TIMER removal.
 - Backends: WebGPU: Fixed DAWN api change using WGPUStringView in WGPUShaderSourceWGSL.
   (#8009, #8010) [@blitz-research]
diff --git a/imgui.cpp b/imgui.cpp
index 9faec405c..3bbaf018f 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3 WIP
+// dear imgui, v1.91.3
 // (main code and documentation)
 
 // Help:
diff --git a/imgui.h b/imgui.h
index 5c362a6a2..77ca8e04f 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3 WIP
+// dear imgui, v1.91.3
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.3 WIP"
-#define IMGUI_VERSION_NUM   19125
+#define IMGUI_VERSION       "1.91.3"
+#define IMGUI_VERSION_NUM   19130
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index dc2f4d39b..8df1755fb 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3 WIP
+// dear imgui, v1.91.3
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index b7a00285f..8084e53c3 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3 WIP
+// dear imgui, v1.91.3
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index f8b4d9d21..9f47ecd21 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3 WIP
+// dear imgui, v1.91.3
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 4a6fbed7c..64126f41d 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3 WIP
+// dear imgui, v1.91.3
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 8f16f6ec0..322c0846c 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3 WIP
+// dear imgui, v1.91.3
 // (widgets code)
 
 /*

From 1dde20ff4a1ae645bda31f3ee983733994d2f6fc Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 7 Oct 2024 17:39:28 +0200
Subject: [PATCH 0406/2359] Version 1.91.4 WIP

---
 docs/CHANGELOG.txt | 9 +++++++++
 imgui.cpp          | 2 +-
 imgui.h            | 6 +++---
 imgui_demo.cpp     | 2 +-
 imgui_draw.cpp     | 2 +-
 imgui_internal.h   | 2 +-
 imgui_tables.cpp   | 2 +-
 imgui_widgets.cpp  | 2 +-
 8 files changed, 18 insertions(+), 9 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 8c91d1300..b5f526809 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -35,6 +35,15 @@ HOW TO UPDATE?
   and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users.
 - Please report any issue!
 
+-----------------------------------------------------------------------
+ VERSION 1.91.4 WIP
+-----------------------------------------------------------------------
+
+Breaking changes:
+
+Other changes:
+
+
 -----------------------------------------------------------------------
  VERSION 1.91.3 (Released 2024-10-04)
 -----------------------------------------------------------------------
diff --git a/imgui.cpp b/imgui.cpp
index 3bbaf018f..2d7edc43e 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3
+// dear imgui, v1.91.4 WIP
 // (main code and documentation)
 
 // Help:
diff --git a/imgui.h b/imgui.h
index 77ca8e04f..49ad70cee 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3
+// dear imgui, v1.91.4 WIP
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.3"
-#define IMGUI_VERSION_NUM   19130
+#define IMGUI_VERSION       "1.91.4 WIP"
+#define IMGUI_VERSION_NUM   19131
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 8df1755fb..a85e28e54 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3
+// dear imgui, v1.91.4 WIP
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 8084e53c3..b69bc789f 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3
+// dear imgui, v1.91.4 WIP
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index 9f47ecd21..05378c3d9 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3
+// dear imgui, v1.91.4 WIP
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 64126f41d..491566d7a 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3
+// dear imgui, v1.91.4 WIP
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 322c0846c..baaf4f4e7 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.3
+// dear imgui, v1.91.4 WIP
 // (widgets code)
 
 /*

From 9bd5d8a24051a370bc8331f85e71d0b78c73687d Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 7 Oct 2024 17:52:57 +0200
Subject: [PATCH 0407/2359] Backends: misc renaming of locals. Use 'draw_list'
 instead of 'cmd_list'. Avoid using 'ctx'.

This is likely to trigger merging issues. If it does, best to always get "theirs" and rename in there.
---
 backends/imgui_impl_allegro5.cpp     |  28 ++---
 backends/imgui_impl_dx10.cpp         | 126 +++++++++++------------
 backends/imgui_impl_dx11.cpp         | 140 ++++++++++++-------------
 backends/imgui_impl_dx12.cpp         |  56 +++++-----
 backends/imgui_impl_dx12.h           |   3 +-
 backends/imgui_impl_dx9.cpp          | 148 ++++++++++++++-------------
 backends/imgui_impl_metal.mm         |  16 +--
 backends/imgui_impl_opengl2.cpp      |  12 +--
 backends/imgui_impl_opengl3.cpp      |  20 ++--
 backends/imgui_impl_sdlrenderer2.cpp |  14 +--
 backends/imgui_impl_sdlrenderer3.cpp |  14 +--
 backends/imgui_impl_vulkan.cpp       |  22 ++--
 backends/imgui_impl_wgpu.cpp         |  22 ++--
 13 files changed, 314 insertions(+), 307 deletions(-)

diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp
index bf1019e2c..9c2571623 100644
--- a/backends/imgui_impl_allegro5.cpp
+++ b/backends/imgui_impl_allegro5.cpp
@@ -149,14 +149,14 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data)
     // Render command lists
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
 
         ImVector& vertices = bd->BufVertices;
 #if ALLEGRO_HAS_DRAW_INDEXED_PRIM
-        vertices.resize(cmd_list->VtxBuffer.Size);
-        for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
+        vertices.resize(draw_list->VtxBuffer.Size);
+        for (int i = 0; i < draw_list->VtxBuffer.Size; i++)
         {
-            const ImDrawVert* src_v = &cmd_list->VtxBuffer[i];
+            const ImDrawVert* src_v = &draw_list->VtxBuffer[i];
             ImDrawVertAllegro* dst_v = &vertices[i];
             DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v);
         }
@@ -166,21 +166,21 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data)
             // FIXME-OPT: Allegro doesn't support 16-bit indices.
             // You can '#define ImDrawIdx int' in imconfig.h to request Dear ImGui to output 32-bit indices.
             // Otherwise, we convert them from 16-bit to 32-bit at runtime here, which works perfectly but is a little wasteful.
-            bd->BufIndices.resize(cmd_list->IdxBuffer.Size);
-            for (int i = 0; i < cmd_list->IdxBuffer.Size; ++i)
-                bd->BufIndices[i] = (int)cmd_list->IdxBuffer.Data[i];
+            bd->BufIndices.resize(draw_list->IdxBuffer.Size);
+            for (int i = 0; i < draw_list->IdxBuffer.Size; ++i)
+                bd->BufIndices[i] = (int)draw_list->IdxBuffer.Data[i];
             indices = bd->BufIndices.Data;
         }
         else if (sizeof(ImDrawIdx) == 4)
         {
-            indices = (const int*)cmd_list->IdxBuffer.Data;
+            indices = (const int*)draw_list->IdxBuffer.Data;
         }
 #else
         // Allegro's implementation of al_draw_indexed_prim() for DX9 was broken until 5.2.5. Unindex buffers ourselves while converting vertex format.
-        vertices.resize(cmd_list->IdxBuffer.Size);
-        for (int i = 0; i < cmd_list->IdxBuffer.Size; i++)
+        vertices.resize(draw_list->IdxBuffer.Size);
+        for (int i = 0; i < draw_list->IdxBuffer.Size; i++)
         {
-            const ImDrawVert* src_v = &cmd_list->VtxBuffer[cmd_list->IdxBuffer[i]];
+            const ImDrawVert* src_v = &draw_list->VtxBuffer[draw_list->IdxBuffer[i]];
             ImDrawVertAllegro* dst_v = &vertices[i];
             DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v);
         }
@@ -188,9 +188,9 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data)
 
         // Render command lists
         ImVec2 clip_off = draw_data->DisplayPos;
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -198,7 +198,7 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data)
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplAllegro5_SetupRenderState(draw_data);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp
index 9691b49fd..96932c3af 100644
--- a/backends/imgui_impl_dx10.cpp
+++ b/backends/imgui_impl_dx10.cpp
@@ -80,7 +80,7 @@ static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData()
 }
 
 // Functions
-static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* ctx)
+static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device)
 {
     ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
 
@@ -92,26 +92,26 @@ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device*
     vp.MinDepth = 0.0f;
     vp.MaxDepth = 1.0f;
     vp.TopLeftX = vp.TopLeftY = 0;
-    ctx->RSSetViewports(1, &vp);
+    device->RSSetViewports(1, &vp);
 
     // Bind shader and vertex buffers
     unsigned int stride = sizeof(ImDrawVert);
     unsigned int offset = 0;
-    ctx->IASetInputLayout(bd->pInputLayout);
-    ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
-    ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
-    ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
-    ctx->VSSetShader(bd->pVertexShader);
-    ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
-    ctx->PSSetShader(bd->pPixelShader);
-    ctx->PSSetSamplers(0, 1, &bd->pFontSampler);
-    ctx->GSSetShader(nullptr);
+    device->IASetInputLayout(bd->pInputLayout);
+    device->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
+    device->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
+    device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+    device->VSSetShader(bd->pVertexShader);
+    device->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
+    device->PSSetShader(bd->pPixelShader);
+    device->PSSetSamplers(0, 1, &bd->pFontSampler);
+    device->GSSetShader(nullptr);
 
     // Setup render state
     const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
-    ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
-    ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0);
-    ctx->RSSetState(bd->pRasterizerState);
+    device->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
+    device->OMSetDepthStencilState(bd->pDepthStencilState, 0);
+    device->RSSetState(bd->pRasterizerState);
 }
 
 // Render function
@@ -122,7 +122,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
         return;
 
     ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
-    ID3D10Device* ctx = bd->pd3dDevice;
+    ID3D10Device* device = bd->pd3dDevice;
 
     // Create and grow vertex/index buffers if needed
     if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
@@ -136,7 +136,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
         desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
         desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
         desc.MiscFlags = 0;
-        if (ctx->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
+        if (device->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
             return;
     }
 
@@ -150,7 +150,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
         desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
         desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
         desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
-        if (ctx->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
+        if (device->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
             return;
     }
 
@@ -161,11 +161,11 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
     bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
-        memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
-        vtx_dst += cmd_list->VtxBuffer.Size;
-        idx_dst += cmd_list->IdxBuffer.Size;
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
+        memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
+        vtx_dst += draw_list->VtxBuffer.Size;
+        idx_dst += draw_list->IdxBuffer.Size;
     }
     bd->pVB->Unmap();
     bd->pIB->Unmap();
@@ -217,24 +217,24 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
     };
     BACKUP_DX10_STATE old = {};
     old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
-    ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
-    ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
-    ctx->RSGetState(&old.RS);
-    ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
-    ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
-    ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
-    ctx->PSGetSamplers(0, 1, &old.PSSampler);
-    ctx->PSGetShader(&old.PS);
-    ctx->VSGetShader(&old.VS);
-    ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
-    ctx->GSGetShader(&old.GS);
-    ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
-    ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
-    ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
-    ctx->IAGetInputLayout(&old.InputLayout);
+    device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
+    device->RSGetViewports(&old.ViewportsCount, old.Viewports);
+    device->RSGetState(&old.RS);
+    device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
+    device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
+    device->PSGetShaderResources(0, 1, &old.PSShaderResource);
+    device->PSGetSamplers(0, 1, &old.PSSampler);
+    device->PSGetShader(&old.PS);
+    device->VSGetShader(&old.VS);
+    device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
+    device->GSGetShader(&old.GS);
+    device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
+    device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
+    device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
+    device->IAGetInputLayout(&old.InputLayout);
 
     // Setup desired DX state
-    ImGui_ImplDX10_SetupRenderState(draw_data, ctx);
+    ImGui_ImplDX10_SetupRenderState(draw_data, device);
 
     // Render command lists
     // (Because we merged all buffers into a single one, we maintain our own offset into them)
@@ -243,18 +243,18 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
     ImVec2 clip_off = draw_data->DisplayPos;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback)
             {
                 // User callback, registered via ImDrawList::AddCallback()
                 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
-                    ImGui_ImplDX10_SetupRenderState(draw_data, ctx);
+                    ImGui_ImplDX10_SetupRenderState(draw_data, device);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -266,34 +266,34 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
 
                 // Apply scissor/clipping rectangle
                 const D3D10_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
-                ctx->RSSetScissorRects(1, &r);
+                device->RSSetScissorRects(1, &r);
 
                 // Bind texture, Draw
                 ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->GetTexID();
-                ctx->PSSetShaderResources(0, 1, &texture_srv);
-                ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
+                device->PSSetShaderResources(0, 1, &texture_srv);
+                device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
             }
         }
-        global_idx_offset += cmd_list->IdxBuffer.Size;
-        global_vtx_offset += cmd_list->VtxBuffer.Size;
+        global_idx_offset += draw_list->IdxBuffer.Size;
+        global_vtx_offset += draw_list->VtxBuffer.Size;
     }
 
     // Restore modified DX state
-    ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
-    ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
-    ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
-    ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
-    ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
-    ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
-    ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
-    ctx->PSSetShader(old.PS); if (old.PS) old.PS->Release();
-    ctx->VSSetShader(old.VS); if (old.VS) old.VS->Release();
-    ctx->GSSetShader(old.GS); if (old.GS) old.GS->Release();
-    ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
-    ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
-    ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
-    ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
-    ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
+    device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
+    device->RSSetViewports(old.ViewportsCount, old.Viewports);
+    device->RSSetState(old.RS); if (old.RS) old.RS->Release();
+    device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
+    device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
+    device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
+    device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
+    device->PSSetShader(old.PS); if (old.PS) old.PS->Release();
+    device->VSSetShader(old.VS); if (old.VS) old.VS->Release();
+    device->GSSetShader(old.GS); if (old.GS) old.GS->Release();
+    device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
+    device->IASetPrimitiveTopology(old.PrimitiveTopology);
+    device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
+    device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
+    device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
 }
 
 static void ImGui_ImplDX10_CreateFontsTexture()
diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp
index 167bda673..f656bbc55 100644
--- a/backends/imgui_impl_dx11.cpp
+++ b/backends/imgui_impl_dx11.cpp
@@ -81,7 +81,7 @@ static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData()
 }
 
 // Functions
-static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* ctx)
+static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* device_ctx)
 {
     ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
 
@@ -93,29 +93,29 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC
     vp.MinDepth = 0.0f;
     vp.MaxDepth = 1.0f;
     vp.TopLeftX = vp.TopLeftY = 0;
-    ctx->RSSetViewports(1, &vp);
+    device_ctx->RSSetViewports(1, &vp);
 
     // Setup shader and vertex buffers
     unsigned int stride = sizeof(ImDrawVert);
     unsigned int offset = 0;
-    ctx->IASetInputLayout(bd->pInputLayout);
-    ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
-    ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
-    ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
-    ctx->VSSetShader(bd->pVertexShader, nullptr, 0);
-    ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
-    ctx->PSSetShader(bd->pPixelShader, nullptr, 0);
-    ctx->PSSetSamplers(0, 1, &bd->pFontSampler);
-    ctx->GSSetShader(nullptr, nullptr, 0);
-    ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
-    ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
-    ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
+    device_ctx->IASetInputLayout(bd->pInputLayout);
+    device_ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
+    device_ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
+    device_ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+    device_ctx->VSSetShader(bd->pVertexShader, nullptr, 0);
+    device_ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
+    device_ctx->PSSetShader(bd->pPixelShader, nullptr, 0);
+    device_ctx->PSSetSamplers(0, 1, &bd->pFontSampler);
+    device_ctx->GSSetShader(nullptr, nullptr, 0);
+    device_ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
+    device_ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
+    device_ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
 
     // Setup blend state
     const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
-    ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
-    ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0);
-    ctx->RSSetState(bd->pRasterizerState);
+    device_ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
+    device_ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0);
+    device_ctx->RSSetState(bd->pRasterizerState);
 }
 
 // Render function
@@ -126,7 +126,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
         return;
 
     ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
-    ID3D11DeviceContext* ctx = bd->pd3dDeviceContext;
+    ID3D11DeviceContext* device = bd->pd3dDeviceContext;
 
     // Create and grow vertex/index buffers if needed
     if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
@@ -159,28 +159,28 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
 
     // Upload vertex/index data into a single contiguous GPU buffer
     D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
-    if (ctx->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
+    if (device->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
         return;
-    if (ctx->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
+    if (device->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
         return;
     ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
     ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
-        memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
-        vtx_dst += cmd_list->VtxBuffer.Size;
-        idx_dst += cmd_list->IdxBuffer.Size;
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
+        memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
+        vtx_dst += draw_list->VtxBuffer.Size;
+        idx_dst += draw_list->IdxBuffer.Size;
     }
-    ctx->Unmap(bd->pVB, 0);
-    ctx->Unmap(bd->pIB, 0);
+    device->Unmap(bd->pVB, 0);
+    device->Unmap(bd->pIB, 0);
 
     // Setup orthographic projection matrix into our constant buffer
     // 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.
     {
         D3D11_MAPPED_SUBRESOURCE mapped_resource;
-        if (ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
+        if (device->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
             return;
         VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData;
         float L = draw_data->DisplayPos.x;
@@ -195,7 +195,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
             { (R+L)/(L-R),  (T+B)/(B-T),    0.5f,       1.0f },
         };
         memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
-        ctx->Unmap(bd->pVertexConstantBuffer, 0);
+        device->Unmap(bd->pVertexConstantBuffer, 0);
     }
 
     // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
@@ -225,26 +225,26 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
     };
     BACKUP_DX11_STATE old = {};
     old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
-    ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
-    ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
-    ctx->RSGetState(&old.RS);
-    ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
-    ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
-    ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
-    ctx->PSGetSamplers(0, 1, &old.PSSampler);
+    device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
+    device->RSGetViewports(&old.ViewportsCount, old.Viewports);
+    device->RSGetState(&old.RS);
+    device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
+    device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
+    device->PSGetShaderResources(0, 1, &old.PSShaderResource);
+    device->PSGetSamplers(0, 1, &old.PSSampler);
     old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256;
-    ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
-    ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
-    ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
-    ctx->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount);
+    device->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
+    device->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
+    device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
+    device->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount);
 
-    ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
-    ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
-    ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
-    ctx->IAGetInputLayout(&old.InputLayout);
+    device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
+    device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
+    device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
+    device->IAGetInputLayout(&old.InputLayout);
 
     // Setup desired DX state
-    ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
+    ImGui_ImplDX11_SetupRenderState(draw_data, device);
 
     // Render command lists
     // (Because we merged all buffers into a single one, we maintain our own offset into them)
@@ -253,18 +253,18 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
     ImVec2 clip_off = draw_data->DisplayPos;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback != nullptr)
             {
                 // User callback, registered via ImDrawList::AddCallback()
                 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
-                    ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
+                    ImGui_ImplDX11_SetupRenderState(draw_data, device);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -276,36 +276,36 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
 
                 // Apply scissor/clipping rectangle
                 const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
-                ctx->RSSetScissorRects(1, &r);
+                device->RSSetScissorRects(1, &r);
 
                 // Bind texture, Draw
                 ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID();
-                ctx->PSSetShaderResources(0, 1, &texture_srv);
-                ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
+                device->PSSetShaderResources(0, 1, &texture_srv);
+                device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
             }
         }
-        global_idx_offset += cmd_list->IdxBuffer.Size;
-        global_vtx_offset += cmd_list->VtxBuffer.Size;
+        global_idx_offset += draw_list->IdxBuffer.Size;
+        global_vtx_offset += draw_list->VtxBuffer.Size;
     }
 
     // Restore modified DX state
-    ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
-    ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
-    ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
-    ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
-    ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
-    ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
-    ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
-    ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
+    device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
+    device->RSSetViewports(old.ViewportsCount, old.Viewports);
+    device->RSSetState(old.RS); if (old.RS) old.RS->Release();
+    device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
+    device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
+    device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
+    device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
+    device->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
     for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
-    ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
-    ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
-    ctx->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release();
+    device->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
+    device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
+    device->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release();
     for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
-    ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
-    ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
-    ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
-    ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
+    device->IASetPrimitiveTopology(old.PrimitiveTopology);
+    device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
+    device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
+    device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
 }
 
 static void ImGui_ImplDX11_CreateFontsTexture()
diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index 32f1622cd..c63503cc0 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -95,7 +95,7 @@ struct VERTEX_CONSTANT_BUFFER_DX12
 };
 
 // Functions
-static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr)
+static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
 {
     ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
 
@@ -125,7 +125,7 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic
     vp.MinDepth = 0.0f;
     vp.MaxDepth = 1.0f;
     vp.TopLeftX = vp.TopLeftY = 0.0f;
-    ctx->RSSetViewports(1, &vp);
+    command_list->RSSetViewports(1, &vp);
 
     // Bind shader and vertex buffers
     unsigned int stride = sizeof(ImDrawVert);
@@ -135,21 +135,21 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic
     vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
     vbv.SizeInBytes = fr->VertexBufferSize * stride;
     vbv.StrideInBytes = stride;
-    ctx->IASetVertexBuffers(0, 1, &vbv);
+    command_list->IASetVertexBuffers(0, 1, &vbv);
     D3D12_INDEX_BUFFER_VIEW ibv;
     memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
     ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
     ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
     ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
-    ctx->IASetIndexBuffer(&ibv);
-    ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
-    ctx->SetPipelineState(bd->pPipelineState);
-    ctx->SetGraphicsRootSignature(bd->pRootSignature);
-    ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
+    command_list->IASetIndexBuffer(&ibv);
+    command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+    command_list->SetPipelineState(bd->pPipelineState);
+    command_list->SetGraphicsRootSignature(bd->pRootSignature);
+    command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
 
     // Setup blend factor
     const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
-    ctx->OMSetBlendFactor(blend_factor);
+    command_list->OMSetBlendFactor(blend_factor);
 }
 
 template
@@ -161,7 +161,7 @@ static inline void SafeRelease(T*& res)
 }
 
 // Render function
-void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx)
+void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
 {
     // Avoid rendering when minimized
     if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
@@ -233,17 +233,17 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL
     ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
-        memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
-        vtx_dst += cmd_list->VtxBuffer.Size;
-        idx_dst += cmd_list->IdxBuffer.Size;
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
+        memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
+        vtx_dst += draw_list->VtxBuffer.Size;
+        idx_dst += draw_list->IdxBuffer.Size;
     }
     fr->VertexBuffer->Unmap(0, &range);
     fr->IndexBuffer->Unmap(0, &range);
 
     // Setup desired DX state
-    ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
+    ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
 
     // Render command lists
     // (Because we merged all buffers into a single one, we maintain our own offset into them)
@@ -252,18 +252,18 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL
     ImVec2 clip_off = draw_data->DisplayPos;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback != nullptr)
             {
                 // User callback, registered via ImDrawList::AddCallback()
                 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
-                    ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
+                    ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -273,17 +273,19 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
                     continue;
 
-                // Apply Scissor/clipping rectangle, Bind texture, Draw
+                // Apply scissor/clipping rectangle
                 const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
+                command_list->RSSetScissorRects(1, &r);
+
+                // Bind texture, Draw
                 D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
                 texture_handle.ptr = (UINT64)pcmd->GetTexID();
-                ctx->SetGraphicsRootDescriptorTable(1, texture_handle);
-                ctx->RSSetScissorRects(1, &r);
-                ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
+                command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
+                command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
             }
         }
-        global_idx_offset += cmd_list->IdxBuffer.Size;
-        global_vtx_offset += cmd_list->VtxBuffer.Size;
+        global_idx_offset += draw_list->IdxBuffer.Size;
+        global_vtx_offset += draw_list->VtxBuffer.Size;
     }
 }
 
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index e1fd07d6d..08c0a1255 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -29,8 +29,7 @@ struct D3D12_GPU_DESCRIPTOR_HANDLE;
 
 // Follow "Getting Started" link and check examples/ folder to learn about using backends!
 
-// cmd_list is the command list that the implementation will use to render imgui draw lists.
-// Before calling the render function, caller must prepare cmd_list by resetting it and setting the appropriate
+// Before calling the render function, caller must prepare the command list by resetting it and setting the appropriate
 // render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle.
 // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture.
 IMGUI_IMPL_API bool     ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap,
diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp
index 3eff9ab5d..24bd5d3b3 100644
--- a/backends/imgui_impl_dx9.cpp
+++ b/backends/imgui_impl_dx9.cpp
@@ -88,41 +88,43 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
     vp.Height = (DWORD)draw_data->DisplaySize.y;
     vp.MinZ = 0.0f;
     vp.MaxZ = 1.0f;
-    bd->pd3dDevice->SetViewport(&vp);
+
+    LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
+    device->SetViewport(&vp);
 
     // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling.
-    bd->pd3dDevice->SetPixelShader(nullptr);
-    bd->pd3dDevice->SetVertexShader(nullptr);
-    bd->pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
-    bd->pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
-    bd->pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
-    bd->pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
-    bd->pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
-    bd->pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
-    bd->pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
-    bd->pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
-    bd->pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
-    bd->pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
-    bd->pd3dDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
-    bd->pd3dDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
-    bd->pd3dDevice->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA);
-    bd->pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
-    bd->pd3dDevice->SetRenderState(D3DRS_FOGENABLE, FALSE);
-    bd->pd3dDevice->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
-    bd->pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
-    bd->pd3dDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
-    bd->pd3dDevice->SetRenderState(D3DRS_CLIPPING, TRUE);
-    bd->pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
-    bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
-    bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
-    bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
-    bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
-    bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
-    bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
-    bd->pd3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
-    bd->pd3dDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
-    bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
-    bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
+    device->SetPixelShader(nullptr);
+    device->SetVertexShader(nullptr);
+    device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
+    device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
+    device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
+    device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
+    device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
+    device->SetRenderState(D3DRS_ZENABLE, FALSE);
+    device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
+    device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
+    device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
+    device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
+    device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
+    device->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
+    device->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA);
+    device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
+    device->SetRenderState(D3DRS_FOGENABLE, FALSE);
+    device->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
+    device->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
+    device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
+    device->SetRenderState(D3DRS_CLIPPING, TRUE);
+    device->SetRenderState(D3DRS_LIGHTING, FALSE);
+    device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
+    device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
+    device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
+    device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
+    device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
+    device->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
+    device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
+    device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
+    device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
+    device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
 
     // 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.
@@ -140,9 +142,9 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
             0.0f,         0.0f,         0.5f,  0.0f,
             (L+R)/(L-R),  (T+B)/(B-T),  0.5f,  1.0f
         } } };
-        bd->pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity);
-        bd->pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity);
-        bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection);
+        device->SetTransform(D3DTS_WORLD, &mat_identity);
+        device->SetTransform(D3DTS_VIEW, &mat_identity);
+        device->SetTransform(D3DTS_PROJECTION, &mat_projection);
     }
 }
 
@@ -153,51 +155,53 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
     if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
         return;
 
-    // Create and grow buffers if needed
     ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
+    LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
+
+    // Create and grow buffers if needed
     if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
     {
         if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
         bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
-        if (bd->pd3dDevice->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0)
+        if (device->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0)
             return;
     }
     if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
     {
         if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
         bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
-        if (bd->pd3dDevice->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0)
+        if (device->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0)
             return;
     }
 
     // Backup the DX9 state
-    IDirect3DStateBlock9* d3d9_state_block = nullptr;
-    if (bd->pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0)
+    IDirect3DStateBlock9* state_block = nullptr;
+    if (device->CreateStateBlock(D3DSBT_ALL, &state_block) < 0)
         return;
-    if (d3d9_state_block->Capture() < 0)
+    if (state_block->Capture() < 0)
     {
-        d3d9_state_block->Release();
+        state_block->Release();
         return;
     }
 
     // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
     D3DMATRIX last_world, last_view, last_projection;
-    bd->pd3dDevice->GetTransform(D3DTS_WORLD, &last_world);
-    bd->pd3dDevice->GetTransform(D3DTS_VIEW, &last_view);
-    bd->pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection);
+    device->GetTransform(D3DTS_WORLD, &last_world);
+    device->GetTransform(D3DTS_VIEW, &last_view);
+    device->GetTransform(D3DTS_PROJECTION, &last_projection);
 
     // Allocate buffers
     CUSTOMVERTEX* vtx_dst;
     ImDrawIdx* idx_dst;
     if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
     {
-        d3d9_state_block->Release();
+        state_block->Release();
         return;
     }
     if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
     {
         bd->pVB->Unlock();
-        d3d9_state_block->Release();
+        state_block->Release();
         return;
     }
 
@@ -207,9 +211,9 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
     //  2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data;
-        for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        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;
             vtx_dst->pos[1] = vtx_src->pos.y;
@@ -220,14 +224,14 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
             vtx_dst++;
             vtx_src++;
         }
-        memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
-        idx_dst += cmd_list->IdxBuffer.Size;
+        memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
+        idx_dst += draw_list->IdxBuffer.Size;
     }
     bd->pVB->Unlock();
     bd->pIB->Unlock();
-    bd->pd3dDevice->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX));
-    bd->pd3dDevice->SetIndices(bd->pIB);
-    bd->pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
+    device->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX));
+    device->SetIndices(bd->pIB);
+    device->SetFVF(D3DFVF_CUSTOMVERTEX);
 
     // Setup desired DX state
     ImGui_ImplDX9_SetupRenderState(draw_data);
@@ -239,10 +243,10 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
     ImVec2 clip_off = draw_data->DisplayPos;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback != nullptr)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -250,7 +254,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplDX9_SetupRenderState(draw_data);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -260,26 +264,28 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
                     continue;
 
-                // Apply Scissor/clipping rectangle, Bind texture, Draw
+                // Apply scissor/clipping rectangle
                 const RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
+                device->SetScissorRect(&r);
+
+                // Bind texture, Draw
                 const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID();
-                bd->pd3dDevice->SetTexture(0, texture);
-                bd->pd3dDevice->SetScissorRect(&r);
-                bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3);
+                device->SetTexture(0, texture);
+                device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)draw_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3);
             }
         }
-        global_idx_offset += cmd_list->IdxBuffer.Size;
-        global_vtx_offset += cmd_list->VtxBuffer.Size;
+        global_idx_offset += draw_list->IdxBuffer.Size;
+        global_vtx_offset += draw_list->VtxBuffer.Size;
     }
 
     // Restore the DX9 transform
-    bd->pd3dDevice->SetTransform(D3DTS_WORLD, &last_world);
-    bd->pd3dDevice->SetTransform(D3DTS_VIEW, &last_view);
-    bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection);
+    device->SetTransform(D3DTS_WORLD, &last_world);
+    device->SetTransform(D3DTS_VIEW, &last_view);
+    device->SetTransform(D3DTS_PROJECTION, &last_projection);
 
     // Restore the DX9 state
-    d3d9_state_block->Apply();
-    d3d9_state_block->Release();
+    state_block->Apply();
+    state_block->Release();
 }
 
 bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm
index f9fd1087e..818961048 100644
--- a/backends/imgui_impl_metal.mm
+++ b/backends/imgui_impl_metal.mm
@@ -246,14 +246,14 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c
     size_t indexBufferOffset = 0;
     for (int n = 0; n < drawData->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = drawData->CmdLists[n];
+        const ImDrawList* draw_list = drawData->CmdLists[n];
 
-        memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, cmd_list->VtxBuffer.Data, (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
-        memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, cmd_list->IdxBuffer.Data, (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
+        memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
+        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 < cmd_list->CmdBuffer.Size; cmd_i++)
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -261,7 +261,7 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -302,8 +302,8 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c
             }
         }
 
-        vertexBufferOffset += (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert);
-        indexBufferOffset += (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx);
+        vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert);
+        indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx);
     }
 
     [commandBuffer addCompletedHandler:^(id)
diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp
index 7f1ea325a..0e69f18b2 100644
--- a/backends/imgui_impl_opengl2.cpp
+++ b/backends/imgui_impl_opengl2.cpp
@@ -192,16 +192,16 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data)
     // Render command lists
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
-        const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
+        const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
         glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, pos)));
         glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, uv)));
         glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, col)));
 
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -209,7 +209,7 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data)
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp
index 7087a7c57..fef6ed761 100644
--- a/backends/imgui_impl_opengl3.cpp
+++ b/backends/imgui_impl_opengl3.cpp
@@ -550,7 +550,7 @@ void    ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
     // Render command lists
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
 
         // Upload vertex/index buffers
         // - OpenGL drivers are in a very sorry state nowadays....
@@ -560,8 +560,8 @@ void    ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
         // - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code.
         //   We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path.
         // - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues.
-        const GLsizeiptr vtx_buffer_size = (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert);
-        const GLsizeiptr idx_buffer_size = (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx);
+        const GLsizeiptr vtx_buffer_size = (GLsizeiptr)draw_list->VtxBuffer.Size * (int)sizeof(ImDrawVert);
+        const GLsizeiptr idx_buffer_size = (GLsizeiptr)draw_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx);
         if (bd->UseBufferSubData)
         {
             if (bd->VertexBufferSize < vtx_buffer_size)
@@ -574,18 +574,18 @@ void    ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
                 bd->IndexBufferSize = idx_buffer_size;
                 GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW));
             }
-            GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data));
-            GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data));
+            GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data));
+            GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data));
         }
         else
         {
-            GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW));
-            GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW));
+            GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data, GL_STREAM_DRAW));
+            GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data, GL_STREAM_DRAW));
         }
 
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback != nullptr)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -593,7 +593,7 @@ void    ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp
index 3d538dfe7..8203c6caf 100644
--- a/backends/imgui_impl_sdlrenderer2.cpp
+++ b/backends/imgui_impl_sdlrenderer2.cpp
@@ -148,13 +148,13 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
     ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
-        const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
+        const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
 
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -162,7 +162,7 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -193,7 +193,7 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
                     xy, (int)sizeof(ImDrawVert),
                     color, (int)sizeof(ImDrawVert),
                     uv, (int)sizeof(ImDrawVert),
-                    cmd_list->VtxBuffer.Size - pcmd->VtxOffset,
+                    draw_list->VtxBuffer.Size - pcmd->VtxOffset,
                     idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx));
             }
         }
diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp
index 30f967bd3..9397a6467 100644
--- a/backends/imgui_impl_sdlrenderer3.cpp
+++ b/backends/imgui_impl_sdlrenderer3.cpp
@@ -171,13 +171,13 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
     ImGui_ImplSDLRenderer3_SetupRenderState(renderer);
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
-        const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
+        const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
 
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -185,7 +185,7 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplSDLRenderer3_SetupRenderState(renderer);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -212,7 +212,7 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
                     xy, (int)sizeof(ImDrawVert),
                     color, (int)sizeof(ImDrawVert),
                     uv, (int)sizeof(ImDrawVert),
-                    cmd_list->VtxBuffer.Size - pcmd->VtxOffset,
+                    draw_list->VtxBuffer.Size - pcmd->VtxOffset,
                     idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx));
             }
         }
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 3b757eb66..a0df9edfb 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -518,11 +518,11 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
         check_vk_result(err);
         for (int n = 0; n < draw_data->CmdListsCount; n++)
         {
-            const ImDrawList* cmd_list = draw_data->CmdLists[n];
-            memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
-            memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
-            vtx_dst += cmd_list->VtxBuffer.Size;
-            idx_dst += cmd_list->IdxBuffer.Size;
+            const ImDrawList* draw_list = draw_data->CmdLists[n];
+            memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
+            memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
+            vtx_dst += draw_list->VtxBuffer.Size;
+            idx_dst += draw_list->IdxBuffer.Size;
         }
         VkMappedMemoryRange range[2] = {};
         range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
@@ -550,10 +550,10 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
     int global_idx_offset = 0;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback != nullptr)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -561,7 +561,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -599,8 +599,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
                 vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
             }
         }
-        global_idx_offset += cmd_list->IdxBuffer.Size;
-        global_vtx_offset += cmd_list->VtxBuffer.Size;
+        global_idx_offset += draw_list->IdxBuffer.Size;
+        global_vtx_offset += draw_list->VtxBuffer.Size;
     }
 
     // Note: at this point both vkCmdSetViewport() and vkCmdSetScissor() have been called.
diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index 4109e392e..9f75364d5 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -425,11 +425,11 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
     ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
-        memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
-        vtx_dst += cmd_list->VtxBuffer.Size;
-        idx_dst += cmd_list->IdxBuffer.Size;
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
+        memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
+        vtx_dst += draw_list->VtxBuffer.Size;
+        idx_dst += draw_list->IdxBuffer.Size;
     }
     int64_t vb_write_size = MEMALIGN((char*)vtx_dst - (char*)fr->VertexBufferHost, 4);
     int64_t ib_write_size = MEMALIGN((char*)idx_dst - (char*)fr->IndexBufferHost, 4);
@@ -447,10 +447,10 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
     ImVec2 clip_off = draw_data->DisplayPos;
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
-        const ImDrawList* cmd_list = draw_data->CmdLists[n];
-        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+        const ImDrawList* draw_list = draw_data->CmdLists[n];
+        for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
         {
-            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+            const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
             if (pcmd->UserCallback != nullptr)
             {
                 // User callback, registered via ImDrawList::AddCallback()
@@ -458,7 +458,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
                     ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
                 else
-                    pcmd->UserCallback(cmd_list, pcmd);
+                    pcmd->UserCallback(draw_list, pcmd);
             }
             else
             {
@@ -494,8 +494,8 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
                 wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
             }
         }
-        global_idx_offset += cmd_list->IdxBuffer.Size;
-        global_vtx_offset += cmd_list->VtxBuffer.Size;
+        global_idx_offset += draw_list->IdxBuffer.Size;
+        global_vtx_offset += draw_list->VtxBuffer.Size;
     }
 }
 

From e94f95d82b94b36dfd0a3b217787ab7cb638d01a Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 7 Oct 2024 21:00:07 +0200
Subject: [PATCH 0408/2359] Backends: DX11, DX12, Vulkan, WGPU: Expose some
 backend-specific render state usable for callbacks. (#6969, #5834, #7468,
 #3590)

---
 backends/imgui_impl_dx11.cpp   | 11 +++++++++++
 backends/imgui_impl_dx11.h     | 12 ++++++++++++
 backends/imgui_impl_dx12.cpp   | 10 ++++++++++
 backends/imgui_impl_dx12.h     | 10 ++++++++++
 backends/imgui_impl_vulkan.cpp | 11 +++++++++++
 backends/imgui_impl_vulkan.h   | 31 +++++++++++++++++++++----------
 backends/imgui_impl_wgpu.cpp   | 10 ++++++++++
 backends/imgui_impl_wgpu.h     | 10 ++++++++++
 docs/CHANGELOG.txt             |  6 ++++++
 imgui.h                        |  9 ++++++++-
 10 files changed, 109 insertions(+), 11 deletions(-)

diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp
index f656bbc55..4ee774085 100644
--- a/backends/imgui_impl_dx11.cpp
+++ b/backends/imgui_impl_dx11.cpp
@@ -4,6 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -15,6 +16,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: DirectX11: Expose selected render state in ImGui_ImplDX11_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
 //  2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
 //  2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
@@ -246,6 +248,14 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
     // Setup desired DX state
     ImGui_ImplDX11_SetupRenderState(draw_data, device);
 
+    // Setup render state structure (for callbacks and custom texture bindings)
+    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
+    ImGui_ImplDX11_RenderState render_state;
+    render_state.Device = bd->pd3dDevice;
+    render_state.DeviceContext = bd->pd3dDeviceContext;
+    render_state.SamplerDefault = bd->pFontSampler;
+    platform_io.Renderer_RenderState = &render_state;
+
     // Render command lists
     // (Because we merged all buffers into a single one, we maintain our own offset into them)
     int global_idx_offset = 0;
@@ -287,6 +297,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
         global_idx_offset += draw_list->IdxBuffer.Size;
         global_vtx_offset += draw_list->VtxBuffer.Size;
     }
+    platform_io.Renderer_RenderState = NULL;
 
     // Restore modified DX state
     device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h
index cde64ee96..cb79633c3 100644
--- a/backends/imgui_impl_dx11.h
+++ b/backends/imgui_impl_dx11.h
@@ -4,6 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -19,6 +20,7 @@
 
 struct ID3D11Device;
 struct ID3D11DeviceContext;
+struct ID3D11SamplerState;
 
 // Follow "Getting Started" link and check examples/ folder to learn about using backends!
 IMGUI_IMPL_API bool     ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context);
@@ -30,4 +32,14 @@ IMGUI_IMPL_API void     ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data);
 IMGUI_IMPL_API void     ImGui_ImplDX11_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool     ImGui_ImplDX11_CreateDeviceObjects();
 
+// [BETA] Selected render state data shared with callbacks.
+// This is temporarily stored in io.BackendRendererRenderState during the ImGui_ImplDX11_RenderDrawData() call.
+// (Please open an issue if you feel you need access to more data)
+struct ImGui_ImplDX11_RenderState
+{
+    ID3D11Device*           Device;
+    ID3D11DeviceContext*    DeviceContext;
+    ID3D11SamplerState*     SamplerDefault;
+};
+
 #endif // #ifndef IMGUI_DISABLE
diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index c63503cc0..376ab7a68 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -4,6 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
 
 // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
 // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
@@ -23,6 +24,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
 //  2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
 //  2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
@@ -245,6 +247,13 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL
     // Setup desired DX state
     ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
 
+    // Setup render state structure (for callbacks and custom texture bindings)
+    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
+    ImGui_ImplDX12_RenderState render_state;
+    render_state.Device = bd->pd3dDevice;
+    render_state.CommandList = command_list;
+    platform_io.Renderer_RenderState = &render_state;
+
     // Render command lists
     // (Because we merged all buffers into a single one, we maintain our own offset into them)
     int global_vtx_offset = 0;
@@ -287,6 +296,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL
         global_idx_offset += draw_list->IdxBuffer.Size;
         global_vtx_offset += draw_list->VtxBuffer.Size;
     }
+    platform_io.Renderer_RenderState = NULL;
 }
 
 static void ImGui_ImplDX12_CreateFontsTexture()
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index 08c0a1255..bee7454fa 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -4,6 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
 
 // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
 // See imgui_impl_dx12.cpp file for details.
@@ -42,4 +43,13 @@ IMGUI_IMPL_API void     ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3
 IMGUI_IMPL_API void     ImGui_ImplDX12_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool     ImGui_ImplDX12_CreateDeviceObjects();
 
+// [BETA] Selected render state data shared with callbacks.
+// This is temporarily stored in io.BackendRendererRenderState during the ImGui_ImplDX12_RenderDrawData() call.
+// (Please open an issue if you feel you need access to more data)
+struct ImGui_ImplDX12_RenderState
+{
+    ID3D12Device*               Device;
+    ID3D12GraphicsCommandList*  CommandList;
+};
+
 #endif // #ifndef IMGUI_DISABLE
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index a0df9edfb..f3f560607 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -4,6 +4,7 @@
 // Implemented features:
 //  [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
 
 // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'.
 // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
@@ -33,6 +34,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: Vulkan: Expose selected render state in ImGui_ImplVulkan_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2024-04-19: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define (you can also use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().)
 //  2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering.
 //  2024-02-12: *BREAKING CHANGE*: Dynamic rendering now require filling PipelineRenderingCreateInfo structure.
@@ -540,6 +542,14 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
     // Setup desired Vulkan state
     ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height);
 
+    // Setup render state structure (for callbacks and custom texture bindings)
+    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
+    ImGui_ImplVulkan_RenderState render_state;
+    render_state.CommandBuffer = command_buffer;
+    render_state.Pipeline = pipeline;
+    render_state.PipelineLayout = bd->PipelineLayout;
+    platform_io.Renderer_RenderState = &render_state;
+
     // Will project scissor/clipping rectangles into framebuffer space
     ImVec2 clip_off = draw_data->DisplayPos;         // (0,0) unless using multi-viewports
     ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
@@ -602,6 +612,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
         global_idx_offset += draw_list->IdxBuffer.Size;
         global_vtx_offset += draw_list->VtxBuffer.Size;
     }
+    platform_io.Renderer_RenderState = NULL;
 
     // Note: at this point both vkCmdSetViewport() and vkCmdSetScissor() have been called.
     // Our last values will leak into user/application rendering IF:
diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h
index 1c7f76951..a834d7d7a 100644
--- a/backends/imgui_impl_vulkan.h
+++ b/backends/imgui_impl_vulkan.h
@@ -4,6 +4,7 @@
 // Implemented features:
 //  [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
 
 // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'.
 // See imgui_impl_vulkan.cpp file for details.
@@ -99,23 +100,33 @@ struct ImGui_ImplVulkan_InitInfo
 };
 
 // Follow "Getting Started" link and check examples/ folder to learn about using backends!
-IMGUI_IMPL_API bool         ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info);
-IMGUI_IMPL_API void         ImGui_ImplVulkan_Shutdown();
-IMGUI_IMPL_API void         ImGui_ImplVulkan_NewFrame();
-IMGUI_IMPL_API void         ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE);
-IMGUI_IMPL_API bool         ImGui_ImplVulkan_CreateFontsTexture();
-IMGUI_IMPL_API void         ImGui_ImplVulkan_DestroyFontsTexture();
-IMGUI_IMPL_API void         ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated)
+IMGUI_IMPL_API bool             ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info);
+IMGUI_IMPL_API void             ImGui_ImplVulkan_Shutdown();
+IMGUI_IMPL_API void             ImGui_ImplVulkan_NewFrame();
+IMGUI_IMPL_API void             ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE);
+IMGUI_IMPL_API bool             ImGui_ImplVulkan_CreateFontsTexture();
+IMGUI_IMPL_API void             ImGui_ImplVulkan_DestroyFontsTexture();
+IMGUI_IMPL_API void             ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated)
 
 // Register a texture (VkDescriptorSet == ImTextureID)
 // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem
 // Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions.
-IMGUI_IMPL_API VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout);
-IMGUI_IMPL_API void            ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set);
+IMGUI_IMPL_API VkDescriptorSet  ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout);
+IMGUI_IMPL_API void             ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set);
 
 // Optional: load Vulkan functions with a custom function loader
 // This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES
-IMGUI_IMPL_API bool         ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr);
+IMGUI_IMPL_API bool             ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr);
+
+// [BETA] Selected render state data shared with callbacks.
+// This is temporarily stored in io.BackendRendererRenderState during the ImGui_ImplVulkan_RenderDrawData() call.
+// (Please open an issue if you feel you need access to more data)
+struct ImGui_ImplVulkan_RenderState
+{
+    VkCommandBuffer     CommandBuffer;
+    VkPipeline          Pipeline;
+    VkPipelineLayout    PipelineLayout;
+};
 
 //-------------------------------------------------------------------------
 // Internal / Miscellaneous Vulkan Helpers
diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index 9f75364d5..84a28406b 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -5,6 +5,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -16,6 +17,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2024-09-16: Added support for optional IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU define to handle ever-changing native implementations. (#7977)
 //  2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
 //  2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
@@ -439,6 +441,13 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
     // Setup desired render state
     ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
 
+    // Setup render state structure (for callbacks and custom texture bindings)
+    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
+    ImGui_ImplWGPU_RenderState render_state;
+    render_state.Device = bd->wgpuDevice;
+    render_state.RenderPassEncoder = pass_encoder;
+    platform_io.Renderer_RenderState = &render_state;
+
     // Render command lists
     // (Because we merged all buffers into a single one, we maintain our own offset into them)
     int global_vtx_offset = 0;
@@ -497,6 +506,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
         global_idx_offset += draw_list->IdxBuffer.Size;
         global_vtx_offset += draw_list->VtxBuffer.Size;
     }
+    platform_io.Renderer_RenderState = NULL;
 }
 
 static void ImGui_ImplWGPU_CreateFontsTexture()
diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h
index e6835dee9..a171fd6d0 100644
--- a/backends/imgui_impl_wgpu.h
+++ b/backends/imgui_impl_wgpu.h
@@ -12,6 +12,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -54,4 +55,13 @@ IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURen
 IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects();
 
+// [BETA] Selected render state data shared with callbacks.
+// This is temporarily stored in io.BackendRendererRenderState during the ImGui_ImplWGPU_RenderDrawData() call.
+// (Please open an issue if you feel you need access to more data)
+struct ImGui_ImplWGPU_RenderState
+{
+    WGPUDevice                  Device;
+    WGPURenderPassEncoder       RenderPassEncoder;
+};
+
 #endif // #ifndef IMGUI_DISABLE
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index b5f526809..4ca534c7b 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,12 @@ Breaking changes:
 
 Other changes:
 
+- IO: added 'void* platform_io.Renderer_RenderState' which is set during the
+  ImGui_ImplXXXX_RenderDrawData() of standard backend to expose selected render
+  state to draw callbacks. (#6969, #5834, #7468, #3590)
+- Backends: DX11, DX12, Vulkan, WGPU: expose selected state in ImGui_ImplXXXX_RenderState.
+  structure during render loop. (#6969, #5834, #7468, #3590)
+
 
 -----------------------------------------------------------------------
  VERSION 1.91.3 (Released 2024-10-04)
diff --git a/imgui.h b/imgui.h
index 49ad70cee..f3d5d83d4 100644
--- a/imgui.h
+++ b/imgui.h
@@ -3515,7 +3515,7 @@ struct ImGuiPlatformIO
     IMGUI_API ImGuiPlatformIO();
 
     //------------------------------------------------------------------
-    // Input - Interface with OS/backends
+    // Interface with OS and Platform backend
     //------------------------------------------------------------------
 
     // Optional: Access OS clipboard
@@ -3538,6 +3538,13 @@ struct ImGuiPlatformIO
     // Optional: Platform locale
     // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point
     ImWchar     Platform_LocaleDecimalPoint;     // '.'
+
+    //------------------------------------------------------------------
+    // Interface with Renderer Backend
+    //------------------------------------------------------------------
+
+    // Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure.
+    void*       Renderer_RenderState;
 };
 
 // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function.

From 74dd38d27c946087c31b21dc83265439ea7a95cd Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 7 Oct 2024 21:53:46 +0200
Subject: [PATCH 0409/2359] Backends: Vulkan: fixed warnings when building in
 32-bit mode.

---
 backends/imgui_impl_vulkan.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index f3f560607..a608b1a63 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -396,7 +396,7 @@ static inline VkDeviceSize AlignBufferSize(VkDeviceSize size, VkDeviceSize align
     return (size + alignment - 1) & ~(alignment - 1);
 }
 
-static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& buffer_size, size_t new_size, VkBufferUsageFlagBits usage)
+static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& buffer_size, VkDeviceSize new_size, VkBufferUsageFlagBits usage)
 {
     ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
     ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
@@ -504,8 +504,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
     if (draw_data->TotalVtxCount > 0)
     {
         // Create or resize the vertex/index buffers
-        size_t vertex_size = AlignBufferSize(draw_data->TotalVtxCount * sizeof(ImDrawVert), bd->BufferMemoryAlignment);
-        size_t index_size = AlignBufferSize(draw_data->TotalIdxCount * sizeof(ImDrawIdx), bd->BufferMemoryAlignment);
+        VkDeviceSize vertex_size = AlignBufferSize(draw_data->TotalVtxCount * sizeof(ImDrawVert), bd->BufferMemoryAlignment);
+        VkDeviceSize index_size = AlignBufferSize(draw_data->TotalIdxCount * sizeof(ImDrawIdx), bd->BufferMemoryAlignment);
         if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size)
             CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
         if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size)

From 42206b3d51347c10330b36af26ec13ae3492ba5e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 7 Oct 2024 22:02:55 +0200
Subject: [PATCH 0410/2359] Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan,
 WGPU: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 (#7468, #7511, #5999, #5502)

---
 backends/imgui_impl_dx10.cpp         | 7 ++++---
 backends/imgui_impl_dx11.cpp         | 7 ++++---
 backends/imgui_impl_dx12.cpp         | 7 ++++---
 backends/imgui_impl_dx9.cpp          | 3 +++
 backends/imgui_impl_opengl2.cpp      | 3 +++
 backends/imgui_impl_opengl3.cpp      | 3 +++
 backends/imgui_impl_opengl3_loader.h | 6 ++++++
 backends/imgui_impl_vulkan.cpp       | 7 ++++---
 backends/imgui_impl_wgpu.cpp         | 7 ++++---
 docs/CHANGELOG.txt                   | 2 ++
 10 files changed, 37 insertions(+), 15 deletions(-)

diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp
index 96932c3af..2638caf9c 100644
--- a/backends/imgui_impl_dx10.cpp
+++ b/backends/imgui_impl_dx10.cpp
@@ -15,6 +15,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
 //  2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
 //  2021-05-19: DirectX10: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
@@ -347,9 +348,9 @@ static void ImGui_ImplDX10_CreateFontsTexture()
         D3D10_SAMPLER_DESC desc;
         ZeroMemory(&desc, sizeof(desc));
         desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
-        desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP;
-        desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP;
-        desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP;
+        desc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
+        desc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
+        desc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
         desc.MipLODBias = 0.f;
         desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
         desc.MinLOD = 0.f;
diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp
index 4ee774085..088e4b67e 100644
--- a/backends/imgui_impl_dx11.cpp
+++ b/backends/imgui_impl_dx11.cpp
@@ -16,6 +16,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: DirectX11: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: DirectX11: Expose selected render state in ImGui_ImplDX11_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
 //  2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
@@ -370,9 +371,9 @@ static void ImGui_ImplDX11_CreateFontsTexture()
         D3D11_SAMPLER_DESC desc;
         ZeroMemory(&desc, sizeof(desc));
         desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
-        desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
-        desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
-        desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
+        desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
+        desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
+        desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
         desc.MipLODBias = 0.f;
         desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
         desc.MinLOD = 0.f;
diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index 376ab7a68..85a870269 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -24,6 +24,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
 //  2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
@@ -489,9 +490,9 @@ bool    ImGui_ImplDX12_CreateDeviceObjects()
         // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
         D3D12_STATIC_SAMPLER_DESC staticSampler = {};
         staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
-        staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
-        staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
-        staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
+        staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+        staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+        staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
         staticSampler.MipLODBias = 0.f;
         staticSampler.MaxAnisotropy = 0;
         staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp
index 24bd5d3b3..f1b069df1 100644
--- a/backends/imgui_impl_dx9.cpp
+++ b/backends/imgui_impl_dx9.cpp
@@ -15,6 +15,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: DirectX9: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575)
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
 //  2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
@@ -125,6 +126,8 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
     device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
     device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
     device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
+    device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
+    device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
 
     // 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.
diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp
index 0e69f18b2..789d74afb 100644
--- a/backends/imgui_impl_opengl2.cpp
+++ b/backends/imgui_impl_opengl2.cpp
@@ -22,6 +22,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-06-28: OpenGL: ImGui_ImplOpenGL2_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL2_DestroyFontsTexture(). (#7748)
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
 //  2021-12-08: OpenGL: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86.
@@ -263,6 +264,8 @@ bool ImGui_ImplOpenGL2_CreateFontsTexture()
     glBindTexture(GL_TEXTURE_2D, bd->FontTexture);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
     glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
 
diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp
index fef6ed761..f5235096f 100644
--- a/backends/imgui_impl_opengl3.cpp
+++ b/backends/imgui_impl_opengl3.cpp
@@ -22,6 +22,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748)
 //  2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562)
 //  2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447)
@@ -681,6 +682,8 @@ bool ImGui_ImplOpenGL3_CreateFontsTexture()
     GL_CALL(glBindTexture(GL_TEXTURE_2D, bd->FontTexture));
     GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
     GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
+    GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
+    GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
 #ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES
     GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
 #endif
diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h
index 3fbc34811..d6ffa5a2d 100644
--- a/backends/imgui_impl_opengl3_loader.h
+++ b/backends/imgui_impl_opengl3_loader.h
@@ -181,6 +181,9 @@ typedef khronos_uint8_t GLubyte;
 #define GL_LINEAR                         0x2601
 #define GL_TEXTURE_MAG_FILTER             0x2800
 #define GL_TEXTURE_MIN_FILTER             0x2801
+#define GL_TEXTURE_WRAP_S                 0x2802
+#define GL_TEXTURE_WRAP_T                 0x2803
+#define GL_REPEAT                         0x2901
 typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode);
 typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
 typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
@@ -231,6 +234,9 @@ GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
 GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
 #endif
 #endif /* GL_VERSION_1_1 */
+#ifndef GL_VERSION_1_2
+#define GL_CLAMP_TO_EDGE                  0x812F
+#endif /* GL_VERSION_1_2 */
 #ifndef GL_VERSION_1_3
 #define GL_TEXTURE0                       0x84C0
 #define GL_ACTIVE_TEXTURE                 0x84E0
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index a608b1a63..31a2516a6 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -34,6 +34,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-07: Vulkan: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: Vulkan: Expose selected render state in ImGui_ImplVulkan_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2024-04-19: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define (you can also use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().)
 //  2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering.
@@ -992,9 +993,9 @@ bool ImGui_ImplVulkan_CreateDeviceObjects()
         info.magFilter = VK_FILTER_LINEAR;
         info.minFilter = VK_FILTER_LINEAR;
         info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
-        info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
-        info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
-        info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
+        info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
+        info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
+        info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
         info.minLod = -1000;
         info.maxLod = 1000;
         info.maxAnisotropy = 1.0f;
diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index 84a28406b..a4f6c03e5 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -18,6 +18,7 @@
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
 //  2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
+//  2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-09-16: Added support for optional IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU define to handle ever-changing native implementations. (#7977)
 //  2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
 //  2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
@@ -565,9 +566,9 @@ static void ImGui_ImplWGPU_CreateFontsTexture()
         sampler_desc.minFilter = WGPUFilterMode_Linear;
         sampler_desc.magFilter = WGPUFilterMode_Linear;
         sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear;
-        sampler_desc.addressModeU = WGPUAddressMode_Repeat;
-        sampler_desc.addressModeV = WGPUAddressMode_Repeat;
-        sampler_desc.addressModeW = WGPUAddressMode_Repeat;
+        sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge;
+        sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge;
+        sampler_desc.addressModeW = WGPUAddressMode_ClampToEdge;
         sampler_desc.maxAnisotropy = 1;
         bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc);
     }
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 4ca534c7b..48496340b 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -48,6 +48,8 @@ Other changes:
   state to draw callbacks. (#6969, #5834, #7468, #3590)
 - Backends: DX11, DX12, Vulkan, WGPU: expose selected state in ImGui_ImplXXXX_RenderState.
   structure during render loop. (#6969, #5834, #7468, #3590)
+- Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan, WGPU: Changed default texture sampler
+  to Clamp instead of Repeat/Wrap. (#7468, #7511, #5999, #5502)
 
 
 -----------------------------------------------------------------------

From f890d8538161ed005680a29ab99af26d1ae5c46f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 7 Oct 2024 22:12:09 +0200
Subject: [PATCH 0411/2359] Backends: Fixed typo in comments from old wip work
 'io.BackendRendererRenderState' -> 'platform_io.Renderer_RenderState'. 
 (#6969, #5834, #7468, #3590

Amend e94f95d
---
 backends/imgui_impl_dx11.cpp   | 2 +-
 backends/imgui_impl_dx11.h     | 4 ++--
 backends/imgui_impl_dx12.cpp   | 2 +-
 backends/imgui_impl_dx12.h     | 4 ++--
 backends/imgui_impl_vulkan.cpp | 2 +-
 backends/imgui_impl_vulkan.h   | 4 ++--
 backends/imgui_impl_wgpu.cpp   | 2 +-
 backends/imgui_impl_wgpu.h     | 4 ++--
 8 files changed, 12 insertions(+), 12 deletions(-)

diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp
index 088e4b67e..16d480e08 100644
--- a/backends/imgui_impl_dx11.cpp
+++ b/backends/imgui_impl_dx11.cpp
@@ -4,7 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h
index cb79633c3..57b19bc03 100644
--- a/backends/imgui_impl_dx11.h
+++ b/backends/imgui_impl_dx11.h
@@ -4,7 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -33,7 +33,7 @@ IMGUI_IMPL_API void     ImGui_ImplDX11_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool     ImGui_ImplDX11_CreateDeviceObjects();
 
 // [BETA] Selected render state data shared with callbacks.
-// This is temporarily stored in io.BackendRendererRenderState during the ImGui_ImplDX11_RenderDrawData() call.
+// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX11_RenderDrawData() call.
 // (Please open an issue if you feel you need access to more data)
 struct ImGui_ImplDX11_RenderState
 {
diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index 85a870269..8dbb1e508 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -4,7 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
 // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index bee7454fa..74001db40 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -4,7 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
 // See imgui_impl_dx12.cpp file for details.
@@ -44,7 +44,7 @@ IMGUI_IMPL_API void     ImGui_ImplDX12_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool     ImGui_ImplDX12_CreateDeviceObjects();
 
 // [BETA] Selected render state data shared with callbacks.
-// This is temporarily stored in io.BackendRendererRenderState during the ImGui_ImplDX12_RenderDrawData() call.
+// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX12_RenderDrawData() call.
 // (Please open an issue if you feel you need access to more data)
 struct ImGui_ImplDX12_RenderState
 {
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 31a2516a6..d670b82a0 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -4,7 +4,7 @@
 // Implemented features:
 //  [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'.
 // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h
index a834d7d7a..cdbcb0caa 100644
--- a/backends/imgui_impl_vulkan.h
+++ b/backends/imgui_impl_vulkan.h
@@ -4,7 +4,7 @@
 // Implemented features:
 //  [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'.
 // See imgui_impl_vulkan.cpp file for details.
@@ -119,7 +119,7 @@ IMGUI_IMPL_API void             ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet d
 IMGUI_IMPL_API bool             ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr);
 
 // [BETA] Selected render state data shared with callbacks.
-// This is temporarily stored in io.BackendRendererRenderState during the ImGui_ImplVulkan_RenderDrawData() call.
+// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplVulkan_RenderDrawData() call.
 // (Please open an issue if you feel you need access to more data)
 struct ImGui_ImplVulkan_RenderState
 {
diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index a4f6c03e5..95f1b0c63 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -5,7 +5,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h
index a171fd6d0..e4398575c 100644
--- a/backends/imgui_impl_wgpu.h
+++ b/backends/imgui_impl_wgpu.h
@@ -12,7 +12,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)platform_io.BackendRendererRenderState'.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -56,7 +56,7 @@ IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects();
 
 // [BETA] Selected render state data shared with callbacks.
-// This is temporarily stored in io.BackendRendererRenderState during the ImGui_ImplWGPU_RenderDrawData() call.
+// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplWGPU_RenderDrawData() call.
 // (Please open an issue if you feel you need access to more data)
 struct ImGui_ImplWGPU_RenderState
 {

From 19b494df89fdba00e903fcd61734eb119ac98bb3 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 8 Oct 2024 12:37:33 +0200
Subject: [PATCH 0412/2359] Examples: DirectX12: update Windows SDK version.

(VS2015 doesn't support latest)
---
 .../example_win32_directx12/example_win32_directx12.vcxproj     | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj b/examples/example_win32_directx12/example_win32_directx12.vcxproj
index 7b64371ef..62191839e 100644
--- a/examples/example_win32_directx12/example_win32_directx12.vcxproj
+++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj
@@ -21,7 +21,7 @@
   
     {b4cf9797-519d-4afe-a8f4-5141a6b521d3}
     example_win32_directx12
-    10.0.18362.0
+    10.0.20348.0
   
   
   

From 92b94980c69ff3d3d7f5dc30c1c19abfb72db47e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 7 Oct 2024 16:45:34 +0200
Subject: [PATCH 0413/2359] (Breaking) Default ImTextureID to use a Im64
 instead of void* (#1641)

---
 backends/imgui_impl_dx12.cpp                  | 16 --------
 backends/imgui_impl_dx12.h                    |  3 --
 backends/imgui_impl_vulkan.cpp                |  8 ----
 backends/imgui_impl_vulkan.h                  |  3 --
 docs/CHANGELOG.txt                            | 16 +++++++-
 docs/FAQ.md                                   | 39 ++++++++++---------
 examples/example_glfw_vulkan/CMakeLists.txt   |  2 +-
 examples/example_glfw_vulkan/build_win32.bat  |  4 +-
 examples/example_glfw_vulkan/build_win64.bat  |  4 +-
 .../example_glfw_vulkan.vcxproj               |  8 ++--
 examples/example_sdl2_vulkan/build_win32.bat  |  2 +-
 .../example_sdl2_vulkan.vcxproj               | 10 ++---
 .../example_win32_directx12/build_win32.bat   |  3 +-
 .../example_win32_directx12.vcxproj           |  8 ++--
 examples/example_win32_directx12/main.cpp     |  4 --
 imgui.cpp                                     |  8 ++++
 imgui.h                                       |  4 +-
 imgui_draw.cpp                                |  4 +-
 imgui_widgets.cpp                             |  2 +-
 19 files changed, 69 insertions(+), 79 deletions(-)

diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index 8dbb1e508..e9345013c 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -6,14 +6,6 @@
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
-// Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
-// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
-// To build this on 32-bit systems:
-// - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file)
-// - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like.
-// - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!)
-// - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file)
-
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
 // Learn about Dear ImGui:
@@ -446,14 +438,6 @@ static void ImGui_ImplDX12_CreateFontsTexture()
     }
 
     // Store our identifier
-    // READ THIS IF THE STATIC_ASSERT() TRIGGERS:
-    // - Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
-    // - This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
-    // [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file)
-    // [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like.
-    // [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!)
-    // [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file)
-    static_assert(sizeof(ImTextureID) >= sizeof(bd->hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
     io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr);
 }
 
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index 74001db40..5da528573 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -6,9 +6,6 @@
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
-// Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
-// See imgui_impl_dx12.cpp file for details.
-
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
 // Learn about Dear ImGui:
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index d670b82a0..78d838955 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -6,14 +6,6 @@
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
-// Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'.
-// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
-// To build this on 32-bit systems and support texture changes:
-// - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in our .vcxproj files)
-// - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like.
-// - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!)
-// - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in our batch files)
-
 // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
 // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
 
diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h
index cdbcb0caa..ca5b4db64 100644
--- a/backends/imgui_impl_vulkan.h
+++ b/backends/imgui_impl_vulkan.h
@@ -6,9 +6,6 @@
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
-// Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'.
-// See imgui_impl_vulkan.cpp file for details.
-
 // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
 // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
 
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 48496340b..96a52ff40 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -36,11 +36,25 @@ HOW TO UPDATE?
 - Please report any issue!
 
 -----------------------------------------------------------------------
- VERSION 1.91.4 WIP
+ VERSION 1.91.4 WIP (In Progress)
 -----------------------------------------------------------------------
 
 Breaking changes:
 
+- The typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
+  - This removes the requirement to redefine it for backends which are e.g. storing
+    descriptor sets or other 64-bits structures when building on 32-bits archs.
+    It therefore simplify various building scripts/helpers.
+  - You may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID'
+    when passing your types to functions taking ImTextureID values, e.g. ImGui::Image().
+    In doubt it is almost always better to do an intermediate intptr_t cast, since it
+    allows casting any pointer/integer type without warning:
+    - May warn:     ImGui::Image((void*)MyTextureData, ...);
+    - May warn:     ImGui::Image((void*)(intptr_t)MyTextureData, ...);
+    - Won't warn:   ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
+  - Note that you can always define ImTextureID to be your own high-level structures
+    (with dedicated constructors) if you like.
+
 Other changes:
 
 - IO: added 'void* platform_io.Renderer_RenderState' which is set during the
diff --git a/docs/FAQ.md b/docs/FAQ.md
index 4e2a42576..38600fe47 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -380,8 +380,9 @@ node open/closed state differently. See what makes more sense in your situation!
 Short explanation:
 - Refer to [Image Loading and Displaying Examples](https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples) on the [Wiki](https://github.com/ocornut/imgui/wiki).
 - You may use functions such as `ImGui::Image()`, `ImGui::ImageButton()` or lower-level `ImDrawList::AddImage()` to emit draw calls that will use your own textures.
-- Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value.
-- Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason).
+- Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as an opaque ImTextureID value.
+- By default ImTextureID can store up to 64-bits. You may `#define` it to a custom type/structure if you need.
+- Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason), but the examples linked above may be useful references.
 
 **Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.**
 
@@ -389,27 +390,27 @@ Long explanation:
 - Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices. At the end of the frame, those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code to render them is generally fairly short (a few dozen lines). In the examples/ folder, we provide functions for popular graphics APIs (OpenGL, DirectX, etc.).
 - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API.
  We carry the information to identify a "texture" in the ImTextureID type.
-ImTextureID is nothing more than a void*, aka 4/8 bytes worth of data: just enough to store one pointer or integer of your choice.
+ImTextureID default to ImU64 aka 8 bytes worth of data: just enough to store one pointer or integer of your choice.
 Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely passes ImTextureID values until they reach your rendering function.
 - In the [examples/](https://github.com/ocornut/imgui/tree/master/examples) backends, for each graphics API we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using:
 ```cpp
 OpenGL:
-- ImTextureID = GLuint
+- ImTextureID should contains 'GLuint' (GL texture identifier).
 - See ImGui_ImplOpenGL3_RenderDrawData() function in imgui_impl_opengl3.cpp
 ```
 ```cpp
 DirectX9:
-- ImTextureID = LPDIRECT3DTEXTURE9
+- ImTextureID should contain a 'LPDIRECT3DTEXTURE9' (pointer).
 - See ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp
 ```
 ```cpp
 DirectX11:
-- ImTextureID = ID3D11ShaderResourceView*
+- ImTextureID should contain a 'ID3D11ShaderResourceView*' (poiter)
 - See ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp
 ```
 ```cpp
 DirectX12:
-- ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE
+- ImTextureID should contain a 'D3D12_GPU_DESCRIPTOR_HANDLE' (always 64-bits)
 - See ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp
 ```
 For example, in the OpenGL example backend we store raw OpenGL texture identifier (GLuint) inside ImTextureID.
@@ -421,14 +422,14 @@ If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a
 
 User code may do:
 ```cpp
-// Cast our texture type to ImTextureID / void*
+// Cast our texture type to ImTextureID
 MyTexture* texture = g_CoffeeTableTexture;
-ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height));
+ImGui::Image((ImTextureID)(intptr_t)texture, ImVec2(texture->Width, texture->Height));
 ```
 The renderer function called after ImGui::Render() will receive that same value that the user code passed:
 ```cpp
-// Cast ImTextureID / void* stored in the draw command as our texture type
-MyTexture* texture = (MyTexture*)pcmd->GetTexID();
+// Cast ImTextureID stored in the draw command as our texture type
+MyTexture* texture = (MyTexture*)(intptr_t)pcmd->GetTexID();
 MyEngineBindTexture2D(texture);
 ```
 Once you understand this design, you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui.
@@ -437,19 +438,19 @@ If you want to display an image file (e.g. PNG file) on the screen, please refer
 
 Refer to [Image Loading and Displaying Examples](https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples) on the [Wiki](https://github.com/ocornut/imgui/wiki) to find simplified examples for loading textures with OpenGL, DirectX9 and DirectX11.
 
-C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTextureID / void*, and vice-versa.
-Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID / void*.
+C/C++ tip: a u64 is 8 bytes. You may safely store any pointer or integer into it by casting your value to ImTextureID, and vice-versa.
+Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID.
 Here are some examples:
 ```cpp
 GLuint my_tex = XXX;
-void* my_void_ptr;
-my_void_ptr = (void*)(intptr_t)my_tex;                  // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer)
-my_tex = (GLuint)(intptr_t)my_void_ptr;                 // cast a void* into a GLuint
+ImTextureID my_imtexid;
+my_imtexid = (ImTextureID)(intptr_t)my_tex;                     // cast a GLuint into a ImTextureID (we don't take its address! we just copy the address)
+my_tex = (GLuint)(intptr_t)my_imtexid;                          // cast a ImTextureID into a GLuint
 
 ID3D11ShaderResourceView* my_dx11_srv = XXX;
-void* my_void_ptr;
-my_void_ptr = (void*)my_dx11_srv;                       // cast a ID3D11ShaderResourceView* into an opaque void*
-my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr;   // cast a void* into a ID3D11ShaderResourceView*
+ImTextureID my_imtexid;
+my_imtexid = (ImTextureID)(intptr_t)my_dx11_srv;                // cast a ID3D11ShaderResourceView* into an opaque ImTextureID
+my_dx11_srv = (ID3D11ShaderResourceView*)(intptr_t)_my_imtexid; // cast a ImTextureID into a ID3D11ShaderResourceView*
 ```
 Finally, you may call `ImGui::ShowMetricsWindow()` to explore/visualize/understand how the ImDrawList are generated.
 
diff --git a/examples/example_glfw_vulkan/CMakeLists.txt b/examples/example_glfw_vulkan/CMakeLists.txt
index a6e5bf910..443a144ea 100644
--- a/examples/example_glfw_vulkan/CMakeLists.txt
+++ b/examples/example_glfw_vulkan/CMakeLists.txt
@@ -42,4 +42,4 @@ file(GLOB sources *.cpp)
 
 add_executable(example_glfw_vulkan ${sources} ${IMGUI_DIR}/backends/imgui_impl_glfw.cpp ${IMGUI_DIR}/backends/imgui_impl_vulkan.cpp ${IMGUI_DIR}/imgui.cpp ${IMGUI_DIR}/imgui_draw.cpp ${IMGUI_DIR}/imgui_demo.cpp ${IMGUI_DIR}/imgui_tables.cpp ${IMGUI_DIR}/imgui_widgets.cpp)
 target_link_libraries(example_glfw_vulkan ${LIBRARIES})
-target_compile_definitions(example_glfw_vulkan PUBLIC -DImTextureID=ImU64)
+
diff --git a/examples/example_glfw_vulkan/build_win32.bat b/examples/example_glfw_vulkan/build_win32.bat
index be9239816..bb54a4210 100644
--- a/examples/example_glfw_vulkan/build_win32.bat
+++ b/examples/example_glfw_vulkan/build_win32.bat
@@ -7,8 +7,8 @@
 
 @set OUT_DIR=Debug
 mkdir %OUT_DIR%
-cl /nologo /Zi /MD /utf-8 %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
+cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
 
 @set OUT_DIR=Release
 mkdir %OUT_DIR%
-cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
+cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
diff --git a/examples/example_glfw_vulkan/build_win64.bat b/examples/example_glfw_vulkan/build_win64.bat
index c60b02789..54e40e3e8 100644
--- a/examples/example_glfw_vulkan/build_win64.bat
+++ b/examples/example_glfw_vulkan/build_win64.bat
@@ -6,8 +6,8 @@
 
 @set OUT_DIR=Debug
 mkdir %OUT_DIR%
-cl /nologo /Zi /MD /utf-8 %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
+cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
 
 @set OUT_DIR=Release
 mkdir %OUT_DIR%
-cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
+cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj
index d0d1c5f88..a81d328df 100644
--- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj
+++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj
@@ -91,7 +91,7 @@
       Level4
       Disabled
       ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories)
-      ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions)
+      _MBCS;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -107,7 +107,7 @@
       Level4
       Disabled
       ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories)
-      ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions)
+      _MBCS;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -126,7 +126,7 @@
       true
       ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories)
       false
-      ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions)
+      _MBCS;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -148,7 +148,7 @@
       true
       ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories)
       false
-      ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions)
+      _MBCS;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
diff --git a/examples/example_sdl2_vulkan/build_win32.bat b/examples/example_sdl2_vulkan/build_win32.bat
index 8a4aefc22..977a2c7e4 100644
--- a/examples/example_sdl2_vulkan/build_win32.bat
+++ b/examples/example_sdl2_vulkan/build_win32.bat
@@ -7,4 +7,4 @@
 
 @set OUT_DIR=Debug
 mkdir %OUT_DIR%
-cl /nologo /Zi /MD /utf-8 %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
+cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
diff --git a/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj b/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj
index ba6afaf72..bcf99a46c 100644
--- a/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj
+++ b/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj
@@ -91,7 +91,7 @@
       Level4
       Disabled
       ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories)
-      ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions)
+      _MBCS;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -107,7 +107,7 @@
       Level4
       Disabled
       ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories)
-      ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions)
+      _MBCS;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -126,7 +126,7 @@
       true
       ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories)
       false
-      ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions)
+      _MBCS;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -148,7 +148,7 @@
       true
       ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories)
       false
-      ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions)
+      _MBCS;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -187,4 +187,4 @@
   
   
   
-
\ No newline at end of file
+
diff --git a/examples/example_win32_directx12/build_win32.bat b/examples/example_win32_directx12/build_win32.bat
index 68e3c921e..cb5e8e273 100644
--- a/examples/example_win32_directx12/build_win32.bat
+++ b/examples/example_win32_directx12/build_win32.bat
@@ -1,9 +1,8 @@
 @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
-@REM Important: to build on 32-bit systems, the DX12 backends needs '#define ImTextureID ImU64', so we pass it here.
 @set OUT_DIR=Debug
 @set OUT_EXE=example_win32_directx12
 @set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared"
 @set SOURCES=main.cpp ..\..\backends\imgui_impl_dx12.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp
 @set LIBS=d3d12.lib d3dcompiler.lib dxgi.lib
 mkdir Debug
-cl /nologo /Zi /MD /utf-8 %INCLUDES% /D ImTextureID=ImU64 /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
+cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj b/examples/example_win32_directx12/example_win32_directx12.vcxproj
index 62191839e..bb98c4141 100644
--- a/examples/example_win32_directx12/example_win32_directx12.vcxproj
+++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj
@@ -87,7 +87,7 @@
       Level4
       Disabled
       ..\..;..\..\backends;%(AdditionalIncludeDirectories)
-      ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions)
+      _UNICODE;UNICODE;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -102,7 +102,7 @@
       Level4
       Disabled
       ..\..;..\..\backends;%(AdditionalIncludeDirectories)
-      ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions)
+      _UNICODE;UNICODE;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -119,7 +119,7 @@
       true
       true
       ..\..;..\..\backends;%(AdditionalIncludeDirectories)
-      ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions)
+      _UNICODE;UNICODE;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
@@ -138,7 +138,7 @@
       true
       true
       ..\..;..\..\backends;%(AdditionalIncludeDirectories)
-      ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions)
+      _UNICODE;UNICODE;%(PreprocessorDefinitions)
       /utf-8 %(AdditionalOptions)
     
     
diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp
index 57a481c71..4173a8010 100644
--- a/examples/example_win32_directx12/main.cpp
+++ b/examples/example_win32_directx12/main.cpp
@@ -6,10 +6,6 @@
 // - Documentation        https://dearimgui.com/docs (same as your local docs/ folder).
 // - Introduction, links and more at the top of imgui.cpp
 
-// Important: to compile on 32-bit systems, the DirectX12 backend requires code to be compiled with '#define ImTextureID ImU64'.
-// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
-// This define is set in the example .vcxproj file and need to be replicated in your app or by adding it to your imconfig.h file.
-
 #include "imgui.h"
 #include "imgui_impl_win32.h"
 #include "imgui_impl_dx12.h"
diff --git a/imgui.cpp b/imgui.cpp
index 2d7edc43e..33170e430 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -430,6 +430,14 @@ CODE
  When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  You can read releases logs https://github.com/ocornut/imgui/releases for more details.
 
+ - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
+                         this removes the requirement to redefine it for backends which are e.g. storing descriptor sets or other 64-bits structures when building on 32-bits archs. It therefore simplify various building scripts/helpers.
+                         you may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID' when passing your types to functions taking ImTextureID values, e.g. ImGui::Image().
+                         in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning:
+                            - May warn:    ImGui::Image((void*)MyTextureData, ...);
+                            - May warn:    ImGui::Image((void*)(intptr_t)MyTextureData, ...);
+                            - Won't warn:  ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
+  -                      note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like.
  - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76)
                        - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed).
                          although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76)
diff --git a/imgui.h b/imgui.h
index f3d5d83d4..87d77c2c2 100644
--- a/imgui.h
+++ b/imgui.h
@@ -249,8 +249,10 @@ typedef int ImGuiWindowFlags;       // -> enum ImGuiWindowFlags_     // Flags: f
 // ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type]
 // - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file.
 // - This can be whatever to you want it to be! read the FAQ about ImTextureID for details.
+// - You can make this a structure with various constructors if you need. You will have to implement ==/!= operators.
+// - (note: before v1.91.4 (2024/10/08) the default type for ImTextureID was void*. Use intermediary intptr_t cast and read FAQ if you have casting warnings)
 #ifndef ImTextureID
-typedef void* ImTextureID;          // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that)
+typedef ImU64 ImTextureID;          // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that)
 #endif
 
 // ImDrawIdx: vertex index. [Compile-time configurable type]
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index b69bc789f..0c10a79b7 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -619,7 +619,7 @@ void ImDrawList::PushTextureID(ImTextureID texture_id)
 void ImDrawList::PopTextureID()
 {
     _TextureIdStack.pop_back();
-    _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1];
+    _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? ImTextureID() : _TextureIdStack.Data[_TextureIdStack.Size - 1];
     _OnChangedTextureID();
 }
 
@@ -2777,7 +2777,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
     ImFontAtlasBuildInit(atlas);
 
     // Clear atlas
-    atlas->TexID = (ImTextureID)NULL;
+    atlas->TexID = ImTextureID();
     atlas->TexWidth = atlas->TexHeight = 0;
     atlas->TexUvScale = ImVec2(0.0f, 0.0f);
     atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index baaf4f4e7..156e7a813 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1122,7 +1122,7 @@ bool ImGui::ImageButton(const char* str_id, ImTextureID user_texture_id, const I
 bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
 {
     // Default to using texture ID as ID. User can still push string/integer prefixes.
-    PushID((void*)(intptr_t)user_texture_id);
+    PushID((ImTextureID)(intptr_t)user_texture_id);
     if (frame_padding >= 0)
         PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2((float)frame_padding, (float)frame_padding));
     bool ret = ImageButton("", user_texture_id, size, uv0, uv1, bg_col, tint_col);

From 6b8accbfa1bca2d755e6dd14c18da5c17ef61488 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 8 Oct 2024 14:29:21 +0200
Subject: [PATCH 0414/2359] Fixed building when defining ImTextureID to a
 multi-token name. (#1641)

Amend 92b9498
---
 imgui_draw.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 0c10a79b7..b69bc789f 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -619,7 +619,7 @@ void ImDrawList::PushTextureID(ImTextureID texture_id)
 void ImDrawList::PopTextureID()
 {
     _TextureIdStack.pop_back();
-    _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? ImTextureID() : _TextureIdStack.Data[_TextureIdStack.Size - 1];
+    _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1];
     _OnChangedTextureID();
 }
 
@@ -2777,7 +2777,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
     ImFontAtlasBuildInit(atlas);
 
     // Clear atlas
-    atlas->TexID = ImTextureID();
+    atlas->TexID = (ImTextureID)NULL;
     atlas->TexWidth = atlas->TexHeight = 0;
     atlas->TexUvScale = ImVec2(0.0f, 0.0f);
     atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);

From c3629adbeb22740c7f352a0dcc17870b80630e37 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 8 Oct 2024 14:33:17 +0200
Subject: [PATCH 0415/2359] Backends: Metal: fixed ImTextureID cast. (#1641)

Amend 92b9498
---
 backends/imgui_impl_metal.mm | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm
index 818961048..b8f82a65d 100644
--- a/backends/imgui_impl_metal.mm
+++ b/backends/imgui_impl_metal.mm
@@ -291,7 +291,7 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c
 
                 // Bind texture, Draw
                 if (ImTextureID tex_id = pcmd->GetTexID())
-                    [commandEncoder setFragmentTexture:(__bridge id)(tex_id) atIndex:0];
+                    [commandEncoder setFragmentTexture:(__bridge id)(void*)(intptr_t)(tex_id) atIndex:0];
 
                 [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0];
                 [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
@@ -347,7 +347,7 @@ bool ImGui_ImplMetal_CreateFontsTexture(id device)
     id  texture = [device newTextureWithDescriptor:textureDescriptor];
     [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4];
     bd->SharedMetalContext.fontTexture = texture;
-    io.Fonts->SetTexID((__bridge void*)bd->SharedMetalContext.fontTexture); // ImTextureID == void*
+    io.Fonts->SetTexID((ImTextureID)(intptr_t)(__bridge void*)bd->SharedMetalContext.fontTexture); // ImTextureID == ImU64
 
     return (bd->SharedMetalContext.fontTexture != nil);
 }

From f3d242a90d645dec043d63d128015c87f0ac9fe8 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 8 Oct 2024 19:45:58 +0200
Subject: [PATCH 0416/2359] Tables: fixed initial auto-sizing issue with
 synched-instances. (#8045, #7218)

---
 docs/CHANGELOG.txt | 1 +
 imgui.h            | 2 +-
 imgui_tables.cpp   | 2 +-
 3 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 96a52ff40..32818837f 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -60,6 +60,7 @@ Other changes:
 - IO: added 'void* platform_io.Renderer_RenderState' which is set during the
   ImGui_ImplXXXX_RenderDrawData() of standard backend to expose selected render
   state to draw callbacks. (#6969, #5834, #7468, #3590)
+- Tables: fixed initial auto-sizing issue with synched-instances. (#8045, #7218)
 - Backends: DX11, DX12, Vulkan, WGPU: expose selected state in ImGui_ImplXXXX_RenderState.
   structure during render loop. (#6969, #5834, #7468, #3590)
 - Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan, WGPU: Changed default texture sampler
diff --git a/imgui.h b/imgui.h
index 87d77c2c2..8cda26dea 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.4 WIP"
-#define IMGUI_VERSION_NUM   19131
+#define IMGUI_VERSION_NUM   19132
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 491566d7a..3ba15fef5 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1160,7 +1160,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table)
         }
 
         // Don't decrement auto-fit counters until container window got a chance to submit its items
-        if (table->HostSkipItems == false)
+        if (table->HostSkipItems == false && table->InstanceCurrent == 0)
         {
             column->AutoFitQueue >>= 1;
             column->CannotSkipItemsQueue >>= 1;

From 661bba09ce1fc815765d662fa982bc1d1d3f8c6e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 9 Oct 2024 13:54:39 +0200
Subject: [PATCH 0417/2359] InputText: fixed an issue with not declaring
 ownership of Delete/Backspace/Arrow keys. (#8048)

---
 docs/CHANGELOG.txt | 4 +++-
 docs/README.md     | 2 +-
 imgui_widgets.cpp  | 8 ++++++++
 3 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 32818837f..1af37fc5f 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -61,10 +61,12 @@ Other changes:
   ImGui_ImplXXXX_RenderDrawData() of standard backend to expose selected render
   state to draw callbacks. (#6969, #5834, #7468, #3590)
 - Tables: fixed initial auto-sizing issue with synched-instances. (#8045, #7218)
+- InputText: fixed an issue with not declaring ownership of Delete/Backspace/Arrow keys,
+  preventing use of external shortcuts not guarded by an ActiveId check. (#8048) [@geertbleyen]
 - Backends: DX11, DX12, Vulkan, WGPU: expose selected state in ImGui_ImplXXXX_RenderState.
   structure during render loop. (#6969, #5834, #7468, #3590)
 - Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan, WGPU: Changed default texture sampler
-  to Clamp instead of Repeat/Wrap. (#7468, #7511, #5999, #5502)
+  to Clamp instead of Repeat/Wrap. (#7468, #7511, #5999, #5502, #7230)
 
 
 -----------------------------------------------------------------------
diff --git a/docs/README.md b/docs/README.md
index 0968727f1..c47f03b9b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -196,7 +196,7 @@ Ongoing Dear ImGui development is and has been financially supported by users an
 **THANK YOU to all past and present supporters for helping to keep this project alive and thriving!**
 
 Dear ImGui is using software and services provided free of charge for open source projects:
-- [PVS-Studio](https://www.viva64.com/en/b/0570/) for static analysis.
+- [PVS-Studio](https://pvs-studio.com/en/pvs-studio/?utm_source=website&utm_medium=github&utm_campaign=open_source) for static analysis (supports C/C++/C#/Java).
 - [GitHub actions](https://github.com/features/actions) for continuous integration systems.
 - [OpenCppCoverage](https://github.com/OpenCppCoverage/OpenCppCoverage) for code coverage analysis.
 
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 156e7a813..4f6315879 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4569,10 +4569,18 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         if (user_clicked)
             SetKeyOwner(ImGuiKey_MouseLeft, id);
         g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
+        SetKeyOwner(ImGuiKey_LeftArrow, id);
+        SetKeyOwner(ImGuiKey_RightArrow, id);
         if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory))
+        {
             g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
+            SetKeyOwner(ImGuiKey_UpArrow, id);
+            SetKeyOwner(ImGuiKey_DownArrow, id);
+        }
         SetKeyOwner(ImGuiKey_Enter, id);
         SetKeyOwner(ImGuiKey_KeypadEnter, id);
+        SetKeyOwner(ImGuiKey_Delete, id);
+        SetKeyOwner(ImGuiKey_Backspace, id);
         SetKeyOwner(ImGuiKey_Home, id);
         SetKeyOwner(ImGuiKey_End, id);
         if (is_multiline)

From 9fbc3134591bdca66d548a97f284c3a5e2811b6f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 9 Oct 2024 14:01:47 +0200
Subject: [PATCH 0418/2359] InputText: amend 661bba0. (#8048)

---
 imgui_widgets.cpp | 12 ++++--------
 1 file changed, 4 insertions(+), 8 deletions(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 4f6315879..9d4ef66da 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4566,23 +4566,19 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     if (g.ActiveId == id)
     {
         // Declare some inputs, the other are registered and polled via Shortcut() routing system.
+        // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combinaison into individual shortcuts.
+        const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Enter, ImGuiKey_KeypadEnter, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End };
+        for (ImGuiKey key : always_owned_keys)
+            SetKeyOwner(key, id);
         if (user_clicked)
             SetKeyOwner(ImGuiKey_MouseLeft, id);
         g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
-        SetKeyOwner(ImGuiKey_LeftArrow, id);
-        SetKeyOwner(ImGuiKey_RightArrow, id);
         if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory))
         {
             g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
             SetKeyOwner(ImGuiKey_UpArrow, id);
             SetKeyOwner(ImGuiKey_DownArrow, id);
         }
-        SetKeyOwner(ImGuiKey_Enter, id);
-        SetKeyOwner(ImGuiKey_KeypadEnter, id);
-        SetKeyOwner(ImGuiKey_Delete, id);
-        SetKeyOwner(ImGuiKey_Backspace, id);
-        SetKeyOwner(ImGuiKey_Home, id);
-        SetKeyOwner(ImGuiKey_End, id);
         if (is_multiline)
         {
             SetKeyOwner(ImGuiKey_PageUp, id);

From a0b811dd37392121227dce75710580834eff2294 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 9 Oct 2024 16:39:28 +0200
Subject: [PATCH 0419/2359] Backends: SDLRenderer2/3: expose selected state in
 ImGui_ImplXXXX_RenderState structures during render loop. (#6969, #5834,
 #7468, #3590 + #7616)

---
 backends/imgui_impl_sdlrenderer2.cpp | 13 ++++++++++++-
 backends/imgui_impl_sdlrenderer2.h   |  9 +++++++++
 backends/imgui_impl_sdlrenderer3.cpp | 13 ++++++++++++-
 backends/imgui_impl_sdlrenderer3.h   |  9 +++++++++
 docs/CHANGELOG.txt                   |  4 ++--
 5 files changed, 44 insertions(+), 4 deletions(-)

diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp
index 8203c6caf..27c952269 100644
--- a/backends/imgui_impl_sdlrenderer2.cpp
+++ b/backends/imgui_impl_sdlrenderer2.cpp
@@ -10,6 +10,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -20,6 +21,7 @@
 // - Introduction, links and more at the top of imgui.cpp
 
 // CHANGELOG
+//  2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer2_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter.
 //  2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3.
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
@@ -140,12 +142,20 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
     SDL_RenderGetViewport(renderer, &old.Viewport);
     SDL_RenderGetClipRect(renderer, &old.ClipRect);
 
+    // Setup desired state
+    ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
+
+    // Setup render state structure (for callbacks and custom texture bindings)
+    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
+    ImGui_ImplSDLRenderer2_RenderState render_state;
+    render_state.Renderer = renderer;
+    platform_io.Renderer_RenderState = &render_state;
+
 	// Will project scissor/clipping rectangles into framebuffer space
 	ImVec2 clip_off = draw_data->DisplayPos;         // (0,0) unless using multi-viewports
 	ImVec2 clip_scale = render_scale;
 
     // Render command lists
-    ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
         const ImDrawList* draw_list = draw_data->CmdLists[n];
@@ -198,6 +208,7 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
             }
         }
     }
+    platform_io.Renderer_RenderState = NULL;
 
     // Restore modified SDL_Renderer state
     SDL_RenderSetViewport(renderer, &old.Viewport);
diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h
index c067eaeea..804ca183d 100644
--- a/backends/imgui_impl_sdlrenderer2.h
+++ b/backends/imgui_impl_sdlrenderer2.h
@@ -10,6 +10,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -37,4 +38,12 @@ IMGUI_IMPL_API void     ImGui_ImplSDLRenderer2_DestroyFontsTexture();
 IMGUI_IMPL_API bool     ImGui_ImplSDLRenderer2_CreateDeviceObjects();
 IMGUI_IMPL_API void     ImGui_ImplSDLRenderer2_DestroyDeviceObjects();
 
+// [BETA] Selected render state data shared with callbacks.
+// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLRenderer2_RenderDrawData() call.
+// (Please open an issue if you feel you need access to more data)
+struct ImGui_ImplSDLRenderer2_RenderState
+{
+    SDL_Renderer*       Renderer;
+};
+
 #endif // #ifndef IMGUI_DISABLE
diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp
index 9397a6467..5dabea199 100644
--- a/backends/imgui_impl_sdlrenderer3.cpp
+++ b/backends/imgui_impl_sdlrenderer3.cpp
@@ -12,6 +12,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -22,6 +23,7 @@
 // - Introduction, links and more at the top of imgui.cpp
 
 // CHANGELOG
+//  2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer3_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2024-07-01: Update for SDL3 api changes: SDL_RenderGeometryRaw() uint32 version was removed (SDL#9009).
 //  2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter.
 //  2024-02-12: Amend to query SDL_RenderViewportSet() and restore viewport accordingly.
@@ -163,12 +165,20 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
     SDL_GetRenderViewport(renderer, &old.Viewport);
     SDL_GetRenderClipRect(renderer, &old.ClipRect);
 
+    // Setup desired state
+    ImGui_ImplSDLRenderer3_SetupRenderState(renderer);
+
+    // Setup render state structure (for callbacks and custom texture bindings)
+    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
+    ImGui_ImplSDLRenderer3_RenderState render_state;
+    render_state.Renderer = renderer;
+    platform_io.Renderer_RenderState = &render_state;
+
 	// Will project scissor/clipping rectangles into framebuffer space
 	ImVec2 clip_off = draw_data->DisplayPos;         // (0,0) unless using multi-viewports
 	ImVec2 clip_scale = render_scale;
 
     // Render command lists
-    ImGui_ImplSDLRenderer3_SetupRenderState(renderer);
     for (int n = 0; n < draw_data->CmdListsCount; n++)
     {
         const ImDrawList* draw_list = draw_data->CmdLists[n];
@@ -217,6 +227,7 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
             }
         }
     }
+    platform_io.Renderer_RenderState = NULL;
 
     // Restore modified SDL_Renderer state
     SDL_SetRenderViewport(renderer, old.ViewportEnabled ? &old.Viewport : nullptr);
diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h
index 6c23deca9..7d4c609e8 100644
--- a/backends/imgui_impl_sdlrenderer3.h
+++ b/backends/imgui_impl_sdlrenderer3.h
@@ -12,6 +12,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
@@ -39,4 +40,12 @@ IMGUI_IMPL_API void     ImGui_ImplSDLRenderer3_DestroyFontsTexture();
 IMGUI_IMPL_API bool     ImGui_ImplSDLRenderer3_CreateDeviceObjects();
 IMGUI_IMPL_API void     ImGui_ImplSDLRenderer3_DestroyDeviceObjects();
 
+// [BETA] Selected render state data shared with callbacks.
+// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLRenderer3_RenderDrawData() call.
+// (Please open an issue if you feel you need access to more data)
+struct ImGui_ImplSDLRenderer3_RenderState
+{
+    SDL_Renderer*       Renderer;
+};
+
 #endif // #ifndef IMGUI_DISABLE
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 1af37fc5f..427086625 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -63,8 +63,8 @@ Other changes:
 - Tables: fixed initial auto-sizing issue with synched-instances. (#8045, #7218)
 - InputText: fixed an issue with not declaring ownership of Delete/Backspace/Arrow keys,
   preventing use of external shortcuts not guarded by an ActiveId check. (#8048) [@geertbleyen]
-- Backends: DX11, DX12, Vulkan, WGPU: expose selected state in ImGui_ImplXXXX_RenderState.
-  structure during render loop. (#6969, #5834, #7468, #3590)
+- Backends: DX11, DX12, SDLRenderer2/3. Vulkan, WGPU: expose selected state in
+  ImGui_ImplXXXX_RenderState structures during render loop. (#6969, #5834, #7468, #3590)
 - Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan, WGPU: Changed default texture sampler
   to Clamp instead of Repeat/Wrap. (#7468, #7511, #5999, #5502, #7230)
 

From f29e505d94ed41e556945ec0f9f29c07cf6c412c Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 9 Oct 2024 17:14:44 +0200
Subject: [PATCH 0420/2359] CI: remove --disableLicenseExpirationCheck.

---
 .github/workflows/static-analysis.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml
index 99b058c91..69df5cdf8 100644
--- a/.github/workflows/static-analysis.yml
+++ b/.github/workflows/static-analysis.yml
@@ -42,5 +42,5 @@ jobs:
           fi
           cd examples/example_null
           pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1
-          pvs-studio-analyzer analyze --disableLicenseExpirationCheck -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log
+          pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log
           plog-converter -a 'GA:1,2;OP:1' -d V1071 -t errorfile -w pvs-studio.log

From 98d52b7b26cccae5d3523bbefddbcb8da627e130 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 11 Oct 2024 13:29:13 +0200
Subject: [PATCH 0421/2359] DrawList: AddCallback() added an optional size
 parameter allowing to copy and store any amount of user data for usage by
 callbacks: (#6969, #4770, #7665)

---
 docs/CHANGELOG.txt |  8 ++++++++
 docs/TODO.txt      |  5 ++---
 imgui.h            | 23 ++++++++++++++++++-----
 imgui_draw.cpp     | 30 ++++++++++++++++++++++++++++--
 4 files changed, 56 insertions(+), 10 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 427086625..4fda69c0e 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -60,6 +60,14 @@ Other changes:
 - IO: added 'void* platform_io.Renderer_RenderState' which is set during the
   ImGui_ImplXXXX_RenderDrawData() of standard backend to expose selected render
   state to draw callbacks. (#6969, #5834, #7468, #3590)
+- DrawList: AddCallback() added an optional size parameter allowing to copy and
+  store any amount of user data for usage by callbacks: (#6969, #4770, #7665)
+  - If userdata_size == 0: we copy/store the 'userdata' argument as-is (existing behavior).
+    It will be available unmodified in ImDrawCmd::UserCallbackData during render.
+  - If userdata_size > 0, we copy/store 'userdata_size' bytes pointed to by 'userdata' (new behavior).
+    We store them in a buffer stored inside the drawlist. ImDrawCmd::UserCallbackData 
+    will point inside that buffer so you have to retrieve data from there. Your callback
+    may need to use ImDrawCmd::UserCallbackDataSize if you expect dynamically-sized data.
 - Tables: fixed initial auto-sizing issue with synched-instances. (#8045, #7218)
 - InputText: fixed an issue with not declaring ownership of Delete/Backspace/Arrow keys,
   preventing use of external shortcuts not guarded by an ActiveId check. (#8048) [@geertbleyen]
diff --git a/docs/TODO.txt b/docs/TODO.txt
index ddceb3b3d..e61501d78 100644
--- a/docs/TODO.txt
+++ b/docs/TODO.txt
@@ -9,8 +9,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
  - doc: add a proper documentation system (maybe relying on automation? #435)
  - doc: checklist app to verify backends/integration of imgui (test inputs, rendering, callback, etc.).
  - doc/tips: tips of the day: website? applet in imgui_club?
- - doc/wiki: work on the wiki https://github.com/ocornut/imgui/wiki
-
+ 
  - window: preserve/restore relative focus ordering (persistent or not), and e.g. of multiple reappearing windows (#2304) -> also see docking reference to same #.
  - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis). (#690)
  - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass.
@@ -44,7 +43,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
  - drawlist: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). (WIP branch)
  - drawlist: make it easier to toggle AA per primitive, so we can use e.g. non-AA fill + AA borders more naturally
  - drawlist: non-AA strokes have gaps between points (#593, #288), glitch especially on RenderCheckmark() and ColorPicker4().
- - drawlist: callback: add an extra void* in ImDrawCallback to allow passing render-local data to the callback (would break API).
+ - drawlist: callback: add an extra void* in ImDrawCallback to expose render state instead of pulling from Renderer_RenderState (would break API).
  - drawlist: AddRect vs AddLine position confusing (#2441)
  - drawlist/opt: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. (#1962)
  - drawlist/opt: AddRect() axis aligned pixel aligned (no-aa) could use 8 triangles instead of 16 and no normal calculation.
diff --git a/imgui.h b/imgui.h
index 8cda26dea..d18879ce1 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.4 WIP"
-#define IMGUI_VERSION_NUM   19132
+#define IMGUI_VERSION_NUM   19133
 #define IMGUI_HAS_TABLE
 
 /*
@@ -2953,9 +2953,11 @@ struct ImDrawCmd
     unsigned int    IdxOffset;          // 4    // Start offset in index buffer.
     unsigned int    ElemCount;          // 4    // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[].
     ImDrawCallback  UserCallback;       // 4-8  // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.
-    void*           UserCallbackData;   // 4-8  // The draw callback code can access this.
+    void*           UserCallbackData;   // 4-8  // Callback user data (when UserCallback != NULL). If called AddCallback() with size == 0, this is a copy of the AddCallback() argument. If called AddCallback() with size > 0, this is pointing to a buffer where data is stored.
+    int             UserCallbackDataSize;  // 4 // Size of callback user data when using storage, otherwise 0.
+    int             UserCallbackDataOffset;// 4 // [Internal] Offset of callback user data when using storage, otherwise -1.
 
-    ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed
+    ImDrawCmd()     { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed
 
     // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature)
     inline ImTextureID GetTexID() const { return TextureId; }
@@ -3068,6 +3070,7 @@ struct ImDrawList
     ImDrawListSplitter      _Splitter;          // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!)
     ImVector        _ClipRectStack;     // [Internal]
     ImVector   _TextureIdStack;    // [Internal]
+    ImVector          _CallbacksDataBuf;  // [Internal]
     float                   _FringeScale;       // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content
     const char*             _OwnerName;         // Pointer to owner window's name for debugging
 
@@ -3140,8 +3143,18 @@ struct ImDrawList
     IMGUI_API void  PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0);               // Quadratic Bezier (3 control points)
     IMGUI_API void  PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawFlags flags = 0);
 
-    // Advanced
-    IMGUI_API void  AddCallback(ImDrawCallback callback, void* callback_data);  // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles.
+    // Advanced: Draw Callbacks
+    // - May be used to alter render state (change sampler, blending, current shader). May be used to emit custom rendering commands (difficult to do correctly, but possible).
+    // - Use special ImDrawCallback_ResetRenderState callback to instruct backend to reset its render state to the default.
+    // - Your rendering loop must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. All standard backends are honoring this.
+    // - For some backends, the callback may access selected render-states exposed by the backend in a ImGui_ImplXXXX_RenderState structure pointed to by platform_io.Renderer_RenderState.
+    // - IMPORTANT: please be mindful of the different level of indirection between using size==0 (copying argument) and using size>0 (copying pointed data into a buffer).
+    //   - If userdata_size == 0: we copy/store the 'userdata' argument as-is. It will be available unmodified in ImDrawCmd::UserCallbackData during render.
+    //   - If userdata_size > 0,  we copy/store 'userdata_size' bytes pointed to by 'userdata'. We store them in a buffer stored inside the drawlist. ImDrawCmd::UserCallbackData will point inside that buffer so you have to retrieve data from there. Your callback may need to use ImDrawCmd::UserCallbackDataSize if you expect dynamically-sized data.
+    //   - Support for userdata_size > 0 was added in v1.91.4, October 2024. So earlier code always only allowed to copy/store a simple void*.
+    IMGUI_API void  AddCallback(ImDrawCallback callback, void* userdata, size_t userdata_size = 0);
+
+    // Advanced: Miscellaneous
     IMGUI_API void  AddDrawCmd();                                               // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible
     IMGUI_API ImDrawList* CloneOutput() const;                                  // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer.
 
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index b69bc789f..efee2ec9c 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -414,6 +414,7 @@ void ImDrawList::_ResetForNewFrame()
     _IdxWritePtr = NULL;
     _ClipRectStack.resize(0);
     _TextureIdStack.resize(0);
+    _CallbacksDataBuf.resize(0);
     _Path.resize(0);
     _Splitter.Clear();
     CmdBuffer.push_back(ImDrawCmd());
@@ -431,6 +432,7 @@ void ImDrawList::_ClearFreeMemory()
     _IdxWritePtr = NULL;
     _ClipRectStack.clear();
     _TextureIdStack.clear();
+    _CallbacksDataBuf.clear();
     _Path.clear();
     _Splitter.ClearFreeMemory();
 }
@@ -470,7 +472,7 @@ void ImDrawList::_PopUnusedDrawCmd()
     }
 }
 
-void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data)
+void ImDrawList::AddCallback(ImDrawCallback callback, void* userdata, size_t userdata_size)
 {
     IM_ASSERT_PARANOID(CmdBuffer.Size > 0);
     ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
@@ -480,8 +482,26 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data)
         AddDrawCmd();
         curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
     }
+
     curr_cmd->UserCallback = callback;
-    curr_cmd->UserCallbackData = callback_data;
+    if (userdata_size == 0)
+    {
+        // Store user data directly in command (no indirection)
+        curr_cmd->UserCallbackData = userdata;
+        curr_cmd->UserCallbackDataSize = 0;
+        curr_cmd->UserCallbackDataOffset = -1;
+    }
+    else
+    {
+        // Copy and store user data in a buffer
+        IM_ASSERT(userdata != NULL);
+        IM_ASSERT(userdata_size < (1u << 31));
+        curr_cmd->UserCallbackData = NULL; // Will be resolved during Render()
+        curr_cmd->UserCallbackDataSize = (int)userdata_size;
+        curr_cmd->UserCallbackDataOffset = _CallbacksDataBuf.Size;
+        _CallbacksDataBuf.resize(_CallbacksDataBuf.Size + (int)userdata_size);
+        memcpy(_CallbacksDataBuf.Data + (size_t)curr_cmd->UserCallbackDataOffset, userdata, userdata_size);
+    }
 
     AddDrawCmd(); // Force a new command after us (see comment below)
 }
@@ -2222,6 +2242,12 @@ void ImGui::AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector
     if (sizeof(ImDrawIdx) == 2)
         IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
 
+    // Resolve callback data pointers
+    if (draw_list->_CallbacksDataBuf.Size > 0)
+        for (ImDrawCmd& cmd : draw_list->CmdBuffer)
+            if (cmd.UserCallback != NULL && cmd.UserCallbackDataOffset != -1 && cmd.UserCallbackDataSize > 0)
+                cmd.UserCallbackData = draw_list->_CallbacksDataBuf.Data + cmd.UserCallbackDataOffset;
+
     // Add to output list + records state in ImDrawData
     out_list->push_back(draw_list);
     draw_data->CmdListsCount++;

From c4bc6744824de148c3f825ffdcde785510e208ac Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 11 Oct 2024 15:31:01 +0200
Subject: [PATCH 0422/2359] IO: WantCaptureKeyboard is never set when
 ImGuiConfigFlags_NoKeyboard is enabled. (#4921)

+ Retroactively add missing changelog item in 1.90
+ Backends: Vulkan: use GetTexID() for consistency.
---
 backends/imgui_impl_vulkan.cpp |  4 ++--
 docs/CHANGELOG.txt             |  2 ++
 imgui.cpp                      | 11 ++++++++---
 3 files changed, 12 insertions(+), 5 deletions(-)

diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 78d838955..a68f862b1 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -589,11 +589,11 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
                 vkCmdSetScissor(command_buffer, 0, 1, &scissor);
 
                 // Bind DescriptorSet with font or user texture
-                VkDescriptorSet desc_set[1] = { (VkDescriptorSet)pcmd->TextureId };
+                VkDescriptorSet desc_set[1] = { (VkDescriptorSet)pcmd->GetTexID() };
                 if (sizeof(ImTextureID) < sizeof(ImU64))
                 {
                     // We don't support texture switches if ImTextureID hasn't been redefined to be 64-bit. Do a flaky check that other textures haven't been used.
-                    IM_ASSERT(pcmd->TextureId == (ImTextureID)bd->FontDescriptorSet);
+                    IM_ASSERT(pcmd->GetTexID() == (ImTextureID)bd->FontDescriptorSet);
                     desc_set[0] = bd->FontDescriptorSet;
                 }
                 vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, desc_set, 0, nullptr);
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 4fda69c0e..8178df1f9 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -60,6 +60,7 @@ Other changes:
 - IO: added 'void* platform_io.Renderer_RenderState' which is set during the
   ImGui_ImplXXXX_RenderDrawData() of standard backend to expose selected render
   state to draw callbacks. (#6969, #5834, #7468, #3590)
+- IO: WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
 - DrawList: AddCallback() added an optional size parameter allowing to copy and
   store any amount of user data for usage by callbacks: (#6969, #4770, #7665)
   - If userdata_size == 0: we copy/store the 'userdata' argument as-is (existing behavior).
@@ -480,6 +481,7 @@ Other changes:
   which was pressed over void/underlying app, which is consistent/needed to allow the
   mouse up event of a drag over void/underlying app to catch release. (#1392) [@Moka42]
 - IO: Added io.ClearInputMouse() to clear mouse state. (#4921)
+- IO: Added ImGuiConfigFlags_NoKeyboard for consistency and convenience. (#4921)
 - Windows: BeginChild(): fixed a glitch when during a resize of a child window which is
   tightly close to the boundaries of its parent (e.g. with zero WindowPadding), the child
   position could have temporarily be moved around by erroneous padding application. (#7706)
diff --git a/imgui.cpp b/imgui.cpp
index 33170e430..0b2d787c4 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4998,9 +4998,14 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
     }
 
     // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
-    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
-    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
-        io.WantCaptureKeyboard = true;
+    io.WantCaptureKeyboard = false;
+    if ((io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) == 0)
+    {
+        if ((g.ActiveId != 0) || (modal_window != NULL))
+            io.WantCaptureKeyboard = true;
+        else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
+            io.WantCaptureKeyboard = true;
+    }
     if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
         io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
 

From 20ae8bd4c32fbeb048312ad23bc71dcf8a87fa89 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 10:22:24 +0200
Subject: [PATCH 0423/2359] Error Handling: turned
 IsItemHovered()/IsWindowHovered() checks into IM_ASSERT_USER_ERROR. (#1651)

---
 docs/CHANGELOG.txt | 1 +
 imgui.cpp          | 8 +++-----
 2 files changed, 4 insertions(+), 5 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 8178df1f9..977db92e6 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -61,6 +61,7 @@ Other changes:
   ImGui_ImplXXXX_RenderDrawData() of standard backend to expose selected render
   state to draw callbacks. (#6969, #5834, #7468, #3590)
 - IO: WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
+- Error Handling: turned a few more functions into recoverable errors. (#1651)
 - DrawList: AddCallback() added an optional size parameter allowing to copy and
   store any amount of user data for usage by callbacks: (#6969, #4770, #7665)
   - If userdata_size == 0: we copy/store the 'userdata' argument as-is (existing behavior).
diff --git a/imgui.cpp b/imgui.cpp
index 0b2d787c4..3bd7a473a 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4433,7 +4433,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
 {
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = g.CurrentWindow;
-    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
+    IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
 
     if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
     {
@@ -4455,8 +4455,6 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
         if (flags & ImGuiHoveredFlags_ForTooltip)
             flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
 
-        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy)) == 0);   // Flags not supported by this function
-
         // Done with rectangle culling so we can perform heavier checks now
         // Test if we are hovering the right window (our window could be behind another window)
         // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
@@ -8143,9 +8141,9 @@ bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_b
 // Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
 bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
 {
-    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
-
     ImGuiContext& g = *GImGui;
+    IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0, "Invalid flags for IsWindowHovered()!");
+
     ImGuiWindow* ref_window = g.HoveredWindow;
     ImGuiWindow* cur_window = g.CurrentWindow;
     if (ref_window == NULL)

From 349af8766cbb6ea7e56b242b18be8476bebbe977 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 13:52:40 +0200
Subject: [PATCH 0424/2359] InputText: ensure mouse cursor is set regardless of
 whether keyboard mode is enabled or not. (#6417)

+ Nav comments (#8059)
---
 docs/CHANGELOG.txt | 2 ++
 imgui.cpp          | 5 ++++-
 imgui_internal.h   | 1 +
 imgui_widgets.cpp  | 6 +++++-
 4 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 977db92e6..a01d5d6bc 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -73,6 +73,8 @@ Other changes:
 - Tables: fixed initial auto-sizing issue with synched-instances. (#8045, #7218)
 - InputText: fixed an issue with not declaring ownership of Delete/Backspace/Arrow keys,
   preventing use of external shortcuts not guarded by an ActiveId check. (#8048) [@geertbleyen]
+- InputText: ensure mouse cursor shape is set regardless of whether keyboard mode is 
+  enabled or not. (#6417)
 - Backends: DX11, DX12, SDLRenderer2/3. Vulkan, WGPU: expose selected state in
   ImGui_ImplXXXX_RenderState structures during render loop. (#6969, #5834, #7468, #3590)
 - Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan, WGPU: Changed default texture sampler
diff --git a/imgui.cpp b/imgui.cpp
index 3bd7a473a..971f48f16 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4606,7 +4606,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag
     }
 #endif
 
-    if (g.NavDisableMouseHover)
+    if (g.NavDisableMouseHover && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
         return false;
 
     return true;
@@ -13340,8 +13340,11 @@ static void ImGui::NavUpdateCancelRequest()
     else
     {
         // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
+        // FIXME-NAV: This should happen on window appearing.
         if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
             g.NavWindow->NavLastIds[0] = 0;
+
+        // Clear nav focus
         g.NavId = 0;
     }
 }
diff --git a/imgui_internal.h b/imgui_internal.h
index 05378c3d9..5722291af 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -833,6 +833,7 @@ enum ImGuiItemFlagsPrivate_
     ImGuiItemFlags_MixedValue               = 1 << 12, // false     // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets)
     ImGuiItemFlags_NoWindowHoverableCheck   = 1 << 13, // false     // Disable hoverable check in ItemHoverable()
     ImGuiItemFlags_AllowOverlap             = 1 << 14, // false     // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame.
+    ImGuiItemFlags_NoNavDisableMouseHover   = 1 << 15, // false     // Nav keyboard/gamepad mode doesn't disable hover.
 
     // Controlled by widget code
     ImGuiItemFlags_Inputable                = 1 << 20, // false     // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature.
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 9d4ef66da..aac7383b1 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4462,9 +4462,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))
                 return false;
     }
-    const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags);
+
+    // Ensure mouse cursor is set even after switching to keyboard/gamepad mode. May generalize further? (#6417)
+    bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags | ImGuiItemFlags_NoNavDisableMouseHover);
     if (hovered)
         SetMouseCursor(ImGuiMouseCursor_TextInput);
+    if (hovered && g.NavDisableMouseHover)
+        hovered = false;
 
     // We are only allowed to access the state if we are already the active widget.
     ImGuiInputTextState* state = GetInputTextState(id);

From d885fe4dd0cda0166415d423e6a4a5d4ef5e997c Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 15:28:00 +0200
Subject: [PATCH 0425/2359] (Breaking) moved
 ImGuiConfigFlags_NavEnableSetMousePos -> io.ConfigNavMoveSetMousePos,
 ImGuiConfigFlags_NavNoCaptureKeyboard -> ConfigNavCaptureKeyboard. (#2517,
 #2009)

---
 backends/imgui_impl_glfw.cpp  |  2 +-
 backends/imgui_impl_sdl2.cpp  |  2 +-
 backends/imgui_impl_sdl3.cpp  |  2 +-
 backends/imgui_impl_win32.cpp |  2 +-
 docs/CHANGELOG.txt            |  5 +++++
 imgui.cpp                     | 27 +++++++++++++++++++------
 imgui.h                       | 37 ++++++++++++++++++++---------------
 imgui_demo.cpp                | 12 ++++++++----
 imgui_internal.h              |  2 +-
 9 files changed, 60 insertions(+), 31 deletions(-)

diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp
index 7134d3e55..c725e9c01 100644
--- a/backends/imgui_impl_glfw.cpp
+++ b/backends/imgui_impl_glfw.cpp
@@ -728,7 +728,7 @@ static void ImGui_ImplGlfw_UpdateMouseData()
 #endif
         if (is_window_focused)
         {
-            // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
+            // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
             if (io.WantSetMousePos)
                 glfwSetCursorPos(window, (double)io.MousePos.x, (double)io.MousePos.y);
 
diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp
index 6d98a697e..1abe8b93d 100644
--- a/backends/imgui_impl_sdl2.cpp
+++ b/backends/imgui_impl_sdl2.cpp
@@ -605,7 +605,7 @@ static void ImGui_ImplSDL2_UpdateMouseData()
 #endif
     if (is_app_focused)
     {
-        // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
+        // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
         if (io.WantSetMousePos)
             SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y);
 
diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp
index 599d3fc44..517ba1ada 100644
--- a/backends/imgui_impl_sdl3.cpp
+++ b/backends/imgui_impl_sdl3.cpp
@@ -573,7 +573,7 @@ static void ImGui_ImplSDL3_UpdateMouseData()
 #endif
     if (is_app_focused)
     {
-        // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
+        // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
         if (io.WantSetMousePos)
             SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y);
 
diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index 0e9164efe..bbfa1a5be 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -308,7 +308,7 @@ static void ImGui_ImplWin32_UpdateMouseData()
     const bool is_app_focused = (focused_window == bd->hWnd);
     if (is_app_focused)
     {
-        // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
+        // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
         if (io.WantSetMousePos)
         {
             POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index a01d5d6bc..d67abea37 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -54,6 +54,11 @@ Breaking changes:
     - Won't warn:   ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
   - Note that you can always define ImTextureID to be your own high-level structures
     (with dedicated constructors) if you like.
+- IO: moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
+- IO: moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool 
+  (note the inverted value!). (#2517, #2009)
+  Kept legacy names (will obsolete) + code that copies settings once the first time. 
+  Dynamically changing the old value won't work. Switch to using the new value!
 
 Other changes:
 
diff --git a/imgui.cpp b/imgui.cpp
index 971f48f16..fa865503c 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -183,8 +183,8 @@ CODE
    - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
      in order to share your PC mouse/keyboard.
    - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
-   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
-     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
+   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the io.ConfigNavMoveSetMousePos flag.
+     Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
      When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
      When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
      (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
@@ -430,6 +430,9 @@ CODE
  When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  You can read releases logs https://github.com/ocornut/imgui/releases for more details.
 
+ - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
+                         moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
+                         kept legacy names (will obsolete) + code that copies settings once the first time. Dynamically changing the old value won't work. Switch to using the new value!
  - 2024/10/10 (1.91.4) - the typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
                          this removes the requirement to redefine it for backends which are e.g. storing descriptor sets or other 64-bits structures when building on 32-bits archs. It therefore simplify various building scripts/helpers.
                          you may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID' when passing your types to functions taking ImTextureID values, e.g. ImGui::Image().
@@ -5001,7 +5004,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
     {
         if ((g.ActiveId != 0) || (modal_window != NULL))
             io.WantCaptureKeyboard = true;
-        else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
+        else if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && io.ConfigNavCaptureKeyboard)
             io.WantCaptureKeyboard = true;
     }
     if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
@@ -10456,8 +10459,20 @@ static void ImGui::ErrorCheckNewFrameSanityChecks()
     if (g.IO.ConfigErrorRecovery)
         IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL);
 
-    // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+    // Remap legacy names
+    if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)
+    {
+        g.IO.ConfigNavMoveSetMousePos = true;
+        g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavEnableSetMousePos;
+    }
+    if (g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)
+    {
+        g.IO.ConfigNavCaptureKeyboard = false;
+        g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard;
+    }
+
+    // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024)
     if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl))
         g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); };
     if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl))
@@ -12168,7 +12183,7 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
 
         ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
         ImRect r_avoid;
-        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
+        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !g.IO.ConfigNavMoveSetMousePos)
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
         else
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
@@ -12973,7 +12988,7 @@ static void ImGui::NavUpdate()
 
     // Update mouse position if requested
     // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
-    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
+    if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
         TeleportMousePos(NavCalcPreferredRefPos());
 
     // [DEBUG]
diff --git a/imgui.h b/imgui.h
index d18879ce1..c2aa54420 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.4 WIP"
-#define IMGUI_VERSION_NUM   19133
+#define IMGUI_VERSION_NUM   19134
 #define IMGUI_HAS_TABLE
 
 /*
@@ -1597,8 +1597,6 @@ enum ImGuiConfigFlags_
     ImGuiConfigFlags_None                   = 0,
     ImGuiConfigFlags_NavEnableKeyboard      = 1 << 0,   // Master keyboard navigation enable flag. Enable full Tabbing + directional arrows + space/enter to activate.
     ImGuiConfigFlags_NavEnableGamepad       = 1 << 1,   // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad.
-    ImGuiConfigFlags_NavEnableSetMousePos   = 1 << 2,   // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth.
-    ImGuiConfigFlags_NavNoCaptureKeyboard   = 1 << 3,   // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set.
     ImGuiConfigFlags_NoMouse                = 1 << 4,   // Instruct dear imgui to disable mouse inputs and interactions.
     ImGuiConfigFlags_NoMouseCursorChange    = 1 << 5,   // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead.
     ImGuiConfigFlags_NoKeyboard             = 1 << 6,   // Instruct dear imgui to disable keyboard inputs and interactions. This is done by ignoring keyboard events and clearing existing states.
@@ -1606,6 +1604,11 @@ enum ImGuiConfigFlags_
     // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui)
     ImGuiConfigFlags_IsSRGB                 = 1 << 20,  // Application is SRGB-aware.
     ImGuiConfigFlags_IsTouchScreen          = 1 << 21,  // Application is using a touch screen instead of a mouse.
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+    ImGuiConfigFlags_NavEnableSetMousePos   = 1 << 2,   // [moved/renamed in 1.91.4] -> use bool io.ConfigNavMoveSetMousePos
+    ImGuiConfigFlags_NavNoCaptureKeyboard   = 1 << 3,   // [moved/renamed in 1.91.4] -> use bool io.ConfigNavCaptureKeyboard
+#endif
 };
 
 // Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend.
@@ -1614,7 +1617,7 @@ enum ImGuiBackendFlags_
     ImGuiBackendFlags_None                  = 0,
     ImGuiBackendFlags_HasGamepad            = 1 << 0,   // Backend Platform supports gamepad and currently has one connected.
     ImGuiBackendFlags_HasMouseCursors       = 1 << 1,   // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape.
-    ImGuiBackendFlags_HasSetMousePos        = 1 << 2,   // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set).
+    ImGuiBackendFlags_HasSetMousePos        = 1 << 2,   // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set).
     ImGuiBackendFlags_RendererHasVtxOffset  = 1 << 3,   // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices.
 };
 
@@ -2242,17 +2245,19 @@ struct ImGuiIO
 
     // Miscellaneous options
     // (you can visualize and interact with all options in 'Demo->Configuration')
-    bool        MouseDrawCursor;                // = false          // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
-    bool        ConfigMacOSXBehaviors;          // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
-    bool        ConfigNavSwapGamepadButtons;    // = false          // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
-    bool        ConfigInputTrickleEventQueue;   // = true           // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.
-    bool        ConfigInputTextCursorBlink;     // = true           // Enable blinking cursor (optional as some users consider it to be distracting).
-    bool        ConfigInputTextEnterKeepActive; // = false          // [BETA] Pressing Enter will keep item active and select contents (single-line only).
-    bool        ConfigDragClickToInputText;     // = false          // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
-    bool        ConfigWindowsResizeFromEdges;   // = true           // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
-    bool        ConfigWindowsMoveFromTitleBarOnly; // = false       // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.
-    bool        ConfigScrollbarScrollByPage;    // = true           // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location.
-    float       ConfigMemoryCompactTimer;       // = 60.0f          // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
+    bool        MouseDrawCursor;                    // = false      // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
+    bool        ConfigMacOSXBehaviors;              // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
+    bool        ConfigNavSwapGamepadButtons;        // = false      // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
+    bool        ConfigNavMoveSetMousePos;           // = false      // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. 
+    bool        ConfigNavCaptureKeyboard;           // = true       // Sets io.WantCaptureKeyboard when io.NavActive is set.
+    bool        ConfigInputTrickleEventQueue;       // = true       // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.
+    bool        ConfigInputTextCursorBlink;         // = true       // Enable blinking cursor (optional as some users consider it to be distracting).
+    bool        ConfigInputTextEnterKeepActive;     // = false      // [BETA] Pressing Enter will keep item active and select contents (single-line only).
+    bool        ConfigDragClickToInputText;         // = false      // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
+    bool        ConfigWindowsResizeFromEdges;       // = true       // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
+    bool        ConfigWindowsMoveFromTitleBarOnly;  // = false      // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.
+    bool        ConfigScrollbarScrollByPage;        // = true       // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location.
+    float       ConfigMemoryCompactTimer;           // = 60.0f      // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
 
     // Inputs Behaviors
     // (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle)
@@ -2358,7 +2363,7 @@ struct ImGuiIO
     bool        WantCaptureMouse;                   // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.).
     bool        WantCaptureKeyboard;                // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.).
     bool        WantTextInput;                      // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
-    bool        WantSetMousePos;                    // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled.
+    bool        WantSetMousePos;                    // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when io.ConfigNavMoveSetMousePos is enabled.
     bool        WantSaveIniSettings;                // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving!
     bool        NavActive;                          // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.
     bool        NavVisible;                         // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events).
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index a85e28e54..1cf4b5eb6 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -501,8 +501,6 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::SameLine(); HelpMarker("Enable keyboard controls.");
             ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad",     &io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad);
             ImGui::SameLine(); HelpMarker("Enable gamepad controls. Require backend to set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details.");
-            ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", &io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos);
-            ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos.");
             ImGui::CheckboxFlags("io.ConfigFlags: NoMouse",              &io.ConfigFlags, ImGuiConfigFlags_NoMouse);
             ImGui::SameLine(); HelpMarker("Instruct dear imgui to disable mouse inputs and interactions.");
 
@@ -529,6 +527,12 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
             ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).");
 
+            ImGui::SeparatorText("Navigation");
+            ImGui::Checkbox("io.ConfigNavSwapGamepadButtons", &io.ConfigNavSwapGamepadButtons);
+            ImGui::Checkbox("io.ConfigNavMoveSetMousePos", &io.ConfigNavMoveSetMousePos);
+            ImGui::SameLine(); HelpMarker("Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult");
+            ImGui::Checkbox("io.ConfigNavCaptureKeyboard", &io.ConfigNavCaptureKeyboard);
+
             ImGui::SeparatorText("Widgets");
             ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink);
             ImGui::SameLine(); HelpMarker("Enable blinking cursor (optional as some users consider it to be distracting).");
@@ -7753,12 +7757,12 @@ void ImGui::ShowAboutWindow(bool* p_open)
         ImGui::Text("io.ConfigFlags: 0x%08X", io.ConfigFlags);
         if (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)        ImGui::Text(" NavEnableKeyboard");
         if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad)         ImGui::Text(" NavEnableGamepad");
-        if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)     ImGui::Text(" NavEnableSetMousePos");
-        if (io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)     ImGui::Text(" NavNoCaptureKeyboard");
         if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)                  ImGui::Text(" NoMouse");
         if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)      ImGui::Text(" NoMouseCursorChange");
         if (io.MouseDrawCursor)                                         ImGui::Text("io.MouseDrawCursor");
         if (io.ConfigMacOSXBehaviors)                                   ImGui::Text("io.ConfigMacOSXBehaviors");
+        if (io.ConfigNavMoveSetMousePos)                                ImGui::Text("io.ConfigNavMoveSetMousePos");
+        if (io.ConfigNavCaptureKeyboard)                                ImGui::Text("io.ConfigNavCaptureKeyboard");
         if (io.ConfigInputTextCursorBlink)                              ImGui::Text("io.ConfigInputTextCursorBlink");
         if (io.ConfigWindowsResizeFromEdges)                            ImGui::Text("io.ConfigWindowsResizeFromEdges");
         if (io.ConfigWindowsMoveFromTitleBarOnly)                       ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly");
diff --git a/imgui_internal.h b/imgui_internal.h
index 5722291af..68593e8f4 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2143,7 +2143,7 @@ struct ImGuiContext
     ImGuiInputSource        NavInputSource;                     // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse
     ImGuiSelectionUserData  NavLastValidSelectionUserData;      // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data.
     bool                    NavIdIsAlive;                       // Nav widget has been seen this frame ~~ NavRectRel is valid
-    bool                    NavMousePosDirty;                   // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default)
+    bool                    NavMousePosDirty;                   // When set we will update mouse position if io.ConfigNavMoveSetMousePos is set (not enabled by default)
     bool                    NavDisableHighlight;                // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover)
     bool                    NavDisableMouseHover;               // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again.
 

From ba5161740ea84e883cd89c775607aaf96a8159c2 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 16:52:25 +0200
Subject: [PATCH 0426/2359] Amend d885fe4, fixes default value of
 ConfigNavCaptureKeyboard. (#2517, #2009)

---
 imgui.cpp      |  2 ++
 imgui.h        | 24 ++++++++++++------------
 imgui_demo.cpp |  1 +
 3 files changed, 15 insertions(+), 12 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index fa865503c..47ea5f471 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1406,6 +1406,8 @@ ImGuiIO::ImGuiIO()
     ConfigMacOSXBehaviors = false;
 #endif
     ConfigNavSwapGamepadButtons = false;
+    ConfigNavMoveSetMousePos = false;
+    ConfigNavCaptureKeyboard = true;
     ConfigInputTrickleEventQueue = true;
     ConfigInputTextCursorBlink = true;
     ConfigInputTextEnterKeepActive = false;
diff --git a/imgui.h b/imgui.h
index c2aa54420..6a2523010 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2245,19 +2245,19 @@ struct ImGuiIO
 
     // Miscellaneous options
     // (you can visualize and interact with all options in 'Demo->Configuration')
-    bool        MouseDrawCursor;                    // = false      // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
-    bool        ConfigMacOSXBehaviors;              // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
-    bool        ConfigNavSwapGamepadButtons;        // = false      // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
-    bool        ConfigNavMoveSetMousePos;           // = false      // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. 
-    bool        ConfigNavCaptureKeyboard;           // = true       // Sets io.WantCaptureKeyboard when io.NavActive is set.
-    bool        ConfigInputTrickleEventQueue;       // = true       // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.
-    bool        ConfigInputTextCursorBlink;         // = true       // Enable blinking cursor (optional as some users consider it to be distracting).
-    bool        ConfigInputTextEnterKeepActive;     // = false      // [BETA] Pressing Enter will keep item active and select contents (single-line only).
-    bool        ConfigDragClickToInputText;         // = false      // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
-    bool        ConfigWindowsResizeFromEdges;       // = true       // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
+    bool        MouseDrawCursor;                // = false          // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
+    bool        ConfigMacOSXBehaviors;          // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
+    bool        ConfigNavSwapGamepadButtons;    // = false          // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
+    bool        ConfigNavMoveSetMousePos;       // = false          // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. 
+    bool        ConfigNavCaptureKeyboard;       // = true           // Sets io.WantCaptureKeyboard when io.NavActive is set.
+    bool        ConfigInputTrickleEventQueue;   // = true           // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.
+    bool        ConfigInputTextCursorBlink;     // = true           // Enable blinking cursor (optional as some users consider it to be distracting).
+    bool        ConfigInputTextEnterKeepActive; // = false          // [BETA] Pressing Enter will keep item active and select contents (single-line only).
+    bool        ConfigDragClickToInputText;     // = false          // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
+    bool        ConfigWindowsResizeFromEdges;   // = true           // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
     bool        ConfigWindowsMoveFromTitleBarOnly;  // = false      // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.
-    bool        ConfigScrollbarScrollByPage;        // = true       // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location.
-    float       ConfigMemoryCompactTimer;           // = 60.0f      // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
+    bool        ConfigScrollbarScrollByPage;    // = true           // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location.
+    float       ConfigMemoryCompactTimer;       // = 60.0f          // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
 
     // Inputs Behaviors
     // (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle)
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 1cf4b5eb6..9c9868aa5 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -7759,6 +7759,7 @@ void ImGui::ShowAboutWindow(bool* p_open)
         if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad)         ImGui::Text(" NavEnableGamepad");
         if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)                  ImGui::Text(" NoMouse");
         if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)      ImGui::Text(" NoMouseCursorChange");
+        if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)               ImGui::Text(" NoKeyboard");
         if (io.MouseDrawCursor)                                         ImGui::Text("io.MouseDrawCursor");
         if (io.ConfigMacOSXBehaviors)                                   ImGui::Text("io.ConfigMacOSXBehaviors");
         if (io.ConfigNavMoveSetMousePos)                                ImGui::Text("io.ConfigNavMoveSetMousePos");

From b0010389011de8c5229775b71233a79e05ec1e7f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 16:57:34 +0200
Subject: [PATCH 0427/2359] Nav: added io.ConfigNavEscapeClearFocusWindow to
 clear focused window on Escape. (#3200)

+ pressing escape to hide nav highlight doesn't clear location from when ctrl+tabbing back into same window later.
---
 docs/CHANGELOG.txt | 3 +++
 imgui.cpp          | 7 +++++--
 imgui.h            | 1 +
 imgui_demo.cpp     | 2 ++
 4 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index d67abea37..aa64698c8 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -67,6 +67,9 @@ Other changes:
   state to draw callbacks. (#6969, #5834, #7468, #3590)
 - IO: WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
 - Error Handling: turned a few more functions into recoverable errors. (#1651)
+- Nav: added io.ConfigNavEscapeClearFocusWindow to clear focused window on Escape. (#3200)
+- Nav: pressing escape to hide nav highlight doesn't clear location from when ctrl+tabbing back
+  into same window later.
 - DrawList: AddCallback() added an optional size parameter allowing to copy and
   store any amount of user data for usage by callbacks: (#6969, #4770, #7665)
   - If userdata_size == 0: we copy/store the 'userdata' argument as-is (existing behavior).
diff --git a/imgui.cpp b/imgui.cpp
index 47ea5f471..486832ec3 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1408,6 +1408,7 @@ ImGuiIO::ImGuiIO()
     ConfigNavSwapGamepadButtons = false;
     ConfigNavMoveSetMousePos = false;
     ConfigNavCaptureKeyboard = true;
+    ConfigNavEscapeClearFocusWindow = false;
     ConfigInputTrickleEventQueue = true;
     ConfigInputTextCursorBlink = true;
     ConfigInputTextEnterKeepActive = false;
@@ -13316,7 +13317,7 @@ void ImGui::NavMoveRequestApplyResult()
         NavRestoreHighlightAfterMove();
 }
 
-// Process NavCancel input (to close a popup, get back to parent, clear focus)
+// Process Escape/NavCancel input (to close a popup, get back to parent, clear focus)
 // FIXME: In order to support e.g. Escape to clear a selection we'll need:
 // - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
 // - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
@@ -13358,11 +13359,13 @@ static void ImGui::NavUpdateCancelRequest()
     {
         // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
         // FIXME-NAV: This should happen on window appearing.
-        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
+        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
             g.NavWindow->NavLastIds[0] = 0;
 
         // Clear nav focus
         g.NavId = 0;
+        if (g.IO.ConfigNavEscapeClearFocusWindow)
+            FocusWindow(NULL);
     }
 }
 
diff --git a/imgui.h b/imgui.h
index 6a2523010..7d17aede6 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2250,6 +2250,7 @@ struct ImGuiIO
     bool        ConfigNavSwapGamepadButtons;    // = false          // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
     bool        ConfigNavMoveSetMousePos;       // = false          // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. 
     bool        ConfigNavCaptureKeyboard;       // = true           // Sets io.WantCaptureKeyboard when io.NavActive is set.
+    bool        ConfigNavEscapeClearFocusWindow;// = false          // Pressing Escape (when no item is active, no popup open etc.) clears focused window + navigation id/highlight.
     bool        ConfigInputTrickleEventQueue;   // = true           // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.
     bool        ConfigInputTextCursorBlink;     // = true           // Enable blinking cursor (optional as some users consider it to be distracting).
     bool        ConfigInputTextEnterKeepActive; // = false          // [BETA] Pressing Enter will keep item active and select contents (single-line only).
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 9c9868aa5..dca674054 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -532,6 +532,8 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::Checkbox("io.ConfigNavMoveSetMousePos", &io.ConfigNavMoveSetMousePos);
             ImGui::SameLine(); HelpMarker("Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult");
             ImGui::Checkbox("io.ConfigNavCaptureKeyboard", &io.ConfigNavCaptureKeyboard);
+            ImGui::Checkbox("io.ConfigNavEscapeClearFocusWindow", &io.ConfigNavEscapeClearFocusWindow);
+            ImGui::SameLine(); HelpMarker("Pressing Escape clears focused window.");
 
             ImGui::SeparatorText("Widgets");
             ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink);

From 626d358e55e92ceaacf6c0200d32cbf9d36fe6eb Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 17:10:36 +0200
Subject: [PATCH 0428/2359] Nav: fixed Ctrl+Tab so when starting with no
 focused window it starts from the top-most window. (#3200)

---
 docs/CHANGELOG.txt |  6 ++++--
 imgui.cpp          | 15 +++++++++------
 2 files changed, 13 insertions(+), 8 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index aa64698c8..203d4d954 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -68,8 +68,10 @@ Other changes:
 - IO: WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
 - Error Handling: turned a few more functions into recoverable errors. (#1651)
 - Nav: added io.ConfigNavEscapeClearFocusWindow to clear focused window on Escape. (#3200)
-- Nav: pressing escape to hide nav highlight doesn't clear location from when ctrl+tabbing back
-  into same window later.
+- Nav: pressing escape to hide nav highlight doesn't clear location from when ctrl+tabbing 
+  back into same window later.
+- Nav: fixed Ctrl+Tab so when starting with no focused window it starts from the top-most
+  window. (#3200)
 - DrawList: AddCallback() added an optional size parameter allowing to copy and
   store any amount of user data for usage by callbacks: (#6969, #4770, #7665)
   - If userdata_size == 0: we copy/store the 'userdata' argument as-is (existing behavior).
diff --git a/imgui.cpp b/imgui.cpp
index 486832ec3..7da199c5c 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -13540,7 +13540,7 @@ static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) //
     return NULL;
 }
 
-static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
+static void NavUpdateWindowingTarget(int focus_change_dir)
 {
     ImGuiContext& g = *GImGui;
     IM_ASSERT(g.NavWindowingTarget);
@@ -13592,14 +13592,17 @@ static void ImGui::NavUpdateWindowing()
     const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
     const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None);
     const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
+    bool just_started_windowing_from_null_focus = false;
     if (start_windowing_with_gamepad || start_windowing_with_keyboard)
         if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
         {
-            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
+            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location
             g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
             g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
             g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
             g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
+            if (g.NavWindow == NULL)
+                just_started_windowing_from_null_focus = true;
 
             // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
             if (keyboard_next_window || keyboard_prev_window)
@@ -13615,9 +13618,9 @@ static void ImGui::NavUpdateWindowing()
 
         // Select window to focus
         const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
-        if (focus_change_dir != 0)
+        if (focus_change_dir != 0 && !just_started_windowing_from_null_focus)
         {
-            NavUpdateWindowingHighlightWindow(focus_change_dir);
+            NavUpdateWindowingTarget(focus_change_dir);
             g.NavWindowingHighlightAlpha = 1.0f;
         }
 
@@ -13640,8 +13643,8 @@ static void ImGui::NavUpdateWindowing()
         ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
         IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
         g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
-        if (keyboard_next_window || keyboard_prev_window)
-            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
+        if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus)
+            NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1);
         else if ((io.KeyMods & shared_mods) != shared_mods)
             apply_focus_window = g.NavWindowingTarget;
     }

From ad37b79bca2bf548c22ca2276dd209f05583e729 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 17:30:14 +0200
Subject: [PATCH 0429/2359] Nav: shallow tidying up.

---
 imgui.cpp         | 8 +++-----
 imgui_internal.h  | 2 +-
 imgui_widgets.cpp | 4 ++--
 3 files changed, 6 insertions(+), 8 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 7da199c5c..eafb7a84d 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4443,9 +4443,9 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
 
     if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
     {
-        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
+        if (g.LastItemData.ID == g.NavId && g.NavId != 0) // IsItemFocused()
             return false;
-        if (!IsItemFocused())
+        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
             return false;
 
         if (flags & ImGuiHoveredFlags_ForTooltip)
@@ -5784,9 +5784,7 @@ bool ImGui::IsItemDeactivatedAfterEdit()
 bool ImGui::IsItemFocused()
 {
     ImGuiContext& g = *GImGui;
-    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
-        return false;
-    return true;
+    return g.NavId == g.LastItemData.ID && g.NavId != 0;
 }
 
 // Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
diff --git a/imgui_internal.h b/imgui_internal.h
index 68593e8f4..99421b700 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -906,7 +906,7 @@ enum ImGuiButtonFlagsPrivate_
     ImGuiButtonFlags_DontClosePopups        = 1 << 13,  // disable automatically closing parent popup on press // [UNUSED]
     //ImGuiButtonFlags_Disabled             = 1 << 14,  // disable interactions -> use BeginDisabled() or ImGuiItemFlags_Disabled
     ImGuiButtonFlags_AlignTextBaseLine      = 1 << 15,  // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine
-    ImGuiButtonFlags_NoKeyModifiers         = 1 << 16,  // disable mouse interaction if a key modifier is held
+    ImGuiButtonFlags_NoKeyModsAllowed       = 1 << 16,  // disable mouse interaction if a key modifier is held
     ImGuiButtonFlags_NoHoldingActiveId      = 1 << 17,  // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only)
     ImGuiButtonFlags_NoNavFocus             = 1 << 18,  // don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags_NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.InFlags)
     ImGuiButtonFlags_NoHoveredOnFocus       = 1 << 19,  // don't report as hovered when nav focus is on this item
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index aac7383b1..8cdd4aa27 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -561,7 +561,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
             }
 
         // Process initial action
-        if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
+        if (!(flags & ImGuiButtonFlags_NoKeyModsAllowed) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
         {
             if (mouse_button_clicked != -1 && g.ActiveId != id)
             {
@@ -6604,7 +6604,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
     else
     {
         if (window != g.HoveredWindow || !is_mouse_x_over_arrow)
-            button_flags |= ImGuiButtonFlags_NoKeyModifiers;
+            button_flags |= ImGuiButtonFlags_NoKeyModsAllowed;
     }
 
     bool hovered, held;

From 462d167456852387dcc6c3d03f1ad502992108c0 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 17:37:36 +0200
Subject: [PATCH 0430/2359] Nav: rectangle highlight not rendered for items
 with ImGuiItemFlags_NoNav. (#8057)

Not fully honored in ItemHoverable/IsItemHovered, seems more destructive. This is mostly designed to avoid rectangle being rendered by large InvisibleButton() when ctrl+tabbing back to a window with a big one.
---
 docs/CHANGELOG.txt | 2 ++
 imgui.cpp          | 2 ++
 2 files changed, 4 insertions(+)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 203d4d954..6a062c459 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -72,6 +72,8 @@ Other changes:
   back into same window later.
 - Nav: fixed Ctrl+Tab so when starting with no focused window it starts from the top-most
   window. (#3200)
+- Nav: rectangle highlight not rendered for items with ImGuiItemFlags_NoNav. Can be relevant
+  when e.g activating the item with mouse, then ctrl+tabbing back and forth. 
 - DrawList: AddCallback() added an optional size parameter allowing to copy and
   store any amount of user data for usage by callbacks: (#6969, #4770, #7665)
   - If userdata_size == 0: we copy/store the 'userdata' argument as-is (existing behavior).
diff --git a/imgui.cpp b/imgui.cpp
index eafb7a84d..0ca2f4ab1 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3701,6 +3701,8 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl
         return;
     if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
         return;
+    if (id == g.LastItemData.ID && (g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
+        return;
     ImGuiWindow* window = g.CurrentWindow;
     if (window->DC.NavHideHighlightOneFrame)
         return;

From 97da66209cffd84a6959bced872da06a91213402 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 19:03:33 +0200
Subject: [PATCH 0431/2359] Internals: removing ImGuiButtonFlags_Repeat (in
 favor of ImGuiItemFlags_ButtonRepeat), ImGuiButtonFlags_DontClosePopups
 (unused)

---
 imgui_internal.h  |  4 ++--
 imgui_widgets.cpp | 15 ++++++++-------
 2 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index 99421b700..5e378d669 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -900,10 +900,10 @@ enum ImGuiButtonFlagsPrivate_
     ImGuiButtonFlags_PressedOnRelease       = 1 << 7,   // return true on release (default requires click+release)
     ImGuiButtonFlags_PressedOnDoubleClick   = 1 << 8,   // return true on double-click (default requires click+release)
     ImGuiButtonFlags_PressedOnDragDropHold  = 1 << 9,   // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers)
-    ImGuiButtonFlags_Repeat                 = 1 << 10,  // hold to repeat
+    //ImGuiButtonFlags_Repeat               = 1 << 10,  // hold to repeat
     ImGuiButtonFlags_FlattenChildren        = 1 << 11,  // allow interactions even if a child window is overlapping
     ImGuiButtonFlags_AllowOverlap           = 1 << 12,  // require previous frame HoveredId to either match id or be null before being usable.
-    ImGuiButtonFlags_DontClosePopups        = 1 << 13,  // disable automatically closing parent popup on press // [UNUSED]
+    //ImGuiButtonFlags_DontClosePopups      = 1 << 13,  // disable automatically closing parent popup on press
     //ImGuiButtonFlags_Disabled             = 1 << 14,  // disable interactions -> use BeginDisabled() or ImGuiItemFlags_Disabled
     ImGuiButtonFlags_AlignTextBaseLine      = 1 << 15,  // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine
     ImGuiButtonFlags_NoKeyModsAllowed       = 1 << 16,  // disable mouse interaction if a key modifier is held
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 8cdd4aa27..2a7b1e9a8 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -508,8 +508,6 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
     ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
     if (flags & ImGuiButtonFlags_AllowOverlap)
         item_flags |= ImGuiItemFlags_AllowOverlap;
-    if (flags & ImGuiButtonFlags_Repeat)
-        item_flags |= ImGuiItemFlags_ButtonRepeat;
 
     ImGuiWindow* backup_hovered_window = g.HoveredWindow;
     const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindow == window;
@@ -3689,21 +3687,22 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data
         // Step buttons
         const ImVec2 backup_frame_padding = style.FramePadding;
         style.FramePadding.x = style.FramePadding.y;
-        ImGuiButtonFlags button_flags = ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups;
         if (flags & ImGuiInputTextFlags_ReadOnly)
             BeginDisabled();
+        PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
         SameLine(0, style.ItemInnerSpacing.x);
-        if (ButtonEx("-", ImVec2(button_size, button_size), button_flags))
+        if (ButtonEx("-", ImVec2(button_size, button_size)))
         {
             DataTypeApplyOp(data_type, '-', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
             value_changed = true;
         }
         SameLine(0, style.ItemInnerSpacing.x);
-        if (ButtonEx("+", ImVec2(button_size, button_size), button_flags))
+        if (ButtonEx("+", ImVec2(button_size, button_size)))
         {
             DataTypeApplyOp(data_type, '+', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
             value_changed = true;
         }
+        PopItemFlag();
         if (flags & ImGuiInputTextFlags_ReadOnly)
             EndDisabled();
 
@@ -9753,17 +9752,19 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)
 
     PushStyleColor(ImGuiCol_Text, arrow_col);
     PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
+    PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
     const float backup_repeat_delay = g.IO.KeyRepeatDelay;
     const float backup_repeat_rate = g.IO.KeyRepeatRate;
     g.IO.KeyRepeatDelay = 0.250f;
     g.IO.KeyRepeatRate = 0.200f;
     float x = ImMax(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.x - scrolling_buttons_width);
     window->DC.CursorPos = ImVec2(x, tab_bar->BarRect.Min.y);
-    if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))
+    if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick))
         select_dir = -1;
     window->DC.CursorPos = ImVec2(x + arrow_button_size.x, tab_bar->BarRect.Min.y);
-    if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))
+    if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick))
         select_dir = +1;
+    PopItemFlag();
     PopStyleColor(2);
     g.IO.KeyRepeatRate = backup_repeat_rate;
     g.IO.KeyRepeatDelay = backup_repeat_delay;

From 42f47590f983f489991f6ebfb72d2b32858cc270 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 19:13:04 +0200
Subject: [PATCH 0432/2359] Fixed ad37b79 breaking
 IsItemHovered()->IsItemFocused() passthrough for navigation.

+ Backends: comments.
---
 backends/imgui_impl_dx12.cpp   | 1 +
 backends/imgui_impl_vulkan.cpp | 1 +
 imgui.cpp                      | 2 +-
 3 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index e9345013c..be117b6c1 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -18,6 +18,7 @@
 // (minor and older changes stripped away, please see git history for details)
 //  2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
+//  2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
 //  2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
 //  2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
 //  2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index a68f862b1..4e4e332fc 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -28,6 +28,7 @@
 // (minor and older changes stripped away, please see git history for details)
 //  2024-10-07: Vulkan: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: Vulkan: Expose selected render state in ImGui_ImplVulkan_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
+//  2024-10-07: Vulkan: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
 //  2024-04-19: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define (you can also use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().)
 //  2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering.
 //  2024-02-12: *BREAKING CHANGE*: Dynamic rendering now require filling PipelineRenderingCreateInfo structure.
diff --git a/imgui.cpp b/imgui.cpp
index 0ca2f4ab1..1cdf4383a 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4445,7 +4445,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
 
     if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
     {
-        if (g.LastItemData.ID == g.NavId && g.NavId != 0) // IsItemFocused()
+        if (!IsItemFocused())
             return false;
         if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
             return false;

From 50de550ecddf8569e4aaa5f45ab803da92fc5921 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 14 Oct 2024 19:34:23 +0200
Subject: [PATCH 0433/2359] Tooltips: fixed incorrect tooltip positioning when
 using keyboard/gamepad navigation (1.91.3 regression). (#8036)

Regression in 1.91.3 commit 5109a77.
---
 docs/CHANGELOG.txt |  2 ++
 imgui.cpp          | 24 ++++++++++++++++++++----
 2 files changed, 22 insertions(+), 4 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 6a062c459..0ade98733 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -74,6 +74,8 @@ Other changes:
   window. (#3200)
 - Nav: rectangle highlight not rendered for items with ImGuiItemFlags_NoNav. Can be relevant
   when e.g activating the item with mouse, then ctrl+tabbing back and forth. 
+- Tooltips: fixed incorrect tooltip positioning when using keyboard/gamepad navigation 
+  (1.91.3 regression). (#8036)
 - DrawList: AddCallback() added an optional size parameter allowing to copy and
   store any amount of user data for usage by callbacks: (#6969, #4770, #7665)
   - If userdata_size == 0: we copy/store the 'userdata' argument as-is (existing behavior).
diff --git a/imgui.cpp b/imgui.cpp
index 1cdf4383a..3ce5e90db 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1199,6 +1199,7 @@ static bool             NavScoreItem(ImGuiNavItemData* result);
 static void             NavApplyItemToResult(ImGuiNavItemData* result);
 static void             NavProcessItem();
 static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
+static ImGuiInputSource NavCalcPreferredRefPosSource();
 static ImVec2           NavCalcPreferredRefPos();
 static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
 static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
@@ -12177,14 +12178,14 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
         const float scale = g.Style.MouseCursorScale;
         const ImVec2 ref_pos = NavCalcPreferredRefPos();
 
-        if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen)
+        if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse)
         {
-            ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
+            ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size);
             if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size)))
                 return tooltip_pos;
         }
 
-        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
+        ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
         ImRect r_avoid;
         if (!g.NavDisableHighlight && g.NavDisableMouseHover && !g.IO.ConfigNavMoveSetMousePos)
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
@@ -12779,7 +12780,7 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
     }
 }
 
-static ImVec2 ImGui::NavCalcPreferredRefPos()
+static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource()
 {
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = g.NavWindow;
@@ -12787,6 +12788,21 @@ static ImVec2 ImGui::NavCalcPreferredRefPos()
 
     // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
     if ((g.NavDisableHighlight || !g.NavDisableMouseHover || !window) && !activated_shortcut)
+        return ImGuiInputSource_Mouse;
+    else
+        return ImGuiInputSource_Keyboard; // or Nav in general
+}
+
+static ImVec2 ImGui::NavCalcPreferredRefPos()
+{
+    ImGuiContext& g = *GImGui;
+    ImGuiWindow* window = g.NavWindow;
+    ImGuiInputSource source = NavCalcPreferredRefPosSource();
+
+    const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
+
+    // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
+    if (source == ImGuiInputSource_Mouse)
     {
         // Mouse (we need a fallback in case the mouse becomes invalid after being used)
         // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.

From 49a9eee33f21bb4f67ffeaad7559a349d1687704 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 15 Oct 2024 10:41:34 +0200
Subject: [PATCH 0434/2359] Commented out obsolete internals's
 SetItemUsingMouseWheel() (#2891), TreeNodeBehaviorIsOpen() (#4814, #5423,
 #282, #2958, #924)

+ Removed obsolete header checks for IMGUI_DISABLE_METRICS_WINDOW.
---
 imgui.h          | 9 +++------
 imgui_internal.h | 5 ++---
 2 files changed, 5 insertions(+), 9 deletions(-)

diff --git a/imgui.h b/imgui.h
index 7d17aede6..2f9f18c2b 100644
--- a/imgui.h
+++ b/imgui.h
@@ -3616,8 +3616,8 @@ namespace ImGui
     //-- OBSOLETED in 1.89 (from August 2022)
     //IMGUI_API bool      ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // --> Use new ImageButton() signature (explicit item id, regular FramePadding). Refer to code in 1.91 if you want to grab a copy of this version.
     //-- OBSOLETED in 1.88 (from May 2022)
-    //static inline void  CaptureKeyboardFromApp(bool want_capture_keyboard = true)     { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value.
-    //static inline void  CaptureMouseFromApp(bool want_capture_mouse = true)           { SetNextFrameWantCaptureMouse(want_capture_mouse); }       // Renamed as name was misleading + removed default value.
+    //static inline void  CaptureKeyboardFromApp(bool want_capture_keyboard = true)                   { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value.
+    //static inline void  CaptureMouseFromApp(bool want_capture_mouse = true)                         { SetNextFrameWantCaptureMouse(want_capture_mouse); }       // Renamed as name was misleading + removed default value.
     //-- OBSOLETED in 1.86 (from November 2021)
     //IMGUI_API void      CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Code removed, see 1.90 for last version of the code. Calculate range of visible items for large list of evenly sized items. Prefer using ImGuiListClipper.
     //-- OBSOLETED in 1.85 (from August 2021)
@@ -3700,10 +3700,7 @@ namespace ImGui
 #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
 
 // RENAMED IMGUI_DISABLE_METRICS_WINDOW > IMGUI_DISABLE_DEBUG_TOOLS in 1.88 (from June 2022)
-#if defined(IMGUI_DISABLE_METRICS_WINDOW) && !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS)
-#define IMGUI_DISABLE_DEBUG_TOOLS
-#endif
-#if defined(IMGUI_DISABLE_METRICS_WINDOW) && defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS)
+#ifdef IMGUI_DISABLE_METRICS_WINDOW
 #error IMGUI_DISABLE_METRICS_WINDOW was renamed to IMGUI_DISABLE_DEBUG_TOOLS, please use new name.
 #endif
 
diff --git a/imgui_internal.h b/imgui_internal.h
index 5e378d669..f96e7091d 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -3478,9 +3478,8 @@ namespace ImGui
 
     // Obsolete functions
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-    inline void     SetItemUsingMouseWheel()                                            { SetItemKeyOwner(ImGuiKey_MouseWheelY); }      // Changed in 1.89
-    inline bool     TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0)    { return TreeNodeUpdateNextOpen(id, flags); }   // Renamed in 1.89
-
+    //inline void   SetItemUsingMouseWheel()                                            { SetItemKeyOwner(ImGuiKey_MouseWheelY); }      // Changed in 1.89
+    //inline bool   TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0)    { return TreeNodeUpdateNextOpen(id, flags); }   // Renamed in 1.89
     //inline bool   IsKeyPressedMap(ImGuiKey key, bool repeat = true)                   { IM_ASSERT(IsNamedKey(key)); return IsKeyPressed(key, repeat); } // Removed in 1.87: Mapping from named key is always identity!
 
     // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister():

From 971d243a872fbc50a654ed18d31a58f9152a294b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?DOTTEL=20Ga=C3=ABl?= 
Date: Tue, 15 Oct 2024 11:35:34 +0200
Subject: [PATCH 0435/2359] Fixed typo (#8063)

---
 docs/FAQ.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/docs/FAQ.md b/docs/FAQ.md
index 38600fe47..8dde1967b 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -405,7 +405,7 @@ DirectX9:
 ```
 ```cpp
 DirectX11:
-- ImTextureID should contain a 'ID3D11ShaderResourceView*' (poiter)
+- ImTextureID should contain a 'ID3D11ShaderResourceView*' (pointer)
 - See ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp
 ```
 ```cpp

From 67e5f3505d481519cf038aa9d054c5d0805a768d Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 16 Oct 2024 19:55:50 +0200
Subject: [PATCH 0436/2359] InvisibleButton: disable navigation properly +
 added ImGuiButtonFlags_EnableNav to enable navigation. (#8057)

---
 docs/CHANGELOG.txt | 5 ++++-
 imgui.h            | 2 +-
 imgui_internal.h   | 2 +-
 imgui_widgets.cpp  | 3 ++-
 4 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 0ade98733..27b7dd780 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -73,7 +73,10 @@ Other changes:
 - Nav: fixed Ctrl+Tab so when starting with no focused window it starts from the top-most
   window. (#3200)
 - Nav: rectangle highlight not rendered for items with ImGuiItemFlags_NoNav. Can be relevant
-  when e.g activating the item with mouse, then ctrl+tabbing back and forth. 
+  when e.g activating the item with mouse, then Ctrl+Tabbing back and forth. 
+- InvisibleButton, Nav: fixed an issue when InvisibleButton() would be navigable into but
+  not display navigation highlight. Properly navigation on it by default. (#8057)
+- InvisibleButton: added ImGuiButtonFlags_EnableNav to enable navigation. (#8057)
 - Tooltips: fixed incorrect tooltip positioning when using keyboard/gamepad navigation 
   (1.91.3 regression). (#8036)
 - DrawList: AddCallback() added an optional size parameter allowing to copy and
diff --git a/imgui.h b/imgui.h
index 2f9f18c2b..ec5d572b9 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1744,7 +1744,7 @@ enum ImGuiButtonFlags_
     ImGuiButtonFlags_MouseButtonRight       = 1 << 1,   // React on right mouse button
     ImGuiButtonFlags_MouseButtonMiddle      = 1 << 2,   // React on center mouse button
     ImGuiButtonFlags_MouseButtonMask_       = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, // [Internal]
-    //ImGuiButtonFlags_MouseButtonDefault_  = ImGuiButtonFlags_MouseButtonLeft,
+    ImGuiButtonFlags_EnableNav              = 1 << 3,   // InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default.
 };
 
 // Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton()
diff --git a/imgui_internal.h b/imgui_internal.h
index f96e7091d..6e207d60e 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -947,7 +947,7 @@ enum ImGuiSelectableFlagsPrivate_
 enum ImGuiTreeNodeFlagsPrivate_
 {
     ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader()
-    ImGuiTreeNodeFlags_UpsideDownArrow            = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, but reversed trees (#6517)
+    ImGuiTreeNodeFlags_UpsideDownArrow            = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517)
     ImGuiTreeNodeFlags_OpenOnMask_                = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow,
 };
 
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 2a7b1e9a8..1cd18c359 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -785,11 +785,12 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiBut
     ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
     const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
     ItemSize(size);
-    if (!ItemAdd(bb, id))
+    if (!ItemAdd(bb, id, NULL, (flags & ImGuiButtonFlags_EnableNav) ? ImGuiItemFlags_None : ImGuiItemFlags_NoNav))
         return false;
 
     bool hovered, held;
     bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
+    RenderNavHighlight(bb, id);
 
     IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);
     return pressed;

From 83ecc846dc40645348d808c7119d1528e76c59a9 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 16 Oct 2024 20:23:33 +0200
Subject: [PATCH 0437/2359] Disabled: clicking a disabled item focuses parent
 window. (#8064)

---
 docs/CHANGELOG.txt |  1 +
 imgui.h            |  2 +-
 imgui_widgets.cpp  | 19 ++++++++++++++++---
 3 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 27b7dd780..147e9f067 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -74,6 +74,7 @@ Other changes:
   window. (#3200)
 - Nav: rectangle highlight not rendered for items with ImGuiItemFlags_NoNav. Can be relevant
   when e.g activating the item with mouse, then Ctrl+Tabbing back and forth. 
+- Disabled: clicking a disabled item focuses parent window. (#8064) 
 - InvisibleButton, Nav: fixed an issue when InvisibleButton() would be navigable into but
   not display navigation highlight. Properly navigation on it by default. (#8057)
 - InvisibleButton: added ImGuiButtonFlags_EnableNav to enable navigation. (#8057)
diff --git a/imgui.h b/imgui.h
index ec5d572b9..ef0c59a9d 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.4 WIP"
-#define IMGUI_VERSION_NUM   19134
+#define IMGUI_VERSION_NUM   19135
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 1cd18c359..247fce39c 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -542,7 +542,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
 
     // Mouse handling
     const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id;
-    if (hovered)
+    const bool hovered_disabled = (g.HoveredId == id && g.HoveredIdIsDisabled);
+    if (hovered || hovered_disabled)
     {
         IM_ASSERT(id != 0); // Lazily check inside rare path.
 
@@ -559,7 +560,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
             }
 
         // Process initial action
-        if (!(flags & ImGuiButtonFlags_NoKeyModsAllowed) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
+        const bool mods_ok = !(flags & ImGuiButtonFlags_NoKeyModsAllowed) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt);
+        if (mods_ok && !hovered_disabled)
         {
             if (mouse_button_clicked != -1 && g.ActiveId != id)
             {
@@ -606,7 +608,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
                     if (!has_repeated_at_least_once)
                         pressed = true;
                     if (!(flags & ImGuiButtonFlags_NoNavFocus))
-                        SetFocusID(id, window);
+                        SetFocusID(id, window); // FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why.
                     ClearActiveID();
                 }
             }
@@ -617,6 +619,17 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
                 if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, ImGuiInputFlags_Repeat, test_owner_id))
                     pressed = true;
         }
+        else if (mods_ok && hovered_disabled)
+        {
+            if (mouse_button_clicked != -1 && g.ActiveId != id)
+            {
+                // Disabled path still focus
+                // FIXME-NAV: Could somehow call SetNavID() with a null ID but mouse pos as NavRectRel so nav may be resumed?
+                // Will do it once we do it for regular click on window-void.
+                if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick))
+                    FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild);
+            }
+        }
 
         if (pressed)
             g.NavDisableHighlight = true;

From 04d9a0455702b376eec7074885bb722ad27171c0 Mon Sep 17 00:00:00 2001
From: Pascal Thomet 
Date: Thu, 8 Aug 2024 12:21:01 +0200
Subject: [PATCH 0438/2359] imgui_freetype: Added support for plutosvg to
 render OpenType SVG fonts.  (#7927, #7187 + #6591, #6607)

See #7927 for details.
---
 docs/CHANGELOG.txt               |  4 ++++
 imconfig.h                       |  9 ++++++---
 misc/freetype/README.md          | 26 ++++++++++++++++++++++----
 misc/freetype/imgui_freetype.cpp | 24 +++++++++++++++++++-----
 misc/freetype/imgui_freetype.h   |  7 +++++++
 5 files changed, 58 insertions(+), 12 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 147e9f067..5d61daa54 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -93,6 +93,10 @@ Other changes:
   preventing use of external shortcuts not guarded by an ActiveId check. (#8048) [@geertbleyen]
 - InputText: ensure mouse cursor shape is set regardless of whether keyboard mode is 
   enabled or not. (#6417)
+- imgui_freetype: Added support for plutosvg (as an alternative to lunasvg) to render 
+  OpenType SVG fonts. Requires defining IMGUI_ENABLE_FREETYPE_PLUTOSVG along with IMGUI_ENABLE_FREETYPE.
+  Providing headers/librairies for plutosvg + plutovg is up to you (see #7927 for help).
+  (#7927, #7187, #6591, #6607) [@pthom]
 - Backends: DX11, DX12, SDLRenderer2/3. Vulkan, WGPU: expose selected state in
   ImGui_ImplXXXX_RenderState structures during render loop. (#6969, #5834, #7468, #3590)
 - Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan, WGPU: Changed default texture sampler
diff --git a/imconfig.h b/imconfig.h
index b8d55842b..63d6ba081 100644
--- a/imconfig.h
+++ b/imconfig.h
@@ -83,10 +83,13 @@
 // On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
 //#define IMGUI_ENABLE_FREETYPE
 
-//---- Use FreeType+lunasvg library to render OpenType SVG fonts (SVGinOT)
-// Requires lunasvg headers to be available in the include path + program to be linked with the lunasvg library (not provided).
+//---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT)
 // Only works in combination with IMGUI_ENABLE_FREETYPE.
-// (implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
+// - lunasvg is currently easier to acquire/install, as e.g. it is part of vcpkg.
+// - plutosvg will support more fonts and may load them faster. It currently requires to be built manually but it is fairly easy. See misc/freetype/README for instructions.
+// - Both require headers to be available in the include path + program to be linked with the library code (not provided).
+// - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
+//#define IMGUI_ENABLE_FREETYPE_PLUTOSVG
 //#define IMGUI_ENABLE_FREETYPE_LUNASVG
 
 //---- Use stb_truetype to build and rasterize the font atlas (default)
diff --git a/misc/freetype/README.md b/misc/freetype/README.md
index 275a53866..3955b080e 100644
--- a/misc/freetype/README.md
+++ b/misc/freetype/README.md
@@ -38,7 +38,25 @@ You can use the `ImGuiFreeTypeBuilderFlags_LoadColor` flag to load certain color
 
 ### Using OpenType SVG fonts (SVGinOT)
 - *SVG in Open Type* is a standard by Adobe and Mozilla for color OpenType and Open Font Format fonts. It allows font creators to embed complete SVG files within a font enabling full color and even animations.
-- Popular fonts such as [twemoji](https://github.com/13rac1/twemoji-color-font) and fonts made with [scfbuild](https://github.com/13rac1/scfbuild) is SVGinOT
-- Requires: [lunasvg](https://github.com/sammycage/lunasvg) v2.3.2 and above
-    1. Add `#define IMGUI_ENABLE_FREETYPE_LUNASVG` in your `imconfig.h`.
-    2. Get latest lunasvg binaries or build yourself. Under Windows you may use vcpkg with: `vcpkg install lunasvg --triplet=x64-windows`.
+- Popular fonts such as [twemoji](https://github.com/13rac1/twemoji-color-font) and fonts made with [scfbuild](https://github.com/13rac1/scfbuild) is SVGinOT 
+- Two alternatives are possible to render SVG fonts: use "lunasvg" or "plutosvg". plutosvg will support some more fonts (e.g. NotoColorEmoji-Regular) and may load them faster.
+
+#### Using lunasvg
+Requires: [lunasvg](https://github.com/sammycage/lunasvg) v2.3.2 and above
+- Add `#define IMGUI_ENABLE_FREETYPE_LUNASVG` in your `imconfig.h`.
+- Get latest lunasvg binaries or build yourself. Under Windows you may use vcpkg with: `vcpkg install lunasvg --triplet=x64-windows`.
+
+#### Using plutosvg (and plutovg)
+- Add `#define IMGUI_ENABLE_FREETYPE_PLUTOSVG` in your `imconfig.h`.
+- Compile and link with plutosvg *and* plutovg (which is required by plutosvg)
+
+_Compilation hints for plutovg_
+- Compile all source files in `plutovg/source/*.c`
+- Add include directory: `plutovg/include` + `plutovg/stb`
+
+_Compilation hints for plutosvg_
+- Compile `plutosvg/source/plutosvg.c`
+- Add include directory: `plutosvg/source`
+- Add define: `PLUTOSVG_HAS_FREETYPE`
+- Link with: plutovg, freetype
+
diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp
index d97605b25..646a3b14e 100644
--- a/misc/freetype/imgui_freetype.cpp
+++ b/misc/freetype/imgui_freetype.cpp
@@ -6,8 +6,9 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927)
 //  2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics.
-//  2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG' (#6591)
+//  2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG'. (#6591)
 //  2023/01/04: fixed a packing issue which in some occurrences would prevent large amount of glyphs from being packed correctly.
 //  2021/08/23: fixed crash when FT_Render_Glyph() fails to render a glyph and returns NULL.
 //  2021/03/05: added ImGuiFreeTypeBuilderFlags_Bitmap to load bitmap glyphs.
@@ -45,12 +46,21 @@
 #include FT_GLYPH_H             // 
 #include FT_SYNTHESIS_H         // 
 
-#ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
+// Handle LunaSVG and PlutoSVG
+#if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) && defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
+#error "Cannot enable both IMGUI_ENABLE_FREETYPE_LUNASVG and IMGUI_ENABLE_FREETYPE_PLUTOSVG"
+#endif
+#ifdef  IMGUI_ENABLE_FREETYPE_LUNASVG
 #include FT_OTSVG_H             // 
 #include FT_BBOX_H              // 
 #include 
+#endif
+#ifdef  IMGUI_ENABLE_FREETYPE_PLUTOSVG
+#include 
+#endif
+#if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined (IMGUI_ENABLE_FREETYPE_PLUTOSVG)
 #if !((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
-#error IMGUI_ENABLE_FREETYPE_LUNASVG requires FreeType version >= 2.12
+#error IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG requires FreeType version >= 2.12
 #endif
 #endif
 
@@ -269,11 +279,11 @@ namespace
 
         // Need an outline for this to work
         FT_GlyphSlot slot = Face->glyph;
-#ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
+#if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
         IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG);
 #else
 #if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
-        IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font");
+        IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font");
 #endif
         IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP);
 #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
@@ -810,6 +820,10 @@ static bool ImFontAtlasBuildWithFreeType(ImFontAtlas* atlas)
     SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot };
     FT_Property_Set(ft_library, "ot-svg", "svg-hooks", &hooks);
 #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
+#ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
+    // With plutosvg, use provided hooks
+    FT_Property_Set(ft_library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks());
+#endif // IMGUI_ENABLE_FREETYPE_PLUTOSVG
 
     bool ret = ImFontAtlasBuildWithFreeTypeEx(ft_library, atlas, atlas->FontBuilderFlags);
     FT_Done_Library(ft_library);
diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h
index b4e1d4893..6572b1547 100644
--- a/misc/freetype/imgui_freetype.h
+++ b/misc/freetype/imgui_freetype.h
@@ -5,6 +5,13 @@
 #include "imgui.h"      // IMGUI_API
 #ifndef IMGUI_DISABLE
 
+// Usage:
+// - Add '#define IMGUI_ENABLE_FREETYPE' in your imconfig to enable support for imgui_freetype in imgui.
+
+// Optional support for OpenType SVG fonts:
+// - Add '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG' to use plutosvg (not provided). See #7927.
+// - Add '#define IMGUI_ENABLE_FREETYPE_LUNASVG' to use lunasvg (not provided). See #6591.
+
 // Forward declarations
 struct ImFontAtlas;
 struct ImFontBuilderIO;

From 706438a43c368c4a7d822b5ff997fa2befdbd5e6 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 17 Oct 2024 11:37:16 +0200
Subject: [PATCH 0439/2359] Disabled: clicking a disabled item focuses parent
 window. Fix/amend 83ecc84. (#8064)

83ecc84 was too not supporting widgets using ItemHoverable() directly + too complex.
Revert 83ecc84 in ButtonBehavior(), reimplement in UpdateMouseMovingWindowEndFrame()>
---
 imgui.cpp         | 10 ++++++----
 imgui_widgets.cpp | 16 ++--------------
 2 files changed, 8 insertions(+), 18 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 3ce5e90db..75e0ad40f 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4875,12 +4875,13 @@ void ImGui::UpdateMouseMovingWindowNewFrame()
     }
 }
 
-// Initiate moving window when clicking on empty space or title bar.
+// Initiate focusing and moving window when clicking on empty space or title bar.
+// Initiate focusing window when clicking on a disabled item.
 // Handle left-click and right-click focus.
 void ImGui::UpdateMouseMovingWindowEndFrame()
 {
     ImGuiContext& g = *GImGui;
-    if (g.ActiveId != 0 || g.HoveredId != 0)
+    if (g.ActiveId != 0 || (g.HoveredId != 0 && !g.HoveredIdIsDisabled))
         return;
 
     // Unless we just made a window/popup appear
@@ -4906,7 +4907,8 @@ void ImGui::UpdateMouseMovingWindowEndFrame()
                     if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
                         g.MovingWindow = NULL;
 
-            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
+            // Cancel moving if clicked over an item which was disabled or inhibited by popups
+            // (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item)0 already)
             if (g.HoveredIdIsDisabled)
                 g.MovingWindow = NULL;
         }
@@ -4920,7 +4922,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame()
     // With right mouse button we close popups without changing focus based on where the mouse is aimed
     // Instead, focus will be restored to the window under the bottom-most closed popup.
     // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
-    if (g.IO.MouseClicked[1])
+    if (g.IO.MouseClicked[1] && g.HoveredId == 0)
     {
         // Find the top-most window between HoveredWindow and the top-most Modal Window.
         // This is where we can trim the popup stack.
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 247fce39c..e240bdd90 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -542,8 +542,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
 
     // Mouse handling
     const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id;
-    const bool hovered_disabled = (g.HoveredId == id && g.HoveredIdIsDisabled);
-    if (hovered || hovered_disabled)
+    if (hovered)
     {
         IM_ASSERT(id != 0); // Lazily check inside rare path.
 
@@ -561,7 +560,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
 
         // Process initial action
         const bool mods_ok = !(flags & ImGuiButtonFlags_NoKeyModsAllowed) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt);
-        if (mods_ok && !hovered_disabled)
+        if (mods_ok)
         {
             if (mouse_button_clicked != -1 && g.ActiveId != id)
             {
@@ -619,17 +618,6 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
                 if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, ImGuiInputFlags_Repeat, test_owner_id))
                     pressed = true;
         }
-        else if (mods_ok && hovered_disabled)
-        {
-            if (mouse_button_clicked != -1 && g.ActiveId != id)
-            {
-                // Disabled path still focus
-                // FIXME-NAV: Could somehow call SetNavID() with a null ID but mouse pos as NavRectRel so nav may be resumed?
-                // Will do it once we do it for regular click on window-void.
-                if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick))
-                    FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild);
-            }
-        }
 
         if (pressed)
             g.NavDisableHighlight = true;

From e6b5cafe65fd983eb87bf2fd4d7f68e544911fcd Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 17 Oct 2024 15:11:35 +0200
Subject: [PATCH 0440/2359] Internals: rename ImGuiLastItemData::InFlags ->
 ItemFlags. ImGuiNextItemData::Flags -> HasFlags to avoid mistakes.

---
 imgui.cpp         | 42 +++++++++++++++++++-------------------
 imgui_internal.h  |  8 ++++----
 imgui_widgets.cpp | 52 +++++++++++++++++++++++------------------------
 3 files changed, 51 insertions(+), 51 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 75e0ad40f..36624f7f9 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3702,7 +3702,7 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl
         return;
     if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
         return;
-    if (id == g.LastItemData.ID && (g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
+    if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
         return;
     ImGuiWindow* window = g.CurrentWindow;
     if (window->DC.NavHideHighlightOneFrame)
@@ -4448,7 +4448,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
     {
         if (!IsItemFocused())
             return false;
-        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
+        if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
             return false;
 
         if (flags & ImGuiHoveredFlags_ForTooltip)
@@ -4483,11 +4483,11 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
 
         // Test if interactions on this window are blocked by an active popup or modal.
         // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
-        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
+        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_NoWindowHoverableCheck))
             return false;
 
         // Test if the item is disabled
-        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
+        if ((g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
             return false;
 
         // Special handling for calling after Begin() which represent the title bar or tab.
@@ -4497,7 +4497,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
             return false;
 
         // Test if using AllowOverlap and overlapped
-        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
+        if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
             if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
                 if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
                     return false;
@@ -4640,7 +4640,7 @@ void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemS
 {
     ImGuiContext& g = *GImGui;
     g.LastItemData.ID = item_id;
-    g.LastItemData.InFlags = in_flags;
+    g.LastItemData.ItemFlags = in_flags;
     g.LastItemData.StatusFlags = item_flags;
     g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
 }
@@ -10280,7 +10280,7 @@ bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, Im
 void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
 {
     ImGuiContext& g = *GImGui;
-    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
+    g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasShortcut;
     g.NextItemData.Shortcut = key_chord;
     g.NextItemData.ShortcutFlags = flags;
 }
@@ -10292,7 +10292,7 @@ void ImGui::ItemHandleShortcut(ImGuiID id)
     ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
     IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
 
-    if (g.LastItemData.InFlags & ImGuiItemFlags_Disabled)
+    if (g.LastItemData.ItemFlags & ImGuiItemFlags_Disabled)
         return;
     if (flags & ImGuiInputFlags_Tooltip)
     {
@@ -10784,7 +10784,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu
     g.LastItemData.ID = id;
     g.LastItemData.Rect = bb;
     g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
-    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
+    g.LastItemData.ItemFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
     g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
     // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
 
@@ -10802,7 +10802,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu
         //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
         // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
         // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
-        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
+        if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
         {
             // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
             window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
@@ -10812,12 +10812,12 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu
                         NavProcessItem();
         }
 
-        if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
+        if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasShortcut)
             ItemHandleShortcut(id);
     }
 
     // Lightweight clear of SetNextItemXXX data.
-    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
+    g.NextItemData.HasFlags = ImGuiNextItemDataFlags_None;
     g.NextItemData.ItemFlags = ImGuiItemFlags_None;
 
 #ifdef IMGUI_ENABLE_TEST_ENGINE
@@ -11046,7 +11046,7 @@ void ImGui::Unindent(float indent_w)
 void ImGui::SetNextItemWidth(float item_width)
 {
     ImGuiContext& g = *GImGui;
-    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
+    g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasWidth;
     g.NextItemData.Width = item_width;
 }
 
@@ -11057,7 +11057,7 @@ void ImGui::PushItemWidth(float item_width)
     ImGuiWindow* window = g.CurrentWindow;
     window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
     window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
-    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
+    g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
 }
 
 void ImGui::PushMultiItemsWidths(int components, float w_full)
@@ -11076,7 +11076,7 @@ void ImGui::PushMultiItemsWidths(int components, float w_full)
         prev_split = next_split;
     }
     window->DC.ItemWidth = ImMax(prev_split, 1.0f);
-    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
+    g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth;
 }
 
 void ImGui::PopItemWidth()
@@ -11099,7 +11099,7 @@ float ImGui::CalcItemWidth()
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = g.CurrentWindow;
     float w;
-    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
+    if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
         w = g.NextItemData.Width;
     else
         w = window->DC.ItemWidth;
@@ -12444,7 +12444,7 @@ static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
     result->Window = window;
     result->ID = g.LastItemData.ID;
     result->FocusScopeId = g.CurrentFocusScopeId;
-    result->InFlags = g.LastItemData.InFlags;
+    result->InFlags = g.LastItemData.ItemFlags;
     result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
     if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
     {
@@ -12469,7 +12469,7 @@ static void ImGui::NavProcessItem()
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = g.CurrentWindow;
     const ImGuiID id = g.LastItemData.ID;
-    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
+    const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags;
 
     // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
     if (window->DC.NavIsScrollPushableX == false)
@@ -12531,7 +12531,7 @@ static void ImGui::NavProcessItem()
         SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
         g.NavFocusScopeId = g.CurrentFocusScopeId;
         g.NavIdIsAlive = true;
-        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
+        if (g.LastItemData.ItemFlags & ImGuiItemFlags_HasSelectionUserData)
         {
             IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
             g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
@@ -12652,7 +12652,7 @@ void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGu
     ImGuiContext& g = *GImGui;
     g.NavMoveScoringItems = false;
     g.LastItemData.ID = tree_node_data->ID;
-    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
+    g.LastItemData.ItemFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
     g.LastItemData.NavRect = tree_node_data->NavRect;
     NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
     NavClearPreferredPosForAxis(ImGuiAxis_Y);
@@ -13916,7 +13916,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
             // Rely on keeping other window->LastItemXXX fields intact.
             source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
             KeepAliveID(source_id);
-            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
+            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.ItemFlags);
             if (is_hovered && g.IO.MouseClicked[mouse_button])
             {
                 SetActiveID(source_id, window);
diff --git a/imgui_internal.h b/imgui_internal.h
index 6e207d60e..f7e4f662e 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1209,7 +1209,7 @@ enum ImGuiNextItemDataFlags_
 
 struct ImGuiNextItemData
 {
-    ImGuiNextItemDataFlags      Flags;
+    ImGuiNextItemDataFlags      HasFlags;           // Called HasFlags instead of Flags to avoid mistaking this
     ImGuiItemFlags              ItemFlags;          // Currently only tested/used for ImGuiItemFlags_AllowOverlap and ImGuiItemFlags_HasSelectionUserData.
     // Non-flags members are NOT cleared by ItemAdd() meaning they are still valid during NavProcessItem()
     ImGuiID                     FocusScopeId;       // Set by SetNextItemSelectionUserData()
@@ -1223,14 +1223,14 @@ struct ImGuiNextItemData
     ImGuiID                     StorageId;          // Set by SetNextItemStorageID()
 
     ImGuiNextItemData()         { memset(this, 0, sizeof(*this)); SelectionUserData = -1; }
-    inline void ClearFlags()    { Flags = ImGuiNextItemDataFlags_None; ItemFlags = ImGuiItemFlags_None; } // Also cleared manually by ItemAdd()!
+    inline void ClearFlags()    { HasFlags = ImGuiNextItemDataFlags_None; ItemFlags = ImGuiItemFlags_None; } // Also cleared manually by ItemAdd()!
 };
 
 // Status storage for the last submitted item
 struct ImGuiLastItemData
 {
     ImGuiID                 ID;
-    ImGuiItemFlags          InFlags;            // See ImGuiItemFlags_
+    ImGuiItemFlags          ItemFlags;          // See ImGuiItemFlags_
     ImGuiItemStatusFlags    StatusFlags;        // See ImGuiItemStatusFlags_
     ImRect                  Rect;               // Full rectangle
     ImRect                  NavRect;            // Navigation scoring rectangle (not displayed)
@@ -3025,7 +3025,7 @@ namespace ImGui
 
     // Basic Accessors
     inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.StatusFlags; }
-    inline ImGuiItemFlags   GetItemFlags()  { ImGuiContext& g = *GImGui; return g.LastItemData.InFlags; }
+    inline ImGuiItemFlags   GetItemFlags()  { ImGuiContext& g = *GImGui; return g.LastItemData.ItemFlags; }
     inline ImGuiID          GetActiveID()   { ImGuiContext& g = *GImGui; return g.ActiveId; }
     inline ImGuiID          GetFocusID()    { ImGuiContext& g = *GImGui; return g.NavId; }
     IMGUI_API void          SetActiveID(ImGuiID id, ImGuiWindow* window);
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index e240bdd90..3aba3a4da 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -505,7 +505,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
 
     // Default behavior inherited from item flags
     // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
-    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
+    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags);
     if (flags & ImGuiButtonFlags_AllowOverlap)
         item_flags |= ImGuiItemFlags_AllowOverlap;
 
@@ -1150,7 +1150,7 @@ bool ImGui::Checkbox(const char* label, bool* v)
     const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
     ItemSize(total_bb, style.FramePadding.y);
     const bool is_visible = ItemAdd(total_bb, id);
-    const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0;
+    const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
     if (!is_visible)
         if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(total_bb)) // Extra layer of "no logic clip" for box-select support
         {
@@ -1180,7 +1180,7 @@ bool ImGui::Checkbox(const char* label, bool* v)
     }
 
     const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
-    const bool mixed_value = (g.LastItemData.InFlags & ImGuiItemFlags_MixedValue) != 0;
+    const bool mixed_value = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0;
     if (is_visible)
     {
         RenderNavHighlight(total_bb, id);
@@ -2562,7 +2562,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v
     }
     if (g.ActiveId != id)
         return false;
-    if ((g.LastItemData.InFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
+    if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
         return false;
 
     switch (data_type)
@@ -2609,7 +2609,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data,
     if (format == NULL)
         format = DataTypeGetInfo(data_type)->PrintFmt;
 
-    const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags);
+    const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
     bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
     if (!temp_input_is_active)
     {
@@ -3104,7 +3104,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ
         }
 
         if (set_new_value)
-            if ((g.LastItemData.InFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
+            if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
                 set_new_value = false;
 
         if (set_new_value)
@@ -3209,7 +3209,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat
     if (format == NULL)
         format = DataTypeGetInfo(data_type)->PrintFmt;
 
-    const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags);
+    const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
     bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
     if (!temp_input_is_active)
     {
@@ -3375,7 +3375,7 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d
     if (format == NULL)
         format = DataTypeGetInfo(data_type)->PrintFmt;
 
-    const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags);
+    const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
     const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
     if (clicked || g.NavActivateId == id)
     {
@@ -3583,7 +3583,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char*
         ClearActiveID();
 
     g.CurrentWindow->DC.CursorPos = bb.Min;
-    g.LastItemData.InFlags |= ImGuiItemFlags_AllowDuplicateId;
+    g.LastItemData.ItemFlags |= ImGuiItemFlags_AllowDuplicateId;
     bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags | ImGuiInputTextFlags_MergedItem);
     if (init)
     {
@@ -3640,7 +3640,7 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG
 void ImGui::SetNextItemRefVal(ImGuiDataType data_type, void* p_data)
 {
     ImGuiContext& g = *GImGui;
-    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasRefVal;
+    g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasRefVal;
     memcpy(&g.NextItemData.RefVal, p_data, DataTypeGetInfo(data_type)->Size);
 }
 
@@ -3658,7 +3658,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data
     if (format == NULL)
         format = DataTypeGetInfo(data_type)->PrintFmt;
 
-    void* p_data_default = (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasRefVal) ? &g.NextItemData.RefVal : &g.DataTypeZeroValue;
+    void* p_data_default = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasRefVal) ? &g.NextItemData.RefVal : &g.DataTypeZeroValue;
 
     char buf[64];
     if ((flags & ImGuiInputTextFlags_DisplayEmptyRefVal) && DataTypeCompare(data_type, p_data, p_data_default) == 0)
@@ -4465,7 +4465,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     }
 
     // Ensure mouse cursor is set even after switching to keyboard/gamepad mode. May generalize further? (#6417)
-    bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags | ImGuiItemFlags_NoNavDisableMouseHover);
+    bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags | ImGuiItemFlags_NoNavDisableMouseHover);
     if (hovered)
         SetMouseCursor(ImGuiMouseCursor_TextInput);
     if (hovered && g.NavDisableMouseHover)
@@ -4474,7 +4474,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     // We are only allowed to access the state if we are already the active widget.
     ImGuiInputTextState* state = GetInputTextState(id);
 
-    if (g.LastItemData.InFlags & ImGuiItemFlags_ReadOnly)
+    if (g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly)
         flags |= ImGuiInputTextFlags_ReadOnly;
     const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0;
     const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
@@ -5300,7 +5300,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         if (g.LastItemData.ID == 0 || g.LastItemData.ID != GetWindowScrollbarID(draw_window, ImGuiAxis_Y))
         {
             g.LastItemData.ID = id;
-            g.LastItemData.InFlags = item_data_backup.InFlags;
+            g.LastItemData.ItemFlags = item_data_backup.ItemFlags;
             g.LastItemData.StatusFlags = item_data_backup.StatusFlags;
         }
     }
@@ -5629,7 +5629,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag
 
     // Drag and Drop Target
     // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
-    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(g.LastItemData.InFlags & ImGuiItemFlags_ReadOnly) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())
+    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())
     {
         bool accepted_drag_drop = false;
         if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
@@ -6411,7 +6411,7 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags)
     ImGuiStorage* storage = window->DC.StateStorage;
 
     bool is_open;
-    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasOpen)
+    if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasOpen)
     {
         if (g.NextItemData.OpenCond & ImGuiCond_Always)
         {
@@ -6457,7 +6457,7 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags)
     ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.back();
     tree_node_data->ID = g.LastItemData.ID;
     tree_node_data->TreeFlags = flags;
-    tree_node_data->InFlags = g.LastItemData.InFlags;
+    tree_node_data->InFlags = g.LastItemData.ItemFlags;
     tree_node_data->NavRect = g.LastItemData.NavRect;
     window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth);
 }
@@ -6506,7 +6506,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
         interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f);
 
     // Compute open and multi-select states before ItemAdd() as it clear NextItem data.
-    ImGuiID storage_id = (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasStorageID) ? g.NextItemData.StorageId : id;
+    ImGuiID storage_id = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasStorageID) ? g.NextItemData.StorageId : id;
     bool is_open = TreeNodeUpdateNextOpen(storage_id, flags);
 
     bool is_visible;
@@ -6559,7 +6559,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
     }
 
     ImGuiButtonFlags button_flags = ImGuiTreeNodeFlags_None;
-    if ((flags & ImGuiTreeNodeFlags_AllowOverlap) || (g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap))
+    if ((flags & ImGuiTreeNodeFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap))
         button_flags |= ImGuiButtonFlags_AllowOverlap;
     if (!is_leaf)
         button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
@@ -6571,7 +6571,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
     const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x;
     const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2);
 
-    const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0;
+    const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
     if (is_multi_select) // We absolutely need to distinguish open vs select so _OpenOnArrow comes by default
         flags |= (flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 ? ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick : ImGuiTreeNodeFlags_OpenOnArrow;
 
@@ -6788,7 +6788,7 @@ void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond)
     ImGuiContext& g = *GImGui;
     if (g.CurrentWindow->SkipItems)
         return;
-    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasOpen;
+    g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasOpen;
     g.NextItemData.OpenVal = is_open;
     g.NextItemData.OpenCond = (ImU8)(cond ? cond : ImGuiCond_Always);
 }
@@ -6799,7 +6799,7 @@ void ImGui::SetNextItemStorageID(ImGuiID storage_id)
     ImGuiContext& g = *GImGui;
     if (g.CurrentWindow->SkipItems)
         return;
-    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasStorageID;
+    g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasStorageID;
     g.NextItemData.StorageId = storage_id;
 }
 
@@ -6925,7 +6925,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
         is_visible = ItemAdd(bb, id, NULL, extra_item_flags);
     }
 
-    const bool is_multi_select = (g.LastItemData.InFlags & ImGuiItemFlags_IsMultiSelect) != 0;
+    const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
     if (!is_visible)
         if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(bb)) // Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd)
             return false;
@@ -6953,7 +6953,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
     if (flags & ImGuiSelectableFlags_SelectOnClick)     { button_flags |= ImGuiButtonFlags_PressedOnClick; }
     if (flags & ImGuiSelectableFlags_SelectOnRelease)   { button_flags |= ImGuiButtonFlags_PressedOnRelease; }
     if (flags & ImGuiSelectableFlags_AllowDoubleClick)  { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }
-    if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; }
+    if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; }
 
     // Multi-selection support (header)
     const bool was_selected = selected;
@@ -7035,7 +7035,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
         RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);
 
     // Automatically close popups
-    if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.InFlags & ImGuiItemFlags_AutoClosePopups))
+    if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups))
         CloseCurrentPopup();
 
     if (disabled_item && !disabled_global)
@@ -9960,7 +9960,7 @@ bool    ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open,
     // Calculate tab contents size
     ImVec2 size = TabItemCalcSize(label, (p_open != NULL) || (flags & ImGuiTabItemFlags_UnsavedDocument));
     tab->RequestedWidth = -1.0f;
-    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
+    if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
         size.x = tab->RequestedWidth = g.NextItemData.Width;
     if (tab_is_new)
         tab->Width = ImMax(1.0f, size.x);

From 0f6a463fae57cbec744f89b5d1afb7bb1a7eb34f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 17 Oct 2024 15:16:05 +0200
Subject: [PATCH 0441/2359] Internals: rename ImGuiTreeNodeStackData::InFlags
 and ImGuiNavItemData::InFlags to ItemFlags too.

---
 imgui.cpp         | 16 ++++++++--------
 imgui_internal.h  | 16 ++++++++--------
 imgui_widgets.cpp |  2 +-
 3 files changed, 17 insertions(+), 17 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 36624f7f9..772df22a5 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4530,7 +4530,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
 // (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
 // FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
 // If you used this in your legacy/custom widgets code:
-// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
+// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'.
 // - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
 bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
 {
@@ -10847,7 +10847,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu
         IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
     }
     //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
-    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
+    //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0)
     //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
 #endif
 
@@ -12444,9 +12444,9 @@ static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
     result->Window = window;
     result->ID = g.LastItemData.ID;
     result->FocusScopeId = g.CurrentFocusScopeId;
-    result->InFlags = g.LastItemData.ItemFlags;
+    result->ItemFlags = g.LastItemData.ItemFlags;
     result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
-    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
+    if (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData)
     {
         IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
         result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
@@ -12652,7 +12652,7 @@ void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGu
     ImGuiContext& g = *GImGui;
     g.NavMoveScoringItems = false;
     g.LastItemData.ID = tree_node_data->ID;
-    g.LastItemData.ItemFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
+    g.LastItemData.ItemFlags = tree_node_data->ItemFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
     g.LastItemData.NavRect = tree_node_data->NavRect;
     NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
     NavClearPreferredPosForAxis(ImGuiAxis_Y);
@@ -13039,7 +13039,7 @@ void ImGui::NavInitRequestApplyResult()
         g.NavJustMovedToFocusScopeId = result->FocusScopeId;
         g.NavJustMovedToKeyMods = 0;
         g.NavJustMovedToIsTabbing = false;
-        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
+        g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
     }
 
     // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
@@ -13298,7 +13298,7 @@ void ImGui::NavMoveRequestApplyResult()
         g.NavJustMovedToFocusScopeId = result->FocusScopeId;
         g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
         g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
-        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
+        g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
         //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
     }
 
@@ -13318,7 +13318,7 @@ void ImGui::NavMoveRequestApplyResult()
     }
 
     // Tabbing: Activates Inputable, otherwise only Focus
-    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
+    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->ItemFlags & ImGuiItemFlags_Inputable) == 0)
         g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
 
     // Activate
diff --git a/imgui_internal.h b/imgui_internal.h
index f7e4f662e..75b586c3b 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -823,8 +823,8 @@ enum ImGuiDataTypePrivate_
 //-----------------------------------------------------------------------------
 
 // Extend ImGuiItemFlags
-// - input: PushItemFlag() manipulates g.CurrentItemFlags, ItemAdd() calls may add extra flags.
-// - output: stored in g.LastItemData.InFlags
+// - input: PushItemFlag() manipulates g.CurrentItemFlags, g.NextItemData.ItemFlags, ItemAdd() calls may add extra flags too.
+// - output: stored in g.LastItemData.ItemFlags
 enum ImGuiItemFlagsPrivate_
 {
     // Controlled by user
@@ -908,7 +908,7 @@ enum ImGuiButtonFlagsPrivate_
     ImGuiButtonFlags_AlignTextBaseLine      = 1 << 15,  // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine
     ImGuiButtonFlags_NoKeyModsAllowed       = 1 << 16,  // disable mouse interaction if a key modifier is held
     ImGuiButtonFlags_NoHoldingActiveId      = 1 << 17,  // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only)
-    ImGuiButtonFlags_NoNavFocus             = 1 << 18,  // don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags_NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.InFlags)
+    ImGuiButtonFlags_NoNavFocus             = 1 << 18,  // don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags_NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.ItemFlags)
     ImGuiButtonFlags_NoHoveredOnFocus       = 1 << 19,  // don't report as hovered when nav focus is on this item
     ImGuiButtonFlags_NoSetKeyOwner          = 1 << 20,  // don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!)
     ImGuiButtonFlags_NoTestKeyOwner         = 1 << 21,  // don't test key/input owner when polling the key (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!)
@@ -1250,7 +1250,7 @@ struct ImGuiTreeNodeStackData
 {
     ImGuiID                 ID;
     ImGuiTreeNodeFlags      TreeFlags;
-    ImGuiItemFlags          InFlags;    // Used for nav landing
+    ImGuiItemFlags          ItemFlags;  // Used for nav landing
     ImRect                  NavRect;    // Used for nav landing
 };
 
@@ -1590,14 +1590,14 @@ struct ImGuiNavItemData
     ImGuiID             ID;             // Init,Move    // Best candidate item ID
     ImGuiID             FocusScopeId;   // Init,Move    // Best candidate focus scope ID
     ImRect              RectRel;        // Init,Move    // Best candidate bounding box in window relative space
-    ImGuiItemFlags      InFlags;        // ????,Move    // Best candidate item flags
+    ImGuiItemFlags      ItemFlags;      // ????,Move    // Best candidate item flags
     float               DistBox;        //      Move    // Best candidate box distance to current NavId
     float               DistCenter;     //      Move    // Best candidate center distance to current NavId
     float               DistAxial;      //      Move    // Best candidate axial distance to current NavId
-    ImGuiSelectionUserData SelectionUserData;//I+Mov    // Best candidate SetNextItemSelectionUserData() value. Valid if (InFlags & ImGuiItemFlags_HasSelectionUserData)
+    ImGuiSelectionUserData SelectionUserData;//I+Mov    // Best candidate SetNextItemSelectionUserData() value. Valid if (ItemFlags & ImGuiItemFlags_HasSelectionUserData)
 
     ImGuiNavItemData()  { Clear(); }
-    void Clear()        { Window = NULL; ID = FocusScopeId = 0; InFlags = 0; SelectionUserData = -1; DistBox = DistCenter = DistAxial = FLT_MAX; }
+    void Clear()        { Window = NULL; ID = FocusScopeId = 0; ItemFlags = 0; SelectionUserData = -1; DistBox = DistCenter = DistAxial = FLT_MAX; }
 };
 
 // Storage for PushFocusScope()
@@ -2177,7 +2177,7 @@ struct ImGuiContext
     ImGuiID                 NavJustMovedToFocusScopeId;         // Just navigated to this focus scope id (result of a successfully MoveRequest).
     ImGuiKeyChord           NavJustMovedToKeyMods;
     bool                    NavJustMovedToIsTabbing;            // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags.
-    bool                    NavJustMovedToHasSelectionData;     // Copy of move result's InFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData.
+    bool                    NavJustMovedToHasSelectionData;     // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData.
 
     // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize)
     ImGuiKeyChord           ConfigNavWindowingKeyNext;          // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828)
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 3aba3a4da..60bb36631 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -6457,7 +6457,7 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags)
     ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.back();
     tree_node_data->ID = g.LastItemData.ID;
     tree_node_data->TreeFlags = flags;
-    tree_node_data->InFlags = g.LastItemData.ItemFlags;
+    tree_node_data->ItemFlags = g.LastItemData.ItemFlags;
     tree_node_data->NavRect = g.LastItemData.NavRect;
     window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth);
 }

From 38617a5ad345126d912be491d09070fbaecb2be1 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 17 Oct 2024 15:38:00 +0200
Subject: [PATCH 0442/2359] Internals: remove ImGuiInputTextFlags_NoMarkEdited
 and g.LockMarkEdited n favor of ImGuiItemFlags_NoMarkEdited.

---
 imgui.cpp         |  5 ++---
 imgui.h           |  2 +-
 imgui_internal.h  |  7 +++----
 imgui_widgets.cpp | 26 +++++++++++++++++---------
 4 files changed, 23 insertions(+), 17 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 772df22a5..182bd2162 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3986,7 +3986,6 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     DragSpeedDefaultRatio = 1.0f / 100.0f;
     DisabledAlphaBackup = 0.0f;
     DisabledStackSize = 0;
-    LockMarkEdited = 0;
     TooltipOverrideCount = 0;
     TooltipPreviousWindow = NULL;
 
@@ -4373,10 +4372,10 @@ ImGuiID ImGui::GetHoveredID()
 
 void ImGui::MarkItemEdited(ImGuiID id)
 {
-    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
+    // This marking is to be able to provide info for IsItemDeactivatedAfterEdit().
     // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
     ImGuiContext& g = *GImGui;
-    if (g.LockMarkEdited > 0)
+    if (g.LastItemData.ItemFlags & ImGuiItemFlags_NoMarkEdited)
         return;
     if (g.ActiveId == id || g.ActiveId == 0)
     {
diff --git a/imgui.h b/imgui.h
index ef0c59a9d..4ea730626 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1154,7 +1154,7 @@ enum ImGuiInputTextFlags_
 
     // Inputs
     ImGuiInputTextFlags_AllowTabInput       = 1 << 5,   // Pressing TAB input a '\t' character into the text field
-    ImGuiInputTextFlags_EnterReturnsTrue    = 1 << 6,   // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function.
+    ImGuiInputTextFlags_EnterReturnsTrue    = 1 << 6,   // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider using IsItemDeactivatedAfterEdit() instead!
     ImGuiInputTextFlags_EscapeClearsAll     = 1 << 7,   // Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert)
     ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 8,   // In multi-line mode, validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter).
 
diff --git a/imgui_internal.h b/imgui_internal.h
index 75b586c3b..bf7759f7b 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -834,6 +834,7 @@ enum ImGuiItemFlagsPrivate_
     ImGuiItemFlags_NoWindowHoverableCheck   = 1 << 13, // false     // Disable hoverable check in ItemHoverable()
     ImGuiItemFlags_AllowOverlap             = 1 << 14, // false     // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame.
     ImGuiItemFlags_NoNavDisableMouseHover   = 1 << 15, // false     // Nav keyboard/gamepad mode doesn't disable hover.
+    ImGuiItemFlags_NoMarkEdited             = 1 << 16, // false     // Skip calling MarkItemEdited()
 
     // Controlled by widget code
     ImGuiItemFlags_Inputable                = 1 << 20, // false     // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature.
@@ -886,9 +887,8 @@ enum ImGuiInputTextFlagsPrivate_
 {
     // [Internal]
     ImGuiInputTextFlags_Multiline           = 1 << 26,  // For internal use by InputTextMultiline()
-    ImGuiInputTextFlags_NoMarkEdited        = 1 << 27,  // For internal use by functions using InputText() before reformatting data
-    ImGuiInputTextFlags_MergedItem          = 1 << 28,  // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match.
-    ImGuiInputTextFlags_LocalizeDecimalPoint= 1 << 29,  // For internal use by InputScalar() and TempInputScalar()
+    ImGuiInputTextFlags_MergedItem          = 1 << 27,  // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match.
+    ImGuiInputTextFlags_LocalizeDecimalPoint= 1 << 28,  // For internal use by InputScalar() and TempInputScalar()
 };
 
 // Extend ImGuiButtonFlags_
@@ -2282,7 +2282,6 @@ struct ImGuiContext
     float                   DragSpeedDefaultRatio;              // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio
     float                   DisabledAlphaBackup;                // Backup for style.Alpha for BeginDisabled()
     short                   DisabledStackSize;
-    short                   LockMarkEdited;
     short                   TooltipOverrideCount;
     ImGuiWindow*            TooltipPreviousWindow;              // Window of last tooltip submitted during the frame
     ImVector          ClipboardHandlerData;               // If no custom clipboard handler is defined
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 60bb36631..9f171c97d 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3601,6 +3601,7 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG
 {
     // 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
+    ImGuiContext& g = *GImGui;
     const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
     char fmt_buf[32];
     char data_buf[32];
@@ -3610,8 +3611,8 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG
     DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format);
     ImStrTrimBlanks(data_buf);
 
-    ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_NoMarkEdited | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
-
+    ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
+    g.LastItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited; // Because TempInputText() uses ImGuiInputTextFlags_MergedItem it doesn't submit a new item, so we poke LastItemData.
     bool value_changed = false;
     if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags))
     {
@@ -3630,6 +3631,7 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG
         }
 
         // Only mark as edited if new value is different
+        g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited;
         value_changed = memcmp(&data_backup, p_data, data_type_size) != 0;
         if (value_changed)
             MarkItemEdited(id);
@@ -3666,8 +3668,10 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data
     else
         DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format);
 
-    flags |= ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string.
-    flags |= (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
+    // Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags_Edited.
+    // We call MarkItemEdited() ourselves by comparing the actual data rather than the string.
+    g.NextItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited;
+    flags |= ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
 
     bool value_changed = false;
     if (p_step == NULL)
@@ -3719,6 +3723,8 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data
         PopID();
         EndGroup();
     }
+
+    g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited;
     if (value_changed)
         MarkItemEdited(g.LastItemData.ID);
 
@@ -5315,7 +5321,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     if (label_size.x > 0)
         RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
 
-    if (value_changed && !(flags & ImGuiInputTextFlags_NoMarkEdited))
+    if (value_changed)
         MarkItemEdited(id);
 
     IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable);
@@ -6196,8 +6202,9 @@ void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
     bool allow_opt_datatype = !(flags & ImGuiColorEditFlags_DataTypeMask_);
     if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
         return;
+
     ImGuiContext& g = *GImGui;
-    g.LockMarkEdited++;
+    PushItemFlag(ImGuiItemFlags_NoMarkEdited, true);
     ImGuiColorEditFlags opts = g.ColorEditOptions;
     if (allow_opt_inputs)
     {
@@ -6239,8 +6246,8 @@ void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
     }
 
     g.ColorEditOptions = opts;
+    PopItemFlag();
     EndPopup();
-    g.LockMarkEdited--;
 }
 
 void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags)
@@ -6249,8 +6256,9 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl
     bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
     if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context"))
         return;
+
     ImGuiContext& g = *GImGui;
-    g.LockMarkEdited++;
+    PushItemFlag(ImGuiItemFlags_NoMarkEdited, true);
     if (allow_opt_picker)
     {
         ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
@@ -6279,8 +6287,8 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl
         if (allow_opt_picker) Separator();
         CheckboxFlags("Alpha Bar", &g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
     }
+    PopItemFlag();
     EndPopup();
-    g.LockMarkEdited--;
 }
 
 //-------------------------------------------------------------------------

From 604f2fa84aa2c71cab53e07235557b5b9207b76e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 17 Oct 2024 15:42:11 +0200
Subject: [PATCH 0443/2359] InputScalar: added an assert to clarify that
 ImGuiInputTextFlags_EnterReturnsTrue is not supported by InputFloat, InputInt
 etc. (#8065)

It was never correctly supported. Please open an issue if you this would be useful to you. Otherwise use IsItemDeactivatedAfterEdit().
---
 docs/CHANGELOG.txt | 2 ++
 imgui_widgets.cpp  | 1 +
 2 files changed, 3 insertions(+)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 5d61daa54..373c12f70 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -93,6 +93,8 @@ Other changes:
   preventing use of external shortcuts not guarded by an ActiveId check. (#8048) [@geertbleyen]
 - InputText: ensure mouse cursor shape is set regardless of whether keyboard mode is 
   enabled or not. (#6417)
+- InputScalar: added an assert to clarify that ImGuiInputTextFlags_EnterReturnsTrue is not
+  supported by InputFloat, InputInt, InputScalar etc. widgets. It actually never was. (#8065)
 - imgui_freetype: Added support for plutosvg (as an alternative to lunasvg) to render 
   OpenType SVG fonts. Requires defining IMGUI_ENABLE_FREETYPE_PLUTOSVG along with IMGUI_ENABLE_FREETYPE.
   Providing headers/librairies for plutosvg + plutovg is up to you (see #7927 for help).
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 9f171c97d..8a504ef1d 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3656,6 +3656,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data
 
     ImGuiContext& g = *GImGui;
     ImGuiStyle& style = g.Style;
+    IM_ASSERT((flags & ImGuiInputTextFlags_EnterReturnsTrue) == 0); // Not supported by InputScalar(). Please open an issue if you this would be useful to you. Otherwise use IsItemDeactivatedAfterEdit()!
 
     if (format == NULL)
         format = DataTypeGetInfo(data_type)->PrintFmt;

From db26fe7ca8de76d7802cb5c74f683e42870754ee Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 12:35:19 +0200
Subject: [PATCH 0444/2359] Debug Tools: Metrics: Fixed a crash when browsing
 "InputText" section before using one. (#8071)

Caused by 21d03edcb
---
 imgui_widgets.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 8a504ef1d..c8e0a5b5e 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4129,6 +4129,7 @@ ImGuiInputTextState::ImGuiInputTextState()
 {
     memset(this, 0, sizeof(*this));
     Stb = IM_NEW(ImStbTexteditState);
+    memset(Stb, 0, sizeof(*Stb));
 }
 
 ImGuiInputTextState::~ImGuiInputTextState()

From 7a56b411247a9bbe32b7642f4434561e4bc6c3eb Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 17 Oct 2024 19:57:18 +0200
Subject: [PATCH 0445/2359] Nav: added io.ConfigNavEscapeClearFocusItem.
 (#8059, #2048, #1074, #3200)

---
 docs/CHANGELOG.txt | 11 ++++++++---
 docs/TODO.txt      |  4 ++--
 imgui.cpp          |  9 ++++++---
 imgui.h            |  5 +++--
 imgui_demo.cpp     |  2 ++
 imgui_internal.h   |  4 +++-
 6 files changed, 24 insertions(+), 11 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 373c12f70..129709152 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,8 +43,8 @@ Breaking changes:
 
 - The typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
   - This removes the requirement to redefine it for backends which are e.g. storing
-    descriptor sets or other 64-bits structures when building on 32-bits archs.
-    It therefore simplify various building scripts/helpers.
+    descriptor sets or other 64-bits structures when building on 32-bits archs
+    (namely our DX12 and Vulkan backends). It therefore simplify various building scripts/helpers.
   - You may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID'
     when passing your types to functions taking ImTextureID values, e.g. ImGui::Image().
     In doubt it is almost always better to do an intermediate intptr_t cast, since it
@@ -67,7 +67,12 @@ Other changes:
   state to draw callbacks. (#6969, #5834, #7468, #3590)
 - IO: WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
 - Error Handling: turned a few more functions into recoverable errors. (#1651)
-- Nav: added io.ConfigNavEscapeClearFocusWindow to clear focused window on Escape. (#3200)
+- Nav: added io.ConfigNavEscapeClearFocusItem and io.ConfigNavEscapeClearFocusWindow to change
+  how pressing Escape affects navigation. (#8059, #2048, #1074, #3200)
+  - Set io.ConfigNavEscapeClearFocusItem = true (default) to clear focused item and highlight.
+  - Set io.ConfigNavEscapeClearFocusItem = false for Escape to not have a specific effect.
+  - Set io.ConfigNavEscapeClearFocusWindow = true to completely unfocus the dear imgui window,
+    is for some reason your app relies on imgui focus to take other decisions.  
 - Nav: pressing escape to hide nav highlight doesn't clear location from when ctrl+tabbing 
   back into same window later.
 - Nav: fixed Ctrl+Tab so when starting with no focused window it starts from the top-most
diff --git a/docs/TODO.txt b/docs/TODO.txt
index e61501d78..dd98d18b1 100644
--- a/docs/TODO.txt
+++ b/docs/TODO.txt
@@ -275,13 +275,13 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
 
  - nav: some features such as PageUp/Down/Home/End should probably work without ImGuiConfigFlags_NavEnableKeyboard? (where do we draw the line? how about CTRL+Tab)
  ! nav: never clear NavId on some setup (e.g. gamepad centric)
- - nav: there's currently no way to completely clear focus with the keyboard. depending on patterns used by the application to dispatch inputs, it may be desirable.
  - nav: Home/End behavior when navigable item is not fully visible at the edge of scrolling? should be backtrack to keep item into view?
  - nav: NavScrollToBringItemIntoView() with item bigger than view should focus top-right? Repro: using Nav in "About Window"
- - nav: wrap around logic to allow e.g. grid based layout (pressing NavRight on the right-most element would go to the next row, etc.). see internal's NavMoveRequestTryWrapping().
+ - nav: expose wrap around flags/logic to allow e.g. grid based layout (pressing NavRight on the right-most element would go to the next row, etc.). see internal's NavMoveRequestTryWrapping().
  - nav: patterns to make it possible for arrows key to update selection (see JustMovedTo in range_select branch)
  - nav: restore/find nearest NavId when current one disappear (e.g. pressed a button that disappear, or perhaps auto restoring when current button change name)
  - nav: SetItemDefaultFocus() level of priority, so widget like Selectable when inside a popup could claim a low-priority default focus on the first selected iem
+ - nav: holding space to repeat a button doesn't show button activated during hold.
  - nav: NavFlattened: init requests don't work properly on flattened siblings.
  - nav: NavFlattened: pageup/pagedown/home/end don't work properly on flattened siblings.
  - nav: NavFlattened: ESC on a flattened child should select something.
diff --git a/imgui.cpp b/imgui.cpp
index 182bd2162..773272e2c 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1409,6 +1409,7 @@ ImGuiIO::ImGuiIO()
     ConfigNavSwapGamepadButtons = false;
     ConfigNavMoveSetMousePos = false;
     ConfigNavCaptureKeyboard = true;
+    ConfigNavEscapeClearFocusItem = true;
     ConfigNavEscapeClearFocusWindow = false;
     ConfigInputTrickleEventQueue = true;
     ConfigInputTextCursorBlink = true;
@@ -13376,11 +13377,13 @@ static void ImGui::NavUpdateCancelRequest()
     {
         // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
         // FIXME-NAV: This should happen on window appearing.
-        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
-            g.NavWindow->NavLastIds[0] = 0;
+        if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
+            if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup)))// || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
+                g.NavWindow->NavLastIds[0] = 0;
 
         // Clear nav focus
-        g.NavId = 0;
+        if (g.IO.ConfigNavEscapeClearFocusItem || g.IO.ConfigNavEscapeClearFocusWindow)
+            g.NavId = 0;
         if (g.IO.ConfigNavEscapeClearFocusWindow)
             FocusWindow(NULL);
     }
diff --git a/imgui.h b/imgui.h
index 4ea730626..641f1d54d 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2250,7 +2250,8 @@ struct ImGuiIO
     bool        ConfigNavSwapGamepadButtons;    // = false          // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
     bool        ConfigNavMoveSetMousePos;       // = false          // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. 
     bool        ConfigNavCaptureKeyboard;       // = true           // Sets io.WantCaptureKeyboard when io.NavActive is set.
-    bool        ConfigNavEscapeClearFocusWindow;// = false          // Pressing Escape (when no item is active, no popup open etc.) clears focused window + navigation id/highlight.
+    bool        ConfigNavEscapeClearFocusItem;  // = true           // Pressing Escape can clear focused item + navigation id/highlight. Set to false if you want to always keep highlight on.
+    bool        ConfigNavEscapeClearFocusWindow;// = false          // Pressing Escape can clear focused window as well (super set of io.ConfigNavEscapeClearFocusItem).
     bool        ConfigInputTrickleEventQueue;   // = true           // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.
     bool        ConfigInputTextCursorBlink;     // = true           // Enable blinking cursor (optional as some users consider it to be distracting).
     bool        ConfigInputTextEnterKeepActive; // = false          // [BETA] Pressing Enter will keep item active and select contents (single-line only).
@@ -2367,7 +2368,7 @@ struct ImGuiIO
     bool        WantSetMousePos;                    // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when io.ConfigNavMoveSetMousePos is enabled.
     bool        WantSaveIniSettings;                // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving!
     bool        NavActive;                          // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.
-    bool        NavVisible;                         // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events).
+    bool        NavVisible;                         // Keyboard/Gamepad navigation highlight is visible and allowed (will handle ImGuiKey_NavXXX events).
     float       Framerate;                          // Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally.
     int         MetricsRenderVertices;              // Vertices output during last call to Render()
     int         MetricsRenderIndices;               // Indices output during last call to Render() = number of triangles * 3
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index dca674054..63f6d15d1 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -532,6 +532,8 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::Checkbox("io.ConfigNavMoveSetMousePos", &io.ConfigNavMoveSetMousePos);
             ImGui::SameLine(); HelpMarker("Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult");
             ImGui::Checkbox("io.ConfigNavCaptureKeyboard", &io.ConfigNavCaptureKeyboard);
+            ImGui::Checkbox("io.ConfigNavEscapeClearFocusItem", &io.ConfigNavEscapeClearFocusItem);
+            ImGui::SameLine(); HelpMarker("Pressing Escape clears focused item.");
             ImGui::Checkbox("io.ConfigNavEscapeClearFocusWindow", &io.ConfigNavEscapeClearFocusWindow);
             ImGui::SameLine(); HelpMarker("Pressing Escape clears focused window.");
 
diff --git a/imgui_internal.h b/imgui_internal.h
index bf7759f7b..bc00d0c28 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1600,7 +1600,7 @@ struct ImGuiNavItemData
     void Clear()        { Window = NULL; ID = FocusScopeId = 0; ItemFlags = 0; SelectionUserData = -1; DistBox = DistCenter = DistAxial = FLT_MAX; }
 };
 
-// Storage for PushFocusScope()
+// Storage for PushFocusScope(), g.FocusScopeStack[], g.NavFocusRoute[]
 struct ImGuiFocusScopeData
 {
     ImGuiID             ID;
@@ -3223,6 +3223,8 @@ namespace ImGui
     IMGUI_API void          RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect);
 
     // Typing-Select API
+    // (provide Windows Explorer style "select items by typing partial name" + "cycle through items by typing same letter" feature)
+    // (this is currently not documented nor used by main library, but should work. See "widgets_typingselect" in imgui_test_suite for usage code. Please let us know if you use this!)
     IMGUI_API ImGuiTypingSelectRequest* GetTypingSelectRequest(ImGuiTypingSelectFlags flags = ImGuiTypingSelectFlags_None);
     IMGUI_API int           TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx);
     IMGUI_API int           TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx);

From 23b655f8e3a37305a89174e32ceaab057dc67318 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 16:42:22 +0200
Subject: [PATCH 0446/2359] Internals: (Breaking) changed g.NavDisableHighlight
 to g.NavCursorVisible : same logic but inverted value. (#1074, #2048, #7237,
 #8059, #1712, #7370, #787)

---
 imgui.cpp         | 36 ++++++++++++++++++------------------
 imgui.h           |  2 +-
 imgui_internal.h  |  3 ++-
 imgui_widgets.cpp | 10 +++++-----
 4 files changed, 26 insertions(+), 25 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 773272e2c..4dd02ee0a 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3701,7 +3701,7 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl
     ImGuiContext& g = *GImGui;
     if (id != g.NavId)
         return;
-    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
+    if (!g.NavCursorVisible && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
         return;
     if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
         return;
@@ -3910,7 +3910,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
     NavIdIsAlive = false;
     NavMousePosDirty = false;
-    NavDisableHighlight = true;
+    NavCursorVisible = false;
     NavDisableMouseHover = false;
 
     NavAnyRequest = false;
@@ -4444,7 +4444,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
     ImGuiWindow* window = g.CurrentWindow;
     IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
 
-    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
+    if (g.NavDisableMouseHover && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
     {
         if (!IsItemFocused())
             return false;
@@ -4824,7 +4824,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
     ImGuiContext& g = *GImGui;
     FocusWindow(window);
     SetActiveID(window->MoveId, window);
-    g.NavDisableHighlight = true;
+    g.NavCursorVisible = false;
     g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
     g.ActiveIdNoClearOnFocusLoss = true;
     SetActiveIdUsingAllKeyboardKeys();
@@ -5835,7 +5835,7 @@ bool ImGui::IsAnyItemActive()
 bool ImGui::IsAnyItemFocused()
 {
     ImGuiContext& g = *GImGui;
-    return g.NavId != 0 && !g.NavDisableHighlight;
+    return g.NavId != 0 && g.NavCursorVisible;
 }
 
 bool ImGui::IsItemVisible()
@@ -6689,7 +6689,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar
         // Title bar only
         const float backup_border_size = style.FrameBorderSize;
         g.Style.FrameBorderSize = window->WindowBorderSize;
-        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
+        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && g.NavCursorVisible) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
         RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
         g.Style.FrameBorderSize = backup_border_size;
     }
@@ -12189,7 +12189,7 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
 
         ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
         ImRect r_avoid;
-        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !g.IO.ConfigNavMoveSetMousePos)
+        if (g.NavCursorVisible && g.NavDisableMouseHover && !g.IO.ConfigNavMoveSetMousePos)
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
         else
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
@@ -12272,7 +12272,7 @@ void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
     if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
         g.NavDisableMouseHover = true;
     else
-        g.NavDisableHighlight = true;
+        g.NavCursorVisible = false;
 
     // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
     NavClearPreferredPosForAxis(ImGuiAxis_X);
@@ -12738,7 +12738,7 @@ void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
 void ImGui::NavRestoreHighlightAfterMove()
 {
     ImGuiContext& g = *GImGui;
-    g.NavDisableHighlight = false;
+    g.NavCursorVisible = true;
     g.NavDisableMouseHover = g.NavMousePosDirty = true;
 }
 
@@ -12789,7 +12789,7 @@ static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource()
     const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
 
     // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
-    if ((g.NavDisableHighlight || !g.NavDisableMouseHover || !window) && !activated_shortcut)
+    if ((!g.NavCursorVisible || !g.NavDisableMouseHover || !window) && !activated_shortcut)
         return ImGuiInputSource_Mouse;
     else
         return ImGuiInputSource_Keyboard; // or Nav in general
@@ -12897,7 +12897,7 @@ static void ImGui::NavUpdate()
     // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
     bool set_mouse_pos = false;
     if (g.NavMousePosDirty && g.NavIdIsAlive)
-        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
+        if (g.NavCursorVisible && g.NavDisableMouseHover && g.NavWindow)
             set_mouse_pos = true;
     g.NavMousePosDirty = false;
     IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
@@ -12913,7 +12913,7 @@ static void ImGui::NavUpdate()
 
     // Set output flags for user application
     io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
-    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
+    io.NavVisible = (io.NavActive && g.NavId != 0 && g.NavCursorVisible) || (g.NavWindowingTarget != NULL);
 
     // Process NavCancel input (to close a popup, get back to parent, clear focus)
     NavUpdateCancelRequest();
@@ -12921,7 +12921,7 @@ static void ImGui::NavUpdate()
     // Process manual activation request
     g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
     g.NavActivateFlags = ImGuiActivateFlags_None;
-    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
+    if (g.NavId != 0 && g.NavCursorVisible && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
     {
         const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
         const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
@@ -12946,7 +12946,7 @@ static void ImGui::NavUpdate()
         }
     }
     if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
-        g.NavDisableHighlight = true;
+        g.NavCursorVisible = false;
     if (g.NavActivateId != 0)
         IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
 
@@ -13003,7 +13003,7 @@ static void ImGui::NavUpdate()
     // Always prioritize mouse highlight if navigation is disabled
     if (!nav_keyboard_active && !nav_gamepad_active)
     {
-        g.NavDisableHighlight = true;
+        g.NavCursorVisible = false;
         g.NavDisableMouseHover = set_mouse_pos = false;
     }
 
@@ -13147,7 +13147,7 @@ void ImGui::NavUpdateCreateMoveRequest()
         IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer);
         g.NavInitRequest = g.NavInitRequestFromMove = true;
         g.NavInitResult.ID = 0;
-        g.NavDisableHighlight = false;
+        g.NavCursorVisible = true;
     }
 
     // When using gamepad, we project the reference nav bounding box into window visible area.
@@ -13211,7 +13211,7 @@ void ImGui::NavUpdateCreateTabbingRequest()
     // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
     const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
     if (nav_keyboard_active)
-        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
+        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavCursorVisible == false && g.ActiveId == 0) ? 0 : +1;
     else
         g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
     ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
@@ -15823,7 +15823,7 @@ void ImGui::ShowMetricsWindow(bool* p_open)
         Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
         Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
         Text("NavActivateFlags: %04X", g.NavActivateFlags);
-        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
+        Text("NavCursorVisible: %d, NavDisableMouseHover: %d", g.NavCursorVisible, g.NavDisableMouseHover);
         Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
         Text("NavFocusRoute[] = ");
         for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
diff --git a/imgui.h b/imgui.h
index 641f1d54d..d89661bf2 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.4 WIP"
-#define IMGUI_VERSION_NUM   19135
+#define IMGUI_VERSION_NUM   19136
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index bc00d0c28..a0f1c1c09 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2144,7 +2144,8 @@ struct ImGuiContext
     ImGuiSelectionUserData  NavLastValidSelectionUserData;      // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data.
     bool                    NavIdIsAlive;                       // Nav widget has been seen this frame ~~ NavRectRel is valid
     bool                    NavMousePosDirty;                   // When set we will update mouse position if io.ConfigNavMoveSetMousePos is set (not enabled by default)
-    bool                    NavDisableHighlight;                // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover)
+    bool                    NavCursorVisible;                   // Nav focus rectangle is visible? We hide it after a mouse click. We show it after a nav move.
+    //bool                  NavDisableHighlight;                // Before 1.91.4 (2024/10/18) we used g.NavDisableHighlight. g.NavCursorVisible is the new variable name, with opposite value (g.NavDisableHighlight = !g.NavCursorVisible)
     bool                    NavDisableMouseHover;               // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again.
 
     // Navigation: Init & Move Requests
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index c8e0a5b5e..7e67cea4e 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -620,12 +620,12 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
         }
 
         if (pressed)
-            g.NavDisableHighlight = true;
+            g.NavCursorVisible = false;
     }
 
     // Gamepad/Keyboard handling
     // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse.
-    if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover)
+    if (g.NavId == id && g.NavCursorVisible && g.NavDisableMouseHover)
         if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))
             hovered = true;
     if (g.NavActivateDownId == id)
@@ -689,7 +689,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
                 ClearActiveID();
             }
             if (!(flags & ImGuiButtonFlags_NoNavFocus))
-                g.NavDisableHighlight = true;
+                g.NavCursorVisible = false;
         }
         else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
         {
@@ -7001,7 +7001,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
         if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
         {
             SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, WindowRectAbsToRel(window, bb)); // (bb == NavRect)
-            g.NavDisableHighlight = true;
+            g.NavCursorVisible = false;
         }
     }
     if (pressed)
@@ -8624,7 +8624,7 @@ void ImGui::EndMenuBar()
             IM_ASSERT(window->DC.NavLayersActiveMaskNext & (1 << layer)); // Sanity check (FIXME: Seems unnecessary)
             FocusWindow(window);
             SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
-            g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection.
+            g.NavCursorVisible = false; // Hide nav cursor for the current frame so we don't see the intermediary selection.
             g.NavDisableMouseHover = g.NavMousePosDirty = true;
             NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat
         }

From 0536ace2b6c24bd1fb14550ac83e035e879834c1 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 16:46:14 +0200
Subject: [PATCH 0447/2359] Internals: (Breaking) renamed RenderNavHighlight()
 to RenderNavCursor(), ImGuiNavHighlightFlags to ImGuiNavRenderCursorFlags.
 (#1074, #2048, #7237, #8059, #1712, #7370, #787)

+ referenced in #8057, #3882, #3411, #2155, #3351, #4722, #1658, #4050.
---
 imgui.cpp         | 14 +++++++-------
 imgui_internal.h  | 23 ++++++++++++++++-------
 imgui_tables.cpp  |  2 +-
 imgui_widgets.cpp | 46 +++++++++++++++++++++++-----------------------
 4 files changed, 47 insertions(+), 38 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 4dd02ee0a..6679291c2 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3696,12 +3696,12 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
     }
 }
 
-void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
+void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags)
 {
     ImGuiContext& g = *GImGui;
     if (id != g.NavId)
         return;
-    if (!g.NavCursorVisible && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
+    if (!g.NavCursorVisible && !(flags & ImGuiNavRenderCursorFlags_AlwaysDraw))
         return;
     if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav))
         return;
@@ -3709,11 +3709,11 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl
     if (window->DC.NavHideHighlightOneFrame)
         return;
 
-    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
+    float rounding = (flags & ImGuiNavRenderCursorFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
     ImRect display_rect = bb;
     display_rect.ClipWith(window->ClipRect);
     const float thickness = 2.0f;
-    if (flags & ImGuiNavHighlightFlags_Compact)
+    if (flags & ImGuiNavRenderCursorFlags_Compact)
     {
         window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
     }
@@ -6067,11 +6067,11 @@ void ImGui::EndChild()
         if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
         {
             ItemAdd(bb, child_window->ChildId);
-            RenderNavHighlight(bb, child_window->ChildId);
+            RenderNavCursor(bb, child_window->ChildId);
 
             // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
             if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
-                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
+                RenderNavCursor(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavRenderCursorFlags_Compact);
         }
         else
         {
@@ -15950,7 +15950,7 @@ bool ImGui::DebugBreakButton(const char* label, const char* description_of_locat
     ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
     ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
 
-    RenderNavHighlight(bb, id);
+    RenderNavCursor(bb, id);
     RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
     RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
 
diff --git a/imgui_internal.h b/imgui_internal.h
index a0f1c1c09..94e0cb0e0 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -177,7 +177,7 @@ typedef int ImGuiDebugLogFlags;         // -> enum ImGuiDebugLogFlags_      // F
 typedef int ImGuiFocusRequestFlags;     // -> enum ImGuiFocusRequestFlags_  // Flags: for FocusWindow()
 typedef int ImGuiItemStatusFlags;       // -> enum ImGuiItemStatusFlags_    // Flags: for g.LastItemData.StatusFlags
 typedef int ImGuiOldColumnFlags;        // -> enum ImGuiOldColumnFlags_     // Flags: for BeginColumns()
-typedef int ImGuiNavHighlightFlags;     // -> enum ImGuiNavHighlightFlags_  // Flags: for RenderNavHighlight()
+typedef int ImGuiNavRenderCursorFlags;  // -> enum ImGuiNavRenderCursorFlags_//Flags: for RenderNavCursor()
 typedef int ImGuiNavMoveFlags;          // -> enum ImGuiNavMoveFlags_       // Flags: for navigation requests
 typedef int ImGuiNextItemDataFlags;     // -> enum ImGuiNextItemDataFlags_  // Flags: for SetNextItemXXX() functions
 typedef int ImGuiNextWindowDataFlags;   // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions
@@ -1546,12 +1546,18 @@ enum ImGuiScrollFlags_
     ImGuiScrollFlags_MaskY_                 = ImGuiScrollFlags_KeepVisibleEdgeY | ImGuiScrollFlags_KeepVisibleCenterY | ImGuiScrollFlags_AlwaysCenterY,
 };
 
-enum ImGuiNavHighlightFlags_
+enum ImGuiNavRenderCursorFlags_
 {
-    ImGuiNavHighlightFlags_None             = 0,
-    ImGuiNavHighlightFlags_Compact          = 1 << 1,       // Compact highlight, no padding
-    ImGuiNavHighlightFlags_AlwaysDraw       = 1 << 2,       // Draw rectangular highlight if (g.NavId == id) _even_ when using the mouse.
-    ImGuiNavHighlightFlags_NoRounding       = 1 << 3,
+    ImGuiNavRenderCursorFlags_None          = 0,
+    ImGuiNavRenderCursorFlags_Compact       = 1 << 1,       // Compact highlight, no padding/distance from focused item
+    ImGuiNavRenderCursorFlags_AlwaysDraw    = 1 << 2,       // Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse.
+    ImGuiNavRenderCursorFlags_NoRounding    = 1 << 3,
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+    ImGuiNavHighlightFlags_None             = ImGuiNavRenderCursorFlags_None,       // Renamed in 1.91.4
+    ImGuiNavHighlightFlags_Compact          = ImGuiNavRenderCursorFlags_Compact,    // Renamed in 1.91.4
+    ImGuiNavHighlightFlags_AlwaysDraw       = ImGuiNavRenderCursorFlags_AlwaysDraw, // Renamed in 1.91.4
+    ImGuiNavHighlightFlags_NoRounding       = ImGuiNavRenderCursorFlags_NoRounding, // Renamed in 1.91.4
+#endif
 };
 
 enum ImGuiNavMoveFlags_
@@ -3343,7 +3349,10 @@ namespace ImGui
     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          RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0);
-    IMGUI_API void          RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_None); // Navigation highlight
+    IMGUI_API void          RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags = ImGuiNavRenderCursorFlags_None); // Navigation highlight
+#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 void          RenderMouseCursor(ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow);
 
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 3ba15fef5..1f8035cde 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -3139,7 +3139,7 @@ void ImGui::TableHeader(const char* label)
         if ((table->RowFlags & ImGuiTableRowFlags_Headers) == 0)
             TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_TableHeaderBg), table->CurrentColumn);
     }
-    RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_Compact | ImGuiNavHighlightFlags_NoRounding);
+    RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact | ImGuiNavRenderCursorFlags_NoRounding);
     if (held)
         table->HeldHeaderColumn = (ImGuiTableColumnIdx)column_n;
     window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f;
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 7e67cea4e..e5f2acc8d 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -739,7 +739,7 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags
 
     // Render
     const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
-    RenderNavHighlight(bb, id);
+    RenderNavCursor(bb, id);
     RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
 
     if (g.LogEnabled)
@@ -791,7 +791,7 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiBut
 
     bool hovered, held;
     bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
-    RenderNavHighlight(bb, id);
+    RenderNavCursor(bb, id);
 
     IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);
     return pressed;
@@ -817,7 +817,7 @@ bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiBu
     // Render
     const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
     const ImU32 text_col = GetColorU32(ImGuiCol_Text);
-    RenderNavHighlight(bb, id);
+    RenderNavCursor(bb, id);
     RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding);
     RenderArrow(window->DrawList, bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), text_col, dir);
 
@@ -858,7 +858,7 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)
     ImU32 bg_col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered);
     if (hovered)
         window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
-    RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_Compact);
+    RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
     ImU32 cross_col = GetColorU32(ImGuiCol_Text);
     ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f);
     float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;
@@ -885,7 +885,7 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos)
     ImU32 text_col = GetColorU32(ImGuiCol_Text);
     if (hovered || held)
         window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
-    RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_Compact);
+    RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
     RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
 
     // Switch to moving the window after mouse is moved beyond the initial drag threshold
@@ -1092,7 +1092,7 @@ bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& imag
 
     // Render
     const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
-    RenderNavHighlight(bb, id);
+    RenderNavCursor(bb, id);
     RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding));
     if (bg_col.w > 0.0f)
         window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
@@ -1183,7 +1183,7 @@ bool ImGui::Checkbox(const char* label, bool* v)
     const bool mixed_value = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0;
     if (is_visible)
     {
-        RenderNavHighlight(total_bb, id);
+        RenderNavCursor(total_bb, id);
         RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
         ImU32 check_col = GetColorU32(ImGuiCol_CheckMark);
         if (mixed_value)
@@ -1285,7 +1285,7 @@ bool ImGui::RadioButton(const char* label, bool active)
     if (pressed)
         MarkItemEdited(id);
 
-    RenderNavHighlight(total_bb, id);
+    RenderNavCursor(total_bb, id);
     const int num_segment = window->DrawList->_CalcCircleAutoSegmentCount(radius);
     window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), num_segment);
     if (active)
@@ -1425,7 +1425,7 @@ bool ImGui::TextLink(const char* label)
 
     bool hovered, held;
     bool pressed = ButtonBehavior(bb, id, &hovered, &held);
-    RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_None);
+    RenderNavCursor(bb, id);
 
     if (hovered)
         SetMouseCursor(ImGuiMouseCursor_Hand);
@@ -1856,7 +1856,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
     // Render shape
     const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
     const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size);
-    RenderNavHighlight(bb, id);
+    RenderNavCursor(bb, id);
     if (!(flags & ImGuiComboFlags_NoPreview))
         window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft);
     if (!(flags & ImGuiComboFlags_NoArrowButton))
@@ -2658,7 +2658,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data,
 
     // Draw frame
     const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
-    RenderNavHighlight(frame_bb, id);
+    RenderNavCursor(frame_bb, id);
     RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
 
     // Drag behavior
@@ -3240,7 +3240,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat
 
     // Draw frame
     const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
-    RenderNavHighlight(frame_bb, id);
+    RenderNavCursor(frame_bb, id);
     RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
 
     // Slider behavior
@@ -3389,7 +3389,7 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d
 
     // Draw frame
     const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
-    RenderNavHighlight(frame_bb, id);
+    RenderNavCursor(frame_bb, id);
     RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
 
     // Slider behavior
@@ -5102,7 +5102,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     // Render frame
     if (!is_multiline)
     {
-        RenderNavHighlight(frame_bb, id);
+        RenderNavCursor(frame_bb, id);
         RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
     }
 
@@ -6113,7 +6113,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl
         else
             window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding);
     }
-    RenderNavHighlight(bb, id);
+    RenderNavCursor(bb, id);
     if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
     {
         if (g.Style.FrameBorderSize > 0.0f)
@@ -6677,15 +6677,15 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
     // Render
     {
         const ImU32 text_col = GetColorU32(ImGuiCol_Text);
-        ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_Compact;
+        ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact;
         if (is_multi_select)
-            nav_highlight_flags |= ImGuiNavHighlightFlags_AlwaysDraw; // Always show the nav rectangle
+            nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle
         if (display_frame)
         {
             // Framed type
             const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
             RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding);
-            RenderNavHighlight(frame_bb, id, nav_highlight_flags);
+            RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
             if (flags & ImGuiTreeNodeFlags_Bullet)
                 RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col);
             else if (!is_leaf)
@@ -6705,7 +6705,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
                 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
                 RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false);
             }
-            RenderNavHighlight(frame_bb, id, nav_highlight_flags);
+            RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
             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)
@@ -7026,10 +7026,10 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
         }
         if (g.NavId == id)
         {
-            ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_Compact | ImGuiNavHighlightFlags_NoRounding;
+            ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact | ImGuiNavRenderCursorFlags_NoRounding;
             if (is_multi_select)
-                nav_highlight_flags |= ImGuiNavHighlightFlags_AlwaysDraw; // Always show the nav rectangle
-            RenderNavHighlight(bb, id, nav_highlight_flags);
+                nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle
+            RenderNavCursor(bb, id, nav_render_cursor_flags);
         }
     }
 
@@ -10109,7 +10109,7 @@ bool    ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open,
         float y_offset = 1.0f * g.CurrentDpiScale;
         display_draw_list->AddLine(bb.GetTL() + ImVec2(x_offset, y_offset), bb.GetTR() + ImVec2(-x_offset, y_offset), GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline), style.TabBarOverlineSize);
     }
-    RenderNavHighlight(bb, id);
+    RenderNavCursor(bb, id);
 
     // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
     const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);

From 0bae2db77fdfe16f0f3c0f76b3af60de9f624b5e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 18:07:58 +0200
Subject: [PATCH 0448/2359] Internals: (Breaking) renamed NavDisableMouseHover
 to NavHighlightItemUnderNav.

Considering adding NavHighlightItemUnderMouse as well, but would require to resolve quite a few ambiguities and for a feature we don't have yet.
---
 imgui.cpp         | 30 +++++++++++++++---------------
 imgui_internal.h  |  9 +++++----
 imgui_widgets.cpp | 14 +++++++-------
 3 files changed, 27 insertions(+), 26 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 6679291c2..09acf5cd6 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3911,7 +3911,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     NavIdIsAlive = false;
     NavMousePosDirty = false;
     NavCursorVisible = false;
-    NavDisableMouseHover = false;
+    NavHighlightItemUnderNav = false;
 
     NavAnyRequest = false;
     NavInitRequest = false;
@@ -4444,7 +4444,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
     ImGuiWindow* window = g.CurrentWindow;
     IM_ASSERT_USER_ERROR((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0, "Invalid flags for IsItemHovered()!");
 
-    if (g.NavDisableMouseHover && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
+    if (g.NavHighlightItemUnderNav && g.NavCursorVisible && !(flags & ImGuiHoveredFlags_NoNavOverride))
     {
         if (!IsItemFocused())
             return false;
@@ -4615,7 +4615,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag
     }
 #endif
 
-    if (g.NavDisableMouseHover && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
+    if (g.NavHighlightItemUnderNav && (item_flags & ImGuiItemFlags_NoNavDisableMouseHover) == 0)
         return false;
 
     return true;
@@ -6589,7 +6589,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si
             g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
             g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
             g.NavWindowingToggleLayer = false;
-            g.NavDisableMouseHover = true;
+            g.NavHighlightItemUnderNav = true;
             resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
             ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
             if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
@@ -7859,7 +7859,7 @@ void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
     if (g.NavWindow != window)
     {
         SetNavWindow(window);
-        if (window && g.NavDisableMouseHover)
+        if (window && g.NavHighlightItemUnderNav)
             g.NavMousePosDirty = true;
         g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
         g.NavLayer = ImGuiNavLayer_Main;
@@ -9778,7 +9778,7 @@ static void ImGui::UpdateMouseInputs()
 
     // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
     if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
-        g.NavDisableMouseHover = false;
+        g.NavHighlightItemUnderNav = false;
 
     for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
     {
@@ -9817,7 +9817,7 @@ static void ImGui::UpdateMouseInputs()
 
         // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
         if (io.MouseClicked[i])
-            g.NavDisableMouseHover = false;
+            g.NavHighlightItemUnderNav = false;
     }
 }
 
@@ -12189,7 +12189,7 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
 
         ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale;
         ImRect r_avoid;
-        if (g.NavCursorVisible && g.NavDisableMouseHover && !g.IO.ConfigNavMoveSetMousePos)
+        if (g.NavCursorVisible && g.NavHighlightItemUnderNav && !g.IO.ConfigNavMoveSetMousePos)
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
         else
             r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
@@ -12270,7 +12270,7 @@ void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
         window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
 
     if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
-        g.NavDisableMouseHover = true;
+        g.NavHighlightItemUnderNav = true;
     else
         g.NavCursorVisible = false;
 
@@ -12739,7 +12739,7 @@ void ImGui::NavRestoreHighlightAfterMove()
 {
     ImGuiContext& g = *GImGui;
     g.NavCursorVisible = true;
-    g.NavDisableMouseHover = g.NavMousePosDirty = true;
+    g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
 }
 
 static inline void ImGui::NavUpdateAnyRequestFlag()
@@ -12789,7 +12789,7 @@ static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource()
     const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
 
     // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
-    if ((!g.NavCursorVisible || !g.NavDisableMouseHover || !window) && !activated_shortcut)
+    if ((!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) && !activated_shortcut)
         return ImGuiInputSource_Mouse;
     else
         return ImGuiInputSource_Keyboard; // or Nav in general
@@ -12897,7 +12897,7 @@ static void ImGui::NavUpdate()
     // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
     bool set_mouse_pos = false;
     if (g.NavMousePosDirty && g.NavIdIsAlive)
-        if (g.NavCursorVisible && g.NavDisableMouseHover && g.NavWindow)
+        if (g.NavCursorVisible && g.NavHighlightItemUnderNav && g.NavWindow)
             set_mouse_pos = true;
     g.NavMousePosDirty = false;
     IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
@@ -13004,7 +13004,7 @@ static void ImGui::NavUpdate()
     if (!nav_keyboard_active && !nav_gamepad_active)
     {
         g.NavCursorVisible = false;
-        g.NavDisableMouseHover = set_mouse_pos = false;
+        g.NavHighlightItemUnderNav = set_mouse_pos = false;
     }
 
     // Update mouse position if requested
@@ -13717,7 +13717,7 @@ static void ImGui::NavUpdateWindowing()
             const float NAV_MOVE_SPEED = 800.0f;
             const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
             g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
-            g.NavDisableMouseHover = true;
+            g.NavHighlightItemUnderNav = true;
             ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
             if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
             {
@@ -15823,7 +15823,7 @@ void ImGui::ShowMetricsWindow(bool* p_open)
         Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
         Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
         Text("NavActivateFlags: %04X", g.NavActivateFlags);
-        Text("NavCursorVisible: %d, NavDisableMouseHover: %d", g.NavCursorVisible, g.NavDisableMouseHover);
+        Text("NavCursorVisible: %d, NavHighlightItemUnderNav: %d", g.NavCursorVisible, g.NavHighlightItemUnderNav);
         Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
         Text("NavFocusRoute[] = ");
         for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
diff --git a/imgui_internal.h b/imgui_internal.h
index 94e0cb0e0..85ca13910 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -833,7 +833,7 @@ enum ImGuiItemFlagsPrivate_
     ImGuiItemFlags_MixedValue               = 1 << 12, // false     // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets)
     ImGuiItemFlags_NoWindowHoverableCheck   = 1 << 13, // false     // Disable hoverable check in ItemHoverable()
     ImGuiItemFlags_AllowOverlap             = 1 << 14, // false     // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame.
-    ImGuiItemFlags_NoNavDisableMouseHover   = 1 << 15, // false     // Nav keyboard/gamepad mode doesn't disable hover.
+    ImGuiItemFlags_NoNavDisableMouseHover   = 1 << 15, // false     // Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false).
     ImGuiItemFlags_NoMarkEdited             = 1 << 16, // false     // Skip calling MarkItemEdited()
 
     // Controlled by widget code
@@ -2133,6 +2133,10 @@ struct ImGuiContext
     ImVector Viewports;                        // Active viewports (Size==1 in 'master' branch). Each viewports hold their copy of ImDrawData.
 
     // Gamepad/keyboard Navigation
+    bool                    NavCursorVisible;                   // Nav focus cursor/rectangle is visible? We hide it after a mouse click. We show it after a nav move.
+    bool                    NavHighlightItemUnderNav;           // Disable mouse hovering highlight. Highlight navigation focused item instead of mouse hovered item.
+    //bool                  NavDisableHighlight;                // Old name for !g.NavCursorVisible before 1.91.4 (2024/10/18). OPPOSITE VALUE (g.NavDisableHighlight == !g.NavCursorVisible)
+    //bool                  NavDisableMouseHover;               // Old name for g.NavHighlightItemUnderNav before 1.91.1 (2024/10/18) this was called When user starts using keyboard/gamepad, we hide mouse hovering highlight until mouse is touched again.
     ImGuiWindow*            NavWindow;                          // Focused window for navigation. Could be called 'FocusedWindow'
     ImGuiID                 NavId;                              // Focused item for navigation
     ImGuiID                 NavFocusScopeId;                    // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope)
@@ -2150,9 +2154,6 @@ struct ImGuiContext
     ImGuiSelectionUserData  NavLastValidSelectionUserData;      // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data.
     bool                    NavIdIsAlive;                       // Nav widget has been seen this frame ~~ NavRectRel is valid
     bool                    NavMousePosDirty;                   // When set we will update mouse position if io.ConfigNavMoveSetMousePos is set (not enabled by default)
-    bool                    NavCursorVisible;                   // Nav focus rectangle is visible? We hide it after a mouse click. We show it after a nav move.
-    //bool                  NavDisableHighlight;                // Before 1.91.4 (2024/10/18) we used g.NavDisableHighlight. g.NavCursorVisible is the new variable name, with opposite value (g.NavDisableHighlight = !g.NavCursorVisible)
-    bool                    NavDisableMouseHover;               // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again.
 
     // Navigation: Init & Move Requests
     bool                    NavAnyRequest;                      // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd()
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index e5f2acc8d..3b28daa4d 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -625,7 +625,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
 
     // Gamepad/Keyboard handling
     // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse.
-    if (g.NavId == id && g.NavCursorVisible && g.NavDisableMouseHover)
+    if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav)
         if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))
             hovered = true;
     if (g.NavActivateDownId == id)
@@ -4476,7 +4476,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags | ImGuiItemFlags_NoNavDisableMouseHover);
     if (hovered)
         SetMouseCursor(ImGuiMouseCursor_TextInput);
-    if (hovered && g.NavDisableMouseHover)
+    if (hovered && g.NavHighlightItemUnderNav)
         hovered = false;
 
     // We are only allowed to access the state if we are already the active widget.
@@ -6628,7 +6628,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
             if ((flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 || (g.NavActivateId == id && !is_multi_select))
                 toggled = true; // Single click
             if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
-                toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job
+                toggled |= is_mouse_x_over_arrow && !g.NavHighlightItemUnderNav; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job
             if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)
                 toggled = true; // Double click
         }
@@ -6998,7 +6998,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
     // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard
     if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))
     {
-        if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
+        if (!g.NavHighlightItemUnderNav && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
         {
             SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, WindowRectAbsToRel(window, bb)); // (bb == NavRect)
             g.NavCursorVisible = false;
@@ -8625,7 +8625,7 @@ void ImGui::EndMenuBar()
             FocusWindow(window);
             SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
             g.NavCursorVisible = false; // Hide nav cursor for the current frame so we don't see the intermediary selection.
-            g.NavDisableMouseHover = g.NavMousePosDirty = true;
+            g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
             NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat
         }
     }
@@ -8833,7 +8833,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
     if (!enabled)
         EndDisabled();
 
-    const bool hovered = (g.HoveredId == id) && enabled && !g.NavDisableMouseHover;
+    const bool hovered = (g.HoveredId == id) && enabled && !g.NavHighlightItemUnderNav;
     if (menuset_is_open)
         PopItemFlag();
 
@@ -8868,7 +8868,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
         // The 'HovereWindow == window' check creates an inconsistency (e.g. moving away from menu slowly tends to hit same window, whereas moving away fast does not)
         // But we also need to not close the top-menu menu when moving over void. Perhaps we should extend the triangle check to a larger polygon.
         // (Remember to test this on BeginPopup("A")->BeginMenu("B") sequence which behaves slightly differently as B isn't a Child of A and hovering isn't shared.)
-        if (menu_is_open && !hovered && g.HoveredWindow == window && !moving_toward_child_menu && !g.NavDisableMouseHover && g.ActiveId == 0)
+        if (menu_is_open && !hovered && g.HoveredWindow == window && !moving_toward_child_menu && !g.NavHighlightItemUnderNav && g.ActiveId == 0)
             want_close = true;
 
         // Open

From 634a7ed988682e0dbb415810ded2f8d86e4996e4 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 17:06:30 +0200
Subject: [PATCH 0449/2359] Nav: added SetNavCursorVisible(). (#1074, #2048,
 #7237, #8059)

+ Further internal renaming for consistency.
---
 docs/CHANGELOG.txt |  2 ++
 imgui.cpp          | 47 ++++++++++++++++++++++++++--------------------
 imgui.h            | 10 ++++++----
 imgui_internal.h   |  4 ++--
 imgui_widgets.cpp  |  4 ++--
 5 files changed, 39 insertions(+), 28 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 129709152..319530e0a 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -67,6 +67,8 @@ Other changes:
   state to draw callbacks. (#6969, #5834, #7468, #3590)
 - IO: WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
 - Error Handling: turned a few more functions into recoverable errors. (#1651)
+- Nav: added NavSetCursorVisible(bool visible) to manipulate visibility of keyboard/gamepad
+  navigation cursor. (#1074, #2048, #7237, #8059)
 - Nav: added io.ConfigNavEscapeClearFocusItem and io.ConfigNavEscapeClearFocusWindow to change
   how pressing Escape affects navigation. (#8059, #2048, #1074, #3200)
   - Set io.ConfigNavEscapeClearFocusItem = true (default) to clear focused item and highlight.
diff --git a/imgui.cpp b/imgui.cpp
index 09acf5cd6..ba4a34121 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -8558,7 +8558,7 @@ void ImGui::FocusItem()
         return;
     }
 
-    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
+    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible | ImGuiNavMoveFlags_NoSelect;
     ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
     SetNavWindow(window);
     NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
@@ -8593,7 +8593,7 @@ void ImGui::SetKeyboardFocusHere(int offset)
 
     SetNavWindow(window);
 
-    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
+    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavCursorVisible;
     ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
     NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
     if (offset == -1)
@@ -12209,6 +12209,20 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
 // In our terminology those should be interchangeable, yet right now this is super confusing.
 // Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
 
+void ImGui::SetNavCursorVisible(bool visible)
+{
+    ImGuiContext& g = *GImGui;
+    g.NavCursorVisible = visible;
+}
+
+// (was called NavRestoreHighlightAfterMove() before 1.91.4)
+void ImGui::SetNavCursorVisibleAfterMove()
+{
+    ImGuiContext& g = *GImGui;
+    g.NavCursorVisible = true;
+    g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
+}
+
 void ImGui::SetNavWindow(ImGuiWindow* window)
 {
     ImGuiContext& g = *GImGui;
@@ -12735,13 +12749,6 @@ void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
     }
 }
 
-void ImGui::NavRestoreHighlightAfterMove()
-{
-    ImGuiContext& g = *GImGui;
-    g.NavCursorVisible = true;
-    g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
-}
-
 static inline void ImGui::NavUpdateAnyRequestFlag()
 {
     ImGuiContext& g = *GImGui;
@@ -13050,7 +13057,7 @@ void ImGui::NavInitRequestApplyResult()
     if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
         g.NavLastValidSelectionUserData = result->SelectionUserData;
     if (g.NavInitRequestFromMove)
-        NavRestoreHighlightAfterMove();
+        SetNavCursorVisibleAfterMove();
 }
 
 // Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
@@ -13243,9 +13250,9 @@ void ImGui::NavMoveRequestApplyResult()
     if (result == NULL)
     {
         if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
-            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
-        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
-            NavRestoreHighlightAfterMove();
+            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavCursorVisible;
+        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
+            SetNavCursorVisibleAfterMove();
         NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
         IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
         return;
@@ -13330,9 +13337,9 @@ void ImGui::NavMoveRequestApplyResult()
             g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
     }
 
-    // Enable nav highlight
-    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
-        NavRestoreHighlightAfterMove();
+    // Make nav cursor visible
+    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavCursorVisible) == 0)
+        SetNavCursorVisibleAfterMove();
 }
 
 // Process Escape/NavCancel input (to close a popup, get back to parent, clear focus)
@@ -13356,7 +13363,7 @@ static void ImGui::NavUpdateCancelRequest()
     {
         // Leave the "menu" layer
         NavRestoreLayer(ImGuiNavLayer_Main);
-        NavRestoreHighlightAfterMove();
+        SetNavCursorVisibleAfterMove();
     }
     else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
     {
@@ -13366,7 +13373,7 @@ static void ImGui::NavUpdateCancelRequest()
         IM_ASSERT(child_window->ChildId != 0);
         FocusWindow(parent_window);
         SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
-        NavRestoreHighlightAfterMove();
+        SetNavCursorVisibleAfterMove();
     }
     else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
     {
@@ -13732,7 +13739,7 @@ static void ImGui::NavUpdateWindowing()
     if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
     {
         ClearActiveID();
-        NavRestoreHighlightAfterMove();
+        SetNavCursorVisibleAfterMove();
         ClosePopupsOverWindow(apply_focus_window, false);
         FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
         apply_focus_window = g.NavWindow;
@@ -13779,7 +13786,7 @@ static void ImGui::NavUpdateWindowing()
             if (new_nav_layer == ImGuiNavLayer_Menu)
                 g.NavWindow->NavLastIds[new_nav_layer] = 0;
             NavRestoreLayer(new_nav_layer);
-            NavRestoreHighlightAfterMove();
+            SetNavCursorVisibleAfterMove();
         }
     }
 }
diff --git a/imgui.h b/imgui.h
index d89661bf2..c5ef6e935 100644
--- a/imgui.h
+++ b/imgui.h
@@ -900,10 +900,12 @@ namespace ImGui
     IMGUI_API void          PopClipRect();
 
     // Focus, Activation
-    // - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item"
-    IMGUI_API void          SetItemDefaultFocus();                                              // make last item the default focused item of a window.
+    IMGUI_API void          SetItemDefaultFocus();                                              // make last item the default focused item of of a newly appearing window.
     IMGUI_API void          SetKeyboardFocusHere(int offset = 0);                               // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.
 
+    // Keyboard/Gamepad Navigation
+    IMGUI_API void          SetNavCursorVisible(bool visible);                                  // alter visibility of keyboard/gamepad cursor. by default: show when using an arrow key, hide when clicking with mouse.
+
     // Overlapping mode
     IMGUI_API void          SetNextItemAllowOverlap();                                          // allow next item to be overlapped by a subsequent item. Useful with invisible buttons, selectable, treenode covering an area where subsequent items may need to be added. Note that both Selectable() and TreeNode() have dedicated flags doing this.
 
@@ -996,7 +998,7 @@ namespace ImGui
     // - Many related features are still in imgui_internal.h. For instance, most IsKeyXXX()/IsMouseXXX() functions have an owner-id-aware version.
     IMGUI_API void          SetItemKeyOwner(ImGuiKey key);                                      // Set key owner to last item ID if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'.
 
-    // Inputs Utilities: Mouse specific
+    // Inputs Utilities: Mouse
     // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right.
     // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle.
     // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold')
@@ -1676,7 +1678,7 @@ enum ImGuiCol_
     ImGuiCol_TextLink,              // Hyperlink color
     ImGuiCol_TextSelectedBg,
     ImGuiCol_DragDropTarget,        // Rectangle highlighting a drop target
-    ImGuiCol_NavHighlight,          // Gamepad/keyboard: current highlighted item
+    ImGuiCol_NavHighlight,          // Color of gamepad/keyboard navigation cursor/rectangle, when visible
     ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
     ImGuiCol_NavWindowingDimBg,     // Darken/colorize entire screen behind the CTRL+TAB window list, when active
     ImGuiCol_ModalWindowDimBg,      // Darken/colorize entire screen behind a modal window, when one is active
diff --git a/imgui_internal.h b/imgui_internal.h
index 85ca13910..921263456 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1578,7 +1578,7 @@ enum ImGuiNavMoveFlags_
     ImGuiNavMoveFlags_IsPageMove            = 1 << 11,  // Identify a PageDown/PageUp request.
     ImGuiNavMoveFlags_Activate              = 1 << 12,  // Activate/select target item.
     ImGuiNavMoveFlags_NoSelect              = 1 << 13,  // Don't trigger selection by not setting g.NavJustMovedTo
-    ImGuiNavMoveFlags_NoSetNavHighlight     = 1 << 14,  // Do not alter the visible state of keyboard vs mouse nav highlight
+    ImGuiNavMoveFlags_NoSetNavCursorVisible = 1 << 14,  // Do not alter the nav cursor visible state
     ImGuiNavMoveFlags_NoClearActiveId       = 1 << 15,  // (Experimental) Do not clear active id when applying move result
 };
 
@@ -3114,7 +3114,7 @@ namespace ImGui
     IMGUI_API void          NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags);
     IMGUI_API void          NavHighlightActivated(ImGuiID id);
     IMGUI_API void          NavClearPreferredPosForAxis(ImGuiAxis axis);
-    IMGUI_API void          NavRestoreHighlightAfterMove();
+    IMGUI_API void          SetNavCursorVisibleAfterMove();
     IMGUI_API void          NavUpdateCurrentWindowIsScrollPushableX();
     IMGUI_API void          SetNavWindow(ImGuiWindow* window);
     IMGUI_API void          SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel);
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 3b28daa4d..c3a61070b 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -7200,7 +7200,7 @@ int ImGui::TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count,
     else
         idx = TypingSelectFindBestLeadingMatch(req, items_count, get_item_name_func, user_data);
     if (idx != -1)
-        NavRestoreHighlightAfterMove();
+        SetNavCursorVisibleAfterMove();
     return idx;
 }
 
@@ -8883,7 +8883,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
         {
             want_open = want_open_nav_init = true;
             NavMoveRequestCancel();
-            NavRestoreHighlightAfterMove();
+            SetNavCursorVisibleAfterMove();
         }
     }
     else

From 1ff9768aa30e2e4152144a68e0edcf7aefa4d0f4 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 17:12:00 +0200
Subject: [PATCH 0450/2359] Nav: (Breaking) renamed ImGuiCol_NavHighlight to
 ImGuiCol_NavCursor. (#1074, #2048, #7237, #8059, #1712, #7370, #787)

---
 docs/CHANGELOG.txt | 2 ++
 imgui.cpp          | 7 ++++---
 imgui.h            | 3 ++-
 imgui_draw.cpp     | 6 +++---
 imgui_widgets.cpp  | 2 +-
 5 files changed, 12 insertions(+), 8 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 319530e0a..ca0c2a374 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -41,6 +41,8 @@ HOW TO UPDATE?
 
 Breaking changes:
 
+- Style: renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor, for consistency with newly
+  exposed and reworked features. Kept inline redirection enum (will obsolete).
 - The typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
   - This removes the requirement to redefine it for backends which are e.g. storing
     descriptor sets or other 64-bits structures when building on 32-bits archs
diff --git a/imgui.cpp b/imgui.cpp
index ba4a34121..4a965898d 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -430,6 +430,7 @@ CODE
  When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  You can read releases logs https://github.com/ocornut/imgui/releases for more details.
 
+ - 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete).
  - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
                          moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
                          kept legacy names (will obsolete) + code that copies settings once the first time. Dynamically changing the old value won't work. Switch to using the new value!
@@ -3491,7 +3492,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx)
     case ImGuiCol_TextLink: return "TextLink";
     case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
     case ImGuiCol_DragDropTarget: return "DragDropTarget";
-    case ImGuiCol_NavHighlight: return "NavHighlight";
+    case ImGuiCol_NavCursor: return "NavCursor";
     case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
     case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
     case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
@@ -3715,7 +3716,7 @@ void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFl
     const float thickness = 2.0f;
     if (flags & ImGuiNavRenderCursorFlags_Compact)
     {
-        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
+        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness);
     }
     else
     {
@@ -3724,7 +3725,7 @@ void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFl
         bool fully_visible = window->ClipRect.Contains(display_rect);
         if (!fully_visible)
             window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
-        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
+        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavCursor), rounding, 0, thickness);
         if (!fully_visible)
             window->DrawList->PopClipRect();
     }
diff --git a/imgui.h b/imgui.h
index c5ef6e935..5cc9922ff 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1678,7 +1678,7 @@ enum ImGuiCol_
     ImGuiCol_TextLink,              // Hyperlink color
     ImGuiCol_TextSelectedBg,
     ImGuiCol_DragDropTarget,        // Rectangle highlighting a drop target
-    ImGuiCol_NavHighlight,          // Color of gamepad/keyboard navigation cursor/rectangle, when visible
+    ImGuiCol_NavCursor,             // Color of gamepad/keyboard navigation cursor/rectangle, when visible
     ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
     ImGuiCol_NavWindowingDimBg,     // Darken/colorize entire screen behind the CTRL+TAB window list, when active
     ImGuiCol_ModalWindowDimBg,      // Darken/colorize entire screen behind a modal window, when one is active
@@ -1688,6 +1688,7 @@ enum ImGuiCol_
     ImGuiCol_TabActive = ImGuiCol_TabSelected,                  // [renamed in 1.90.9]
     ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed,                 // [renamed in 1.90.9]
     ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected,   // [renamed in 1.90.9]
+    ImGuiCol_NavHighlight = ImGuiCol_NavCursor,                 // [renamed in 1.91.4]
 #endif
 };
 
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index efee2ec9c..57b7d3ba2 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -230,7 +230,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst)
     colors[ImGuiCol_TextLink]               = colors[ImGuiCol_HeaderActive];
     colors[ImGuiCol_TextSelectedBg]         = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
     colors[ImGuiCol_DragDropTarget]         = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
-    colors[ImGuiCol_NavHighlight]           = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+    colors[ImGuiCol_NavCursor]              = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
     colors[ImGuiCol_NavWindowingHighlight]  = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
     colors[ImGuiCol_NavWindowingDimBg]      = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
     colors[ImGuiCol_ModalWindowDimBg]       = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
@@ -293,7 +293,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
     colors[ImGuiCol_TextLink]               = colors[ImGuiCol_HeaderActive];
     colors[ImGuiCol_TextSelectedBg]         = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
     colors[ImGuiCol_DragDropTarget]         = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
-    colors[ImGuiCol_NavHighlight]           = colors[ImGuiCol_HeaderHovered];
+    colors[ImGuiCol_NavCursor]              = colors[ImGuiCol_HeaderHovered];
     colors[ImGuiCol_NavWindowingHighlight]  = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
     colors[ImGuiCol_NavWindowingDimBg]      = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
     colors[ImGuiCol_ModalWindowDimBg]       = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
@@ -357,7 +357,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
     colors[ImGuiCol_TextLink]               = colors[ImGuiCol_HeaderActive];
     colors[ImGuiCol_TextSelectedBg]         = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
     colors[ImGuiCol_DragDropTarget]         = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
-    colors[ImGuiCol_NavHighlight]           = colors[ImGuiCol_HeaderHovered];
+    colors[ImGuiCol_NavCursor]              = colors[ImGuiCol_HeaderHovered];
     colors[ImGuiCol_NavWindowingHighlight]  = ImVec4(0.70f, 0.70f, 0.70f, 0.70f);
     colors[ImGuiCol_NavWindowingDimBg]      = ImVec4(0.20f, 0.20f, 0.20f, 0.20f);
     colors[ImGuiCol_ModalWindowDimBg]       = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index c3a61070b..ddfc263ef 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -7399,7 +7399,7 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flag
     ImRect box_select_r = bs->BoxSelectRectCurr;
     box_select_r.ClipWith(scope_rect);
     window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling
-    window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavHighlight)); // FIXME-MULTISELECT: Styling
+    window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT: Styling
 
     // Scroll
     const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0;

From 3982cb35dcf987ac278db35548d714c938bd4ab7 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 17:26:20 +0200
Subject: [PATCH 0451/2359] Nav, Docs: consistently use "keyboard/gamepad"
 instead of sometimes "gamepad/keyboard".

---
 imgui.cpp         | 31 +++++++++++++++++--------------
 imgui.h           | 24 +++++++++++++-----------
 imgui_demo.cpp    |  2 +-
 imgui_internal.h  | 12 ++++++------
 imgui_widgets.cpp |  8 ++++----
 5 files changed, 41 insertions(+), 36 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 4a965898d..c4388cedd 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1400,6 +1400,13 @@ ImGuiIO::ImGuiIO()
     FontAllowUserScaling = false;
     DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
 
+    // Keyboard/Gamepad Navigation options
+    ConfigNavSwapGamepadButtons = false;
+    ConfigNavMoveSetMousePos = false;
+    ConfigNavCaptureKeyboard = true;
+    ConfigNavEscapeClearFocusItem = true;
+    ConfigNavEscapeClearFocusWindow = false;
+
     // Miscellaneous options
     MouseDrawCursor = false;
 #ifdef __APPLE__
@@ -1407,11 +1414,6 @@ ImGuiIO::ImGuiIO()
 #else
     ConfigMacOSXBehaviors = false;
 #endif
-    ConfigNavSwapGamepadButtons = false;
-    ConfigNavMoveSetMousePos = false;
-    ConfigNavCaptureKeyboard = true;
-    ConfigNavEscapeClearFocusItem = true;
-    ConfigNavEscapeClearFocusWindow = false;
     ConfigInputTrickleEventQueue = true;
     ConfigInputTextCursorBlink = true;
     ConfigInputTextEnterKeepActive = false;
@@ -3900,8 +3902,13 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     CurrentItemFlags = ImGuiItemFlags_None;
     DebugShowGroupRects = false;
 
+    NavCursorVisible = false;
+    NavHighlightItemUnderNav = false;
+    NavMousePosDirty = false;
+    NavIdIsAlive = false;
+    NavId = 0;
     NavWindow = NULL;
-    NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
+    NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0;
     NavLayer = ImGuiNavLayer_Main;
     NavNextActivateId = 0;
     NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;
@@ -3909,10 +3916,6 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     NavHighlightActivatedTimer = 0.0f;
     NavInputSource = ImGuiInputSource_Keyboard;
     NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
-    NavIdIsAlive = false;
-    NavMousePosDirty = false;
-    NavCursorVisible = false;
-    NavHighlightItemUnderNav = false;
 
     NavAnyRequest = false;
     NavInitRequest = false;
@@ -5197,7 +5200,7 @@ void ImGui::NewFrame()
     //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
     //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
 
-    // Update gamepad/keyboard navigation
+    // Update keyboard/gamepad navigation
     NavUpdate();
 
     // Update mouse input state
@@ -9777,7 +9780,7 @@ static void ImGui::UpdateMouseInputs()
     g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
     //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
 
-    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
+    // If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
     if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
         g.NavHighlightItemUnderNav = false;
 
@@ -9816,7 +9819,7 @@ static void ImGui::UpdateMouseInputs()
         // We provide io.MouseDoubleClicked[] as a legacy service
         io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
 
-        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
+        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation
         if (io.MouseClicked[i])
             g.NavHighlightItemUnderNav = false;
     }
@@ -12310,7 +12313,7 @@ static float inline NavScoreItemDistInterval(float cand_min, float cand_max, flo
     return 0.0f;
 }
 
-// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
+// Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057
 static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
 {
     ImGuiContext& g = *GImGui;
diff --git a/imgui.h b/imgui.h
index 5cc9922ff..60bcbee6c 100644
--- a/imgui.h
+++ b/imgui.h
@@ -581,7 +581,7 @@ namespace ImGui
     //   the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
     // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
     // - Format string may also be set to NULL or use the default format ("%f" or "%d").
-    // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).
+    // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For keyboard/gamepad navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).
     // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used.
     // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum.
     // - 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.
@@ -1080,8 +1080,8 @@ enum ImGuiWindowFlags_
     ImGuiWindowFlags_NoBringToFrontOnFocus  = 1 << 13,  // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)
     ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14,  // Always show vertical scrollbar (even if ContentSize.y < Size.y)
     ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15,  // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
-    ImGuiWindowFlags_NoNavInputs            = 1 << 16,  // No gamepad/keyboard navigation within the window
-    ImGuiWindowFlags_NoNavFocus             = 1 << 17,  // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
+    ImGuiWindowFlags_NoNavInputs            = 1 << 16,  // No keyboard/gamepad navigation within the window
+    ImGuiWindowFlags_NoNavFocus             = 1 << 17,  // No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by CTRL+TAB)
     ImGuiWindowFlags_UnsavedDocument        = 1 << 18,  // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.
     ImGuiWindowFlags_NoNav                  = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
     ImGuiWindowFlags_NoDecoration           = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse,
@@ -1121,7 +1121,7 @@ enum ImGuiChildFlags_
     ImGuiChildFlags_AutoResizeY             = 1 << 5,   // Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above.
     ImGuiChildFlags_AlwaysAutoResize        = 1 << 6,   // Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED.
     ImGuiChildFlags_FrameStyle              = 1 << 7,   // Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding.
-    ImGuiChildFlags_NavFlattened            = 1 << 8,   // [BETA] Share focus scope, allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows.
+    ImGuiChildFlags_NavFlattened            = 1 << 8,   // [BETA] Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows.
 
     // Obsolete names
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
@@ -1328,7 +1328,7 @@ enum ImGuiHoveredFlags_
     ImGuiHoveredFlags_AllowWhenOverlappedByItem     = 1 << 8,   // IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item.
     ImGuiHoveredFlags_AllowWhenOverlappedByWindow   = 1 << 9,   // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window.
     ImGuiHoveredFlags_AllowWhenDisabled             = 1 << 10,  // IsItemHovered() only: Return true even if the item is disabled
-    ImGuiHoveredFlags_NoNavOverride                 = 1 << 11,  // IsItemHovered() only: Disable using gamepad/keyboard navigation state when active, always query mouse
+    ImGuiHoveredFlags_NoNavOverride                 = 1 << 11,  // IsItemHovered() only: Disable using keyboard/gamepad navigation state when active, always query mouse
     ImGuiHoveredFlags_AllowWhenOverlapped           = ImGuiHoveredFlags_AllowWhenOverlappedByItem | ImGuiHoveredFlags_AllowWhenOverlappedByWindow,
     ImGuiHoveredFlags_RectOnly                      = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped,
     ImGuiHoveredFlags_RootAndChildWindows           = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows,
@@ -1678,7 +1678,7 @@ enum ImGuiCol_
     ImGuiCol_TextLink,              // Hyperlink color
     ImGuiCol_TextSelectedBg,
     ImGuiCol_DragDropTarget,        // Rectangle highlighting a drop target
-    ImGuiCol_NavCursor,             // Color of gamepad/keyboard navigation cursor/rectangle, when visible
+    ImGuiCol_NavCursor,             // Color of keyboard/gamepad navigation cursor/rectangle, when visible
     ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
     ImGuiCol_NavWindowingDimBg,     // Darken/colorize entire screen behind the CTRL+TAB window list, when active
     ImGuiCol_ModalWindowDimBg,      // Darken/colorize entire screen behind a modal window, when one is active
@@ -2230,7 +2230,7 @@ struct ImGuiIO
     // Configuration                            // Default value
     //------------------------------------------------------------------
 
-    ImGuiConfigFlags   ConfigFlags;             // = 0              // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc.
+    ImGuiConfigFlags   ConfigFlags;             // = 0              // See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc.
     ImGuiBackendFlags  BackendFlags;            // = 0              // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend.
     ImVec2      DisplaySize;                    //           // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame.
     float       DeltaTime;                      // = 1.0f/60.0f     // Time elapsed since last frame, in seconds. May change every frame.
@@ -2246,15 +2246,17 @@ struct ImGuiIO
     ImFont*     FontDefault;                    // = NULL           // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].
     ImVec2      DisplayFramebufferScale;        // = (1, 1)         // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale.
 
-    // Miscellaneous options
-    // (you can visualize and interact with all options in 'Demo->Configuration')
-    bool        MouseDrawCursor;                // = false          // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
-    bool        ConfigMacOSXBehaviors;          // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
+    // Keyboard/Gamepad Navigation options
     bool        ConfigNavSwapGamepadButtons;    // = false          // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
     bool        ConfigNavMoveSetMousePos;       // = false          // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. 
     bool        ConfigNavCaptureKeyboard;       // = true           // Sets io.WantCaptureKeyboard when io.NavActive is set.
     bool        ConfigNavEscapeClearFocusItem;  // = true           // Pressing Escape can clear focused item + navigation id/highlight. Set to false if you want to always keep highlight on.
     bool        ConfigNavEscapeClearFocusWindow;// = false          // Pressing Escape can clear focused window as well (super set of io.ConfigNavEscapeClearFocusItem).
+
+    // Miscellaneous options
+    // (you can visualize and interact with all options in 'Demo->Configuration')
+    bool        MouseDrawCursor;                // = false          // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.
+    bool        ConfigMacOSXBehaviors;          // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.
     bool        ConfigInputTrickleEventQueue;   // = true           // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.
     bool        ConfigInputTextCursorBlink;     // = true           // Enable blinking cursor (optional as some users consider it to be distracting).
     bool        ConfigInputTextEnterKeepActive; // = false          // [BETA] Pressing Enter will keep item active and select contents (single-line only).
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 63f6d15d1..c484dd48c 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1012,7 +1012,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data)
 
         // The following examples are passed for documentation purpose but may not be useful to most users.
         // Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() will pull ImGuiHoveredFlags flags values from
-        // 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or gamepad/keyboard is being used.
+        // 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or keyboard/gamepad is being used.
         // With default settings, ImGuiHoveredFlags_ForTooltip is equivalent to ImGuiHoveredFlags_DelayShort + ImGuiHoveredFlags_Stationary.
         ImGui::Button("Manual", sz);
         if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip))
diff --git a/imgui_internal.h b/imgui_internal.h
index 921263456..bca327cdf 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -141,7 +141,7 @@ struct ImGuiLocEntry;               // A localization entry.
 struct ImGuiMenuColumns;            // Simple column measurement, currently used for MenuItem() only
 struct ImGuiMultiSelectState;       // Multi-selection persistent state (for focused selection).
 struct ImGuiMultiSelectTempData;    // Multi-selection temporary state (while traversing).
-struct ImGuiNavItemData;            // Result of a gamepad/keyboard directional navigation move query result
+struct ImGuiNavItemData;            // Result of a keyboard/gamepad directional navigation move query result
 struct ImGuiMetricsConfig;          // Storage for ShowMetricsWindow() and DebugNodeXXX() functions
 struct ImGuiNextWindowData;         // Storage for SetNextWindow** functions
 struct ImGuiNextItemData;           // Storage for SetNextItem** functions
@@ -2132,13 +2132,15 @@ struct ImGuiContext
     // Viewports
     ImVector Viewports;                        // Active viewports (Size==1 in 'master' branch). Each viewports hold their copy of ImDrawData.
 
-    // Gamepad/keyboard Navigation
+    // Keyboard/Gamepad Navigation
     bool                    NavCursorVisible;                   // Nav focus cursor/rectangle is visible? We hide it after a mouse click. We show it after a nav move.
     bool                    NavHighlightItemUnderNav;           // Disable mouse hovering highlight. Highlight navigation focused item instead of mouse hovered item.
     //bool                  NavDisableHighlight;                // Old name for !g.NavCursorVisible before 1.91.4 (2024/10/18). OPPOSITE VALUE (g.NavDisableHighlight == !g.NavCursorVisible)
     //bool                  NavDisableMouseHover;               // Old name for g.NavHighlightItemUnderNav before 1.91.1 (2024/10/18) this was called When user starts using keyboard/gamepad, we hide mouse hovering highlight until mouse is touched again.
-    ImGuiWindow*            NavWindow;                          // Focused window for navigation. Could be called 'FocusedWindow'
+    bool                    NavMousePosDirty;                   // When set we will update mouse position if io.ConfigNavMoveSetMousePos is set (not enabled by default)
+    bool                    NavIdIsAlive;                       // Nav widget has been seen this frame ~~ NavRectRel is valid
     ImGuiID                 NavId;                              // Focused item for navigation
+    ImGuiWindow*            NavWindow;                          // Focused window for navigation. Could be called 'FocusedWindow'
     ImGuiID                 NavFocusScopeId;                    // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope)
     ImGuiNavLayer           NavLayer;                           // Focused layer (main scrolling layer, or menu/title bar layer)
     ImGuiID                 NavActivateId;                      // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItem()
@@ -2152,8 +2154,6 @@ struct ImGuiContext
     ImGuiActivateFlags      NavNextActivateFlags;
     ImGuiInputSource        NavInputSource;                     // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse
     ImGuiSelectionUserData  NavLastValidSelectionUserData;      // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data.
-    bool                    NavIdIsAlive;                       // Nav widget has been seen this frame ~~ NavRectRel is valid
-    bool                    NavMousePosDirty;                   // When set we will update mouse position if io.ConfigNavMoveSetMousePos is set (not enabled by default)
 
     // Navigation: Init & Move Requests
     bool                    NavAnyRequest;                      // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd()
@@ -3101,7 +3101,7 @@ namespace ImGui
     IMGUI_API bool          BeginComboPreview();
     IMGUI_API void          EndComboPreview();
 
-    // Gamepad/Keyboard Navigation
+    // Keyboard/Gamepad Navigation
     IMGUI_API void          NavInitWindow(ImGuiWindow* window, bool force_reinit);
     IMGUI_API void          NavInitRequestApplyResult();
     IMGUI_API bool          NavMoveRequestButNoResultYet();
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index ddfc263ef..e0bc7f747 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -623,7 +623,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
             g.NavCursorVisible = false;
     }
 
-    // Gamepad/Keyboard handling
+    // Keyboard/Gamepad navigation handling
     // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse.
     if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav)
         if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))
@@ -3049,14 +3049,14 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ
                 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
                 if (decimal_precision > 0)
                 {
-                    input_delta /= 100.0f;    // Gamepad/keyboard tweak speeds in % of slider bounds
+                    input_delta /= 100.0f; // Keyboard/Gamepad tweak speeds in % of slider bounds
                     if (tweak_slow)
                         input_delta /= 10.0f;
                 }
                 else
                 {
                     if ((v_range_f >= -100.0f && v_range_f <= 100.0f && v_range_f != 0.0f) || tweak_slow)
-                        input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / v_range_f; // Gamepad/keyboard tweak speeds in integer steps
+                        input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / v_range_f; // Keyboard/Gamepad tweak speeds in integer steps
                     else
                         input_delta /= 100.0f;
                 }
@@ -6995,7 +6995,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
                 selected = pressed = true;
     }
 
-    // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard
+    // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad
     if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))
     {
         if (!g.NavHighlightItemUnderNav && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)

From ab9ce2a927ab0688c97f7fefadb49d84e41df346 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 18:28:27 +0200
Subject: [PATCH 0452/2359] Nav: added io.ConfigNavCursorVisibleAuto,
 io.ConfigNavCursorVisibleAlways. (#1074, #2048, #7237, #8059, #3200, #787)

Note: the NavCursorHideFrames addition is to support 88a354585 even though ConfigNavCursorVisibleAlways is set.
---
 docs/CHANGELOG.txt | 34 ++++++++++++++++++++--------------
 docs/TODO.txt      |  1 -
 imgui.cpp          | 21 +++++++++++++++++----
 imgui.h            |  2 ++
 imgui_demo.cpp     |  6 +++++-
 imgui_internal.h   |  1 +
 imgui_widgets.cpp  | 14 ++++++++++----
 7 files changed, 55 insertions(+), 24 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index ca0c2a374..3279969a2 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -69,20 +69,26 @@ Other changes:
   state to draw callbacks. (#6969, #5834, #7468, #3590)
 - IO: WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
 - Error Handling: turned a few more functions into recoverable errors. (#1651)
-- Nav: added NavSetCursorVisible(bool visible) to manipulate visibility of keyboard/gamepad
-  navigation cursor. (#1074, #2048, #7237, #8059)
-- Nav: added io.ConfigNavEscapeClearFocusItem and io.ConfigNavEscapeClearFocusWindow to change
-  how pressing Escape affects navigation. (#8059, #2048, #1074, #3200)
-  - Set io.ConfigNavEscapeClearFocusItem = true (default) to clear focused item and highlight.
-  - Set io.ConfigNavEscapeClearFocusItem = false for Escape to not have a specific effect.
-  - Set io.ConfigNavEscapeClearFocusWindow = true to completely unfocus the dear imgui window,
-    is for some reason your app relies on imgui focus to take other decisions.  
-- Nav: pressing escape to hide nav highlight doesn't clear location from when ctrl+tabbing 
-  back into same window later.
-- Nav: fixed Ctrl+Tab so when starting with no focused window it starts from the top-most
-  window. (#3200)
-- Nav: rectangle highlight not rendered for items with ImGuiItemFlags_NoNav. Can be relevant
-  when e.g activating the item with mouse, then Ctrl+Tabbing back and forth. 
+- Nav (Keyboard/Gamepad navigation):
+  - Nav: added io.ConfigNavCursorVisibleAuto and io.ConfigNavCursorVisibleAlways to configure
+    visibility of navigation cursor. (#1074, #2048, #7237, #8059, #3200, #787)
+     - Set io.ConfigNavCursorVisibleAuto = true (default) to enable automatic toggling
+       of cursor visibility (mouse click hide the cursor, arrow keys makes it visible).
+     - Set io.ConfigNavCursorVisibleAlways to keep cursor always visible.
+  - Nav: added NavSetCursorVisible(bool visible) function to manipulate visibility of 
+    navigation cursor (e.g. set default state, or after some actions). (#1074, #2048, #7237, #8059)
+  - Nav: added io.ConfigNavEscapeClearFocusItem and io.ConfigNavEscapeClearFocusWindow to change
+    how pressing Escape affects navigation. (#8059, #2048, #1074, #3200)
+    - Set io.ConfigNavEscapeClearFocusItem = true (default) to clear focused item and highlight.
+    - Set io.ConfigNavEscapeClearFocusItem = false for Escape to not have a specific effect.
+    - Set io.ConfigNavEscapeClearFocusWindow = true to completely unfocus the dear imgui window,
+      is for some reason your app relies on imgui focus to take other decisions.  
+  - Nav: pressing escape to hide nav highlight doesn't clear location from when Ctrl+Tabbing 
+    back into same window later.
+  - Nav: fixed Ctrl+Tab so when starting with no focused window it starts from the top-most
+    window. (#3200)
+  - Nav: rectangle highlight not rendered for items with ImGuiItemFlags_NoNav. Can be relevant
+    when e.g activating the item with mouse, then Ctrl+Tabbing back and forth. 
 - Disabled: clicking a disabled item focuses parent window. (#8064) 
 - InvisibleButton, Nav: fixed an issue when InvisibleButton() would be navigable into but
   not display navigation highlight. Properly navigation on it by default. (#8057)
diff --git a/docs/TODO.txt b/docs/TODO.txt
index dd98d18b1..2a42874cd 100644
--- a/docs/TODO.txt
+++ b/docs/TODO.txt
@@ -274,7 +274,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
  - font/opt: Glyph currently 40 bytes (2+9*4). Consider storing UV as 16-bits integer? (->32 bytes). X0/Y0/X1/Y1 as 16 fixed-point integers? Or X0/Y0 as float and X1/Y1 as fixed8_8?
 
  - nav: some features such as PageUp/Down/Home/End should probably work without ImGuiConfigFlags_NavEnableKeyboard? (where do we draw the line? how about CTRL+Tab)
- ! nav: never clear NavId on some setup (e.g. gamepad centric)
  - nav: Home/End behavior when navigable item is not fully visible at the edge of scrolling? should be backtrack to keep item into view?
  - nav: NavScrollToBringItemIntoView() with item bigger than view should focus top-right? Repro: using Nav in "About Window"
  - nav: expose wrap around flags/logic to allow e.g. grid based layout (pressing NavRight on the right-most element would go to the next row, etc.). see internal's NavMoveRequestTryWrapping().
diff --git a/imgui.cpp b/imgui.cpp
index c4388cedd..0ebd61dc5 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1406,6 +1406,8 @@ ImGuiIO::ImGuiIO()
     ConfigNavCaptureKeyboard = true;
     ConfigNavEscapeClearFocusItem = true;
     ConfigNavEscapeClearFocusWindow = false;
+    ConfigNavCursorVisibleAuto = true;
+    ConfigNavCursorVisibleAlways = false;
 
     // Miscellaneous options
     MouseDrawCursor = false;
@@ -3916,6 +3918,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     NavHighlightActivatedTimer = 0.0f;
     NavInputSource = ImGuiInputSource_Keyboard;
     NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
+    NavCursorHideFrames = 0;
 
     NavAnyRequest = false;
     NavInitRequest = false;
@@ -4828,7 +4831,8 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
     ImGuiContext& g = *GImGui;
     FocusWindow(window);
     SetActiveID(window->MoveId, window);
-    g.NavCursorVisible = false;
+    if (g.IO.ConfigNavCursorVisibleAuto)
+        g.NavCursorVisible = false;
     g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
     g.ActiveIdNoClearOnFocusLoss = true;
     SetActiveIdUsingAllKeyboardKeys();
@@ -12216,6 +12220,8 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
 void ImGui::SetNavCursorVisible(bool visible)
 {
     ImGuiContext& g = *GImGui;
+    if (g.IO.ConfigNavCursorVisibleAlways)
+        visible = true;
     g.NavCursorVisible = visible;
 }
 
@@ -12223,7 +12229,8 @@ void ImGui::SetNavCursorVisible(bool visible)
 void ImGui::SetNavCursorVisibleAfterMove()
 {
     ImGuiContext& g = *GImGui;
-    g.NavCursorVisible = true;
+    if (g.IO.ConfigNavCursorVisibleAuto)
+        g.NavCursorVisible = true;
     g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
 }
 
@@ -12289,7 +12296,7 @@ void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
 
     if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
         g.NavHighlightItemUnderNav = true;
-    else
+    else if (g.IO.ConfigNavCursorVisibleAuto)
         g.NavCursorVisible = false;
 
     // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
@@ -12904,6 +12911,9 @@ static void ImGui::NavUpdate()
         NavMoveRequestApplyResult();
     g.NavTabbingCounter = 0;
     g.NavMoveSubmitted = g.NavMoveScoringItems = false;
+    if (g.NavCursorHideFrames > 0)
+        if (--g.NavCursorHideFrames == 0)
+            g.NavCursorVisible = true;
 
     // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
     bool set_mouse_pos = false;
@@ -12958,6 +12968,8 @@ static void ImGui::NavUpdate()
     }
     if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
         g.NavCursorVisible = false;
+    else if (g.IO.ConfigNavCursorVisibleAlways && g.NavCursorHideFrames == 0)
+        g.NavCursorVisible = true;
     if (g.NavActivateId != 0)
         IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
 
@@ -13158,7 +13170,8 @@ void ImGui::NavUpdateCreateMoveRequest()
         IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer);
         g.NavInitRequest = g.NavInitRequestFromMove = true;
         g.NavInitResult.ID = 0;
-        g.NavCursorVisible = true;
+        if (g.IO.ConfigNavCursorVisibleAuto)
+            g.NavCursorVisible = true;
     }
 
     // When using gamepad, we project the reference nav bounding box into window visible area.
diff --git a/imgui.h b/imgui.h
index 60bcbee6c..73705cd36 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2252,6 +2252,8 @@ struct ImGuiIO
     bool        ConfigNavCaptureKeyboard;       // = true           // Sets io.WantCaptureKeyboard when io.NavActive is set.
     bool        ConfigNavEscapeClearFocusItem;  // = true           // Pressing Escape can clear focused item + navigation id/highlight. Set to false if you want to always keep highlight on.
     bool        ConfigNavEscapeClearFocusWindow;// = false          // Pressing Escape can clear focused window as well (super set of io.ConfigNavEscapeClearFocusItem).
+    bool        ConfigNavCursorVisibleAuto;     // = true           // Using directional navigation key makes the cursor visible. Mouse click hides the cursor.
+    bool        ConfigNavCursorVisibleAlways;   // = false          // Navigation cursor is always visible.
 
     // Miscellaneous options
     // (you can visualize and interact with all options in 'Demo->Configuration')
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index c484dd48c..668c5c0ee 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -527,7 +527,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
             ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).");
 
-            ImGui::SeparatorText("Navigation");
+            ImGui::SeparatorText("Keyboard/Gamepad Navigation");
             ImGui::Checkbox("io.ConfigNavSwapGamepadButtons", &io.ConfigNavSwapGamepadButtons);
             ImGui::Checkbox("io.ConfigNavMoveSetMousePos", &io.ConfigNavMoveSetMousePos);
             ImGui::SameLine(); HelpMarker("Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult");
@@ -536,6 +536,10 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::SameLine(); HelpMarker("Pressing Escape clears focused item.");
             ImGui::Checkbox("io.ConfigNavEscapeClearFocusWindow", &io.ConfigNavEscapeClearFocusWindow);
             ImGui::SameLine(); HelpMarker("Pressing Escape clears focused window.");
+            ImGui::Checkbox("io.ConfigNavCursorVisibleAuto", &io.ConfigNavCursorVisibleAuto);
+            ImGui::SameLine(); HelpMarker("Using directional navigation key makes the cursor visible. Mouse click hides the cursor.");
+            ImGui::Checkbox("io.ConfigNavCursorVisibleAlways", &io.ConfigNavCursorVisibleAlways);
+            ImGui::SameLine(); HelpMarker("Navigation cursor is always visible.");
 
             ImGui::SeparatorText("Widgets");
             ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink);
diff --git a/imgui_internal.h b/imgui_internal.h
index bca327cdf..97a51a355 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2154,6 +2154,7 @@ struct ImGuiContext
     ImGuiActivateFlags      NavNextActivateFlags;
     ImGuiInputSource        NavInputSource;                     // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse
     ImGuiSelectionUserData  NavLastValidSelectionUserData;      // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data.
+    ImS8                    NavCursorHideFrames;
 
     // Navigation: Init & Move Requests
     bool                    NavAnyRequest;                      // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd()
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index e0bc7f747..307e11d5b 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -619,7 +619,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
                     pressed = true;
         }
 
-        if (pressed)
+        if (pressed && g.IO.ConfigNavCursorVisibleAuto)
             g.NavCursorVisible = false;
     }
 
@@ -688,7 +688,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
                 }
                 ClearActiveID();
             }
-            if (!(flags & ImGuiButtonFlags_NoNavFocus))
+            if (!(flags & ImGuiButtonFlags_NoNavFocus) && g.IO.ConfigNavCursorVisibleAuto)
                 g.NavCursorVisible = false;
         }
         else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
@@ -7001,7 +7001,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
         if (!g.NavHighlightItemUnderNav && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
         {
             SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, WindowRectAbsToRel(window, bb)); // (bb == NavRect)
-            g.NavCursorVisible = false;
+            if (g.IO.ConfigNavCursorVisibleAuto)
+                g.NavCursorVisible = false;
         }
     }
     if (pressed)
@@ -8624,7 +8625,12 @@ void ImGui::EndMenuBar()
             IM_ASSERT(window->DC.NavLayersActiveMaskNext & (1 << layer)); // Sanity check (FIXME: Seems unnecessary)
             FocusWindow(window);
             SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
-            g.NavCursorVisible = false; // Hide nav cursor for the current frame so we don't see the intermediary selection.
+            // FIXME-NAV: How to deal with this when not using g.IO.ConfigNavCursorVisibleAuto?
+            if (g.NavCursorVisible)
+            {
+                g.NavCursorVisible = false; // Hide nav cursor for the current frame so we don't see the intermediary selection. Will be set again
+                g.NavCursorHideFrames = 2;
+            }
             g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
             NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat
         }

From 83b64b8be222248d9d15a4f9325ddf5f1e97ddbc Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 21:33:35 +0200
Subject: [PATCH 0453/2359] Version 1.91.4

---
 docs/CHANGELOG.txt | 10 +++++-----
 imgui.cpp          |  2 +-
 imgui.h            |  6 +++---
 imgui_demo.cpp     |  2 +-
 imgui_draw.cpp     |  2 +-
 imgui_internal.h   |  2 +-
 imgui_tables.cpp   |  2 +-
 imgui_widgets.cpp  |  2 +-
 8 files changed, 14 insertions(+), 14 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 3279969a2..b7b8df333 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -36,18 +36,18 @@ HOW TO UPDATE?
 - Please report any issue!
 
 -----------------------------------------------------------------------
- VERSION 1.91.4 WIP (In Progress)
+ VERSION 1.91.4 (Released 2024-10-18)
 -----------------------------------------------------------------------
 
 Breaking changes:
 
-- Style: renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor, for consistency with newly
-  exposed and reworked features. Kept inline redirection enum (will obsolete).
+- Style: renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor, for consistency with 
+  newly exposed and reworked features. Kept inline redirection enum (will obsolete).
 - The typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
   - This removes the requirement to redefine it for backends which are e.g. storing
     descriptor sets or other 64-bits structures when building on 32-bits archs
     (namely our DX12 and Vulkan backends). It therefore simplify various building scripts/helpers.
-  - You may have compile-time issues if you were casting to 'void*' instead of 'ImTextureID'
+  - You may have compile-time warnings if you were casting to 'void*' instead of 'ImTextureID'
     when passing your types to functions taking ImTextureID values, e.g. ImGui::Image().
     In doubt it is almost always better to do an intermediate intptr_t cast, since it
     allows casting any pointer/integer type without warning:
@@ -109,7 +109,7 @@ Other changes:
 - InputText: ensure mouse cursor shape is set regardless of whether keyboard mode is 
   enabled or not. (#6417)
 - InputScalar: added an assert to clarify that ImGuiInputTextFlags_EnterReturnsTrue is not
-  supported by InputFloat, InputInt, InputScalar etc. widgets. It actually never was. (#8065)
+  supported by InputFloat, InputInt, InputScalar etc. widgets. It actually never was. (#8065, #3946)
 - imgui_freetype: Added support for plutosvg (as an alternative to lunasvg) to render 
   OpenType SVG fonts. Requires defining IMGUI_ENABLE_FREETYPE_PLUTOSVG along with IMGUI_ENABLE_FREETYPE.
   Providing headers/librairies for plutosvg + plutovg is up to you (see #7927 for help).
diff --git a/imgui.cpp b/imgui.cpp
index 0ebd61dc5..f85d4f139 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4 WIP
+// dear imgui, v1.91.4
 // (main code and documentation)
 
 // Help:
diff --git a/imgui.h b/imgui.h
index 73705cd36..22f992fa9 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4 WIP
+// dear imgui, v1.91.4
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.4 WIP"
-#define IMGUI_VERSION_NUM   19136
+#define IMGUI_VERSION       "1.91.4"
+#define IMGUI_VERSION_NUM   19140
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 668c5c0ee..5849e11ef 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4 WIP
+// dear imgui, v1.91.4
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 57b7d3ba2..2fba4993f 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4 WIP
+// dear imgui, v1.91.4
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index 97a51a355..c9ddceb34 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4 WIP
+// dear imgui, v1.91.4
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 1f8035cde..598496be4 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4 WIP
+// dear imgui, v1.91.4
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 307e11d5b..dea089c26 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4 WIP
+// dear imgui, v1.91.4
 // (widgets code)
 
 /*

From 99109c0b3b052cffa154a9295440f68868a39f74 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 18 Oct 2024 22:04:03 +0200
Subject: [PATCH 0454/2359] Amend Changelog, oops didn't get it in the previous
 commit.

---
 docs/CHANGELOG.txt | 30 ++++++++++++++++--------------
 1 file changed, 16 insertions(+), 14 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index b7b8df333..81aec81ea 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -55,7 +55,7 @@ Breaking changes:
     - May warn:     ImGui::Image((void*)(intptr_t)MyTextureData, ...);
     - Won't warn:   ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...);
   - Note that you can always define ImTextureID to be your own high-level structures
-    (with dedicated constructors) if you like.
+    (with dedicated constructors and extra render parameters) if you like.
 - IO: moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
 - IO: moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool 
   (note the inverted value!). (#2517, #2009)
@@ -65,9 +65,9 @@ Breaking changes:
 Other changes:
 
 - IO: added 'void* platform_io.Renderer_RenderState' which is set during the
-  ImGui_ImplXXXX_RenderDrawData() of standard backend to expose selected render
-  state to draw callbacks. (#6969, #5834, #7468, #3590)
-- IO: WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
+  ImGui_ImplXXXX_RenderDrawData() of standard backends to expose selected render
+  states to your draw callbacks. (#6969, #5834, #7468, #3590)
+- IO: io.WantCaptureKeyboard is never set when ImGuiConfigFlags_NoKeyboard is enabled. (#4921)
 - Error Handling: turned a few more functions into recoverable errors. (#1651)
 - Nav (Keyboard/Gamepad navigation):
   - Nav: added io.ConfigNavCursorVisibleAuto and io.ConfigNavCursorVisibleAlways to configure
@@ -80,15 +80,14 @@ Other changes:
   - Nav: added io.ConfigNavEscapeClearFocusItem and io.ConfigNavEscapeClearFocusWindow to change
     how pressing Escape affects navigation. (#8059, #2048, #1074, #3200)
     - Set io.ConfigNavEscapeClearFocusItem = true (default) to clear focused item and highlight.
-    - Set io.ConfigNavEscapeClearFocusItem = false for Escape to not have a specific effect.
+    - Set io.ConfigNavEscapeClearFocusItem = false for Escape to not have an effect.
     - Set io.ConfigNavEscapeClearFocusWindow = true to completely unfocus the dear imgui window,
       is for some reason your app relies on imgui focus to take other decisions.  
-  - Nav: pressing escape to hide nav highlight doesn't clear location from when Ctrl+Tabbing 
-    back into same window later.
-  - Nav: fixed Ctrl+Tab so when starting with no focused window it starts from the top-most
-    window. (#3200)
-  - Nav: rectangle highlight not rendered for items with ImGuiItemFlags_NoNav. Can be relevant
-    when e.g activating the item with mouse, then Ctrl+Tabbing back and forth. 
+  - Nav: pressing escape to hide the navigation cursor doesn't clear location, so it may be
+    restored when Ctrl+Tabbing back into the same window later.
+  - Nav: fixed Ctrl+Tab initiated with no focused window from skipping the top-most window. (#3200)
+  - Nav: navigation cursor is not rendered for items with `ImGuiItemFlags_NoNav`. Can be relevant 
+    when e.g activating a _NoNav item with mouse, then Ctrl+Tabbing back and forth.
 - Disabled: clicking a disabled item focuses parent window. (#8064) 
 - InvisibleButton, Nav: fixed an issue when InvisibleButton() would be navigable into but
   not display navigation highlight. Properly navigation on it by default. (#8057)
@@ -103,9 +102,11 @@ Other changes:
     We store them in a buffer stored inside the drawlist. ImDrawCmd::UserCallbackData 
     will point inside that buffer so you have to retrieve data from there. Your callback
     may need to use ImDrawCmd::UserCallbackDataSize if you expect dynamically-sized data.
-- Tables: fixed initial auto-sizing issue with synched-instances. (#8045, #7218)
+  - Note that we use a raw type-less copy.
+- Tables: fixed initial auto-sizing issue with synced-instances. (#8045, #7218)
 - InputText: fixed an issue with not declaring ownership of Delete/Backspace/Arrow keys,
-  preventing use of external shortcuts not guarded by an ActiveId check. (#8048) [@geertbleyen]
+  preventing use of external shortcuts that are not guarded by an ActiveId check. (#8048) 
+  [@geertbleyen]
 - InputText: ensure mouse cursor shape is set regardless of whether keyboard mode is 
   enabled or not. (#6417)
 - InputScalar: added an assert to clarify that ImGuiInputTextFlags_EnterReturnsTrue is not
@@ -115,7 +116,8 @@ Other changes:
   Providing headers/librairies for plutosvg + plutovg is up to you (see #7927 for help).
   (#7927, #7187, #6591, #6607) [@pthom]
 - Backends: DX11, DX12, SDLRenderer2/3. Vulkan, WGPU: expose selected state in
-  ImGui_ImplXXXX_RenderState structures during render loop. (#6969, #5834, #7468, #3590)
+  ImGui_ImplXXXX_RenderState structures during render loop user draw callbacks. 
+  (#6969, #5834, #7468, #3590)
 - Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan, WGPU: Changed default texture sampler
   to Clamp instead of Repeat/Wrap. (#7468, #7511, #5999, #5502, #7230)
 

From 41f02825fc5ca54596fab73b57157d85af3130b2 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 23 Oct 2024 12:16:00 +0200
Subject: [PATCH 0455/2359] Version 1.91.5 WIP

---
 docs/CHANGELOG.txt | 8 ++++++++
 imgui.cpp          | 2 +-
 imgui.h            | 6 +++---
 imgui_demo.cpp     | 2 +-
 imgui_draw.cpp     | 2 +-
 imgui_internal.h   | 2 +-
 imgui_tables.cpp   | 2 +-
 imgui_widgets.cpp  | 2 +-
 8 files changed, 17 insertions(+), 9 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 81aec81ea..2342c4726 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -35,6 +35,14 @@ HOW TO UPDATE?
   and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users.
 - Please report any issue!
 
+-----------------------------------------------------------------------
+ VERSION 1.91.5 WIP (In Progress)
+-----------------------------------------------------------------------
+
+Breaking changes:
+
+Other changes:
+
 -----------------------------------------------------------------------
  VERSION 1.91.4 (Released 2024-10-18)
 -----------------------------------------------------------------------
diff --git a/imgui.cpp b/imgui.cpp
index f85d4f139..0d704e166 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.91.5 WIP
 // (main code and documentation)
 
 // Help:
diff --git a/imgui.h b/imgui.h
index 22f992fa9..04f958eec 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.91.5 WIP
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.4"
-#define IMGUI_VERSION_NUM   19140
+#define IMGUI_VERSION       "1.91.5 WIP"
+#define IMGUI_VERSION_NUM   19141
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 5849e11ef..f24254e2e 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.91.5 WIP
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 2fba4993f..01723b35c 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.91.5 WIP
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index c9ddceb34..0c441a260 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.91.5 WIP
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 598496be4..03007bb79 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.91.5 WIP
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index dea089c26..757eb8ab6 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.4
+// dear imgui, v1.91.5 WIP
 // (widgets code)
 
 /*

From 4994e75852a8140072cc5dd74fac4638150a4a9e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 23 Oct 2024 12:40:20 +0200
Subject: [PATCH 0456/2359] Backends: DX12: Unmap() call specify written range.

The range is informational and may be used by debug tools.
---
 backends/imgui_impl_dx12.cpp | 11 +++++++++--
 docs/CHANGELOG.txt           |  3 +++
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index be117b6c1..7a428a1a5 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -16,6 +16,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
 //  2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
@@ -218,9 +219,9 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL
     }
 
     // Upload vertex/index data into a single contiguous GPU buffer
+    // During Map() we specify a null read range (as per DX12 API, this is informational and for tooling only)
     void* vtx_resource, *idx_resource;
-    D3D12_RANGE range;
-    memset(&range, 0, sizeof(D3D12_RANGE));
+    D3D12_RANGE range = { 0, 0 };
     if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
         return;
     if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
@@ -235,7 +236,13 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL
         vtx_dst += draw_list->VtxBuffer.Size;
         idx_dst += draw_list->IdxBuffer.Size;
     }
+
+    // During Unmap() we specify the written range (as per DX12 API, this is informational and for tooling only)
+    range.End = (SIZE_T)((intptr_t)vtx_dst - (intptr_t)vtx_resource);
+    IM_ASSERT(range.End == draw_data->TotalVtxCount * sizeof(ImDrawVert));
     fr->VertexBuffer->Unmap(0, &range);
+    range.End = (SIZE_T)((intptr_t)idx_dst - (intptr_t)idx_resource);
+    IM_ASSERT(range.End == draw_data->TotalIdxCount * sizeof(ImDrawIdx));
     fr->IndexBuffer->Unmap(0, &range);
 
     // Setup desired DX state
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 2342c4726..f66866e9e 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,9 @@ Breaking changes:
 
 Other changes:
 
+- Backends: DX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
+
+
 -----------------------------------------------------------------------
  VERSION 1.91.4 (Released 2024-10-18)
 -----------------------------------------------------------------------

From 062e580436e60e2e991268ef911773969a1b5774 Mon Sep 17 00:00:00 2001
From: Eugene Sandulenko 
Date: Thu, 24 Oct 2024 09:26:57 +0200
Subject: [PATCH 0457/2359] Fixed copy/paste error in DebugModeWindow() (#8094)

---
 imgui.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui.cpp b/imgui.cpp
index 0d704e166..81f872f7b 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -16351,7 +16351,7 @@ void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
     for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
     {
         ImRect r = window->NavRectRel[layer];
-        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
+        if (r.Min.x >= r.Max.x && r.Min.y >= r.Max.y)
             BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
         else
             BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);

From 06092a9756b5476ad0b36d6f980fe904a87418da Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 24 Oct 2024 14:47:07 +0200
Subject: [PATCH 0458/2359] Backends: SDL2, SDL3: SDL_EVENT_MOUSE_WHEEL event
 doesn't require dividing by 100.0f on Emscripten. (#4019, #6096, #1463)

Ref https://github.com/libsdl-org/SDL/issues/10454#issuecomment-2434187317
---
 backends/imgui_impl_sdl2.cpp | 3 ++-
 backends/imgui_impl_sdl3.cpp | 4 +---
 docs/CHANGELOG.txt           | 3 ++-
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp
index 1abe8b93d..d87f5081e 100644
--- a/backends/imgui_impl_sdl2.cpp
+++ b/backends/imgui_impl_sdl2.cpp
@@ -21,6 +21,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f.
 //  2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190)
 //  2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
 //               - io.GetClipboardTextFn    -> platform_io.Platform_GetClipboardTextFn
@@ -359,7 +360,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
             float wheel_x = -(float)event->wheel.x;
             float wheel_y = (float)event->wheel.y;
 #endif
-#ifdef __EMSCRIPTEN__
+#if defined(__EMSCRIPTEN__) && !SDL_VERSION_ATLEAST(2,31,0)
             wheel_x /= 100.0f;
 #endif
             io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp
index 517ba1ada..ca960cad5 100644
--- a/backends/imgui_impl_sdl3.cpp
+++ b/backends/imgui_impl_sdl3.cpp
@@ -21,6 +21,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten.
 //  2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807)
 //  2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
 //               - io.GetClipboardTextFn    -> platform_io.Platform_GetClipboardTextFn
@@ -338,9 +339,6 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
             //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
             float wheel_x = -event->wheel.x;
             float wheel_y = event->wheel.y;
-    #ifdef __EMSCRIPTEN__
-            wheel_x /= 100.0f;
-    #endif
             io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
             io.AddMouseWheelEvent(wheel_x, wheel_y);
             return true;
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index f66866e9e..997acce28 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -44,7 +44,8 @@ Breaking changes:
 Other changes:
 
 - Backends: DX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
-
+- Backends: SDL3: Update for SDL3 api change: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f 
+  on Emscripten target. (#4019, #6096, #1463)
 
 -----------------------------------------------------------------------
  VERSION 1.91.4 (Released 2024-10-18)

From a855bd8df3ca172e17fc7bb5ac88e0a76bd9b965 Mon Sep 17 00:00:00 2001
From: Eugene Sandulenko 
Date: Thu, 24 Oct 2024 00:20:13 +0200
Subject: [PATCH 0459/2359] Backends: SDL2: Replace
 SDL_Vulkan_GetDrawableSize() forward declaration with the actual include.
 (#8095, #7967, #3190)

---
 backends/imgui_impl_sdl2.cpp | 2 +-
 docs/CHANGELOG.txt           | 5 +++--
 2 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp
index d87f5081e..7a8af3b82 100644
--- a/backends/imgui_impl_sdl2.cpp
+++ b/backends/imgui_impl_sdl2.cpp
@@ -115,7 +115,7 @@
 #endif
 #define SDL_HAS_VULKAN                      SDL_VERSION_ATLEAST(2,0,6)
 #if SDL_HAS_VULKAN
-extern "C" { extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window* window, int* w, int* h); }
+#include 
 #endif
 
 // SDL Data
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 997acce28..2e8d2823f 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -44,8 +44,9 @@ Breaking changes:
 Other changes:
 
 - Backends: DX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
-- Backends: SDL3: Update for SDL3 api change: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f 
-  on Emscripten target. (#4019, #6096, #1463)
+- Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the actual include. (#8095, #7967, #3190) [@sev-] 
+- Backends: SDL2, SDL3: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing 
+  by 100.0f on Emscripten target. (#4019, #6096, #1463)
 
 -----------------------------------------------------------------------
  VERSION 1.91.4 (Released 2024-10-18)

From b4033b37ad7980e34a7335aac8375ffc109ef818 Mon Sep 17 00:00:00 2001
From: Nicolas Chavez 
Date: Mon, 21 Oct 2024 14:19:31 +0200
Subject: [PATCH 0460/2359] Backends: WGPU: update for Dawn WGPU String usage.
 (#8082, #8083)

---
 backends/imgui_impl_wgpu.cpp | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index 95f1b0c63..075f74734 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -17,6 +17,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-10-14: Update Dawn support for change of string usages. (#8082, #8083)
 //  2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-09-16: Added support for optional IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU define to handle ever-changing native implementations. (#7977)
@@ -275,7 +276,11 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c
 
     WGPUProgrammableStageDescriptor stage_desc = {};
     stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc);
+#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+    stage_desc.entryPoint = { "main", WGPU_STRLEN };
+#else
     stage_desc.entryPoint = "main";
+#endif
     return stage_desc;
 }
 
@@ -388,6 +393,9 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
         {
             nullptr,
             "Dear ImGui Vertex buffer",
+#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+            WGPU_STRLEN,
+#endif
             WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
             MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4),
             false
@@ -412,6 +420,9 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
         {
             nullptr,
             "Dear ImGui Index buffer",
+#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+            WGPU_STRLEN,
+#endif
             WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
             MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4),
             false
@@ -522,7 +533,11 @@ static void ImGui_ImplWGPU_CreateFontsTexture()
     // Upload texture to graphics system
     {
         WGPUTextureDescriptor tex_desc = {};
+#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+        tex_desc.label = { "Dear ImGui Font Texture", WGPU_STRLEN };
+#else
         tex_desc.label = "Dear ImGui Font Texture";
+#endif
         tex_desc.dimension = WGPUTextureDimension_2D;
         tex_desc.size.width = width;
         tex_desc.size.height = height;
@@ -585,6 +600,9 @@ static void ImGui_ImplWGPU_CreateUniformBuffer()
     {
         nullptr,
         "Dear ImGui Uniform buffer",
+#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
+        WGPU_STRLEN,
+#endif
         WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
         MEMALIGN(sizeof(Uniforms), 16),
         false

From a908d73c16a4c539b320b9f5cb001c70908ae065 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 24 Oct 2024 17:24:47 +0200
Subject: [PATCH 0461/2359] Backends: avoid missing -Wmissing-declaration
 warning.  (#8087, #7997)

---
 backends/imgui_impl_allegro5.cpp | 1 +
 backends/imgui_impl_glfw.cpp     | 1 +
 backends/imgui_impl_osx.mm       | 1 +
 backends/imgui_impl_sdl2.cpp     | 1 +
 backends/imgui_impl_sdl3.cpp     | 1 +
 backends/imgui_impl_win32.cpp    | 1 +
 6 files changed, 6 insertions(+)

diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp
index 9c2571623..d5d65703e 100644
--- a/backends/imgui_impl_allegro5.cpp
+++ b/backends/imgui_impl_allegro5.cpp
@@ -311,6 +311,7 @@ static void ImGui_ImplAllegro5_SetClipboardText(ImGuiContext*, const char* text)
 #endif
 
 // Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code);
 ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code)
 {
     switch (key_code)
diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp
index c725e9c01..774fb0d5d 100644
--- a/backends/imgui_impl_glfw.cpp
+++ b/backends/imgui_impl_glfw.cpp
@@ -187,6 +187,7 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData()
 // Functions
 
 // Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode);
 ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode)
 {
     IM_UNUSED(scancode);
diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm
index 3115bf1c2..de9b57408 100644
--- a/backends/imgui_impl_osx.mm
+++ b/backends/imgui_impl_osx.mm
@@ -261,6 +261,7 @@ static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view);
 // Functions
 
 // Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code);
 ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code)
 {
     switch (key_code)
diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp
index 7a8af3b82..529ca79e0 100644
--- a/backends/imgui_impl_sdl2.cpp
+++ b/backends/imgui_impl_sdl2.cpp
@@ -182,6 +182,7 @@ static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImG
 }
 
 // Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
 ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
 {
     IM_UNUSED(scancode);
diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp
index ca960cad5..de8b53158 100644
--- a/backends/imgui_impl_sdl3.cpp
+++ b/backends/imgui_impl_sdl3.cpp
@@ -161,6 +161,7 @@ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view
 }
 
 // Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
 ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
 {
     // Keypad doesn't have individual key values in SDL3
diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index bbfa1a5be..477d54abe 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -421,6 +421,7 @@ void    ImGui_ImplWin32_NewFrame()
 
 // Map VK_xxx to ImGuiKey_xxx.
 // Not static to allow third-party code to use that if they want to (but undocumented)
+ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam);
 ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam)
 {
     // There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED.

From 1039b7f543cf18a3349b7411399ce3ed4900ce38 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 24 Oct 2024 17:49:01 +0200
Subject: [PATCH 0462/2359] Examples: added more build_win64.bat helpers.

---
 examples/example_glfw_vulkan/build_win64.bat  |  3 ++-
 examples/example_sdl2_vulkan/build_win32.bat  |  4 ++++
 examples/example_sdl2_vulkan/build_win64.bat  | 14 ++++++++++++++
 examples/example_sdl3_opengl3/build_win32.bat |  8 +++++++-
 examples/example_sdl3_opengl3/build_win64.bat | 14 ++++++++++++++
 5 files changed, 41 insertions(+), 2 deletions(-)
 create mode 100644 examples/example_sdl2_vulkan/build_win64.bat
 create mode 100644 examples/example_sdl3_opengl3/build_win64.bat

diff --git a/examples/example_glfw_vulkan/build_win64.bat b/examples/example_glfw_vulkan/build_win64.bat
index 54e40e3e8..ca9b788d8 100644
--- a/examples/example_glfw_vulkan/build_win64.bat
+++ b/examples/example_glfw_vulkan/build_win64.bat
@@ -1,5 +1,6 @@
-@REM Build for Visual Studio compiler. Run your copy of amd64/vcvars32.bat to setup 64-bit command-line compiler.
+@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup 64-bit command-line compiler.
 
+@set OUT_EXE=example_glfw_vulkan
 @set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include /I %VULKAN_SDK%\include
 @set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp
 @set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib
diff --git a/examples/example_sdl2_vulkan/build_win32.bat b/examples/example_sdl2_vulkan/build_win32.bat
index 977a2c7e4..f634aba00 100644
--- a/examples/example_sdl2_vulkan/build_win32.bat
+++ b/examples/example_sdl2_vulkan/build_win32.bat
@@ -8,3 +8,7 @@
 @set OUT_DIR=Debug
 mkdir %OUT_DIR%
 cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
+
+@set OUT_DIR=Release
+@REM mkdir %OUT_DIR%
+@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
diff --git a/examples/example_sdl2_vulkan/build_win64.bat b/examples/example_sdl2_vulkan/build_win64.bat
new file mode 100644
index 000000000..5d315cca2
--- /dev/null
+++ b/examples/example_sdl2_vulkan/build_win64.bat
@@ -0,0 +1,14 @@
+@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler.
+
+@set OUT_EXE=example_sdl2_vulkan
+@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I %VULKAN_SDK%\include
+@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp
+@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib SDL2.lib SDL2main.lib shell32.lib vulkan-1.lib
+
+@set OUT_DIR=Debug
+mkdir %OUT_DIR%
+cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
+
+@set OUT_DIR=Release
+@REM mkdir %OUT_DIR%
+@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
diff --git a/examples/example_sdl3_opengl3/build_win32.bat b/examples/example_sdl3_opengl3/build_win32.bat
index 5b8d5f871..5bed40ac1 100644
--- a/examples/example_sdl3_opengl3/build_win32.bat
+++ b/examples/example_sdl3_opengl3/build_win32.bat
@@ -1,8 +1,14 @@
 @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
-@set OUT_DIR=Debug
+
 @set OUT_EXE=example_sdl3_opengl3
 @set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include
 @set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp
 @set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib opengl32.lib shell32.lib
+
+@set OUT_DIR=Debug
 mkdir %OUT_DIR%
 cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
+
+@set OUT_DIR=Release
+@REM mkdir %OUT_DIR%
+@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
diff --git a/examples/example_sdl3_opengl3/build_win64.bat b/examples/example_sdl3_opengl3/build_win64.bat
new file mode 100644
index 000000000..87c6bb8b5
--- /dev/null
+++ b/examples/example_sdl3_opengl3/build_win64.bat
@@ -0,0 +1,14 @@
+@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler.
+
+@set OUT_EXE=example_sdl3_opengl3
+@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include
+@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp
+@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x64 SDL3.lib opengl32.lib shell32.lib
+
+@set OUT_DIR=Debug
+mkdir %OUT_DIR%
+cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
+
+@set OUT_DIR=Release
+@REM mkdir %OUT_DIR%
+@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console

From ccb6646baeac88d276078ebade5616f4c6d7c03a Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 24 Oct 2024 18:07:22 +0200
Subject: [PATCH 0463/2359] Examples: added SDL3+Vulkan example. (#8084, #8085)

---
 docs/CHANGELOG.txt                            |   7 +-
 examples/example_sdl3_vulkan/build_win32.bat  |  14 +
 examples/example_sdl3_vulkan/build_win64.bat  |  14 +
 .../example_sdl3_vulkan.vcxproj               | 190 ++++++
 .../example_sdl3_vulkan.vcxproj.filters       |  64 ++
 examples/example_sdl3_vulkan/main.cpp         | 587 ++++++++++++++++++
 examples/imgui_examples.sln                   |  10 +
 7 files changed, 884 insertions(+), 2 deletions(-)
 create mode 100644 examples/example_sdl3_vulkan/build_win32.bat
 create mode 100644 examples/example_sdl3_vulkan/build_win64.bat
 create mode 100644 examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj
 create mode 100644 examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj.filters
 create mode 100644 examples/example_sdl3_vulkan/main.cpp

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 2e8d2823f..194803ac6 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,10 +43,13 @@ Breaking changes:
 
 Other changes:
 
-- Backends: DX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
-- Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the actual include. (#8095, #7967, #3190) [@sev-] 
+- Backends: DX12: Unmap() call specify written range. The range is informational and
+  may be used by debug tools.
+- Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the 
+  actual include. (#8095, #7967, #3190) [@sev-] 
 - Backends: SDL2, SDL3: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing 
   by 100.0f on Emscripten target. (#4019, #6096, #1463)
+- Examples: Added SDL3+Vulkan example. (#8084, #8085)
 
 -----------------------------------------------------------------------
  VERSION 1.91.4 (Released 2024-10-18)
diff --git a/examples/example_sdl3_vulkan/build_win32.bat b/examples/example_sdl3_vulkan/build_win32.bat
new file mode 100644
index 000000000..3e26d3088
--- /dev/null
+++ b/examples/example_sdl3_vulkan/build_win32.bat
@@ -0,0 +1,14 @@
+@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
+
+@set OUT_EXE=example_sdl3_vulkan
+@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I %VULKAN_SDK%\include
+@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp
+@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 SDL3.lib shell32.lib vulkan-1.lib
+
+@set OUT_DIR=Debug
+mkdir %OUT_DIR%
+cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
+
+@set OUT_DIR=Release
+@REM mkdir %OUT_DIR%
+@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
diff --git a/examples/example_sdl3_vulkan/build_win64.bat b/examples/example_sdl3_vulkan/build_win64.bat
new file mode 100644
index 000000000..5d038d1ee
--- /dev/null
+++ b/examples/example_sdl3_vulkan/build_win64.bat
@@ -0,0 +1,14 @@
+@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler.
+
+@set OUT_EXE=example_sdl3_vulkan
+@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I %VULKAN_SDK%\include
+@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp
+@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib SDL3.lib shell32.lib vulkan-1.lib
+
+@set OUT_DIR=Debug
+mkdir %OUT_DIR%
+cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
+
+@set OUT_DIR=Release
+@REM mkdir %OUT_DIR%
+@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console
diff --git a/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj b/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj
new file mode 100644
index 000000000..d48e4aff3
--- /dev/null
+++ b/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj
@@ -0,0 +1,190 @@
+
+
+  
+    
+      Debug
+      Win32
+    
+    
+      Debug
+      x64
+    
+    
+      Release
+      Win32
+    
+    
+      Release
+      x64
+    
+  
+  
+    {663A7E89-1E42-4222-921C-177F5B5910DF}
+    example_sdl3_vulkan
+    8.1
+  
+  
+  
+    Application
+    true
+    MultiByte
+    v140
+  
+  
+    Application
+    true
+    MultiByte
+    v140
+  
+  
+    Application
+    false
+    true
+    MultiByte
+    v140
+  
+  
+    Application
+    false
+    true
+    MultiByte
+    v140
+  
+  
+  
+  
+  
+    
+  
+  
+    
+  
+  
+    
+  
+  
+    
+  
+  
+  
+    $(ProjectDir)$(Configuration)\
+    $(ProjectDir)$(Configuration)\
+    $(IncludePath)
+  
+  
+    $(ProjectDir)$(Configuration)\
+    $(ProjectDir)$(Configuration)\
+    $(IncludePath)
+  
+  
+    $(ProjectDir)$(Configuration)\
+    $(ProjectDir)$(Configuration)\
+    $(IncludePath)
+  
+  
+    $(ProjectDir)$(Configuration)\
+    $(ProjectDir)$(Configuration)\
+    $(IncludePath)
+  
+  
+    
+      Level4
+      Disabled
+      ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories)
+      _MBCS;%(PreprocessorDefinitions)
+      /utf-8 %(AdditionalOptions)
+    
+    
+      true
+      %VULKAN_SDK%\lib32;%SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories)
+      vulkan-1.lib;SDL3.lib;%(AdditionalDependencies)
+      Console
+      msvcrt.lib
+    
+  
+  
+    
+      Level4
+      Disabled
+      ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories)
+      _MBCS;%(PreprocessorDefinitions)
+      /utf-8 %(AdditionalOptions)
+    
+    
+      true
+      %VULKAN_SDK%\lib;%SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories)
+      vulkan-1.lib;SDL3.lib;%(AdditionalDependencies)
+      Console
+      msvcrt.lib
+    
+  
+  
+    
+      Level4
+      MaxSpeed
+      true
+      true
+      ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories)
+      false
+      _MBCS;%(PreprocessorDefinitions)
+      /utf-8 %(AdditionalOptions)
+    
+    
+      true
+      true
+      true
+      %VULKAN_SDK%\lib32;%SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories)
+      vulkan-1.lib;SDL3.lib;%(AdditionalDependencies)
+      Console
+      
+      
+    
+  
+  
+    
+      Level4
+      MaxSpeed
+      true
+      true
+      ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories)
+      false
+      _MBCS;%(PreprocessorDefinitions)
+      /utf-8 %(AdditionalOptions)
+    
+    
+      true
+      true
+      true
+      %VULKAN_SDK%\lib;%SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories)
+      vulkan-1.lib;SDL3.lib;%(AdditionalDependencies)
+      Console
+      
+      
+    
+  
+  
+    
+    
+    
+    
+    
+    
+    
+    
+  
+  
+    
+    
+    
+    
+    
+  
+  
+    
+    
+    
+  
+  
+  
+  
+
\ No newline at end of file
diff --git a/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj.filters b/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj.filters
new file mode 100644
index 000000000..46ebb5829
--- /dev/null
+++ b/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj.filters
@@ -0,0 +1,64 @@
+
+
+  
+    
+      {20b90ce4-7fcb-4731-b9a0-075f875de82d}
+    
+    
+      {f18ab499-84e1-499f-8eff-9754361e0e52}
+      cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
+    
+  
+  
+    
+      imgui
+    
+    
+      imgui
+    
+    
+      imgui
+    
+    
+      sources
+    
+    
+      sources
+    
+    
+      sources
+    
+    
+      imgui
+    
+    
+      imgui
+    
+  
+  
+    
+      imgui
+    
+    
+      imgui
+    
+    
+      imgui
+    
+    
+      sources
+    
+    
+      sources
+    
+  
+  
+    
+    
+      imgui
+    
+    
+      imgui
+    
+  
+
\ No newline at end of file
diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp
new file mode 100644
index 000000000..dde3c0d4c
--- /dev/null
+++ b/examples/example_sdl3_vulkan/main.cpp
@@ -0,0 +1,587 @@
+// Dear ImGui: standalone example application for SDL3 + Vulkan
+
+// Learn about Dear ImGui:
+// - FAQ                  https://dearimgui.com/faq
+// - Getting Started      https://dearimgui.com/getting-started
+// - Documentation        https://dearimgui.com/docs (same as your local docs/ folder).
+// - Introduction, links and more at the top of imgui.cpp
+
+// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
+// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
+//   You will use those if you want to use this rendering backend in your engine/app.
+// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by
+//   the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code.
+// Read comments in imgui_impl_vulkan.h.
+
+#include "imgui.h"
+#include "imgui_impl_sdl3.h"
+#include "imgui_impl_vulkan.h"
+#include           // printf, fprintf
+#include          // abort
+#include 
+#include 
+
+// This example doesn't compile with Emscripten yet! Awaiting SDL3 support.
+#ifdef __EMSCRIPTEN__
+#include "../libs/emscripten/emscripten_mainloop_stub.h"
+#endif
+
+// Volk headers
+#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
+#define VOLK_IMPLEMENTATION
+#include 
+#endif
+
+//#define APP_USE_UNLIMITED_FRAME_RATE
+#ifdef _DEBUG
+#define APP_USE_VULKAN_DEBUG_REPORT
+#endif
+
+// Data
+static VkAllocationCallbacks*   g_Allocator = nullptr;
+static VkInstance               g_Instance = VK_NULL_HANDLE;
+static VkPhysicalDevice         g_PhysicalDevice = VK_NULL_HANDLE;
+static VkDevice                 g_Device = VK_NULL_HANDLE;
+static uint32_t                 g_QueueFamily = (uint32_t)-1;
+static VkQueue                  g_Queue = VK_NULL_HANDLE;
+static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE;
+static VkPipelineCache          g_PipelineCache = VK_NULL_HANDLE;
+static VkDescriptorPool         g_DescriptorPool = VK_NULL_HANDLE;
+
+static ImGui_ImplVulkanH_Window g_MainWindowData;
+static uint32_t                 g_MinImageCount = 2;
+static bool                     g_SwapChainRebuild = false;
+
+static void check_vk_result(VkResult err)
+{
+    if (err == 0)
+        return;
+    fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err);
+    if (err < 0)
+        abort();
+}
+
+#ifdef APP_USE_VULKAN_DEBUG_REPORT
+static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData)
+{
+    (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments
+    fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage);
+    return VK_FALSE;
+}
+#endif // APP_USE_VULKAN_DEBUG_REPORT
+
+static bool IsExtensionAvailable(const ImVector& properties, const char* extension)
+{
+    for (const VkExtensionProperties& p : properties)
+        if (strcmp(p.extensionName, extension) == 0)
+            return true;
+    return false;
+}
+
+static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice()
+{
+    uint32_t gpu_count;
+    VkResult err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, nullptr);
+    check_vk_result(err);
+    IM_ASSERT(gpu_count > 0);
+
+    ImVector gpus;
+    gpus.resize(gpu_count);
+    err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus.Data);
+    check_vk_result(err);
+
+    // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers
+    // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple
+    // dedicated GPUs) is out of scope of this sample.
+    for (VkPhysicalDevice& device : gpus)
+    {
+        VkPhysicalDeviceProperties properties;
+        vkGetPhysicalDeviceProperties(device, &properties);
+        if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
+            return device;
+    }
+
+    // Use first GPU (Integrated) is a Discrete one is not available.
+    if (gpu_count > 0)
+        return gpus[0];
+    return VK_NULL_HANDLE;
+}
+
+static void SetupVulkan(ImVector instance_extensions)
+{
+    VkResult err;
+#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
+    volkInitialize();
+#endif
+
+    // Create Vulkan Instance
+    {
+        VkInstanceCreateInfo create_info = {};
+        create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
+
+        // Enumerate available extensions
+        uint32_t properties_count;
+        ImVector properties;
+        vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, nullptr);
+        properties.resize(properties_count);
+        err = vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, properties.Data);
+        check_vk_result(err);
+
+        // Enable required extensions
+        if (IsExtensionAvailable(properties, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME))
+            instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
+#ifdef VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME
+        if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME))
+        {
+            instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
+            create_info.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
+        }
+#endif
+
+        // Enabling validation layers
+#ifdef APP_USE_VULKAN_DEBUG_REPORT
+        const char* layers[] = { "VK_LAYER_KHRONOS_validation" };
+        create_info.enabledLayerCount = 1;
+        create_info.ppEnabledLayerNames = layers;
+        instance_extensions.push_back("VK_EXT_debug_report");
+#endif
+
+        // Create Vulkan Instance
+        create_info.enabledExtensionCount = (uint32_t)instance_extensions.Size;
+        create_info.ppEnabledExtensionNames = instance_extensions.Data;
+        err = vkCreateInstance(&create_info, g_Allocator, &g_Instance);
+        check_vk_result(err);
+#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
+        volkLoadInstance(g_Instance);
+#endif
+
+        // Setup the debug report callback
+#ifdef APP_USE_VULKAN_DEBUG_REPORT
+        auto f_vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT");
+        IM_ASSERT(f_vkCreateDebugReportCallbackEXT != nullptr);
+        VkDebugReportCallbackCreateInfoEXT debug_report_ci = {};
+        debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
+        debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
+        debug_report_ci.pfnCallback = debug_report;
+        debug_report_ci.pUserData = nullptr;
+        err = f_vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport);
+        check_vk_result(err);
+#endif
+    }
+
+    // Select Physical Device (GPU)
+    g_PhysicalDevice = SetupVulkan_SelectPhysicalDevice();
+
+    // Select graphics queue family
+    {
+        uint32_t count;
+        vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, nullptr);
+        VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count);
+        vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues);
+        for (uint32_t i = 0; i < count; i++)
+            if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
+            {
+                g_QueueFamily = i;
+                break;
+            }
+        free(queues);
+        IM_ASSERT(g_QueueFamily != (uint32_t)-1);
+    }
+
+    // Create Logical Device (with 1 queue)
+    {
+        ImVector device_extensions;
+        device_extensions.push_back("VK_KHR_swapchain");
+
+        // Enumerate physical device extension
+        uint32_t properties_count;
+        ImVector properties;
+        vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, nullptr);
+        properties.resize(properties_count);
+        vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, properties.Data);
+#ifdef VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME
+        if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME))
+            device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME);
+#endif
+
+        const float queue_priority[] = { 1.0f };
+        VkDeviceQueueCreateInfo queue_info[1] = {};
+        queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
+        queue_info[0].queueFamilyIndex = g_QueueFamily;
+        queue_info[0].queueCount = 1;
+        queue_info[0].pQueuePriorities = queue_priority;
+        VkDeviceCreateInfo create_info = {};
+        create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
+        create_info.queueCreateInfoCount = sizeof(queue_info) / sizeof(queue_info[0]);
+        create_info.pQueueCreateInfos = queue_info;
+        create_info.enabledExtensionCount = (uint32_t)device_extensions.Size;
+        create_info.ppEnabledExtensionNames = device_extensions.Data;
+        err = vkCreateDevice(g_PhysicalDevice, &create_info, g_Allocator, &g_Device);
+        check_vk_result(err);
+        vkGetDeviceQueue(g_Device, g_QueueFamily, 0, &g_Queue);
+    }
+
+    // Create Descriptor Pool
+    // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that)
+    // If you wish to load e.g. additional textures you may need to alter pools sizes.
+    {
+        VkDescriptorPoolSize pool_sizes[] =
+        {
+            { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 },
+        };
+        VkDescriptorPoolCreateInfo pool_info = {};
+        pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
+        pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
+        pool_info.maxSets = 1;
+        pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes);
+        pool_info.pPoolSizes = pool_sizes;
+        err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool);
+        check_vk_result(err);
+    }
+}
+
+// All the ImGui_ImplVulkanH_XXX structures/functions are optional helpers used by the demo.
+// Your real engine/app may not use them.
+static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height)
+{
+    wd->Surface = surface;
+
+    // Check for WSI support
+    VkBool32 res;
+    vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, wd->Surface, &res);
+    if (res != VK_TRUE)
+    {
+        fprintf(stderr, "Error no WSI support on physical device 0\n");
+        exit(-1);
+    }
+
+    // Select Surface Format
+    const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM };
+    const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
+    wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace);
+
+    // Select Present Mode
+#ifdef APP_UNLIMITED_FRAME_RATE
+    VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR };
+#else
+    VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR };
+#endif
+    wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_ARRAYSIZE(present_modes));
+    //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode);
+
+    // Create SwapChain, RenderPass, Framebuffer, etc.
+    IM_ASSERT(g_MinImageCount >= 2);
+    ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount);
+}
+
+static void CleanupVulkan()
+{
+    vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator);
+
+#ifdef APP_USE_VULKAN_DEBUG_REPORT
+    // Remove the debug report callback
+    auto f_vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT");
+    f_vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator);
+#endif // APP_USE_VULKAN_DEBUG_REPORT
+
+    vkDestroyDevice(g_Device, g_Allocator);
+    vkDestroyInstance(g_Instance, g_Allocator);
+}
+
+static void CleanupVulkanWindow()
+{
+    ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator);
+}
+
+static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data)
+{
+    VkResult err;
+
+    VkSemaphore image_acquired_semaphore  = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore;
+    VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore;
+    err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex);
+    if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR)
+    {
+        g_SwapChainRebuild = true;
+        return;
+    }
+    check_vk_result(err);
+
+    ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex];
+    {
+        err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX);    // wait indefinitely instead of periodically checking
+        check_vk_result(err);
+
+        err = vkResetFences(g_Device, 1, &fd->Fence);
+        check_vk_result(err);
+    }
+    {
+        err = vkResetCommandPool(g_Device, fd->CommandPool, 0);
+        check_vk_result(err);
+        VkCommandBufferBeginInfo info = {};
+        info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
+        info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
+        err = vkBeginCommandBuffer(fd->CommandBuffer, &info);
+        check_vk_result(err);
+    }
+    {
+        VkRenderPassBeginInfo info = {};
+        info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
+        info.renderPass = wd->RenderPass;
+        info.framebuffer = fd->Framebuffer;
+        info.renderArea.extent.width = wd->Width;
+        info.renderArea.extent.height = wd->Height;
+        info.clearValueCount = 1;
+        info.pClearValues = &wd->ClearValue;
+        vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE);
+    }
+
+    // Record dear imgui primitives into command buffer
+    ImGui_ImplVulkan_RenderDrawData(draw_data, fd->CommandBuffer);
+
+    // Submit command buffer
+    vkCmdEndRenderPass(fd->CommandBuffer);
+    {
+        VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
+        VkSubmitInfo info = {};
+        info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
+        info.waitSemaphoreCount = 1;
+        info.pWaitSemaphores = &image_acquired_semaphore;
+        info.pWaitDstStageMask = &wait_stage;
+        info.commandBufferCount = 1;
+        info.pCommandBuffers = &fd->CommandBuffer;
+        info.signalSemaphoreCount = 1;
+        info.pSignalSemaphores = &render_complete_semaphore;
+
+        err = vkEndCommandBuffer(fd->CommandBuffer);
+        check_vk_result(err);
+        err = vkQueueSubmit(g_Queue, 1, &info, fd->Fence);
+        check_vk_result(err);
+    }
+}
+
+static void FramePresent(ImGui_ImplVulkanH_Window* wd)
+{
+    if (g_SwapChainRebuild)
+        return;
+    VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore;
+    VkPresentInfoKHR info = {};
+    info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
+    info.waitSemaphoreCount = 1;
+    info.pWaitSemaphores = &render_complete_semaphore;
+    info.swapchainCount = 1;
+    info.pSwapchains = &wd->Swapchain;
+    info.pImageIndices = &wd->FrameIndex;
+    VkResult err = vkQueuePresentKHR(g_Queue, &info);
+    if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR)
+    {
+        g_SwapChainRebuild = true;
+        return;
+    }
+    check_vk_result(err);
+    wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores
+}
+
+// Main code
+int main(int, char**)
+{
+    // Setup SDL
+    if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD) != 0)
+    {
+        printf("Error: SDL_Init(): %s\n", SDL_GetError());
+        return -1;
+    }
+
+    // Create window with Vulkan graphics context
+    SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_HIDDEN);
+    SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Vulkan example", 1280, 720, window_flags);
+    if (window == nullptr)
+    {
+        printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
+        return -1;
+    }
+
+    ImVector extensions;
+    {
+        uint32_t sdl_extensions_count = 0;
+        const char* const* sdl_extensions = SDL_Vulkan_GetInstanceExtensions(&sdl_extensions_count);
+        for (uint32_t n = 0; n < sdl_extensions_count; n++)
+            extensions.push_back(sdl_extensions[n]);
+    }
+    SetupVulkan(extensions);
+
+    // Create Window Surface
+    VkSurfaceKHR surface;
+    VkResult err;
+    if (SDL_Vulkan_CreateSurface(window, g_Instance, g_Allocator, &surface) == 0)
+    {
+        printf("Failed to create Vulkan surface.\n");
+        return 1;
+    }
+
+    // Create Framebuffers
+    int w, h;
+    SDL_GetWindowSize(window, &w, &h);
+    ImGui_ImplVulkanH_Window* wd = &g_MainWindowData;
+    SetupVulkanWindow(wd, surface, w, h);
+    SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
+    SDL_ShowWindow(window);
+
+    // Setup Dear ImGui context
+    IMGUI_CHECKVERSION();
+    ImGui::CreateContext();
+    ImGuiIO& io = ImGui::GetIO(); (void)io;
+    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
+    io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls
+
+    // Setup Dear ImGui style
+    ImGui::StyleColorsDark();
+    //ImGui::StyleColorsLight();
+
+    // Setup Platform/Renderer backends
+    ImGui_ImplSDL3_InitForVulkan(window);
+    ImGui_ImplVulkan_InitInfo init_info = {};
+    init_info.Instance = g_Instance;
+    init_info.PhysicalDevice = g_PhysicalDevice;
+    init_info.Device = g_Device;
+    init_info.QueueFamily = g_QueueFamily;
+    init_info.Queue = g_Queue;
+    init_info.PipelineCache = g_PipelineCache;
+    init_info.DescriptorPool = g_DescriptorPool;
+    init_info.RenderPass = wd->RenderPass;
+    init_info.Subpass = 0;
+    init_info.MinImageCount = g_MinImageCount;
+    init_info.ImageCount = wd->ImageCount;
+    init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT;
+    init_info.Allocator = g_Allocator;
+    init_info.CheckVkResultFn = check_vk_result;
+    ImGui_ImplVulkan_Init(&init_info);
+
+    // Load Fonts
+    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+    // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+    // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
+    // - Read 'docs/FONTS.md' for more instructions and details.
+    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
+    //io.Fonts->AddFontDefault();
+    //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f);
+    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
+    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
+    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
+    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
+    //IM_ASSERT(font != nullptr);
+
+    // Our state
+    bool show_demo_window = true;
+    bool show_another_window = false;
+    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
+
+    // Main loop
+    bool done = false;
+    while (!done)
+    {
+        // Poll and handle events (inputs, window resize, etc.)
+        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
+        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
+        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
+        SDL_Event event;
+        while (SDL_PollEvent(&event))
+        {
+            ImGui_ImplSDL3_ProcessEvent(&event);
+            if (event.type == SDL_EVENT_QUIT)
+                done = true;
+            if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window))
+                done = true;
+        }
+        if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
+        {
+            SDL_Delay(10);
+            continue;
+        }
+
+        // Resize swap chain?
+        int fb_width, fb_height;
+        SDL_GetWindowSize(window, &fb_width, &fb_height);
+        if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height))
+        {
+            ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount);
+            ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount);
+            g_MainWindowData.FrameIndex = 0;
+            g_SwapChainRebuild = false;
+        }
+
+        // Start the Dear ImGui frame
+        ImGui_ImplVulkan_NewFrame();
+        ImGui_ImplSDL3_NewFrame();
+        ImGui::NewFrame();
+
+        // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
+        if (show_demo_window)
+            ImGui::ShowDemoWindow(&show_demo_window);
+
+        // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
+        {
+            static float f = 0.0f;
+            static int counter = 0;
+
+            ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.
+
+            ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
+            ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
+            ImGui::Checkbox("Another Window", &show_another_window);
+
+            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
+            ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
+
+            if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
+                counter++;
+            ImGui::SameLine();
+            ImGui::Text("counter = %d", counter);
+
+            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
+            ImGui::End();
+        }
+
+        // 3. Show another simple window.
+        if (show_another_window)
+        {
+            ImGui::Begin("Another Window", &show_another_window);   // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
+            ImGui::Text("Hello from another window!");
+            if (ImGui::Button("Close Me"))
+                show_another_window = false;
+            ImGui::End();
+        }
+
+        // Rendering
+        ImGui::Render();
+        ImDrawData* draw_data = ImGui::GetDrawData();
+        const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f);
+        if (!is_minimized)
+        {
+            wd->ClearValue.color.float32[0] = clear_color.x * clear_color.w;
+            wd->ClearValue.color.float32[1] = clear_color.y * clear_color.w;
+            wd->ClearValue.color.float32[2] = clear_color.z * clear_color.w;
+            wd->ClearValue.color.float32[3] = clear_color.w;
+            FrameRender(wd, draw_data);
+            FramePresent(wd);
+        }
+    }
+
+    // Cleanup
+    err = vkDeviceWaitIdle(g_Device);
+    check_vk_result(err);
+    ImGui_ImplVulkan_Shutdown();
+    ImGui_ImplSDL3_Shutdown();
+    ImGui::DestroyContext();
+
+    CleanupVulkanWindow();
+    CleanupVulkan();
+
+    SDL_DestroyWindow(window);
+    SDL_Quit();
+
+    return 0;
+}
diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln
index 9aee4a99e..ea9f65cbd 100644
--- a/examples/imgui_examples.sln
+++ b/examples/imgui_examples.sln
@@ -33,6 +33,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_opengl3", "exa
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlrenderer3", "example_sdl3_sdlrenderer3\example_sdl3_sdlrenderer3.vcxproj", "{C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}"
 EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_vulkan", "example_sdl3_vulkan\example_sdl3_vulkan.vcxproj", "{663A7E89-1E42-4222-921C-177F5B5910DF}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Win32 = Debug|Win32
@@ -161,6 +163,14 @@ Global
 		{C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|Win32.Build.0 = Release|Win32
 		{C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|x64.ActiveCfg = Release|x64
 		{C0290D21-3AD2-4A35-ABBC-A2F5F48326DA}.Release|x64.Build.0 = Release|x64
+		{663A7E89-1E42-4222-921C-177F5B5910DF}.Debug|Win32.ActiveCfg = Debug|Win32
+		{663A7E89-1E42-4222-921C-177F5B5910DF}.Debug|Win32.Build.0 = Debug|Win32
+		{663A7E89-1E42-4222-921C-177F5B5910DF}.Debug|x64.ActiveCfg = Debug|x64
+		{663A7E89-1E42-4222-921C-177F5B5910DF}.Debug|x64.Build.0 = Debug|x64
+		{663A7E89-1E42-4222-921C-177F5B5910DF}.Release|Win32.ActiveCfg = Release|Win32
+		{663A7E89-1E42-4222-921C-177F5B5910DF}.Release|Win32.Build.0 = Release|Win32
+		{663A7E89-1E42-4222-921C-177F5B5910DF}.Release|x64.ActiveCfg = Release|x64
+		{663A7E89-1E42-4222-921C-177F5B5910DF}.Release|x64.Build.0 = Release|x64
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

From 81cfe09657891236fe45839842f67119e6d2eef1 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 28 Oct 2024 15:44:44 +0100
Subject: [PATCH 0464/2359] Selectable, Style: selected Selectable() use
 _Header color instead of an arbitrary lerp between _Header and
 _HeaderHovered. (#8106, #1861)

---
 docs/CHANGELOG.txt | 2 ++
 imgui_demo.cpp     | 2 +-
 imgui_widgets.cpp  | 8 ++------
 3 files changed, 5 insertions(+), 7 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 194803ac6..4e987c003 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,8 @@ Breaking changes:
 
 Other changes:
 
+- Selectable: selected Selectables use ImGuiCol_Header instead of an arbitrary lerp
+  between _Header and _HeaderHovered which was introduced v1.91 (#8106, #1861)
 - Backends: DX12: Unmap() call specify written range. The range is informational and
   may be used by debug tools.
 - Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the 
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index f24254e2e..c6c06a58c 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -10220,7 +10220,7 @@ struct ExampleAssetsBrowser
 
             // Rendering parameters
             const ImU32 icon_type_overlay_colors[3] = { 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255) };
-            const ImU32 icon_bg_color = ImGui::GetColorU32(ImGuiCol_MenuBarBg);
+            const ImU32 icon_bg_color = ImGui::GetColorU32(IM_COL32(35, 35, 35, 220));
             const ImVec2 icon_type_overlay_size = ImVec2(4.0f, 4.0f);
             const bool display_label = (LayoutItemSize.x >= ImGui::CalcTextSize("999").x);
 
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 757eb8ab6..ee15e990a 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -7017,12 +7017,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
         const bool highlighted = hovered || (flags & ImGuiSelectableFlags_Highlight);
         if (highlighted || selected)
         {
-            // FIXME-MULTISELECT: Styling: Color for 'selected' elements? ImGuiCol_HeaderSelected
-            ImU32 col;
-            if (selected && !highlighted)
-                col = GetColorU32(ImLerp(GetStyleColorVec4(ImGuiCol_Header), GetStyleColorVec4(ImGuiCol_HeaderHovered), 0.5f));
-            else
-                col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
+            // Between 1.91.0 and 1.91.4 we made selected Selectable use an arbitrary lerp between _Header and _HeaderHovered. Removed that now. (#8106)
+            ImU32 col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
             RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
         }
         if (g.NavId == id)

From 81b689b9693df736386026916b598eeedf43a9bb Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 28 Oct 2024 15:52:37 +0100
Subject: [PATCH 0465/2359] Backends: OpenGL3: added additional debug GL_CALL
 enclosure for glCreateShader() calls. (#8104)

---
 backends/imgui_impl_opengl3.cpp | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp
index f5235096f..c03156a7e 100644
--- a/backends/imgui_impl_opengl3.cpp
+++ b/backends/imgui_impl_opengl3.cpp
@@ -895,13 +895,15 @@ bool    ImGui_ImplOpenGL3_CreateDeviceObjects()
 
     // Create shaders
     const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader };
-    GLuint vert_handle = glCreateShader(GL_VERTEX_SHADER);
+    GLuint vert_handle;
+    GL_CALL(vert_handle = glCreateShader(GL_VERTEX_SHADER));
     glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr);
     glCompileShader(vert_handle);
     CheckShader(vert_handle, "vertex shader");
 
     const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader };
-    GLuint frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
+    GLuint frag_handle;
+    GL_CALL(frag_handle = glCreateShader(GL_FRAGMENT_SHADER));
     glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr);
     glCompileShader(frag_handle);
     CheckShader(frag_handle, "fragment shader");

From d67e2eea1a0775066bb966ac8bbb9ecd6b5c48ba Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 28 Oct 2024 16:43:41 +0100
Subject: [PATCH 0466/2359] Backends: Win32: internal rename.

---
 backends/imgui_impl_win32.cpp | 34 +++++++++++++++++-----------------
 1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index 477d54abe..97735ae33 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -559,22 +559,10 @@ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam)
 #define DBT_DEVNODES_CHANGED 0x0007
 #endif
 
-// Win32 message handler (process Win32 mouse/keyboard inputs, etc.)
-// Call from your application's message handler. Keep calling your message handler unless this function returns TRUE.
-// When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs.
-// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
-// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
-// Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
-// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds.
-// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
-#if 0
-// Copy this line into your .cpp file to forward declare the function.
-extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
-#endif
-
+// Helper to obtain the source of mouse messages.
 // See https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages
 // Prefer to call this at the top of the message handler to avoid the possibility of other Win32 calls interfering with this.
-static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo()
+static ImGuiMouseSource ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo()
 {
     LPARAM extra_info = ::GetMessageExtraInfo();
     if ((extra_info & 0xFFFFFF80) == 0xFF515700)
@@ -584,6 +572,18 @@ static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo()
     return ImGuiMouseSource_Mouse;
 }
 
+// Win32 message handler (process Win32 mouse/keyboard inputs, etc.)
+// Call from your application's message handler. Keep calling your message handler unless this function returns TRUE.
+// When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs.
+// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
+// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
+// Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
+// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds.
+// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
+
+// Copy this line into your .cpp file to forward declare the function:
+extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+
 IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
 {
     // Most backends don't have silent checks like this one, but we need it because WndProc are called early in CreateWindow().
@@ -599,7 +599,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
     case WM_NCMOUSEMOVE:
     {
         // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events
-        ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo();
+        ImGuiMouseSource mouse_source = ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo();
         const int area = (msg == WM_MOUSEMOVE) ? 1 : 2;
         bd->MouseHwnd = hwnd;
         if (bd->MouseTrackedArea != area)
@@ -646,7 +646,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
     case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
     case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK:
     {
-        ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo();
+        ImGuiMouseSource mouse_source = ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo();
         int button = 0;
         if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; }
         if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; }
@@ -664,7 +664,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
     case WM_MBUTTONUP:
     case WM_XBUTTONUP:
     {
-        ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo();
+        ImGuiMouseSource mouse_source = ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo();
         int button = 0;
         if (msg == WM_LBUTTONUP) { button = 0; }
         if (msg == WM_RBUTTONUP) { button = 1; }

From 3b8c7d0326d307598edce07e53f03614f972b757 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 28 Oct 2024 16:58:07 +0100
Subject: [PATCH 0467/2359] Backends: Win32: rework to add
 ImGui_ImplWin32_WndProcHandlerEx() not using current context (experimental).
 (#8069, #6293, #5856, #586)

+ GetIOEx(). Amend fedf45c + cba656a. Amend 416cfdb9.
---
 backends/imgui_impl_win32.cpp | 94 +++++++++++++++++++----------------
 imgui.cpp                     |  7 +++
 imgui.h                       |  2 +-
 imgui_internal.h              |  1 +
 4 files changed, 59 insertions(+), 45 deletions(-)

diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index 97735ae33..c213f8158 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -133,12 +133,16 @@ static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData()
 {
     return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
 }
+static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData(ImGuiIO& io)
+{
+    return (ImGui_ImplWin32_Data*)io.BackendPlatformUserData;
+}
 
 // Functions
-static void ImGui_ImplWin32_UpdateKeyboardCodePage()
+static void ImGui_ImplWin32_UpdateKeyboardCodePage(ImGuiIO& io)
 {
     // Retrieve keyboard code page, required for handling of non-Unicode Windows.
-    ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
+    ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
     HKL keyboard_layout = ::GetKeyboardLayout(0);
     LCID keyboard_lcid = MAKELCID(HIWORD(keyboard_layout), SORT_DEFAULT);
     if (::GetLocaleInfoA(keyboard_lcid, (LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE), (LPSTR)&bd->KeyboardCodePage, sizeof(bd->KeyboardCodePage)) == 0)
@@ -168,7 +172,7 @@ static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc)
     bd->TicksPerSecond = perf_frequency;
     bd->Time = perf_counter;
     bd->LastMouseCursor = ImGuiMouseCursor_COUNT;
-    ImGui_ImplWin32_UpdateKeyboardCodePage();
+    ImGui_ImplWin32_UpdateKeyboardCodePage(io);
 
     // Set platform dependent data in viewport
     ImGuiViewport* main_viewport = ImGui::GetMainViewport();
@@ -228,13 +232,11 @@ void    ImGui_ImplWin32_Shutdown()
     IM_DELETE(bd);
 }
 
-static bool ImGui_ImplWin32_UpdateMouseCursor()
+static bool ImGui_ImplWin32_UpdateMouseCursor(ImGuiIO& io, ImGuiMouseCursor imgui_cursor)
 {
-    ImGuiIO& io = ImGui::GetIO();
     if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
         return false;
 
-    ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
     if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
     {
         // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
@@ -266,42 +268,39 @@ static bool IsVkDown(int vk)
     return (::GetKeyState(vk) & 0x8000) != 0;
 }
 
-static void ImGui_ImplWin32_AddKeyEvent(ImGuiKey key, bool down, int native_keycode, int native_scancode = -1)
+static void ImGui_ImplWin32_AddKeyEvent(ImGuiIO& io, ImGuiKey key, bool down, int native_keycode, int native_scancode = -1)
 {
-    ImGuiIO& io = ImGui::GetIO();
     io.AddKeyEvent(key, down);
     io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code)
     IM_UNUSED(native_scancode);
 }
 
-static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds()
+static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds(ImGuiIO& io)
 {
     // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one.
     if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT))
-        ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, false, VK_LSHIFT);
+        ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftShift, false, VK_LSHIFT);
     if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT))
-        ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, false, VK_RSHIFT);
+        ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightShift, false, VK_RSHIFT);
 
     // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW).
     if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN))
-        ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftSuper, false, VK_LWIN);
+        ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftSuper, false, VK_LWIN);
     if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN))
-        ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightSuper, false, VK_RWIN);
+        ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightSuper, false, VK_RWIN);
 }
 
-static void ImGui_ImplWin32_UpdateKeyModifiers()
+static void ImGui_ImplWin32_UpdateKeyModifiers(ImGuiIO& io)
 {
-    ImGuiIO& io = ImGui::GetIO();
     io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL));
     io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT));
     io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU));
     io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_LWIN) || IsVkDown(VK_RWIN));
 }
 
-static void ImGui_ImplWin32_UpdateMouseData()
+static void ImGui_ImplWin32_UpdateMouseData(ImGuiIO& io)
 {
-    ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
-    ImGuiIO& io = ImGui::GetIO();
+    ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
     IM_ASSERT(bd->hWnd != 0);
 
     HWND focused_window = ::GetForegroundWindow();
@@ -328,11 +327,10 @@ static void ImGui_ImplWin32_UpdateMouseData()
 }
 
 // Gamepad navigation mapping
-static void ImGui_ImplWin32_UpdateGamepads()
+static void ImGui_ImplWin32_UpdateGamepads(ImGuiIO& io)
 {
 #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
-    ImGuiIO& io = ImGui::GetIO();
-    ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
+    ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
     //if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
     //    return;
 
@@ -381,7 +379,9 @@ static void ImGui_ImplWin32_UpdateGamepads()
     MAP_ANALOG(ImGuiKey_GamepadRStickDown,      gamepad.sThumbRY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
     #undef MAP_BUTTON
     #undef MAP_ANALOG
-#endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
+#else // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
+    IM_UNUSED(io);
+#endif
 }
 
 void    ImGui_ImplWin32_NewFrame()
@@ -402,21 +402,21 @@ void    ImGui_ImplWin32_NewFrame()
     bd->Time = current_time;
 
     // Update OS mouse position
-    ImGui_ImplWin32_UpdateMouseData();
+    ImGui_ImplWin32_UpdateMouseData(io);
 
     // Process workarounds for known Windows key handling issues
-    ImGui_ImplWin32_ProcessKeyEventsWorkarounds();
+    ImGui_ImplWin32_ProcessKeyEventsWorkarounds(io);
 
     // Update OS mouse cursor with the cursor requested by imgui
     ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
     if (bd->LastMouseCursor != mouse_cursor)
     {
         bd->LastMouseCursor = mouse_cursor;
-        ImGui_ImplWin32_UpdateMouseCursor();
+        ImGui_ImplWin32_UpdateMouseCursor(io, mouse_cursor);
     }
 
     // Update game controllers (if enabled and available)
-    ImGui_ImplWin32_UpdateGamepads();
+    ImGui_ImplWin32_UpdateGamepads(io);
 }
 
 // Map VK_xxx to ImGuiKey_xxx.
@@ -578,21 +578,27 @@ static ImGuiMouseSource ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo()
 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
 // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
-// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds.
 // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
 
-// Copy this line into your .cpp file to forward declare the function:
-extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+// Copy either line into your .cpp file to forward declare the function:
+extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);                // Use ImGui::GetCurrentContext()
+extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, ImGuiIO& io); // Doesn't use ImGui::GetCurrentContext()
 
 IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
 {
     // Most backends don't have silent checks like this one, but we need it because WndProc are called early in CreateWindow().
     // We silently allow both context or just only backend data to be nullptr.
-    ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
-    if (bd == nullptr)
+    if (ImGui::GetCurrentContext() == NULL)
         return 0;
-    ImGuiIO& io = ImGui::GetIO();
+    return ImGui_ImplWin32_WndProcHandlerEx(hwnd, msg, wParam, lParam, ImGui::GetIO());
+}
 
+// This version is in theory thread-safe in the sense that no path should access ImGui::GetCurrentContext().
+IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, ImGuiIO& io)
+{
+    ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
+    if (bd == NULL)
+        return 0;
     switch (msg)
     {
     case WM_MOUSEMOVE:
@@ -653,7 +659,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
         if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; }
         if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
         if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr)
-            ::SetCapture(hwnd);
+            ::SetCapture(hwnd); // Allow us to read mouse coordinates when dragging mouse outside of our window bounds.
         bd->MouseButtonsDown |= 1 << button;
         io.AddMouseSourceEvent(mouse_source);
         io.AddMouseButtonEvent(button, true);
@@ -692,7 +698,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
         if (wParam < 256)
         {
             // Submit modifiers
-            ImGui_ImplWin32_UpdateKeyModifiers();
+            ImGui_ImplWin32_UpdateKeyModifiers(io);
 
             // Obtain virtual key code and convert to ImGuiKey
             const ImGuiKey key = ImGui_ImplWin32_KeyEventToImGuiKey(wParam, lParam);
@@ -701,28 +707,28 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
 
             // Special behavior for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit the key down event.
             if (key == ImGuiKey_PrintScreen && !is_key_down)
-                ImGui_ImplWin32_AddKeyEvent(key, true, vk, scancode);
+                ImGui_ImplWin32_AddKeyEvent(io, key, true, vk, scancode);
 
             // Submit key event
             if (key != ImGuiKey_None)
-                ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode);
+                ImGui_ImplWin32_AddKeyEvent(io, key, is_key_down, vk, scancode);
 
             // Submit individual left/right modifier events
             if (vk == VK_SHIFT)
             {
                 // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds()
-                if (IsVkDown(VK_LSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); }
-                if (IsVkDown(VK_RSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); }
+                if (IsVkDown(VK_LSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); }
+                if (IsVkDown(VK_RSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); }
             }
             else if (vk == VK_CONTROL)
             {
-                if (IsVkDown(VK_LCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); }
-                if (IsVkDown(VK_RCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); }
+                if (IsVkDown(VK_LCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); }
+                if (IsVkDown(VK_RCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); }
             }
             else if (vk == VK_MENU)
             {
-                if (IsVkDown(VK_LMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); }
-                if (IsVkDown(VK_RMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); }
+                if (IsVkDown(VK_LMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); }
+                if (IsVkDown(VK_RMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); }
             }
         }
         return 0;
@@ -732,7 +738,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
         io.AddFocusEvent(msg == WM_SETFOCUS);
         return 0;
     case WM_INPUTLANGCHANGE:
-        ImGui_ImplWin32_UpdateKeyboardCodePage();
+        ImGui_ImplWin32_UpdateKeyboardCodePage(io);
         return 0;
     case WM_CHAR:
         if (::IsWindowUnicode(hwnd))
@@ -750,7 +756,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
         return 0;
     case WM_SETCURSOR:
         // This is required to restore cursor when transitioning from e.g resize borders to client area.
-        if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
+        if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor(io, bd->LastMouseCursor))
             return 1;
         return 0;
     case WM_DEVICECHANGE:
diff --git a/imgui.cpp b/imgui.cpp
index 81f872f7b..25089e0fd 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4748,6 +4748,13 @@ ImGuiIO& ImGui::GetIO()
     return GImGui->IO;
 }
 
+// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856)
+ImGuiIO& ImGui::GetIOEx(ImGuiContext* ctx)
+{
+    IM_ASSERT(ctx != NULL);
+    return ctx->IO;
+}
+
 ImGuiPlatformIO& ImGui::GetPlatformIO()
 {
     IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
diff --git a/imgui.h b/imgui.h
index 04f958eec..eb3991d97 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2248,7 +2248,7 @@ struct ImGuiIO
 
     // Keyboard/Gamepad Navigation options
     bool        ConfigNavSwapGamepadButtons;    // = false          // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout.
-    bool        ConfigNavMoveSetMousePos;       // = false          // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. 
+    bool        ConfigNavMoveSetMousePos;       // = false          // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true.
     bool        ConfigNavCaptureKeyboard;       // = true           // Sets io.WantCaptureKeyboard when io.NavActive is set.
     bool        ConfigNavEscapeClearFocusItem;  // = true           // Pressing Escape can clear focused item + navigation id/highlight. Set to false if you want to always keep highlight on.
     bool        ConfigNavEscapeClearFocusWindow;// = false          // Pressing Escape can clear focused window as well (super set of io.ConfigNavEscapeClearFocusItem).
diff --git a/imgui_internal.h b/imgui_internal.h
index 0c441a260..fab157303 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2936,6 +2936,7 @@ namespace ImGui
     // If this ever crashes because g.CurrentWindow is NULL, it means that either:
     // - ImGui::NewFrame() has never been called, which is illegal.
     // - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.
+    IMGUI_API ImGuiIO&      GetIOEx(ImGuiContext* ctx);
     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);

From 0bde57c25a90ee1b99e511385611db6185d318f8 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 29 Oct 2024 11:47:03 +0100
Subject: [PATCH 0468/2359] Font, Misc: remove qualifier from most font
 functions.

Fixed ClearOutputData() not clearing Used4kPagesMap (mostly harmless).
---
 backends/imgui_impl_dx10.h   |  2 +-
 backends/imgui_impl_dx11.cpp |  2 +-
 backends/imgui_impl_dx11.h   |  2 +-
 backends/imgui_impl_dx12.h   |  2 +-
 backends/imgui_impl_wgpu.h   |  2 +-
 docs/CHANGELOG.txt           |  1 +
 imgui.cpp                    |  2 +-
 imgui.h                      | 16 ++++++++--------
 imgui_draw.cpp               | 15 ++++++++-------
 9 files changed, 23 insertions(+), 21 deletions(-)

diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h
index 95759737b..667f296f1 100644
--- a/backends/imgui_impl_dx10.h
+++ b/backends/imgui_impl_dx10.h
@@ -26,7 +26,7 @@ IMGUI_IMPL_API void     ImGui_ImplDX10_NewFrame();
 IMGUI_IMPL_API void     ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data);
 
 // Use if you want to reset your rendering device without losing Dear ImGui state.
-IMGUI_IMPL_API void     ImGui_ImplDX10_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool     ImGui_ImplDX10_CreateDeviceObjects();
+IMGUI_IMPL_API void     ImGui_ImplDX10_InvalidateDeviceObjects();
 
 #endif // #ifndef IMGUI_DISABLE
diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp
index 16d480e08..b928bb86f 100644
--- a/backends/imgui_impl_dx11.cpp
+++ b/backends/imgui_impl_dx11.cpp
@@ -23,7 +23,7 @@
 //  2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
 //  2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer.
 //  2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled).
-//  2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore.
+//  2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX11_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore.
 //  2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
 //  2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
 //  2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h
index 57b19bc03..c3b8379b1 100644
--- a/backends/imgui_impl_dx11.h
+++ b/backends/imgui_impl_dx11.h
@@ -29,8 +29,8 @@ IMGUI_IMPL_API void     ImGui_ImplDX11_NewFrame();
 IMGUI_IMPL_API void     ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data);
 
 // Use if you want to reset your rendering device without losing Dear ImGui state.
-IMGUI_IMPL_API void     ImGui_ImplDX11_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool     ImGui_ImplDX11_CreateDeviceObjects();
+IMGUI_IMPL_API void     ImGui_ImplDX11_InvalidateDeviceObjects();
 
 // [BETA] Selected render state data shared with callbacks.
 // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX11_RenderDrawData() call.
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index 5da528573..1e36d730f 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -37,8 +37,8 @@ IMGUI_IMPL_API void     ImGui_ImplDX12_NewFrame();
 IMGUI_IMPL_API void     ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list);
 
 // Use if you want to reset your rendering device without losing Dear ImGui state.
-IMGUI_IMPL_API void     ImGui_ImplDX12_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool     ImGui_ImplDX12_CreateDeviceObjects();
+IMGUI_IMPL_API void     ImGui_ImplDX12_InvalidateDeviceObjects();
 
 // [BETA] Selected render state data shared with callbacks.
 // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX12_RenderDrawData() call.
diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h
index e4398575c..f9fb03776 100644
--- a/backends/imgui_impl_wgpu.h
+++ b/backends/imgui_impl_wgpu.h
@@ -52,8 +52,8 @@ IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame();
 IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder);
 
 // Use if you want to reset your rendering device without losing Dear ImGui state.
-IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects();
 IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects();
+IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects();
 
 // [BETA] Selected render state data shared with callbacks.
 // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplWGPU_RenderDrawData() call.
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 4e987c003..744397615 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -45,6 +45,7 @@ Other changes:
 
 - Selectable: selected Selectables use ImGuiCol_Header instead of an arbitrary lerp
   between _Header and _HeaderHovered which was introduced v1.91 (#8106, #1861)
+- Fonts: removed const qualifiers from most font functions.
 - Backends: DX12: Unmap() call specify written range. The range is informational and
   may be used by debug tools.
 - Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the 
diff --git a/imgui.cpp b/imgui.cpp
index 25089e0fd..94358e417 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3637,7 +3637,7 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con
         // min   max   ellipsis_max
         //          <-> this is generally some padding value
 
-        const ImFont* font = draw_list->_Data->Font;
+        ImFont* font = draw_list->_Data->Font;
         const float font_size = draw_list->_Data->FontSize;
         const float font_scale = draw_list->_Data->FontScale;
         const char* text_end_ellipsis = NULL;
diff --git a/imgui.h b/imgui.h
index eb3991d97..7aec7b0e2 100644
--- a/imgui.h
+++ b/imgui.h
@@ -3122,7 +3122,7 @@ struct ImDrawList
     IMGUI_API void  AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f);
     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(const 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(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  AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 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);               // Quadratic Bezier (3 control points)
 
@@ -3471,18 +3471,18 @@ struct ImFont
     // Methods
     IMGUI_API ImFont();
     IMGUI_API ~ImFont();
-    IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;
-    IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const;
-    float                       GetCharAdvance(ImWchar c) const     { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
+    IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c);
+    IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c);
+    float                       GetCharAdvance(ImWchar c)           { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
     bool                        IsLoaded() const                    { return ContainerAtlas != NULL; }
     const char*                 GetDebugName() const                { return ConfigData ? ConfigData->Name : ""; }
 
     // '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 ImVec2            CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8
-    IMGUI_API const char*       CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const;
-    IMGUI_API void              RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) const;
-    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, bool cpu_fine_clip = false) const;
+    IMGUI_API ImVec2            CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL); // utf8
+    IMGUI_API const char*       CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width);
+    IMGUI_API void              RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c);
+    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, bool cpu_fine_clip = false);
 
     // [Internal] Don't use!
     IMGUI_API void              BuildLookupTable();
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 01723b35c..d54c96bab 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1646,7 +1646,7 @@ void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const Im
     PathStroke(col, 0, thickness);
 }
 
-void ImDrawList::AddText(const 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, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect)
 {
     if ((col & IM_COL32_A_MASK) == 0)
         return;
@@ -3638,6 +3638,7 @@ void    ImFont::ClearOutputData()
     DirtyLookupTables = true;
     Ascent = Descent = 0.0f;
     MetricsTotalSurface = 0;
+    memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap));
 }
 
 static ImWchar FindFirstExistingGlyph(ImFont* font, const ImWchar* candidate_chars, int candidate_chars_count)
@@ -3822,7 +3823,7 @@ void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
     IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f;
 }
 
-const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const
+const ImFontGlyph* ImFont::FindGlyph(ImWchar c)
 {
     if (c >= (size_t)IndexLookup.Size)
         return FallbackGlyph;
@@ -3832,7 +3833,7 @@ const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const
     return &Glyphs.Data[i];
 }
 
-const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const
+const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c)
 {
     if (c >= (size_t)IndexLookup.Size)
         return NULL;
@@ -3855,7 +3856,7 @@ static inline const char* CalcWordWrapNextLineStartA(const char* text, const cha
 // 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.
 // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.)
-const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const
+const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width)
 {
     // For references, possible wrap point marked with ^
     //  "aaa bbb, ccc,ddd. eee   fff. ggg!"
@@ -3953,7 +3954,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
     return s;
 }
 
-ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const
+ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining)
 {
     if (!text_end)
         text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this.
@@ -4032,7 +4033,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
 }
 
 // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound.
-void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) const
+void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c)
 {
     const ImFontGlyph* glyph = FindGlyph(c);
     if (!glyph || !glyph->Visible)
@@ -4047,7 +4048,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.
-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, bool cpu_fine_clip) const
+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, bool cpu_fine_clip)
 {
     if (!text_end)
         text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls.

From 9a0dff1bc56bff17269ec922f78b03ca838e3ea2 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 29 Oct 2024 14:26:02 +0100
Subject: [PATCH 0469/2359] Buttons: using ImGuiItemFlags_ButtonRepeat makes
 default button behavior use PressedOnClick instead of PressedOnClickRelease
 when unspecified.

---
 docs/CHANGELOG.txt |  2 ++
 imgui.h            |  2 +-
 imgui_widgets.cpp  | 14 +++++++-------
 3 files changed, 10 insertions(+), 8 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 744397615..82c6b2266 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -45,6 +45,8 @@ Other changes:
 
 - Selectable: selected Selectables use ImGuiCol_Header instead of an arbitrary lerp
   between _Header and _HeaderHovered which was introduced v1.91 (#8106, #1861)
+- Buttons: using ImGuiItemFlags_ButtonRepeat makes default button behavior use
+  PressedOnClick instead of PressedOnClickRelease when unspecified.
 - Fonts: removed const qualifiers from most font functions.
 - Backends: DX12: Unmap() call specify written range. The range is informational and
   may be used by debug tools.
diff --git a/imgui.h b/imgui.h
index 7aec7b0e2..6f6779abf 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.5 WIP"
-#define IMGUI_VERSION_NUM   19141
+#define IMGUI_VERSION_NUM   19142
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index ee15e990a..1ee9a9624 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -495,19 +495,19 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = GetCurrentWindow();
 
+    // Default behavior inherited from item flags
+    // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
+    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags);
+    if (flags & ImGuiButtonFlags_AllowOverlap)
+        item_flags |= ImGuiItemFlags_AllowOverlap;
+
     // Default only reacts to left mouse button
     if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0)
         flags |= ImGuiButtonFlags_MouseButtonLeft;
 
     // Default behavior requires click + release inside bounding box
     if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0)
-        flags |= ImGuiButtonFlags_PressedOnDefault_;
-
-    // Default behavior inherited from item flags
-    // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
-    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags);
-    if (flags & ImGuiButtonFlags_AllowOverlap)
-        item_flags |= ImGuiItemFlags_AllowOverlap;
+        flags |= (item_flags & ImGuiItemFlags_ButtonRepeat) ? ImGuiButtonFlags_PressedOnClick : ImGuiButtonFlags_PressedOnDefault_;
 
     ImGuiWindow* backup_hovered_window = g.HoveredWindow;
     const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindow == window;

From a4fcc93f4af38e567de0a09e40b67134158be5de Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 30 Oct 2024 15:07:26 +0100
Subject: [PATCH 0470/2359] Log/Capture: renaming ImGuiLogType to ImGuiLogFlags

---
 imgui.cpp        | 33 +++++++++++++++++----------------
 imgui_internal.h | 20 ++++++++++++--------
 2 files changed, 29 insertions(+), 24 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 94358e417..44a17508f 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4007,7 +4007,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     memset(LocalizationTable, 0, sizeof(LocalizationTable));
 
     LogEnabled = false;
-    LogType = ImGuiLogType_None;
+    LogFlags = ImGuiLogFlags_None;
     LogNextPrefix = LogNextSuffix = NULL;
     LogFile = NULL;
     LogLinePosY = FLT_MAX;
@@ -14324,15 +14324,16 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char*
 }
 
 // Start logging/capturing text output
-void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
+void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth)
 {
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = g.CurrentWindow;
     IM_ASSERT(g.LogEnabled == false);
-    IM_ASSERT(g.LogFile == NULL);
-    IM_ASSERT(g.LogBuffer.empty());
+    IM_ASSERT(g.LogFile == NULL && g.LogBuffer.empty());
+    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiLogFlags_OutputMask_)); // Check that only 1 type flag is used
+
     g.LogEnabled = g.ItemUnclipByLog = true;
-    g.LogType = type;
+    g.LogFlags = flags;
     g.LogNextPrefix = g.LogNextSuffix = NULL;
     g.LogDepthRef = window->DC.TreeDepth;
     g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
@@ -14355,7 +14356,7 @@ void ImGui::LogToTTY(int auto_open_depth)
         return;
     IM_UNUSED(auto_open_depth);
 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
-    LogBegin(ImGuiLogType_TTY, auto_open_depth);
+    LogBegin(ImGuiLogFlags_OutputTTY, auto_open_depth);
     g.LogFile = stdout;
 #endif
 }
@@ -14381,7 +14382,7 @@ void ImGui::LogToFile(int auto_open_depth, const char* filename)
         return;
     }
 
-    LogBegin(ImGuiLogType_File, auto_open_depth);
+    LogBegin(ImGuiLogFlags_OutputFile, auto_open_depth);
     g.LogFile = f;
 }
 
@@ -14391,7 +14392,7 @@ void ImGui::LogToClipboard(int auto_open_depth)
     ImGuiContext& g = *GImGui;
     if (g.LogEnabled)
         return;
-    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
+    LogBegin(ImGuiLogFlags_OutputClipboard, auto_open_depth);
 }
 
 void ImGui::LogToBuffer(int auto_open_depth)
@@ -14399,7 +14400,7 @@ void ImGui::LogToBuffer(int auto_open_depth)
     ImGuiContext& g = *GImGui;
     if (g.LogEnabled)
         return;
-    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
+    LogBegin(ImGuiLogFlags_OutputBuffer, auto_open_depth);
 }
 
 void ImGui::LogFinish()
@@ -14409,29 +14410,29 @@ void ImGui::LogFinish()
         return;
 
     LogText(IM_NEWLINE);
-    switch (g.LogType)
+    switch (g.LogFlags & ImGuiLogFlags_OutputMask_)
     {
-    case ImGuiLogType_TTY:
+    case ImGuiLogFlags_OutputTTY:
 #ifndef IMGUI_DISABLE_TTY_FUNCTIONS
         fflush(g.LogFile);
 #endif
         break;
-    case ImGuiLogType_File:
+    case ImGuiLogFlags_OutputFile:
         ImFileClose(g.LogFile);
         break;
-    case ImGuiLogType_Buffer:
+    case ImGuiLogFlags_OutputBuffer:
         break;
-    case ImGuiLogType_Clipboard:
+    case ImGuiLogFlags_OutputClipboard:
         if (!g.LogBuffer.empty())
             SetClipboardText(g.LogBuffer.begin());
         break;
-    case ImGuiLogType_None:
+    default:
         IM_ASSERT(0);
         break;
     }
 
     g.LogEnabled = g.ItemUnclipByLog = false;
-    g.LogType = ImGuiLogType_None;
+    g.LogFlags = ImGuiLogFlags_None;
     g.LogFile = NULL;
     g.LogBuffer.clear();
 }
diff --git a/imgui_internal.h b/imgui_internal.h
index fab157303..af7270be8 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -177,6 +177,7 @@ typedef int ImGuiDebugLogFlags;         // -> enum ImGuiDebugLogFlags_      // F
 typedef int ImGuiFocusRequestFlags;     // -> enum ImGuiFocusRequestFlags_  // Flags: for FocusWindow()
 typedef int ImGuiItemStatusFlags;       // -> enum ImGuiItemStatusFlags_    // Flags: for g.LastItemData.StatusFlags
 typedef int ImGuiOldColumnFlags;        // -> enum ImGuiOldColumnFlags_     // Flags: for BeginColumns()
+typedef int ImGuiLogFlags;              // -> enum ImGuiLogFlags_           // Flags: for LogBegin() text capturing function
 typedef int ImGuiNavRenderCursorFlags;  // -> enum ImGuiNavRenderCursorFlags_//Flags: for RenderNavCursor()
 typedef int ImGuiNavMoveFlags;          // -> enum ImGuiNavMoveFlags_       // Flags: for navigation requests
 typedef int ImGuiNextItemDataFlags;     // -> enum ImGuiNextItemDataFlags_  // Flags: for SetNextItemXXX() functions
@@ -989,13 +990,16 @@ enum ImGuiLayoutType_
     ImGuiLayoutType_Vertical = 1
 };
 
-enum ImGuiLogType
+// Flags for LogBegin() text capturing function
+enum ImGuiLogFlags_
 {
-    ImGuiLogType_None = 0,
-    ImGuiLogType_TTY,
-    ImGuiLogType_File,
-    ImGuiLogType_Buffer,
-    ImGuiLogType_Clipboard,
+    ImGuiLogFlags_None = 0,
+
+    ImGuiLogFlags_OutputTTY         = 1 << 0,
+    ImGuiLogFlags_OutputFile        = 1 << 1,
+    ImGuiLogFlags_OutputBuffer      = 1 << 2,
+    ImGuiLogFlags_OutputClipboard   = 1 << 3,
+    ImGuiLogFlags_OutputMask_       = ImGuiLogFlags_OutputTTY | ImGuiLogFlags_OutputFile | ImGuiLogFlags_OutputBuffer | ImGuiLogFlags_OutputClipboard,
 };
 
 // X/Y enums are fixed to 0/1 so they may be used to index ImVec2
@@ -2316,7 +2320,7 @@ struct ImGuiContext
 
     // Capture/Logging
     bool                    LogEnabled;                         // Currently capturing
-    ImGuiLogType            LogType;                            // Capture target
+    ImGuiLogFlags           LogFlags;                           // Capture flags/type
     ImFileHandle            LogFile;                            // If != NULL log to stdout/ file
     ImGuiTextBuffer         LogBuffer;                          // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators.
     const char*             LogNextPrefix;
@@ -3067,7 +3071,7 @@ namespace ImGui
     IMGUI_API void          EndDisabledOverrideReenable();
 
     // Logging/Capture
-    IMGUI_API void          LogBegin(ImGuiLogType type, int auto_open_depth);           // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name.
+    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          LogSetNextTextDecoration(const char* prefix, const char* suffix);

From f37a9a27e582ad5316186f017e66b662efd9ca6b Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 30 Oct 2024 15:10:35 +0100
Subject: [PATCH 0471/2359] Log/Capture: reworked scope + decorating menus,
 tabs.

---
 docs/CHANGELOG.txt | 2 ++
 imgui.cpp          | 4 +++-
 imgui_internal.h   | 1 +
 imgui_widgets.cpp  | 4 ++++
 4 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 82c6b2266..c20f0f047 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -48,6 +48,8 @@ Other changes:
 - Buttons: using ImGuiItemFlags_ButtonRepeat makes default button behavior use
   PressedOnClick instead of PressedOnClickRelease when unspecified.
 - Fonts: removed const qualifiers from most font functions.
+- Log/Capture: better decorating of BeginMenu() and TabItem() output.
+- Log/Capture: a non terminated log ends automatically in the window which called it.
 - Backends: DX12: Unmap() call specify written range. The range is informational and
   may be used by debug tools.
 - Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the 
diff --git a/imgui.cpp b/imgui.cpp
index 44a17508f..5d079f4ae 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4008,6 +4008,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
 
     LogEnabled = false;
     LogFlags = ImGuiLogFlags_None;
+    LogWindow = NULL;
     LogNextPrefix = LogNextSuffix = NULL;
     LogFile = NULL;
     LogLinePosY = FLT_MAX;
@@ -7748,7 +7749,7 @@ void ImGui::End()
     }
 
     // Stop logging
-    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
+    if (g.LogWindow == window) // FIXME: add more options for scope of logging
         LogFinish();
 
     if (window->DC.IsSetPos)
@@ -14334,6 +14335,7 @@ void ImGui::LogBegin(ImGuiLogFlags flags, int auto_open_depth)
 
     g.LogEnabled = g.ItemUnclipByLog = true;
     g.LogFlags = flags;
+    g.LogWindow = window;
     g.LogNextPrefix = g.LogNextSuffix = NULL;
     g.LogDepthRef = window->DC.TreeDepth;
     g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
diff --git a/imgui_internal.h b/imgui_internal.h
index af7270be8..932a0484c 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2321,6 +2321,7 @@ struct ImGuiContext
     // Capture/Logging
     bool                    LogEnabled;                         // Currently capturing
     ImGuiLogFlags           LogFlags;                           // Capture flags/type
+    ImGuiWindow*            LogWindow;
     ImFileHandle            LogFile;                            // If != NULL log to stdout/ file
     ImGuiTextBuffer         LogBuffer;                          // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators.
     const char*             LogNextPrefix;
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 1ee9a9624..def3f5870 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -8811,6 +8811,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
         float w = label_size.x;
         ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
         pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, label_size.y));
+        LogSetNextTextDecoration("[", "]");
         RenderText(text_pos, label);
         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().
@@ -8827,6 +8828,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
         float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
         ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
         pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y));
+        LogSetNextTextDecoration("", ">");
         RenderText(text_pos, label);
         if (icon_w > 0.0f)
             RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);
@@ -9040,6 +9042,7 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut
             if (shortcut_w > 0.0f)
             {
                 PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);
+                LogSetNextTextDecoration("(", ")");
                 RenderText(pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false);
                 PopStyleColor();
             }
@@ -10288,6 +10291,7 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb,
         text_ellipsis_clip_bb.Max.x -= unsaved_marker_visible ? (button_sz * 0.80f) : 0.0f;
         ellipsis_max_x = text_pixel_clip_bb.Max.x;
     }
+    LogSetNextTextDecoration("/", "\\");
     RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size);
 
 #if 0

From 772ca9e9a9d9c8f7c90730b751279490fa427f7d Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 30 Oct 2024 15:14:02 +0100
Subject: [PATCH 0472/2359] Log/Capture: added experimental
 io.ConfigWindowsCopyContentsWithCtrlC config option.

---
 docs/CHANGELOG.txt |  4 ++++
 imgui.cpp          | 18 ++++++++----------
 imgui.h            |  5 +++--
 imgui_demo.cpp     |  4 +++-
 4 files changed, 18 insertions(+), 13 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index c20f0f047..026448b76 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -50,6 +50,10 @@ Other changes:
 - Fonts: removed const qualifiers from most font functions.
 - Log/Capture: better decorating of BeginMenu() and TabItem() output.
 - Log/Capture: a non terminated log ends automatically in the window which called it.
+- Log/Capture: added experimental io.ConfigWindowsCopyContentsWithCtrlC option to
+  automatically copy window contents into clipboard using CTRL+C. This is experimental
+  because (1) it currently breaks on nested Begin/End, (2) text output quality varies,
+  and (3) text output comes in submission order rather than spatial order.
 - Backends: DX12: Unmap() call specify written range. The range is informational and
   may be used by debug tools.
 - Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the 
diff --git a/imgui.cpp b/imgui.cpp
index 5d079f4ae..b24f75068 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1422,6 +1422,7 @@ ImGuiIO::ImGuiIO()
     ConfigDragClickToInputText = false;
     ConfigWindowsResizeFromEdges = true;
     ConfigWindowsMoveFromTitleBarOnly = false;
+    ConfigWindowsCopyContentsWithCtrlC = false;
     ConfigScrollbarScrollByPage = true;
     ConfigMemoryCompactTimer = 60.0f;
     ConfigDebugIsDebuggerPresent = false;
@@ -7587,6 +7588,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
         if (want_focus && window == g.NavWindow)
             NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
 
+        // Pressing CTRL+C copy window content into the clipboard
+        // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope.
+        // [EXPERIMENTAL] Text outputs has many issues.
+        if (g.IO.ConfigWindowsCopyContentsWithCtrlC)
+            if (g.NavWindow && g.NavWindow->RootWindow == window && g.ActiveId == 0 && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C))
+                LogToClipboard(0);
+
         // Title bar
         if (!(flags & ImGuiWindowFlags_NoTitleBar))
             RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
@@ -7597,16 +7605,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
         if (flags & ImGuiWindowFlags_Tooltip)
             g.TooltipPreviousWindow = window;
 
-        // Pressing CTRL+C while holding on a window copy its content to the clipboard
-        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
-        // Maybe we can support CTRL+C on every element?
-        /*
-        //if (g.NavWindow == window && g.ActiveId == 0)
-        if (g.ActiveId == window->MoveId)
-            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
-                LogToClipboard();
-        */
-
         // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
         // This is useful to allow creating context menus on title bar only, etc.
         SetLastItemDataForWindow(window, title_bar_rect);
diff --git a/imgui.h b/imgui.h
index 6f6779abf..726c97f73 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2242,7 +2242,7 @@ struct ImGuiIO
     // Font system
     ImFontAtlas*Fonts;                          //            // Font atlas: load, rasterize and pack one or more fonts into a single texture.
     float       FontGlobalScale;                // = 1.0f           // Global scale all fonts
-    bool        FontAllowUserScaling;           // = false          // Allow user scaling text of individual window with CTRL+Wheel.
+    bool        FontAllowUserScaling;           // = false          // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel.
     ImFont*     FontDefault;                    // = NULL           // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].
     ImVec2      DisplayFramebufferScale;        // = (1, 1)         // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale.
 
@@ -2263,8 +2263,9 @@ struct ImGuiIO
     bool        ConfigInputTextCursorBlink;     // = true           // Enable blinking cursor (optional as some users consider it to be distracting).
     bool        ConfigInputTextEnterKeepActive; // = false          // [BETA] Pressing Enter will keep item active and select contents (single-line only).
     bool        ConfigDragClickToInputText;     // = false          // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
-    bool        ConfigWindowsResizeFromEdges;   // = true           // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
+    bool        ConfigWindowsResizeFromEdges;   // = true           // Enable resizing of windows from their edges and from the lower-left corner. This requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
     bool        ConfigWindowsMoveFromTitleBarOnly;  // = false      // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.
+    bool        ConfigWindowsCopyContentsWithCtrlC; // = false      // [EXPERIMENTAL] CTRL+C copy the contents of focused window into the clipboard. Experimental because: (1) has known issues with nested Begin/End pairs (2) text output quality varies (3) text output is in submission order rather than spatial order.
     bool        ConfigScrollbarScrollByPage;    // = true           // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location.
     float       ConfigMemoryCompactTimer;       // = 60.0f          // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
 
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index c6c06a58c..1a52b0ed2 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -549,8 +549,10 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::Checkbox("io.ConfigDragClickToInputText", &io.ConfigDragClickToInputText);
             ImGui::SameLine(); HelpMarker("Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving).");
             ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges);
-            ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback.");
+            ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback.");
             ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly);
+            ImGui::Checkbox("io.ConfigWindowsCopyContentsWithCtrlC", &io.ConfigWindowsCopyContentsWithCtrlC); // [EXPERIMENTAL]
+            ImGui::SameLine(); HelpMarker("*EXPERIMENTAL* CTRL+C copy the contents of focused window into the clipboard.\n\nExperimental because:\n- (1) has known issues with nested Begin/End pairs.\n- (2) text output quality varies.\n- (3) text output is in submission order rather than spatial order.");
             ImGui::Checkbox("io.ConfigScrollbarScrollByPage", &io.ConfigScrollbarScrollByPage);
             ImGui::SameLine(); HelpMarker("Enable scrolling page by page when clicking outside the scrollbar grab.\nWhen disabled, always scroll to clicked location.\nWhen enabled, Shift+Click scrolls to clicked location.");
             ImGui::Checkbox("io.ConfigMacOSXBehaviors", &io.ConfigMacOSXBehaviors);

From 71c77c081ac36841e682498229088e7678207112 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 30 Oct 2024 15:41:45 +0100
Subject: [PATCH 0473/2359] Demo: added a "Windows" section.

---
 imgui_demo.cpp | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 1a52b0ed2..f44aedc6e 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -541,13 +541,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::Checkbox("io.ConfigNavCursorVisibleAlways", &io.ConfigNavCursorVisibleAlways);
             ImGui::SameLine(); HelpMarker("Navigation cursor is always visible.");
 
-            ImGui::SeparatorText("Widgets");
-            ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink);
-            ImGui::SameLine(); HelpMarker("Enable blinking cursor (optional as some users consider it to be distracting).");
-            ImGui::Checkbox("io.ConfigInputTextEnterKeepActive", &io.ConfigInputTextEnterKeepActive);
-            ImGui::SameLine(); HelpMarker("Pressing Enter will keep item active and select contents (single-line only).");
-            ImGui::Checkbox("io.ConfigDragClickToInputText", &io.ConfigDragClickToInputText);
-            ImGui::SameLine(); HelpMarker("Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving).");
+            ImGui::SeparatorText("Windows");
             ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges);
             ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback.");
             ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly);
@@ -555,6 +549,14 @@ void ImGui::ShowDemoWindow(bool* p_open)
             ImGui::SameLine(); HelpMarker("*EXPERIMENTAL* CTRL+C copy the contents of focused window into the clipboard.\n\nExperimental because:\n- (1) has known issues with nested Begin/End pairs.\n- (2) text output quality varies.\n- (3) text output is in submission order rather than spatial order.");
             ImGui::Checkbox("io.ConfigScrollbarScrollByPage", &io.ConfigScrollbarScrollByPage);
             ImGui::SameLine(); HelpMarker("Enable scrolling page by page when clicking outside the scrollbar grab.\nWhen disabled, always scroll to clicked location.\nWhen enabled, Shift+Click scrolls to clicked location.");
+
+            ImGui::SeparatorText("Widgets");
+            ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink);
+            ImGui::SameLine(); HelpMarker("Enable blinking cursor (optional as some users consider it to be distracting).");
+            ImGui::Checkbox("io.ConfigInputTextEnterKeepActive", &io.ConfigInputTextEnterKeepActive);
+            ImGui::SameLine(); HelpMarker("Pressing Enter will keep item active and select contents (single-line only).");
+            ImGui::Checkbox("io.ConfigDragClickToInputText", &io.ConfigDragClickToInputText);
+            ImGui::SameLine(); HelpMarker("Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving).");
             ImGui::Checkbox("io.ConfigMacOSXBehaviors", &io.ConfigMacOSXBehaviors);
             ImGui::SameLine(); HelpMarker("Swap Cmd<>Ctrl keys, enable various MacOS style behaviors.");
             ImGui::Text("Also see Style->Rendering for rendering options.");

From f77d22837c0d2e8d0582cd1e8f077a88fa6ebd9b Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 4 Nov 2024 14:24:54 +0100
Subject: [PATCH 0474/2359] Examples: Android+OpenGL: Using ALooper_pollOnce()
 instead of ALooper_pollAll(). (#8013)

---
 docs/CHANGELOG.txt                        | 4 +++-
 examples/example_android_opengl3/main.cpp | 2 +-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 026448b76..02297a64b 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -60,7 +60,9 @@ Other changes:
   actual include. (#8095, #7967, #3190) [@sev-] 
 - Backends: SDL2, SDL3: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing 
   by 100.0f on Emscripten target. (#4019, #6096, #1463)
-- Examples: Added SDL3+Vulkan example. (#8084, #8085)
+- Examples: SDL3+Vulkan: Added example. (#8084, #8085)
+- Examples: Android+OpenGL: Using ALooper_pollOnce() instead of ALooper_pollAll()
+  which has been deprecated. (#8013) [@feather179]
 
 -----------------------------------------------------------------------
  VERSION 1.91.4 (Released 2024-10-18)
diff --git a/examples/example_android_opengl3/main.cpp b/examples/example_android_opengl3/main.cpp
index e0ad5f936..42aa622f7 100644
--- a/examples/example_android_opengl3/main.cpp
+++ b/examples/example_android_opengl3/main.cpp
@@ -68,7 +68,7 @@ void android_main(struct android_app* app)
         struct android_poll_source* out_data;
 
         // Poll all events. If the app is not visible, this loop blocks until g_Initialized == true.
-        while (ALooper_pollAll(g_Initialized ? 0 : -1, nullptr, &out_events, (void**)&out_data) >= 0)
+        while (ALooper_pollOnce(g_Initialized ? 0 : -1, nullptr, &out_events, (void**)&out_data) >= 0)
         {
             // Process one event
             if (out_data != nullptr)

From 75f83de52abe2b419eacbcbbee5d62c99f65b85b Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 4 Nov 2024 19:48:40 +0100
Subject: [PATCH 0475/2359] InputText: fixed a bug (regression in 1.91.2) where
 modifying text buffer within a callback would sometimes prevents further
 appending to the buffer. (#7925)

There's a confusion between TextA.Size and CurLenA we should be merging them.
Amend 19accb14a
---
 docs/CHANGELOG.txt | 2 ++
 imgui.h            | 2 +-
 imgui_internal.h   | 2 +-
 imgui_widgets.cpp  | 6 ++++--
 4 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 02297a64b..7bb626478 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -48,6 +48,8 @@ Other changes:
 - Buttons: using ImGuiItemFlags_ButtonRepeat makes default button behavior use
   PressedOnClick instead of PressedOnClickRelease when unspecified.
 - Fonts: removed const qualifiers from most font functions.
+- InputText: fixed a bug (regression in 1.91.2) where modifying text buffer within
+  a callback would sometimes prevents further appending to the buffer.
 - Log/Capture: better decorating of BeginMenu() and TabItem() output.
 - Log/Capture: a non terminated log ends automatically in the window which called it.
 - Log/Capture: added experimental io.ConfigWindowsCopyContentsWithCtrlC option to
diff --git a/imgui.h b/imgui.h
index 726c97f73..9fd077379 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.5 WIP"
-#define IMGUI_VERSION_NUM   19142
+#define IMGUI_VERSION_NUM   19143
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index 932a0484c..18b146777 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1111,7 +1111,7 @@ struct IMGUI_API ImGuiInputTextState
     ImStbTexteditState*     Stb;                    // State for stb_textedit.h
     ImGuiID                 ID;                     // widget id owning the text state
     int                     CurLenA;                // UTF-8 length of the string in TextA (in bytes)
-    ImVector          TextA;                  // main UTF8 buffer.
+    ImVector          TextA;                  // main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1).
     ImVector          InitialTextA;           // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
     ImVector          CallbackTextBackup;     // temporary storage for callback to support automatic reconcile of undo-stack
     int                     BufCapacityA;           // end-user buffer capacity
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index def3f5870..40e482d45 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4200,6 +4200,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons
     if (new_text == new_text_end)
         return;
 
+    // Grow internal buffer if needed
     const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;
     const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
     if (new_text_len + BufTextLen >= BufSize)
@@ -4213,7 +4214,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons
         IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID);
         IM_ASSERT(Buf == edit_state->TextA.Data);
         int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
-        edit_state->TextA.reserve(new_buf_size + 1);
+        edit_state->TextA.resize(new_buf_size + 1);
         Buf = edit_state->TextA.Data;
         BufSize = edit_state->BufCapacityA = new_buf_size;
     }
@@ -5034,7 +5035,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                         IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
                         InputTextReconcileUndoStateAfterUserCallback(state, callback_data.Buf, callback_data.BufTextLen); // FIXME: Move the rest of this block inside function and rename to InputTextReconcileStateAfterUserCallback() ?
                         state->CurLenA = callback_data.BufTextLen;  // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
-                        state->TextA.Size = state->CurLenA + 1;
                         state->CursorAnimReset();
                     }
                 }
@@ -5342,6 +5342,8 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
     Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId);
     DebugLocateItemOnHover(state->ID);
     Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->CurLenA, stb_state->cursor, stb_state->select_start, stb_state->select_end);
+    Text("TextA.Size: %d, Capacity: %d", state->TextA.Size, state->TextA.Capacity);
+    Text("BufCapacityA: %d", state->BufCapacityA);
     Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x);
     Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point);
     if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state

From 82d0584e7bbefdd5de1d181f8bcf6eb6d656d525 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 4 Nov 2024 20:24:36 +0100
Subject: [PATCH 0476/2359] InputText: using CurLenA instead of TextA.Size for
 correctness. (#7925)

Was harmless because TextA is always zero-terminated, and TextA.Size >= CurLenA + 1.
---
 imgui_widgets.cpp | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 40e482d45..01828c5e8 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3930,7 +3930,7 @@ namespace ImStb
 {
 static int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->CurLenA; }
 static char    STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->CurLenA); return obj->TextA[idx]; }
-static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->TextA.Size); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
+static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->CurLenA); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
 static char    STB_TEXTEDIT_NEWLINE = '\n';
 static void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
 {
@@ -3953,7 +3953,7 @@ static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int id
     if (idx >= obj->CurLenA)
         return obj->CurLenA + 1;
     unsigned int c;
-    return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->TextA.Size);
+    return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->CurLenA);
 }
 
 static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
@@ -3986,8 +3986,8 @@ static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
 
     const char* curr_p = obj->TextA.Data + idx;
     const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
-    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextA.Data + obj->TextA.Size);
-    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextA.Data + obj->TextA.Size);
+    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextA.Data + obj->CurLenA);
+    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextA.Data + obj->CurLenA);
 
     bool prev_white = ImCharIsBlankW(prev_c);
     bool prev_separ = ImCharIsSeparatorW(prev_c);
@@ -4002,8 +4002,8 @@ static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
 
     const char* curr_p = obj->TextA.Data + idx;
     const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
-    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextA.Data + obj->TextA.Size);
-    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextA.Data + obj->TextA.Size);
+    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextA.Data + obj->CurLenA);
+    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextA.Data + obj->CurLenA);
 
     bool prev_white = ImCharIsBlankW(prev_c);
     bool prev_separ = ImCharIsSeparatorW(prev_c);
@@ -5342,8 +5342,8 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
     Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId);
     DebugLocateItemOnHover(state->ID);
     Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->CurLenA, stb_state->cursor, stb_state->select_start, stb_state->select_end);
-    Text("TextA.Size: %d, Capacity: %d", state->TextA.Size, state->TextA.Capacity);
     Text("BufCapacityA: %d", state->BufCapacityA);
+    Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity);
     Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x);
     Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point);
     if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state

From d4791f1bbef15fa407c853bf845ee1adefb0b940 Mon Sep 17 00:00:00 2001
From: Brotcrunsher 
Date: Tue, 5 Nov 2024 10:12:52 +0100
Subject: [PATCH 0477/2359] Fixed a comment typo. (#8128)

---
 imgui.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui.h b/imgui.h
index 9fd077379..27e3bda5e 100644
--- a/imgui.h
+++ b/imgui.h
@@ -3065,7 +3065,7 @@ enum ImDrawListFlags_
 // access the current window draw list and draw custom primitives.
 // You can interleave normal ImGui:: calls and adding primitives to the current draw list.
 // In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize).
-// You are totally free to apply whatever transformation matrix to want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!)
+// You are totally free to apply whatever transformation matrix you want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!)
 // Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects.
 struct ImDrawList
 {

From 88e232739bc9da4c4070a9c912b7ebee0acc84f6 Mon Sep 17 00:00:00 2001
From: Maya Warrier <34803055+mayawarrier@users.noreply.github.com>
Date: Tue, 5 Nov 2024 04:44:39 -0500
Subject: [PATCH 0478/2359] Ignore clang warning Wnontrivial-memaccess (#8129)

Produced when memset(this, ..) is used on a non-trivially copyable type
---
 backends/imgui_impl_metal.mm | 7 +++++++
 backends/imgui_impl_osx.mm   | 7 +++++++
 imgui_draw.cpp               | 1 +
 imgui_internal.h             | 1 +
 4 files changed, 16 insertions(+)

diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm
index b8f82a65d..102f6982a 100644
--- a/backends/imgui_impl_metal.mm
+++ b/backends/imgui_impl_metal.mm
@@ -38,6 +38,13 @@
 #import 
 #import 
 
+#if defined(__clang__)
+#if __has_warning("-Wunknown-warning-option")
+#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'
+#endif
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
+#endif
+
 #pragma mark - Support classes
 
 // A wrapper around a MTLBuffer object that knows the last time it was reused
diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm
index de9b57408..6ff4f19a4 100644
--- a/backends/imgui_impl_osx.mm
+++ b/backends/imgui_impl_osx.mm
@@ -27,6 +27,13 @@
 #import 
 #import 
 
+#if defined(__clang__)
+#if __has_warning("-Wunknown-warning-option")
+#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'
+#endif
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
+#endif
+
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
 //  2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index d54c96bab..2385d2ed8 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -66,6 +66,7 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
 #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
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #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
diff --git a/imgui_internal.h b/imgui_internal.h
index 18b146777..ad90e0309 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -91,6 +91,7 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wmissing-noreturn"               // warning: function 'xxx' could be declared with attribute 'noreturn'
 #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #elif defined(__GNUC__)
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wpragmas"              // warning: unknown option after '#pragma GCC diagnostic' kind

From be2d006e2e7e9f029e893ff358d9acc87c250411 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 5 Nov 2024 10:50:49 +0100
Subject: [PATCH 0479/2359] Align warning blocks. Removed -Wunused-function,
 -Wmissing-prototypes from imgui_internal.h

As supposedly they were for stb_textedit.h which is now moved to imgui_draw.cpp
---
 imgui.cpp        | 18 +++++++++---------
 imgui.h          |  8 ++++----
 imgui_demo.cpp   | 12 ++++++------
 imgui_draw.cpp   | 14 +++++++-------
 imgui_internal.h | 12 +++++-------
 5 files changed, 31 insertions(+), 33 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index b24f75068..01a72c6b7 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1126,15 +1126,15 @@ CODE
 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
 #elif defined(__GNUC__)
 // We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
-#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 "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
-#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
-#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
-#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
-#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
-#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
-#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 "-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 "-Wint-to-pointer-cast"              // warning: cast to pointer from integer of different size
+#pragma GCC diagnostic ignored "-Wformat"                           // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
+#pragma GCC diagnostic ignored "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wconversion"                       // warning: conversion to 'xxxx' from 'xxxx' may alter its value
+#pragma GCC diagnostic ignored "-Wformat-nonliteral"                // warning: format not a string literal, format string not checked
+#pragma GCC diagnostic ignored "-Wstrict-overflow"                  // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
+#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
 #endif
 
 // Debug options
diff --git a/imgui.h b/imgui.h
index 27e3bda5e..973a52f53 100644
--- a/imgui.h
+++ b/imgui.h
@@ -130,15 +130,15 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'
 #endif
 #pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
-#pragma clang diagnostic ignored "-Wold-style-cast"
+#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 "-Wzero-as-null-pointer-constant"
+#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
 #elif defined(__GNUC__)
 #pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wpragmas"          // warning: unknown option after '#pragma GCC diagnostic' kind
-#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 "-Wpragmas"                          // warning: unknown option after '#pragma GCC diagnostic' kind
+#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
 #endif
 
 //-----------------------------------------------------------------------------
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index f44aedc6e..f5e16f06c 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -145,12 +145,12 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
 #elif defined(__GNUC__)
-#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
-#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
-#pragma GCC diagnostic ignored "-Wformat-security"          // warning: format string is not a string literal (potentially insecure)
-#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
-#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
-#pragma GCC diagnostic ignored "-Wmisleading-indentation"   // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement      // GCC 6.0+ only. See #883 on GitHub.
+#pragma GCC diagnostic ignored "-Wpragmas"                          // warning: unknown option after '#pragma GCC diagnostic' kind
+#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"              // warning: cast to pointer from integer of different size
+#pragma GCC diagnostic ignored "-Wformat-security"                  // warning: format string is not a string literal (potentially insecure)
+#pragma GCC diagnostic ignored "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wconversion"                       // warning: conversion to 'xxxx' from 'xxxx' may alter its value
+#pragma GCC diagnostic ignored "-Wmisleading-indentation"           // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement      // GCC 6.0+ only. See #883 on GitHub.
 #endif
 
 // Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!)
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 2385d2ed8..ac6d02281 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -68,12 +68,12 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
 #pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #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 "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
-#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
-#pragma GCC diagnostic ignored "-Wstack-protector"          // warning: stack protector not protecting local variables: variable length buffer
-#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 "-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 "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wconversion"                       // warning: conversion to 'xxxx' from 'xxxx' may alter its value
+#pragma GCC diagnostic ignored "-Wstack-protector"                  // warning: stack protector not protecting local variables: variable length buffer
+#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
 #endif
 
 //-------------------------------------------------------------------------
@@ -102,7 +102,7 @@ namespace IMGUI_STB_NAMESPACE
 
 #if defined(__clang__)
 #pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wunused-function"
+#pragma clang diagnostic ignored "-Wunused-function"        // warning: 'xxxx' defined but not used
 #pragma clang diagnostic ignored "-Wmissing-prototypes"
 #pragma clang diagnostic ignored "-Wimplicit-fallthrough"
 #pragma clang diagnostic ignored "-Wcast-qual"              // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier
diff --git a/imgui_internal.h b/imgui_internal.h
index ad90e0309..a35ab64e2 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -82,11 +82,9 @@ Index of this file:
 #endif
 #pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
 #pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok, for ImFloor()
-#pragma clang diagnostic ignored "-Wunused-function"                // for stb_textedit.h
-#pragma clang diagnostic ignored "-Wmissing-prototypes"             // for stb_textedit.h
-#pragma clang diagnostic ignored "-Wold-style-cast"
-#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
-#pragma clang diagnostic ignored "-Wdouble-promotion"
+#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast
+#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant
+#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function
 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
 #pragma clang diagnostic ignored "-Wmissing-noreturn"               // warning: function 'xxx' could be declared with attribute 'noreturn'
 #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
@@ -94,8 +92,8 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #elif defined(__GNUC__)
 #pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wpragmas"              // warning: unknown option after '#pragma GCC diagnostic' kind
-#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 "-Wpragmas"                          // warning: unknown option after '#pragma GCC diagnostic' kind
+#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 "-Wdeprecated-enum-enum-conversion"  // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
 #endif
 

From 63234f8dd0a2acf5fa48184798382ea1e045ab3a Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 5 Nov 2024 11:32:02 +0100
Subject: [PATCH 0480/2359] InputText: Internals: rename CurLenA->TextLen,
 InitialTextA->TextToRevertTo.

Follow the refactors in #7925.
---
 imgui_internal.h  | 10 ++---
 imgui_widgets.cpp | 96 +++++++++++++++++++++++------------------------
 2 files changed, 53 insertions(+), 53 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index a35ab64e2..6d84f1027 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1109,11 +1109,11 @@ struct IMGUI_API ImGuiInputTextState
     ImGuiContext*           Ctx;                    // parent UI context (needs to be set explicitly by parent).
     ImStbTexteditState*     Stb;                    // State for stb_textedit.h
     ImGuiID                 ID;                     // widget id owning the text state
-    int                     CurLenA;                // UTF-8 length of the string in TextA (in bytes)
+    int                     TextLen;                // UTF-8 length of the string in TextA (in bytes)
     ImVector          TextA;                  // main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1).
-    ImVector          InitialTextA;           // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
+    ImVector          TextToRevertTo;         // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
     ImVector          CallbackTextBackup;     // temporary storage for callback to support automatic reconcile of undo-stack
-    int                     BufCapacityA;           // end-user buffer capacity
+    int                     BufCapacity;            // end-user buffer capacity (include zero terminator)
     ImVec2                  Scroll;                 // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y)
     float                   CursorAnim;             // timer for cursor blink, reset on every user action so the cursor reappears immediately
     bool                    CursorFollow;           // set when we want scrolling to follow the current cursor position (not always!)
@@ -1126,8 +1126,8 @@ struct IMGUI_API ImGuiInputTextState
 
     ImGuiInputTextState();
     ~ImGuiInputTextState();
-    void        ClearText()                 { CurLenA = 0; TextA[0] = 0; CursorClamp(); }
-    void        ClearFreeMemory()           { TextA.clear(); InitialTextA.clear(); }
+    void        ClearText()                 { TextLen = 0; TextA[0] = 0; CursorClamp(); }
+    void        ClearFreeMemory()           { TextA.clear(); TextToRevertTo.clear(); }
     void        OnKeyPressed(int key);      // Cannot be inline because we call in code in stb_textedit.h implementation
     void        OnCharPressed(unsigned int c);
 
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 01828c5e8..9d5724222 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3928,15 +3928,15 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c
 // - ...but we don't use that feature.
 namespace ImStb
 {
-static int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->CurLenA; }
-static char    STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->CurLenA); return obj->TextA[idx]; }
-static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->CurLenA); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
+static int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->TextLen; }
+static char    STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->TextLen); return obj->TextA[idx]; }
+static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
 static char    STB_TEXTEDIT_NEWLINE = '\n';
 static void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
 {
     const char* text = obj->TextA.Data;
     const char* text_remaining = NULL;
-    const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->CurLenA, &text_remaining, NULL, true);
+    const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, &text_remaining, NULL, true);
     r->x0 = 0.0f;
     r->x1 = size.x;
     r->baseline_y_delta = size.y;
@@ -3950,10 +3950,10 @@ static void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* ob
 
 static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
 {
-    if (idx >= obj->CurLenA)
-        return obj->CurLenA + 1;
+    if (idx >= obj->TextLen)
+        return obj->TextLen + 1;
     unsigned int c;
-    return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->CurLenA);
+    return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->TextLen);
 }
 
 static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
@@ -3986,8 +3986,8 @@ static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
 
     const char* curr_p = obj->TextA.Data + idx;
     const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
-    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextA.Data + obj->CurLenA);
-    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextA.Data + obj->CurLenA);
+    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextA.Data + obj->TextLen);
+    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextA.Data + obj->TextLen);
 
     bool prev_white = ImCharIsBlankW(prev_c);
     bool prev_separ = ImCharIsSeparatorW(prev_c);
@@ -4002,8 +4002,8 @@ static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
 
     const char* curr_p = obj->TextA.Data + idx;
     const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
-    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextA.Data + obj->CurLenA);
-    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextA.Data + obj->CurLenA);
+    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextA.Data + obj->TextLen);
+    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextA.Data + obj->TextLen);
 
     bool prev_white = ImCharIsBlankW(prev_c);
     bool prev_separ = ImCharIsSeparatorW(prev_c);
@@ -4020,7 +4020,7 @@ static int  STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)
 }
 static int  STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)
 {
-    int len = obj->CurLenA;
+    int len = obj->TextLen;
     idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
     while (idx < len && !is_word_boundary_from_left(obj, idx))
         idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
@@ -4029,7 +4029,7 @@ static int  STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)
 static int  STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)
 {
     idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
-    int len = obj->CurLenA;
+    int len = obj->TextLen;
     while (idx < len && !is_word_boundary_from_right(obj, idx))
         idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
     return idx > len ? len : idx;
@@ -4043,7 +4043,7 @@ static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
     char* dst = obj->TextA.Data + pos;
 
     obj->Edited = true;
-    obj->CurLenA -= n;
+    obj->TextLen -= n;
 
     // Offset remaining text (FIXME-OPT: Use memmove)
     const char* src = obj->TextA.Data + pos + n;
@@ -4055,10 +4055,10 @@ static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
 static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len)
 {
     const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0;
-    const int text_len = obj->CurLenA;
+    const int text_len = obj->TextLen;
     IM_ASSERT(pos <= text_len);
 
-    if (!is_resizable && (new_text_len + obj->CurLenA + 1 > obj->BufCapacityA))
+    if (!is_resizable && (new_text_len + obj->TextLen + 1 > obj->BufCapacity))
         return false;
 
     // Grow internal buffer if needed
@@ -4075,8 +4075,8 @@ static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ch
     memcpy(text + pos, new_text, (size_t)new_text_len);
 
     obj->Edited = true;
-    obj->CurLenA += new_text_len;
-    obj->TextA[obj->CurLenA] = '\0';
+    obj->TextLen += new_text_len;
+    obj->TextA[obj->TextLen] = '\0';
 
     return true;
 }
@@ -4108,8 +4108,8 @@ static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ch
 // the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?)
 static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len)
 {
-    stb_text_makeundo_replace(str, state, 0, str->CurLenA, text_len);
-    ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->CurLenA);
+    stb_text_makeundo_replace(str, state, 0, str->TextLen, text_len);
+    ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->TextLen);
     state->cursor = state->select_start = state->select_end = 0;
     if (text_len <= 0)
         return;
@@ -4157,13 +4157,13 @@ void ImGuiInputTextState::OnCharPressed(unsigned int c)
 
 // Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header.
 void ImGuiInputTextState::CursorAnimReset()                 { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
-void ImGuiInputTextState::CursorClamp()                     { Stb->cursor = ImMin(Stb->cursor, CurLenA); Stb->select_start = ImMin(Stb->select_start, CurLenA); Stb->select_end = ImMin(Stb->select_end, CurLenA); }
+void ImGuiInputTextState::CursorClamp()                     { Stb->cursor = ImMin(Stb->cursor, TextLen); Stb->select_start = ImMin(Stb->select_start, TextLen); Stb->select_end = ImMin(Stb->select_end, TextLen); }
 bool ImGuiInputTextState::HasSelection() const              { return Stb->select_start != Stb->select_end; }
 void ImGuiInputTextState::ClearSelection()                  { Stb->select_start = Stb->select_end = Stb->cursor; }
 int  ImGuiInputTextState::GetCursorPos() const              { return Stb->cursor; }
 int  ImGuiInputTextState::GetSelectionStart() const         { return Stb->select_start; }
 int  ImGuiInputTextState::GetSelectionEnd() const           { return Stb->select_end; }
-void ImGuiInputTextState::SelectAll()                       { Stb->select_start = 0; Stb->cursor = Stb->select_end = CurLenA; Stb->has_preferred_x = 0; }
+void ImGuiInputTextState::SelectAll()                       { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; }
 void ImGuiInputTextState::ReloadUserBufAndSelectAll()       { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
 void ImGuiInputTextState::ReloadUserBufAndKeepSelection()   { ReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
 void ImGuiInputTextState::ReloadUserBufAndMoveToEnd()       { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
@@ -4216,7 +4216,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons
         int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
         edit_state->TextA.resize(new_buf_size + 1);
         Buf = edit_state->TextA.Data;
-        BufSize = edit_state->BufCapacityA = new_buf_size;
+        BufSize = edit_state->BufCapacity = new_buf_size;
     }
 
     if (BufTextLen != pos)
@@ -4380,8 +4380,8 @@ void ImGui::InputTextDeactivateHook(ImGuiID id)
     else
     {
         IM_ASSERT(state->TextA.Data != 0);
-        g.InputTextDeactivatedState.TextA.resize(state->CurLenA + 1);
-        memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->CurLenA + 1);
+        g.InputTextDeactivatedState.TextA.resize(state->TextLen + 1);
+        memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->TextLen + 1);
     }
 }
 
@@ -4521,21 +4521,21 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         if (!init_reload_from_user_buf)
         {
             // Take a copy of the initial buffer value.
-            state->InitialTextA.resize(buf_len + 1);    // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
-            memcpy(state->InitialTextA.Data, buf, buf_len + 1);
+            state->TextToRevertTo.resize(buf_len + 1);    // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
+            memcpy(state->TextToRevertTo.Data, buf, buf_len + 1);
         }
 
         // Preserve cursor position and undo/redo stack if we come back to same widget
         // FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
         bool recycle_state = (state->ID == id && !init_changed_specs && !init_reload_from_user_buf);
-        if (recycle_state && (state->CurLenA != buf_len || (strncmp(state->TextA.Data, buf, buf_len) != 0)))
+        if (recycle_state && (state->TextLen != buf_len || (strncmp(state->TextA.Data, buf, buf_len) != 0)))
             recycle_state = false;
 
         // Start edition
         state->ID = id;
         state->TextA.resize(buf_size + 1);          // we use +1 to make sure that .Data is always pointing to at least an empty string.
-        state->CurLenA = (int)strlen(buf);
-        memcpy(state->TextA.Data, buf, state->CurLenA + 1);
+        state->TextLen = (int)strlen(buf);
+        memcpy(state->TextA.Data, buf, state->TextLen + 1);
 
         if (recycle_state)
         {
@@ -4646,7 +4646,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     {
         IM_ASSERT(state != NULL);
         state->Edited = false;
-        state->BufCapacityA = buf_size;
+        state->BufCapacity = buf_size;
         state->Flags = flags;
 
         // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
@@ -4871,7 +4871,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
             {
                 const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0;
-                const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->CurLenA;
+                const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->TextLen;
 
                 char backup = state->TextA.Data[ie];
                 state->TextA.Data[ie] = 0; // A bit of a hack since SetClipboardText only takes null terminated strings
@@ -4936,15 +4936,15 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                 IMSTB_TEXTEDIT_CHARTYPE empty_string;
                 stb_textedit_replace(state, state->Stb, &empty_string, 0);
             }
-            else if (strcmp(buf, state->InitialTextA.Data) != 0)
+            else if (strcmp(buf, state->TextToRevertTo.Data) != 0)
             {
-                apply_new_text = state->InitialTextA.Data;
-                apply_new_text_length = state->InitialTextA.Size - 1;
+                apply_new_text = state->TextToRevertTo.Data;
+                apply_new_text_length = state->TextToRevertTo.Size - 1;
 
                 // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
                 // Push records into the undo stack so we can CTRL+Z the revert operation itself
                 value_changed = true;
-                stb_textedit_replace(state, state->Stb, state->InitialTextA.Data, state->InitialTextA.Size - 1);
+                stb_textedit_replace(state, state->Stb, state->TextToRevertTo.Data, state->TextToRevertTo.Size - 1);
             }
         }
 
@@ -5003,14 +5003,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     callback_data.UserData = callback_user_data;
 
                     // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925
-                    state->CallbackTextBackup.resize(state->CurLenA + 1);
-                    memcpy(state->CallbackTextBackup.Data, state->TextA.Data, state->CurLenA + 1);
+                    state->CallbackTextBackup.resize(state->TextLen + 1);
+                    memcpy(state->CallbackTextBackup.Data, state->TextA.Data, state->TextLen + 1);
 
                     char* callback_buf = is_readonly ? buf : state->TextA.Data;
                     callback_data.EventKey = event_key;
                     callback_data.Buf = callback_buf;
-                    callback_data.BufTextLen = state->CurLenA;
-                    callback_data.BufSize = state->BufCapacityA;
+                    callback_data.BufTextLen = state->TextLen;
+                    callback_data.BufSize = state->BufCapacity;
                     callback_data.BufDirty = false;
 
                     const int utf8_cursor_pos = callback_data.CursorPos = state->Stb->cursor;
@@ -5023,7 +5023,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     // Read back what user may have modified
                     callback_buf = is_readonly ? buf : state->TextA.Data; // Pointer may have been invalidated by a resize callback
                     IM_ASSERT(callback_data.Buf == callback_buf);         // Invalid to modify those fields
-                    IM_ASSERT(callback_data.BufSize == state->BufCapacityA);
+                    IM_ASSERT(callback_data.BufSize == state->BufCapacity);
                     IM_ASSERT(callback_data.Flags == flags);
                     const bool buf_dirty = callback_data.BufDirty;
                     if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty)            { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; }
@@ -5034,7 +5034,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                         // Callback may update buffer and thus set buf_dirty even in read-only mode.
                         IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
                         InputTextReconcileUndoStateAfterUserCallback(state, callback_data.Buf, callback_data.BufTextLen); // FIXME: Move the rest of this block inside function and rename to InputTextReconcileStateAfterUserCallback() ?
-                        state->CurLenA = callback_data.BufTextLen;  // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
+                        state->TextLen = callback_data.BufTextLen;  // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
                         state->CursorAnimReset();
                     }
                 }
@@ -5044,7 +5044,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             if (!is_readonly && strcmp(state->TextA.Data, buf) != 0)
             {
                 apply_new_text = state->TextA.Data;
-                apply_new_text_length = state->CurLenA;
+                apply_new_text_length = state->TextLen;
                 value_changed = true;
             }
         }
@@ -5128,7 +5128,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     {
         IM_ASSERT(state != NULL);
         if (!is_displaying_hint)
-            buf_display_end = buf_display + state->CurLenA;
+            buf_display_end = buf_display + state->TextLen;
 
         // Render text (with cursor and selection)
         // This is going to be messy. We need to:
@@ -5138,7 +5138,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
         // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
         const char* text_begin = state->TextA.Data;
-        const char* text_end = text_begin + state->CurLenA;
+        const char* text_end = text_begin + state->TextLen;
         ImVec2 cursor_offset, select_start_offset;
 
         {
@@ -5280,7 +5280,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         if (is_multiline)
             text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width
         else if (!is_displaying_hint && g.ActiveId == id)
-            buf_display_end = buf_display + state->CurLenA;
+            buf_display_end = buf_display + state->TextLen;
         else if (!is_displaying_hint)
             buf_display_end = buf_display + strlen(buf_display);
 
@@ -5341,8 +5341,8 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
     ImStb::StbUndoState* undo_state = &stb_state->undostate;
     Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId);
     DebugLocateItemOnHover(state->ID);
-    Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->CurLenA, stb_state->cursor, stb_state->select_start, stb_state->select_end);
-    Text("BufCapacityA: %d", state->BufCapacityA);
+    Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->TextLen, stb_state->cursor, stb_state->select_start, stb_state->select_end);
+    Text("BufCapacityA: %d", state->BufCapacity);
     Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity);
     Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x);
     Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point);

From ec2f1d69c8d8d6373d64ee0ffb29b51b78925d65 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 5 Nov 2024 13:18:16 +0100
Subject: [PATCH 0481/2359] Docs: word-wrap some the older changelogs.

---
 docs/CHANGELOG.txt | 765 +++++++++++++++++++++++++++++++--------------
 1 file changed, 523 insertions(+), 242 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 7bb626478..9e43a56a1 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -4597,20 +4597,27 @@ Other Changes:
   - See https://github.com/ocornut/imgui/issues/1599 for recommended gamepad mapping or download PNG/PSD at http://goo.gl/9LgVZW
   - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. Read imgui.cpp for more details.
 - To use Keyboard Navigation:
-  - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
-  - Basic controls: arrows to navigate, Alt to enter menus, Space to activate item, Enter to edit text, Escape to cancel/close, Ctrl-Tab to focus windows, etc.
-  - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag will be set.
-    For more advanced uses, you may want to read from io.NavActive or io.NavVisible. Read imgui.cpp for more details.
+  - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically
+    fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
+  - Basic controls: arrows to navigate, Alt to enter menus, Space to activate item, Enter to edit text,
+    Escape to cancel/close, Ctrl-Tab to focus windows, etc.
+  - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard),
+    the io.WantCaptureKeyboard flag will be set.
+  - For more advanced uses, you may want to read from io.NavActive or io.NavVisible. Read imgui.cpp for more details.
 - Navigation: SetItemDefaultFocus() sets the navigation position in addition to scrolling. (#787)
 - Navigation: Added IsItemFocused(), added IsAnyItemFocused(). (#787)
 - Navigation: Added window flags: ImGuiWindowFlags_NoNav (== ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus).
 - Navigation: Style: Added ImGuiCol_NavHighlight, ImGuiCol_NavWindowingHighlight colors. (#787)
 - Navigation: TreeNode: Added ImGuiTreeNodeFlags_NavLeftJumpsBackHere flag to allow Nav Left direction to jump back to parent tree node from any of its child. (#1079)
 - Navigation: IO: Added io.ConfigFlags (input), io.NavActive (output), io.NavVisible (output). (#787)
-- Context: Removed the default global context and font atlas instances, which caused various problems to users of multiple contexts and DLL users. (#1565, #1599)
-  YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END. Existing apps will assert/crash without it.
-- Context: Added SetAllocatorFunctions() to rewire memory allocators (as a replacement to previous parameters to CreateContext()). Allocators are shared by all contexts and imgui helpers. (#1565, #586, #992, #1007, #1558)
-- Context: You may pass a ImFontAtlas to CreateContext() to specify a font atlas to share. Shared font atlas are not owned by the context and not destroyed along with it. (#1599)
+- Context: Removed the default global context and font atlas instances, which caused various
+  problems to users of multiple contexts and DLL users. (#1565, #1599) YOU NOW NEED TO CALL
+  ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
+  Existing apps will assert/crash without it.
+- Context: Added SetAllocatorFunctions() to rewire memory allocators (as a replacement to previous
+  parameters to CreateContext()). Allocators are shared by all contexts and imgui helpers. (#1565, #586, #992, #1007, #1558)
+- Context: You may pass a ImFontAtlas to CreateContext() to specify a font atlas to share.
+  Shared font atlas are not owned by the context and not destroyed along with it. (#1599)
 - Context: Added IMGUI_DISABLE_DEFAULT_ALLOCATORS to disable linking with malloc/free. (#1565, #586, #992, #1007, #1558)
 - IO: Added io.ConfigFlags for user application to store settings for imgui and for the backend:
   - ImGuiConfigFlags_NavEnableKeyboard: Enable keyboard navigation.
@@ -4619,61 +4626,85 @@ Other Changes:
   - ImGuiConfigFlags_NoMouseCursorChange: Instruct backend to not alter mouse cursor shape and visibility (by default the example backend use mouse cursor API of the platform when available)
   - ImGuiConfigFlags_NoMouse: Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information passed by the backend.
   - ImGuiConfigFlags_IsSRGB, ImGuiConfigFlags_IsTouchScreen: Flags for general application use.
-- IO: Added io.BackendFlags for backend to store its capabilities (currently: _HasGamepad, _HasMouseCursors, _HasSetMousePos). This will be used more in the next version.
+- IO: Added io.BackendFlags for backend to store its capabilities (currently: _HasGamepad,
+  _HasMouseCursors, _HasSetMousePos). This will be used more in the next version.
 - IO: Added ImGuiKey_Insert, ImGuiKey_Space keys. Setup in all example backends. (#1541)
 - IO: Added Horizontal Mouse Wheel support for horizontal scrolling. (#1463) [@tseeker]
 - IO: Added IsAnyMouseDown() helper which is helpful for backends to handle mouse capturing.
-- Window: Clicking on a window with the ImGuiWIndowFlags_NoMove flags takes an ActiveId so we can't hover something else when dragging afterwards. (#1381, #1337)
-- Window: IsWindowHovered(): Added ImGuiHoveredFlags_AnyWindow, ImGuiFocusedFlags_AnyWindow flags (See Breaking Changes). Added to demo. (#1382)
-- Window: Added SetNextWindowBgAlpha() helper. Particularly helpful since the legacy 5-parameters version of Begin() has been marked as obsolete in 1.53. (#1567)
-- Window: Fixed SetNextWindowContentSize() with 0.0f on Y axis (or SetNextWindowContentWidth()) overwriting the contents size. Got broken on Dec 10 (1.53). (#1363)
+- Window: Clicking on a window with the ImGuiWIndowFlags_NoMove flags takes an ActiveId so
+  we can't hover something else when dragging afterwards. (#1381, #1337)
+- Window: IsWindowHovered(): Added ImGuiHoveredFlags_AnyWindow, ImGuiFocusedFlags_AnyWindow flags
+  (See Breaking Changes). Added to demo. (#1382)
+- Window: Added SetNextWindowBgAlpha() helper. Particularly helpful since the legacy 5-parameters
+  version of Begin() has been marked as obsolete in 1.53. (#1567)
+- Window: Fixed SetNextWindowContentSize() with 0.0f on Y axis (or SetNextWindowContentWidth())
+  overwriting the contents size. Got broken on Dec 10 (1.53). (#1363)
 - ArrowButton: Added ArrowButton() given a cardinal direction (e.g. ImGuiDir_Left).
 - InputText: Added alternative clipboard shortcuts: Shift+Delete (cut), CTRL+Insert (copy), Shift+Insert (paste). (#1541)
-- InputText: Fixed losing Cursor X position when clicking outside on an item that's submitted after the InputText(). It was only noticeable when restoring focus programmatically. (#1418, #1554)
-- InputText: Added ImGuiInputTextFlags_CharsScientific flag to also allow 'e'/'E' for input of values using scientific notation. Automatically used by InputFloat.
+- InputText: Fixed losing Cursor X position when clicking outside on an item that's submitted
+  after the InputText(). It was only noticeable when restoring focus programmatically. (#1418, #1554)
+- InputText: Added ImGuiInputTextFlags_CharsScientific flag to also allow 'e'/'E' for input of values
+  using scientific notation. Automatically used by InputFloat.
 - Style: Default style is now StyleColorsDark(), instead of the old StyleColorsClassic(). (#707)
 - Style: Enable window border by default. (#707)
-- Style: Exposed ImGuiStyleVar_WindowTitleAlign, ImGuiStyleVar_ScrollbarSize, ImGuiStyleVar_ScrollbarRounding, ImGuiStyleVar_GrabRounding + added an assert to reduce accidental breakage. (#1181)
+- Style: Exposed ImGuiStyleVar_WindowTitleAlign, ImGuiStyleVar_ScrollbarSize, ImGuiStyleVar_ScrollbarRounding,
+  ImGuiStyleVar_GrabRounding + added an assert to reduce accidental breakage. (#1181)
 - Style: Added style.MouseCursorScale help when using the software mouse cursor facility. (#939).
 - Style: Close button nows display a cross before hovering. Fixed cross positioning being a little off. Uses button colors for highlight when hovering. (#707)
 - Popup: OpenPopup() Always reopen existing pop-ups. (Removed imgui_internal.h's OpenPopupEx() which was used for this.) (#1497, #1533).
 - Popup: BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick() all react on mouse release instead of mouse press. (~#439)
-- Popup: Better handling of user mistakenly calling OpenPopup() every frame (with reopen_existing option). The error will now be more visible and easier to understand. (#1497)
+- Popup: Better handling of user mistakenly calling OpenPopup() every frame (with the 'reopen_existing' option).
+  The error will now be more visible and easier to understand. (#1497)
 - Popup: BeginPopup(): Exposed extra_flags parameter that are passed through to Begin(). (#1533)
-- Popup: BeginPopupModal: fixed the conditional test for SetNextWindowPos() which was polling the wrong window, which in practice made the test succeed all the time.
+- Popup: BeginPopupModal: fixed the conditional test for SetNextWindowPos() which was polling
+  the wrong window, which in practice made the test succeed all the time.
 - Tooltip: BeginTooltip() sets ImGuiWindowFlags_NoInputs flag.
-- Scrollbar: Fixed ScrollbarY enable test after ScrollbarX has been enabled being a little off (small regression from Nov 2017). (#1574)
-- Scrollbar: Fixed ScrollbarX enable test subtracting WindowPadding.x (this has been there since the addition of horizontal scroll bar!).
+- Scrollbar: Fixed ScrollbarY enable test after ScrollbarX has been enabled being a little
+  off (small regression from Nov 2017). (#1574)
+- Scrollbar: Fixed ScrollbarX enable test subtracting WindowPadding.x (this has been there
+  since the addition of horizontal scroll bar!).
 - Columns: Clear offsets data when columns count changed. (#1525)
 - Columns: Fixed a memory leak of ImGuiColumnsSet's Columns vector. (#1529) [@unprompted]
 - Columns: Fixed resizing a window very small breaking some columns positioning (broken in 1.53).
-- Columns: The available column extent takes consideration of the right-most clipped pixel, so the right-most column may look a little wider but will contain the same amount of visible contents.
+- Columns: The available column extent takes consideration of the right-most clipped pixel,
+  so the right-most column may look a little wider but will contain the same amount of visible contents.
 - MenuBar: Fixed menu bar pushing a clipping rect outside of its allocated bound (usually unnoticeable).
 - TreeNode: nodes with the ImGuiTreeNodeFlags_Leaf flag correctly disable highlight when DragDrop is active. (#143, #581)
 - Drag and Drop: Increased payload type string to 32 characters instead of 8. (#143)
 - Drag and Drop: TreeNode as drop target displays rectangle over full frame. (#1597, #143)
 - DragFloat: Fix/workaround for backends which do not preserve a valid mouse position when dragged out of bounds. (#1559)
 - InputFloat: Allow inputing value using scientific notation e.g. "1e+10".
-- InputDouble: Added InputDouble() function. We use a format string instead of a decimal_precision parameter to also for "%e" and variants. (#1011)
+- InputDouble: Added InputDouble() function. We use a format string instead of a 'decimal_precision'
+  parameter to also for "%e" and variants. (#1011)
 - Slider, Combo: Use ImGuiCol_FrameBgHovered color when hovered. (#1456) [@stfx]
-- Combo: BeginCombo(): Added ImGuiComboFlags_NoArrowButton to disable the arrow button and only display the wide value preview box.
-- Combo: BeginCombo(): Added ImGuiComboFlags_NoPreview to disable the preview and only display a square arrow button.
+- Combo: BeginCombo(): Added ImGuiComboFlags_NoArrowButton to disable the arrow button and
+  only display the wide value preview box.
+- Combo: BeginCombo(): Added ImGuiComboFlags_NoPreview to disable the preview and only
+  display a square arrow button.
 - Combo: Arrow button isn't displayed over frame background so its blended color matches other buttons. Left side of the button isn't rounded.
 - PlotLines: plot a flat line if scale_min==scale_max. (#1621)
-- Fonts: Changed DisplayOffset.y to defaults to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer.
-  If you were adding or subtracting (not assigning) to ImFont::DisplayOffset check if your fonts are correctly aligned vertically. (#1619)
+- Fonts: Changed DisplayOffset.y to defaults to 0 instead of +1. Fixed rounding of Ascent/Descent
+  to match TrueType renderer. If you were adding or subtracting (not assigning) to ImFont::DisplayOffset
+  check if your fonts are correctly aligned vertically. (#1619)
 - Fonts: Updated stb_truetype from 1.14 to stb_truetype 1.19. (w/ include fix from some platforms #1622)
 - Fonts: Added optional FreeType rasterizer in misc/freetype. Moved from imgui_club repo. (#618) [@Vuhdo, @mikesart, @ocornut]
 - Fonts: Moved extra_fonts/ to misc/fonts/.
 - ImFontAtlas: Fixed cfg.MergeMode not reusing existing glyphs if available (always overwrote).
-- ImFontAtlas: Handle stb_truetype stbtt_InitFont() and stbtt_PackBegin() possible failures more gracefully, GetTexDataAsRGBA32() won't crash during conversion. (#1527)
-- ImFontAtlas: Moved mouse cursor data out of ImGuiContext, fix drawing them with multiple contexts. Also remove the last remaining undesirable dependency on ImGui in imgui_draw.cpp. (#939)
-- ImFontAtlas: Added ImFontAtlasFlags_NoPowerOfTwoHeight flag to disable padding font height to nearest power of two. (#1613)
-- ImFontAtlas: Added ImFontAtlasFlags_NoMouseCursors flag to disable baking software mouse cursors, mostly to save texture memory on very low end hardware. (#1613)
-- ImDrawList: Fixed AddRect() with anti-aliasing disabled (lower-right corner pixel was often missing, rounding looks a little better.) (#1646)
+- ImFontAtlas: Handle stb_truetype stbtt_InitFont() and stbtt_PackBegin() possible failures
+  more gracefully, GetTexDataAsRGBA32() won't crash during conversion. (#1527)
+- ImFontAtlas: Moved mouse cursor data out of ImGuiContext, fix drawing them with multiple contexts.
+  Also remove the last remaining undesirable dependency on ImGui in imgui_draw.cpp. (#939)
+- ImFontAtlas: Added ImFontAtlasFlags_NoPowerOfTwoHeight flag to disable padding font height
+  to nearest power of two. (#1613)
+- ImFontAtlas: Added ImFontAtlasFlags_NoMouseCursors flag to disable baking software mouse cursors,
+  mostly to save texture memory on very low end hardware. (#1613)
+- ImDrawList: Fixed AddRect() with anti-aliasing disabled (lower-right corner pixel was often
+  missing, rounding looks a little better.) (#1646)
 - ImDrawList: Added CloneOutput() helper to facilitate the cloning of ImDrawData or ImDrawList for multi-threaded rendering.
-- Misc: Functions passed to libc qsort are explicitly marked cdecl to support compiling with vectorcall as the default calling convention. (#1230, #1611) [@RandyGaul]
-- Misc: ImVec2: added [] operator. This is becoming desirable for some code working of either axes independently. Better adding it sooner than later.
+- Misc: Functions passed to libc qsort are explicitly marked cdecl to support compiling with
+  vectorcall as the default calling convention. (#1230, #1611) [@RandyGaul]
+- Misc: ImVec2: added [] operator. This is becoming desirable for some code working of either
+  axes independently. Better adding it sooner than later.
 - Misc: NewFrame(): Added an assert to detect incorrect filling of the io.KeyMap[] array earlier. (#1555)
 - Misc: Added IM_OFFSETOF() helper in imgui.h (previously was in imgui_internal.h)
 - Misc: Added IM_NEW(), IM_DELETE() helpers in imgui.h (previously were in imgui_internal.h)
@@ -4692,7 +4723,8 @@ Other Changes:
 - Examples: Using Dark theme by default. (#707). Tweaked demo code.
 - Examples: Added support for horizontal mouse wheel for API that allows it. (#1463) [@tseeker]
 - Examples: All examples now setup the io.BackendFlags to signify they can honor mouse cursors, gamepad, etc.
-- Examples: DirectX10: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example but removed in 1.47 (Nov 2015) in every other backends. (#1733)
+- Examples: DirectX10: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that
+  was left in DX10 example but removed in 1.47 (Nov 2015) in every other backends. (#1733)
 - Examples: DirectX12: Added DirectX 12 example. (#301) [@jdm3]
 - Examples: OpenGL3+GLFW,SDL: Changed GLSL shader version from 330 to 150. (#1466, #1504)
 - Examples: OpenGL3+GLFW,SDL: Added a way to override the GLSL version string in the Init function. (#1466, #1504).
@@ -4706,11 +4738,13 @@ Other Changes:
 - Examples: GLFW: Added support for mouse cursor shapes (the diagonal resize cursors are unfortunately not supported by GLFW at the moment. (#1495)
 - Examples: GLFW: Don't attempt to change the mouse cursor input mode if it is set to GLFW_CURSOR_DISABLED by the application. (#1202) [@PhilCK]
 - Examples: SDL: Added support for mouse cursor shapes. (#1626) [@olls]
-- Examples: SDL: Using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging (SDL 2.0.4+ only, otherwise using SDL_WINDOW_INPUT_FOCUS instead of previously SDL_WINDOW_MOUSE_FOCUS). (#1559)
+- Examples: SDL: Using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging
+  (SDL 2.0.4+ only, otherwise using SDL_WINDOW_INPUT_FOCUS instead of previously SDL_WINDOW_MOUSE_FOCUS). (#1559)
 - Examples: SDL: Enabled vsync by default so people don't come at us when the examples are running at 2000 FPS and burning a CPU core.
 - Examples: SDL: Using SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency() to handle frame-rate over 1000 FPS properly. (#996)
 - Examples: SDL: Using scan-code exclusively instead of a confusing mixture of scan-codes and key-codes.
-- Examples: SDL: Visual Studio: Added .vcxproj file. Using %SDL2_DIR% in the default .vcxproj and build files instead of %SDL_DIR%, the earlier being more standard.
+- Examples: SDL: Visual Studio: Added .vcxproj file. Using %SDL2_DIR% in the default .vcxproj
+  and build files instead of %SDL_DIR%, the earlier being more standard.
 - Examples: Vulkan: Visual Studio: Added .vcxproj file.
 - Examples: Apple: Fixed filenames in OSX xcode project. Various other Mac friendly fixes. [@gerryhernandez etc.]
 - Examples: Visual Studio: Disabled extraneous function-level check in Release build.
@@ -4756,41 +4790,63 @@ Other Changes:
   - See ImGuiDragDropFlags for various options.
   - The ColorEdit4() and ColorButton() widgets now support Drag and Drop.
   - The API is tagged as Beta as it still may be subject to small changes.
-- Drag and Drop: When drag and drop is active, tree nodes and collapsing header can be opened by hovering on them for 0.7 seconds.
-- Renamed io.OSXBehaviors to io.OptMacOSXBehaviors. Should not affect users as the compile-time default is usually enough. (#473, #650)
+- Drag and Drop: When drag and drop is active, tree nodes and collapsing header can be opened
+  by hovering on them for 0.7 seconds.
+- Renamed io.OSXBehaviors to io.OptMacOSXBehaviors. Should not affect users as the compile-time
+  default is usually enough. (#473, #650)
 - Style: Added StyleColorsDark() style. (#707) [@dougbinks]
 - Style: Added StyleColorsLight() style. Best used with frame borders + thicker font than the default font. (#707)
 - Style: Added style.PopupRounding setting. (#1112)
-- Style: Added style.FrameBorderSize, style.WindowBorderSize, style.PopupBorderSize. Removed ImGuiWindowFlags_ShowBorders window flag!
+- Style: Added style.FrameBorderSize, style.WindowBorderSize, style.PopupBorderSize.
+  Removed ImGuiWindowFlags_ShowBorders window flag!
   Borders are now fully set up in the ImGuiStyle structure. Use ImGui::ShowStyleEditor() to look them up. (#707, fix #819, #1031)
 - Style: Various small changes to the classic style (most noticeably, buttons are now using blue shades). (#707)
 - Style: Renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
 - Style: Renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
 - Style: Removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency. (#707)
 - Style: Made the ScaleAllSizes() helper rounds down every values so they are aligned on integers.
-- Focus: Added SetItemDefaultFocus(), which in the current (master) branch behave the same as doing `if (IsWindowAppearing()) SetScrollHere()`.
-  In the navigation branch this will also set the default focus. Prefer using this when creating combo boxes with `BeginCombo()` so your code will be forward-compatible with gamepad/keyboard navigation features. (#787)
-- Combo: Pop-up grows horizontally to accommodate for contents that is larger then the parent combo button.
-- Combo: Added BeginCombo()/EndCombo() API which allows use to submit content of any form and manage your selection state without relying on indices.
-- Combo: Added ImGuiComboFlags_PopupAlignLeft flag to BeginCombo() to prioritize keeping the pop-up on the left side (for small-button-looking combos).
-- Combo: Added ImGuiComboFlags_HeightSmall, ImGuiComboFlags_HeightLarge, ImGuiComboFlags_HeightLargest to easily provide desired pop-up height.
-- Combo: You can use SetNextWindowSizeConstraints() before BeginCombo() to specify specific pop-up width/height constraints.
+- Focus: Added SetItemDefaultFocus(), which in the current (master) branch behave the same
+  as doing `if (IsWindowAppearing()) SetScrollHere()`. In the navigation branch this will also
+  set the default focus. Prefer using this when creating combo boxes with `BeginCombo()` so your
+  code will be forward-compatible with gamepad/keyboard navigation features. (#787)
+- Combo: Pop-up grows horizontally to accommodate for contents that is larger then the parent
+  combo button.
+- Combo: Added BeginCombo()/EndCombo() API which allows use to submit content of any form and
+  manage your selection state without relying on indices.
+- Combo: Added ImGuiComboFlags_PopupAlignLeft flag to BeginCombo() to prioritize keeping the
+  pop-up on the left side (for small-button-looking combos).
+- Combo: Added ImGuiComboFlags_HeightSmall, ImGuiComboFlags_HeightLarge, ImGuiComboFlags_HeightLargest
+  to easily provide desired pop-up height.
+- Combo: You can use SetNextWindowSizeConstraints() before BeginCombo() to specify specific
+  pop-up width/height constraints.
 - Combo: Offset popup position by border size so that a double border isn't so visible. (#707)
 - Combo: Recycling windows by using a stack number instead of a unique id, wasting less memory (like menus do).
 - InputText: Added ImGuiInputTextFlags_NoUndoRedo flag. (#1506, #1508) [@ibachar]
-- Window: Fixed auto-resize allocating too much space for scrollbar when SizeContents is bigger than maximum window size (fixes c0547d3). (#1417)
-- Window: Child windows with MenuBar use regular WindowPadding.y so layout look consistent as child or as a regular window.
-- Window: Begin(): Fixed appending into a child window with a second Begin() from a different window stack querying the wrong window for the window->Collapsed test.
-- Window: Calling IsItemActive(), IsItemHovered() etc. after a call to Begin() provides item data for the title bar, so you can easily test if the title bar is being hovered, etc. (#823)
+- Window: Fixed auto-resize allocating too much space for scrollbar when SizeContents is
+  bigger than maximum window size (fixes c0547d3). (#1417)
+- Window: Child windows with MenuBar use regular WindowPadding.y so layout look consistent as
+  child or as a regular window.
+- Window: Begin(): Fixed appending into a child window with a second Begin() from a different
+  window stack querying the wrong window for the window->Collapsed test.
+- Window: Calling IsItemActive(), IsItemHovered() etc. after a call to Begin() provides item
+  data for the title bar, so you can easily test if the title bar is being hovered, etc. (#823)
 - Window: Made it possible to use SetNextWindowPos() on a child window.
-- Window: Fixed a one frame glitch. When an appearing window claimed the focus themselves, the title bar wouldn't use the focused color for one frame.
-- Window: Added ImGuiWindowFlags_ResizeFromAnySide flag to resize from any borders or from the lower-left corner of a window. This requires your backend to honor GetMouseCursor() requests for full usability. (#822)
+- Window: Fixed a one frame glitch. When an appearing window claimed the focus themselves, the
+  title bar wouldn't use the focused color for one frame.
+- Window: Added ImGuiWindowFlags_ResizeFromAnySide flag to resize from any borders or from the
+  lower-left corner of a window. This requires your backend to honor GetMouseCursor() requests
+  for full usability. (#822)
 - Window: Sizing fixes when using SetNextWindowSize() on individual axises.
-- Window: Hide new window for one frame until they calculate their size. Also fixes SetNextWindowPos() given a non-zero pivot. (#1694)
+- Window: Hide new window for one frame until they calculate their size.
+  Also fixes SetNextWindowPos() given a non-zero pivot. (#1694)
 - Window: Made mouse wheel scrolling accommodate better to windows that are smaller than the scroll step.
-- Window: SetNextWindowContentSize() adjust for the size of decorations (title bar/menu bar), but _not_ for borders are we consistently make borders not affect layout.
-  If you need a non-child window of an exact size with border enabled but zero window padding, you'll need to accommodate for the border size yourself.
-- Window: Using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set. (#1380, #1502)
+- Window: SetNextWindowContentSize() adjust for the size of decorations (title bar/menu bar),
+  but _not_ for borders are we consistently make borders not affect layout.
+  If you need a non-child window of an exact size with border enabled but zero window padding,
+  you'll need to accommodate for the border size yourself.
+- Window: Using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel
+  event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar
+  are also set. (#1380, #1502)
 - Window: Active Modal window always set the WantCaptureKeyboard flag. (#744)
 - Window: Moving window doesn't use accumulating MouseDelta so straying out of imgui boundaries keeps moved imgui window at the same cursor-relative position.
 - IsWindowFocused(): Added ImGuiFocusedFlags_ChildWindows flag to include child windows in the focused test. (#1382).
@@ -4799,39 +4855,52 @@ Other Changes:
 - IsWindowHovered(): Added ImGuiHoveredFlags_RootWindow flag to start hovered test from the root (top-most) window. The combination of both flags obsoletes IsRootWindowOrAnyChildHovered(). (#1382)
 - IsWindowHovered(): Fixed return value when an item is active to use the same logic as IsItemHovered(). (#1382, #1404)
 - IsWindowHovered(): Always return true when current window is being moved. (#1382)
-- Scrollbar: Fixed issues with vertical scrollbar flickering/appearing, typically when manually resizing and using a pattern of filling available height (e.g. full sized BeginChild).
+- Scrollbar: Fixed issues with vertical scrollbar flickering/appearing, typically when manually
+  resizing and using a pattern of filling available height (e.g. full sized BeginChild).
 - Scrollbar: Minor graphical fix for when scrollbar don't have enough visible space to display the full grab.
-- Scrolling: Fixed padding and scrolling asymmetry where lower/right sides of a window wouldn't use WindowPadding properly + causing minor scrolling glitches.
+- Scrolling: Fixed padding and scrolling asymmetry where lower/right sides of a window wouldn't
+  use WindowPadding properly + causing minor scrolling glitches.
 - Tree: TreePush with zero arguments was ambiguous. Resolved by making it call TreePush(const void*). [@JasonWilkins]
 - Tree: Renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. (#600, #1330)
 - MenuBar: Fixed minor rendering issues on the right size when resizing a window very small and using rounded window corners.
-- MenuBar: better software clipping to handle small windows, in particular child window don't have minimum constraints so we need to render clipped menus better.
+- MenuBar: better software clipping to handle small windows, in particular child window don't have
+  minimum constraints so we need to render clipped menus better.
 - BeginMenu(): Tweaked the Arrow/Triangle displayed on child menu items.
-- Columns: Clipping columns borders on Y axis on CPU because some Linux GPU drivers appears to be unhappy with triangle spanning large regions. (#125)
-- Columns: Added ImGuiColumnsFlags_GrowParentContentsSize to internal API to restore old content sizes behavior (may be obsolete). (#1444, #125)
-- Columns: Columns width is no longer lost when dragging a column to the right side of the window, until releasing the mouse button you have a chance to save them. (#1499, #125). [@ggtucker]
+- Columns: Clipping columns borders on Y axis on CPU because some Linux GPU drivers appears to
+  be unhappy with triangle spanning large regions. (#125)
+- Columns: Added ImGuiColumnsFlags_GrowParentContentsSize to internal API to restore old content
+  sizes behavior (may be obsolete). (#1444, #125)
+- Columns: Columns width is no longer lost when dragging a column to the right side of the window,
+  until releasing the mouse button you have a chance to save them. (#1499, #125). [@ggtucker]
 - Columns: Fixed dragging when using a same of columns multiple times in the frame. (#125)
 - Indent(), Unindent(): Allow passing negative values.
 - ColorEdit4(): Made IsItemActive() return true when picker pop-up is active. (#1489)
 - ColorEdit4(): Tweaked tooltip so that the color button aligns more correctly with text.
-- ColorEdit4(): Support drag and drop. Color buttons can be used as drag sources, and ColorEdit widgets as drag targets. (#143)
-- ColorPicker4(): Fixed continuously returning true when holding mouse button on the sat/value/alpha locations. We only return true on value change. (#1489)
-- NewFrame(): using literal strings in the most-frequently firing IM_ASSERT expressions to increase the odd of programmers seeing them (especially those who don't use a debugger).
-- NewFrame() now asserts if neither Render or EndFrame have been called. Exposed EndFrame(). Made it legal to call EndFrame() more than one. (#1423)
+- ColorEdit4(): Support drag and drop. Color buttons can be used as drag sources, and ColorEdit
+  widgets as drag targets. (#143)
+- ColorPicker4(): Fixed continuously returning true when holding mouse button on the sat/value/alpha
+  locations. We only return true on value change. (#1489)
+- NewFrame(): using literal strings in the most-frequently firing IM_ASSERT expressions to
+  increase the odd of programmers seeing them (especially those who don't use a debugger).
+- NewFrame() now asserts if neither Render or EndFrame have been called. Exposed EndFrame().
+  Made it legal to call EndFrame() more than one. (#1423)
 - ImGuiStorage: Added BuildSortByKey() helper to rebuild storage from scratch.
 - ImFont: Added GetDebugName() helper.
 - ImFontAtlas: Added missing Thai punctuation in the GetGlyphRangesThai() ranges. (#1396) [@nProtect]
 - ImDrawList: Removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Anti-aliasing is controlled via the regular style.AntiAliased flags.
 - ImDrawList: Added ImDrawList::AddImageRounded() helper. (#845) [@thedmd]
 - ImDrawList: Refactored to make ImDrawList independent of ImGui. Removed static variable in PathArcToFast() which caused linking issues to some.
-- ImDrawList: Exposed ImDrawCornerFlags, replaced occurrences of ~0 with an explicit ImDrawCornerFlags_All. NB: Inversed BotLeft (prev 1<<3, now 1<<2) and BotRight (prev 1<<2, now 1<<3).
+- ImDrawList: Exposed ImDrawCornerFlags, replaced occurrences of ~0 with an explicit ImDrawCornerFlags_All.
+  NB: Inversed BotLeft (prev 1<<3, now 1<<2) and BotRight (prev 1<<2, now 1<<3).
 - ImVector: Added ImVector::push_front() helper.
 - ImVector: Added ImVector::contains() helper.
 - ImVector: insert() uses grow_capacity() instead of using grow policy inconsistent with push_back().
 - Internals: Remove requirement to define IMGUI_DEFINE_PLACEMENT_NEW to use the IM_PLACEMENT_NEW macro. (#1103)
-- Internals: ButtonBehavior: Fixed ImGuiButtonFlags_NoHoldingActiveID flag from incorrectly setting the ActiveIdClickOffset field.
-  This had no known effect within imgui code but could have affected custom drag and drop patterns. And it is more correct this way! (#1418)
-- Internals: ButtonBehavior: Fixed ImGuiButtonFlags_AllowOverlapMode to avoid temporarily activating widgets on click before they have been correctly double-hovered. (#319, #600)
+- Internals: ButtonBehavior: Fixed ImGuiButtonFlags_NoHoldingActiveID flag from incorrectly
+  setting the ActiveIdClickOffset field. This had no known effect within imgui code but could have
+  affected custom drag and drop patterns. And it is more correct this way! (#1418)
+- Internals: ButtonBehavior: Fixed ImGuiButtonFlags_AllowOverlapMode to avoid temporarily activating
+widgets on click before they have been correctly double-hovered. (#319, #600)
 - Internals: Added SplitterBehavior() helper. (#319)
 - Internals: Added IM_NEW(), IM_DELETE() helpers. (#484, #504, #1517)
 - Internals: Basic refactor of the settings API which now allows external elements to be loaded/saved.
@@ -4840,9 +4909,11 @@ Other Changes:
 - Demo: Renamed the emblematic ShowTestWindow() function to ShowDemoWindow().
 - Demo: Style Editor: Added a "Simplified settings" sections with check-boxes for border size and frame rounding. (#707, #1019)
 - Demo: Style Editor: Added combo box to select stock styles and select current font when multiple are loaded. (#707)
-- Demo: Style Editor: Using local storage so Save/Revert button makes more sense without code passing its storage. Added horizontal scroll bar. Fixed Save/Revert button to be always accessible. (#1211)
+- Demo: Style Editor: Using local storage so Save/Revert button makes more sense without code passing
+  its storage. Added horizontal scroll bar. Fixed Save/Revert button to be always accessible. (#1211)
 - Demo: Console: Fixed context menu issue. (#1404)
-- Demo: Console: Fixed incorrect positioning which was hidden by a minor scroll issue (this would affect people who copied the Console code as is).
+- Demo: Console: Fixed incorrect positioning which was hidden by a minor scroll issue (this would
+  affect people who copied the Console code as is).
 - Demo: Constrained Resize: Added more test cases. (#1417)
 - Demo: Custom Rendering: Fixed clipping rectangle extruding out of parent window.
 - Demo: Layout: Removed unnecessary and misleading BeginChild/EndChild calls.
@@ -4864,24 +4935,41 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 
 Breaking Changes:
 
-- IO: `io.MousePos` needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing, instead of ImVec2(-1,-1) as previously) This is needed so we can clear `io.MouseDelta` field when the mouse is made available again.
-- Renamed `AlignFirstTextHeightToWidgets()` to `AlignTextToFramePadding()`. Kept inline redirection function (will obsolete).
-- Obsoleted the legacy 5 parameters version of Begin(). Please avoid using it. If you need a transparent window background, uses `PushStyleColor()`. The old size parameter there was also misleading and equivalent to calling `SetNextWindowSize(size, ImGuiCond_FirstTimeEver)`. Kept inline redirection function (will obsolete).
-- Obsoleted `IsItemHoveredRect()`, `IsMouseHoveringWindow()` in favor of using the newly introduced flags of `IsItemHovered()` and `IsWindowHovered()`. Kept inline redirection function (will obsolete). (#1382)
-- Obsoleted 'SetNextWindowPosCenter()' in favor of using 1SetNextWindowPos()` with a pivot value which allows to do the same and more. Keep inline redirection function.
-- Removed `IsItemRectHovered()`, `IsWindowRectHovered()` recently introduced in 1.51 which were merely the more consistent/correct names for the above functions which are now obsolete anyway. (#1382)
-- Changed `IsWindowHovered()` default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it. (#1382)
-- Renamed imconfig.h's `IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS`/`IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS` to `IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS`/`IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS` for consistency.
+- IO: `io.MousePos` needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing,
+  instead of ImVec2(-1,-1) as previously) This is needed so we can clear `io.MouseDelta` field when
+  the mouse is made available again.
+- Renamed `AlignFirstTextHeightToWidgets()` to `AlignTextToFramePadding()`.
+  Kept inline redirection function (will obsolete).
+- Obsoleted the legacy 5 parameters version of Begin(). Please avoid using it. If you need a
+  transparent window background, uses `PushStyleColor()`. The old size parameter there was also
+  misleading and equivalent to calling `SetNextWindowSize(size, ImGuiCond_FirstTimeEver)`.
+  Kept inline redirection function (will obsolete).
+- Obsoleted `IsItemHoveredRect()`, `IsMouseHoveringWindow()` in favor of using the newly introduced
+  flags of `IsItemHovered()` and `IsWindowHovered()`. Kept inline redirection function (will obsolete). (#1382)
+- Obsoleted 'SetNextWindowPosCenter()' in favor of using 1SetNextWindowPos()` with a pivot value which
+  allows to do the same and more. Keep inline redirection function.
+- Removed `IsItemRectHovered()`, `IsWindowRectHovered()` recently introduced in 1.51 which were merely
+  the more consistent/correct names for the above functions which are now obsolete anyway. (#1382)
+- Changed `IsWindowHovered()` default parameters behavior to return false if an item is active in
+  another window (e.g. click-dragging item from another window to this window). You can use the newly
+  introduced IsWindowHovered() flags to requests this specific behavior if you need it. (#1382)
+- Renamed imconfig.h's `IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS`/`IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS`
+  to `IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS`/`IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS` for consistency.
 - Renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
 
 Other Changes:
 
 - ProgressBar: fixed rendering when straddling rounded area. (#1296)
-- SliderFloat, DragFloat: Using scientific notation e.g. "%.1e" in the displayed format string doesn't mistakenly trigger rounding of the value. [@MomentsInGraphics]
-- Combo, InputFloat, InputInt: Made the small button on the right side align properly with the equivalent colored button of ColorEdit4().
-- IO: Tweaked logic for `io.WantCaptureMouse` so it now outputs false when e.g. hovering over void while an InputText() is active. (#621) [@pdoane]
-- IO: Fixed `io.WantTextInput` from mistakenly outputting true when an activated Drag or Slider was previously turned into an InputText(). (#1317)
-- Misc: Added flags to `IsItemHovered()`, `IsWindowHovered()` to access advanced hovering-test behavior. Generally useful for pop-ups and drag and drop behaviors: (relates to ~#439, #1013, #143, #925)
+- SliderFloat, DragFloat: Using scientific notation e.g. "%.1e" in the displayed format string doesn't
+  mistakenly trigger rounding of the value. [@MomentsInGraphics]
+- Combo, InputFloat, InputInt: Made the small button on the right side align properly with the
+  equivalent colored button of ColorEdit4().
+- IO: Tweaked logic for `io.WantCaptureMouse` so it now outputs false when e.g. hovering over void
+  while an InputText() is active. (#621) [@pdoane]
+- IO: Fixed `io.WantTextInput` from mistakenly outputting true when an activated Drag or Slider was
+  previously turned into an InputText(). (#1317)
+- Misc: Added flags to `IsItemHovered()`, `IsWindowHovered()` to access advanced hovering-test behavior.
+  Generally useful for pop-ups and drag and drop behaviors: (relates to ~#439, #1013, #143, #925)
   - `ImGuiHoveredFlags_AllowWhenBlockedByPopup`
   - `ImGuiHoveredFlags_AllowWhenBlockedByActiveItem`
   - `ImGuiHoveredFlags_AllowWhenOverlapped`
@@ -4892,54 +4980,80 @@ Other Changes:
 - CheckBox: Now rendering a tick mark instead of a full square.
 - ColorEdit4: Added "Copy as..." option in context menu. (#346)
 - ColorPicker: Improved ColorPicker hue wheel color interpolation. (#1313) [@thevaber]
-- ColorButton: Reduced bordering artifact that would be particularly visible with an opaque Col_FrameBg and FrameRounding enabled.
-- ColorButton: Fixed rendering color button with a checkerboard if the transparency comes from the global style.Alpha and not from the actual source color.
-- TreeNode: Added `ImGuiTreeNodeFlags_FramePadding` flag to conveniently create a tree node with full padding at the beginning of a line, without having to call `AlignTextToFramePadding()`.
+- ColorButton: Reduced bordering artifact that would be particularly visible with an opaque
+  Col_FrameBg and FrameRounding enabled.
+- ColorButton: Fixed rendering color button with a checkerboard if the transparency comes from the global
+  style.Alpha and not from the actual source color.
+- TreeNode: Added `ImGuiTreeNodeFlags_FramePadding` flag to conveniently create a tree node with full
+  padding at the beginning of a line, without having to call `AlignTextToFramePadding()`.
 - Trees: Fixed calling `SetNextTreeNodeOpen()` on a collapsed window leaking to the first tree node item of the next frame.
-- Layout: Horizontal layout is automatically enforced in a menu bar, so you can use non-MenuItem elements without calling SameLine().
-- Separator: Output a vertical separator when used inside a menu bar (or in general when horizontal layout is active, but that isn't exposed yet!).
+- Layout: Horizontal layout is automatically enforced in a menu bar, so you can use non-MenuItem elements
+  without calling SameLine().
+- Separator: Output a vertical separator when used inside a menu bar (or in general when horizontal layout
+  is active, but that isn't exposed yet!).
 - Window: Added `IsWindowAppearing()` helper (helpful e.g. as a condition before initializing some of your own things.).
 - Window: Added pivot parameter to `SetNextWindowPos()`, making it possible to center or right align a window. Obsoleted `SetNextWindowPosCenter()`.
 - Window: Fixed title bar color of top-most window under a modal window.
 - Window: Fixed not being able to move a window by clicking on one of its child window. (#1337, #635)
-- Window: Fixed `Begin()` auto-fit calculation code that predict the presence of a scrollbar so it works better when window size constraints are used.
-- Window: Fixed calling `Begin()` more than once per frame setting `window_just_activated_by_user` which in turn would set enable the Appearing condition for that frame.
-- Window: The implicit "Debug" window now uses a "Debug##Default" identifier instead of "Debug" to allow user creating a window called "Debug" without losing their custom flags.
-- Window: Made the `ImGuiWindowFlags_NoMove` flag properly inherited from parent to child. In a setup with ParentWindow (no flag) -> Child (NoMove) -> SubChild (no flag), the user won't be able to move the parent window by clicking on SubChild. (#1381)
+- Window: Fixed `Begin()` auto-fit calculation code that predict the presence of a scrollbar so it works
+  better when window size constraints are used.
+- Window: Fixed calling `Begin()` more than once per frame setting `window_just_activated_by_user` which
+  in turn would set enable the Appearing condition for that frame.
+- Window: The implicit "Debug" window now uses a "Debug##Default" identifier instead of "Debug" to allow
+  user creating a window called "Debug" without losing their custom flags.
+- Window: Made the `ImGuiWindowFlags_NoMove` flag properly inherited from parent to child. In a setup
+  with ParentWindow (no flag) -> Child (NoMove) -> SubChild (no flag), the user won't be able to move
+  the parent window by clicking on SubChild. (#1381)
 - Popups: Pop-ups can be closed with a right-click anywhere, without altering focus under the pop-up. (~#439)
-- Popups: `BeginPopupContextItem()`, `BeginPopupContextWindow()` are now setup to allow reopening a context menu by right-clicking again. (~#439)
+- Popups: `BeginPopupContextItem()`, `BeginPopupContextWindow()` are now setup to allow reopening
+  a context menu by right-clicking again. (~#439)
 - Popups: `BeginPopupContextItem()` now supports a NULL string identifier and uses the last item ID if available.
 - Popups: Added `OpenPopupOnItemClick()` helper which mimic `BeginPopupContextItem()` but doesn't do the BeginPopup().
 - MenuItem: Only activating on mouse release. [@Urmeli0815] (was already fixed in nav branch).
 - MenuItem: Made tick mark thicker (thick mark?).
-- MenuItem: Tweaks to be usable inside a menu bar (nb: it looks like a regular menu and thus is misleading, prefer using Button() and regular widgets in menu bar if you need to). (#1387)
+- MenuItem: Tweaks to be usable inside a menu bar (nb: it looks like a regular menu and thus is misleading,
+  prefer using Button() and regular widgets in menu bar if you need to). (#1387)
 - ImDrawList: Fixed a rare draw call merging bug which could lead to undisplayed triangles. (#1172, #1368)
-- ImDrawList: Fixed a rare bug in `ChannelsMerge()` when all contents has been clipped, leading to an extraneous draw call being created. (#1172, #1368)
+- ImDrawList: Fixed a rare bug in `ChannelsMerge()` when all contents has been clipped, leading to
+  an extraneous draw call being created. (#1172, #1368)
 - ImFont: Added `AddGlyph()` building helper for use by custom atlas builders.
-- ImFontAtlas: Added support for CustomRect API to submit custom rectangles to be packed into the atlas. You can map them as font glyphs, or use them for custom purposes.
-  After the atlas is built you can query the position of your rectangles in the texture and then copy your data there. You can use this features to create e.g. full color font-mapped icons.
-- ImFontAtlas: Fixed fall-back handling when merging fonts, if a glyph was missing from the second font input it could have used a glyph from the first one. (#1349) [@inolen]
-- ImFontAtlas: Fixed memory leak on build failure case when stbtt_InitFont failed (generally due to incorrect or supported font type). (#1391) (@Moka42)
-- ImFontConfig: Added `RasterizerMultiply` option to alter the brightness of individual fonts at rasterization time, which may help increasing readability for some.
-- ImFontConfig: Added `RasterizerFlags` to pass options to custom rasterizer (e.g. the [imgui_freetype](https://github.com/ocornut/imgui_club/tree/master/imgui_freetype) rasterizer in imgui_club has such options).
+- ImFontAtlas: Added support for CustomRect API to submit custom rectangles to be packed into the atlas.
+  You can map them as font glyphs, or use them for custom purposes.
+  After the atlas is built you can query the position of your rectangles in the texture and then copy
+  your data there. You can use this features to create e.g. full color font-mapped icons.
+- ImFontAtlas: Fixed fall-back handling when merging fonts, if a glyph was missing from the second font
+  input it could have used a glyph from the first one. (#1349) [@inolen]
+- ImFontAtlas: Fixed memory leak on build failure case when stbtt_InitFont failed (generally due to
+  incorrect or supported font type). (#1391) (@Moka42)
+- ImFontConfig: Added `RasterizerMultiply` option to alter the brightness of individual fonts at
+  rasterization time, which may help increasing readability for some.
+- ImFontConfig: Added `RasterizerFlags` to pass options to custom rasterizer (e.g. the
+  [imgui_freetype](https://github.com/ocornut/imgui_club/tree/master/imgui_freetype) rasterizer in imgui_club has such options).
 - ImVector: added resize() variant with initialization value.
-- Misc: Changed the internal name formatting of child windows identifier to use slashes (instead of dots) as separator, more readable.
+- Misc: Changed the internal name formatting of child windows identifier to use slashes
+  (instead of dots) as separator, more readable.
 - Misc: Fixed compilation with `IMGUI_DISABLE_OBSOLETE_FUNCTIONS` defined.
 - Misc: Marked all format+va_list functions with format attribute so GCC/Clang can warn about misuses.
 - Misc: Fixed compilation on NetBSD due to missing alloca.h (#1319) [@RyuKojiro]
 - Misc: Improved warnings compilation for newer versions of Clang. (#1324) (@waywardmonkeys)
-- Misc: Added `io.WantMoveMouse flags` (from Nav branch) and honored in Examples applications. Currently unused but trying to spread Examples applications code that supports it.
-- Misc: Added `IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS` support in imconfig.h to allow user reimplementing the `ImFormatString()` functions e.g. to use stb_printf(). (#1038)
-- Misc: [Windows] Fixed default Win32 `SetClipboardText()` handler leaving the Win32 clipboard handler unclosed on failure. [@pdoane]
-- Style: Added `ImGuiStyle::ScaleAllSizes(float)` helper to make it easier to have application transition e.g. from low to high DPI with a matching style.
+- Misc: Added `io.WantMoveMouse flags` (from Nav branch) and honored in Examples applications.
+  Currently unused but trying to spread Examples applications code that supports it.
+- Misc: Added `IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS` support in imconfig.h to allow user
+  reimplementing the `ImFormatString()` functions e.g. to use stb_printf(). (#1038)
+- Misc: [Windows] Fixed default Win32 `SetClipboardText()` handler leaving the Win32 clipboard
+  handler unclosed on failure. [@pdoane]
+- Style: Added `ImGuiStyle::ScaleAllSizes(float)` helper to make it easier to have application
+  transition e.g. from low to high DPI with a matching style.
 - Metrics: Draw window bounding boxes when hovering Pos/Size; List all draw layers; Trimming empty commands like Render() does.
 - Examples: OpenGL3: Save and restore sampler state. (#1145) [@nlguillemot]
 - Examples: OpenGL2, OpenGL3: Save and restore polygon mode. (#1307) [@JJscott]
 - Examples: DirectX11: Allow creating device with feature level 10 since we don't really need much for that example. (#1333)
-- Examples: DirectX9/10/12: Using the Win32 SetCapture/ReleaseCapture API to read mouse coordinates when they are out of bounds. (#1375) [@Gargaj, @ocornut]
+- Examples: DirectX9/10/12: Using the Win32 SetCapture/ReleaseCapture API to read mouse coordinates
+  when they are out of bounds. (#1375) [@Gargaj, @ocornut]
 - Tools: Fixed binary_to_compressed_c tool to return 0 when successful. (#1350) [@benvanik]
 - Internals: Exposed more helpers and unfinished features in imgui_internal.h. (use at your own risk!).
-- Internals: A bunch of internal refactoring, hopefully haven't broken anything! Merged a bunch of internal changes from the upcoming Navigation branch.
+- Internals: A bunch of internal refactoring, hopefully haven't broken anything!
+  Merged a bunch of internal changes from the upcoming Navigation branch.
 - Various tweaks, fixes and documentation changes.
 
 Beta Navigation Branch:
@@ -4948,12 +5062,16 @@ Beta Navigation Branch:
 - Nav: Added `#define IMGUI_HAS_NAV` in imgui.h to ease sharing code between both branches. (#787)
 - Nav: MainMenuBar now releases focus when user gets out of the menu layer. (#787)
 - Nav: When applying focus to a window with only menus, the menu layer is automatically activated. (#787)
-- Nav: Added `ImGuiNavInput_KeyMenu` (~Alt key) aside from ImGuiNavInput_PadMenu input as it is one differentiator of pad vs keyboard that was detrimental to the keyboard experience. Although isn't officially supported, it makes the current experience better. (#787)
+- Nav: Added `ImGuiNavInput_KeyMenu` (~Alt key) aside from ImGuiNavInput_PadMenu input as it is
+  one differentiator of pad vs keyboard that was detrimental to the keyboard experience.
+  Although isn't officially supported, it makes the current experience better. (#787)
 - Nav: Move requests now wrap vertically inside Menus and Pop-ups. (#787)
 - Nav: Allow to collapse tree nodes with NavLeft and open them with NavRight. (#787, #1079).
-- Nav: It's now possible to navigate sibling of a menu-bar while navigating inside one of their child. If a Left<>Right navigation request fails to find a match we forward the request to the root menu. (#787, #126)
+- Nav: It's now possible to navigate sibling of a menu-bar while navigating inside one of their child.
+  If a Left<>Right navigation request fails to find a match we forward the request to the root menu. (#787, #126)
 - Nav: Fixed `SetItemDefaultFocus` from stealing default focus when we are initializing default focus for a menu bar layer. (#787)
-- Nav: Support for fall-back horizontal scrolling with PadLeft/PadRight (nb: fall-back scrolling is only used to navigate windows that have no interactive items). (#787)
+- Nav: Support for fall-back horizontal scrolling with PadLeft/PadRight (nb: fall-back scrolling
+  is only used to navigate windows that have no interactive items). (#787)
 - Nav: Fixed tool-tip from being selectable in the window selection list. (#787)
 - Nav: `CollapsingHeader(bool*)` variant: fixed for `IsItemHovered()` not working properly in the nav branch. (#600, #787)
 - Nav: InputText: Fixed using Up/Down history callback feature when Nav is enabled. (#787)
@@ -4970,7 +5088,14 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 
 Breaking Changes:
 
-Work on dear imgui has been gradually resuming. It means that fixes and new features should be tackled at a faster rate than last year. However, in order to move forward with the library and get rid of some cruft, I have taken the liberty to be a little bit more aggressive than usual with API breaking changes. Read the details below and search for those names in your code! In the grand scheme of things, those changes are small and should not affect everyone, but this is technically our most aggressive release so far in term of API breakage. If you want to be extra forward-facing, you can enable `#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS` in your imconfig.h to disable the obsolete names/redirection.
+Work on dear imgui has been gradually resuming. It means that fixes and new features should be tackled at
+a faster rate than last year. However, in order to move forward with the library and get rid of some cruft,
+I have taken the liberty to be a little bit more aggressive than usual with API breaking changes.
+Read the details below and search for those names in your code! In the grand scheme of things,
+those changes are small and should not affect everyone, but this is technically our most aggressive
+release so far in term of API breakage.
+If you want to be extra forward-facing, you can enable `#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS` in
+your imconfig.h to disable the obsolete names/redirection.
 
 - Renamed `IsItemHoveredRect()` to `IsItemRectHovered()`. Kept inline redirection function (will obsolete).
 - Renamed `IsMouseHoveringWindow()` to `IsWindowRectHovered()` for consistency. Kept inline redirection function (will obsolete).
@@ -4978,43 +5103,79 @@ Work on dear imgui has been gradually resuming. It means that fixes and new feat
 - Renamed `ImGuiCol_Columns***` enums to `ImGuiCol_Separator***`. Kept redirection enums (will obsolete).
 - Renamed `ImGuiSetCond***` types and enums to `ImGuiCond***`. Kept redirection enums (will obsolete).
 - Renamed `GetStyleColName()` to `GetStyleColorName()` for consistency. Unlikely to be used by end-user!
-- Added `PushStyleColor(ImGuiCol idx, ImU32 col)` overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicitly to fix.
+- Added `PushStyleColor(ImGuiCol idx, ImU32 col)` overload, which _might_ cause an "ambiguous call"
+  compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicitly to fix.
 - Marked the weird `IMGUI_ONCE_UPON_A_FRAME` helper macro as obsolete. Prefer using the more explicit `ImGuiOnceUponAFrame`.
-- Changed `ColorEdit4(const char* label, float col[4], bool show_alpha = true)` signature to `ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)`, where flags 0x01 is a safe no-op (hello dodgy backward compatibility!). The new `ColorEdit4`/`ColorPicker4` functions have lots of available flags! Check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
-- Changed signature of `ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)` to `ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))`. This function was rarely used and was very dodgy (no explicit ID!).
-- Changed `BeginPopupContextWindow(bool also_over_items=true, const char* str_id=NULL, int mouse_button=1)` signature to `(const char* str_id=NULL, int mouse_button=1, bool also_over_items=true)`. This is perhaps the most aggressive change in this update, but note that the majority of users relied on default parameters completely, so this will affect only a fraction of users of this already rarely used function.
-- Removed `IsPosHoveringAnyWindow()`, which was partly broken and misleading. In the vast majority of cases, people using that function wanted to use `io.WantCaptureMouse` flag. Replaced with IM_ASSERT + comment redirecting user to `io.WantCaptureMouse`. (#1237)
+- Changed `ColorEdit4(const char* label, float col[4], bool show_alpha = true)` signature to
+  `ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)`, where flags 0x01 is a safe no-op
+  (hello dodgy backward compatibility!). The new `ColorEdit4`/`ColorPicker4` functions have lots of available flags!
+  Check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
+- Changed signature of `ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)`
+  to `ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))`.
+  This function was rarely used and was very dodgy (no explicit ID!).
+- Changed `BeginPopupContextWindow(bool also_over_items=true, const char* str_id=NULL, int mouse_button=1)`
+  signature to `(const char* str_id=NULL, int mouse_button=1, bool also_over_items=true)`.
+  This is perhaps the most aggressive change in this update, but note that the majority of users relied
+  on default parameters completely, so this will affect only a fraction of users of this already rarely
+  used function.
+- Removed `IsPosHoveringAnyWindow()`, which was partly broken and misleading. In the vast majority of cases,
+  people using that function wanted to use `io.WantCaptureMouse` flag. Replaced with IM_ASSERT + a comment
+  redirecting user to `io.WantCaptureMouse`. (#1237)
 - Removed the old `ValueColor()` helpers, they are equivalent to calling `Text(label)` + `SameLine()` + `ColorButton()`.
-- Removed `ColorEditMode()` and `ImGuiColorEditMode` type in favor of `ImGuiColorEditFlags` and parameters to the various Color*() functions. The `SetColorEditOptions()` function allows to initialize default but the user can still change them with right-click context menu. Commenting out your old call to `ColorEditMode()` may just be fine!
+- Removed `ColorEditMode()` and `ImGuiColorEditMode` type in favor of `ImGuiColorEditFlags` and
+  parameters to the various Color*() functions. The `SetColorEditOptions()` function allows to
+  initialize default but the user can still change them with right-click context menu.
+  Commenting out your old call to `ColorEditMode()` may just be fine!
 
 Other Changes:
 
-- Added flags to `ColorEdit3()`, `ColorEdit4()`. The color edit widget now has a context-menu and access to the color picker. (#346)
+- Added flags to `ColorEdit3()`, `ColorEdit4()`. The color edit widget now has a context-menu
+  and access to the color picker. (#346)
 - Added flags to `ColorButton()`. (#346)
-- Added `ColorPicker3()`, `ColorPicker4()`. The API along with those of the updated `ColorEdit4()` was designed so you may use them in various situation and hopefully compose your own picker if required. There are a bunch of available flags, check the Demo window and comment for `ImGuiColorEditFlags_`. Some of the options it supports are: two color picker types (hue bar + sat/val rectangle, hue wheel + rotating sat/val triangle), display as u8 or float, lifting 0.0..1.0 constraints (currently rgba only), context menus, alpha bar, background checkerboard options, preview tooltip, basic revert. For simple use, calling the existing `ColorEdit4()` function as you did before will be enough, as you can now open the color picker from there. (#346) [@r-lyeh, @nem0, @thennequin, @dariomanesku and @ocornut]
-- Added `SetColorEditOptions()` to set default color options (e.g. if you want HSV over RGBA, float over u8, select a default picker mode etc. at startup time without a user intervention. Note that the user can still change options with the context menu unless disabled with `ImGuiColorFlags_NoOptions` or explicitly enforcing a display type/picker mode etc.).
+- Added `ColorPicker3()`, `ColorPicker4()`. (#346) [@r-lyeh, @nem0, @thennequin, @dariomanesku and @ocornut]
+  The API along with those of the updated `ColorEdit4()` was designed so you may use them in various
+  situation and hopefully compose your own picker if required. There are a bunch of available flags,
+  check the Demo window and comment for `ImGuiColorEditFlags_`.
+  Some of the options it supports are: two color picker types (hue bar + sat/val rectangle,
+  hue wheel + rotating sat/val triangle), display as u8 or float, lifting 0.0..1.0 constraints
+  (currently rgba only),  context menus, alpha bar, background checkerboard options, preview tooltip,
+  basic revert. For simple use, calling the existing `ColorEdit4()` function as you did before
+  will be enough, as you can now open the color picker from there.
+- Added `SetColorEditOptions()` to set default color options (e.g. if you want HSV over RGBA,
+  float over u8, select a default picker mode etc. at startup time without a user intervention.
+  Note that the user can still change options with the context menu unless disabled with
+  `ImGuiColorFlags_NoOptions` or explicitly enforcing a display type/picker mode etc.).
 - Added user-facing `IsPopupOpen()` function. (#891) [@mkeeter]
-- Added `GetColorU32(u32)` variant that perform the style alpha multiply without a floating-point round trip, and helps makes code more consistent when using ImDrawList APIs.
+- Added `GetColorU32(u32)` variant that perform the style alpha multiply without a floating-point
+  round trip, and helps makes code more consistent when using ImDrawList APIs.
 - Added `PushStyleColor(ImGuiCol idx, ImU32 col)` overload.
-- Added `GetStyleColorVec4(ImGuiCol idx)` which is equivalent to accessing `ImGui::GetStyle().Colors[idx]` (aka return the raw style color without alpha alteration).
-- ImFontAtlas: Added `GlyphRangesBuilder` helper class, which makes it easier to build custom glyph ranges from your app/game localization data, or add into existing glyph ranges.
+- Added `GetStyleColorVec4(ImGuiCol idx)` which is equivalent to accessing `ImGui::GetStyle().Colors[idx]`
+  (aka return the raw style color without alpha alteration).
+- ImFontAtlas: Added `GlyphRangesBuilder` helper class, which makes it easier to build custom glyph ranges
+  from your app/game localization data, or add into existing glyph ranges.
 - ImFontAtlas: Added `TexGlyphPadding` option. (#1282) [@jadwallis]
 - ImFontAtlas: Made it possible to override size of AddFontDefault() (even if it isn't really recommended!).
 - ImDrawList: Added `GetClipRectMin()`, `GetClipRectMax()` helpers.
 - Fixed Ini saving crash if the ImGuiWindowFlags_NoSavedSettings gets removed from a window after its creation (unlikely!). (#1000)
-- Fixed `PushID()`/`PopID()` from marking parent window as Accessed (which needlessly woke up the root "Debug" window when used outside of a regular window). (#747)
+- Fixed `PushID()`/`PopID()` from marking parent window as Accessed (which needlessly woke up the
+  root "Debug" window when used outside of a regular window). (#747)
 - Fixed an assert when calling `CloseCurrentPopup()` twice in a row. [@nem0]
 - Window size can be loaded from .ini data even if ImGuiWindowFlags_NoResize flag is set. (#1048, #1056)
 - Columns: Added `SetColumnWidth()`. (#913) [@ggtucker]
 - Columns: Dragging a column preserve its width by default. (#913) [@ggtucker]
 - Columns: Fixed first column appearing wider than others. (#1266)
-- Columns: Fixed allocating space on the right-most side with the assumption of a vertical scrollbar. The space is only allocated when needed. (#125, #913, #893, #1138)
-- Columns: Fixed the right-most column from registering its content width to the parent window, which led to various issues when using auto-resizing window or e.g. horizontal scrolling. (#519, #125, #913)
+- Columns: Fixed allocating space on the right-most side with the assumption of a vertical scrollbar.
+  The space is only allocated when needed. (#125, #913, #893, #1138)
+- Columns: Fixed the right-most column from registering its content width to the parent window,
+  which led to various issues when using auto-resizing window or e.g. horizontal scrolling. (#519, #125, #913)
 - Columns: Refactored some of the columns code internally toward a better API (not yet exposed) + minor optimizations. (#913) [@ggtucker, @ocornut]
-- Popups: Most pop-ups windows can be moved by the user after appearing (if they don't have explicit positions provided by caller, or e.g. sub-menu pop-up). The previous restriction was totally arbitrary. (#1252)
-- Tooltip: `SetTooltip()` is expanded immediately into a window, honoring current font / styling setting. Add internal mechanism to override tooltips. (#862)
+- Popups: Most pop-ups windows can be moved by the user after appearing (if they don't have explicit
+  positions provided by caller, or e.g. sub-menu pop-up). The previous restriction was totally arbitrary. (#1252)
+- Tooltip: `SetTooltip()` is expanded immediately into a window, honoring current font / styling setting.
+  Add internal mechanism to override tooltips. (#862)
 - PlotHistogram: bars are drawn based on zero-line, so negative values are going under. (#828)
-- Scrolling: Fixed return values of `GetScrollMaxX()`, `GetScrollMaxY()` when both scrollbars were enabled. Tweak demo to display more data. (#1271) [@degracode]
+- Scrolling: Fixed return values of `GetScrollMaxX()`, `GetScrollMaxY()` when both scrollbars were enabled.
+  Tweak demo to display more data. (#1271) [@degracode]
 - Scrolling: Fixes for Vertical Scrollbar not automatically getting enabled if enabled Horizontal Scrollbar straddle the vertical limit. (#1271, #246)
 - Scrolling: `SetScrollHere()`, `SetScrollFromPosY()`: Fixed Y scroll aiming when Horizontal Scrollbar is enabled. (#665).
 - [Windows] Clipboard: Fixed not closing Win32 clipboard on early open failure path. (#1264)
@@ -5022,7 +5183,8 @@ Other Changes:
 - Demo: Rearranged everything under Widgets in a more consistent way.
 - Demo: Columns: Added Horizontal Scrolling demo. Tweaked another Columns demo. (#519, #125, #913)
 - Examples: OpenGL: Various makefiles for MINGW, Linux. (#1209, #1229, #1209) [@fr500, @acda]
-- Examples: Enabled vsync by default in example applications, so it doesn't confuse people that the sample run at 2000+ fps and waste an entire CPU. (#1213, #1151).
+- Examples: Enabled vsync by default in example applications, so it doesn't confuse people that
+  the sample run at 2000+ fps and waste an entire CPU. (#1213, #1151).
 - Various other small fixes, tweaks, comments, optimizations.
 
 
@@ -5035,11 +5197,16 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 Breaking Changes:
 
 - Added a void* user_data parameter to Clipboard function handlers. (#875)
-- SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
+- SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window.
+  This was sort of always the intent and hopefully breakage should be minimal.
 - Renamed ImDrawList::PathFill() - rarely used directly - to ImDrawList::PathFillConvex() for clarity and consistency.
 - Removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
-- Style: style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
-- BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
+- Style: style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f)
+  for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
+- BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions
+  as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple
+  times to a same child from different locations of the stack id. If that's the case, generate an id with GetId()
+  and use it instead of passing string to BeginChild().
 
 Other Changes:
 
@@ -5049,7 +5216,8 @@ Other Changes:
 - InputText(): Fixed pressing home key on last character when it isn't a trailing \n (#588, #815)
 - InputText(): Fixed state corruption/crash bug in stb_textedit.h redo logic when exhausting undo/redo char buffer. (#715. #681)
 - InputTextMultiline(): Fixed CTRL+DownArrow moving scrolling out of bounds.
-- InputTextMultiline(): Scrollbar fix for when input and latched internal buffers differs in a way that affects vertical scrollbar existence. (#725)
+- InputTextMultiline(): Scrollbar fix for when input and latched internal buffers differs in
+  a way that affects vertical scrollbar existence. (#725)
 - ImFormatString(): Fixed an overflow handling bug with implementation of vsnprintf() that do not return -1. (#793)
 - BeginChild(const char*) now applies stack id to provided label, consistent with other widgets. (#894, #713)
 - SameLine() with explicit X position is relative to left of group/columns. (ref #746, #125, #630)
@@ -5068,7 +5236,8 @@ Other Changes:
 - Fixed PlotLines() PlotHistogram() calling with values_count == 0.
 - Fixed clicking on a window's void while staying still overzealously marking .ini settings as dirty. (#923)
 - Fixed assert triggering when a window has zero rendering but has a callback. (#810)
-- Scrollbar: Fixed rendering when sizes are negative to reduce glitches (which can happen with certain style settings and zero WindowMinSize).
+- Scrollbar: Fixed rendering when sizes are negative to reduce glitches (which can happen with
+  certain style settings and zero WindowMinSize).
 - EndGroup(): Made IsItemHovered() work when an item was activated within the group. (#849)
 - BulletText(): Fixed stopping to display formatted string after the '##' mark.
 - Closing the focused window restore focus to the first active root window in descending z-order .(part of #727)
@@ -5078,7 +5247,8 @@ Other Changes:
 - ImGuiListClipper: Fixed automatic-height calc path dumbly having user display element 0 twice. (#661, #716)
 - ImGuiListClipper: Fix to behave within column. (#661, #662, #716)
 - ImDrawList: Renamed ImDrawList::PathFill() to ImDrawList::PathFillConvex() for clarity. (BREAKING API)
-- Columns: End() avoid calling Columns(1) if no columns set is open, not sure why it wasn't the case already (pros: faster, cons: exercise less code).
+- Columns: End() avoid calling Columns(1) if no columns set is open, not sure why it wasn't the
+  case already (pros: faster, cons: exercise less code).
 - ColorButton(): Fix ColorButton showing wrong hex value for alpha. (#1068) [@codecat]
 - ColorEdit4(): better preserve inputting value out of 0..255 range, display then clamped in Hexadecimal form.
 - Shutdown() clear out some remaining pointers for sanity. (#836)
@@ -5089,7 +5259,8 @@ Other Changes:
 - ImFont: Added GetGlyphRangesThai() helper. [@nProtect]
 - ImFont: CalcWordWrapPositionA() fixed font scaling with fallback character.
 - ImFont: Calculate and store the approximate texture surface to get an idea of how costly each source font is.
-- ImFontConfig: Added GlyphOffset to explicitly offset glyphs at font build time, useful for merged fonts. Removed MergeGlyphCenterV. (BREAKING API)
+- ImFontConfig: Added GlyphOffset to explicitly offset glyphs at font build time, useful for merged fonts.
+  Removed MergeGlyphCenterV. (BREAKING API)
 - Clarified asserts in CheckStacksSize() when there is a stack mismatch.
 - Context: Support for #define-ing GImGui and IMGUI_SET_CURRENT_CONTEXT_FUNC to enable custom thread-based hackery (#586)
 - Updated stb_truetype.h to 1.14 (added OTF support, removed warnings). (#883, #976)
@@ -5111,7 +5282,8 @@ Other Changes:
 - Examples: OpenGL*: Saving/restoring active texture number (the value modified by glActiveTexture). (#1087, #1088, #1116)
 - Examples: OpenGL*: Saving/restoring separate color/alpha blend functions correctly. (#1120) [@greggman]
 - Examples: OpenGL2: Uploading font texture as RGBA32 to increase compatibility with users shaders for beginners. (#824)
-- Examples: Vulkan: Countless fixes and improvements. (#785, #804, #910, #1017, #1039, #1041, #1042, #1043, #1080) [@martty, @Loftilus, @ParticlePeter, @SaschaWillems]
+- Examples: Vulkan: Countless fixes and improvements. (#785, #804, #910, #1017, #1039, #1041,
+  #1042, #1043, #1080) [@martty, @Loftilus, @ParticlePeter, @SaschaWillems]
 - Examples: DirectX9/10/10: Only call SetCursor(NULL) is io.MouseDrawCursor is set. (#585, #909)
 - Examples: DirectX9: Explicitly setting viewport to match that other examples are doing. (#937)
 - Examples: GLFW+OpenGL3: Fixed Shutdown() calling GL functions with NULL parameters if NewFrame was never called. (#800)
@@ -5131,11 +5303,22 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 Breaking Changes:
 
 - Renamed `SetNextTreeNodeOpened()` to `SetNextTreeNodeOpen()` for consistency, no redirection.
-- Removed confusing set of `GetInternalState()`, `GetInternalStateSize()`, `SetInternalState()` functions. Now using `CreateContext()`, `DestroyContext()`, `GetCurrentContext()`, `SetCurrentContext()`. If you were using multiple contexts the change should be obvious and trivial.
-- Obsoleted old signature of `CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false)`, as extra parameters were badly designed and rarely used. Most uses were using 1 parameter and shouldn't affect you. You can replace the "default_open = true" flag in new API with `CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen)`.
-- Changed `ImDrawList::PushClipRect(ImVec4 rect)` to `ImDraw::PushClipRect(ImVec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false)`. Note that higher-level `ImGui::PushClipRect()` is preferable because it will clip at logic/widget level, whereas `ImDrawList::PushClipRect()` only affect your renderer.
-- Title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore (see #655). If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
-  This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. (Or If this is confusing, just pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.)
+- Removed confusing set of `GetInternalState()`, `GetInternalStateSize()`, `SetInternalState()` functions.
+  Now using `CreateContext()`, `DestroyContext()`, `GetCurrentContext()`, `SetCurrentContext()`.
+  If you were using multiple contexts the change should be obvious and trivial.
+- Obsoleted old signature of `CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false)`,
+  as extra parameters were badly designed and rarely used. Most uses were using 1 parameter and shouldn't affect you.
+  You can replace the "default_open = true" flag in new API with `CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen)`.
+- Changed `ImDrawList::PushClipRect(ImVec4 rect)` to `ImDraw::PushClipRect(ImVec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false)`.
+  Note that higher-level `ImGui::PushClipRect()` is preferable because it will clip at logic/widget level, whereas `ImDrawList::PushClipRect()` only affect your renderer.
+- Title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background
+  (ImGuiCol_WindowBg color) anymore (see #655). If your TitleBg/TitleBgActive alpha was 1.0f or you are using
+  the default theme it will not affect you. However if your TitleBg/TitleBgActive alpha was <1.0f you need to
+  tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
+  This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output,
+  given the OLD color and the OLD WindowBg color. (Or If this is confusing, just pick the RGB value from
+  title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create
+  TitleBgActive from a tweaked TitleBg color.)
 
     ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
     {
@@ -5146,9 +5329,11 @@ Breaking Changes:
 
 Other changes:
 
-- New version of ImGuiListClipper helper calculates item height automatically. See comments and demo code. (#662, #661, #660)
+- New version of ImGuiListClipper helper calculates item height automatically.
+  See comments and demo code. (#662, #661, #660)
 - Added SetNextWindowSizeConstraints() to enable basic min/max and programmatic size constraints on window. Added demo. (#668)
-- Added PushClipRect()/PopClipRect() (previously part of imgui_internal.h). Changed ImDrawList::PushClipRect() prototype. (#610)
+- Added PushClipRect()/PopClipRect() (previously part of imgui_internal.h).
+  Changed ImDrawList::PushClipRect() prototype. (#610)
 - Added IsRootWindowOrAnyChildHovered() helper. (#615)
 - Added TreeNodeEx() functions. (#581, #600, #190)
 - Added ImGuiTreeNodeFlags_Selected flag to display TreeNode as "selected". (#581, #190)
@@ -5158,31 +5343,38 @@ Other changes:
 - Added ImGuiTreeNodeFlags_DefaultOpen flag (previously private).
 - Added ImGuiTreeNodeFlags_OpenOnDoubleClick flag.
 - Added ImGuiTreeNodeFlags_OpenOnArrow flag.
-- Added ImGuiTreeNodeFlags_Leaf flag, always opened, no arrow, for convenience. For simple use case prefer using TreeAdvanceToLabelPos()+Text().
+- Added ImGuiTreeNodeFlags_Leaf flag, always opened, no arrow, for convenience.
+  For simple use case prefer using TreeAdvanceToLabelPos()+Text().
 - Added ImGuiTreeNodeFlags_Bullet flag, to add a bullet to Leaf node or replace Arrow with a bullet.
 - Added TreeAdvanceToLabelPos(), GetTreeNodeToLabelSpacing() helpers. (#581, #324)
-- Added CreateContext()/DestroyContext()/GetCurrentContext()/SetCurrentContext(). Obsoleted nearly identical GetInternalState()/SetInternalState() functions. (#586, #269)
+- Added CreateContext()/DestroyContext()/GetCurrentContext()/SetCurrentContext().
+  Obsoleted nearly identical GetInternalState()/SetInternalState() functions. (#586, #269)
 - Added NewLine() to undo a SameLine() and as a shy reminder that horizontal layout support hasn't been implemented yet.
 - Added IsItemClicked() helper. (#581)
 - Added CollapsingHeader() variant with close button. (#600)
 - Fixed MenuBar missing lower border when borders are enabled.
 - InputText(): Fixed clipping of cursor rendering in case it gets out of the box (which can be forced w/ ImGuiInputTextFlags_NoHorizontalScroll. (#601)
 - Style: Changed default IndentSpacing from 22 to 21. (#581, #324)
-- Style: Fixed TitleBg/TitleBgActive color being rendered above WindowBg color, which was inconsistent and causing visual artifact. (#655)
-  This broke the meaning of TitleBg and TitleBgActive. Only affect values where Alpha<1.0f. Fixed default theme. Read comments in "API BREAKING CHANGES" section to convert.
+- Style: Fixed TitleBg/TitleBgActive color being rendered above WindowBg color, which was
+  inconsistent and causing visual artifact. (#655)
+  This broke the meaning of TitleBg and TitleBgActive. Only affect values where Alpha<1.0f.
+  Fixed default theme. Read comments in "API BREAKING CHANGES" section to convert.
 - Relative rendering of order of Child windows creation is preserved, to allow more control with overlapping children. (#595)
 - Fixed GetWindowContentRegionMax() being off by ScrollbarSize amount when explicit SizeContents is set.
 - Indent(), Unindent(): optional non-default indenting width. (#324, #581)
 - Bullet(), BulletText(): Slightly bigger. Less polygons.
-- ButtonBehavior(): fixed subtle old bug when a repeating button would also return true on mouse release (barely noticeable unless RepeatRate is set to be very slow). (#656)
+- ButtonBehavior(): fixed subtle old bug when a repeating button would also return true on mouse
+  release (barely noticeable unless RepeatRate is set to be very slow). (#656)
 - BeginMenu(): a menu that becomes disabled while open gets closed down, facilitate user's code. (#126)
 - BeginGroup(): fixed using within Columns set. (#630)
 - Fixed a lag in reading the currently hovered window when dragging a window. (#635)
 - Obsoleted 4 parameters version of CollapsingHeader(). Refactored code into TreeNodeBehavior. (#600, #579)
 - Scrollbar: minor fix for top-right rounding of scrollbar background when window has menu bar but no title bar.
 - MenuItem(): the check mark renders in disabled color when menu item is disabled.
-- Fixed clipping rectangle floating point representation to ensure renderer-side float point operations yield correct results in typical DirectX/GL settings. (#582, 597)
-- Fixed GetFrontMostModalRootWindow(), fixing missing fade-out when a combo pop was used stacked over a modal window. (#604)
+- Fixed clipping rectangle floating point representation to ensure renderer-side floating-point
+  operations yield correct results in typical DirectX/GL settings. (#582, 597)
+- Fixed GetFrontMostModalRootWindow(), fixing missing fade-out when a combo pop was used stacked
+  over a modal window. (#604)
 - ImDrawList: Added AddQuad(), AddQuadFilled() helpers.
 - ImDrawList: AddText() refactor, moving some code to ImFont, reserving less unused vertices when large vertical clipping occurs.
 - ImFont: Added RenderChar() helper.
@@ -5193,7 +5385,8 @@ Other changes:
 - Renamed majority of use of the word "opened" to "open" for clarity. Renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(). (#625, #579)
 - Examples: OpenGL3: Saving/restoring glActiveTexture() state. (#602)
 - Examples: DirectX9: save/restore all device state.
-- Examples: DirectX9: Removed dependency on d3dx9.h, d3dx9.lib, dxguid.lib so it can be used in a DirectXMath.h only environment. (#611)
+- Examples: DirectX9: Removed dependency on d3dx9.h, d3dx9.lib, dxguid.lib so it can be used in
+  a DirectXMath.h only environment. (#611)
 - Examples: DirectX10/X11: Apply depth-stencil state (no use of depth buffer). (#640, #636)
 - Examples: DirectX11/X11: Added comments on removing dependency on D3DCompiler. (#638)
 - Examples: SDL: Initialize video+timer subsystem only.
@@ -5208,33 +5401,53 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 
 Breaking Changes:
 
-- Consistently honoring exact width passed to PushItemWidth() (when positive), previously it would add extra FramePadding.x*2 over that width. Some hand-tuned layout may be affected slightly. (#346)
-- Style: removed `style.WindowFillAlphaDefault` which was confusing and redundant, baked alpha into `ImGuiCol_WindowBg` color. If you had a custom WindowBg color but didn't change WindowFillAlphaDefault, multiply WindowBg alpha component by 0.7. Renamed `ImGuiCol_TooltipBg` to `ImGuiCol_PopupBG`, applies to other types of pop-ups. `bg_alpha` parameter of 5-parameters version of Begin() is an override. (#337)
-- InputText(): Added BufTextLen field in ImGuiTextEditCallbackData. Requesting user to update it if the buffer is modified in the callback. Added a temporary length-check assert to minimize panic for the 3 people using the callback. (#541)
-- Renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). (#340)
+- Consistently honoring exact width passed to PushItemWidth() (when positive), previously it would
+  add extra FramePadding.x*2 over that width. Some hand-tuned layout may be affected slightly. (#346)
+- Style: removed `style.WindowFillAlphaDefault` which was confusing and redundant, baked alpha into
+  `ImGuiCol_WindowBg` color. If you had a custom WindowBg color but didn't change WindowFillAlphaDefault,
+  multiply WindowBg alpha component by 0.7. Renamed `ImGuiCol_TooltipBg` to `ImGuiCol_PopupBG`,
+  applies to other types of pop-ups. `bg_alpha` parameter of 5-parameters version of Begin() is an override. (#337)
+- InputText(): Added BufTextLen field in ImGuiTextEditCallbackData. Requesting user to update it
+  if the buffer is modified in the callback. Added a temporary length-check assert to minimize panic
+  for the 3 people using the callback. (#541)
+- Renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize().
+  Kept inline redirection function (will obsolete). (#340)
 
 Other Changes:
 
-- Consistently honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. Some hand-tuned layout may be affected slightly. (#346)
-- Fixed clipping of child windows within parent not taking account of child outer clipping boundaries (including scrollbar, etc.). (#506)
-- TextUnformatted(): Fixed rare crash bug with large blurb of text (2k+) not finished with a '\n' and fully above the clipping Y line. (#535)
+- Consistently honoring exact width passed to PushItemWidth(), previously it would add extra
+  FramePadding.x*2 over that width. Some hand-tuned layout may be affected slightly. (#346)
+- Fixed clipping of child windows within parent not taking account of child outer clipping
+  boundaries (including scrollbar, etc.). (#506)
+- TextUnformatted(): Fixed rare crash bug with large blurb of text (2k+) not finished with
+  a '\n' and fully above the clipping Y line. (#535)
 - IO: Added 'KeySuper' field to hold CMD keyboard modifiers for OS X. Updated all examples accordingly. (#473)
 - Added ImGuiWindowFlags_ForceVerticalScrollbar, ImGuiWindowFlags_ForceHorizontalScrollbar flags. (#476)
 - Added IM_COL32 macros to generate a U32 packed color, convenient for direct use of ImDrawList api. (#346)
 - Added GetFontTexUvWhitePixel() helper, convenient for direct use of ImDrawList api.
-- Selectable(): Added ImGuiSelectableFlags_AllowDoubleClick flag to allow user reacting on double-click. (@zapolnov) (#516)
+- Selectable(): Added ImGuiSelectableFlags_AllowDoubleClick flag to allow user reacting
+  on double-click. (@zapolnov) (#516)
 - Begin(): made the close button explicitly set the boolean to false instead of toggling it. (#499)
 - BeginChild()/EndChild(): fixed incorrect layout to allow widgets submitted after an auto-fitted child window. (#540)
-- BeginChild(): Added ImGuiWindowFlags_AlwaysUseWindowPadding flag to ensure non-bordered child window uses window padding. (#462)
-- Fixed InputTextMultiLine(), ListBox(), BeginChildFrame(), ProgressBar(): outer frame not honoring bordering. (#462, #503)
+- BeginChild(): Added ImGuiWindowFlags_AlwaysUseWindowPadding flag to ensure non-bordered child window
+  uses window padding. (#462)
+- Fixed InputTextMultiLine(), ListBox(), BeginChildFrame(), ProgressBar(): outer frame not
+  honoring bordering. (#462, #503)
 - Fixed Image(), ImageButtion() rendering a rectangle 1 px too large on each axis. (#457)
 - SetItemAllowOverlap(): Promoted from imgui_internal.h to public imgui.h api. (#517)
 - Combo(): Right-most button stays highlighted when pop-up is open.
 - Combo(): Display pop-up above if there's isn't enough space below / or select largest side. (#505)
-- DragFloat(), SliderFloat(), InputFloat(): fixed cases of erroneously returning true repeatedly after a text input modification (e.g. "0.0" --> "0.000" would keep returning true). (#564)
-- DragFloat(): Always apply value when mouse is held/widget active, so that an always-resetting variable (e.g. non saved local) can be passed.
-- InputText(): OS X friendly behaviors: Word movement uses ALT key; Shortcuts uses CMD key; Double-clicking text select a single word; Jumping to next word sets cursor to end of current word instead of beginning of current word. (@zhiayang), (#473)
-- InputText(): Added BufTextLen in ImGuiTextEditCallbackData. Requesting user to maintain it if buffer is modified. Zero-ing structure properly before use. (#541)
+- DragFloat(), SliderFloat(), InputFloat(): fixed cases of erroneously returning true repeatedly
+  after a text input modification (e.g. "0.0" --> "0.000" would keep returning true). (#564)
+- DragFloat(): Always apply value when mouse is held/widget active, so that an always-resetting
+  variable (e.g. non saved local) can be passed.
+- InputText(): OS X friendly behaviors:  (@zhiayang), (#473)
+  - Word movement uses ALT key;
+  - Shortcuts uses CMD key;
+  - Double-clicking text select a single word;
+  - Jumping to next word sets cursor to end of current word instead of beginning of current word.
+- InputText(): Added BufTextLen in ImGuiTextEditCallbackData. Requesting user to maintain it
+  if buffer is modified. Zero-ing structure properly before use. (#541)
 - CheckboxFlags(): Added support for testing/setting multiple flags at the same time. (@DMartinek) (#555)
 - TreeNode(), CollapsingHeader() fixed not being able to use "##" sequence in a formatted label.
 - ColorEdit4(): Empty label doesn't add InnerSpacing.x, matching behavior of other widgets. (#346)
@@ -5260,11 +5473,13 @@ Other Changes:
 - Demo: plot code doesn't use ImVector to avoid heap allocation and be more friendly to custom allocator users. (#538)
 - Fixed compilation on DragonFly BSD (@mneumann) (#563)
 - Examples: Vulkan: Added a Vulkan example (@Loftilus) (#549)
-- Examples: DX10, DX11: Saving/restoring most device state so dropping render function in your codebase shouldn't have DX device side-effects. (#570)
+- Examples: DX10, DX11: Saving/restoring most device state so dropping render function in your
+  codebase shouldn't have DX device side-effects. (#570)
 - Examples: DX10, DX11: Fixed ImGui_ImplDX??_NewFrame() from recreating device objects if render isn't called (g_pVB not set).
 - Examples: OpenGL3: Fix BindVertexArray/BindBuffer order. (@nlguillemot) (#527)
 - Examples: OpenGL: skip rendering and calling glViewport() if we have zero-fixed buffer. (#486)
-- Examples: SDL2+OpenGL3: Fix context creation options. Made ImGui_ImplSdlGL3_NewFrame() signature match GL2 one. (#468, #463)
+- Examples: SDL2+OpenGL3: Fix context creation options. Made ImGui_ImplSdlGL3_NewFrame() signature
+  match GL2 one. (#468, #463)
 - Examples: SDL2+OpenGL2/3: Fix for high-dpi displays. (@nickgravelyn)
 - Various extra comments and clarification in the code.
 - Various other fixes and optimizations.
@@ -5388,7 +5603,11 @@ Breaking Changes:
   are now incorporating the scrolling amount. They were incorrectly not incorporating this amount previously.
   It PROBABLY shouldn't break anything, but that depends on how you used them. Namely:
   - If you always used SetCursorPos() with values relative to GetCursorPos() there shouldn't be a problem.
-    However if you used absolute coordinates, note that SetCursorPosY(100.0f) will put you at +100 from the initial Y position (which may be scrolled out of the view), NOT at +100 from the window top border. Since there wasn't any official scrolling value on X axis (past just manually moving the cursor) this can only affect you if you used to set absolute coordinates on the Y axis which is hopefully rare/unlikely, and trivial to fix.
+    However if you used absolute coordinates, note that SetCursorPosY(100.0f) will put you at +100 from the
+    initial Y position (which may be scrolled out of the view), NOT at +100 from the window top border.
+    Since there wasn't any official scrolling value on X axis (past just manually moving the cursor) this can
+    only affect you if you used to set absolute coordinates on the Y axis which is hopefully rare/unlikely,
+    and trivial to fix.
   - The value of GetWindowContentRegionMax() isn't necessarily close to GetWindowWidth() if horizontally scrolling.
     Previously they were roughly interchangeable (roughly because the content region exclude window padding).
 
@@ -5416,9 +5635,11 @@ Other Changes:
 - TreeNode(): Fixed mouse interaction padding past the node label being accounted for in layout (#282).
 - BeginChild(): Passing a ImGuiWindowFlags_NoMove inhibits moving parent window from this child.
 - BeginChild() fixed missing rounding for child sizes which leaked into layout and have items misaligned.
-- Begin(): Removed default name = "Debug" parameter. We already have a "Debug" window pushed to the stack in the first place so it's not really a useful default.
+- Begin(): Removed default name = "Debug" parameter. We already have a "Debug" window pushed to the stack in
+  the first place so it's not really a useful default.
 - Begin(): Minor fixes with windows main clipping rectangle (e.g. child window with border).
-- Begin(): Window flags are only read on the first call of the frame. Subsequent calls ignore flags, which allows appending to a window without worryin about flags.
+- Begin(): Window flags are only read on the first call of the frame. Subsequent calls ignore flags, which allows
+  appending to a window without worryin about flags.
 - InputText(): ignore character input when ctrl/alt are held. (Normally those text input are ignored by most wrappers.) (#279).
 - Demo: Fixed incorrectly formed string passed to Combo (#298).
 - Demo: Added simple Log demo.
@@ -5573,10 +5794,13 @@ Other Changes:
 - Added TitleBgActive color in style so focused window is made visible. (#253)
 - Added CaptureKeyboardFromApp() / CaptureMouseFromApp() to manually enforce inputs capturing.
 - Added DragFloatRange2() DragIntRange2() helpers. (#76)
-- Added a Y centering ratio to SetScrollFromCursorPos() which can be used to aim the top or bottom of the window. (#150)
+- Added a Y centering ratio to SetScrollFromCursorPos() which can be used to aim the top
+  or bottom of the window. (#150)
 - Added SetScrollY(), SetScrollFromPos(), GetCursorStartPos() for manual scrolling manipulations. (#150).
-- Added GetKeyIndex() helper for converting from ImGuiKey_\* enum to user's keycodes. Basically pulls from io.KeysMap[].
-- Added missing ImGuiKey_PageUp, ImGuiKey_PageDown so more UI code can be written without referring to implementation-side keycodes.
+- Added GetKeyIndex() helper for converting from ImGuiKey_\* enum to user's keycodes.
+  Basically pulls from io.KeysMap[].
+- Added missing ImGuiKey_PageUp, ImGuiKey_PageDown so more UI code can be written without
+  referring to implementation-side keycodes.
 - MenuItem() can be activated on release. (#245)
 - Allowing NewFrame() with DeltaTime==0.0f to not assert.
 - Fixed IsMouseDragging(). (#260)
@@ -5587,8 +5811,8 @@ Other Changes:
 - Fixed text baseline alignment of small button (no padding) after regular buttons.
 - Fixed ListBoxHeader() not honoring negative sizes the same way as BeginChild() or BeginChildFrame(). (#263)
 - Fixed warnings for more pedantic compiler settings (#258).
-- ImVector<> cannot be re-defined anymore, cannot be replaced with std::vector<>. Allowed us to clean up and optimize
-  lots of code. Yeah! (#262)
+- ImVector<> cannot be re-defined anymore, cannot be replaced with std::vector<>.
+  Allowed us to clean up and optimize lots of code. Yeah! (#262)
 - ImDrawList: store pointer to their owner name for easier auditing/debugging.
 - Examples: added scroll tracking example with SetScrollFromCursorPos().
 - Examples: metrics windows render clip rectangle when hovering over a draw call.
@@ -5611,11 +5835,12 @@ Breaking Changes:
 
 Other Changes:
 
-- Added InputTextMultiline() multi-line text editor, vertical scrolling, selection, optimized enough to handle rather
-  big chunks of text in stateless context (thousands of lines are ok), option for allowing Tab to be input, option
-  for validating with Return or Ctrl+Return (#200).
-- Added modal window API, BeginPopupModal(), follows the popup api scheme. Modal windows can be closed by clicking
-  outside. By default the rest of the screen is dimmed (using ImGuiCol_ModalWindowDarkening). Modal windows can be stacked.
+- Added InputTextMultiline() multi-line text editor, vertical scrolling, selection, optimized
+  enough to handle rather big chunks of text in stateless context (thousands of lines are ok),
+  option for allowing Tab to be input, option for validating with Return or Ctrl+Return (#200).
+- Added modal window API, BeginPopupModal(), follows the popup api scheme. Modal windows can be closed
+  by clicking outside. By default the rest of the screen is dimmed (using ImGuiCol_ModalWindowDarkening).
+  Modal windows can be stacked.
 - Added GetGlyphRangesCyrillic() helper (#237).
 - Added SetNextWindowPosCenter() to center a window prior to knowing its size. (#249)
 - Added IsWindowHovered() helper.
@@ -5631,7 +5856,8 @@ Other Changes:
 - Selectable(): Added flag ImGuiSelectableFlags_DontClosePopups.
 - Selectable(): Added flag ImGuiSelectableFlags_SpanAllColumns (#125).
 - Combo(): Fixed issue with activating a Combo() not taking active id (#241).
-- ColorButton(), ColorEdit4(): fix to ensure that the colored square stays square when non-default padding settings are used.
+- ColorButton(), ColorEdit4(): fix to ensure that the colored square stays square when
+  non-default padding settings are used.
 - BeginChildFrame(): returns bool like BeginChild() for clipping.
 - SetScrollPosHere(): takes account of item height + more accurate centering + fixed precision issue.
 - ImFont: ignoring '\r'.
@@ -5653,26 +5879,30 @@ Breaking Changes:
 - The third parameter of Button(), 'repeat_if_held' has been removed. While it's been very rarely used,
   some code will possibly break if you didn't rely on the default parameter.
   Use PushButtonRepeat()/PopButtonRepeat() to configure repeat.
-- Renamed IsRectClipped() to !IsRectVisible() for consistency (opposite return value!). Kept inline redirection function (will obsolete)
-- Renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline indirection function (will obsolete).
+- Renamed IsRectClipped() to !IsRectVisible() for consistency (opposite return value!).
+  Kept inline redirection function (will obsolete)
+- Renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency.
+  Kept inline indirection function (will obsolete).
 
 Other Changes:
 
-- Menus: Added a menu system! Menus are typically populated with menu items and sub-menus, but you can add any sort of
-  widgets in them (buttons, text inputs, sliders, etc.). (#126)
-- Menus: Added MenuItem() to append a menu item. Optional shortcut display, acts a button & toggle with checked/unchecked state,
-  disabled mode. Menu items can be used in any window.
+- Menus: Added a menu system! Menus are typically populated with menu items and sub-menus,
+  but you can add any sort of widgets in them (buttons, text inputs, sliders, etc.). (#126)
+- Menus: Added MenuItem() to append a menu item. Optional shortcut display, acts a button & toggle
+  with checked/unchecked state, disabled mode. Menu items can be used in any window.
 - Menus: Added BeginMenu() to append a sub-menu. Note that you generally want to add sub-menu inside a popup or a menu-bar.
   They will work inside a normal window but it will be a bit unusual.
 - Menus: Added BeginMenuBar() to append to window menu-bar (set ImGuiWindowFlags_MenuBar to enable).
 - Menus: Added BeginMainMenuBar() helper to append to a fullscreen main menu-bar.
 - Popups: Support for stacked popups. Each popup level inhibit inputs to lower levels. The menus system is based on this. (#126).
-- Popups: Added BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid() to create a popup window on mouse-click.
+- Popups: Added BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid() to
+  create a popup window on mouse-click.
 - Popups: Popups have borders by default (#197), attenuated border alpha in default theme.
-- Popups & Tooltip: Fit within display. Handling various positioning/sizing/scrolling edge cases. Better hysteresis when moving
-  in corners. Tooltip always tries to stay away from mouse-cursor.
+- Popups & Tooltip: Fit within display. Handling various positioning/sizing/scrolling edge
+  cases. Better hysteresis when moving in corners. Tooltip always tries to stay away from mouse-cursor.
 - Added ImGuiStorage::GetVoidPtrRef() for manipulating stored void*.
-- Added IsKeyDown() IsMouseDown() as convenience and for consistency with existing functions (instead of reading them from IO structures).
+- Added IsKeyDown() IsMouseDown() as convenience and for consistency with existing functions
+  (instead of reading them from IO structures).
 - Added Dummy() helper to advance layout by a given size. Unlike InvisibleButton() this doesn't catch any click.
 - Added configurable io.KeyRepeatDelay, io.KeyRepeatRate keyboard and mouse repeat rate.
 - Added PushButtonRepeat() / PopButtonRepeat() to enable hold-button-to-repeat press on any button.
@@ -5698,7 +5928,8 @@ Other Changes:
 - Window: Added ImGuiSetCond_Appearing to test the hidden->visible transition in SetWindow***/SetNextWindow*** functions.
 - Window: Auto-fitting cancel out one worth of vertical spacing for vertical symmetry (like what group and tooltip do).
 - Window: Default item width for auto-resizing windows expressed as a factor of font height, scales better with different font.
-- Window: Fixed auto-fit calculation mismatch of whether a scrollbar will be added by maximum height clamping. Also honor NoScrollBar in the case of height clamping, not adding extra horizontal space.
+- Window: Fixed auto-fit calculation mismatch of whether a scrollbar will be added by maximum height
+  clamping. Also honor NoScrollBar in the case of height clamping, not adding extra horizontal space.
 - Window: Hovering require to hover same child window. Reverted 860cf57 (December 3). Might break something if you have
   child overlapping items in parent window.
 - Window: Fixed appending multiple times to an existing child via multiple BeginChild/EndChild calls to same child name.
@@ -5707,7 +5938,8 @@ Other Changes:
 - Metrics: Added io.MetricsActiveWindows counter. (#213.
 - Metrics: Added io.MetricsAllocs counter (number of active memory allocations).
 - Metrics: ShowMetricsWindow() shows popups stack, allocations.
-- Style: Added style.DisplayWindowPadding to prevent windows from reaching edges of display (similar to style.DisplaySafeAreaPadding which is still in effect and also affect popups/tooltips).
+- Style: Added style.DisplayWindowPadding to prevent windows from reaching edges of display
+  (similar to style.DisplaySafeAreaPadding which is still in effect and also affect popups/tooltips).
 - Style: Removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
 - Style: Added style.ScrollbarRounding. (#212)
 - Style: Added ImGuiCol_TextDisabled for disabled text. Added TextDisabled() helper.
@@ -5749,9 +5981,11 @@ Other Changes:
   Hold SHIFT/ALT to speed-up/slow-down. Double-click or CTRL+click to input text.
   Passing min >= max makes the widget unbounded.
 - Added DragFloat2(), DragFloat3(), DragFloat4(), DragInt2(), DragInt3(), DragInt4() helper variants.
-- Added ShowMetricsWindow() which is mainly useful to debug ImGui internals. Added IO.MetricsRenderVertices counter.
+- Added ShowMetricsWindow() which is mainly useful to debug ImGui internals.
+- Added IO.MetricsRenderVertices counter.
 - Added ResetMouseDragDelta() for iterative dragging operations.
-- Added ImFontAtlas::AddFontFromCompressedTTF() helper + binary_to_compressed_c.cpp tool to compress a file and create a .c array from it.
+- Added ImFontAtlas::AddFontFromCompressedTTF() helper + binary_to_compressed_c.cpp tool to
+  compress a file and create a .c array from it.
 - Added PushId() GetId() variants that takes string range to avoid user making unnecessary copies.
 - Added IsItemVisible().
 - Fixed IsRectClipped() incorrectly returning false when log is enabled.
@@ -5773,7 +6007,8 @@ Other Changes:
 - ShowTestWindow(): added examples for DragFloat, DragInt and only custom label embedded in format strings.
 - ShowTestWindow(): fixed "manipulating titles" example not doing the right thing, broken in ff35d24
 - Examples: OpenGL/GLFW: Fixed modifier key state setting in GLFW callbacks.
-- Examples: OpenGL/GLFW: Added glBindTexture(0) in OpenGL fixed pipeline examples. Save restore current program and texture in the OpenGL3 example.
+- Examples: OpenGL/GLFW: Added glBindTexture(0) in OpenGL fixed pipeline examples.
+  Save restore current program and texture in the OpenGL3 example.
 - Examples: DirectX11: Removed unnecessary vertices conversion and CUSTOMVERTEX types.
 - Comments, fixes, tweaks.
 
@@ -5787,16 +6022,22 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 Other Changes:
 
 - Added a more convenient three parameters version of Begin() which covers the common uses better.
-- Added mouse cursor types handling (resize, move, text input cursors, etc.) that user can query with GetMouseCursor(). Added demo and instructions in ShowTestWindow().
+- Added mouse cursor types handling (resize, move, text input cursors, etc.) that user
+  can query with GetMouseCursor(). Added demo and instructions in ShowTestWindow().
 - Added embedded mouse cursor data for MouseDrawCursor software cursor rendering, for consoles/tablets/etc. (#155).
-- Added first version of BeginPopup/EndPopup() helper API to create popup menus. Popups automatically lock their position to the mouse cursor when first appearing. They close  automatically when clicking outside, and inhibit hovering items from other windows when active (to allow for clicking outside). (#126)
+- Added first version of BeginPopup/EndPopup() helper API to create popup menus. Popups automatically
+  lock their position to the mouse cursor when first appearing. They close automatically when clicking
+  outside, and inhibit hovering items from other windows when active (to allow for clicking outside). (#126)
 - Added thickness parameter to ImDrawList::AddLine().
 - Added ImDrawList::PushClipRectFullScreen() helper.
-- Added style.DisplaySafeAreaPadding which was previously hard-coded (useful if you can't see the edges of your display, e.g. TV screens).
+- Added style.DisplaySafeAreaPadding which was previously hard-coded.
+   (useful if you can't see the edges of your display, e.g. TV screens).
 - Added CalcItemRectClosestPoint() helper.
-- Added GetMouseDragDelta(), IsMouseDragging() helpers, given a mouse button and an optional "unlock" threshold. Added io.MouseDragThreshold setting. (#167)
+- Added GetMouseDragDelta(), IsMouseDragging() helpers, given a mouse button and an optional
+  "unlock" threshold. Added io.MouseDragThreshold setting. (#167)
 - IsItemHovered() return false if another widget is active, aka we can't use what we are hovering now.
-- Added IsItemHoveredRect() if old behavior of IsItemHovered() is needed (e.g. for implementing the drop side of a drag'n drop operation).
+- Added IsItemHoveredRect() if old behavior of IsItemHovered() is needed (e.g. for implementing
+  the drop side of a drag'n drop operation).
 - IsItemhovered() include space taken by label and behave consistently for all widgets (#145)
 - Auto-filling child window feed their content size to parent (#170)
 - InputText() removed the odd ~ characters when clipping.
@@ -5806,15 +6047,20 @@ Other Changes:
 - Selectable(const char*, bool) version has bool defaulting to false.
 - Selectable(): fixed misusage of GetContentRegionMax().x leaking into auto-fitting.
 - Windows starting Collapsed runs initial auto-fit to retrieve a width for their title bar (#175)
-- Fixed new window from having an incorrect content size on their first frame, if queried by user. Fixed SetWindowPos/SetNextWindowPos having a side-effect size computation (#175)
+- Fixed new window from having an incorrect content size on their first frame, if queried by user.
+  Fixed SetWindowPos/SetNextWindowPos having a side-effect size computation (#175)
 - InputFloat(): fixed label alignment if total widget width forcefully bigger than space available.
 - Auto contents size aware of enforced vertical scrollbar if window is larger than display size.
-- Fixed new windows auto-fitting bigger than their .ini saved size. This was a bug but it may be a desirable effect sometimes, may reconsider it.
-- Fixed negative clipping rectangle when collapsing windows that could affect manual submission to ImDrawList and end-user rendering function if unhandled (#177)
+- Fixed new windows auto-fitting bigger than their .ini saved size.
+  This was a bug but it may be a desirable effect sometimes, may reconsider it.
+- Fixed negative clipping rectangle when collapsing windows that could affect manual
+  submission to ImDrawList and end-user rendering function if unhandled (#177)
 - Fixed bounding measurement of empty groups (fix #162)
-- Fixed assignment order in Begin() making auto-fit size effectively lag by one frame. Also disabling "clamp into view" while windows are auto-fitting so that auto-fitting window in corners don't get pushed away.
+- Fixed assignment order in Begin() making auto-fit size effectively lag by one frame. Also disabling
+  "clamp into view" while windows are auto-fitting so that auto-fitting window in corners don't get pushed away.
 - Fixed MouseClickedPos not updated on double-click update (#167)
-- Fixed MouseDrawCursor feature submitting an empty trailing command in the draw list. Fixed unmerged draw calls for software mouse cursor.
+- Fixed MouseDrawCursor feature submitting an empty trailing command in the draw list.
+ Fixed unmerged draw calls for software mouse cursor.
 - Fixed double-clicking on resize grip keeping the grip active if mouse button is kept held.
 - Bounding box tests exclude higher bound, so touching items (zero spacing) don't report double hover when cursor is on edge.
 - Setting io.LogFilename to NULL disable default LogToFile() (part of #175)
@@ -5845,7 +6091,8 @@ Other Changes:
 - Added IsRootWindowFocused(), IsRootWindowOrAnyChildFocused().
 - Added io.KeyAlt + support in examples apps, in prevision for future usage of Alt modifier (was missing).
 - Added ImGuiStyleVar_GrabMinSize enum value for PushStyleVar().
-- Various fixes related to vertical alignment of text after widget of varied sizes. Allow for multiple blocks of multiple lines text on the same "line". Added demos.
+- Various fixes related to vertical alignment of text after widget of varied sizes.
+  Allow for multiple blocks of multiple lines text on the same "line". Added demos.
 - Explicit size passed to Plot*(), Button() includes the frame padding.
 - Style: Changed default Border and Column border colors to be most subtle.
 - Renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing.
@@ -5874,8 +6121,10 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 
 Other Changes:
 
-- Examples: refactored all examples application to make it easier to isolate and grab the code you need for OpenGL 2/3, DirectX 9/11, and toward a more sensible format for samples.
-- Scrollbar grab have a minimum size (style.GrabSizeMin), always visible even with huge scroll amount. (#150).
+- Examples: refactored all examples application to make it easier to isolate and grab the
+  code you need for OpenGL 2/3, DirectX 9/11, and toward a more sensible format for samples.
+- Scrollbar grab have a minimum size (style.GrabSizeMin), always visible even with huge
+  scroll amount. (#150).
 - Scrollbar: Clicking inside the grab box doesn't modify scroll value. Subsequent movement always relative.
 - Added "###" labelling syntax to pass a label that isn't part of the hashed ID (#107), e.g. ("%d###static_id",rand()).
 - Added GetColumnIndex(), GetColumnsCount() (#154)
@@ -5885,12 +6134,15 @@ Other Changes:
 - Fixed ListBoxHeader() incorrect handling of SkipItems early out when window is collapsed.
 - Fixed using IsItemHovered() after EndChild() (#151)
 - Fixed malformed UTF-8 decoding errors leading to infinite loops (#158)
-- InputText() handles buffer limit correctly for multi-byte UTF-8 characters, won't insert an incomplete UTF-8 character when reaching buffer limit (fix #158)
-- Handle double-width space (0x3000) in various places the same as single-width spaces, for Chinese/Japanese users.
+- InputText() handles buffer limit correctly for multi-byte UTF-8 characters, won't insert
+  an incomplete UTF-8 character when reaching buffer limit (fix #158)
+- Handle double-width space (0x3000) in various places the same as single-width spaces,
+  for Chinese/Japanese users.
 - Collapse triangle uses text color (not border color).
 - Fixed font fallback glyph width.
 - Renamed style.ScrollBarWidth to style.ScrollbarWidth to be consistent with other casing.
-- Windows: setup a default handler for ImeSetInputScreenPosFn so the IME dialog (for Japanese/Chinese, etc.) is positioned correctly as you input text.
+- Windows: setup a default handler for ImeSetInputScreenPosFn so the IME dialog
+  (for Japanese/Chinese, etc.) is positioned correctly as you input text.
 - Windows: default clipboard handlers for Windows handle UTF-8.
 - Examples: Fixed DirectX 9/11 examples applications handling of Microsoft IME.
 - Examples: Allow DirectX 9/11 examples applications to resize the window.
@@ -5909,7 +6161,8 @@ Other Changes:
 - Added Bullet() helper - equivalent to BulletText(""), SameLine().
 - Added SetWindowFocus(), SetWindowFocus(const char*), SetNextWindowFocus() (#146)
 - Added SetWindowPos(), SetWindowSize(), SetWindowCollaposed() given a window name.
-- Added SetNextTreeNodeOpened() with optional condition flag in replacement of OpenNextNode() and consistent with other API.
+- Added SetNextTreeNodeOpened() with optional condition flag in replacement of OpenNextNode()
+  and consistent with other API.
 - Renamed ImGuiSetCondition_* to ImGuiSetCond_* and ImGuiCondition_FirstUseThisSession to ImGuiCond_Once.
 - Added missing definition for ImGui::GetWindowCollapsed().
 - Fixed GetGlyphRangesJapanese() actually missing katakana ranges and a few useful extensions.
@@ -5940,18 +6193,23 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 
 Other Changes:
 
-- InputText: having a InputText widget active doesn't steal mouse inputs from clicking on a button before losing focus (relate to #134)
+- InputText: having a InputText widget active doesn't steal mouse inputs from clicking on
+  a button before losing focus (relate to #134)
 - InputText: cursor/selection/undo stack persist when using other widgets and getting back to same (#134).
-- InputText: fix effective buffer size being smaller than necessary by 1 byte (so if you give 3 bytes you can input 2 ascii chars + zero terminator, which is correct).
+- InputText: fix effective buffer size being smaller than necessary by 1 byte (so if you give
+  3 bytes you can input 2 ascii chars + zero terminator, which is correct).
 - Added IsAnyItemActive().
-- Child window explicitly inherit collapse state from parent (so if user keeps submitting items even thought Begin has returned 'false' the child items will be clipped faster).
+- Child window explicitly inherit collapse state from parent (so if user keeps submitting items
+  even thought Begin has returned 'false' the child items will be clipped faster).
 - BeginChild() return a bool the same way Begin() does. if true you can skip submitting content.
 - Removed extraneous (1,1) padding on child window (pointed out in #125)
 - Columns: doesn't bail out when SkipItems is set (fix #136)
 - Columns: Separator() within column correctly vertical offset all cells (pointed out in #125)
-- GetColumnOffset() / SetColumnOffset() handles padding values more correctly so matching columns can be lined up between a parent and a child window (cf. #125)
+- GetColumnOffset() / SetColumnOffset() handles padding values more correctly so matching columns
+  can be lined up between a parent and a child window (cf. #125)
 - Fix ImFont::BuildLookupTable() potential dangling pointer dereference (fix #131)
-- Fix hovering of child window extending past their parent not taking account of parent clipping rectangle (fix #137)
+- Fix hovering of child window extending past their parent not taking account of parent clipping
+  rectangle (fix #137)
 - Sliders: value text is clipped inside the frame when resizing sliders to be small.
 - ImGuITextFilter::Draw() use regular width call rather than computing its own arbitrary width.
 - ImGuiTextFilter: can take a default filter string during construction.
@@ -5969,11 +6227,13 @@ Other Changes:
 - Added ListBox() (#129).
 - Added ListBoxHeader(), ListBoxFooter() for customized list traversal and creating multi-selection boxes.
 - Fixed title bar text clipping issue (fix #128).
-- InputText: added ImGuiInputTextFlags_CallbackCharFilter system for filtering/replacement (#130). Callback now passed an "EventFlag" parameter.
+- InputText: added ImGuiInputTextFlags_CallbackCharFilter system for filtering/replacement (#130).
+  Callback now passed an "EventFlag" parameter.
 - InputText: Added ImGuiInputTextFlags_CharsUppercase and ImGuiInputTextFlags_CharsNoBlank stock filters.
 - PushItemWidth() can take negative value to right-align items.
 - Optimisation: Columns offsets cached to avoid unnecessary binary search.
-- Optimisation: Optimized CalcTextSize() function by about 25% (they are often the bottleneck when submitting thousands of clipped items).
+- Optimisation: Optimized CalcTextSize() function by about 25% (they are often the bottleneck when
+  submitting thousands of clipped items).
 - Added ImGuiCol_ChildWindowBg, ImGuiStyleVar_ChildWindowRounding for completeness and flexibility.
 - Added BeginChild() variant that takes an ImGuiID.
 - Tweak default ImGuiCol_HeaderActive color to be less bright.
@@ -5989,9 +6249,11 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 Other Changes:
 
 - Added ImGuiWindowFlags_NoCollapse flag.
-- Added a way to replace the internal state pointer so that we can optionally share it between modules (e.g. multiple DLLs).
+- Added a way to replace the internal state pointer so that we can optionally share it between
+  modules (e.g. multiple DLLs).
 - Added tint_col parameter to ImageButton().
-- Added CalcListClipping() helper to perform faster/coarse clipping on user side (when manipulating lists with thousands of items).
+- Added CalcListClipping() helper to perform faster/coarse clipping on user side
+  (when manipulating lists with thousands of items).
 - Added GetCursorPosX() / GetCursorPosY() shortcuts.
 - Renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing().
 - Combo box always appears above other child windows of a same parent.
@@ -6013,7 +6275,8 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 
 Breaking Changes:
 
-- Big update! Initialisation had to be changed. You don't need to load PNG data anymore. The new system gives you uncompressed texture data.
+- Big update! Initialisation had to be changed. You don't need to load PNG data anymore. Th
+  new system gives you uncompressed texture data.
   - This sequence:
       const void* png_data;
       unsigned int png_size;
@@ -6026,19 +6289,23 @@ Breaking Changes:
       io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
       // 
       io.Fonts->TexID = (your_texture_identifier);
-  - PixelCenterOffset has been removed and isn't a necessary setting anymore. Offset your projection matrix by 0.5 if you have rendering problems.
+  - PixelCenterOffset has been removed and isn't a necessary setting anymore. Offset your
+    projection matrix by 0.5 if you have rendering problems.
 
 Other Changes:
 
 - Loading TTF files with stb_truetype.h.
 - We still embed a compressed pixel-perfect TTF version of ProggyClean for convenience.
 - Runtime font rendering is a little faster than previously.
-- You can load multiple fonts with multiple size inside the font atlas. Rendering with multiple fonts are still merged into a single draw call whenever possible.
+- You can load multiple fonts with multiple size inside the font atlas. Rendering with multiple
+  fonts are still merged into a single draw call whenever possible.
 - The system handles UTF-8 and provide ranges to easily load e.g. characters for Japanese display.
 - Added PushFont() / PopFont().
 - Added Image() and ImageButton() to display your own texture data.
-- Added callback system in command-list. This can be used if you want to do your own rendering (e.g. render a 3D scene) inside ImGui widgets.
-- Added IsItemActive() to tell if last widget is being held / modified (as opposed to just being hovered). Useful for custom dragging behaviors.
+- Added callback system in command-list. This can be used if you want to do your own rendering
+  (e.g. render a 3D scene) inside ImGui widgets.
+- Added IsItemActive() to tell if last widget is being held / modified (as opposed to just
+  being hovered). Useful for custom dragging behaviors.
 - Style: Added FrameRounding setting for a more rounded look (default to 0 for now).
 - Window: Fixed using multiple Begin/End pair on the same wnidow.
 - Window: Fixed style.WindowMinSize not being honored properly.
@@ -6071,7 +6338,8 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 - Dragging outside area of a widget while it is active doesn't trigger hover on other widgets.
 - Activating widget bring parent window to front if not already.
 - Checkbox and Radio buttons activate on click-release to be consistent with other widgets and most UI.
-- InputText() nows consume input characters immediately so they cannot be reused if ImGui::Update is called again with a call to ImGui::Render(). (fixes #105)
+- InputText() nows consume input characters immediately so they cannot be reused if
+  ImGui::Update is called again with a call to ImGui::Render(). (fixes #105)
 - Examples: Console: added support for History callbacks + some cleanup.
 - Various small optimisations.
 - Cleanup and other fixes.
@@ -6089,7 +6357,8 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 - Widgets more consistently handle empty labels (starting with ## mark) for their size calculation.
 - Fixed crashing with zero sized frame-buffer.
 - Fixed ImGui::Combo() not registering its size properly when clipped out of screen.
-- Renamed second parameter to Begin() to 'bool* p_opened' to be a little more self-explanatory. Added more comments on the use of Begin().
+- Renamed second parameter to Begin() to 'bool* p_opened' to be a little more self-explanatory.
+  Added more comments on the use of Begin().
 - Logging: Added LogText() to pass text straight to the log output (tty/clipboard/file) without rendering it.
 - Logging: Added LogFinish() to stop logging at an arbitrary point.
 - Logging: Log depth padding relative to start depth.
@@ -6108,7 +6377,10 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 
 - Added ImGuiWindowFlags_NoScrollWithMouse, disable mouse wheel scrolling on a window.
 - Added ImGuiWindowFlags_NoSavedSettings, disable loading/saving window state to .ini file.
-- Added SetNextWindowPos(), SetNextWindowSize(), SetNextWindowCollapsed() API along with SetWindowPos(), SetWindowSize(), SetWindowCollapsed(). All functions include an optional second parameter to easily set current value vs session default value vs persistent default value.
+- Added SetNextWindowPos(), SetNextWindowSize(), SetNextWindowCollapsed() API along
+  with SetWindowPos(), SetWindowSize(), SetWindowCollapsed(). All functions include an
+  optional second parameter to easily set current value vs session default value vs.
+  persistent default value.
 - Removed rarely useful SetNewWindowDefaultPos() in favor of new API.
 - Fixed hovering of lower-right resize grip when it is above a child window.
 - Fixed InputInt() writing to output when it doesn't need to.
@@ -6134,7 +6406,8 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 - Increased visibility of check box and radio button with smaller size.
 - Smooth mouse scrolling on OSX (uses floating point scroll/wheel input).
 - New version of IMGUI_ONCE_UPON_A_FRAME helper macro that works with all compilers.
-- Moved IO.Font*** options to inside the IO.Font-> structure.. Added IO.FontGlobalScale setting (in addition to Font->Scale per individual font).
+- Moved IO.Font*** options to inside the IO.Font-> structure.
+- Added IO.FontGlobalScale setting (in addition to Font->Scale per individual font).
 - Fixed more Clang -Weverything warnings.
 - Examples: Added DirectX11 example application.
 - Examples: Created single .sln solution for all example projects.
@@ -6162,7 +6435,8 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 - Fixed unaligned memory access for Emscripten compatibility.
 - Various pedantic warning fixes (now testing with Clang).
 - Added extra asserts to catch incorrect usage.
-- PushStyleColor() / PushStyleVar() can be used outside the scope of a window (namely to change variables that are used within the Begin() call).
+- PushStyleColor() / PushStyleVar() can be used outside the scope of a window (namely to change
+  variables that are used within the Begin() call).
 - PushTextWrapPos() defaults to 0.0 (right-end of current drawing region).
 - Fixed compatibility with std::vector if user decide to #define ImVector.
 - MouseWheel input is now normalized.
@@ -6200,7 +6474,8 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 - Comments and fixes.
 - Added SetKeyboardFocusHere() to set input focus from code.
 - Added GetWindowFont(), GetWindowFontSize() for users of the low-level ImDrawList API.
-- Added a UserData void *pointer so that the callback functions can access user state "Just in case a project has adverse reactions to adding globals or statics in their own code."
+- Added a UserData void *pointer so that the callback functions can access user state
+  "Just in case a project has adverse reactions to adding globals or statics in their own code."
 - Renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL
 
 
@@ -6228,7 +6503,8 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 - Added IsMouseHoveringWindow(), IsMouseHoveringAnyWindow(), IsPosHoveringAnyWindow() helpers.
 - Added va_list variations of all functions taking ellipsis (...) parameters.
 - Added section in documentation to explicitly document cases of API breaking changes (e.g. renamed IM_MALLOC below).
-- Moved IM_MALLOC / IM_FREE defines. to IO structure members that can be set at runtime (also allowing precompiled ImGui to cover more use cases).
+- Moved IM_MALLOC / IM_FREE defines. to IO structure members that can be set at runtime
+  (also allowing precompiled ImGui to cover more use cases).
 - Fixed OpenGL samples for Retina display.
 - Comments and minor fixes.
 
@@ -6268,7 +6544,10 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 
 Breaking Changes:
 
-- The behaviour of PixelCenterOffset changed! You may need to change your value if you had set it to non-default in your code and/or offset your projection matrix by 0.5 pixels. It is likely that the default PixelCenterOffset value of 0.0 is now suitable unless your rendering uses some form of multisampling.
+- The behaviour of PixelCenterOffset changed! You may need to change your value if you had set
+  it to non-default in your code and/or offset your projection matrix by 0.5 pixels. It is
+  likely that the default PixelCenterOffset value of 0.0 is now suitable unless your rendering
+  uses some form of multisampling.
 
 Other Changes:
 
@@ -6299,10 +6578,12 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v
 Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.07
 
 - Added InputFloat4(), SliderFloat4() helpers.
-- Added global Alpha in ImGuiStyle structure. When Alpha=0.0, ImGui skips most of logic and all rendering processing.
+- Added global Alpha in ImGuiStyle structure. When Alpha=0.0, ImGui skips most of logic
+  and all rendering processing.
 - Fix clipping of title bar text.
 - Fix to allow the user to call NewFrame() multiple times without calling Render().
-- Reduce inner window clipping to take account for the extend of CollapsingHeader() - share same clipping rectangle.
+- Reduce inner window clipping to take account for the extend of CollapsingHeader() - share
+  same clipping rectangle.
 - Fix for child windows with inverted clip rectangles (when scrolled and out of screen, Etc.).
 - Minor fixes, tweaks, comments.
 

From 57ab2b4226010f3291c79a9ba1e72e72041fbe9f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Michael=20B=C3=B6hme?= 
Date: Tue, 5 Nov 2024 23:26:41 +0100
Subject: [PATCH 0482/2359] Fixed unused function warning (#8130)

---
 imgui.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/imgui.cpp b/imgui.cpp
index 01a72c6b7..9de1a8157 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1210,9 +1210,11 @@ static int              FindWindowFocusIndex(ImGuiWindow* window);
 // Error Checking and Debug Tools
 static void             ErrorCheckNewFrameSanityChecks();
 static void             ErrorCheckEndFrameSanityChecks();
+#ifndef IMGUI_DISABLE_DEBUG_TOOLS
 static void             UpdateDebugToolItemPicker();
 static void             UpdateDebugToolStackQueries();
 static void             UpdateDebugToolFlashStyleColor();
+#endif
 
 // Inputs
 static void             UpdateKeyboardInputs();

From 6f287dd16d5d7f393d5b6089585dd87ea5ea0d92 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 6 Nov 2024 16:56:51 +0100
Subject: [PATCH 0483/2359] (Breaking) Removed pre-1.87 obsolete io.KeyMap[],
 io.KeysDown[], io.NavInputs[]. Remove IMGUI_DISABLE_OBSOLETE_KEYIO. (#4921)

---
 backends/imgui_impl_allegro5.cpp |   2 +-
 backends/imgui_impl_allegro5.h   |   2 +-
 backends/imgui_impl_android.cpp  |   2 +-
 backends/imgui_impl_android.h    |   2 +-
 backends/imgui_impl_glfw.cpp     |   2 +-
 backends/imgui_impl_glfw.h       |   2 +-
 backends/imgui_impl_glut.cpp     |   2 +-
 backends/imgui_impl_glut.h       |   2 +-
 backends/imgui_impl_osx.h        |   2 +-
 backends/imgui_impl_osx.mm       |   2 +-
 backends/imgui_impl_sdl2.cpp     |   2 +-
 backends/imgui_impl_sdl2.h       |   2 +-
 backends/imgui_impl_sdl3.cpp     |   2 +-
 backends/imgui_impl_sdl3.h       |   2 +-
 backends/imgui_impl_win32.cpp    |   2 +-
 backends/imgui_impl_win32.h      |   2 +-
 docs/CHANGELOG.txt               |  12 +++
 imconfig.h                       |   1 -
 imgui.cpp                        | 173 +++----------------------------
 imgui.h                          |  57 +++-------
 imgui_demo.cpp                   |   8 --
 21 files changed, 60 insertions(+), 223 deletions(-)

diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp
index d5d65703e..3e6d76647 100644
--- a/backends/imgui_impl_allegro5.cpp
+++ b/backends/imgui_impl_allegro5.cpp
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Clipboard support (from Allegro 5.1.12)
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 // Issues:
diff --git a/backends/imgui_impl_allegro5.h b/backends/imgui_impl_allegro5.h
index f1501eca8..aba5c4770 100644
--- a/backends/imgui_impl_allegro5.h
+++ b/backends/imgui_impl_allegro5.h
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Clipboard support (from Allegro 5.1.12)
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 // Issues:
diff --git a/backends/imgui_impl_android.cpp b/backends/imgui_impl_android.cpp
index b0c463931..05939293c 100644
--- a/backends/imgui_impl_android.cpp
+++ b/backends/imgui_impl_android.cpp
@@ -2,7 +2,7 @@
 // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3)
 
 // Implemented features:
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
 // Missing features:
 //  [ ] Platform: Clipboard support.
diff --git a/backends/imgui_impl_android.h b/backends/imgui_impl_android.h
index 92a044db0..efe27dcb9 100644
--- a/backends/imgui_impl_android.h
+++ b/backends/imgui_impl_android.h
@@ -2,7 +2,7 @@
 // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3)
 
 // Implemented features:
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
 // Missing features:
 //  [ ] Platform: Clipboard support.
diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp
index 774fb0d5d..afa2185a3 100644
--- a/backends/imgui_impl_glfw.cpp
+++ b/backends/imgui_impl_glfw.cpp
@@ -6,7 +6,7 @@
 // Implemented features:
 //  [X] Platform: Clipboard support.
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
 
diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h
index 60b95bd99..5d8940a0c 100644
--- a/backends/imgui_impl_glfw.h
+++ b/backends/imgui_impl_glfw.h
@@ -5,7 +5,7 @@
 // Implemented features:
 //  [X] Platform: Clipboard support.
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
 
diff --git a/backends/imgui_impl_glut.cpp b/backends/imgui_impl_glut.cpp
index d8ffc9073..6bb9eae7e 100644
--- a/backends/imgui_impl_glut.cpp
+++ b/backends/imgui_impl_glut.cpp
@@ -6,7 +6,7 @@
 // !!! Nowadays, prefer using GLFW or SDL instead!
 
 // Implemented features:
-//  [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values are obsolete since 1.87 and not supported since 1.91.5]
 // Issues:
 //  [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I
 //  [ ] Platform: Missing horizontal mouse wheel support.
diff --git a/backends/imgui_impl_glut.h b/backends/imgui_impl_glut.h
index a7479e1d7..feeca8b3f 100644
--- a/backends/imgui_impl_glut.h
+++ b/backends/imgui_impl_glut.h
@@ -6,7 +6,7 @@
 // !!! Nowadays, prefer using GLFW or SDL instead!
 
 // Implemented features:
-//  [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values are obsolete since 1.87 and not supported since 1.91.5]
 // Issues:
 //  [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I
 //  [ ] Platform: Missing horizontal mouse wheel support.
diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h
index 28e133128..4caab8ff5 100644
--- a/backends/imgui_impl_osx.h
+++ b/backends/imgui_impl_osx.h
@@ -6,7 +6,7 @@
 // Implemented features:
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 //  [X] Platform: Mouse support. Can discriminate Mouse/Pen.
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend).
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: IME support.
diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm
index 6ff4f19a4..69108ca4a 100644
--- a/backends/imgui_impl_osx.mm
+++ b/backends/imgui_impl_osx.mm
@@ -6,7 +6,7 @@
 // Implemented features:
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 //  [X] Platform: Mouse support. Can discriminate Mouse/Pen.
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend).
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: IME support.
diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp
index 529ca79e0..14022159f 100644
--- a/backends/imgui_impl_sdl2.cpp
+++ b/backends/imgui_impl_sdl2.cpp
@@ -6,7 +6,7 @@
 // Implemented features:
 //  [X] Platform: Clipboard support.
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 //  [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
diff --git a/backends/imgui_impl_sdl2.h b/backends/imgui_impl_sdl2.h
index e551e52a2..8ccc6fdc7 100644
--- a/backends/imgui_impl_sdl2.h
+++ b/backends/imgui_impl_sdl2.h
@@ -5,7 +5,7 @@
 // Implemented features:
 //  [X] Platform: Clipboard support.
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 //  [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp
index de8b53158..3cd56a756 100644
--- a/backends/imgui_impl_sdl3.cpp
+++ b/backends/imgui_impl_sdl3.cpp
@@ -7,7 +7,7 @@
 // Implemented features:
 //  [X] Platform: Clipboard support.
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 
diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h
index 880ba9615..c4a5a1230 100644
--- a/backends/imgui_impl_sdl3.h
+++ b/backends/imgui_impl_sdl3.h
@@ -7,7 +7,7 @@
 // Implemented features:
 //  [X] Platform: Clipboard support.
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 
diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index c213f8158..687bc5a18 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -4,7 +4,7 @@
 // Implemented features:
 //  [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 
diff --git a/backends/imgui_impl_win32.h b/backends/imgui_impl_win32.h
index 3ad1a7eaf..0dfd56a80 100644
--- a/backends/imgui_impl_win32.h
+++ b/backends/imgui_impl_win32.h
@@ -4,7 +4,7 @@
 // Implemented features:
 //  [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
-//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
+//  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 9e43a56a1..603828c39 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -41,6 +41,18 @@ HOW TO UPDATE?
 
 Breaking changes:
 
+- Commented out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before).
+  - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
+  - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
+  - Pre-1.87 backends are not supported:
+    - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
+    - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
+  - For more reference:
+    - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
+    - read https://github.com/ocornut/imgui/issues/4921
+  - If you have trouble updating a very old codebase using legacy backend-specific key codes:
+    consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
+
 Other changes:
 
 - Selectable: selected Selectables use ImGuiCol_Header instead of an arbitrary lerp
diff --git a/imconfig.h b/imconfig.h
index 63d6ba081..fea89dea0 100644
--- a/imconfig.h
+++ b/imconfig.h
@@ -29,7 +29,6 @@
 
 //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
 //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-//#define IMGUI_DISABLE_OBSOLETE_KEYIO                      // 1.87+ disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This is automatically done by IMGUI_DISABLE_OBSOLETE_FUNCTIONS.
 
 //---- Disable all of Dear ImGui or don't implement standard windows/tools.
 // It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
diff --git a/imgui.cpp b/imgui.cpp
index 9de1a8157..74da7355e 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -174,7 +174,6 @@ CODE
       - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
       - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
         Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
-      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
    - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
      with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
 
@@ -430,6 +429,16 @@ CODE
  When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  You can read releases logs https://github.com/ocornut/imgui/releases for more details.
 
+ - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before)
+                            - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
+                            - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
+                            - pre-1.87 backends are not supported:
+                               - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
+                               - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
+                            - for more reference:
+                              - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
+                              - read https://github.com/ocornut/imgui/issues/4921
+                            - if you have trouble updating a very old codebase using legacy backend-specific key codes: consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
  - 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete).
  - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
                          moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
@@ -1390,10 +1399,6 @@ ImGuiIO::ImGuiIO()
     IniSavingRate = 5.0f;
     IniFilename = "imgui.ini"; // Important: "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).
     LogFilename = "imgui_log.txt";
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    for (int i = 0; i < ImGuiKey_COUNT; i++)
-        KeyMap[i] = -1;
-#endif
     UserData = NULL;
 
     Fonts = NULL;
@@ -1456,8 +1461,6 @@ ImGuiIO::ImGuiIO()
     for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
     for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
     AppAcceptingEvents = true;
-    BackendUsingLegacyKeyArrays = (ImS8)-1;
-    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
 }
 
 // Pass in translated ASCII characters for text input.
@@ -1538,9 +1541,6 @@ void ImGuiIO::ClearEventsQueue()
 // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
 void ImGuiIO::ClearInputKeys()
 {
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    memset(KeysDown, 0, sizeof(KeysDown));
-#endif
     for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
     {
         if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
@@ -1625,17 +1625,6 @@ void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
         else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
     }
 
-    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
-    if (BackendUsingLegacyKeyArrays == -1)
-        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
-            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
-    BackendUsingLegacyKeyArrays = 0;
-#endif
-    if (ImGui::IsGamepadKey(key))
-        BackendUsingLegacyNavInputArray = false;
-
     // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
     const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
     const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
@@ -1671,20 +1660,10 @@ void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native
         return;
     IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
     IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
-    IM_UNUSED(native_keycode);  // Yet unused
-    IM_UNUSED(native_scancode); // Yet unused
-
-    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
-    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
-        return;
-    KeyMap[legacy_key] = key;
-    KeyMap[key] = legacy_key;
-#else
-    IM_UNUSED(key);
-    IM_UNUSED(native_legacy_index);
-#endif
+    IM_UNUSED(key);                 // Yet unused
+    IM_UNUSED(native_keycode);      // Yet unused
+    IM_UNUSED(native_scancode);     // Yet unused
+    IM_UNUSED(native_legacy_index); // Yet unused
 }
 
 // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
@@ -8928,27 +8907,10 @@ ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
     if (key & ImGuiMod_Mask_)
         key = ConvertSingleModFlagToKey(key);
 
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
-    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
-        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
-#else
     IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
-#endif
     return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
 }
 
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-// Formally moved to obsolete section in 1.90.5 in spite of documented as obsolete since 1.87
-ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
-{
-    ImGuiContext& g = *GImGui;
-    IM_ASSERT(IsNamedKey(key));
-    const ImGuiKeyData* key_data = GetKeyData(key);
-    return (ImGuiKey)(key_data - g.IO.KeysData);
-}
-#endif
-
 // Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
 static const char* const GKeyNames[] =
 {
@@ -8980,18 +8942,7 @@ const char* ImGui::GetKeyName(ImGuiKey key)
 {
     if (key == ImGuiKey_None)
         return "None";
-#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
     IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
-#else
-    ImGuiContext& g = *GImGui;
-    if (IsLegacyKey(key))
-    {
-        if (g.IO.KeyMap[key] == -1)
-            return "N/A";
-        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
-        key = (ImGuiKey)g.IO.KeyMap[key];
-    }
-#endif
     if (key & ImGuiMod_Mask_)
         key = ConvertSingleModFlagToKey(key);
     if (!IsNamedKey(key))
@@ -9635,74 +9586,6 @@ static void ImGui::UpdateKeyboardInputs()
     if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
         io.ClearInputKeys();
 
-    // Import legacy keys or verify they are not used
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    if (io.BackendUsingLegacyKeyArrays == 0)
-    {
-        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
-        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
-            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
-    }
-    else
-    {
-        if (g.FrameCount == 0)
-            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
-                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
-
-        // Build reverse KeyMap (Named -> Legacy)
-        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
-            if (io.KeyMap[n] != -1)
-            {
-                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
-                io.KeyMap[io.KeyMap[n]] = n;
-            }
-
-        // Import legacy keys into new ones
-        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
-            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
-            {
-                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
-                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
-                io.KeysData[key].Down = io.KeysDown[n];
-                if (key != n)
-                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
-                io.BackendUsingLegacyKeyArrays = 1;
-            }
-        if (io.BackendUsingLegacyKeyArrays == 1)
-        {
-            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
-            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
-            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
-            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
-        }
-    }
-#endif
-
-    // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
-    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
-    {
-        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
-        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
-        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
-        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
-        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
-        #undef NAV_MAP_KEY
-    }
-#endif
-
     // Update aliases
     for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
         UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
@@ -10100,13 +9983,6 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
             key_changed_mask.SetBit(key_data_index);
             if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input)
                 key_changed_nonchar = true;
-
-            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-            io.KeysDown[key_data_index] = key_data->Down;
-            if (io.KeyMap[key_data_index] != -1)
-                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
-#endif
         }
         else if (e->Type == ImGuiInputEventType_Text)
         {
@@ -10468,14 +10344,6 @@ static void ImGui::ErrorCheckNewFrameSanityChecks()
     IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
     IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
     IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
-        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
-
-    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
-    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
-        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
-#endif
 
     // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way.
     if (g.IO.ConfigErrorRecovery)
@@ -15732,18 +15600,11 @@ void ImGui::ShowMetricsWindow(bool* p_open)
     {
         Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
         {
-            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
             // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
             Indent();
-#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
-            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
-#else
-            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
-            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
-#endif
-            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
-            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
-            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
+            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
+            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
+            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
             Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
             Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
             DebugRenderKeyboardPreview(GetWindowDrawList());
diff --git a/imgui.h b/imgui.h
index 973a52f53..824cea059 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.5 WIP"
-#define IMGUI_VERSION_NUM   19143
+#define IMGUI_VERSION_NUM   19144
 #define IMGUI_HAS_TABLE
 
 /*
@@ -961,9 +961,8 @@ namespace ImGui
 
     // Inputs Utilities: Keyboard/Mouse/Gamepad
     // - the ImGuiKey enum contains all possible keyboard, mouse and gamepad inputs (e.g. ImGuiKey_A, ImGuiKey_MouseLeft, ImGuiKey_GamepadDpadUp...).
-    // - before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. About use of those legacy ImGuiKey values:
-    //  - without IMGUI_DISABLE_OBSOLETE_KEYIO (legacy support): you can still use your legacy native/user indices (< 512) according to how your backend/engine stored them in io.KeysDown[], but need to cast them to ImGuiKey.
-    //  - with    IMGUI_DISABLE_OBSOLETE_KEYIO (this is the way forward): any use of ImGuiKey will assert with key < 512. GetKeyIndex() is pass-through and therefore deprecated (gone if IMGUI_DISABLE_OBSOLETE_KEYIO is defined).
+    // - (legacy: before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. This was obsoleted in 1.87 (2022-02) and completely removed in 1.91.5 (2024-11). See https://github.com/ocornut/imgui/issues/4921)
+    // - (legacy: any use of ImGuiKey will assert when key < 512 to detect passing legacy native/user indices)
     IMGUI_API bool          IsKeyDown(ImGuiKey key);                                            // is key being held.
     IMGUI_API bool          IsKeyPressed(ImGuiKey key, bool repeat = true);                     // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
     IMGUI_API bool          IsKeyReleased(ImGuiKey key);                                        // was key released (went from Down to !Down)?
@@ -1415,15 +1414,10 @@ enum ImGuiSortDirection : ImU8
     ImGuiSortDirection_Descending   = 2     // Descending = 9->0, Z->A etc.
 };
 
-// Since 1.90, defining IMGUI_DISABLE_OBSOLETE_FUNCTIONS automatically defines IMGUI_DISABLE_OBSOLETE_KEYIO as well.
-#if defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(IMGUI_DISABLE_OBSOLETE_KEYIO)
-#define IMGUI_DISABLE_OBSOLETE_KEYIO
-#endif
-
 // A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value): can represent Keyboard, Mouse and Gamepad values.
-// All our named keys are >= 512. Keys value 0 to 511 are left unused as legacy native/opaque key values (< 1.87).
-// Since >= 1.89 we increased typing (went from int to enum), some legacy code may need a cast to ImGuiKey.
-// Read details about the 1.87 and 1.89 transition : https://github.com/ocornut/imgui/issues/4921
+// All our named keys are >= 512. Keys value 0 to 511 are left unused and were legacy native/opaque key values (< 1.87).
+// Support for legacy keys was completely removed in 1.91.5.
+// Read details about the 1.87+ transition : https://github.com/ocornut/imgui/issues/4921
 // Note that "Keys" related to physical keys and are not the same concept as input "Characters", the later are submitted via io.AddInputCharacter().
 // The keyboard key enum values are named after the keys on a standard US keyboard, and on other keyboard types the keys reported may not match the keycaps.
 enum ImGuiKey : int
@@ -1535,19 +1529,12 @@ enum ImGuiKey : int
     ImGuiMod_Super                  = 1 << 15, // Windows/Super (non-macOS), Ctrl (macOS)
     ImGuiMod_Mask_                  = 0xF000,  // 4-bits
 
-    // [Internal] Prior to 1.87 we required user to fill io.KeysDown[512] using their own native index + the io.KeyMap[] array.
-    // We are ditching this method but keeping a legacy path for user code doing e.g. IsKeyPressed(MY_NATIVE_KEY_CODE)
-    // If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END.
+    // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END.
     ImGuiKey_NamedKey_BEGIN         = 512,
     ImGuiKey_NamedKey_END           = ImGuiKey_COUNT,
     ImGuiKey_NamedKey_COUNT         = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN,
-#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
     ImGuiKey_KeysData_SIZE          = ImGuiKey_NamedKey_COUNT,  // Size of KeysData[]: only hold named keys
     ImGuiKey_KeysData_OFFSET        = ImGuiKey_NamedKey_BEGIN,  // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index.
-#else
-    ImGuiKey_KeysData_SIZE          = ImGuiKey_COUNT,           // Size of KeysData[]: hold legacy 0..512 keycodes + named keys
-    ImGuiKey_KeysData_OFFSET        = 0,                        // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index.
-#endif
 
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
     ImGuiMod_Shortcut               = ImGuiMod_Ctrl,            // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl
@@ -1581,18 +1568,6 @@ enum ImGuiInputFlags_
     ImGuiInputFlags_Tooltip                 = 1 << 18,  // Automatically display a tooltip when hovering item [BETA] Unsure of right api (opt-in/opt-out)
 };
 
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-// OBSOLETED in 1.88 (from July 2022): ImGuiNavInput and io.NavInputs[].
-// Official backends between 1.60 and 1.86: will keep working and feed gamepad inputs as long as IMGUI_DISABLE_OBSOLETE_KEYIO is not set.
-// Custom backends: feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums.
-enum ImGuiNavInput
-{
-    ImGuiNavInput_Activate, ImGuiNavInput_Cancel, ImGuiNavInput_Input, ImGuiNavInput_Menu, ImGuiNavInput_DpadLeft, ImGuiNavInput_DpadRight, ImGuiNavInput_DpadUp, ImGuiNavInput_DpadDown,
-    ImGuiNavInput_LStickLeft, ImGuiNavInput_LStickRight, ImGuiNavInput_LStickUp, ImGuiNavInput_LStickDown, ImGuiNavInput_FocusPrev, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakSlow, ImGuiNavInput_TweakFast,
-    ImGuiNavInput_COUNT,
-};
-#endif
-
 // Configuration flags stored in io.ConfigFlags. Set by user/application.
 enum ImGuiConfigFlags_
 {
@@ -2425,20 +2400,18 @@ struct ImGuiIO
     float       PenPressure;                        // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui.
     bool        AppFocusLost;                       // Only modify via AddFocusEvent()
     bool        AppAcceptingEvents;                 // Only modify via SetAppAcceptingEvents()
-    ImS8        BackendUsingLegacyKeyArrays;        // -1: unknown, 0: using AddKeyEvent(), 1: using legacy io.KeysDown[]
-    bool        BackendUsingLegacyNavInputArray;    // 0: using AddKeyAnalogEvent(), 1: writing to legacy io.NavInputs[] directly
     ImWchar16   InputQueueSurrogate;                // For AddInputCharacterUTF16()
     ImVector InputQueueCharacters;         // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper.
 
     // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame.
     // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent().
     //   Old (<1.87):  ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Space]) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space)
-#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
-    int         KeyMap[ImGuiKey_COUNT];             // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512.
-    bool        KeysDown[ImGuiKey_COUNT];           // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow.
-    float       NavInputs[ImGuiNavInput_COUNT];     // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums.
+    //   Old (<1.87):  ImGui::IsKeyPressed(MYPLATFORM_KEY_SPACE)                  --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space)
+    // Read https://github.com/ocornut/imgui/issues/4921 for details.
+    //int       KeyMap[ImGuiKey_COUNT];             // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512.
+    //bool      KeysDown[ImGuiKey_COUNT];           // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow.
+    //float     NavInputs[ImGuiNavInput_COUNT];     // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums.
     //void*     ImeWindowHandle;                    // [Obsoleted in 1.87] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning.
-#endif
 
     // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO.
     // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete).
@@ -3617,9 +3590,6 @@ namespace ImGui
     // OBSOLETED in 1.89.4 (from March 2023)
     static inline void  PushAllowKeyboardFocus(bool tab_stop)                   { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); }
     static inline void  PopAllowKeyboardFocus()                                 { PopItemFlag(); }
-    // OBSOLETED in 1.87 (from February 2022 but more formally obsoleted April 2024)
-    IMGUI_API ImGuiKey  GetKeyIndex(ImGuiKey key);                              // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value!
-    //static inline ImGuiKey GetKeyIndex(ImGuiKey key)                          { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; }
 
     // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE)
     //-- OBSOLETED in 1.89 (from August 2022)
@@ -3627,6 +3597,9 @@ namespace ImGui
     //-- OBSOLETED in 1.88 (from May 2022)
     //static inline void  CaptureKeyboardFromApp(bool want_capture_keyboard = true)                   { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value.
     //static inline void  CaptureMouseFromApp(bool want_capture_mouse = true)                         { SetNextFrameWantCaptureMouse(want_capture_mouse); }       // Renamed as name was misleading + removed default value.
+    //-- OBSOLETED in 1.87 (from February 2022, more formally obsoleted April 2024)
+    //IMGUI_API ImGuiKey  GetKeyIndex(ImGuiKey key);                                                  { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); const ImGuiKeyData* key_data = GetKeyData(key); return (ImGuiKey)(key_data - g.IO.KeysData); } // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value!
+    //static inline ImGuiKey GetKeyIndex(ImGuiKey key)                                                { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; }
     //-- OBSOLETED in 1.86 (from November 2021)
     //IMGUI_API void      CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Code removed, see 1.90 for last version of the code. Calculate range of visible items for large list of evenly sized items. Prefer using ImGuiListClipper.
     //-- OBSOLETED in 1.85 (from August 2021)
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index f5e16f06c..e28ca3b7a 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -7370,13 +7370,8 @@ static void ShowDemoWindowInputs()
             // displaying the data for old/new backends.
             // User code should never have to go through such hoops!
             // You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
-#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
             struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
             ImGuiKey start_key = ImGuiKey_NamedKey_BEGIN;
-#else
-            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && ImGui::GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
-            ImGuiKey start_key = (ImGuiKey)0;
-#endif
             ImGui::Text("Keys down:");         for (ImGuiKey key = start_key; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !ImGui::IsKeyDown(key)) continue; ImGui::SameLine(); ImGui::Text((key < ImGuiKey_NamedKey_BEGIN) ? "\"%s\"" : "\"%s\" %d", ImGui::GetKeyName(key), key); }
             ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
             ImGui::Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine();  ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
@@ -7699,9 +7694,6 @@ void ImGui::ShowAboutWindow(bool* p_open)
 #ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
         ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS");
 #endif
-#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
-        ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_KEYIO");
-#endif
 #ifdef IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
         ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS");
 #endif

From 738d6db3e6b9b28284aa1026dbf082238d9c9aab Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 6 Nov 2024 17:42:02 +0100
Subject: [PATCH 0484/2359] (Breaking) Removed used of ImGuiKey_KeysData_SIZE,
 ImGuiKey_KeysData_OFFSET. (#4921)

---
 imgui.cpp | 39 ++++++++++++++++++++-------------------
 imgui.h   |  6 +++---
 2 files changed, 23 insertions(+), 22 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 74da7355e..028f08c3c 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1541,13 +1541,15 @@ void ImGuiIO::ClearEventsQueue()
 // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
 void ImGuiIO::ClearInputKeys()
 {
-    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
+    ImGuiContext& g = *Ctx;
+    for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
     {
-        if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
+        if (ImGui::IsMouseKey((ImGuiKey)key))
             continue;
-        KeysData[n].Down             = false;
-        KeysData[n].DownDuration     = -1.0f;
-        KeysData[n].DownDurationPrev = -1.0f;
+        ImGuiKeyData* key_data = &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
+        key_data->Down = false;
+        key_data->DownDuration = -1.0f;
+        key_data->DownDurationPrev = -1.0f;
     }
     KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
     KeyMods = ImGuiMod_None;
@@ -1558,7 +1560,7 @@ void ImGuiIO::ClearInputMouse()
 {
     for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
     {
-        ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET];
+        ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_NamedKey_BEGIN];
         key_data->Down = false;
         key_data->DownDuration = -1.0f;
         key_data->DownDurationPrev = -1.0f;
@@ -8908,7 +8910,7 @@ ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
         key = ConvertSingleModFlagToKey(key);
 
     IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
-    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
+    return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN];
 }
 
 // Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
@@ -9609,22 +9611,21 @@ static void ImGui::UpdateKeyboardInputs()
 
     // Clear gamepad data if disabled
     if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
-        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
+        for (int key = ImGuiKey_Gamepad_BEGIN; key < ImGuiKey_Gamepad_END; key++)
         {
-            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
-            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
+            io.KeysData[key - ImGuiKey_NamedKey_BEGIN].Down = false;
+            io.KeysData[key - ImGuiKey_NamedKey_BEGIN].AnalogValue = 0.0f;
         }
 
     // Update keys
-    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
+    for (int key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key++)
     {
-        ImGuiKeyData* key_data = &io.KeysData[i];
+        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
         key_data->DownDurationPrev = key_data->DownDuration;
         key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
         if (key_data->DownDuration == 0.0f)
         {
-            ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
-            if (IsKeyboardKey(key))
+            if (IsKeyboardKey((ImGuiKey)key))
                 g.LastKeyboardKeyPressTime = g.Time;
             else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
                 g.LastKeyboardKeyPressTime = g.Time;
@@ -9634,7 +9635,7 @@ static void ImGui::UpdateKeyboardInputs()
     // Update keys/input owner (named keys only): one entry per key
     for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
     {
-        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
+        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_NamedKey_BEGIN];
         ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
         owner_data->OwnerCurr = owner_data->OwnerNext;
         if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
@@ -9920,7 +9921,7 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
 
     bool mouse_moved = false, mouse_wheeled = false, key_changed = false, key_changed_nonchar = false, text_inputted = false;
     int  mouse_button_changed = 0x00;
-    ImBitArray key_changed_mask;
+    ImBitArray key_changed_mask;
 
     int event_n = 0;
     for (; event_n < g.InputEventsQueue.Size; event_n++)
@@ -15602,9 +15603,9 @@ void ImGui::ShowMetricsWindow(bool* p_open)
         {
             // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
             Indent();
-            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
-            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
-            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
+            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
+            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
+            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
             Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
             Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
             DebugRenderKeyboardPreview(GetWindowDrawList());
diff --git a/imgui.h b/imgui.h
index 824cea059..6965c5e6b 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1533,8 +1533,8 @@ enum ImGuiKey : int
     ImGuiKey_NamedKey_BEGIN         = 512,
     ImGuiKey_NamedKey_END           = ImGuiKey_COUNT,
     ImGuiKey_NamedKey_COUNT         = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN,
-    ImGuiKey_KeysData_SIZE          = ImGuiKey_NamedKey_COUNT,  // Size of KeysData[]: only hold named keys
-    ImGuiKey_KeysData_OFFSET        = ImGuiKey_NamedKey_BEGIN,  // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index.
+    //ImGuiKey_KeysData_SIZE        = ImGuiKey_NamedKey_COUNT,  // Size of KeysData[]: only hold named keys
+    //ImGuiKey_KeysData_OFFSET      = ImGuiKey_NamedKey_BEGIN,  // Accesses to io.KeysData[] must use (key - ImGuiKey_NamedKey_BEGIN) index.
 
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
     ImGuiMod_Shortcut               = ImGuiMod_Ctrl,            // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl
@@ -2380,7 +2380,7 @@ struct ImGuiIO
 
     // Other state maintained from data above + IO function calls
     ImGuiKeyChord KeyMods;                          // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. Read-only, updated by NewFrame()
-    ImGuiKeyData  KeysData[ImGuiKey_KeysData_SIZE]; // Key state for all known keys. Use IsKeyXXX() functions to access this.
+    ImGuiKeyData  KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. Use IsKeyXXX() functions to access this.
     bool        WantCaptureMouseUnlessPopupClose;   // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup.
     ImVec2      MousePosPrev;                       // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid)
     ImVec2      MouseClickedPos[5];                 // Position at time of clicking

From df0776e931d2be6efe5d8a6e465b97851b23c9d5 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 6 Nov 2024 17:49:52 +0100
Subject: [PATCH 0485/2359] (Breaking) Removed ImGuiKey_COUNT. (#4921)

---
 docs/CHANGELOG.txt | 2 ++
 imgui.cpp          | 1 +
 imgui.h            | 7 ++++---
 3 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 603828c39..1e8016a13 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -52,6 +52,8 @@ Breaking changes:
     - read https://github.com/ocornut/imgui/issues/4921
   - If you have trouble updating a very old codebase using legacy backend-specific key codes:
     consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
+  - Obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0).
+    Probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END?
 
 Other changes:
 
diff --git a/imgui.cpp b/imgui.cpp
index 028f08c3c..7f853fa0f 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -439,6 +439,7 @@ CODE
                               - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
                               - read https://github.com/ocornut/imgui/issues/4921
                             - if you have trouble updating a very old codebase using legacy backend-specific key codes: consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
+                       - obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0). probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END?
  - 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete).
  - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
                          moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).
diff --git a/imgui.h b/imgui.h
index 6965c5e6b..ec3d6c0a7 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1424,6 +1424,8 @@ enum ImGuiKey : int
 {
     // Keyboard
     ImGuiKey_None = 0,
+    ImGuiKey_NamedKey_BEGIN = 512,  // First valid key value (other than 0)
+
     ImGuiKey_Tab = 512,             // == ImGuiKey_NamedKey_BEGIN
     ImGuiKey_LeftArrow,
     ImGuiKey_RightArrow,
@@ -1511,7 +1513,7 @@ enum ImGuiKey : int
 
     // [Internal] Reserved for mod storage
     ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper,
-    ImGuiKey_COUNT,
+    ImGuiKey_NamedKey_END,
 
     // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls)
     // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing
@@ -1530,13 +1532,12 @@ enum ImGuiKey : int
     ImGuiMod_Mask_                  = 0xF000,  // 4-bits
 
     // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END.
-    ImGuiKey_NamedKey_BEGIN         = 512,
-    ImGuiKey_NamedKey_END           = ImGuiKey_COUNT,
     ImGuiKey_NamedKey_COUNT         = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN,
     //ImGuiKey_KeysData_SIZE        = ImGuiKey_NamedKey_COUNT,  // Size of KeysData[]: only hold named keys
     //ImGuiKey_KeysData_OFFSET      = ImGuiKey_NamedKey_BEGIN,  // Accesses to io.KeysData[] must use (key - ImGuiKey_NamedKey_BEGIN) index.
 
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+    ImGuiKey_COUNT                  = ImGuiKey_NamedKey_END,    // Obsoleted in 1.91.5 because it was extremely misleading (since named keys don't start at 0 anymore)
     ImGuiMod_Shortcut               = ImGuiMod_Ctrl,            // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl
     ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89
     //ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter,              // Renamed in 1.87

From d97bbf19042c8addf7098978609de20fef9978e6 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 6 Nov 2024 18:08:15 +0100
Subject: [PATCH 0486/2359] Tabs, Style: made
 ImGuiCol_TabDimmedSelectedOverline alpha 0 (not visible) in default styles.

---
 docs/CHANGELOG.txt | 2 ++
 imgui_draw.cpp     | 6 +++---
 2 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 1e8016a13..abf339421 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -64,6 +64,8 @@ Other changes:
 - Fonts: removed const qualifiers from most font functions.
 - InputText: fixed a bug (regression in 1.91.2) where modifying text buffer within
   a callback would sometimes prevents further appending to the buffer.
+- Tabs, Style: made ImGuiCol_TabDimmedSelectedOverline alpha 0 (not visible) in default
+  styles as the current look is not right (but ImGuiCol_TabSelectedOverline stays the same).
 - Log/Capture: better decorating of BeginMenu() and TabItem() output.
 - Log/Capture: a non terminated log ends automatically in the window which called it.
 - Log/Capture: added experimental io.ConfigWindowsCopyContentsWithCtrlC option to
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index ac6d02281..43a49eb29 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -218,7 +218,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst)
     colors[ImGuiCol_TabSelectedOverline]    = colors[ImGuiCol_HeaderActive];
     colors[ImGuiCol_TabDimmed]              = ImLerp(colors[ImGuiCol_Tab],          colors[ImGuiCol_TitleBg], 0.80f);
     colors[ImGuiCol_TabDimmedSelected]      = ImLerp(colors[ImGuiCol_TabSelected],  colors[ImGuiCol_TitleBg], 0.40f);
-    colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
+    colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.50f, 0.50f, 0.50f, 0.00f);
     colors[ImGuiCol_PlotLines]              = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
     colors[ImGuiCol_PlotLinesHovered]       = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
     colors[ImGuiCol_PlotHistogram]          = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
@@ -281,7 +281,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst)
     colors[ImGuiCol_TabSelectedOverline]    = colors[ImGuiCol_HeaderActive];
     colors[ImGuiCol_TabDimmed]              = ImLerp(colors[ImGuiCol_Tab],          colors[ImGuiCol_TitleBg], 0.80f);
     colors[ImGuiCol_TabDimmedSelected]      = ImLerp(colors[ImGuiCol_TabSelected],  colors[ImGuiCol_TitleBg], 0.40f);
-    colors[ImGuiCol_TabDimmedSelectedOverline] = colors[ImGuiCol_HeaderActive];
+    colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.53f, 0.53f, 0.87f, 0.00f);
     colors[ImGuiCol_PlotLines]              = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
     colors[ImGuiCol_PlotLinesHovered]       = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
     colors[ImGuiCol_PlotHistogram]          = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
@@ -345,7 +345,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst)
     colors[ImGuiCol_TabSelectedOverline]    = colors[ImGuiCol_HeaderActive];
     colors[ImGuiCol_TabDimmed]              = ImLerp(colors[ImGuiCol_Tab],          colors[ImGuiCol_TitleBg], 0.80f);
     colors[ImGuiCol_TabDimmedSelected]      = ImLerp(colors[ImGuiCol_TabSelected],  colors[ImGuiCol_TitleBg], 0.40f);
-    colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.26f, 0.59f, 1.00f, 1.00f);
+    colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.26f, 0.59f, 1.00f, 0.00f);
     colors[ImGuiCol_PlotLines]              = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
     colors[ImGuiCol_PlotLinesHovered]       = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
     colors[ImGuiCol_PlotHistogram]          = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);

From 3543dfda953beefd9add1316328e2c7cfb4aa637 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 6 Nov 2024 18:14:44 +0100
Subject: [PATCH 0487/2359] Docs: document removal of ImFont const qualifier as
 potentially breaking.

---
 docs/CHANGELOG.txt | 34 +++++++++++++++++-----------------
 imgui.cpp          |  1 +
 2 files changed, 18 insertions(+), 17 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index abf339421..ebc128a04 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -54,6 +54,7 @@ Breaking changes:
     consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
   - Obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0).
     Probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END?
+- Fonts: removed const qualifiers from most font functions in prevision for upcoming fonts improvements.
 
 Other changes:
 
@@ -61,7 +62,6 @@ Other changes:
   between _Header and _HeaderHovered which was introduced v1.91 (#8106, #1861)
 - Buttons: using ImGuiItemFlags_ButtonRepeat makes default button behavior use
   PressedOnClick instead of PressedOnClickRelease when unspecified.
-- Fonts: removed const qualifiers from most font functions.
 - InputText: fixed a bug (regression in 1.91.2) where modifying text buffer within
   a callback would sometimes prevents further appending to the buffer.
 - Tabs, Style: made ImGuiCol_TabDimmedSelectedOverline alpha 0 (not visible) in default
@@ -74,9 +74,9 @@ Other changes:
   and (3) text output comes in submission order rather than spatial order.
 - Backends: DX12: Unmap() call specify written range. The range is informational and
   may be used by debug tools.
-- Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the 
-  actual include. (#8095, #7967, #3190) [@sev-] 
-- Backends: SDL2, SDL3: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing 
+- Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the
+  actual include. (#8095, #7967, #3190) [@sev-]
+- Backends: SDL2, SDL3: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing
   by 100.0f on Emscripten target. (#4019, #6096, #1463)
 - Examples: SDL3+Vulkan: Added example. (#8084, #8085)
 - Examples: Android+OpenGL: Using ALooper_pollOnce() instead of ALooper_pollAll()
@@ -88,7 +88,7 @@ Other changes:
 
 Breaking changes:
 
-- Style: renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor, for consistency with 
+- Style: renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor, for consistency with
   newly exposed and reworked features. Kept inline redirection enum (will obsolete).
 - The typedef for ImTextureID now defaults to ImU64 instead of void*. (#1641)
   - This removes the requirement to redefine it for backends which are e.g. storing
@@ -104,9 +104,9 @@ Breaking changes:
   - Note that you can always define ImTextureID to be your own high-level structures
     (with dedicated constructors and extra render parameters) if you like.
 - IO: moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
-- IO: moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool 
+- IO: moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool
   (note the inverted value!). (#2517, #2009)
-  Kept legacy names (will obsolete) + code that copies settings once the first time. 
+  Kept legacy names (will obsolete) + code that copies settings once the first time.
   Dynamically changing the old value won't work. Switch to using the new value!
 
 Other changes:
@@ -122,48 +122,48 @@ Other changes:
      - Set io.ConfigNavCursorVisibleAuto = true (default) to enable automatic toggling
        of cursor visibility (mouse click hide the cursor, arrow keys makes it visible).
      - Set io.ConfigNavCursorVisibleAlways to keep cursor always visible.
-  - Nav: added NavSetCursorVisible(bool visible) function to manipulate visibility of 
+  - Nav: added NavSetCursorVisible(bool visible) function to manipulate visibility of
     navigation cursor (e.g. set default state, or after some actions). (#1074, #2048, #7237, #8059)
   - Nav: added io.ConfigNavEscapeClearFocusItem and io.ConfigNavEscapeClearFocusWindow to change
     how pressing Escape affects navigation. (#8059, #2048, #1074, #3200)
     - Set io.ConfigNavEscapeClearFocusItem = true (default) to clear focused item and highlight.
     - Set io.ConfigNavEscapeClearFocusItem = false for Escape to not have an effect.
     - Set io.ConfigNavEscapeClearFocusWindow = true to completely unfocus the dear imgui window,
-      is for some reason your app relies on imgui focus to take other decisions.  
+      is for some reason your app relies on imgui focus to take other decisions.
   - Nav: pressing escape to hide the navigation cursor doesn't clear location, so it may be
     restored when Ctrl+Tabbing back into the same window later.
   - Nav: fixed Ctrl+Tab initiated with no focused window from skipping the top-most window. (#3200)
-  - Nav: navigation cursor is not rendered for items with `ImGuiItemFlags_NoNav`. Can be relevant 
+  - Nav: navigation cursor is not rendered for items with `ImGuiItemFlags_NoNav`. Can be relevant
     when e.g activating a _NoNav item with mouse, then Ctrl+Tabbing back and forth.
-- Disabled: clicking a disabled item focuses parent window. (#8064) 
+- Disabled: clicking a disabled item focuses parent window. (#8064)
 - InvisibleButton, Nav: fixed an issue when InvisibleButton() would be navigable into but
   not display navigation highlight. Properly navigation on it by default. (#8057)
 - InvisibleButton: added ImGuiButtonFlags_EnableNav to enable navigation. (#8057)
-- Tooltips: fixed incorrect tooltip positioning when using keyboard/gamepad navigation 
+- Tooltips: fixed incorrect tooltip positioning when using keyboard/gamepad navigation
   (1.91.3 regression). (#8036)
 - DrawList: AddCallback() added an optional size parameter allowing to copy and
   store any amount of user data for usage by callbacks: (#6969, #4770, #7665)
   - If userdata_size == 0: we copy/store the 'userdata' argument as-is (existing behavior).
     It will be available unmodified in ImDrawCmd::UserCallbackData during render.
   - If userdata_size > 0, we copy/store 'userdata_size' bytes pointed to by 'userdata' (new behavior).
-    We store them in a buffer stored inside the drawlist. ImDrawCmd::UserCallbackData 
+    We store them in a buffer stored inside the drawlist. ImDrawCmd::UserCallbackData
     will point inside that buffer so you have to retrieve data from there. Your callback
     may need to use ImDrawCmd::UserCallbackDataSize if you expect dynamically-sized data.
   - Note that we use a raw type-less copy.
 - Tables: fixed initial auto-sizing issue with synced-instances. (#8045, #7218)
 - InputText: fixed an issue with not declaring ownership of Delete/Backspace/Arrow keys,
-  preventing use of external shortcuts that are not guarded by an ActiveId check. (#8048) 
+  preventing use of external shortcuts that are not guarded by an ActiveId check. (#8048)
   [@geertbleyen]
-- InputText: ensure mouse cursor shape is set regardless of whether keyboard mode is 
+- InputText: ensure mouse cursor shape is set regardless of whether keyboard mode is
   enabled or not. (#6417)
 - InputScalar: added an assert to clarify that ImGuiInputTextFlags_EnterReturnsTrue is not
   supported by InputFloat, InputInt, InputScalar etc. widgets. It actually never was. (#8065, #3946)
-- imgui_freetype: Added support for plutosvg (as an alternative to lunasvg) to render 
+- imgui_freetype: Added support for plutosvg (as an alternative to lunasvg) to render
   OpenType SVG fonts. Requires defining IMGUI_ENABLE_FREETYPE_PLUTOSVG along with IMGUI_ENABLE_FREETYPE.
   Providing headers/librairies for plutosvg + plutovg is up to you (see #7927 for help).
   (#7927, #7187, #6591, #6607) [@pthom]
 - Backends: DX11, DX12, SDLRenderer2/3. Vulkan, WGPU: expose selected state in
-  ImGui_ImplXXXX_RenderState structures during render loop user draw callbacks. 
+  ImGui_ImplXXXX_RenderState structures during render loop user draw callbacks.
   (#6969, #5834, #7468, #3590)
 - Backends: DX9, DX10, DX11, DX12, OpenGL, Vulkan, WGPU: Changed default texture sampler
   to Clamp instead of Repeat/Wrap. (#7468, #7511, #5999, #5502, #7230)
diff --git a/imgui.cpp b/imgui.cpp
index 7f853fa0f..1f2dbc09a 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -440,6 +440,7 @@ CODE
                               - read https://github.com/ocornut/imgui/issues/4921
                             - if you have trouble updating a very old codebase using legacy backend-specific key codes: consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
                        - obsoleted ImGuiKey_COUNT (it is unusually error-prone/misleading since valid keys don't start at 0). probably use ImGuiKey_NamedKey_BEGIN/ImGuiKey_NamedKey_END?
+                       - fonts: removed const qualifiers from most font functions in prevision for upcoming font improvements.
  - 2024/10/18 (1.91.4) - renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor (for consistency with newly exposed and reworked features). Kept inline redirection enum (will obsolete).
  - 2024/10/14 (1.91.4) - moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool.
                          moved ImGuiConfigFlags_NavNoCaptureKeyboard to standalone io.ConfigNavCaptureKeyboard bool (note the inverted value!).

From 3b683927ee623d010725c7664cd4e2c4ac20085c Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 7 Nov 2024 14:39:54 +0100
Subject: [PATCH 0488/2359] imgui_freetype: Fixed a crash in build font atlas
 when using merged fonts and the first font in a merged set has no loaded
 glyph. (#8081)

---
 docs/CHANGELOG.txt               | 2 ++
 misc/freetype/imgui_freetype.cpp | 5 +++--
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index ebc128a04..a1655fdab 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -72,6 +72,8 @@ Other changes:
   automatically copy window contents into clipboard using CTRL+C. This is experimental
   because (1) it currently breaks on nested Begin/End, (2) text output quality varies,
   and (3) text output comes in submission order rather than spatial order.
+- imgui_freetype: Fixed a crash in build font atlas when using merged fonts and the
+  first font in a merged set has no loaded glyph. (#8081)
 - Backends: DX12: Unmap() call specify written range. The range is informational and
   may be used by debug tools.
 - Backends: SDL2: Replace SDL_Vulkan_GetDrawableSize() forward declaration with the
diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp
index 646a3b14e..c2d5f074c 100644
--- a/misc/freetype/imgui_freetype.cpp
+++ b/misc/freetype/imgui_freetype.cpp
@@ -681,8 +681,6 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u
     for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
     {
         ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
-        if (src_tmp.GlyphsCount == 0)
-            continue;
 
         // When merging fonts with MergeMode=true:
         // - We can have multiple input fonts writing into a same destination font.
@@ -693,6 +691,9 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u
         const float ascent = src_tmp.Font.Info.Ascender;
         const float descent = src_tmp.Font.Info.Descender;
         ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
+
+        if (src_tmp.GlyphsCount == 0)
+            continue;
         const float font_off_x = cfg.GlyphOffset.x;
         const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
 

From 17bd417a3d18610dbdaba4b56296bdcf87c7cbbf Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 7 Nov 2024 14:57:16 +0100
Subject: [PATCH 0489/2359] AddCustomRectFontGlyph: added storage for Colored
 bool in ImFontAtlasCustomRect. (#8133)

---
 imgui.h        | 5 +++--
 imgui_draw.cpp | 3 +++
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/imgui.h b/imgui.h
index ec3d6c0a7..de6ec7b1c 100644
--- a/imgui.h
+++ b/imgui.h
@@ -3278,11 +3278,12 @@ struct ImFontAtlasCustomRect
 {
     unsigned short  Width, Height;  // Input    // Desired rectangle dimension
     unsigned short  X, Y;           // Output   // Packed position in Atlas
-    unsigned int    GlyphID;        // Input    // For custom font glyphs only (ID < 0x110000)
+    unsigned int    GlyphID : 31;   // Input    // For custom font glyphs only (ID < 0x110000)
+    unsigned int    GlyphColored : 1; // Input  // For custom font glyphs only: glyph is colored, removed tinting.
     float           GlyphAdvanceX;  // Input    // For custom font glyphs only: glyph xadvance
     ImVec2          GlyphOffset;    // Input    // For custom font glyphs only: glyph display offset
     ImFont*         Font;           // Input    // For custom font glyphs only: target font
-    ImFontAtlasCustomRect()         { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; }
+    ImFontAtlasCustomRect()         { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; }
     bool IsPacked() const           { return X != 0xFFFF; }
 };
 
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 43a49eb29..c0a5b5b75 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -2676,6 +2676,7 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int
     r.Width = (unsigned short)width;
     r.Height = (unsigned short)height;
     r.GlyphID = id;
+    r.GlyphColored = 0; // Set to 1 manually to mark glyph as colored // FIXME: No official API for that (#8133)
     r.GlyphAdvanceX = advance_x;
     r.GlyphOffset = offset;
     r.Font = font;
@@ -3286,6 +3287,8 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
         ImVec2 uv0, uv1;
         atlas->CalcCustomRectUV(r, &uv0, &uv1);
         r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX);
+        if (r->GlyphColored)
+            r->Font->Glyphs.back().Colored = 1;
     }
 
     // Build all fonts lookup tables

From 419a9ada16eb9b6d84ead4911b9c2a32820cfffb Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 7 Nov 2024 19:08:37 +0100
Subject: [PATCH 0490/2359] Ignore clang warning Wnontrivial-memaccess (#8129,
 #8135)

Amend 88e2327
Use void* cast in backend where the memset are infrequent.
---
 backends/imgui_impl_metal.mm   | 9 +--------
 backends/imgui_impl_osx.mm     | 9 +--------
 backends/imgui_impl_vulkan.cpp | 6 +++---
 imgui.cpp                      | 1 +
 imgui.h                        | 1 +
 imgui_tables.cpp               | 1 +
 imgui_widgets.cpp              | 1 +
 7 files changed, 9 insertions(+), 19 deletions(-)

diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm
index 102f6982a..12dc3d50f 100644
--- a/backends/imgui_impl_metal.mm
+++ b/backends/imgui_impl_metal.mm
@@ -38,13 +38,6 @@
 #import 
 #import 
 
-#if defined(__clang__)
-#if __has_warning("-Wunknown-warning-option")
-#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'
-#endif
-#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
-#endif
-
 #pragma mark - Support classes
 
 // A wrapper around a MTLBuffer object that knows the last time it was reused
@@ -83,7 +76,7 @@ struct ImGui_ImplMetal_Data
 {
     MetalContext*               SharedMetalContext;
 
-    ImGui_ImplMetal_Data()      { memset(this, 0, sizeof(*this)); }
+    ImGui_ImplMetal_Data()      { memset((void*)this, 0, sizeof(*this)); }
 };
 
 static ImGui_ImplMetal_Data*    ImGui_ImplMetal_GetBackendData()    { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; }
diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm
index 69108ca4a..c99ba1f06 100644
--- a/backends/imgui_impl_osx.mm
+++ b/backends/imgui_impl_osx.mm
@@ -27,13 +27,6 @@
 #import 
 #import 
 
-#if defined(__clang__)
-#if __has_warning("-Wunknown-warning-option")
-#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'
-#endif
-#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
-#endif
-
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
 //  2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
@@ -94,7 +87,7 @@ struct ImGui_ImplOSX_Data
     id                          Monitor;
     NSWindow*                   Window;
 
-    ImGui_ImplOSX_Data()        { memset(this, 0, sizeof(*this)); }
+    ImGui_ImplOSX_Data()        { memset((void*)this, 0, sizeof(*this)); }
 };
 
 static ImGui_ImplOSX_Data*      ImGui_ImplOSX_GetBackendData()      { return (ImGui_ImplOSX_Data*)ImGui::GetIO().BackendPlatformUserData; }
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 4e4e332fc..d499ecb92 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -489,7 +489,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
         wrb->Index = 0;
         wrb->Count = v->ImageCount;
         wrb->FrameRenderBuffers = (ImGui_ImplVulkan_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count);
-        memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count);
+        memset((void*)wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count);
     }
     IM_ASSERT(wrb->Count == v->ImageCount);
     wrb->Index = (wrb->Index + 1) % wrb->Count;
@@ -1445,8 +1445,8 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V
         wd->SemaphoreCount = wd->ImageCount + 1;
         wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount);
         wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->SemaphoreCount);
-        memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount);
-        memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->SemaphoreCount);
+        memset((void*)wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount);
+        memset((void*)wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->SemaphoreCount);
         for (uint32_t i = 0; i < wd->ImageCount; i++)
             wd->Frames[i].Backbuffer = backbuffers[i];
     }
diff --git a/imgui.cpp b/imgui.cpp
index 1f2dbc09a..2ea9417b4 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1135,6 +1135,7 @@ CODE
 #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.
 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #elif defined(__GNUC__)
 // We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
 #pragma GCC diagnostic ignored "-Wpragmas"                          // warning: unknown option after '#pragma GCC diagnostic' kind
diff --git a/imgui.h b/imgui.h
index de6ec7b1c..32425db89 100644
--- a/imgui.h
+++ b/imgui.h
@@ -135,6 +135,7 @@ Index of this file:
 #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
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #elif defined(__GNUC__)
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wpragmas"                          // warning: unknown option after '#pragma GCC diagnostic' kind
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 03007bb79..122cd87b1 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -229,6 +229,7 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #elif defined(__GNUC__)
 #pragma GCC diagnostic ignored "-Wpragmas"                          // warning: unknown option after '#pragma GCC diagnostic' kind
 #pragma GCC diagnostic ignored "-Wformat-nonliteral"                // warning: format not a string literal, format string not checked
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 9d5724222..bb445d977 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -79,6 +79,7 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
+#pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #elif defined(__GNUC__)
 #pragma GCC diagnostic ignored "-Wpragmas"                          // warning: unknown option after '#pragma GCC diagnostic' kind
 #pragma GCC diagnostic ignored "-Wformat-nonliteral"                // warning: format not a string literal, format string not checked

From 01d27a4acde14c13e86adfcd0569e752f181e205 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 7 Nov 2024 16:58:50 +0100
Subject: [PATCH 0491/2359] Internals: added IM_LIKELY(), IM_UNLIKELY() helper
 macros (yet unused). Added ImFontGetCharAdvanceX() macro.

---
 imgui_draw.cpp   | 16 +++++++++-------
 imgui_internal.h |  9 +++++++++
 2 files changed, 18 insertions(+), 7 deletions(-)

diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index c0a5b5b75..7934949ec 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -3847,7 +3847,7 @@ const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c)
     return &Glyphs.Data[i];
 }
 
-// Wrapping skips upcoming blanks
+// Trim trailing space and find beginning of next line
 static inline const char* CalcWordWrapNextLineStartA(const char* text, const char* text_end)
 {
     while (text < text_end && ImCharIsBlankA(*text))
@@ -3857,6 +3857,8 @@ static inline const char* CalcWordWrapNextLineStartA(const char* text, const cha
     return text;
 }
 
+#define ImFontGetCharAdvanceX(_FONT, _CH)  ((int)(_CH) < (_FONT)->IndexAdvanceX.Size ? (_FONT)->IndexAdvanceX.Data[_CH] : (_FONT)->FallbackAdvanceX)
+
 // 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.
 // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.)
@@ -3909,7 +3911,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
             }
         }
 
-        const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX);
+        const float char_width = ImFontGetCharAdvanceX(this, c);
         if (ImCharIsBlankW(c))
         {
             if (inside_word)
@@ -4014,7 +4016,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
                 continue;
         }
 
-        const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX) * scale;
+        const float char_width = ImFontGetCharAdvanceX(this, c);
         if (line_width + char_width >= max_width)
         {
             s = prev_s;
@@ -4063,9 +4065,9 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
     if (y > clip_rect.w)
         return;
 
-    const float start_x = x;
     const float scale = size / FontSize;
     const float line_height = FontSize * scale;
+    const float origin_x = x;
     const bool word_wrap_enabled = (wrap_width > 0.0f);
 
     // Fast-forward to first visible line
@@ -4124,11 +4126,11 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
         {
             // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.
             if (!word_wrap_eol)
-                word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - start_x));
+                word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - origin_x));
 
             if (s >= word_wrap_eol)
             {
-                x = start_x;
+                x = origin_x;
                 y += line_height;
                 if (y > clip_rect.w)
                     break; // break out of main loop
@@ -4149,7 +4151,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
         {
             if (c == '\n')
             {
-                x = start_x;
+                x = origin_x;
                 y += line_height;
                 if (y > clip_rect.w)
                     break; // break out of main loop
diff --git a/imgui_internal.h b/imgui_internal.h
index 6d84f1027..9e6452bcb 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -260,6 +260,15 @@ extern IMGUI_API ImGuiContext* GImGui;  // Current implicit context pointer
 #define IM_FLOOR IM_TRUNC
 #endif
 
+// Hint for branch prediction
+#if (defined(__cplusplus) && (__cplusplus >= 202002L)) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 202002L))
+#define IM_LIKELY   [[likely]]
+#define IM_UNLIKELY [[unlikely]]
+#else
+#define IM_LIKELY
+#define IM_UNLIKELY
+#endif
+
 // Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall
 #ifdef _MSC_VER
 #define IMGUI_CDECL __cdecl

From 31b967f098dc53a6bb36f9be36f4a9e5d592f775 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 7 Nov 2024 19:35:00 +0100
Subject: [PATCH 0492/2359] Fix 01d27a4 (sorry I cherry-picked from wrong
 branch)

---
 imgui_draw.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 7934949ec..48d42f392 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -4016,7 +4016,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
                 continue;
         }
 
-        const float char_width = ImFontGetCharAdvanceX(this, c);
+        const float char_width = ImFontGetCharAdvanceX(this, c) * scale;
         if (line_width + char_width >= max_width)
         {
             s = prev_s;

From f401021d5a5d56fe2304056c391e78f81c8d4b8f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 7 Nov 2024 19:38:30 +0100
Subject: [PATCH 0493/2359] Version 1.91.5

---
 docs/CHANGELOG.txt | 14 +++++++++-----
 imgui.cpp          |  2 +-
 imgui.h            |  6 +++---
 imgui_demo.cpp     |  2 +-
 imgui_draw.cpp     |  2 +-
 imgui_internal.h   |  2 +-
 imgui_tables.cpp   |  2 +-
 imgui_widgets.cpp  |  2 +-
 8 files changed, 18 insertions(+), 14 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index a1655fdab..ce752ca29 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -36,9 +36,11 @@ HOW TO UPDATE?
 - Please report any issue!
 
 -----------------------------------------------------------------------
- VERSION 1.91.5 WIP (In Progress)
+ VERSION 1.91.5 (Released 2024-11-07)
 -----------------------------------------------------------------------
 
+Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.5
+
 Breaking changes:
 
 - Commented out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before).
@@ -47,8 +49,8 @@ Breaking changes:
   - Pre-1.87 backends are not supported:
     - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields.
     - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields.
-  - For more reference:
-    - read 1.87 and 1.88 part of this section or read Changelog for 1.87 and 1.88.
+  - For more references:
+    - read 1.87 and 1.88 part of API BREAKING CHANGES in imgui.cpp or read Changelog for 1.87 and 1.88.
     - read https://github.com/ocornut/imgui/issues/4921
   - If you have trouble updating a very old codebase using legacy backend-specific key codes:
     consider updating to 1.91.4 first, then #define IMGUI_DISABLE_OBSOLETE_KEYIO, then update to latest.
@@ -66,12 +68,12 @@ Other changes:
   a callback would sometimes prevents further appending to the buffer.
 - Tabs, Style: made ImGuiCol_TabDimmedSelectedOverline alpha 0 (not visible) in default
   styles as the current look is not right (but ImGuiCol_TabSelectedOverline stays the same).
-- Log/Capture: better decorating of BeginMenu() and TabItem() output.
-- Log/Capture: a non terminated log ends automatically in the window which called it.
 - Log/Capture: added experimental io.ConfigWindowsCopyContentsWithCtrlC option to
   automatically copy window contents into clipboard using CTRL+C. This is experimental
   because (1) it currently breaks on nested Begin/End, (2) text output quality varies,
   and (3) text output comes in submission order rather than spatial order.
+- Log/Capture: better decorating of BeginMenu() and TabItem() output.
+- Log/Capture: a non terminated log ends automatically in the window which called it.
 - imgui_freetype: Fixed a crash in build font atlas when using merged fonts and the
   first font in a merged set has no loaded glyph. (#8081)
 - Backends: DX12: Unmap() call specify written range. The range is informational and
@@ -88,6 +90,8 @@ Other changes:
  VERSION 1.91.4 (Released 2024-10-18)
 -----------------------------------------------------------------------
 
+Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.4
+
 Breaking changes:
 
 - Style: renamed ImGuiCol_NavHighlight to ImGuiCol_NavCursor, for consistency with
diff --git a/imgui.cpp b/imgui.cpp
index 2ea9417b4..4624c45d9 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5 WIP
+// dear imgui, v1.91.5
 // (main code and documentation)
 
 // Help:
diff --git a/imgui.h b/imgui.h
index 32425db89..d6286592b 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5 WIP
+// dear imgui, v1.91.5
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.5 WIP"
-#define IMGUI_VERSION_NUM   19144
+#define IMGUI_VERSION       "1.91.5"
+#define IMGUI_VERSION_NUM   19150
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index e28ca3b7a..76a06cc7d 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5 WIP
+// dear imgui, v1.91.5
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 48d42f392..fa82a9419 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5 WIP
+// dear imgui, v1.91.5
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index 9e6452bcb..49452ab0a 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5 WIP
+// dear imgui, v1.91.5
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 122cd87b1..e36e6f172 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5 WIP
+// dear imgui, v1.91.5
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index bb445d977..b5d66baa0 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5 WIP
+// dear imgui, v1.91.5
 // (widgets code)
 
 /*

From 3381ab423b359bda18ef47e9919643bbaf5cc131 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 12 Nov 2024 11:44:29 +0100
Subject: [PATCH 0494/2359] Version 1.91.6 WIP + fixed typo in tooltip.

---
 docs/CHANGELOG.txt | 9 +++++++++
 imgui.cpp          | 4 ++--
 imgui.h            | 6 +++---
 imgui_demo.cpp     | 2 +-
 imgui_draw.cpp     | 2 +-
 imgui_internal.h   | 2 +-
 imgui_tables.cpp   | 2 +-
 imgui_widgets.cpp  | 2 +-
 8 files changed, 19 insertions(+), 10 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index ce752ca29..67d5bef53 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -35,6 +35,14 @@ HOW TO UPDATE?
   and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users.
 - Please report any issue!
 
+-----------------------------------------------------------------------
+ VERSION 1.91.6 WIP (In Progress)
+-----------------------------------------------------------------------
+
+Breaking changes:
+
+Other changes:
+
 -----------------------------------------------------------------------
  VERSION 1.91.5 (Released 2024-11-07)
 -----------------------------------------------------------------------
@@ -86,6 +94,7 @@ Other changes:
 - Examples: Android+OpenGL: Using ALooper_pollOnce() instead of ALooper_pollAll()
   which has been deprecated. (#8013) [@feather179]
 
+
 -----------------------------------------------------------------------
  VERSION 1.91.4 (Released 2024-10-18)
 -----------------------------------------------------------------------
diff --git a/imgui.cpp b/imgui.cpp
index 4624c45d9..431cac9c1 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5
+// dear imgui, v1.91.6 WIP
 // (main code and documentation)
 
 // Help:
@@ -10579,7 +10579,7 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip()
         BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!");
         BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!");
         //BulletText("Code intending to use duplicate ID may use e.g. PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()"); // Not making this too visible for fear of it being abused.
-        BulletText("Set io.ConfigDebugDetectIdConflicts=false to disable this warning in non-programmers builds.");
+        BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.");
         Separator();
         Text("(Hold CTRL to: use");
         SameLine();
diff --git a/imgui.h b/imgui.h
index d6286592b..815b07924 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5
+// dear imgui, v1.91.6 WIP
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.5"
-#define IMGUI_VERSION_NUM   19150
+#define IMGUI_VERSION       "1.91.6 WIP"
+#define IMGUI_VERSION_NUM   19151
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 76a06cc7d..ac34e6b1d 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5
+// dear imgui, v1.91.6 WIP
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index fa82a9419..0003fe1e2 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5
+// dear imgui, v1.91.6 WIP
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index 49452ab0a..2af196cb7 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5
+// dear imgui, v1.91.6 WIP
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index e36e6f172..5254f7858 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5
+// dear imgui, v1.91.6 WIP
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index b5d66baa0..c60378f82 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.5
+// dear imgui, v1.91.6 WIP
 // (widgets code)
 
 /*

From e97b97467e434d2c53b76a19563d641e55130e16 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Tue, 12 Nov 2024 19:09:00 +0100
Subject: [PATCH 0495/2359] Error Handling: fixed cases where recoverable error
 handling would crash. (#1651)

---
 docs/CHANGELOG.txt | 4 ++++
 imgui.cpp          | 2 +-
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 67d5bef53..6586cba20 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,10 @@ Breaking changes:
 
 Other changes:
 
+- Error Handling: fixed cases where recoverable error handling would crash when 
+  processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
+
+
 -----------------------------------------------------------------------
  VERSION 1.91.5 (Released 2024-11-07)
 -----------------------------------------------------------------------
diff --git a/imgui.cpp b/imgui.cpp
index 431cac9c1..45af644ae 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -10542,7 +10542,7 @@ bool    ImGui::ErrorLog(const char* msg)
     // Output to tooltip
     if (g.IO.ConfigErrorRecoveryEnableTooltip)
     {
-        if (BeginErrorTooltip())
+        if (g.WithinFrameScope && BeginErrorTooltip())
         {
             if (g.ErrorCountCurrentFrame < 20)
             {

From 8be0723fb7a626f0fad6e70a2ad9139e442c4008 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 13 Nov 2024 16:55:06 +0100
Subject: [PATCH 0496/2359] Amend Changelog to better document how changing
 button behavior of InputInt/InputFloat step buttons affected some mis-uses
 (#8149)

---
 docs/CHANGELOG.txt | 5 +++++
 imgui.cpp          | 2 +-
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 6586cba20..0dc526e24 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -76,6 +76,11 @@ Other changes:
   between _Header and _HeaderHovered which was introduced v1.91 (#8106, #1861)
 - Buttons: using ImGuiItemFlags_ButtonRepeat makes default button behavior use
   PressedOnClick instead of PressedOnClickRelease when unspecified.
+  - This is intended to make the +/- buttons of InputInt/InputFloat react on the
+    initial mouse down event.
+  - Note that it may reveal incorrect usage if you were using InputInt/InputFloat
+    without persistent storage by relying solely on e.g. IsItemDeactivatedAfterEdit():
+    this was never supported and didn't work consistantly (see #8149).
 - InputText: fixed a bug (regression in 1.91.2) where modifying text buffer within
   a callback would sometimes prevents further appending to the buffer.
 - Tabs, Style: made ImGuiCol_TabDimmedSelectedOverline alpha 0 (not visible) in default
diff --git a/imgui.cpp b/imgui.cpp
index 45af644ae..3512ec87d 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -5788,7 +5788,7 @@ bool ImGui::IsItemDeactivatedAfterEdit()
     return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
 }
 
-// == GetItemID() == GetFocusID()
+// == (GetItemID() == GetFocusID() && GetFocusID() != 0)
 bool ImGui::IsItemFocused()
 {
     ImGuiContext& g = *GImGui;

From 3260ea6954554f5cfac7461e94bc18d14cce3617 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 15 Nov 2024 16:03:58 +0100
Subject: [PATCH 0497/2359] Examples: Win32+DX12: Tweaks.

---
 backends/imgui_impl_dx12.cpp              |  3 ++
 backends/imgui_impl_dx12.h                |  3 ++
 examples/example_win32_directx12/main.cpp | 36 +++++++++++------------
 3 files changed, 24 insertions(+), 18 deletions(-)

diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index 7a428a1a5..24b195bda 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -6,6 +6,9 @@
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
+// The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
+// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
+
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
 // Learn about Dear ImGui:
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index 1e36d730f..b5a8dde2e 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -6,6 +6,9 @@
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
+// The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
+// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
+
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
 // Learn about Dear ImGui:
diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp
index 4173a8010..168b69660 100644
--- a/examples/example_win32_directx12/main.cpp
+++ b/examples/example_win32_directx12/main.cpp
@@ -22,20 +22,20 @@
 #pragma comment(lib, "dxguid.lib")
 #endif
 
-#include "imgui_internal.h"
+// Config for example app
+static const int APP_NUM_FRAMES_IN_FLIGHT = 3;
+static const int APP_NUM_BACK_BUFFERS = 3;
 
 struct FrameContext
 {
-    ID3D12CommandAllocator* CommandAllocator;
-    UINT64                  FenceValue;
+    ID3D12CommandAllocator*     CommandAllocator;
+    UINT64                      FenceValue;
 };
 
 // Data
-static int const                    NUM_FRAMES_IN_FLIGHT = 3;
-static FrameContext                 g_frameContext[NUM_FRAMES_IN_FLIGHT] = {};
+static FrameContext                 g_frameContext[APP_NUM_FRAMES_IN_FLIGHT] = {};
 static UINT                         g_frameIndex = 0;
 
-static int const                    NUM_BACK_BUFFERS = 3;
 static ID3D12Device*                g_pd3dDevice = nullptr;
 static ID3D12DescriptorHeap*        g_pd3dRtvDescHeap = nullptr;
 static ID3D12DescriptorHeap*        g_pd3dSrvDescHeap = nullptr;
@@ -47,8 +47,8 @@ static UINT64                       g_fenceLastSignaledValue = 0;
 static IDXGISwapChain3*             g_pSwapChain = nullptr;
 static bool                         g_SwapChainOccluded = false;
 static HANDLE                       g_hSwapChainWaitableObject = nullptr;
-static ID3D12Resource*              g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {};
-static D3D12_CPU_DESCRIPTOR_HANDLE  g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {};
+static ID3D12Resource*              g_mainRenderTargetResource[APP_NUM_BACK_BUFFERS] = {};
+static D3D12_CPU_DESCRIPTOR_HANDLE  g_mainRenderTargetDescriptor[APP_NUM_BACK_BUFFERS] = {};
 
 // Forward declarations of helper functions
 bool CreateDeviceD3D(HWND hWnd);
@@ -249,7 +249,7 @@ bool CreateDeviceD3D(HWND hWnd)
     DXGI_SWAP_CHAIN_DESC1 sd;
     {
         ZeroMemory(&sd, sizeof(sd));
-        sd.BufferCount = NUM_BACK_BUFFERS;
+        sd.BufferCount = APP_NUM_BACK_BUFFERS;
         sd.Width = 0;
         sd.Height = 0;
         sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
@@ -292,7 +292,7 @@ bool CreateDeviceD3D(HWND hWnd)
     {
         D3D12_DESCRIPTOR_HEAP_DESC desc = {};
         desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
-        desc.NumDescriptors = NUM_BACK_BUFFERS;
+        desc.NumDescriptors = APP_NUM_BACK_BUFFERS;
         desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
         desc.NodeMask = 1;
         if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dRtvDescHeap)) != S_OK)
@@ -300,7 +300,7 @@ bool CreateDeviceD3D(HWND hWnd)
 
         SIZE_T rtvDescriptorSize = g_pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
         D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_pd3dRtvDescHeap->GetCPUDescriptorHandleForHeapStart();
-        for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
+        for (UINT i = 0; i < APP_NUM_BACK_BUFFERS; i++)
         {
             g_mainRenderTargetDescriptor[i] = rtvHandle;
             rtvHandle.ptr += rtvDescriptorSize;
@@ -325,7 +325,7 @@ bool CreateDeviceD3D(HWND hWnd)
             return false;
     }
 
-    for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++)
+    for (UINT i = 0; i < APP_NUM_FRAMES_IN_FLIGHT; i++)
         if (g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_frameContext[i].CommandAllocator)) != S_OK)
             return false;
 
@@ -351,7 +351,7 @@ bool CreateDeviceD3D(HWND hWnd)
             return false;
         swapChain1->Release();
         dxgiFactory->Release();
-        g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS);
+        g_pSwapChain->SetMaximumFrameLatency(APP_NUM_BACK_BUFFERS);
         g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject();
     }
 
@@ -364,7 +364,7 @@ void CleanupDeviceD3D()
     CleanupRenderTarget();
     if (g_pSwapChain) { g_pSwapChain->SetFullscreenState(false, nullptr); g_pSwapChain->Release(); g_pSwapChain = nullptr; }
     if (g_hSwapChainWaitableObject != nullptr) { CloseHandle(g_hSwapChainWaitableObject); }
-    for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++)
+    for (UINT i = 0; i < APP_NUM_FRAMES_IN_FLIGHT; i++)
         if (g_frameContext[i].CommandAllocator) { g_frameContext[i].CommandAllocator->Release(); g_frameContext[i].CommandAllocator = nullptr; }
     if (g_pd3dCommandQueue) { g_pd3dCommandQueue->Release(); g_pd3dCommandQueue = nullptr; }
     if (g_pd3dCommandList) { g_pd3dCommandList->Release(); g_pd3dCommandList = nullptr; }
@@ -386,7 +386,7 @@ void CleanupDeviceD3D()
 
 void CreateRenderTarget()
 {
-    for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
+    for (UINT i = 0; i < APP_NUM_BACK_BUFFERS; i++)
     {
         ID3D12Resource* pBackBuffer = nullptr;
         g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer));
@@ -399,13 +399,13 @@ void CleanupRenderTarget()
 {
     WaitForLastSubmittedFrame();
 
-    for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
+    for (UINT i = 0; i < APP_NUM_BACK_BUFFERS; i++)
         if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = nullptr; }
 }
 
 void WaitForLastSubmittedFrame()
 {
-    FrameContext* frameCtx = &g_frameContext[g_frameIndex % NUM_FRAMES_IN_FLIGHT];
+    FrameContext* frameCtx = &g_frameContext[g_frameIndex % APP_NUM_FRAMES_IN_FLIGHT];
 
     UINT64 fenceValue = frameCtx->FenceValue;
     if (fenceValue == 0)
@@ -427,7 +427,7 @@ FrameContext* WaitForNextFrameResources()
     HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, nullptr };
     DWORD numWaitableObjects = 1;
 
-    FrameContext* frameCtx = &g_frameContext[nextFrameIndex % NUM_FRAMES_IN_FLIGHT];
+    FrameContext* frameCtx = &g_frameContext[nextFrameIndex % APP_NUM_FRAMES_IN_FLIGHT];
     UINT64 fenceValue = frameCtx->FenceValue;
     if (fenceValue != 0) // means no fence was signaled
     {

From 40b2286d16e92ea017347a62cb91e63f378ff455 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 15 Nov 2024 19:02:26 +0100
Subject: [PATCH 0498/2359] (Breaking) Backends: DX12: changed
 ImGui_ImplDX12_Init() signature. Added ImGui_ImplDX12_InitInfo. Added support
 for Srv allocators.

Ref 7708
---
 backends/imgui_impl_dx12.cpp              | 67 +++++++++++++++++++----
 backends/imgui_impl_dx12.h                | 40 ++++++++++----
 docs/CHANGELOG.txt                        | 10 ++++
 examples/example_win32_directx12/main.cpp | 66 ++++++++++++++++++++--
 4 files changed, 155 insertions(+), 28 deletions(-)

diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index 24b195bda..105bcb213 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -19,6 +19,8 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
+//  2024-11-15: DirectX12: *BREAKING CHANGE* User is now required to pass function pointers to allocate/free SRV Descriptors. We provide convenience legacy fields to pass a single descriptor, matching the old API, but upcoming features will want multiple.
 //  2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
 //  2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
@@ -57,6 +59,7 @@
 struct ImGui_ImplDX12_RenderBuffers;
 struct ImGui_ImplDX12_Data
 {
+    ImGui_ImplDX12_InitInfo     InitInfo;
     ID3D12Device*               pd3dDevice;
     ID3D12RootSignature*        pRootSignature;
     ID3D12PipelineState*        pPipelineState;
@@ -695,8 +698,14 @@ void    ImGui_ImplDX12_InvalidateDeviceObjects()
     ImGuiIO& io = ImGui::GetIO();
     SafeRelease(bd->pRootSignature);
     SafeRelease(bd->pPipelineState);
+
+    // Free SRV descriptor used by texture
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+    if (bd->InitInfo.SrvDescriptorFreeFn != NULL)
+#endif
+        bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, bd->hFontSrvCpuDescHandle, bd->hFontSrvGpuDescHandle);
     SafeRelease(bd->pFontTextureResource);
-    io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
+    io.Fonts->SetTexID(0); // We copied bd->hFontSrvGpuDescHandle to io.Fonts->TexID so let's clear that as well.
 
     for (UINT i = 0; i < bd->numFramesInFlight; i++)
     {
@@ -706,8 +715,7 @@ void    ImGui_ImplDX12_InvalidateDeviceObjects()
     }
 }
 
-bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap,
-                         D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
+bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
 {
     ImGuiIO& io = ImGui::GetIO();
     IMGUI_CHECKVERSION();
@@ -715,21 +723,39 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO
 
     // Setup backend capabilities flags
     ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
+
+    bd->InitInfo = *init_info; // Deep copy
+    bd->pd3dDevice = init_info->Device;
+    bd->RTVFormat = init_info->RTVFormat;
+    bd->numFramesInFlight = init_info->NumFramesInFlight;
+    bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
+
     io.BackendRendererUserData = (void*)bd;
     io.BackendRendererName = "imgui_impl_dx12";
     io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;  // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
 
-    bd->pd3dDevice = device;
-    bd->RTVFormat = rtv_format;
-    bd->hFontSrvCpuDescHandle = font_srv_cpu_desc_handle;
-    bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle;
-    bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[num_frames_in_flight];
-    bd->numFramesInFlight = num_frames_in_flight;
-    bd->pd3dSrvDescHeap = cbv_srv_heap;
-    bd->frameIndex = UINT_MAX;
+    // Allocate 1 SRV descriptor for the font texture
+    if (init_info->SrvDescriptorAllocFn != NULL)
+    {
+        IM_ASSERT(init_info->SrvDescriptorFreeFn != NULL);
+        init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->hFontSrvCpuDescHandle, &bd->hFontSrvGpuDescHandle);
+    }
+    else
+    {
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+        IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
+        bd->hFontSrvCpuDescHandle = init_info->LegacySingleSrvCpuDescriptor;
+        bd->hFontSrvGpuDescHandle = init_info->LegacySingleSrvGpuDescriptor;
+#else
+        IM_ASSERT(init_info->SrvDescriptorAllocFn != NULL);
+        IM_ASSERT(init_info->SrvDescriptorFreeFn != NULL);
+#endif
+    }
 
     // Create buffers with a default size (they will later be grown as needed)
-    for (int i = 0; i < num_frames_in_flight; i++)
+    bd->frameIndex = UINT_MAX;
+    bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[bd->numFramesInFlight];
+    for (int i = 0; i < (int)bd->numFramesInFlight; i++)
     {
         ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
         fr->IndexBuffer = nullptr;
@@ -741,6 +767,22 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO
     return true;
 }
 
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+// Legacy initialization API Obsoleted in 1.91.5
+// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap'
+bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
+{
+    ImGui_ImplDX12_InitInfo init_info;
+    init_info.Device = device;
+    init_info.NumFramesInFlight = num_frames_in_flight;
+    init_info.RTVFormat = rtv_format;
+    init_info.SrvDescriptorHeap = srv_descriptor_heap;
+    init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle;
+    init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;;
+    return ImGui_ImplDX12_Init(&init_info);
+}
+#endif
+
 void ImGui_ImplDX12_Shutdown()
 {
     ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
@@ -750,6 +792,7 @@ void ImGui_ImplDX12_Shutdown()
     // Clean up windows and device objects
     ImGui_ImplDX12_InvalidateDeviceObjects();
     delete[] bd->pFrameResources;
+
     io.BackendRendererName = nullptr;
     io.BackendRendererUserData = nullptr;
     io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index b5a8dde2e..34938fb56 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -21,24 +21,42 @@
 #include "imgui.h"      // IMGUI_IMPL_API
 #ifndef IMGUI_DISABLE
 #include  // DXGI_FORMAT
+#include       // D3D12_CPU_DESCRIPTOR_HANDLE
 
-struct ID3D12Device;
-struct ID3D12DescriptorHeap;
-struct ID3D12GraphicsCommandList;
-struct D3D12_CPU_DESCRIPTOR_HANDLE;
-struct D3D12_GPU_DESCRIPTOR_HANDLE;
+// Initialization data, for ImGui_ImplDX12_Init()
+struct ImGui_ImplDX12_InitInfo
+{
+    ID3D12Device*               Device;
+    ID3D12CommandQueue*         CommandQueue;
+    int                         NumFramesInFlight;
+    DXGI_FORMAT                 RTVFormat;
+    void*                       UserData;
+
+    // Allocating SRV descriptors for textures is up to the application, so we provide callbacks.
+    // (current version of the backend will only allocate one descriptor, future versions will need to allocate more)
+    ID3D12DescriptorHeap*       SrvDescriptorHeap;
+    void                        (*SrvDescriptorAllocFn)(ImGui_ImplDX12_InitInfo* info, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_desc_handle);
+    void                        (*SrvDescriptorFreeFn)(ImGui_ImplDX12_InitInfo* info, D3D12_CPU_DESCRIPTOR_HANDLE cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE gpu_desc_handle);
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+    D3D12_CPU_DESCRIPTOR_HANDLE LegacySingleSrvCpuDescriptor; // To facilitate transition from single descriptor to allocator callback, you may use those.
+    D3D12_GPU_DESCRIPTOR_HANDLE LegacySingleSrvGpuDescriptor;
+#endif
+
+    ImGui_ImplDX12_InitInfo()   { memset(this, 0, sizeof(*this)); }
+};
 
 // Follow "Getting Started" link and check examples/ folder to learn about using backends!
-
-// Before calling the render function, caller must prepare the command list by resetting it and setting the appropriate
-// render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle.
-// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture.
-IMGUI_IMPL_API bool     ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap,
-                                            D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle);
+IMGUI_IMPL_API bool     ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* info);
 IMGUI_IMPL_API void     ImGui_ImplDX12_Shutdown();
 IMGUI_IMPL_API void     ImGui_ImplDX12_NewFrame();
 IMGUI_IMPL_API void     ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list);
 
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+// Legacy initialization API Obsoleted in 1.91.5
+// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap'
+IMGUI_IMPL_API bool     ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle);
+#endif
+
 // Use if you want to reset your rendering device without losing Dear ImGui state.
 IMGUI_IMPL_API bool     ImGui_ImplDX12_CreateDeviceObjects();
 IMGUI_IMPL_API void     ImGui_ImplDX12_InvalidateDeviceObjects();
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 0dc526e24..ef42ebc4d 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -41,10 +41,20 @@ HOW TO UPDATE?
 
 Breaking changes:
 
+- Backends: DX12: Changed ImGui_ImplDX12_Init() signature to take a
+  ImGui_ImplDX12_InitInfo struct.
+  - Using the new API, application is now required to pass function pointers
+    to allocate/free SRV Descriptors.
+  - We provide convenience legacy fields to pass a single descriptor,
+    matching the old API, but upcoming features will want multiple.
+  - Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
+
 Other changes:
 
 - Error Handling: fixed cases where recoverable error handling would crash when 
   processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
+- Examples: Win32+DX12: Using a basic free-list allocator to manage multiple
+  SRV descriptors.
 
 
 -----------------------------------------------------------------------
diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp
index 168b69660..257410e2c 100644
--- a/examples/example_win32_directx12/main.cpp
+++ b/examples/example_win32_directx12/main.cpp
@@ -25,6 +25,7 @@
 // Config for example app
 static const int APP_NUM_FRAMES_IN_FLIGHT = 3;
 static const int APP_NUM_BACK_BUFFERS = 3;
+static const int APP_SRV_HEAP_SIZE = 64;
 
 struct FrameContext
 {
@@ -32,6 +33,51 @@ struct FrameContext
     UINT64                      FenceValue;
 };
 
+// Simple free list based allocator
+struct ExampleDescriptorHeapAllocator
+{
+    ID3D12DescriptorHeap*       Heap = nullptr;
+    D3D12_DESCRIPTOR_HEAP_TYPE  HeapType = D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES;
+    D3D12_CPU_DESCRIPTOR_HANDLE HeapStartCpu;
+    D3D12_GPU_DESCRIPTOR_HANDLE HeapStartGpu;
+    UINT                        HeapHandleIncrement;
+    ImVector               FreeIndices;
+
+    void Create(ID3D12Device* device, ID3D12DescriptorHeap* heap)
+    {
+        IM_ASSERT(Heap == nullptr && FreeIndices.empty());
+        Heap = heap;
+        D3D12_DESCRIPTOR_HEAP_DESC desc = heap->GetDesc();
+        HeapType = desc.Type;
+        HeapStartCpu = Heap->GetCPUDescriptorHandleForHeapStart();
+        HeapStartGpu = Heap->GetGPUDescriptorHandleForHeapStart();
+        HeapHandleIncrement = device->GetDescriptorHandleIncrementSize(HeapType);
+        FreeIndices.reserve((int)desc.NumDescriptors);
+        for (int n = desc.NumDescriptors; n > 0; n--)
+            FreeIndices.push_back(n);
+    }
+    void Destroy()
+    {
+        Heap = NULL;
+        FreeIndices.clear();
+    }
+    void Alloc(D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_desc_handle)
+    {
+        IM_ASSERT(FreeIndices.Size > 0);
+        int idx = FreeIndices.back();
+        FreeIndices.pop_back();
+        out_cpu_desc_handle->ptr = HeapStartCpu.ptr + (idx * HeapHandleIncrement);
+        out_gpu_desc_handle->ptr = HeapStartGpu.ptr + (idx * HeapHandleIncrement);
+    }
+    void Free(D3D12_CPU_DESCRIPTOR_HANDLE out_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE out_gpu_desc_handle)
+    {
+        int cpu_idx = (int)((out_cpu_desc_handle.ptr - HeapStartCpu.ptr) / HeapHandleIncrement);
+        int gpu_idx = (int)((out_gpu_desc_handle.ptr - HeapStartGpu.ptr) / HeapHandleIncrement);
+        IM_ASSERT(cpu_idx == gpu_idx);
+        FreeIndices.push_back(cpu_idx);
+    }
+};
+
 // Data
 static FrameContext                 g_frameContext[APP_NUM_FRAMES_IN_FLIGHT] = {};
 static UINT                         g_frameIndex = 0;
@@ -39,6 +85,7 @@ static UINT                         g_frameIndex = 0;
 static ID3D12Device*                g_pd3dDevice = nullptr;
 static ID3D12DescriptorHeap*        g_pd3dRtvDescHeap = nullptr;
 static ID3D12DescriptorHeap*        g_pd3dSrvDescHeap = nullptr;
+static ExampleDescriptorHeapAllocator g_pd3dSrvDescHeapAlloc;
 static ID3D12CommandQueue*          g_pd3dCommandQueue = nullptr;
 static ID3D12GraphicsCommandList*   g_pd3dCommandList = nullptr;
 static ID3D12Fence*                 g_fence = nullptr;
@@ -93,10 +140,18 @@ int main(int, char**)
 
     // Setup Platform/Renderer backends
     ImGui_ImplWin32_Init(hwnd);
-    ImGui_ImplDX12_Init(g_pd3dDevice, NUM_FRAMES_IN_FLIGHT,
-        DXGI_FORMAT_R8G8B8A8_UNORM, g_pd3dSrvDescHeap,
-        g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(),
-        g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart());
+
+    ImGui_ImplDX12_InitInfo init_info = {};
+    init_info.Device = g_pd3dDevice;
+    init_info.CommandQueue = g_pd3dCommandQueue;
+    init_info.NumFramesInFlight = APP_NUM_FRAMES_IN_FLIGHT;
+    init_info.RTVFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
+    // Allocating SRV descriptors (for textures) is up to the application, so we provide callbacks.
+    // (current version of the backend will only allocate one descriptor, future versions will need to allocate more)
+    init_info.SrvDescriptorHeap = g_pd3dSrvDescHeap;
+    init_info.SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle) { return g_pd3dSrvDescHeapAlloc.Alloc(out_cpu_handle, out_gpu_handle); };
+    init_info.SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle)            { return g_pd3dSrvDescHeapAlloc.Free(cpu_handle, gpu_handle); };
+    ImGui_ImplDX12_Init(&init_info);
 
     // Load Fonts
     // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
@@ -310,10 +365,11 @@ bool CreateDeviceD3D(HWND hWnd)
     {
         D3D12_DESCRIPTOR_HEAP_DESC desc = {};
         desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
-        desc.NumDescriptors = 1;
+        desc.NumDescriptors = APP_SRV_HEAP_SIZE;
         desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
         if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dSrvDescHeap)) != S_OK)
             return false;
+        g_pd3dSrvDescHeapAlloc.Create(g_pd3dDevice, g_pd3dSrvDescHeap);
     }
 
     {

From 08400f5be7fa8a83682b99d611ab7cdc66258425 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 15 Nov 2024 19:14:04 +0100
Subject: [PATCH 0499/2359] Backends: DX12: tidying up, added a
 ImGui_ImplDX12_Texture helper struct.

---
 backends/imgui_impl_dx12.cpp | 34 +++++++++++++++++++++-------------
 1 file changed, 21 insertions(+), 13 deletions(-)

diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index 105bcb213..8f9eb090c 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -55,8 +55,16 @@
 #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
 #endif
 
-// DirectX data
+// DirectX12 data
 struct ImGui_ImplDX12_RenderBuffers;
+
+struct ImGui_ImplDX12_Texture
+{
+    ID3D12Resource*             pTextureResource;
+    D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
+    D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
+};
+
 struct ImGui_ImplDX12_Data
 {
     ImGui_ImplDX12_InitInfo     InitInfo;
@@ -64,9 +72,7 @@ struct ImGui_ImplDX12_Data
     ID3D12RootSignature*        pRootSignature;
     ID3D12PipelineState*        pPipelineState;
     DXGI_FORMAT                 RTVFormat;
-    ID3D12Resource*             pFontTextureResource;
-    D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
-    D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
+    ImGui_ImplDX12_Texture      FontTexture;
     ID3D12DescriptorHeap*       pd3dSrvDescHeap;
     UINT                        numFramesInFlight;
 
@@ -316,6 +322,7 @@ static void ImGui_ImplDX12_CreateFontsTexture()
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
 
     // Upload texture to graphics system
+    ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
     {
         D3D12_HEAP_PROPERTIES props;
         memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
@@ -446,13 +453,13 @@ static void ImGui_ImplDX12_CreateFontsTexture()
         srvDesc.Texture2D.MipLevels = desc.MipLevels;
         srvDesc.Texture2D.MostDetailedMip = 0;
         srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
-        bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle);
-        SafeRelease(bd->pFontTextureResource);
-        bd->pFontTextureResource = pTexture;
+        bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, font_tex->hFontSrvCpuDescHandle);
+        SafeRelease(font_tex->pTextureResource);
+        font_tex->pTextureResource = pTexture;
     }
 
     // Store our identifier
-    io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr);
+    io.Fonts->SetTexID((ImTextureID)font_tex->hFontSrvGpuDescHandle.ptr);
 }
 
 bool    ImGui_ImplDX12_CreateDeviceObjects()
@@ -700,11 +707,12 @@ void    ImGui_ImplDX12_InvalidateDeviceObjects()
     SafeRelease(bd->pPipelineState);
 
     // Free SRV descriptor used by texture
+    ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
     if (bd->InitInfo.SrvDescriptorFreeFn != NULL)
 #endif
-        bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, bd->hFontSrvCpuDescHandle, bd->hFontSrvGpuDescHandle);
-    SafeRelease(bd->pFontTextureResource);
+        bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, font_tex->hFontSrvCpuDescHandle, font_tex->hFontSrvGpuDescHandle);
+    SafeRelease(font_tex->pTextureResource);
     io.Fonts->SetTexID(0); // We copied bd->hFontSrvGpuDescHandle to io.Fonts->TexID so let's clear that as well.
 
     for (UINT i = 0; i < bd->numFramesInFlight; i++)
@@ -738,14 +746,14 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
     if (init_info->SrvDescriptorAllocFn != NULL)
     {
         IM_ASSERT(init_info->SrvDescriptorFreeFn != NULL);
-        init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->hFontSrvCpuDescHandle, &bd->hFontSrvGpuDescHandle);
+        init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->FontTexture.hFontSrvCpuDescHandle, &bd->FontTexture.hFontSrvGpuDescHandle);
     }
     else
     {
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
         IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
-        bd->hFontSrvCpuDescHandle = init_info->LegacySingleSrvCpuDescriptor;
-        bd->hFontSrvGpuDescHandle = init_info->LegacySingleSrvGpuDescriptor;
+        bd->FontTexture.hFontSrvCpuDescHandle = init_info->LegacySingleSrvCpuDescriptor;
+        bd->FontTexture.hFontSrvGpuDescHandle = init_info->LegacySingleSrvGpuDescriptor;
 #else
         IM_ASSERT(init_info->SrvDescriptorAllocFn != NULL);
         IM_ASSERT(init_info->SrvDescriptorFreeFn != NULL);

From 142827f7d8618d107f18d995da3530dab8aefd8f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 18 Nov 2024 15:16:41 +0100
Subject: [PATCH 0500/2359] Backends: DX12: rework legacy path for handling
 ImGui_ImplDX12_Init() being called with space for a single descriptor.

---
 backends/imgui_impl_dx12.cpp | 48 +++++++++++++++++++++---------------
 1 file changed, 28 insertions(+), 20 deletions(-)

diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index 8f9eb090c..acf98858b 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -72,13 +72,15 @@ struct ImGui_ImplDX12_Data
     ID3D12RootSignature*        pRootSignature;
     ID3D12PipelineState*        pPipelineState;
     DXGI_FORMAT                 RTVFormat;
-    ImGui_ImplDX12_Texture      FontTexture;
     ID3D12DescriptorHeap*       pd3dSrvDescHeap;
     UINT                        numFramesInFlight;
 
     ImGui_ImplDX12_RenderBuffers* pFrameResources;
     UINT                        frameIndex;
 
+    ImGui_ImplDX12_Texture      FontTexture;
+    bool                        LegacySingleDescriptorUsed;
+
     ImGui_ImplDX12_Data()       { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; }
 };
 
@@ -708,10 +710,7 @@ void    ImGui_ImplDX12_InvalidateDeviceObjects()
 
     // Free SRV descriptor used by texture
     ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-    if (bd->InitInfo.SrvDescriptorFreeFn != NULL)
-#endif
-        bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, font_tex->hFontSrvCpuDescHandle, font_tex->hFontSrvGpuDescHandle);
+    bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, font_tex->hFontSrvCpuDescHandle, font_tex->hFontSrvGpuDescHandle);
     SafeRelease(font_tex->pTextureResource);
     io.Fonts->SetTexID(0); // We copied bd->hFontSrvGpuDescHandle to io.Fonts->TexID so let's clear that as well.
 
@@ -731,8 +730,9 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
 
     // Setup backend capabilities flags
     ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
-
     bd->InitInfo = *init_info; // Deep copy
+    init_info = &bd->InitInfo;
+
     bd->pd3dDevice = init_info->Device;
     bd->RTVFormat = init_info->RTVFormat;
     bd->numFramesInFlight = init_info->NumFramesInFlight;
@@ -742,23 +742,31 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
     io.BackendRendererName = "imgui_impl_dx12";
     io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;  // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
 
-    // Allocate 1 SRV descriptor for the font texture
-    if (init_info->SrvDescriptorAllocFn != NULL)
-    {
-        IM_ASSERT(init_info->SrvDescriptorFreeFn != NULL);
-        init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->FontTexture.hFontSrvCpuDescHandle, &bd->FontTexture.hFontSrvGpuDescHandle);
-    }
-    else
-    {
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+    if (init_info->SrvDescriptorAllocFn == NULL)
+    {
+        // Wrap legacy behavior of passing space for a single descriptor
         IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
-        bd->FontTexture.hFontSrvCpuDescHandle = init_info->LegacySingleSrvCpuDescriptor;
-        bd->FontTexture.hFontSrvGpuDescHandle = init_info->LegacySingleSrvGpuDescriptor;
-#else
-        IM_ASSERT(init_info->SrvDescriptorAllocFn != NULL);
-        IM_ASSERT(init_info->SrvDescriptorFreeFn != NULL);
-#endif
+        init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle)
+        {
+            ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
+            IM_ASSERT(bd->LegacySingleDescriptorUsed == false);
+            *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor;
+            *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor;
+            bd->LegacySingleDescriptorUsed = true;
+        };
+        init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE)
+        {
+            ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
+            IM_ASSERT(bd->LegacySingleDescriptorUsed == true);
+            bd->LegacySingleDescriptorUsed = false;
+        };
     }
+#endif
+
+    // Allocate 1 SRV descriptor for the font texture
+    IM_ASSERT(init_info->SrvDescriptorAllocFn != NULL && init_info->SrvDescriptorFreeFn != NULL);
+    init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->FontTexture.hFontSrvCpuDescHandle, &bd->FontTexture.hFontSrvGpuDescHandle);
 
     // Create buffers with a default size (they will later be grown as needed)
     bd->frameIndex = UINT_MAX;

From eb0ad66d88d96be3ccad31e22ef9d3126ec79ef2 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 18 Nov 2024 18:46:27 +0100
Subject: [PATCH 0501/2359] Demo: example tree used by Property Editor &
 Selection demos properly freed on app closure. (#8158)

---
 docs/CHANGELOG.txt |  2 ++
 imgui_demo.cpp     | 11 ++++++++++-
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index ef42ebc4d..29d1cf98a 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -53,6 +53,8 @@ Other changes:
 
 - Error Handling: fixed cases where recoverable error handling would crash when 
   processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
+- Demo: example tree used by Property Editor & Selection demos properly freed
+  on application closure. (#8158) [@Legulysse]
 - Examples: Win32+DX12: Using a basic free-list allocator to manage multiple
   SRV descriptors.
 
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index ac34e6b1d..c822c162e 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -308,6 +308,13 @@ static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, Exampl
     return node;
 }
 
+static void ExampleTree_DestroyNode(ExampleTreeNode* node)
+{
+    for (ExampleTreeNode* child_node : node->Childs)
+        ExampleTree_DestroyNode(child_node);
+    IM_DELETE(node);
+}
+
 // Create example tree data
 // (this allocates _many_ more times than most other code in either Dear ImGui or others demo)
 static ExampleTreeNode* ExampleTree_CreateDemoTree()
@@ -343,7 +350,7 @@ static ExampleTreeNode* ExampleTree_CreateDemoTree()
 // [SECTION] Demo Window / ShowDemoWindow()
 //-----------------------------------------------------------------------------
 
-// Data to be shared accross different functions of the demo.
+// Data to be shared across different functions of the demo.
 struct ImGuiDemoWindowData
 {
     // Examples Apps (accessible from the "Examples" menu)
@@ -371,6 +378,8 @@ struct ImGuiDemoWindowData
 
     // Other data
     ExampleTreeNode* DemoTree = NULL;
+
+    ~ImGuiDemoWindowData() { if (DemoTree) ExampleTree_DestroyNode(DemoTree); }
 };
 
 // Demonstrate most Dear ImGui features (this is big function!)

From 5ae3dd52a07e4996c777dfb0a85682260f968674 Mon Sep 17 00:00:00 2001
From: chuikingshek 
Date: Tue, 19 Nov 2024 02:36:26 +0800
Subject: [PATCH 0502/2359] Fonts: added IMGUI_DISABLE_DEFAULT_FONT macro.
 (#8161)

---
 docs/CHANGELOG.txt |  2 ++
 imconfig.h         |  1 +
 imgui_draw.cpp     | 11 +++++++++++
 3 files changed, 14 insertions(+)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 29d1cf98a..f04eccd6f 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -53,6 +53,8 @@ Other changes:
 
 - Error Handling: fixed cases where recoverable error handling would crash when 
   processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
+- Misc: added IMGUI_DISABLE_DEFAULT_FONT to strip embedded font from binary. (#8161)
+  [@demonese]
 - Demo: example tree used by Property Editor & Selection demos properly freed
   on application closure. (#8158) [@Legulysse]
 - Examples: Win32+DX12: Using a basic free-list allocator to manage multiple
diff --git a/imconfig.h b/imconfig.h
index fea89dea0..adc69d1a3 100644
--- a/imconfig.h
+++ b/imconfig.h
@@ -48,6 +48,7 @@
 //#define IMGUI_DISABLE_FILE_FUNCTIONS                      // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
 //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS              // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
 //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS                  // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
+//#define IMGUI_DISABLE_DEFAULT_FONT                        // Disable default embedded font (ProggyClean.ttf), remove ~14 KB from output binary. AddFontDefault() will assert.
 //#define IMGUI_DISABLE_SSE                                 // Disable use of SSE intrinsics even if available
 
 //---- Enable Test Engine / Automation features.
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 0003fe1e2..731dd0598 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -2560,7 +2560,9 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
 // Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder)
 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);
+#ifndef IMGUI_DISABLE_DEFAULT_FONT
 static const char*  GetDefaultCompressedFontDataTTFBase85();
+#endif
 static unsigned int Decode85Byte(char c)                                    { return c >= '\\' ? c-36 : c-35; }
 static void         Decode85(const unsigned char* src, unsigned char* dst)
 {
@@ -2576,6 +2578,7 @@ static void         Decode85(const unsigned char* src, unsigned char* dst)
 // Load embedded ProggyClean.ttf at size 13, disable oversampling
 ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
 {
+#ifndef IMGUI_DISABLE_DEFAULT_FONT
     ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
     if (!font_cfg_template)
     {
@@ -2593,6 +2596,11 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
     const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault();
     ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges);
     return font;
+#else
+    IM_ASSERT(0 && "AddFontDefault() disabled in this build.");
+    IM_UNUSED(font_cfg_template);
+    return NULL;
+#endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT
 }
 
 ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
@@ -4578,6 +4586,8 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i
 // Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding).
 // The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size.
 //-----------------------------------------------------------------------------
+
+#ifndef IMGUI_DISABLE_DEFAULT_FONT
 static const char proggy_clean_ttf_compressed_data_base85[11980 + 1] =
     "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/"
     "2*>]b(MC;$jPfY.;h^`IWM9
Date: Wed, 20 Nov 2024 14:02:44 +0100
Subject: [PATCH 0503/2359] Misc: changed embedded ProggyClean encoding to save
 a bit of binary space (~12kb to 9.5kb). (#8161)

Encoding as char to ensure compatibility with big endian (#81)
---
 docs/CHANGELOG.txt                    |   1 +
 imconfig.h                            |   2 +-
 imgui_draw.cpp                        | 278 +++++++++++++++++---------
 misc/fonts/binary_to_compressed_c.cpp |  23 ++-
 4 files changed, 205 insertions(+), 99 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index f04eccd6f..5305b889e 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -53,6 +53,7 @@ Other changes:
 
 - Error Handling: fixed cases where recoverable error handling would crash when 
   processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
+- Misc: changed embedded ProggyClean encoding to save a bit of binary space (~12kb to 9.5kb).
 - Misc: added IMGUI_DISABLE_DEFAULT_FONT to strip embedded font from binary. (#8161)
   [@demonese]
 - Demo: example tree used by Property Editor & Selection demos properly freed
diff --git a/imconfig.h b/imconfig.h
index adc69d1a3..3504a4e4d 100644
--- a/imconfig.h
+++ b/imconfig.h
@@ -48,7 +48,7 @@
 //#define IMGUI_DISABLE_FILE_FUNCTIONS                      // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
 //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS              // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
 //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS                  // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
-//#define IMGUI_DISABLE_DEFAULT_FONT                        // Disable default embedded font (ProggyClean.ttf), remove ~14 KB from output binary. AddFontDefault() will assert.
+//#define IMGUI_DISABLE_DEFAULT_FONT                        // Disable default embedded font (ProggyClean.ttf), remove ~9.5 KB from output binary. AddFontDefault() will assert.
 //#define IMGUI_DISABLE_SSE                                 // Disable use of SSE intrinsics even if available
 
 //---- Enable Test Engine / Automation features.
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 731dd0598..0f74a98b3 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -2560,9 +2560,6 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
 // Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder)
 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);
-#ifndef IMGUI_DISABLE_DEFAULT_FONT
-static const char*  GetDefaultCompressedFontDataTTFBase85();
-#endif
 static unsigned int Decode85Byte(char c)                                    { return c >= '\\' ? c-36 : c-35; }
 static void         Decode85(const unsigned char* src, unsigned char* dst)
 {
@@ -2574,6 +2571,9 @@ static void         Decode85(const unsigned char* src, unsigned char* dst)
         dst += 4;
     }
 }
+#ifndef IMGUI_DISABLE_DEFAULT_FONT
+static const char* GetDefaultCompressedFontDataTTF(int* out_size);
+#endif
 
 // Load embedded ProggyClean.ttf at size 13, disable oversampling
 ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
@@ -2592,9 +2592,10 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
     font_cfg.EllipsisChar = (ImWchar)0x0085;
     font_cfg.GlyphOffset.y = 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f);  // Add +1 offset per 13 units
 
-    const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();
+    int ttf_compressed_size = 0;
+    const char* ttf_compressed = GetDefaultCompressedFontDataTTF(&ttf_compressed_size);
     const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault();
-    ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges);
+    ImFont* font = AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg, glyph_ranges);
     return font;
 #else
     IM_ASSERT(0 && "AddFontDefault() disabled in this build.");
@@ -4583,102 +4584,185 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i
 // Download and more information at http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php
 //-----------------------------------------------------------------------------
 // File: 'ProggyClean.ttf' (41208 bytes)
-// Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding).
-// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size.
+// Exported using "misc/fonts/binary_to_compressed_c.exe ../ProggyClean.ttf proggy_clean_ttf_compressed (with compression, no base85 encoding).
 //-----------------------------------------------------------------------------
 
 #ifndef IMGUI_DISABLE_DEFAULT_FONT
-static const char proggy_clean_ttf_compressed_data_base85[11980 + 1] =
-    "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/"
-    "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;--VsM.M0rJfLH2eTM`*oJMHRC`N"
-    "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc."
-    "x]Ip.PH^'/aqUO/$1WxLoW0[iLAw=4h(9.`G"
-    "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[7MI2k).'2($5FNP&EQ(,)"
-    "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#"
-    "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM"
-    "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu"
-    "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/"
-    "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[Ket`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO"
-    "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%"
-    "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$MhLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]"
-    "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et"
-    "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:"
-    "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M"
-    "D?@f&1'BW-)Ju#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX("
-    "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs"
-    "bIu)'Z,*[>br5fX^:FPAWr-m2KgLQ_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q"
-    "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aege0jT6'N#(q%.O=?2S]u*(m<-"
-    "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i"
-    "sZ88+dKQ)W6>J%CL`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P	r+$%CE=68>K8r0=dSC%%(@p7"
-    ".m7jilQ02'0-VWAgTlGW'b)Tq7VT9q^*^$$.:&N@@"
-    "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*"
-    "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u"
-    "@-W$U%VEQ/,,>>#)D#%8cY#YZ?=,`Wdxu/ae&#"
-    "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$so8lKN%5/$(vdfq7+ebA#"
-    "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8"
-    "6e%B/:=>)N4xeW.*wft-;$'58-ESqr#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#"
-    "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#SfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5"
-    "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%"
-    "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;"
-    "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmLq9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:"
-    "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3$U4O]GKx'm9)b@p7YsvK3w^YR-"
-    "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*"
-    "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdFTi1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-"
-    "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj"
-    "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa"
-    ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>"
-    "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I"
-    "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)"
-    "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo"
-    "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P"
-    "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*'IAO"
-    "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#"
-    ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T"
-    "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4"
-    "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#"
-    "/QHC#3^ZC#7jmC#;v)D#?,)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP"
-    "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp"
-    "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#";
-
-static const char* GetDefaultCompressedFontDataTTFBase85()
+static const unsigned int proggy_clean_ttf_compressed_size = 9583;
+static const unsigned char proggy_clean_ttf_compressed_data[9583] =
 {
-    return proggy_clean_ttf_compressed_data_base85;
+    87,188,0,0,0,0,0,0,0,0,160,248,0,4,0,0,55,0,1,0,0,0,12,0,128,0,3,0,64,79,83,47,50,136,235,116,144,0,0,1,72,130,21,44,78,99,109,97,112,2,18,35,117,0,0,3,160,130,19,36,82,99,118,116,
+    32,130,23,130,2,33,4,252,130,4,56,2,103,108,121,102,18,175,137,86,0,0,7,4,0,0,146,128,104,101,97,100,215,145,102,211,130,27,32,204,130,3,33,54,104,130,16,39,8,66,1,195,0,0,1,4,130,
+    15,59,36,104,109,116,120,138,0,126,128,0,0,1,152,0,0,2,6,108,111,99,97,140,115,176,216,0,0,5,130,30,41,2,4,109,97,120,112,1,174,0,218,130,31,32,40,130,16,44,32,110,97,109,101,37,89,
+    187,150,0,0,153,132,130,19,44,158,112,111,115,116,166,172,131,239,0,0,155,36,130,51,44,210,112,114,101,112,105,2,1,18,0,0,4,244,130,47,32,8,132,203,46,1,0,0,60,85,233,213,95,15,60,
+    245,0,3,8,0,131,0,34,183,103,119,130,63,43,0,0,189,146,166,215,0,0,254,128,3,128,131,111,130,241,33,2,0,133,0,32,1,130,65,38,192,254,64,0,0,3,128,131,16,130,5,32,1,131,7,138,3,33,2,
+    0,130,17,36,1,1,0,144,0,130,121,130,23,38,2,0,8,0,64,0,10,130,9,32,118,130,9,130,6,32,0,130,59,33,1,144,131,200,35,2,188,2,138,130,16,32,143,133,7,37,1,197,0,50,2,0,131,0,33,4,9,131,
+    5,145,3,43,65,108,116,115,0,64,0,0,32,172,8,0,131,0,35,5,0,1,128,131,77,131,3,33,3,128,191,1,33,1,128,130,184,35,0,0,128,0,130,3,131,11,32,1,130,7,33,0,128,131,1,32,1,136,9,32,0,132,
+    15,135,5,32,1,131,13,135,27,144,35,32,1,149,25,131,21,32,0,130,0,32,128,132,103,130,35,132,39,32,0,136,45,136,97,133,17,130,5,33,0,0,136,19,34,0,128,1,133,13,133,5,32,128,130,15,132,
+    131,32,3,130,5,32,3,132,27,144,71,32,0,133,27,130,29,130,31,136,29,131,63,131,3,65,63,5,132,5,132,205,130,9,33,0,0,131,9,137,119,32,3,132,19,138,243,130,55,32,1,132,35,135,19,131,201,
+    136,11,132,143,137,13,130,41,32,0,131,3,144,35,33,128,0,135,1,131,223,131,3,141,17,134,13,136,63,134,15,136,53,143,15,130,96,33,0,3,131,4,130,3,34,28,0,1,130,5,34,0,0,76,130,17,131,
+    9,36,28,0,4,0,48,130,17,46,8,0,8,0,2,0,0,0,127,0,255,32,172,255,255,130,9,34,0,0,129,132,9,130,102,33,223,213,134,53,132,22,33,1,6,132,6,64,4,215,32,129,165,216,39,177,0,1,141,184,
+    1,255,133,134,45,33,198,0,193,1,8,190,244,1,28,1,158,2,20,2,136,2,252,3,20,3,88,3,156,3,222,4,20,4,50,4,80,4,98,4,162,5,22,5,102,5,188,6,18,6,116,6,214,7,56,7,126,7,236,8,78,8,108,
+    8,150,8,208,9,16,9,74,9,136,10,22,10,128,11,4,11,86,11,200,12,46,12,130,12,234,13,94,13,164,13,234,14,80,14,150,15,40,15,176,16,18,16,116,16,224,17,82,17,182,18,4,18,110,18,196,19,
+    76,19,172,19,246,20,88,20,174,20,234,21,64,21,128,21,166,21,184,22,18,22,126,22,198,23,52,23,142,23,224,24,86,24,186,24,238,25,54,25,150,25,212,26,72,26,156,26,240,27,92,27,200,28,
+    4,28,76,28,150,28,234,29,42,29,146,29,210,30,64,30,142,30,224,31,36,31,118,31,166,31,166,32,16,130,1,52,46,32,138,32,178,32,200,33,20,33,116,33,152,33,238,34,98,34,134,35,12,130,1,
+    33,128,35,131,1,60,152,35,176,35,216,36,0,36,74,36,104,36,144,36,174,37,6,37,96,37,130,37,248,37,248,38,88,38,170,130,1,8,190,216,39,64,39,154,40,10,40,104,40,168,41,14,41,32,41,184,
+    41,248,42,54,42,96,42,96,43,2,43,42,43,94,43,172,43,230,44,32,44,52,44,154,45,40,45,92,45,120,45,170,45,232,46,38,46,166,47,38,47,182,47,244,48,94,48,200,49,62,49,180,50,30,50,158,
+    51,30,51,130,51,238,52,92,52,206,53,58,53,134,53,212,54,38,54,114,54,230,55,118,55,216,56,58,56,166,57,18,57,116,57,174,58,46,58,154,59,6,59,124,59,232,60,58,60,150,61,34,61,134,61,
+    236,62,86,62,198,63,42,63,154,64,18,64,106,64,208,65,54,65,162,66,8,66,64,66,122,66,184,66,240,67,98,67,204,68,42,68,138,68,238,69,88,69,182,69,226,70,84,70,180,71,20,71,122,71,218,
+    72,84,72,198,73,64,0,36,70,21,8,8,77,3,0,7,0,11,0,15,0,19,0,23,0,27,0,31,0,35,0,39,0,43,0,47,0,51,0,55,0,59,0,63,0,67,0,71,0,75,0,79,0,83,0,87,0,91,0,95,0,99,0,103,0,107,0,111,0,115,
+    0,119,0,123,0,127,0,131,0,135,0,139,0,143,0,0,17,53,51,21,49,150,3,32,5,130,23,32,33,130,3,211,7,151,115,32,128,133,0,37,252,128,128,2,128,128,190,5,133,74,32,4,133,6,206,5,42,0,7,
+    1,128,0,0,2,0,4,0,0,65,139,13,37,0,1,53,51,21,7,146,3,32,3,130,19,32,1,141,133,32,3,141,14,131,13,38,255,0,128,128,0,6,1,130,84,35,2,128,4,128,140,91,132,89,32,51,65,143,6,139,7,33,
+    1,0,130,57,32,254,130,3,32,128,132,4,32,4,131,14,138,89,35,0,0,24,0,130,0,33,3,128,144,171,66,55,33,148,115,65,187,19,32,5,130,151,143,155,163,39,32,1,136,182,32,253,134,178,132,7,
+    132,200,145,17,32,3,65,48,17,165,17,39,0,0,21,0,128,255,128,3,65,175,17,65,3,27,132,253,131,217,139,201,155,233,155,27,131,67,131,31,130,241,33,255,0,131,181,137,232,132,15,132,4,138,
+    247,34,255,0,128,179,238,32,0,130,0,32,20,65,239,48,33,0,19,67,235,10,32,51,65,203,14,65,215,11,32,7,154,27,135,39,32,33,130,35,33,128,128,130,231,32,253,132,231,32,128,132,232,34,
+    128,128,254,133,13,136,8,32,253,65,186,5,130,36,130,42,176,234,133,231,34,128,0,0,66,215,44,33,0,1,68,235,6,68,211,19,32,49,68,239,14,139,207,139,47,66,13,7,32,51,130,47,33,1,0,130,
+    207,35,128,128,1,0,131,222,131,5,130,212,130,6,131,212,32,0,130,10,133,220,130,233,130,226,32,254,133,255,178,233,39,3,1,128,3,0,2,0,4,68,15,7,68,99,12,130,89,130,104,33,128,4,133,
+    93,130,10,38,0,0,11,1,0,255,0,68,63,16,70,39,9,66,215,8,32,7,68,77,6,68,175,14,32,29,68,195,6,132,7,35,2,0,128,255,131,91,132,4,65,178,5,141,111,67,129,23,165,135,140,107,142,135,33,
+    21,5,69,71,6,131,7,33,1,0,140,104,132,142,130,4,137,247,140,30,68,255,12,39,11,0,128,0,128,3,0,3,69,171,15,67,251,7,65,15,8,66,249,11,65,229,7,67,211,7,66,13,7,35,1,128,128,254,133,
+    93,32,254,131,145,132,4,132,18,32,2,151,128,130,23,34,0,0,9,154,131,65,207,8,68,107,15,68,51,7,32,7,70,59,7,135,121,130,82,32,128,151,111,41,0,0,4,0,128,255,0,1,128,1,137,239,33,0,
+    37,70,145,10,65,77,10,65,212,14,37,0,0,0,5,0,128,66,109,5,70,123,10,33,0,19,72,33,18,133,237,70,209,11,33,0,2,130,113,137,119,136,115,33,1,0,133,43,130,5,34,0,0,10,69,135,6,70,219,
+    13,66,155,7,65,9,12,66,157,11,66,9,11,32,7,130,141,132,252,66,151,9,137,9,66,15,30,36,0,20,0,128,0,130,218,71,11,42,68,51,8,65,141,7,73,19,15,69,47,23,143,39,66,81,7,32,1,66,55,6,34,
+    1,128,128,68,25,5,69,32,6,137,6,136,25,32,254,131,42,32,3,66,88,26,148,26,32,0,130,0,32,14,164,231,70,225,12,66,233,7,67,133,19,71,203,15,130,161,32,255,130,155,32,254,139,127,134,
+    12,164,174,33,0,15,164,159,33,59,0,65,125,20,66,25,7,32,5,68,191,6,66,29,7,144,165,65,105,9,35,128,128,255,0,137,2,133,182,164,169,33,128,128,197,171,130,155,68,235,7,32,21,70,77,19,
+    66,21,10,68,97,8,66,30,5,66,4,43,34,0,17,0,71,19,41,65,253,20,71,25,23,65,91,15,65,115,7,34,2,128,128,66,9,8,130,169,33,1,0,66,212,13,132,28,72,201,43,35,0,0,0,18,66,27,38,76,231,5,
+    68,157,20,135,157,32,7,68,185,13,65,129,28,66,20,5,32,253,66,210,11,65,128,49,133,61,32,0,65,135,6,74,111,37,72,149,12,66,203,19,65,147,19,68,93,7,68,85,8,76,4,5,33,255,0,133,129,34,
+    254,0,128,68,69,8,181,197,34,0,0,12,65,135,32,65,123,20,69,183,27,133,156,66,50,5,72,87,10,67,137,32,33,0,19,160,139,78,251,13,68,55,20,67,119,19,65,91,36,69,177,15,32,254,143,16,65,
+    98,53,32,128,130,0,32,0,66,43,54,70,141,23,66,23,15,131,39,69,47,11,131,15,70,129,19,74,161,9,36,128,255,0,128,254,130,153,65,148,32,67,41,9,34,0,0,4,79,15,5,73,99,10,71,203,8,32,3,
+    72,123,6,72,43,8,32,2,133,56,131,99,130,9,34,0,0,6,72,175,5,73,159,14,144,63,135,197,132,189,133,66,33,255,0,73,6,7,70,137,12,35,0,0,0,10,130,3,73,243,25,67,113,12,65,73,7,69,161,7,
+    138,7,37,21,2,0,128,128,254,134,3,73,116,27,33,128,128,130,111,39,12,0,128,1,0,3,128,2,72,219,21,35,43,0,47,0,67,47,20,130,111,33,21,1,68,167,13,81,147,8,133,230,32,128,77,73,6,32,
+    128,131,142,134,18,130,6,32,255,75,18,12,131,243,37,128,0,128,3,128,3,74,231,21,135,123,32,29,134,107,135,7,32,21,74,117,7,135,7,134,96,135,246,74,103,23,132,242,33,0,10,67,151,28,
+    67,133,20,66,141,11,131,11,32,3,77,71,6,32,128,130,113,32,1,81,4,6,134,218,66,130,24,131,31,34,0,26,0,130,0,77,255,44,83,15,11,148,155,68,13,7,32,49,78,231,18,79,7,11,73,243,11,32,
+    33,65,187,10,130,63,65,87,8,73,239,19,35,0,128,1,0,131,226,32,252,65,100,6,32,128,139,8,33,1,0,130,21,32,253,72,155,44,73,255,20,32,128,71,67,8,81,243,39,67,15,20,74,191,23,68,121,
+    27,32,1,66,150,6,32,254,79,19,11,131,214,32,128,130,215,37,2,0,128,253,0,128,136,5,65,220,24,147,212,130,210,33,0,24,72,219,42,84,255,13,67,119,16,69,245,19,72,225,19,65,3,15,69,93,
+    19,131,55,132,178,71,115,14,81,228,6,142,245,33,253,0,132,43,172,252,65,16,11,75,219,8,65,219,31,66,223,24,75,223,10,33,29,1,80,243,10,66,175,8,131,110,134,203,133,172,130,16,70,30,
+    7,164,183,130,163,32,20,65,171,48,65,163,36,65,143,23,65,151,19,65,147,13,65,134,17,133,17,130,216,67,114,5,164,217,65,137,12,72,147,48,79,71,19,74,169,22,80,251,8,65,173,7,66,157,
+    15,74,173,15,32,254,65,170,8,71,186,45,72,131,6,77,143,40,187,195,152,179,65,123,38,68,215,57,68,179,15,65,85,7,69,187,14,32,21,66,95,15,67,19,25,32,1,83,223,6,32,2,76,240,7,77,166,
+    43,65,8,5,130,206,32,0,67,39,54,143,167,66,255,19,82,193,11,151,47,85,171,5,67,27,17,132,160,69,172,11,69,184,56,66,95,6,33,12,1,130,237,32,2,68,179,27,68,175,16,80,135,15,72,55,7,
+    71,87,12,73,3,12,132,12,66,75,32,76,215,5,169,139,147,135,148,139,81,12,12,81,185,36,75,251,7,65,23,27,76,215,9,87,165,12,65,209,15,72,157,7,65,245,31,32,128,71,128,6,32,1,82,125,5,
+    34,0,128,254,131,169,32,254,131,187,71,180,9,132,27,32,2,88,129,44,32,0,78,47,40,65,79,23,79,171,14,32,21,71,87,8,72,15,14,65,224,33,130,139,74,27,62,93,23,7,68,31,7,75,27,7,139,15,
+    74,3,7,74,23,27,65,165,11,65,177,15,67,123,5,32,1,130,221,32,252,71,96,5,74,12,12,133,244,130,25,34,1,0,128,130,2,139,8,93,26,8,65,9,32,65,57,14,140,14,32,0,73,79,67,68,119,11,135,
+    11,32,51,90,75,14,139,247,65,43,7,131,19,139,11,69,159,11,65,247,6,36,1,128,128,253,0,90,71,9,33,1,0,132,14,32,128,89,93,14,69,133,6,130,44,131,30,131,6,65,20,56,33,0,16,72,179,40,
+    75,47,12,65,215,19,74,95,19,65,43,11,131,168,67,110,5,75,23,17,69,106,6,75,65,5,71,204,43,32,0,80,75,47,71,203,15,159,181,68,91,11,67,197,7,73,101,13,68,85,6,33,128,128,130,214,130,
+    25,32,254,74,236,48,130,194,37,0,18,0,128,255,128,77,215,40,65,139,64,32,51,80,159,10,65,147,39,130,219,84,212,43,130,46,75,19,97,74,33,11,65,201,23,65,173,31,33,1,0,79,133,6,66,150,
+    5,67,75,48,85,187,6,70,207,37,32,71,87,221,13,73,163,14,80,167,15,132,15,83,193,19,82,209,8,78,99,9,72,190,11,77,110,49,89,63,5,80,91,35,99,63,32,70,235,23,81,99,10,69,148,10,65,110,
+    36,32,0,65,99,47,95,219,11,68,171,51,66,87,7,72,57,7,74,45,17,143,17,65,114,50,33,14,0,65,111,40,159,195,98,135,15,35,7,53,51,21,100,78,9,95,146,16,32,254,82,114,6,32,128,67,208,37,
+    130,166,99,79,58,32,17,96,99,14,72,31,19,72,87,31,82,155,7,67,47,14,32,21,131,75,134,231,72,51,17,72,78,8,133,8,80,133,6,33,253,128,88,37,9,66,124,36,72,65,12,134,12,71,55,43,66,139,
+    27,85,135,10,91,33,12,65,35,11,66,131,11,71,32,8,90,127,6,130,244,71,76,11,168,207,33,0,12,66,123,32,32,0,65,183,15,68,135,11,66,111,7,67,235,11,66,111,15,32,254,97,66,12,160,154,67,
+    227,52,80,33,15,87,249,15,93,45,31,75,111,12,93,45,11,77,99,9,160,184,81,31,12,32,15,98,135,30,104,175,7,77,249,36,69,73,15,78,5,12,32,254,66,151,19,34,128,128,4,87,32,12,149,35,133,
+    21,96,151,31,32,19,72,35,5,98,173,15,143,15,32,21,143,99,158,129,33,0,0,65,35,52,65,11,15,147,15,98,75,11,33,1,0,143,151,132,15,32,254,99,200,37,132,43,130,4,39,0,10,0,128,1,128,3,
+    0,104,151,14,97,187,20,69,131,15,67,195,11,87,227,7,33,128,128,132,128,33,254,0,68,131,9,65,46,26,42,0,0,0,7,0,0,255,128,3,128,0,88,223,15,33,0,21,89,61,22,66,209,12,65,2,12,37,0,2,
+    1,0,3,128,101,83,8,36,0,1,53,51,29,130,3,34,21,1,0,66,53,8,32,0,68,215,6,100,55,25,107,111,9,66,193,11,72,167,8,73,143,31,139,31,33,1,0,131,158,32,254,132,5,33,253,128,65,16,9,133,
+    17,89,130,25,141,212,33,0,0,93,39,8,90,131,25,93,39,14,66,217,6,106,179,8,159,181,71,125,15,139,47,138,141,87,11,14,76,23,14,65,231,26,140,209,66,122,8,81,179,5,101,195,26,32,47,74,
+    75,13,69,159,11,83,235,11,67,21,16,136,167,131,106,130,165,130,15,32,128,101,90,24,134,142,32,0,65,103,51,108,23,11,101,231,15,75,173,23,74,237,23,66,15,6,66,46,17,66,58,17,65,105,
+    49,66,247,55,71,179,12,70,139,15,86,229,7,84,167,15,32,1,95,72,12,89,49,6,33,128,128,65,136,38,66,30,9,32,0,100,239,7,66,247,29,70,105,20,65,141,19,69,81,15,130,144,32,128,83,41,5,
+    32,255,131,177,68,185,5,133,126,65,97,37,32,0,130,0,33,21,0,130,55,66,195,28,67,155,13,34,79,0,83,66,213,13,73,241,19,66,59,19,65,125,11,135,201,66,249,16,32,128,66,44,11,66,56,17,
+    68,143,8,68,124,38,67,183,12,96,211,9,65,143,29,112,171,5,32,0,68,131,63,34,33,53,51,71,121,11,32,254,98,251,16,32,253,74,231,10,65,175,37,133,206,37,0,0,8,1,0,0,107,123,11,113,115,
+    9,33,0,1,130,117,131,3,73,103,7,66,51,18,66,44,5,133,75,70,88,5,32,254,65,39,12,68,80,9,34,12,0,128,107,179,28,68,223,6,155,111,86,147,15,32,2,131,82,141,110,33,254,0,130,15,32,4,103,
+    184,15,141,35,87,176,5,83,11,5,71,235,23,114,107,11,65,189,16,70,33,15,86,153,31,135,126,86,145,30,65,183,41,32,0,130,0,32,10,65,183,24,34,35,0,39,67,85,9,65,179,15,143,15,33,1,0,65,
+    28,17,157,136,130,123,32,20,130,3,32,0,97,135,24,115,167,19,80,71,12,32,51,110,163,14,78,35,19,131,19,155,23,77,229,8,78,9,17,151,17,67,231,46,94,135,8,73,31,31,93,215,56,82,171,25,
+    72,77,8,162,179,169,167,99,131,11,69,85,19,66,215,15,76,129,13,68,115,22,72,79,35,67,113,5,34,0,0,19,70,31,46,65,89,52,73,223,15,85,199,33,95,33,8,132,203,73,29,32,67,48,16,177,215,
+    101,13,15,65,141,43,69,141,15,75,89,5,70,0,11,70,235,21,178,215,36,10,0,128,0,0,71,207,24,33,0,19,100,67,6,80,215,11,66,67,7,80,43,12,71,106,7,80,192,5,65,63,5,66,217,26,33,0,13,156,
+    119,68,95,5,72,233,12,134,129,85,81,11,76,165,20,65,43,8,73,136,8,75,10,31,38,128,128,0,0,0,13,1,130,4,32,3,106,235,29,114,179,12,66,131,23,32,7,77,133,6,67,89,12,131,139,116,60,9,
+    89,15,37,32,0,74,15,7,103,11,22,65,35,5,33,55,0,93,81,28,67,239,23,78,85,5,107,93,14,66,84,17,65,193,26,74,183,10,66,67,34,143,135,79,91,15,32,7,117,111,8,75,56,9,84,212,9,154,134,
+    32,0,130,0,32,18,130,3,70,171,41,83,7,16,70,131,19,84,191,15,84,175,19,84,167,30,84,158,12,154,193,68,107,15,33,0,0,65,79,42,65,71,7,73,55,7,118,191,16,83,180,9,32,255,76,166,9,154,
+    141,32,0,130,0,69,195,52,65,225,15,151,15,75,215,31,80,56,10,68,240,17,100,32,9,70,147,39,65,93,12,71,71,41,92,85,15,84,135,23,78,35,15,110,27,10,84,125,8,107,115,29,136,160,38,0,0,
+    14,0,128,255,0,82,155,24,67,239,8,119,255,11,69,131,11,77,29,6,112,31,8,134,27,105,203,8,32,2,75,51,11,75,195,12,74,13,29,136,161,37,128,0,0,0,11,1,130,163,82,115,8,125,191,17,69,35,
+    12,74,137,15,143,15,32,1,65,157,12,136,12,161,142,65,43,40,65,199,6,65,19,24,102,185,11,76,123,11,99,6,12,135,12,32,254,130,8,161,155,101,23,9,39,8,0,0,1,128,3,128,2,78,63,17,72,245,
+    12,67,41,11,90,167,9,32,128,97,49,9,32,128,109,51,14,132,97,81,191,8,130,97,125,99,12,121,35,9,127,75,15,71,79,12,81,151,23,87,97,7,70,223,15,80,245,16,105,97,15,32,254,113,17,6,32,
+    128,130,8,105,105,8,76,122,18,65,243,21,74,63,7,38,4,1,0,255,0,2,0,119,247,28,133,65,32,255,141,91,35,0,0,0,16,67,63,36,34,59,0,63,77,59,9,119,147,11,143,241,66,173,15,66,31,11,67,
+    75,8,81,74,16,32,128,131,255,87,181,42,127,43,5,34,255,128,2,120,235,11,37,19,0,23,0,0,37,109,191,14,118,219,7,127,43,14,65,79,14,35,0,0,0,3,73,91,5,130,5,38,3,0,7,0,11,0,0,70,205,
+    11,88,221,12,32,0,73,135,7,87,15,22,73,135,10,79,153,15,97,71,19,65,49,11,32,1,131,104,121,235,11,80,65,11,142,179,144,14,81,123,46,32,1,88,217,5,112,5,8,65,201,15,83,29,15,122,147,
+    11,135,179,142,175,143,185,67,247,39,66,199,7,35,5,0,128,3,69,203,15,123,163,12,67,127,7,130,119,71,153,10,141,102,70,175,8,32,128,121,235,30,136,89,100,191,11,116,195,11,111,235,15,
+    72,39,7,32,2,97,43,5,132,5,94,67,8,131,8,125,253,10,32,3,65,158,16,146,16,130,170,40,0,21,0,128,0,0,3,128,5,88,219,15,24,64,159,32,135,141,65,167,15,68,163,10,97,73,49,32,255,82,58,
+    7,93,80,8,97,81,16,24,67,87,52,34,0,0,5,130,231,33,128,2,80,51,13,65,129,8,113,61,6,132,175,65,219,5,130,136,77,152,17,32,0,95,131,61,70,215,6,33,21,51,90,53,10,78,97,23,105,77,31,
+    65,117,7,139,75,24,68,195,9,24,64,22,9,33,0,128,130,11,33,128,128,66,25,5,121,38,5,134,5,134,45,66,40,36,66,59,18,34,128,0,0,66,59,81,135,245,123,103,19,120,159,19,77,175,12,33,255,
+    0,87,29,10,94,70,21,66,59,54,39,3,1,128,3,0,2,128,4,24,65,7,15,66,47,7,72,98,12,37,0,0,0,3,1,0,24,65,55,21,131,195,32,1,67,178,6,33,4,0,77,141,8,32,6,131,47,74,67,16,24,69,3,20,24,
+    65,251,7,133,234,130,229,94,108,17,35,0,0,6,0,141,175,86,59,5,162,79,85,166,8,70,112,13,32,13,24,64,67,26,24,71,255,7,123,211,12,80,121,11,69,215,15,66,217,11,69,71,10,131,113,132,
+    126,119,90,9,66,117,19,132,19,32,0,130,0,24,64,47,59,33,7,0,73,227,5,68,243,15,85,13,12,76,37,22,74,254,15,130,138,33,0,4,65,111,6,137,79,65,107,16,32,1,77,200,6,34,128,128,3,75,154,
+    12,37,0,16,0,0,2,0,104,115,36,140,157,68,67,19,68,51,15,106,243,15,134,120,70,37,10,68,27,10,140,152,65,121,24,32,128,94,155,7,67,11,8,24,74,11,25,65,3,12,83,89,18,82,21,37,67,200,
+    5,130,144,24,64,172,12,33,4,0,134,162,74,80,14,145,184,32,0,130,0,69,251,20,32,19,81,243,5,82,143,8,33,5,53,89,203,5,133,112,79,109,15,33,0,21,130,71,80,175,41,36,75,0,79,0,83,121,
+    117,9,87,89,27,66,103,11,70,13,15,75,191,11,135,67,87,97,20,109,203,5,69,246,8,108,171,5,78,195,38,65,51,13,107,203,11,77,3,17,24,75,239,17,65,229,28,79,129,39,130,175,32,128,123,253,
+    7,132,142,24,65,51,15,65,239,41,36,128,128,0,0,13,65,171,5,66,163,28,136,183,118,137,11,80,255,15,67,65,7,74,111,8,32,0,130,157,32,253,24,76,35,10,103,212,5,81,175,9,69,141,7,66,150,
+    29,131,158,24,75,199,28,124,185,7,76,205,15,68,124,14,32,3,123,139,16,130,16,33,128,128,108,199,6,33,0,3,65,191,35,107,11,6,73,197,11,24,70,121,15,83,247,15,24,70,173,23,69,205,14,
+    32,253,131,140,32,254,136,4,94,198,9,32,3,78,4,13,66,127,13,143,13,32,0,130,0,33,16,0,24,69,59,39,109,147,12,76,253,19,24,69,207,15,69,229,15,130,195,71,90,10,139,10,130,152,73,43,
+    40,91,139,10,65,131,37,35,75,0,79,0,84,227,12,143,151,68,25,15,80,9,23,95,169,11,34,128,2,128,112,186,5,130,6,83,161,19,76,50,6,130,37,65,145,44,110,83,5,32,16,67,99,6,71,67,15,76,
+    55,17,140,215,67,97,23,76,69,15,77,237,11,104,211,23,77,238,11,65,154,43,33,0,10,83,15,28,83,13,20,67,145,19,67,141,14,97,149,21,68,9,15,86,251,5,66,207,5,66,27,37,82,1,23,127,71,12,
+    94,235,10,110,175,24,98,243,15,132,154,132,4,24,66,69,10,32,4,67,156,43,130,198,35,2,1,0,4,75,27,9,69,85,9,95,240,7,32,128,130,35,32,28,66,43,40,24,82,63,23,83,123,12,72,231,15,127,
+    59,23,116,23,19,117,71,7,24,77,99,15,67,111,15,71,101,8,36,2,128,128,252,128,127,60,11,32,1,132,16,130,18,141,24,67,107,9,32,3,68,194,15,175,15,38,0,11,0,128,1,128,2,80,63,25,32,0,
+    24,65,73,11,69,185,15,83,243,16,32,0,24,81,165,8,130,86,77,35,6,155,163,88,203,5,24,66,195,30,70,19,19,24,80,133,15,32,1,75,211,8,32,254,108,133,8,79,87,20,65,32,9,41,0,0,7,0,128,0,
+    0,2,128,2,68,87,15,66,1,16,92,201,16,24,76,24,17,133,17,34,128,0,30,66,127,64,34,115,0,119,73,205,9,66,43,11,109,143,15,24,79,203,11,90,143,15,131,15,155,31,65,185,15,86,87,11,35,128,
+    128,253,0,69,7,6,130,213,33,1,0,119,178,15,142,17,66,141,74,83,28,6,36,7,0,0,4,128,82,39,18,76,149,12,67,69,21,32,128,79,118,15,32,0,130,0,32,8,131,206,32,2,79,83,9,100,223,14,102,
+    113,23,115,115,7,24,65,231,12,130,162,32,4,68,182,19,130,102,93,143,8,69,107,29,24,77,255,12,143,197,72,51,7,76,195,15,132,139,85,49,15,130,152,131,18,71,81,23,70,14,11,36,0,10,0,128,
+    2,69,59,9,89,151,15,66,241,11,76,165,12,71,43,15,75,49,13,65,12,23,132,37,32,0,179,115,130,231,95,181,16,132,77,32,254,67,224,8,65,126,20,79,171,8,32,2,89,81,5,75,143,6,80,41,8,34,
+    2,0,128,24,81,72,9,32,0,130,0,35,17,0,0,255,77,99,39,95,65,36,67,109,15,24,69,93,11,77,239,5,95,77,23,35,128,1,0,128,24,86,7,8,132,167,32,2,69,198,41,130,202,33,0,26,120,75,44,24,89,
+    51,15,71,243,12,70,239,11,24,84,3,11,66,7,11,71,255,10,32,21,69,155,35,88,151,12,32,128,74,38,10,65,210,8,74,251,5,65,226,5,75,201,13,32,3,65,9,41,146,41,40,0,0,0,9,1,0,1,0,2,91,99,
+    19,32,35,106,119,13,70,219,15,83,239,12,137,154,32,2,67,252,19,36,128,0,0,4,1,130,196,32,2,130,8,91,107,8,32,0,135,81,24,73,211,8,132,161,73,164,13,36,0,8,0,128,2,105,123,26,139,67,
+    76,99,15,34,1,0,128,135,76,83,156,20,92,104,8,67,251,30,24,86,47,27,123,207,12,24,86,7,15,71,227,8,32,4,65,20,20,131,127,32,0,130,123,32,0,71,223,26,32,19,90,195,22,71,223,15,84,200,
+    6,32,128,133,241,24,84,149,9,67,41,25,36,0,0,0,22,0,88,111,49,32,87,66,21,5,77,3,27,123,75,7,71,143,19,135,183,71,183,19,130,171,74,252,5,131,5,89,87,17,32,1,132,18,130,232,68,11,10,
+    33,1,128,70,208,16,66,230,18,147,18,130,254,223,255,75,27,23,65,59,15,135,39,155,255,34,128,128,254,104,92,8,33,0,128,65,32,11,65,1,58,33,26,0,130,0,72,71,18,78,55,17,76,11,19,86,101,
+    12,75,223,11,89,15,11,24,76,87,15,75,235,15,131,15,72,95,7,85,71,11,72,115,11,73,64,6,34,1,128,128,66,215,9,34,128,254,128,134,14,33,128,255,67,102,5,32,0,130,16,70,38,11,66,26,57,
+    88,11,8,24,76,215,34,78,139,7,95,245,7,32,7,24,73,75,23,32,128,131,167,130,170,101,158,9,82,49,22,118,139,6,32,18,67,155,44,116,187,9,108,55,14,80,155,23,66,131,15,93,77,10,131,168,
+    32,128,73,211,12,24,75,187,22,32,4,96,71,20,67,108,19,132,19,120,207,8,32,5,76,79,15,66,111,21,66,95,8,32,3,190,211,111,3,8,211,212,32,20,65,167,44,34,75,0,79,97,59,13,32,33,112,63,
+    10,65,147,19,69,39,19,143,39,24,66,71,9,130,224,65,185,43,94,176,12,65,183,24,71,38,8,24,72,167,7,65,191,38,136,235,24,96,167,12,65,203,62,115,131,13,65,208,42,175,235,67,127,6,32,
+    4,76,171,29,114,187,5,32,71,65,211,5,65,203,68,72,51,8,164,219,32,0,172,214,71,239,58,78,3,27,66,143,15,77,19,15,147,31,35,33,53,51,21,66,183,10,173,245,66,170,30,150,30,34,0,0,23,
+    80,123,54,76,1,16,73,125,15,82,245,11,167,253,24,76,85,12,70,184,5,32,254,131,185,37,254,0,128,1,0,128,133,16,117,158,18,92,27,38,65,3,17,130,251,35,17,0,128,254,24,69,83,39,140,243,
+    121,73,19,109,167,7,81,41,15,24,95,175,12,102,227,15,121,96,11,24,95,189,7,32,3,145,171,154,17,24,77,47,9,33,0,5,70,71,37,68,135,7,32,29,117,171,11,69,87,15,24,79,97,19,24,79,149,23,
+    131,59,32,1,75,235,5,72,115,11,72,143,7,132,188,71,27,46,131,51,32,0,69,95,6,175,215,32,21,131,167,81,15,19,151,191,151,23,131,215,71,43,5,32,254,24,79,164,24,74,109,8,77,166,13,65,
+    176,26,88,162,5,98,159,6,171,219,120,247,6,79,29,8,99,169,10,103,59,19,65,209,35,131,35,91,25,19,112,94,15,83,36,8,173,229,33,20,0,88,75,43,71,31,12,65,191,71,33,1,0,130,203,32,254,
+    131,4,68,66,7,67,130,6,104,61,13,173,215,38,13,1,0,0,0,2,128,67,111,28,74,129,16,104,35,19,79,161,16,87,14,7,138,143,132,10,67,62,36,114,115,5,162,151,67,33,16,108,181,15,143,151,67,
+    5,5,24,100,242,15,170,153,34,0,0,14,65,51,34,32,55,79,75,9,32,51,74,7,10,65,57,38,132,142,32,254,72,0,14,139,163,32,128,80,254,8,67,158,21,65,63,7,32,4,72,227,27,95,155,12,67,119,19,
+    124,91,24,149,154,72,177,34,97,223,8,155,151,24,108,227,15,88,147,16,72,117,19,68,35,11,92,253,15,70,199,15,24,87,209,17,32,2,87,233,7,32,1,24,88,195,10,119,24,8,32,3,81,227,24,65,
+    125,21,35,128,128,0,25,76,59,48,24,90,187,9,97,235,12,66,61,11,91,105,19,24,79,141,11,24,79,117,15,24,79,129,27,90,53,13,130,13,32,253,131,228,24,79,133,40,69,70,8,66,137,31,65,33,
+    19,96,107,8,68,119,29,66,7,5,68,125,16,65,253,19,65,241,27,24,90,179,13,24,79,143,18,33,128,128,130,246,32,254,130,168,68,154,36,77,51,9,97,47,5,167,195,32,21,131,183,78,239,27,155,
+    195,78,231,14,201,196,77,11,6,32,5,73,111,37,97,247,12,77,19,31,155,207,78,215,19,162,212,69,17,14,66,91,19,80,143,57,78,203,39,159,215,32,128,93,134,8,24,80,109,24,66,113,15,169,215,
+    66,115,6,32,4,69,63,33,32,0,101,113,7,86,227,35,143,211,36,49,53,51,21,1,77,185,14,65,159,28,69,251,34,67,56,8,33,9,0,24,107,175,25,90,111,12,110,251,11,119,189,24,119,187,34,87,15,
+    9,32,4,66,231,37,90,39,7,66,239,8,84,219,15,69,105,23,24,85,27,27,87,31,11,33,1,128,76,94,6,32,1,85,241,7,33,128,128,106,48,10,33,128,128,69,136,11,133,13,24,79,116,49,84,236,8,24,
+    91,87,9,32,5,165,255,69,115,12,66,27,15,159,15,24,72,247,12,74,178,5,24,80,64,15,33,0,128,143,17,77,89,51,130,214,24,81,43,7,170,215,74,49,8,159,199,143,31,139,215,69,143,5,32,254,
+    24,81,50,35,181,217,84,123,70,143,195,159,15,65,187,16,66,123,7,65,175,15,65,193,29,68,207,39,79,27,5,70,131,6,32,4,68,211,33,33,67,0,83,143,14,159,207,143,31,140,223,33,0,128,24,80,
+    82,14,24,93,16,23,32,253,65,195,5,68,227,40,133,214,107,31,7,32,5,67,115,27,87,9,8,107,31,43,66,125,6,32,0,103,177,23,131,127,72,203,36,32,0,110,103,8,155,163,73,135,6,32,19,24,112,
+    99,10,65,71,11,73,143,19,143,31,126,195,5,24,85,21,9,24,76,47,14,32,254,24,93,77,36,68,207,11,39,25,0,0,255,128,3,128,4,66,51,37,95,247,13,82,255,24,76,39,19,147,221,66,85,27,24,118,
+    7,8,24,74,249,12,76,74,8,91,234,8,67,80,17,131,222,33,253,0,121,30,44,73,0,16,69,15,6,32,0,65,23,38,69,231,12,65,179,6,98,131,16,86,31,27,24,108,157,14,80,160,8,24,65,46,17,33,4,0,
+    96,2,18,144,191,65,226,8,68,19,5,171,199,80,9,15,180,199,67,89,5,32,255,24,79,173,28,174,201,24,79,179,50,32,1,24,122,5,10,82,61,10,180,209,83,19,8,32,128,24,80,129,27,111,248,43,131,
+    71,24,115,103,8,67,127,41,78,213,24,100,247,19,66,115,39,75,107,5,32,254,165,219,78,170,40,24,112,163,49,32,1,97,203,6,65,173,64,32,0,83,54,7,133,217,88,37,12,32,254,131,28,33,128,
+    3,67,71,44,84,183,6,32,5,69,223,33,96,7,7,123,137,16,192,211,24,112,14,9,32,255,67,88,29,68,14,10,84,197,38,33,0,22,116,47,50,32,87,106,99,9,116,49,15,89,225,15,97,231,23,70,41,19,
+    82,85,8,93,167,6,32,253,132,236,108,190,7,89,251,5,116,49,58,33,128,128,131,234,32,15,24,74,67,38,70,227,24,24,83,45,23,89,219,12,70,187,12,89,216,19,32,2,69,185,24,141,24,70,143,66,
+    24,82,119,56,78,24,10,32,253,133,149,132,6,24,106,233,7,69,198,48,178,203,81,243,12,68,211,15,106,255,23,66,91,15,69,193,7,100,39,10,24,83,72,16,176,204,33,19,0,88,207,45,68,21,12,
+    68,17,10,65,157,53,68,17,6,32,254,92,67,10,65,161,25,69,182,43,24,118,91,47,69,183,18,181,209,111,253,12,89,159,8,66,112,12,69,184,45,35,0,0,0,9,24,80,227,26,73,185,16,118,195,15,131,
+    15,33,1,0,65,59,15,66,39,27,160,111,66,205,12,148,111,143,110,33,128,128,156,112,24,81,199,8,75,199,23,66,117,20,155,121,32,254,68,126,12,72,213,29,134,239,149,123,89,27,16,148,117,
+    65,245,8,24,71,159,14,141,134,134,28,73,51,55,109,77,15,105,131,11,68,67,11,76,169,27,107,209,12,102,174,8,32,128,72,100,18,116,163,56,79,203,11,75,183,44,85,119,19,71,119,23,151,227,
+    32,1,93,27,8,65,122,5,77,102,8,110,120,20,66,23,8,66,175,17,66,63,12,133,12,79,35,8,74,235,33,67,149,16,69,243,15,78,57,15,69,235,16,67,177,7,151,192,130,23,67,84,29,141,192,174,187,
+    77,67,15,69,11,12,159,187,77,59,10,199,189,24,70,235,50,96,83,19,66,53,23,105,65,19,77,47,12,163,199,66,67,37,78,207,50,67,23,23,174,205,67,228,6,71,107,13,67,22,14,66,85,11,83,187,
+    38,124,47,49,95,7,19,66,83,23,67,23,19,24,96,78,17,80,101,16,71,98,40,33,0,7,88,131,22,24,89,245,12,84,45,12,102,213,5,123,12,9,32,2,126,21,14,43,255,0,128,128,0,0,20,0,128,255,128,
+    3,126,19,39,32,75,106,51,7,113,129,15,24,110,135,19,126,47,15,115,117,11,69,47,11,32,2,109,76,9,102,109,9,32,128,75,2,10,130,21,32,254,69,47,6,32,3,94,217,47,32,0,65,247,10,69,15,46,
+    65,235,31,65,243,15,101,139,10,66,174,14,65,247,16,72,102,28,69,17,14,84,243,9,165,191,88,47,48,66,53,12,32,128,71,108,6,203,193,32,17,75,187,42,73,65,16,65,133,52,114,123,9,167,199,
+    69,21,37,86,127,44,75,171,11,180,197,78,213,12,148,200,81,97,46,24,95,243,9,32,4,66,75,33,113,103,9,87,243,36,143,225,24,84,27,31,90,145,8,148,216,67,49,5,24,84,34,14,75,155,27,67,
+    52,13,140,13,36,0,20,0,128,255,24,135,99,46,88,59,43,155,249,80,165,7,136,144,71,161,23,32,253,132,33,32,254,88,87,44,136,84,35,128,0,0,21,81,103,5,94,47,44,76,51,12,143,197,151,15,
+    65,215,31,24,64,77,13,65,220,20,65,214,14,71,4,40,65,213,13,32,0,130,0,35,21,1,2,0,135,0,34,36,0,72,134,10,36,1,0,26,0,130,134,11,36,2,0,14,0,108,134,11,32,3,138,23,32,4,138,11,34,
+    5,0,20,134,33,34,0,0,6,132,23,32,1,134,15,32,18,130,25,133,11,37,1,0,13,0,49,0,133,11,36,2,0,7,0,38,134,11,36,3,0,17,0,45,134,11,32,4,138,35,36,5,0,10,0,62,134,23,32,6,132,23,36,3,
+    0,1,4,9,130,87,131,167,133,11,133,167,133,11,133,167,133,11,37,3,0,34,0,122,0,133,11,133,167,133,11,133,167,133,11,133,167,34,50,0,48,130,1,34,52,0,47,134,5,8,49,49,0,53,98,121,32,
+    84,114,105,115,116,97,110,32,71,114,105,109,109,101,114,82,101,103,117,108,97,114,84,84,88,32,80,114,111,103,103,121,67,108,101,97,110,84,84,50,48,48,52,47,130,2,53,49,53,0,98,0,121,
+    0,32,0,84,0,114,0,105,0,115,0,116,0,97,0,110,130,15,32,71,132,15,36,109,0,109,0,101,130,9,32,82,130,5,36,103,0,117,0,108,130,29,32,114,130,43,34,84,0,88,130,35,32,80,130,25,34,111,
+    0,103,130,1,34,121,0,67,130,27,32,101,132,59,32,84,130,31,33,0,0,65,155,9,34,20,0,0,65,11,6,130,8,135,2,33,1,1,130,9,8,120,1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9,1,10,1,11,1,12,1,13,1,14,
+    1,15,1,16,1,17,1,18,1,19,1,20,1,21,1,22,1,23,1,24,1,25,1,26,1,27,1,28,1,29,1,30,1,31,1,32,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,
+    22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,130,187,8,66,33,0,34,0,35,0,36,0,37,0,38,0,39,0,40,0,41,0,42,0,43,0,44,0,45,0,46,0,47,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0,
+    57,0,58,0,59,0,60,0,61,0,62,0,63,0,64,0,65,0,66,130,243,9,75,68,0,69,0,70,0,71,0,72,0,73,0,74,0,75,0,76,0,77,0,78,0,79,0,80,0,81,0,82,0,83,0,84,0,85,0,86,0,87,0,88,0,89,0,90,0,91,0,
+    92,0,93,0,94,0,95,0,96,0,97,1,33,1,34,1,35,1,36,1,37,1,38,1,39,1,40,1,41,1,42,1,43,1,44,1,45,1,46,1,47,1,48,1,49,1,50,1,51,1,52,1,53,1,54,1,55,1,56,1,57,1,58,1,59,1,60,1,61,1,62,1,
+    63,1,64,1,65,0,172,0,163,0,132,0,133,0,189,0,150,0,232,0,134,0,142,0,139,0,157,0,169,0,164,0,239,0,138,0,218,0,131,0,147,0,242,0,243,0,141,0,151,0,136,0,195,0,222,0,241,0,158,0,170,
+    0,245,0,244,0,246,0,162,0,173,0,201,0,199,0,174,0,98,0,99,0,144,0,100,0,203,0,101,0,200,0,202,0,207,0,204,0,205,0,206,0,233,0,102,0,211,0,208,0,209,0,175,0,103,0,240,0,145,0,214,0,
+    212,0,213,0,104,0,235,0,237,0,137,0,106,0,105,0,107,0,109,0,108,0,110,0,160,0,111,0,113,0,112,0,114,0,115,0,117,0,116,0,118,0,119,0,234,0,120,0,122,0,121,0,123,0,125,0,124,0,184,0,
+    161,0,127,0,126,0,128,0,129,0,236,0,238,0,186,14,117,110,105,99,111,100,101,35,48,120,48,48,48,49,141,14,32,50,141,14,32,51,141,14,32,52,141,14,32,53,141,14,32,54,141,14,32,55,141,
+    14,32,56,141,14,32,57,141,14,32,97,141,14,32,98,141,14,32,99,141,14,32,100,141,14,32,101,141,14,32,102,140,14,33,49,48,141,14,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,
+    141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,32,49,141,239,45,49,102,6,100,101,108,101,116,101,4,69,117,114,
+    111,140,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,32,56,141,236,
+    32,56,141,236,32,56,141,236,32,56,65,220,13,32,57,65,220,13,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,
+    239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,35,57,102,0,0,5,250,72,249,98,247,
+};
+
+static const char* GetDefaultCompressedFontDataTTF(int* out_size)
+{
+    *out_size = proggy_clean_ttf_compressed_size;
+    return (const char*)proggy_clean_ttf_compressed_data;
 }
 #endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT
 
diff --git a/misc/fonts/binary_to_compressed_c.cpp b/misc/fonts/binary_to_compressed_c.cpp
index f41d20f75..f16c3b2c3 100644
--- a/misc/fonts/binary_to_compressed_c.cpp
+++ b/misc/fonts/binary_to_compressed_c.cpp
@@ -113,21 +113,42 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b
         }
         fprintf(out, "\";\n\n");
     }
+#if 0
     else
     {
+        // As individual bytes, not subject to endianness issues.
+        fprintf(out, "%sconst unsigned int %s_%ssize = %d;\n", static_str, symbol, compressed_str, (int)compressed_sz);
+        fprintf(out, "%sconst unsigned char %s_%sdata[%d] =\n{", static_str, symbol, compressed_str, (int)compressed_sz);
+        int column = 0;
+        for (int i = 0; i < compressed_sz; i++)
+        {
+            unsigned char d = *(unsigned char*)(compressed + i);
+            if (column == 0)
+                fprintf(out, "\n    ");
+            column += fprintf(out, "%d,", d);
+            if (column >= 180)
+                column = 0;
+        }
+        fprintf(out, "\n};\n\n");
+    }
+#else
+    else
+    {
+        // As integers
         fprintf(out, "%sconst unsigned int %s_%ssize = %d;\n", static_str, symbol, compressed_str, (int)compressed_sz);
         fprintf(out, "%sconst unsigned int %s_%sdata[%d/4] =\n{", static_str, symbol, compressed_str, (int)((compressed_sz + 3) / 4)*4);
         int column = 0;
         for (int i = 0; i < compressed_sz; i += 4)
         {
             unsigned int d = *(unsigned int*)(compressed + i);
-            if ((column++ % 12) == 0)
+            if ((column++ % 14) == 0)
                 fprintf(out, "\n    0x%08x, ", d);
             else
                 fprintf(out, "0x%08x, ", d);
         }
         fprintf(out, "\n};\n\n");
     }
+#endif
 
     // Cleanup
     delete[] data;

From 551b6c4d662a3938f0cd197e79cc29922feec1ff Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 20 Nov 2024 14:32:44 +0100
Subject: [PATCH 0504/2359] Tools: binary_to_compressed_c: added
 -u8/-u32/-base85 export options.

---
 docs/CHANGELOG.txt                    |  1 +
 imgui_draw.cpp                        |  6 ++--
 misc/fonts/binary_to_compressed_c.cpp | 51 +++++++++++++++++----------
 3 files changed, 37 insertions(+), 21 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 5305b889e..5a49416e2 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -56,6 +56,7 @@ Other changes:
 - Misc: changed embedded ProggyClean encoding to save a bit of binary space (~12kb to 9.5kb).
 - Misc: added IMGUI_DISABLE_DEFAULT_FONT to strip embedded font from binary. (#8161)
   [@demonese]
+- Tools: binary_to_compressed_c: added -u8/-u32/-base85 export options.
 - Demo: example tree used by Property Editor & Selection demos properly freed
   on application closure. (#8158) [@Legulysse]
 - Examples: Win32+DX12: Using a basic free-list allocator to manage multiple
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 0f74a98b3..5647f53fd 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -4583,11 +4583,11 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i
 // MIT license (see License.txt in http://www.proggyfonts.net/index.php?menu=download)
 // Download and more information at http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php
 //-----------------------------------------------------------------------------
-// File: 'ProggyClean.ttf' (41208 bytes)
-// Exported using "misc/fonts/binary_to_compressed_c.exe ../ProggyClean.ttf proggy_clean_ttf_compressed (with compression, no base85 encoding).
-//-----------------------------------------------------------------------------
 
 #ifndef IMGUI_DISABLE_DEFAULT_FONT
+
+// File: 'ProggyClean.ttf' (41208 bytes)
+// Exported using binary_to_compressed_c.exe -u8 "ProggyClean.ttf" proggy_clean_ttf
 static const unsigned int proggy_clean_ttf_compressed_size = 9583;
 static const unsigned char proggy_clean_ttf_compressed_data[9583] =
 {
diff --git a/misc/fonts/binary_to_compressed_c.cpp b/misc/fonts/binary_to_compressed_c.cpp
index f16c3b2c3..b0a243a71 100644
--- a/misc/fonts/binary_to_compressed_c.cpp
+++ b/misc/fonts/binary_to_compressed_c.cpp
@@ -2,10 +2,11 @@
 // (binary_to_compressed_c.cpp)
 // Helper tool to turn a file into a C array, if you want to embed font data in your source code.
 
-// The data is first compressed with stb_compress() to reduce source code size,
-// then encoded in Base85 to fit in a string so we can fit roughly 4 bytes of compressed data into 5 bytes of source code (suggested by @mmalex)
-// (If we used 32-bit constants it would require take 11 bytes of source code to encode 4 bytes, and be endianness dependent)
-// Note that even with compression, the output array is likely to be bigger than the binary file..
+// The data is first compressed with stb_compress() to reduce source code size.
+// Then stored in a C array:
+// - Base85:   ~5 bytes of source code for 4 bytes of input data. 5 bytes stored in binary (suggested by @mmalex).
+// - As int:  ~11 bytes of source code for 4 bytes of input data. 4 bytes stored in binary. Endianness dependant, need swapping on big-endian CPU.
+// - As char: ~12 bytes of source code for 4 bytes of input data. 4 bytes stored in binary. Not endianness dependant.
 // Load compressed TTF fonts with ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF()
 
 // Build with, e.g:
@@ -15,10 +16,12 @@
 // You can also find a precompiled Windows binary in the binary/demo package available from https://github.com/ocornut/imgui
 
 // Usage:
-//   binary_to_compressed_c.exe [-base85] [-nocompress] [-nostatic]  
+//   binary_to_compressed_c.exe [-nocompress] [-nostatic] [-base85]  
 // Usage example:
 //   # binary_to_compressed_c.exe myfont.ttf MyFont > myfont.cpp
 //   # binary_to_compressed_c.exe -base85 myfont.ttf MyFont > myfont.cpp
+// Note:
+//   Base85 encoding will be obsoleted by future version of Dear ImGui!
 
 #define _CRT_SECURE_NO_WARNINGS
 #include 
@@ -31,23 +34,36 @@ typedef unsigned int stb_uint;
 typedef unsigned char stb_uchar;
 stb_uint stb_compress(stb_uchar* out, stb_uchar* in, stb_uint len);
 
-static bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression, bool use_static);
+enum SourceEncoding
+{
+    SourceEncoding_U8,      // New default since 2024/11
+    SourceEncoding_U32,
+    SourceEncoding_Base85,
+};
+
+static bool binary_to_compressed_c(const char* filename, const char* symbol, SourceEncoding source_encoding, bool use_compression, bool use_static);
 
 int main(int argc, char** argv)
 {
     if (argc < 3)
     {
-        printf("Syntax: %s [-base85] [-nocompress] [-nostatic]  \n", argv[0]);
+        printf("Syntax: %s [-u8|-u32|-base85] [-nocompress] [-nostatic]  \n", argv[0]);
+        printf("Source encoding types:\n");
+        printf(" -u8     = ~12 bytes of source per 4 bytes of data. 4 bytes in binary.\n");
+        printf(" -u32    = ~11 bytes of source per 4 bytes of data. 4 bytes in binary. Need endianness swapping on big-endian.\n");
+        printf(" -base85 =  ~5 bytes of source per 4 bytes of data. 5 bytes in binary. Need decoder.\n");
         return 0;
     }
 
     int argn = 1;
-    bool use_base85_encoding = false;
     bool use_compression = true;
     bool use_static = true;
+    SourceEncoding source_encoding = SourceEncoding_U8; // New default
     while (argn < (argc - 2) && argv[argn][0] == '-')
     {
-        if (strcmp(argv[argn], "-base85") == 0) { use_base85_encoding = true; argn++; }
+        if (strcmp(argv[argn], "-u8") == 0) { source_encoding = SourceEncoding_U8; argn++; }
+        else if (strcmp(argv[argn], "-u32") == 0) { source_encoding = SourceEncoding_U32; argn++; }
+        else if (strcmp(argv[argn], "-base85") == 0) { source_encoding = SourceEncoding_Base85; argn++; }
         else if (strcmp(argv[argn], "-nocompress") == 0) { use_compression = false; argn++; }
         else if (strcmp(argv[argn], "-nostatic") == 0) { use_static = false; argn++; }
         else
@@ -57,7 +73,7 @@ int main(int argc, char** argv)
         }
     }
 
-    bool ret = binary_to_compressed_c(argv[argn], argv[argn + 1], use_base85_encoding, use_compression, use_static);
+    bool ret = binary_to_compressed_c(argv[argn], argv[argn + 1], source_encoding, use_compression, use_static);
     if (!ret)
         fprintf(stderr, "Error opening or reading file: '%s'\n", argv[argn]);
     return ret ? 0 : 1;
@@ -69,7 +85,7 @@ char Encode85Byte(unsigned int x)
     return (char)((x >= '\\') ? x + 1 : x);
 }
 
-bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression, bool use_static)
+bool binary_to_compressed_c(const char* filename, const char* symbol, SourceEncoding source_encoding, bool use_compression, bool use_static)
 {
     // Read file
     FILE* f = fopen(filename, "rb");
@@ -91,11 +107,11 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b
     // Output as Base85 encoded
     FILE* out = stdout;
     fprintf(out, "// File: '%s' (%d bytes)\n", filename, (int)data_sz);
-    fprintf(out, "// Exported using binary_to_compressed_c.cpp\n");
     const char* static_str = use_static ? "static " : "";
     const char* compressed_str = use_compression ? "compressed_" : "";
-    if (use_base85_encoding)
+    if (source_encoding == SourceEncoding_Base85)
     {
+        fprintf(out, "// Exported using binary_to_compressed_c.exe -base85 \"%s\" %s\n", filename, symbol);
         fprintf(out, "%sconst char %s_%sdata_base85[%d+1] =\n    \"", static_str, symbol, compressed_str, (int)((compressed_sz + 3) / 4)*5);
         char prev_c = 0;
         for (int src_i = 0; src_i < compressed_sz; src_i += 4)
@@ -113,10 +129,10 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b
         }
         fprintf(out, "\";\n\n");
     }
-#if 0
-    else
+    else if (source_encoding == SourceEncoding_U8)
     {
         // As individual bytes, not subject to endianness issues.
+        fprintf(out, "// Exported using binary_to_compressed_c.exe -u8 \"%s\" %s\n", filename, symbol);
         fprintf(out, "%sconst unsigned int %s_%ssize = %d;\n", static_str, symbol, compressed_str, (int)compressed_sz);
         fprintf(out, "%sconst unsigned char %s_%sdata[%d] =\n{", static_str, symbol, compressed_str, (int)compressed_sz);
         int column = 0;
@@ -131,10 +147,10 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b
         }
         fprintf(out, "\n};\n\n");
     }
-#else
-    else
+    else if (source_encoding == SourceEncoding_U32)
     {
         // As integers
+        fprintf(out, "// Exported using binary_to_compressed_c.exe -u32 \"%s\" %s\n", filename, symbol);
         fprintf(out, "%sconst unsigned int %s_%ssize = %d;\n", static_str, symbol, compressed_str, (int)compressed_sz);
         fprintf(out, "%sconst unsigned int %s_%sdata[%d/4] =\n{", static_str, symbol, compressed_str, (int)((compressed_sz + 3) / 4)*4);
         int column = 0;
@@ -148,7 +164,6 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b
         }
         fprintf(out, "\n};\n\n");
     }
-#endif
 
     // Cleanup
     delete[] data;

From 20360e00ceb26b67a4569521b762fbd89d9db61c Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 20 Nov 2024 21:46:47 +0100
Subject: [PATCH 0505/2359] Merge miscellaneous small changes to reduce drift
 with texture update branch.

- ImGuiDebugLogFlags_EventFont is yet unused.
---
 backends/imgui_impl_opengl3.cpp  |  3 +-
 imgui.cpp                        | 28 +++++-----
 imgui.h                          | 19 ++++---
 imgui_draw.cpp                   | 94 ++++++++++++++++++--------------
 imgui_internal.h                 | 25 +++++----
 misc/freetype/imgui_freetype.cpp |  1 +
 6 files changed, 97 insertions(+), 73 deletions(-)

diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp
index c03156a7e..57c699421 100644
--- a/backends/imgui_impl_opengl3.cpp
+++ b/backends/imgui_impl_opengl3.cpp
@@ -164,6 +164,7 @@
 // In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.).
 // If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp):
 // - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped
+//   Typically you would run: python3 ./gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
 // - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases
 // Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version.
 #define IMGL3W_IMPL
@@ -689,7 +690,7 @@ bool ImGui_ImplOpenGL3_CreateFontsTexture()
 #endif
     GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
 
-    // Store our identifier
+    // Store identifier
     io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
 
     // Restore state
diff --git a/imgui.cpp b/imgui.cpp
index 3512ec87d..a8c86cc57 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4010,7 +4010,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     StackSizesInBeginForCurrentWindow = NULL;
 
     DebugDrawIdConflictsCount = 0;
-    DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY;
+    DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY | ImGuiDebugLogFlags_EventFont;
     DebugLocateId = 0;
     DebugLogSkippedErrors = 0;
     DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
@@ -4226,8 +4226,8 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL
     FontWindowScale = 1.0f;
     SettingsOffset = -1;
     DrawList = &DrawListInst;
-    DrawList->_Data = &Ctx->DrawListSharedData;
     DrawList->_OwnerName = Name;
+    DrawList->_Data = &Ctx->DrawListSharedData;
     NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
 }
 
@@ -5025,7 +5025,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags()
     io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
 }
 
-// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
+// Called once a frame. Followed by SetCurrentFont() which sets up the remaining data.
 static void SetupDrawListSharedData()
 {
     ImGuiContext& g = *GImGui;
@@ -15180,6 +15180,17 @@ void ImGui::UpdateDebugToolFlashStyleColor()
         DebugFlashStyleColorStop();
 }
 
+static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
+{
+    union { void* ptr; int integer; } tex_id_opaque;
+    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
+    if (sizeof(tex_id) >= sizeof(void*))
+        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
+    else
+        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
+    return buf;
+}
+
 // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
 static void MetricsHelpMarker(const char* desc)
 {
@@ -15868,16 +15879,6 @@ void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
     TreePop();
 }
 
-static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
-{
-    union { void* ptr; int integer; } tex_id_opaque;
-    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
-    if (sizeof(tex_id) >= sizeof(void*))
-        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
-    else
-        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
-}
-
 // [DEBUG] Display contents of ImDrawList
 void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
 {
@@ -16379,6 +16380,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open)
     ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
     ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
     ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
+    //ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont);
     ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
     ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
     ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
diff --git a/imgui.h b/imgui.h
index 815b07924..12dc7d008 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2309,6 +2309,7 @@ struct ImGuiIO
     // (the imgui_impl_xxxx backend files are setting those up for you)
     //------------------------------------------------------------------
 
+    // Nowadays those would be stored in ImGuiPlatformIO but we are leaving them here for legacy reasons.
     // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff.
     const char* BackendPlatformName;            // = NULL
     const char* BackendRendererName;            // = NULL
@@ -3064,10 +3065,11 @@ struct ImDrawList
     float                   _FringeScale;       // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content
     const char*             _OwnerName;         // Pointer to owner window's name for debugging
 
-    // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui)
-    ImDrawList(ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; }
-
-    ~ImDrawList() { _ClearFreeMemory(); }
+    // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData().
+    // (advanced: you may create and use your own ImDrawListSharedData so you can use ImDrawList without ImGui, but that's more involved)
+    IMGUI_API ImDrawList(ImDrawListSharedData* shared_data);
+    IMGUI_API ~ImDrawList();
+    
     IMGUI_API void  PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false);  // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
     IMGUI_API void  PushClipRectFullScreen();
     IMGUI_API void  PopClipRect();
@@ -3277,14 +3279,16 @@ struct ImFontGlyphRangesBuilder
 // See ImFontAtlas::AddCustomRectXXX functions.
 struct ImFontAtlasCustomRect
 {
-    unsigned short  Width, Height;  // Input    // Desired rectangle dimension
     unsigned short  X, Y;           // Output   // Packed position in Atlas
+
+    // [Internal]
+    unsigned short  Width, Height;  // Input    // Desired rectangle dimension
     unsigned int    GlyphID : 31;   // Input    // For custom font glyphs only (ID < 0x110000)
     unsigned int    GlyphColored : 1; // Input  // For custom font glyphs only: glyph is colored, removed tinting.
     float           GlyphAdvanceX;  // Input    // For custom font glyphs only: glyph xadvance
     ImVec2          GlyphOffset;    // Input    // For custom font glyphs only: glyph display offset
     ImFont*         Font;           // Input    // For custom font glyphs only: target font
-    ImFontAtlasCustomRect()         { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; }
+    ImFontAtlasCustomRect()         { X = Y = 0xFFFF; Width = Height = 0; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; }
     bool IsPacked() const           { return X != 0xFFFF; }
 };
 
@@ -3431,8 +3435,9 @@ struct ImFont
     const ImFontGlyph*          FallbackGlyph;      // 4-8   // out // = FindGlyph(FontFallbackChar)
 
     // Members: Cold ~32/40 bytes
+    // Conceptually ConfigData[] is the list of font sources merged to create this font.
     ImFontAtlas*                ContainerAtlas;     // 4-8   // out //            // What we has been loaded into
-    const ImFontConfig*         ConfigData;         // 4-8   // in  //            // Pointer within ContainerAtlas->ConfigData
+    const ImFontConfig*         ConfigData;         // 4-8   // in  //            // Pointer within ContainerAtlas->ConfigData to ConfigDataCount instances
     short                       ConfigDataCount;    // 2     // in  // ~ 1        // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont.
     ImWchar                     FallbackChar;       // 2     // out // = FFFD/'?' // Character used if a glyph isn't found.
     ImWchar                     EllipsisChar;       // 2     // out // = '...'/'.'// Character used for ellipsis rendering.
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 5647f53fd..fd1feb0a8 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -14,7 +14,7 @@ Index of this file:
 // [SECTION] Helpers ShadeVertsXXX functions
 // [SECTION] ImFontConfig
 // [SECTION] ImFontAtlas
-// [SECTION] ImFontAtlas glyph ranges helpers
+// [SECTION] ImFontAtlas: glyph ranges helpers
 // [SECTION] ImFontGlyphRangesBuilder
 // [SECTION] ImFont
 // [SECTION] ImGui Internal Render Helpers
@@ -394,6 +394,17 @@ void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error)
     ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError);
 }
 
+ImDrawList::ImDrawList(ImDrawListSharedData* shared_data)
+{
+    memset(this, 0, sizeof(*this)); 
+    _Data = shared_data;
+}
+
+ImDrawList::~ImDrawList()
+{
+    _ClearFreeMemory();
+}
+
 // Initialize before use in a new frame. We always have a command ready in the buffer.
 // In the majority of cases, you would want to call PushClipRect() and PushTextureID() after this.
 void ImDrawList::_ResetForNewFrame()
@@ -2528,6 +2539,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
     IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0);
     IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?");
     IM_ASSERT(font_cfg->OversampleH > 0 && font_cfg->OversampleV > 0 && "Is ImFontConfig struct correctly initialized?");
+    IM_ASSERT(font_cfg->RasterizerDensity > 0.0f);
 
     // Create new font
     if (!font_cfg->MergeMode)
@@ -2546,9 +2558,16 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
         memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize);
     }
 
+    // Round font size
+    // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
+    // - Note that using io.FontGlobalScale or SetWindowFontScale(), with are legacy-ish, partially supported features, can still lead to unrounded sizes.
+    // - We may support it better later and remove this rounding.
+    new_font_cfg.SizePixels = ImTrunc(new_font_cfg.SizePixels);
+
     if (new_font_cfg.DstFont->EllipsisChar == (ImWchar)-1)
         new_font_cfg.DstFont->EllipsisChar = font_cfg->EllipsisChar;
 
+    // Pointers to ConfigData and BuilderData are otherwise dangling
     ImFontAtlasUpdateConfigDataPointers(this);
 
     // Invalidate texture
@@ -3163,9 +3182,23 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas)
     IM_ASSERT(r->IsPacked());
 
     const int w = atlas->TexWidth;
-    if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))
+    if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors)
     {
-        // Render/copy pixels
+        // White pixels only
+        IM_ASSERT(r->Width == 2 && r->Height == 2);
+        const int offset = (int)r->X + (int)r->Y * w;
+        if (atlas->TexPixelsAlpha8 != NULL)
+        {
+            atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF;
+        }
+        else
+        {
+            atlas->TexPixelsRGBA32[offset] = atlas->TexPixelsRGBA32[offset + 1] = atlas->TexPixelsRGBA32[offset + w] = atlas->TexPixelsRGBA32[offset + w + 1] = IM_COL32_WHITE;
+        }
+    }
+    else
+    {
+        // White pixels and mouse cursor
         IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H);
         const int x_for_white = r->X;
         const int x_for_black = r->X + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;
@@ -3180,20 +3213,6 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas)
             ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', IM_COL32_WHITE);
         }
     }
-    else
-    {
-        // Render 4 white pixels
-        IM_ASSERT(r->Width == 2 && r->Height == 2);
-        const int offset = (int)r->X + (int)r->Y * w;
-        if (atlas->TexPixelsAlpha8 != NULL)
-        {
-            atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF;
-        }
-        else
-        {
-            atlas->TexPixelsRGBA32[offset] = atlas->TexPixelsRGBA32[offset + 1] = atlas->TexPixelsRGBA32[offset + w] = atlas->TexPixelsRGBA32[offset + w + 1] = IM_COL32_WHITE;
-        }
-    }
     atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y);
 }
 
@@ -3205,38 +3224,38 @@ static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas)
     // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them
     ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines);
     IM_ASSERT(r->IsPacked());
-    for (unsigned int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row
+    for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row
     {
         // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle
-        unsigned int y = n;
-        unsigned int line_width = n;
-        unsigned int pad_left = (r->Width - line_width) / 2;
-        unsigned int pad_right = r->Width - (pad_left + line_width);
+        int y = n;
+        int line_width = n;
+        int pad_left = (r->Width - line_width) / 2;
+        int pad_right = r->Width - (pad_left + line_width);
 
         // Write each slice
         IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels
         if (atlas->TexPixelsAlpha8 != NULL)
         {
             unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)];
-            for (unsigned int i = 0; i < pad_left; i++)
+            for (int i = 0; i < pad_left; i++)
                 *(write_ptr + i) = 0x00;
 
-            for (unsigned int i = 0; i < line_width; i++)
+            for (int i = 0; i < line_width; i++)
                 *(write_ptr + pad_left + i) = 0xFF;
 
-            for (unsigned int i = 0; i < pad_right; i++)
+            for (int i = 0; i < pad_right; i++)
                 *(write_ptr + pad_left + line_width + i) = 0x00;
         }
         else
         {
             unsigned int* write_ptr = &atlas->TexPixelsRGBA32[r->X + ((r->Y + y) * atlas->TexWidth)];
-            for (unsigned int i = 0; i < pad_left; i++)
+            for (int i = 0; i < pad_left; i++)
                 *(write_ptr + i) = IM_COL32(255, 255, 255, 0);
 
-            for (unsigned int i = 0; i < line_width; i++)
+            for (int i = 0; i < line_width; i++)
                 *(write_ptr + pad_left + i) = IM_COL32_WHITE;
 
-            for (unsigned int i = 0; i < pad_right; i++)
+            for (int i = 0; i < pad_right; i++)
                 *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0);
         }
 
@@ -3251,13 +3270,6 @@ static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas)
 // Note: this is called / shared by both the stb_truetype and the FreeType builder
 void ImFontAtlasBuildInit(ImFontAtlas* atlas)
 {
-    // Round font size
-    // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
-    // - Note that using io.FontGlobalScale or SetWindowFontScale(), with are legacy-ish, partially supported features, can still lead to unrounded sizes.
-    // - We may support it better later and remove this rounding.
-    for (ImFontConfig& cfg : atlas->ConfigData)
-       cfg.SizePixels = ImTrunc(cfg.SizePixels);
-
     // Register texture region for mouse cursors or standard white pixels
     if (atlas->PackIdMouseCursors < 0)
     {
@@ -3308,6 +3320,10 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
     atlas->TexReady = true;
 }
 
+//-------------------------------------------------------------------------
+// [SECTION] ImFontAtlas: glyph ranges helpers
+//-------------------------------------------------------------------------
+
 // Retrieve list of range (2 int per range, values are inclusive)
 const ImWchar*   ImFontAtlas::GetGlyphRangesDefault()
 {
@@ -3369,10 +3385,6 @@ static void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short*
     out_ranges[0] = 0;
 }
 
-//-------------------------------------------------------------------------
-// [SECTION] ImFontAtlas glyph ranges helpers
-//-------------------------------------------------------------------------
-
 const ImWchar*  ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon()
 {
     // Store 2500 regularly used characters for Simplified Chinese.
@@ -3799,8 +3811,9 @@ void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, floa
         advance_x += cfg->GlyphExtraSpacing.x;
     }
 
+    int glyph_idx = Glyphs.Size;
     Glyphs.resize(Glyphs.Size + 1);
-    ImFontGlyph& glyph = Glyphs.back();
+    ImFontGlyph& glyph = Glyphs[glyph_idx];
     glyph.Codepoint = (unsigned int)codepoint;
     glyph.Visible = (x0 != x1) && (y0 != y1);
     glyph.Colored = false;
@@ -3836,6 +3849,7 @@ void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
     IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f;
 }
 
+// Find glyph, return fallback if missing
 const ImFontGlyph* ImFont::FindGlyph(ImWchar c)
 {
     if (c >= (size_t)IndexLookup.Size)
diff --git a/imgui_internal.h b/imgui_internal.h
index 2af196cb7..40cf3c0c3 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -212,11 +212,6 @@ extern IMGUI_API ImGuiContext* GImGui;  // Current implicit context pointer
 #endif
 
 // Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam.
-#ifndef IMGUI_DISABLE_DEBUG_TOOLS
-#define IMGUI_DEBUG_LOG(...)            ImGui::DebugLog(__VA_ARGS__)
-#else
-#define IMGUI_DEBUG_LOG(...)            ((void)0)
-#endif
 #define IMGUI_DEBUG_LOG_ERROR(...)      do { ImGuiContext& g2 = *GImGui; if (g2.DebugLogFlags & ImGuiDebugLogFlags_EventError) IMGUI_DEBUG_LOG(__VA_ARGS__); else g2.DebugLogSkippedErrors++; } while (0)
 #define IMGUI_DEBUG_LOG_ACTIVEID(...)   do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventActiveId)    IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
 #define IMGUI_DEBUG_LOG_FOCUS(...)      do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFocus)       IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
@@ -225,6 +220,7 @@ extern IMGUI_API ImGuiContext* GImGui;  // Current implicit context pointer
 #define IMGUI_DEBUG_LOG_SELECTION(...)  do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection)   IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
 #define IMGUI_DEBUG_LOG_CLIPPER(...)    do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper)     IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
 #define IMGUI_DEBUG_LOG_IO(...)         do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO)          IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
+#define IMGUI_DEBUG_LOG_FONT(...)       do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFont)        IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
 #define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0)
 
 // Static Asserts
@@ -760,10 +756,13 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag
 #define IM_DRAWLIST_ARCFAST_SAMPLE_MAX                          IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle.
 
 // Data shared between all ImDrawList instances
-// You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure.
+// Conceptually this could have been called e.g. ImDrawListSharedContext
+// Typically one ImGui context would create and maintain one of this.
+// You may want to create your own instance of you try to ImDrawList completely without ImGui. In that case, watch out for future changes to this structure.
 struct IMGUI_API ImDrawListSharedData
 {
     ImVec2          TexUvWhitePixel;            // UV of white pixel in the atlas
+    const ImVec4*   TexUvLines;                 // UV of anti-aliased lines in the atlas
     ImFont*         Font;                       // Current/default font (optional, for simplified AddText overload)
     float           FontSize;                   // Current/default font size (optional, for simplified AddText overload)
     float           FontScale;                  // Current/default font scale (== FontSize / Font->FontSize)
@@ -779,7 +778,6 @@ struct IMGUI_API ImDrawListSharedData
     ImVec2          ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle.
     float           ArcFastRadiusCutoff;                        // Cutoff radius after which arc drawing will fallback to slower PathArcTo()
     ImU8            CircleSegmentCounts[64];    // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead)
-    const ImVec4*   TexUvLines;                 // UV of anti-aliased lines in the atlas
 
     ImDrawListSharedData();
     void SetCircleTessellationMaxError(float max_error);
@@ -1919,6 +1917,7 @@ typedef void (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const cha
 // [SECTION] Metrics, Debug Tools
 //-----------------------------------------------------------------------------
 
+// See IMGUI_DEBUG_LOG() and IMGUI_DEBUG_LOG_XXX() macros.
 enum ImGuiDebugLogFlags_
 {
     // Event types
@@ -1931,11 +1930,12 @@ enum ImGuiDebugLogFlags_
     ImGuiDebugLogFlags_EventClipper         = 1 << 5,
     ImGuiDebugLogFlags_EventSelection       = 1 << 6,
     ImGuiDebugLogFlags_EventIO              = 1 << 7,
-    ImGuiDebugLogFlags_EventInputRouting    = 1 << 8,
-    ImGuiDebugLogFlags_EventDocking         = 1 << 9,   // Unused in this branch
-    ImGuiDebugLogFlags_EventViewport        = 1 << 10,  // Unused in this branch
+    ImGuiDebugLogFlags_EventFont            = 1 << 8,
+    ImGuiDebugLogFlags_EventInputRouting    = 1 << 9,
+    ImGuiDebugLogFlags_EventDocking         = 1 << 10,  // Unused in this branch
+    ImGuiDebugLogFlags_EventViewport        = 1 << 11,  // Unused in this branch
 
-    ImGuiDebugLogFlags_EventMask_           = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport,
+    ImGuiDebugLogFlags_EventMask_           = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventFont | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport,
     ImGuiDebugLogFlags_OutputToTTY          = 1 << 20,  // Also send output to TTY
     ImGuiDebugLogFlags_OutputToTestEngine   = 1 << 21,  // Also send output to Test Engine
 };
@@ -3524,7 +3524,8 @@ namespace ImGui
 // [SECTION] ImFontAtlas internal API
 //-----------------------------------------------------------------------------
 
-// This structure is likely to evolve as we add support for incremental atlas updates
+// This structure is likely to evolve as we add support for incremental atlas updates.
+// Conceptually this could be in ImGuiPlatformIO, but we are far from ready to make this public.
 struct ImFontBuilderIO
 {
     bool    (*FontBuilder_Build)(ImFontAtlas* atlas);
diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp
index c2d5f074c..e68a2af40 100644
--- a/misc/freetype/imgui_freetype.cpp
+++ b/misc/freetype/imgui_freetype.cpp
@@ -169,6 +169,7 @@ namespace
         const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint);
         const FT_Bitmap*        RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info);
         void                    BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr);
+        FreeTypeFont()          { memset(this, 0, sizeof(*this)); }
         ~FreeTypeFont()         { CloseFont(); }
 
         // [Internals]

From dfbf1b4f6b1a12b3854c58ef7cc160c998a66537 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 20 Nov 2024 22:19:34 +0100
Subject: [PATCH 0506/2359] Backends: DX9: cache result of
 ImGui_ImplDX9_CheckFormatSupport() as we are going to need it more often.

---
 backends/imgui_impl_dx9.cpp | 47 ++++++++++++++++++-------------------
 1 file changed, 23 insertions(+), 24 deletions(-)

diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp
index f1b069df1..4d1527b5a 100644
--- a/backends/imgui_impl_dx9.cpp
+++ b/backends/imgui_impl_dx9.cpp
@@ -52,6 +52,7 @@ struct ImGui_ImplDX9_Data
     LPDIRECT3DTEXTURE9          FontTexture;
     int                         VertexBufferSize;
     int                         IndexBufferSize;
+    bool                        HasRgbaSupport;
 
     ImGui_ImplDX9_Data()        { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
 };
@@ -291,6 +292,24 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
     state_block->Release();
 }
 
+static bool ImGui_ImplDX9_CheckFormatSupport(LPDIRECT3DDEVICE9 pDevice, D3DFORMAT format)
+{
+    LPDIRECT3D9 pd3d = nullptr;
+    if (pDevice->GetDirect3D(&pd3d) != D3D_OK)
+        return false;
+    D3DDEVICE_CREATION_PARAMETERS param = {};
+    D3DDISPLAYMODE mode = {};
+    if (pDevice->GetCreationParameters(¶m) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK)
+    {
+        pd3d->Release();
+        return false;
+    }
+    // Font texture should support linear filter, color blend and write to render-target
+    bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK;
+    pd3d->Release();
+    return support;
+}
+
 bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
 {
     ImGuiIO& io = ImGui::GetIO();
@@ -305,6 +324,7 @@ bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
 
     bd->pd3dDevice = device;
     bd->pd3dDevice->AddRef();
+    bd->HasRgbaSupport = ImGui_ImplDX9_CheckFormatSupport(bd->pd3dDevice, D3DFMT_A8B8G8R8);
 
     return true;
 }
@@ -323,24 +343,6 @@ void ImGui_ImplDX9_Shutdown()
     IM_DELETE(bd);
 }
 
-static bool ImGui_ImplDX9_CheckFormatSupport(IDirect3DDevice9* pDevice, D3DFORMAT format)
-{
-    IDirect3D9* pd3d = nullptr;
-    if (pDevice->GetDirect3D(&pd3d) != D3D_OK)
-        return false;
-    D3DDEVICE_CREATION_PARAMETERS param = {};
-    D3DDISPLAYMODE mode = {};
-    if (pDevice->GetCreationParameters(¶m) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK)
-    {
-        pd3d->Release();
-        return false;
-    }
-    // Font texture should support linear filter, color blend and write to render-target
-    bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK;
-    pd3d->Release();
-    return support;
-}
-
 static bool ImGui_ImplDX9_CreateFontsTexture()
 {
     // Build texture atlas
@@ -352,21 +354,18 @@ static bool ImGui_ImplDX9_CreateFontsTexture()
 
     // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
 #ifndef IMGUI_USE_BGRA_PACKED_COLOR
-    const bool rgba_support = ImGui_ImplDX9_CheckFormatSupport(bd->pd3dDevice, D3DFMT_A8B8G8R8);
-    if (!rgba_support && io.Fonts->TexPixelsUseColors)
+    if (!bd->HasRgbaSupport && io.Fonts->TexPixelsUseColors)
     {
         ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel);
         for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++)
             *dst = IMGUI_COL_TO_DX9_ARGB(*src);
         pixels = (unsigned char*)dst_start;
     }
-#else
-    const bool rgba_support = false;
 #endif
 
     // Upload texture to graphics system
     bd->FontTexture = nullptr;
-    if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, rgba_support ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0)
+    if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, bd->HasRgbaSupport ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0)
         return false;
     D3DLOCKED_RECT tex_locked_rect;
     if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK)
@@ -379,7 +378,7 @@ static bool ImGui_ImplDX9_CreateFontsTexture()
     io.Fonts->SetTexID((ImTextureID)bd->FontTexture);
 
 #ifndef IMGUI_USE_BGRA_PACKED_COLOR
-    if (!rgba_support && io.Fonts->TexPixelsUseColors)
+    if (!bd->HasRgbaSupport && io.Fonts->TexPixelsUseColors)
         ImGui::MemFree(pixels);
 #endif
 

From 5b7feebfd8f3e58392d955b4c8ae01f77eae25ed Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 21 Nov 2024 16:57:51 +0100
Subject: [PATCH 0507/2359] Backends: DX9: extract RGBA convert loop as we are
 going to need it more often.

---
 backends/imgui_impl_dx9.cpp | 42 ++++++++++++++++++++-----------------
 1 file changed, 23 insertions(+), 19 deletions(-)

diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp
index 4d1527b5a..c97d3c740 100644
--- a/backends/imgui_impl_dx9.cpp
+++ b/backends/imgui_impl_dx9.cpp
@@ -343,6 +343,28 @@ void ImGui_ImplDX9_Shutdown()
     IM_DELETE(bd);
 }
 
+// Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
+static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, ImU32* src, int src_pitch, ImU32* dst, int dst_pitch, int w, int h)
+{
+#ifndef IMGUI_USE_BGRA_PACKED_COLOR
+    ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
+    const bool convert_rgba_to_bgra = (!bd->HasRgbaSupport && tex_use_colors);
+#else
+    const bool convert_rgba_to_bgra = false;
+    IM_UNUSED(tex_use_colors);
+#endif
+    for (int y = 0; y < h; y++)
+    {
+        ImU32* src_p = (ImU32*)((unsigned char*)src + src_pitch * y);
+        ImU32* dst_p = (ImU32*)((unsigned char*)dst + dst_pitch * y);
+        if (convert_rgba_to_bgra)
+            for (int x = w; x > 0; x--, src_p++, dst_p++) // Convert copy
+                *dst_p = IMGUI_COL_TO_DX9_ARGB(*src_p);
+        else
+            memcpy(dst_p, src_p, w * 4); // Raw copy
+    }
+}
+
 static bool ImGui_ImplDX9_CreateFontsTexture()
 {
     // Build texture atlas
@@ -352,17 +374,6 @@ static bool ImGui_ImplDX9_CreateFontsTexture()
     int width, height, bytes_per_pixel;
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
 
-    // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
-#ifndef IMGUI_USE_BGRA_PACKED_COLOR
-    if (!bd->HasRgbaSupport && io.Fonts->TexPixelsUseColors)
-    {
-        ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel);
-        for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++)
-            *dst = IMGUI_COL_TO_DX9_ARGB(*src);
-        pixels = (unsigned char*)dst_start;
-    }
-#endif
-
     // Upload texture to graphics system
     bd->FontTexture = nullptr;
     if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, bd->HasRgbaSupport ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0)
@@ -370,18 +381,11 @@ static bool ImGui_ImplDX9_CreateFontsTexture()
     D3DLOCKED_RECT tex_locked_rect;
     if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK)
         return false;
-    for (int y = 0; y < height; y++)
-        memcpy((unsigned char*)tex_locked_rect.pBits + (size_t)tex_locked_rect.Pitch * y, pixels + (size_t)width * bytes_per_pixel * y, (size_t)width * bytes_per_pixel);
+    ImGui_ImplDX9_CopyTextureRegion(io.Fonts->TexPixelsUseColors, (ImU32*)pixels, width * bytes_per_pixel, (ImU32*)tex_locked_rect.pBits, (int)tex_locked_rect.Pitch, width, height);
     bd->FontTexture->UnlockRect(0);
 
     // Store our identifier
     io.Fonts->SetTexID((ImTextureID)bd->FontTexture);
-
-#ifndef IMGUI_USE_BGRA_PACKED_COLOR
-    if (!bd->HasRgbaSupport && io.Fonts->TexPixelsUseColors)
-        ImGui::MemFree(pixels);
-#endif
-
     return true;
 }
 

From 9b273294377dfe0e054614489f90632bfb7af0e3 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 25 Nov 2024 18:59:56 +0100
Subject: [PATCH 0508/2359] Comments on ImageButton(). (#8165) + comments on
 Emscripten -sSINGLE_FILE option. (#8153)

---
 examples/example_glfw_opengl3/Makefile.emscripten | 3 +++
 examples/example_glfw_wgpu/Makefile.emscripten    | 3 +++
 examples/example_sdl2_opengl3/Makefile.emscripten | 3 +++
 examples/example_sdl3_opengl3/Makefile.emscripten | 3 +++
 imgui.h                                           | 3 ++-
 imgui_widgets.cpp                                 | 5 ++---
 6 files changed, 16 insertions(+), 4 deletions(-)

diff --git a/examples/example_glfw_opengl3/Makefile.emscripten b/examples/example_glfw_opengl3/Makefile.emscripten
index bd972abff..bba4ac9dc 100644
--- a/examples/example_glfw_opengl3/Makefile.emscripten
+++ b/examples/example_glfw_opengl3/Makefile.emscripten
@@ -35,6 +35,9 @@ EMS =
 EMS += -s DISABLE_EXCEPTION_CATCHING=1
 LDFLAGS += -s USE_GLFW=3 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1
 
+# Build as single file (binary text encoded in .html file)
+#LDFLAGS += -sSINGLE_FILE
+
 # Uncomment next line to fix possible rendering bugs with Emscripten version older then 1.39.0 (https://github.com/ocornut/imgui/issues/2877)
 #EMS += -s BINARYEN_TRAP_MODE=clamp
 #EMS += -s SAFE_HEAP=1    ## Adds overhead
diff --git a/examples/example_glfw_wgpu/Makefile.emscripten b/examples/example_glfw_wgpu/Makefile.emscripten
index 5c79f0c77..78d64b4d3 100644
--- a/examples/example_glfw_wgpu/Makefile.emscripten
+++ b/examples/example_glfw_wgpu/Makefile.emscripten
@@ -36,6 +36,9 @@ EMS += -s DISABLE_EXCEPTION_CATCHING=1
 LDFLAGS += -s USE_GLFW=3 -s USE_WEBGPU=1
 LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1
 
+# Build as single file (binary text encoded in .html file)
+#LDFLAGS += -sSINGLE_FILE
+
 # Emscripten allows preloading a file or folder to be accessible at runtime.
 # The Makefile for this example project suggests embedding the misc/fonts/ folder into our application, it will then be accessible as "/fonts"
 # See documentation for more details: https://emscripten.org/docs/porting/files/packaging_files.html
diff --git a/examples/example_sdl2_opengl3/Makefile.emscripten b/examples/example_sdl2_opengl3/Makefile.emscripten
index da0348435..bc06adeb7 100644
--- a/examples/example_sdl2_opengl3/Makefile.emscripten
+++ b/examples/example_sdl2_opengl3/Makefile.emscripten
@@ -36,6 +36,9 @@ EMS += -s USE_SDL=2
 EMS += -s DISABLE_EXCEPTION_CATCHING=1
 LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1
 
+# Build as single file (binary text encoded in .html file)
+#LDFLAGS += -sSINGLE_FILE
+
 # Uncomment next line to fix possible rendering bugs with Emscripten version older then 1.39.0 (https://github.com/ocornut/imgui/issues/2877)
 #EMS += -s BINARYEN_TRAP_MODE=clamp
 #EMS += -s SAFE_HEAP=1    ## Adds overhead
diff --git a/examples/example_sdl3_opengl3/Makefile.emscripten b/examples/example_sdl3_opengl3/Makefile.emscripten
index 9e9ffd603..57247ff21 100644
--- a/examples/example_sdl3_opengl3/Makefile.emscripten
+++ b/examples/example_sdl3_opengl3/Makefile.emscripten
@@ -40,6 +40,9 @@ EMS += -s USE_SDL=2
 EMS += -s DISABLE_EXCEPTION_CATCHING=1
 LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1
 
+# Build as single file (binary text encoded in .html file)
+#LDFLAGS += -sSINGLE_FILE
+
 # Uncomment next line to fix possible rendering bugs with Emscripten version older then 1.39.0 (https://github.com/ocornut/imgui/issues/2877)
 #EMS += -s BINARYEN_TRAP_MODE=clamp
 #EMS += -s SAFE_HEAP=1    ## Adds overhead
diff --git a/imgui.h b/imgui.h
index 12dc7d008..35a903889 100644
--- a/imgui.h
+++ b/imgui.h
@@ -564,6 +564,7 @@ namespace ImGui
     // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
     // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above.
     // - Note that Image() may add +2.0f to provided size if a border is visible, ImageButton() adds style.FramePadding*2.0f to provided size.
+    // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified.
     IMGUI_API void          Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), const ImVec4& border_col = ImVec4(0, 0, 0, 0));
     IMGUI_API bool          ImageButton(const char* str_id, ImTextureID user_texture_id, 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));
 
@@ -3069,7 +3070,7 @@ struct ImDrawList
     // (advanced: you may create and use your own ImDrawListSharedData so you can use ImDrawList without ImGui, but that's more involved)
     IMGUI_API ImDrawList(ImDrawListSharedData* shared_data);
     IMGUI_API ~ImDrawList();
-    
+
     IMGUI_API void  PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false);  // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
     IMGUI_API void  PushClipRectFullScreen();
     IMGUI_API void  PopClipRect();
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index c60378f82..81b480cb1 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1073,8 +1073,6 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const I
     window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
 }
 
-// ImageButton() is flawed as 'id' is always derived from 'texture_id' (see #2464 #1390)
-// We provide this internal helper to write your own variant while we figure out how to redesign the public ImageButton() API.
 bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags)
 {
     ImGuiContext& g = *GImGui;
@@ -1102,7 +1100,8 @@ bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& imag
     return pressed;
 }
 
-// Note that ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button.
+// - 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, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col)
 {
     ImGuiContext& g = *GImGui;

From 61ab94d5534b0809079c136fd1301227e91f6003 Mon Sep 17 00:00:00 2001
From: Arseny Kapoulkine 
Date: Fri, 22 Nov 2024 07:40:30 +0900
Subject: [PATCH 0509/2359] Backends: Vulkan: Make descriptor pool optional
 (#8172, #4867)

Comments/amends by ocornut
---
 backends/imgui_impl_vulkan.cpp | 31 +++++++++++++++++++++++++++----
 backends/imgui_impl_vulkan.h   | 16 ++++++++++++----
 docs/CHANGELOG.txt             |  3 +++
 3 files changed, 42 insertions(+), 8 deletions(-)

diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index d499ecb92..1d2d8a19d 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -26,6 +26,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-11-27: Vulkan: Make user-provided descriptor pool optional. As a convenience, when setting init_info->DescriptorPoolSize the backend will create one itself. (#8172, #4867)
 //  2024-10-07: Vulkan: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: Vulkan: Expose selected render state in ImGui_ImplVulkan_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
 //  2024-10-07: Vulkan: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
@@ -131,6 +132,7 @@ static bool g_FunctionsLoaded = true;
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdSetViewport) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateBuffer) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateCommandPool) \
+    IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateDescriptorPool) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateDescriptorSetLayout) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateFence) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateFramebuffer) \
@@ -221,6 +223,7 @@ struct ImGui_ImplVulkan_Data
     VkPipeline                  Pipeline;
     VkShaderModule              ShaderModuleVert;
     VkShaderModule              ShaderModuleFrag;
+    VkDescriptorPool            DescriptorPool;
 
     // Font data
     VkSampler                   FontSampler;
@@ -1010,6 +1013,20 @@ bool ImGui_ImplVulkan_CreateDeviceObjects()
         check_vk_result(err);
     }
 
+    if (v->DescriptorPoolSize)
+    {
+        VkDescriptorPoolSize pool_size = { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, v->DescriptorPoolSize };
+        VkDescriptorPoolCreateInfo pool_info = {};
+        pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
+        pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
+        pool_info.maxSets = v->DescriptorPoolSize;
+        pool_info.poolSizeCount = 1;
+        pool_info.pPoolSizes = &pool_size;
+
+        err = vkCreateDescriptorPool(v->Device, &pool_info, v->Allocator, &bd->DescriptorPool);
+        check_vk_result(err);
+    }
+
     if (!bd->PipelineLayout)
     {
         // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix
@@ -1048,6 +1065,7 @@ void    ImGui_ImplVulkan_DestroyDeviceObjects()
     if (bd->DescriptorSetLayout)  { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; }
     if (bd->PipelineLayout)       { vkDestroyPipelineLayout(v->Device, bd->PipelineLayout, v->Allocator); bd->PipelineLayout = VK_NULL_HANDLE; }
     if (bd->Pipeline)             { vkDestroyPipeline(v->Device, bd->Pipeline, v->Allocator); bd->Pipeline = VK_NULL_HANDLE; }
+    if (bd->DescriptorPool)       { vkDestroyDescriptorPool(v->Device, bd->DescriptorPool, v->Allocator); bd->DescriptorPool = VK_NULL_HANDLE; }
 }
 
 bool    ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data)
@@ -1110,7 +1128,10 @@ bool    ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info)
     IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE);
     IM_ASSERT(info->Device != VK_NULL_HANDLE);
     IM_ASSERT(info->Queue != VK_NULL_HANDLE);
-    IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE);
+    if (info->DescriptorPool != VK_NULL_HANDLE) // Either DescriptorPool or DescriptorPoolSize must be set, not both!
+        IM_ASSERT(info->DescriptorPoolSize == 0);
+    else
+        IM_ASSERT(info->DescriptorPoolSize > 0);
     IM_ASSERT(info->MinImageCount >= 2);
     IM_ASSERT(info->ImageCount >= info->MinImageCount);
     if (info->UseDynamicRendering == false)
@@ -1159,19 +1180,20 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count)
     bd->VulkanInitInfo.MinImageCount = min_image_count;
 }
 
-// Register a texture
+// Register a texture by creating a descriptor
 // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem, please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions.
 VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout)
 {
     ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
     ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
+    VkDescriptorPool pool = bd->DescriptorPool ? bd->DescriptorPool : v->DescriptorPool;
 
     // Create Descriptor Set:
     VkDescriptorSet descriptor_set;
     {
         VkDescriptorSetAllocateInfo alloc_info = {};
         alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
-        alloc_info.descriptorPool = v->DescriptorPool;
+        alloc_info.descriptorPool = pool;
         alloc_info.descriptorSetCount = 1;
         alloc_info.pSetLayouts = &bd->DescriptorSetLayout;
         VkResult err = vkAllocateDescriptorSets(v->Device, &alloc_info, &descriptor_set);
@@ -1199,7 +1221,8 @@ void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set)
 {
     ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
     ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
-    vkFreeDescriptorSets(v->Device, v->DescriptorPool, 1, &descriptor_set);
+    VkDescriptorPool pool = bd->DescriptorPool ? bd->DescriptorPool : v->DescriptorPool;
+    vkFreeDescriptorSets(v->Device, pool, 1, &descriptor_set);
 }
 
 void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator)
diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h
index ca5b4db64..8d9e19f9a 100644
--- a/backends/imgui_impl_vulkan.h
+++ b/backends/imgui_impl_vulkan.h
@@ -62,10 +62,15 @@
 #endif
 
 // Initialization data, for ImGui_ImplVulkan_Init()
-// - VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
-//   and must contain a pool size large enough to hold an ImGui VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptor.
-// - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure.
 // [Please zero-clear before use!]
+// - About descriptor pool:
+//   - A VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
+//     and must contain a pool size large enough to hold a small number of VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptors.
+//   - As an convenience, by setting DescriptorPoolSize > 0 the backend will create one for you.
+//   - Current version of the backend use 1 descriptor for the font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture().
+//   - It is expected that as early as Q1 2025 the backend will use a few more descriptors, so aim at 10 + number of desierd calls to ImGui_ImplVulkan_AddTexture().
+// - About dynamic rendering:
+//   - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure.
 struct ImGui_ImplVulkan_InitInfo
 {
     VkInstance                      Instance;
@@ -73,7 +78,7 @@ struct ImGui_ImplVulkan_InitInfo
     VkDevice                        Device;
     uint32_t                        QueueFamily;
     VkQueue                         Queue;
-    VkDescriptorPool                DescriptorPool;               // See requirements in note above
+    VkDescriptorPool                DescriptorPool;               // See requirements in note above; ignored if using DescriptorPoolSize > 0
     VkRenderPass                    RenderPass;                   // Ignored if using dynamic rendering
     uint32_t                        MinImageCount;                // >= 2
     uint32_t                        ImageCount;                   // >= MinImageCount
@@ -83,6 +88,9 @@ struct ImGui_ImplVulkan_InitInfo
     VkPipelineCache                 PipelineCache;
     uint32_t                        Subpass;
 
+    // (Optional) Set to create internal descriptor pool instead of using DescriptorPool
+    uint32_t                        DescriptorPoolSize;
+
     // (Optional) Dynamic Rendering
     // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3.
     bool                            UseDynamicRendering;
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 5a49416e2..642adfc31 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -59,6 +59,9 @@ Other changes:
 - Tools: binary_to_compressed_c: added -u8/-u32/-base85 export options.
 - Demo: example tree used by Property Editor & Selection demos properly freed
   on application closure. (#8158) [@Legulysse]
+- Backends: Vulkan: Make user-provided descriptor pool optional. As a convenience,
+  when setting init_info->DescriptorPoolSize then the backend will create and manage
+  one itself. (#8172, #4867) [@zeux]
 - Examples: Win32+DX12: Using a basic free-list allocator to manage multiple
   SRV descriptors.
 

From e6dd8f626a189d984a078d9e2f6d4d36a7af91cb Mon Sep 17 00:00:00 2001
From: Teselka <53512153+Teselka@users.noreply.github.com>
Date: Fri, 22 Nov 2024 13:33:25 +0200
Subject: [PATCH 0510/2359] Misc: changed CRC32 table to use crc32c polynomial
 in order to be compatible with SSE 4.2 instructions. (#8169, #4933)

---
 docs/CHANGELOG.txt |  3 +++
 imgui.cpp          | 34 ++++++++++++++++++----------------
 imgui.h            |  2 +-
 3 files changed, 22 insertions(+), 17 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 642adfc31..e901e437e 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -48,6 +48,9 @@ Breaking changes:
   - We provide convenience legacy fields to pass a single descriptor,
     matching the old API, but upcoming features will want multiple.
   - Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
+- Misc: changed CRC32 table to use CRC32c polynomial in order to be compatible
+  with the result of SSE 4.2 instructions. As a result, old .ini data may be
+  partially lost. (#8169, #4933) [@Teselka]
 
 Other changes:
 
diff --git a/imgui.cpp b/imgui.cpp
index a8c86cc57..072c09799 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -429,6 +429,7 @@ CODE
  When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  You can read releases logs https://github.com/ocornut/imgui/releases for more details.
 
+ - 2024/11/27 (1.91.6) - changed CRC32 table to use CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions. As a result, old .ini data may be partially lost.
  - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before)
                             - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
                             - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
@@ -2152,24 +2153,25 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end,
 // CRC32 needs a 1KB lookup table (not cache friendly)
 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
+// On 2024/11/27 this was changed from crc32-adler to crc32c (polynomial 0x1EDC6F41), which invalidated some hashes stored in .ini files.
 static const ImU32 GCrc32LookupTable[256] =
 {
-    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
-    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
-    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
-    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
-    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
-    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
-    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
-    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
-    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
-    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
-    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
-    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
-    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
-    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
-    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
-    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
+    0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
+    0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
+    0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
+    0x30E349B1,0xC288CAB2,0xD1D83946,0x23B3BA45,0xF779DEAE,0x05125DAD,0x1642AE59,0xE4292D5A,0xBA3A117E,0x4851927D,0x5B016189,0xA96AE28A,0x7DA08661,0x8FCB0562,0x9C9BF696,0x6EF07595,
+    0x417B1DBC,0xB3109EBF,0xA0406D4B,0x522BEE48,0x86E18AA3,0x748A09A0,0x67DAFA54,0x95B17957,0xCBA24573,0x39C9C670,0x2A993584,0xD8F2B687,0x0C38D26C,0xFE53516F,0xED03A29B,0x1F682198,
+    0x5125DAD3,0xA34E59D0,0xB01EAA24,0x42752927,0x96BF4DCC,0x64D4CECF,0x77843D3B,0x85EFBE38,0xDBFC821C,0x2997011F,0x3AC7F2EB,0xC8AC71E8,0x1C661503,0xEE0D9600,0xFD5D65F4,0x0F36E6F7,
+    0x61C69362,0x93AD1061,0x80FDE395,0x72966096,0xA65C047D,0x5437877E,0x4767748A,0xB50CF789,0xEB1FCBAD,0x197448AE,0x0A24BB5A,0xF84F3859,0x2C855CB2,0xDEEEDFB1,0xCDBE2C45,0x3FD5AF46,
+    0x7198540D,0x83F3D70E,0x90A324FA,0x62C8A7F9,0xB602C312,0x44694011,0x5739B3E5,0xA55230E6,0xFB410CC2,0x092A8FC1,0x1A7A7C35,0xE811FF36,0x3CDB9BDD,0xCEB018DE,0xDDE0EB2A,0x2F8B6829,
+    0x82F63B78,0x709DB87B,0x63CD4B8F,0x91A6C88C,0x456CAC67,0xB7072F64,0xA457DC90,0x563C5F93,0x082F63B7,0xFA44E0B4,0xE9141340,0x1B7F9043,0xCFB5F4A8,0x3DDE77AB,0x2E8E845F,0xDCE5075C,
+    0x92A8FC17,0x60C37F14,0x73938CE0,0x81F80FE3,0x55326B08,0xA759E80B,0xB4091BFF,0x466298FC,0x1871A4D8,0xEA1A27DB,0xF94AD42F,0x0B21572C,0xDFEB33C7,0x2D80B0C4,0x3ED04330,0xCCBBC033,
+    0xA24BB5A6,0x502036A5,0x4370C551,0xB11B4652,0x65D122B9,0x97BAA1BA,0x84EA524E,0x7681D14D,0x2892ED69,0xDAF96E6A,0xC9A99D9E,0x3BC21E9D,0xEF087A76,0x1D63F975,0x0E330A81,0xFC588982,
+    0xB21572C9,0x407EF1CA,0x532E023E,0xA145813D,0x758FE5D6,0x87E466D5,0x94B49521,0x66DF1622,0x38CC2A06,0xCAA7A905,0xD9F75AF1,0x2B9CD9F2,0xFF56BD19,0x0D3D3E1A,0x1E6DCDEE,0xEC064EED,
+    0xC38D26C4,0x31E6A5C7,0x22B65633,0xD0DDD530,0x0417B1DB,0xF67C32D8,0xE52CC12C,0x1747422F,0x49547E0B,0xBB3FFD08,0xA86F0EFC,0x5A048DFF,0x8ECEE914,0x7CA56A17,0x6FF599E3,0x9D9E1AE0,
+    0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
+    0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
+    0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
 };
 
 // Known size hash
diff --git a/imgui.h b/imgui.h
index 35a903889..30115e810 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.6 WIP"
-#define IMGUI_VERSION_NUM   19151
+#define IMGUI_VERSION_NUM   19152
 #define IMGUI_HAS_TABLE
 
 /*

From 326dc95f9c7ab7adf6ee63f4221b64b4002b6bed Mon Sep 17 00:00:00 2001
From: Teselka <53512153+Teselka@users.noreply.github.com>
Date: Wed, 20 Nov 2024 13:10:36 +0200
Subject: [PATCH 0511/2359] Misc: use native crc32 instructions on SEE 4.2
 targets. (#8169, #4933)

---
 docs/CHANGELOG.txt |  1 +
 imgui.cpp          | 18 ++++++++++++++++++
 imgui_internal.h   |  4 ++++
 3 files changed, 23 insertions(+)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index e901e437e..b93888c85 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -62,6 +62,7 @@ Other changes:
 - Tools: binary_to_compressed_c: added -u8/-u32/-base85 export options.
 - Demo: example tree used by Property Editor & Selection demos properly freed
   on application closure. (#8158) [@Legulysse]
+- Misc: use SSE 4.2 crc32 instructions when available. (#8169, #4933) [@Teselka]
 - Backends: Vulkan: Make user-provided descriptor pool optional. As a convenience,
   when setting init_info->DescriptorPoolSize then the backend will create and manage
   one itself. (#8172, #4867) [@zeux]
diff --git a/imgui.cpp b/imgui.cpp
index 072c09799..ff5d25408 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -2150,6 +2150,7 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end,
     }
 }
 
+#ifndef IMGUI_ENABLE_SSE4_2
 // CRC32 needs a 1KB lookup table (not cache friendly)
 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
@@ -2173,6 +2174,7 @@ static const ImU32 GCrc32LookupTable[256] =
     0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
     0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
 };
+#endif
 
 // Known size hash
 // It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
@@ -2181,10 +2183,16 @@ ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
 {
     ImU32 crc = ~seed;
     const unsigned char* data = (const unsigned char*)data_p;
+#ifndef IMGUI_ENABLE_SSE4_2
     const ImU32* crc32_lut = GCrc32LookupTable;
     while (data_size-- != 0)
         crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
     return ~crc;
+#else
+    while (data_size-- != 0)
+        crc = _mm_crc32_u8(crc, *data++);
+    return ~crc;
+#endif
 }
 
 // Zero-terminated string hash, with support for ### to reset back to seed value
@@ -2198,7 +2206,9 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
     seed = ~seed;
     ImU32 crc = seed;
     const unsigned char* data = (const unsigned char*)data_p;
+#ifndef IMGUI_ENABLE_SSE4_2
     const ImU32* crc32_lut = GCrc32LookupTable;
+#endif
     if (data_size != 0)
     {
         while (data_size-- != 0)
@@ -2206,7 +2216,11 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
             unsigned char c = *data++;
             if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
                 crc = seed;
+#ifndef IMGUI_ENABLE_SSE4_2
             crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
+#else
+            crc = _mm_crc32_u8(crc, c);
+#endif
         }
     }
     else
@@ -2215,7 +2229,11 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
         {
             if (c == '#' && data[0] == '#' && data[1] == '#')
                 crc = seed;
+#ifndef IMGUI_ENABLE_SSE4_2
             crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
+#else
+            crc = _mm_crc32_u8(crc, c);
+#endif
         }
     }
     return ~crc;
diff --git a/imgui_internal.h b/imgui_internal.h
index 40cf3c0c3..fd8a185a5 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -61,6 +61,10 @@ Index of this file:
 #if (defined __SSE__ || defined __x86_64__ || defined _M_X64 || (defined(_M_IX86_FP) && (_M_IX86_FP >= 1))) && !defined(IMGUI_DISABLE_SSE)
 #define IMGUI_ENABLE_SSE
 #include 
+#if (defined __AVX__ || defined __SSE4_2__)
+#define IMGUI_ENABLE_SSE4_2
+#include 
+#endif
 #endif
 
 // Visual Studio warnings

From 2d660108b27a5c03ea8bd8bbd70a0aa3054b995a Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 27 Nov 2024 12:34:16 +0100
Subject: [PATCH 0512/2359] Misc: amend crc32 to use _mm_crc32_u32. (#8169,
 #4933)

---
 imgui.cpp | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index ff5d25408..5f6c85900 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -2183,13 +2183,19 @@ ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
 {
     ImU32 crc = ~seed;
     const unsigned char* data = (const unsigned char*)data_p;
+    const unsigned char *data_end = (const unsigned char*)data_p + data_size;
 #ifndef IMGUI_ENABLE_SSE4_2
     const ImU32* crc32_lut = GCrc32LookupTable;
-    while (data_size-- != 0)
+    while (data < data_end)
         crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
     return ~crc;
 #else
-    while (data_size-- != 0)
+    while (data + 4 <= data_end)
+    {
+        crc = _mm_crc32_u32(crc, *(ImU32*)data);
+        data += 4;
+    }
+    while (data < data_end)
         crc = _mm_crc32_u8(crc, *data++);
     return ~crc;
 #endif

From 96877eb9c30192d8d99b632a66418c037b92913e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 27 Nov 2024 12:38:12 +0100
Subject: [PATCH 0513/2359] Backends: Vulkan: fixed build with
 VK_NO_PROTOTYPES. (#8172, #4867)

Amend 61ab94d
---
 backends/imgui_impl_vulkan.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 1d2d8a19d..8a61a81ba 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -147,6 +147,7 @@ static bool g_FunctionsLoaded = true;
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSwapchainKHR) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyBuffer) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyCommandPool) \
+    IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyDescriptorPool) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyDescriptorSetLayout) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyFence) \
     IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyFramebuffer) \

From 90dd510df1e2fa85c490ddc97e2ea059c46e9fd3 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 11 Oct 2024 17:45:28 +0200
Subject: [PATCH 0514/2359] Backends: DX11: create sampler outside of
 ImGui_ImplDX11_CreateFontsTexture().

---
 backends/imgui_impl_dx11.cpp | 40 +++++++++++++++++++++++-------------
 1 file changed, 26 insertions(+), 14 deletions(-)

diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp
index b928bb86f..4316a9f10 100644
--- a/backends/imgui_impl_dx11.cpp
+++ b/backends/imgui_impl_dx11.cpp
@@ -364,21 +364,16 @@ static void ImGui_ImplDX11_CreateFontsTexture()
 
     // Store our identifier
     io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView);
+}
 
-    // Create texture sampler
-    // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
+static void ImGui_ImplDX11_DestroyFontsTexture()
+{
+    ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
+    if (bd->pFontTextureView)
     {
-        D3D11_SAMPLER_DESC desc;
-        ZeroMemory(&desc, sizeof(desc));
-        desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
-        desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
-        desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
-        desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
-        desc.MipLODBias = 0.f;
-        desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
-        desc.MinLOD = 0.f;
-        desc.MaxLOD = 0.f;
-        bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
+        bd->pFontTextureView->Release();
+        bd->pFontTextureView = nullptr;
+        ImGui::GetIO().Fonts->SetTexID(0); // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well.
     }
 }
 
@@ -531,6 +526,22 @@ bool    ImGui_ImplDX11_CreateDeviceObjects()
         bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
     }
 
+    // Create texture sampler
+    // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
+    {
+        D3D11_SAMPLER_DESC desc;
+        ZeroMemory(&desc, sizeof(desc));
+        desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
+        desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
+        desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
+        desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
+        desc.MipLODBias = 0.f;
+        desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
+        desc.MinLOD = 0.f;
+        desc.MaxLOD = 0.f;
+        bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
+    }
+
     ImGui_ImplDX11_CreateFontsTexture();
 
     return true;
@@ -542,8 +553,9 @@ void    ImGui_ImplDX11_InvalidateDeviceObjects()
     if (!bd->pd3dDevice)
         return;
 
+    ImGui_ImplDX11_DestroyFontsTexture();
+
     if (bd->pFontSampler)           { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
-    if (bd->pFontTextureView)       { bd->pFontTextureView->Release(); bd->pFontTextureView = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well.
     if (bd->pIB)                    { bd->pIB->Release(); bd->pIB = nullptr; }
     if (bd->pVB)                    { bd->pVB->Release(); bd->pVB = nullptr; }
     if (bd->pBlendState)            { bd->pBlendState->Release(); bd->pBlendState = nullptr; }

From c1123fd8d0519942c4347708af999d876e7b7728 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 27 Nov 2024 14:17:32 +0100
Subject: [PATCH 0515/2359] Backends: Vulkan: small refactor to use a texture
 struct.

---
 backends/imgui_impl_vulkan.cpp | 101 ++++++++++++++++++---------------
 1 file changed, 55 insertions(+), 46 deletions(-)

diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 8a61a81ba..2d9664089 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -213,6 +213,16 @@ struct ImGui_ImplVulkan_WindowRenderBuffers
     ImGui_ImplVulkan_FrameRenderBuffers* FrameRenderBuffers;
 };
 
+struct ImGui_ImplVulkan_Texture
+{
+    VkDeviceMemory              Memory;
+    VkImage                     Image;
+    VkImageView                 ImageView;
+    VkDescriptorSet             DescriptorSet;
+
+    ImGui_ImplVulkan_Texture() { memset(this, 0, sizeof(*this)); }
+};
+
 // Vulkan data
 struct ImGui_ImplVulkan_Data
 {
@@ -226,14 +236,11 @@ struct ImGui_ImplVulkan_Data
     VkShaderModule              ShaderModuleFrag;
     VkDescriptorPool            DescriptorPool;
 
-    // Font data
-    VkSampler                   FontSampler;
-    VkDeviceMemory              FontMemory;
-    VkImage                     FontImage;
-    VkImageView                 FontView;
-    VkDescriptorSet             FontDescriptorSet;
-    VkCommandPool               FontCommandPool;
-    VkCommandBuffer             FontCommandBuffer;
+    // Texture management
+    ImGui_ImplVulkan_Texture    FontTexture;
+    VkSampler                   TexSampler;
+    VkCommandPool               TexCommandPool;
+    VkCommandBuffer             TexCommandBuffer;
 
     // Render buffers for main window
     ImGui_ImplVulkan_WindowRenderBuffers MainWindowRenderBuffers;
@@ -598,8 +605,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
                 if (sizeof(ImTextureID) < sizeof(ImU64))
                 {
                     // We don't support texture switches if ImTextureID hasn't been redefined to be 64-bit. Do a flaky check that other textures haven't been used.
-                    IM_ASSERT(pcmd->GetTexID() == (ImTextureID)bd->FontDescriptorSet);
-                    desc_set[0] = bd->FontDescriptorSet;
+                    IM_ASSERT(pcmd->GetTexID() == (ImTextureID)bd->FontTexture.DescriptorSet);
+                    desc_set[0] = bd->FontTexture.DescriptorSet;
                 }
                 vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, desc_set, 0, nullptr);
 
@@ -631,39 +638,39 @@ bool ImGui_ImplVulkan_CreateFontsTexture()
     VkResult err;
 
     // Destroy existing texture (if any)
-    if (bd->FontView || bd->FontImage || bd->FontMemory || bd->FontDescriptorSet)
+    if (bd->FontTexture.DescriptorSet)
     {
         vkQueueWaitIdle(v->Queue);
         ImGui_ImplVulkan_DestroyFontsTexture();
     }
 
     // Create command pool/buffer
-    if (bd->FontCommandPool == VK_NULL_HANDLE)
+    if (bd->TexCommandPool == VK_NULL_HANDLE)
     {
         VkCommandPoolCreateInfo info = {};
         info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
         info.flags = 0;
         info.queueFamilyIndex = v->QueueFamily;
-        vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->FontCommandPool);
+        vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->TexCommandPool);
     }
-    if (bd->FontCommandBuffer == VK_NULL_HANDLE)
+    if (bd->TexCommandBuffer == VK_NULL_HANDLE)
     {
         VkCommandBufferAllocateInfo info = {};
         info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
-        info.commandPool = bd->FontCommandPool;
+        info.commandPool = bd->TexCommandPool;
         info.commandBufferCount = 1;
-        err = vkAllocateCommandBuffers(v->Device, &info, &bd->FontCommandBuffer);
+        err = vkAllocateCommandBuffers(v->Device, &info, &bd->TexCommandBuffer);
         check_vk_result(err);
     }
 
     // Start command buffer
     {
-        err = vkResetCommandPool(v->Device, bd->FontCommandPool, 0);
+        err = vkResetCommandPool(v->Device, bd->TexCommandPool, 0);
         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(bd->FontCommandBuffer, &begin_info);
+        err = vkBeginCommandBuffer(bd->TexCommandBuffer, &begin_info);
         check_vk_result(err);
     }
 
@@ -673,6 +680,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture()
     size_t upload_size = width * height * 4 * sizeof(char);
 
     // Create the Image:
+    ImGui_ImplVulkan_Texture* backend_tex = &bd->FontTexture;
     {
         VkImageCreateInfo info = {};
         info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
@@ -688,17 +696,17 @@ bool ImGui_ImplVulkan_CreateFontsTexture()
         info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
         info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
         info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
-        err = vkCreateImage(v->Device, &info, v->Allocator, &bd->FontImage);
+        err = vkCreateImage(v->Device, &info, v->Allocator, &backend_tex->Image);
         check_vk_result(err);
         VkMemoryRequirements req;
-        vkGetImageMemoryRequirements(v->Device, bd->FontImage, &req);
+        vkGetImageMemoryRequirements(v->Device, backend_tex->Image, &req);
         VkMemoryAllocateInfo alloc_info = {};
         alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
         alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size);
         alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits);
-        err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &bd->FontMemory);
+        err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &backend_tex->Memory);
         check_vk_result(err);
-        err = vkBindImageMemory(v->Device, bd->FontImage, bd->FontMemory, 0);
+        err = vkBindImageMemory(v->Device, backend_tex->Image, backend_tex->Memory, 0);
         check_vk_result(err);
     }
 
@@ -706,18 +714,18 @@ bool ImGui_ImplVulkan_CreateFontsTexture()
     {
         VkImageViewCreateInfo info = {};
         info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
-        info.image = bd->FontImage;
+        info.image = backend_tex->Image;
         info.viewType = VK_IMAGE_VIEW_TYPE_2D;
         info.format = VK_FORMAT_R8G8B8A8_UNORM;
         info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
         info.subresourceRange.levelCount = 1;
         info.subresourceRange.layerCount = 1;
-        err = vkCreateImageView(v->Device, &info, v->Allocator, &bd->FontView);
+        err = vkCreateImageView(v->Device, &info, v->Allocator, &backend_tex->ImageView);
         check_vk_result(err);
     }
 
     // Create the Descriptor Set:
-    bd->FontDescriptorSet = (VkDescriptorSet)ImGui_ImplVulkan_AddTexture(bd->FontSampler, bd->FontView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
+    backend_tex->DescriptorSet = ImGui_ImplVulkan_AddTexture(bd->TexSampler, backend_tex->ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
 
     // Create the Upload Buffer:
     VkDeviceMemory upload_buffer_memory;
@@ -767,11 +775,11 @@ bool ImGui_ImplVulkan_CreateFontsTexture()
         copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
         copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
         copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
-        copy_barrier[0].image = bd->FontImage;
+        copy_barrier[0].image = backend_tex->Image;
         copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
         copy_barrier[0].subresourceRange.levelCount = 1;
         copy_barrier[0].subresourceRange.layerCount = 1;
-        vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier);
+        vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier);
 
         VkBufferImageCopy region = {};
         region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
@@ -779,7 +787,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture()
         region.imageExtent.width = width;
         region.imageExtent.height = height;
         region.imageExtent.depth = 1;
-        vkCmdCopyBufferToImage(bd->FontCommandBuffer, upload_buffer, bd->FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
+        vkCmdCopyBufferToImage(bd->TexCommandBuffer, upload_buffer, backend_tex->Image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
 
         VkImageMemoryBarrier use_barrier[1] = {};
         use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
@@ -789,22 +797,22 @@ bool ImGui_ImplVulkan_CreateFontsTexture()
         use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
         use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
         use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
-        use_barrier[0].image = bd->FontImage;
+        use_barrier[0].image = backend_tex->Image;
         use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
         use_barrier[0].subresourceRange.levelCount = 1;
         use_barrier[0].subresourceRange.layerCount = 1;
-        vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier);
+        vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier);
     }
 
     // Store our identifier
-    io.Fonts->SetTexID((ImTextureID)bd->FontDescriptorSet);
+    io.Fonts->SetTexID((ImTextureID)backend_tex->DescriptorSet);
 
     // End command buffer
     VkSubmitInfo end_info = {};
     end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
     end_info.commandBufferCount = 1;
-    end_info.pCommandBuffers = &bd->FontCommandBuffer;
-    err = vkEndCommandBuffer(bd->FontCommandBuffer);
+    end_info.pCommandBuffers = &bd->TexCommandBuffer;
+    err = vkEndCommandBuffer(bd->TexCommandBuffer);
     check_vk_result(err);
     err = vkQueueSubmit(v->Queue, 1, &end_info, VK_NULL_HANDLE);
     check_vk_result(err);
@@ -825,16 +833,17 @@ void ImGui_ImplVulkan_DestroyFontsTexture()
     ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
     ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
 
-    if (bd->FontDescriptorSet)
+    ImGui_ImplVulkan_Texture* backend_tex = &bd->FontTexture;
+
+    if (backend_tex->DescriptorSet)
     {
-        ImGui_ImplVulkan_RemoveTexture(bd->FontDescriptorSet);
-        bd->FontDescriptorSet = VK_NULL_HANDLE;
+        ImGui_ImplVulkan_RemoveTexture(backend_tex->DescriptorSet);
+        backend_tex->DescriptorSet = VK_NULL_HANDLE;
         io.Fonts->SetTexID(0);
     }
-
-    if (bd->FontView)   { vkDestroyImageView(v->Device, bd->FontView, v->Allocator); bd->FontView = VK_NULL_HANDLE; }
-    if (bd->FontImage)  { vkDestroyImage(v->Device, bd->FontImage, v->Allocator); bd->FontImage = VK_NULL_HANDLE; }
-    if (bd->FontMemory) { vkFreeMemory(v->Device, bd->FontMemory, v->Allocator); bd->FontMemory = VK_NULL_HANDLE; }
+    if (backend_tex->ImageView) { vkDestroyImageView(v->Device, backend_tex->ImageView, v->Allocator); backend_tex->ImageView = VK_NULL_HANDLE; }
+    if (backend_tex->Image)     { vkDestroyImage(v->Device, backend_tex->Image, v->Allocator); backend_tex->Image = VK_NULL_HANDLE; }
+    if (backend_tex->Memory)    { vkFreeMemory(v->Device, backend_tex->Memory, v->Allocator); backend_tex->Memory = VK_NULL_HANDLE; }
 }
 
 static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator)
@@ -982,7 +991,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects()
     ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
     VkResult err;
 
-    if (!bd->FontSampler)
+    if (!bd->TexSampler)
     {
         // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
         VkSamplerCreateInfo info = {};
@@ -996,7 +1005,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects()
         info.minLod = -1000;
         info.maxLod = 1000;
         info.maxAnisotropy = 1.0f;
-        err = vkCreateSampler(v->Device, &info, v->Allocator, &bd->FontSampler);
+        err = vkCreateSampler(v->Device, &info, v->Allocator, &bd->TexSampler);
         check_vk_result(err);
     }
 
@@ -1058,11 +1067,11 @@ void    ImGui_ImplVulkan_DestroyDeviceObjects()
     ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator);
     ImGui_ImplVulkan_DestroyFontsTexture();
 
-    if (bd->FontCommandBuffer)    { vkFreeCommandBuffers(v->Device, bd->FontCommandPool, 1, &bd->FontCommandBuffer); bd->FontCommandBuffer = VK_NULL_HANDLE; }
-    if (bd->FontCommandPool)      { vkDestroyCommandPool(v->Device, bd->FontCommandPool, v->Allocator); bd->FontCommandPool = VK_NULL_HANDLE; }
+    if (bd->TexCommandBuffer)     { vkFreeCommandBuffers(v->Device, bd->TexCommandPool, 1, &bd->TexCommandBuffer); bd->TexCommandBuffer = VK_NULL_HANDLE; }
+    if (bd->TexCommandPool)       { vkDestroyCommandPool(v->Device, bd->TexCommandPool, v->Allocator); bd->TexCommandPool = VK_NULL_HANDLE; }
+    if (bd->TexSampler)           { vkDestroySampler(v->Device, bd->TexSampler, v->Allocator); bd->TexSampler = VK_NULL_HANDLE; }
     if (bd->ShaderModuleVert)     { vkDestroyShaderModule(v->Device, bd->ShaderModuleVert, v->Allocator); bd->ShaderModuleVert = VK_NULL_HANDLE; }
     if (bd->ShaderModuleFrag)     { vkDestroyShaderModule(v->Device, bd->ShaderModuleFrag, v->Allocator); bd->ShaderModuleFrag = VK_NULL_HANDLE; }
-    if (bd->FontSampler)          { vkDestroySampler(v->Device, bd->FontSampler, v->Allocator); bd->FontSampler = VK_NULL_HANDLE; }
     if (bd->DescriptorSetLayout)  { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; }
     if (bd->PipelineLayout)       { vkDestroyPipelineLayout(v->Device, bd->PipelineLayout, v->Allocator); bd->PipelineLayout = VK_NULL_HANDLE; }
     if (bd->Pipeline)             { vkDestroyPipeline(v->Device, bd->Pipeline, v->Allocator); bd->Pipeline = VK_NULL_HANDLE; }
@@ -1163,7 +1172,7 @@ void ImGui_ImplVulkan_NewFrame()
     ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
     IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplVulkan_Init()?");
 
-    if (!bd->FontDescriptorSet)
+    if (!bd->FontTexture.DescriptorSet)
         ImGui_ImplVulkan_CreateFontsTexture();
 }
 

From dda7672008e4f447a4a179d30cf5745fd5a18fb0 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 28 Nov 2024 19:23:01 +0100
Subject: [PATCH 0516/2359] Backends: Vulkan: removed sizeof(ImTextureID)
 check.

(not necessary anymore and it happens to when with a later coming change of ImTextureID, so best removed earlier).
---
 backends/imgui_impl_vulkan.cpp | 10 ++--------
 1 file changed, 2 insertions(+), 8 deletions(-)

diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 2d9664089..69f493762 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -601,14 +601,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
                 vkCmdSetScissor(command_buffer, 0, 1, &scissor);
 
                 // Bind DescriptorSet with font or user texture
-                VkDescriptorSet desc_set[1] = { (VkDescriptorSet)pcmd->GetTexID() };
-                if (sizeof(ImTextureID) < sizeof(ImU64))
-                {
-                    // We don't support texture switches if ImTextureID hasn't been redefined to be 64-bit. Do a flaky check that other textures haven't been used.
-                    IM_ASSERT(pcmd->GetTexID() == (ImTextureID)bd->FontTexture.DescriptorSet);
-                    desc_set[0] = bd->FontTexture.DescriptorSet;
-                }
-                vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, desc_set, 0, nullptr);
+                VkDescriptorSet desc_set = (VkDescriptorSet)pcmd->GetTexID();
+                vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, &desc_set, 0, nullptr);
 
                 // Draw
                 vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);

From 9b26743c6b30d647662c3ef315d9968fde4c1033 Mon Sep 17 00:00:00 2001
From: Diego Mateos 
Date: Fri, 29 Nov 2024 13:31:11 +0100
Subject: [PATCH 0517/2359] SliderAngle: only write back to value v_rad on
 value_changed. (#8193)

---
 imgui_widgets.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 81b480cb1..f9939cec4 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3329,7 +3329,8 @@ bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, fl
         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);
-    *v_rad = v_deg * (2 * IM_PI) / 360.0f;
+    if (value_changed)
+        *v_rad = v_deg * (2 * IM_PI) / 360.0f;
     return value_changed;
 }
 

From 19a1f2a5d2cb1366d7c702e905e6aa5ed4b1ab12 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 29 Nov 2024 18:46:17 +0100
Subject: [PATCH 0518/2359] Fonts: fixed AddCustomRect() not being packed with
 TexGlyphPadding + not accounted in surface area. (#8107)

---
 docs/CHANGELOG.txt               |  2 ++
 imgui.h                          |  6 +++---
 imgui_draw.cpp                   | 18 +++++++++++-------
 misc/freetype/imgui_freetype.cpp |  4 +++-
 4 files changed, 19 insertions(+), 11 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index b93888c85..6650debf0 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -62,6 +62,8 @@ Other changes:
 - Tools: binary_to_compressed_c: added -u8/-u32/-base85 export options.
 - Demo: example tree used by Property Editor & Selection demos properly freed
   on application closure. (#8158) [@Legulysse]
+- Fonts: fixed AddCustomRect() not being packed with TexGlyphPadding + not accounted
+  for surface area used to determine best-guess texture size. (#8107) [@YarikTH, @ocornut]
 - Misc: use SSE 4.2 crc32 instructions when available. (#8169, #4933) [@Teselka]
 - Backends: Vulkan: Make user-provided descriptor pool optional. As a convenience,
   when setting init_info->DescriptorPoolSize then the backend will create and manage
diff --git a/imgui.h b/imgui.h
index 30115e810..423e2a8ba 100644
--- a/imgui.h
+++ b/imgui.h
@@ -3230,8 +3230,8 @@ struct ImFontConfig
     float           SizePixels;             //          // Size in pixels for rasterizer (more or less maps to the resulting font height).
     int             OversampleH;            // 2        // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details.
     int             OversampleV;            // 1        // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis.
-    bool            PixelSnapH;             // false    // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
-    ImVec2          GlyphExtraSpacing;      // 0, 0     // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
+    bool            PixelSnapH;             // false    // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
+    ImVec2          GlyphExtraSpacing;      // 0, 0     // Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now.
     ImVec2          GlyphOffset;            // 0, 0     // Offset all glyphs from this font input.
     const ImWchar*  GlyphRanges;            // NULL     // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list).
     float           GlyphMinAdvanceX;       // 0        // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
@@ -3389,7 +3389,7 @@ struct ImFontAtlas
     ImFontAtlasFlags            Flags;              // Build flags (see ImFontAtlasFlags_)
     ImTextureID                 TexID;              // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.
     int                         TexDesiredWidth;    // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
-    int                         TexGlyphPadding;    // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false).
+    int                         TexGlyphPadding;    // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false).
     bool                        Locked;             // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert.
     void*                       UserData;           // Store your own atlas related user-data (if e.g. you have multiple font atlas).
 
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index fd1feb0a8..631472a71 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -2941,6 +2941,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
     int total_surface = 0;
     int buf_rects_out_n = 0;
     int buf_packedchars_out_n = 0;
+    const int pack_padding = atlas->TexGlyphPadding;
     for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
     {
         ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
@@ -2964,18 +2965,19 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
 
         // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects)
         const float scale = (cfg.SizePixels > 0.0f) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels * cfg.RasterizerDensity) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels * cfg.RasterizerDensity);
-        const int padding = atlas->TexGlyphPadding;
         for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
         {
             int x0, y0, x1, y1;
             const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]);
             IM_ASSERT(glyph_index_in_font != 0);
             stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * cfg.OversampleH, scale * cfg.OversampleV, 0, 0, &x0, &y0, &x1, &y1);
-            src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + padding + cfg.OversampleH - 1);
-            src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + padding + cfg.OversampleV - 1);
+            src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + pack_padding + cfg.OversampleH - 1);
+            src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + pack_padding + cfg.OversampleV - 1);
             total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
         }
     }
+    for (int i = 0; i < atlas->CustomRects.Size; i++)
+        total_surface += (atlas->CustomRects[i].Width + pack_padding) * (atlas->CustomRects[i].Height + pack_padding);
 
     // We need a width for the skyline algorithm, any width!
     // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
@@ -2991,7 +2993,8 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
     // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
     const int TEX_HEIGHT_MAX = 1024 * 32;
     stbtt_pack_context spc = {};
-    stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, atlas->TexGlyphPadding, NULL);
+    stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, 0, NULL);
+    spc.padding = atlas->TexGlyphPadding; // Because we mixup stbtt_PackXXX and stbrp_PackXXX there's a bit of a hack here, not passing the value to stbtt_PackBegin() allows us to still pack a TexWidth-1 wide item. (#8107)
     ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info);
 
     // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
@@ -3137,13 +3140,14 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa
     if (user_rects.Size < 1) { __builtin_unreachable(); } // Workaround for GCC bug if IM_ASSERT() is defined to conditionally throw (see #5343)
 #endif
 
+    const int pack_padding = atlas->TexGlyphPadding;
     ImVector pack_rects;
     pack_rects.resize(user_rects.Size);
     memset(pack_rects.Data, 0, (size_t)pack_rects.size_in_bytes());
     for (int i = 0; i < user_rects.Size; i++)
     {
-        pack_rects[i].w = user_rects[i].Width;
-        pack_rects[i].h = user_rects[i].Height;
+        pack_rects[i].w = user_rects[i].Width + pack_padding;
+        pack_rects[i].h = user_rects[i].Height + pack_padding;
     }
     stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size);
     for (int i = 0; i < pack_rects.Size; i++)
@@ -3151,7 +3155,7 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa
         {
             user_rects[i].X = (unsigned short)pack_rects[i].x;
             user_rects[i].Y = (unsigned short)pack_rects[i].y;
-            IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height);
+            IM_ASSERT(pack_rects[i].w == user_rects[i].Width + pack_padding && pack_rects[i].h == user_rects[i].Height + pack_padding);
             atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h);
         }
 }
diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp
index e68a2af40..bee15ba08 100644
--- a/misc/freetype/imgui_freetype.cpp
+++ b/misc/freetype/imgui_freetype.cpp
@@ -573,6 +573,7 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u
     // 8. Render/rasterize font characters into the texture
     int total_surface = 0;
     int buf_rects_out_n = 0;
+    const int pack_padding = atlas->TexGlyphPadding;
     for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
     {
         ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
@@ -590,7 +591,6 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u
             ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
 
         // Gather the sizes of all rectangles we will need to pack
-        const int padding = atlas->TexGlyphPadding;
         for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
         {
             ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
@@ -623,6 +623,8 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u
             total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
         }
     }
+    for (int i = 0; i < atlas->CustomRects.Size; i++)
+        total_surface += (atlas->CustomRects[i].Width + pack_padding) * (atlas->CustomRects[i].Height + pack_padding);
 
     // We need a width for the skyline algorithm, any width!
     // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.

From ee2119d7cbe1361689f9a7a6ef6853c1deae08f6 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Fri, 29 Nov 2024 19:10:39 +0100
Subject: [PATCH 0519/2359] imgui_freetype: Fix build broken by 19a1f2a (#8107)

---
 misc/freetype/imgui_freetype.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp
index bee15ba08..1bd3be65a 100644
--- a/misc/freetype/imgui_freetype.cpp
+++ b/misc/freetype/imgui_freetype.cpp
@@ -618,8 +618,8 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u
             buf_bitmap_current_used_bytes += bitmap_size_in_bytes;
             src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width, multiply_enabled ? multiply_table : nullptr);
 
-            src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + padding);
-            src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + padding);
+            src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + pack_padding);
+            src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + pack_padding);
             total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
         }
     }

From 43c51eb12d187d9113af0f646d24da9e8cc04c83 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 2 Dec 2024 13:23:09 +0100
Subject: [PATCH 0520/2359] Tables: fixed SetNextWindowScroll() value being
 ignored by BeginTable() during the first frame or when scrolling flags have
 changed. (#8196)

---
 docs/CHANGELOG.txt | 2 ++
 imgui_tables.cpp   | 3 ++-
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 6650debf0..874c7502f 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -56,6 +56,8 @@ Other changes:
 
 - Error Handling: fixed cases where recoverable error handling would crash when 
   processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
+- Tables: fixed SetNextWindowScroll() value being ignored by BeginTable() during
+  the first frame or when scrolling flags have changed. (#8196)
 - Misc: changed embedded ProggyClean encoding to save a bit of binary space (~12kb to 9.5kb).
 - Misc: added IMGUI_DISABLE_DEFAULT_FONT to strip embedded font from binary. (#8161)
   [@demonese]
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 5254f7858..db34aa347 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -410,7 +410,8 @@ bool    ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG
 
         // Reset scroll if we are reactivating it
         if ((previous_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0)
-            SetNextWindowScroll(ImVec2(0.0f, 0.0f));
+            if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll) == 0)
+                SetNextWindowScroll(ImVec2(0.0f, 0.0f));
 
         // Create scrolling region (without border and zero window padding)
         ImGuiWindowFlags child_window_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None;

From 923ca4765a8a6b4cc10b7f438c8e63a25d1f5c61 Mon Sep 17 00:00:00 2001
From: Thomas Hope 
Date: Sat, 30 Nov 2024 16:58:48 +0100
Subject: [PATCH 0521/2359] Backends: OpenGL3: Fix compile error with
 IMGUI_IMPL_OPENGL_ES2 and IMGUI_IMPL_OPENGL_DEBUG (#8197)

---
 backends/imgui_impl_opengl3.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp
index 57c699421..8f3177837 100644
--- a/backends/imgui_impl_opengl3.cpp
+++ b/backends/imgui_impl_opengl3.cpp
@@ -299,6 +299,8 @@ bool    ImGui_ImplOpenGL3_Init(const char* glsl_version)
     // Query for GL version (e.g. 320 for GL 3.2)
 #if defined(IMGUI_IMPL_OPENGL_ES2)
     // GLES 2
+    const char* gl_version_str = "";
+    IM_UNUSED(gl_version_str); // For IMGUI_IMPL_OPENGL_DEBUG block below.
     bd->GlVersion = 200;
     bd->GlProfileIsES2 = true;
 #else
@@ -336,7 +338,7 @@ bool    ImGui_ImplOpenGL3_Init(const char* glsl_version)
 #endif
 
 #ifdef IMGUI_IMPL_OPENGL_DEBUG
-    printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2 = %d, GlProfileIsES3 = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG]
+    printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2/IsEs3 = %d/%d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG]
 #endif
 
 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET

From 70b6ba42402f27b40760c15c7d7e926cc06c96fa Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 4 Dec 2024 10:38:19 +0100
Subject: [PATCH 0522/2359] Clarify that IMGUI_USE_BGRA_PACKED_COLOR requires
 backend support. (#8201)

---
 backends/imgui_impl_dx9.cpp | 1 +
 backends/imgui_impl_dx9.h   | 1 +
 imconfig.h                  | 2 +-
 imgui.h                     | 3 ++-
 4 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp
index c97d3c740..ee0e23940 100644
--- a/backends/imgui_impl_dx9.cpp
+++ b/backends/imgui_impl_dx9.cpp
@@ -4,6 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR is supported, as this is the optimal color encoding for DirectX9.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_dx9.h b/backends/imgui_impl_dx9.h
index df6a0a012..c096b3398 100644
--- a/backends/imgui_impl_dx9.h
+++ b/backends/imgui_impl_dx9.h
@@ -4,6 +4,7 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR is supported, as this is the optimal color encoding for DirectX9.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/imconfig.h b/imconfig.h
index 3504a4e4d..6790f147a 100644
--- a/imconfig.h
+++ b/imconfig.h
@@ -59,7 +59,7 @@
 //#define IMGUI_INCLUDE_IMGUI_USER_H
 //#define IMGUI_USER_H_FILENAME         "my_folder/my_imgui_user.h"
 
-//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
+//---- Pack vertex colors as BGRA8 instead of RGBA8 (to avoid converting from one to another). Need dedicated backend support.
 //#define IMGUI_USE_BGRA_PACKED_COLOR
 
 //---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
diff --git a/imgui.h b/imgui.h
index 423e2a8ba..b86c7d4e5 100644
--- a/imgui.h
+++ b/imgui.h
@@ -2715,7 +2715,8 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE
 #endif
 
 // Helpers macros to generate 32-bit encoded colors
-// User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file.
+// - User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file.
+// - Any setting other than the default will need custom backend support. The only standard backend that supports anything else than the default is DirectX9.
 #ifndef IM_COL32_R_SHIFT
 #ifdef IMGUI_USE_BGRA_PACKED_COLOR
 #define IM_COL32_R_SHIFT    16

From 6f6ac84228a6502b6f21c7dc3641195783a06fb2 Mon Sep 17 00:00:00 2001
From: Jack Holmes 
Date: Wed, 4 Dec 2024 17:59:51 +0000
Subject: [PATCH 0523/2359] Demo: Assets Browser: use correct axis for layout
 computation, to allow making items non-square. (#8207)

---
 imgui_demo.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index c822c162e..5efbe6304 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -10175,7 +10175,7 @@ struct ExampleAssetsBrowser
         }
 
         ImGuiIO& io = ImGui::GetIO();
-        ImGui::SetNextWindowContentSize(ImVec2(0.0f, LayoutOuterPadding + LayoutLineCount * (LayoutItemSize.x + LayoutItemSpacing)));
+        ImGui::SetNextWindowContentSize(ImVec2(0.0f, LayoutOuterPadding + LayoutLineCount * (LayoutItemSize.y + LayoutItemSpacing)));
         if (ImGui::BeginChild("Assets", ImVec2(0.0f, -ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove))
         {
             ImDrawList* draw_list = ImGui::GetWindowDrawList();

From 566558b17c528b82d88236d9e38d270eb766c261 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 5 Dec 2024 12:25:02 +0100
Subject: [PATCH 0524/2359] Replacing NULL with nullptr in examples/backends
 when they creeped back. (#6313, #7071, #4537)

---
 backends/imgui_impl_dx11.cpp              |  2 +-
 backends/imgui_impl_dx12.cpp              |  6 +++---
 backends/imgui_impl_glfw.cpp              |  4 ++--
 backends/imgui_impl_sdl2.cpp              | 14 +++++++-------
 backends/imgui_impl_sdl2.h                |  2 +-
 backends/imgui_impl_sdl3.cpp              | 22 +++++++++++-----------
 backends/imgui_impl_sdl3.h                |  2 +-
 backends/imgui_impl_sdlrenderer2.cpp      |  2 +-
 backends/imgui_impl_sdlrenderer3.cpp      |  2 +-
 backends/imgui_impl_vulkan.cpp            |  4 ++--
 backends/imgui_impl_wgpu.cpp              |  2 +-
 backends/imgui_impl_win32.cpp             |  4 ++--
 examples/example_win32_directx12/main.cpp |  2 +-
 misc/freetype/imgui_freetype.cpp          |  2 +-
 14 files changed, 35 insertions(+), 35 deletions(-)

diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp
index 4316a9f10..4a87c23a1 100644
--- a/backends/imgui_impl_dx11.cpp
+++ b/backends/imgui_impl_dx11.cpp
@@ -298,7 +298,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
         global_idx_offset += draw_list->IdxBuffer.Size;
         global_vtx_offset += draw_list->VtxBuffer.Size;
     }
-    platform_io.Renderer_RenderState = NULL;
+    platform_io.Renderer_RenderState = nullptr;
 
     // Restore modified DX state
     device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index acf98858b..a02094128 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -311,7 +311,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL
         global_idx_offset += draw_list->IdxBuffer.Size;
         global_vtx_offset += draw_list->VtxBuffer.Size;
     }
-    platform_io.Renderer_RenderState = NULL;
+    platform_io.Renderer_RenderState = nullptr;
 }
 
 static void ImGui_ImplDX12_CreateFontsTexture()
@@ -743,7 +743,7 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
     io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;  // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
 
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-    if (init_info->SrvDescriptorAllocFn == NULL)
+    if (init_info->SrvDescriptorAllocFn == nullptr)
     {
         // Wrap legacy behavior of passing space for a single descriptor
         IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
@@ -765,7 +765,7 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
 #endif
 
     // Allocate 1 SRV descriptor for the font texture
-    IM_ASSERT(init_info->SrvDescriptorAllocFn != NULL && init_info->SrvDescriptorFreeFn != NULL);
+    IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr);
     init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->FontTexture.hFontSrvCpuDescHandle, &bd->FontTexture.hFontSrvGpuDescHandle);
 
     // Create buffers with a default size (they will later be grown as needed)
diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp
index afa2185a3..1cdb2534f 100644
--- a/backends/imgui_impl_glfw.cpp
+++ b/backends/imgui_impl_glfw.cpp
@@ -595,8 +595,8 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw
     bd->Time = 0.0;
 
     ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
-    platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(NULL, text); };
-    platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(NULL); };
+    platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(nullptr, text); };
+    platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(nullptr); };
 #ifdef __EMSCRIPTEN__
     platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; };
 #endif
diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp
index 14022159f..af5f6b013 100644
--- a/backends/imgui_impl_sdl2.cpp
+++ b/backends/imgui_impl_sdl2.cpp
@@ -324,7 +324,7 @@ static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
 static ImGuiViewport* ImGui_ImplSDL2_GetViewportForWindowID(Uint32 window_id)
 {
     ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
-    return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : NULL;
+    return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr;
 }
 
 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
@@ -342,7 +342,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
     {
         case SDL_MOUSEMOTION:
         {
-            if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == NULL)
+            if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == nullptr)
                 return false;
             ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
             io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
@@ -351,7 +351,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
         }
         case SDL_MOUSEWHEEL:
         {
-            if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == NULL)
+            if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == nullptr)
                 return false;
             //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
 #if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!
@@ -371,7 +371,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
         case SDL_MOUSEBUTTONDOWN:
         case SDL_MOUSEBUTTONUP:
         {
-            if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == NULL)
+            if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == nullptr)
                 return false;
             int mouse_button = -1;
             if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
@@ -388,7 +388,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
         }
         case SDL_TEXTINPUT:
         {
-            if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == NULL)
+            if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == nullptr)
                 return false;
             io.AddInputCharactersUTF8(event->text.text);
             return true;
@@ -396,7 +396,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
         case SDL_KEYDOWN:
         case SDL_KEYUP:
         {
-            if (ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID) == NULL)
+            if (ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID) == nullptr)
                 return false;
             ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);
             ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);
@@ -406,7 +406,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
         }
         case SDL_WINDOWEVENT:
         {
-            if (ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID) == NULL)
+            if (ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID) == nullptr)
                 return false;
             // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.
             // - However we won't get a correct LEAVE event for a captured window.
diff --git a/backends/imgui_impl_sdl2.h b/backends/imgui_impl_sdl2.h
index 8ccc6fdc7..e071e9715 100644
--- a/backends/imgui_impl_sdl2.h
+++ b/backends/imgui_impl_sdl2.h
@@ -41,6 +41,6 @@ IMGUI_IMPL_API bool     ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event);
 // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this.
 // When using manual mode, caller is responsible for opening/closing gamepad.
 enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual };
-IMGUI_IMPL_API void     ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = NULL, int manual_gamepads_count = -1);
+IMGUI_IMPL_API void     ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = nullptr, int manual_gamepads_count = -1);
 
 #endif // #ifndef IMGUI_DISABLE
diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp
index 3cd56a756..0955859a5 100644
--- a/backends/imgui_impl_sdl3.cpp
+++ b/backends/imgui_impl_sdl3.cpp
@@ -128,7 +128,7 @@ static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*)
     if (bd->ClipboardTextData)
         SDL_free(bd->ClipboardTextData);
     const char* sdl_clipboard_text = SDL_GetClipboardText();
-    bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : NULL;
+    bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : nullptr;
     return bd->ClipboardTextData;
 }
 
@@ -142,7 +142,7 @@ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view
     ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
     SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle;
     SDL_Window* window = SDL_GetWindowFromID(window_id);
-    if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != NULL)
+    if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != nullptr)
     {
         SDL_StopTextInput(bd->ImeWindow);
         bd->ImeWindow = nullptr;
@@ -308,7 +308,7 @@ static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
 static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id)
 {
     ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
-    return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : NULL;
+    return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr;
 }
 
 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
@@ -326,7 +326,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
     {
         case SDL_EVENT_MOUSE_MOTION:
         {
-            if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == NULL)
+            if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == nullptr)
                 return false;
             ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
             io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
@@ -335,7 +335,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
         }
         case SDL_EVENT_MOUSE_WHEEL:
         {
-            if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == NULL)
+            if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == nullptr)
                 return false;
             //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
             float wheel_x = -event->wheel.x;
@@ -347,7 +347,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
         case SDL_EVENT_MOUSE_BUTTON_DOWN:
         case SDL_EVENT_MOUSE_BUTTON_UP:
         {
-            if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == NULL)
+            if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == nullptr)
                 return false;
             int mouse_button = -1;
             if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
@@ -364,7 +364,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
         }
         case SDL_EVENT_TEXT_INPUT:
         {
-            if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == NULL)
+            if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == nullptr)
                 return false;
             io.AddInputCharactersUTF8(event->text.text);
             return true;
@@ -372,7 +372,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
         case SDL_EVENT_KEY_DOWN:
         case SDL_EVENT_KEY_UP:
         {
-            if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == NULL)
+            if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == nullptr)
                 return false;
             //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod);
             ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod);
@@ -383,7 +383,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
         }
         case SDL_EVENT_WINDOW_MOUSE_ENTER:
         {
-            if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL)
+            if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
                 return false;
             bd->MouseWindowID = event->window.windowID;
             bd->MousePendingLeaveFrame = 0;
@@ -395,7 +395,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
         // FIXME: Unconfirmed whether this is still needed with SDL3.
         case SDL_EVENT_WINDOW_MOUSE_LEAVE:
         {
-            if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL)
+            if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
                 return false;
             bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1;
             return true;
@@ -403,7 +403,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
         case SDL_EVENT_WINDOW_FOCUS_GAINED:
         case SDL_EVENT_WINDOW_FOCUS_LOST:
         {
-            if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL)
+            if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
                 return false;
             io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED);
             return true;
diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h
index c4a5a1230..b86aa1901 100644
--- a/backends/imgui_impl_sdl3.h
+++ b/backends/imgui_impl_sdl3.h
@@ -42,6 +42,6 @@ IMGUI_IMPL_API bool     ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event);
 // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this.
 // When using manual mode, caller is responsible for opening/closing gamepad.
 enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual };
-IMGUI_IMPL_API void     ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = NULL, int manual_gamepads_count = -1);
+IMGUI_IMPL_API void     ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = nullptr, int manual_gamepads_count = -1);
 
 #endif // #ifndef IMGUI_DISABLE
diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp
index 27c952269..485adabb3 100644
--- a/backends/imgui_impl_sdlrenderer2.cpp
+++ b/backends/imgui_impl_sdlrenderer2.cpp
@@ -208,7 +208,7 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
             }
         }
     }
-    platform_io.Renderer_RenderState = NULL;
+    platform_io.Renderer_RenderState = nullptr;
 
     // Restore modified SDL_Renderer state
     SDL_RenderSetViewport(renderer, &old.Viewport);
diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp
index 5dabea199..1238246c2 100644
--- a/backends/imgui_impl_sdlrenderer3.cpp
+++ b/backends/imgui_impl_sdlrenderer3.cpp
@@ -227,7 +227,7 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer*
             }
         }
     }
-    platform_io.Renderer_RenderState = NULL;
+    platform_io.Renderer_RenderState = nullptr;
 
     // Restore modified SDL_Renderer state
     SDL_SetRenderViewport(renderer, old.ViewportEnabled ? &old.Viewport : nullptr);
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 69f493762..1491ccabf 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -611,7 +611,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
         global_idx_offset += draw_list->IdxBuffer.Size;
         global_vtx_offset += draw_list->VtxBuffer.Size;
     }
-    platform_io.Renderer_RenderState = NULL;
+    platform_io.Renderer_RenderState = nullptr;
 
     // Note: at this point both vkCmdSetViewport() and vkCmdSetScissor() have been called.
     // Our last values will leak into user/application rendering IF:
@@ -969,7 +969,7 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC
     if (bd->VulkanInitInfo.UseDynamicRendering)
     {
         IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR");
-        IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo pNext must be NULL");
+        IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo pNext must be nullptr");
         info.pNext = &bd->VulkanInitInfo.PipelineRenderingCreateInfo;
         info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr.
     }
diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index 075f74734..02a8caeb4 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -518,7 +518,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
         global_idx_offset += draw_list->IdxBuffer.Size;
         global_vtx_offset += draw_list->VtxBuffer.Size;
     }
-    platform_io.Renderer_RenderState = NULL;
+    platform_io.Renderer_RenderState = nullptr;
 }
 
 static void ImGui_ImplWGPU_CreateFontsTexture()
diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index 687bc5a18..843ef161b 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -588,7 +588,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
 {
     // Most backends don't have silent checks like this one, but we need it because WndProc are called early in CreateWindow().
     // We silently allow both context or just only backend data to be nullptr.
-    if (ImGui::GetCurrentContext() == NULL)
+    if (ImGui::GetCurrentContext() == nullptr)
         return 0;
     return ImGui_ImplWin32_WndProcHandlerEx(hwnd, msg, wParam, lParam, ImGui::GetIO());
 }
@@ -597,7 +597,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
 IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, ImGuiIO& io)
 {
     ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
-    if (bd == NULL)
+    if (bd == nullptr)
         return 0;
     switch (msg)
     {
diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp
index 257410e2c..eeff99c1b 100644
--- a/examples/example_win32_directx12/main.cpp
+++ b/examples/example_win32_directx12/main.cpp
@@ -58,7 +58,7 @@ struct ExampleDescriptorHeapAllocator
     }
     void Destroy()
     {
-        Heap = NULL;
+        Heap = nullptr;
         FreeIndices.clear();
     }
     void Alloc(D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_desc_handle)
diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp
index 1bd3be65a..aeab6dfa0 100644
--- a/misc/freetype/imgui_freetype.cpp
+++ b/misc/freetype/imgui_freetype.cpp
@@ -10,7 +10,7 @@
 //  2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics.
 //  2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG'. (#6591)
 //  2023/01/04: fixed a packing issue which in some occurrences would prevent large amount of glyphs from being packed correctly.
-//  2021/08/23: fixed crash when FT_Render_Glyph() fails to render a glyph and returns NULL.
+//  2021/08/23: fixed crash when FT_Render_Glyph() fails to render a glyph and returns nullptr.
 //  2021/03/05: added ImGuiFreeTypeBuilderFlags_Bitmap to load bitmap glyphs.
 //  2021/03/02: set 'atlas->TexPixelsUseColors = true' to help some backends with deciding of a preferred texture format.
 //  2021/01/28: added support for color-layered glyphs via ImGuiFreeTypeBuilderFlags_LoadColor (require Freetype 2.10+).

From 43fbd7ce8405d48caa90cd2d2b244c059288744d Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 5 Dec 2024 12:43:04 +0100
Subject: [PATCH 0525/2359] Backends: standardized top of file comments.

---
 backends/imgui_impl_allegro5.cpp     | 6 +++---
 backends/imgui_impl_allegro5.h       | 6 +++---
 backends/imgui_impl_android.cpp      | 4 ++--
 backends/imgui_impl_android.h        | 4 ++--
 backends/imgui_impl_dx10.cpp         | 2 +-
 backends/imgui_impl_dx10.h           | 2 +-
 backends/imgui_impl_dx11.cpp         | 2 +-
 backends/imgui_impl_dx11.h           | 2 +-
 backends/imgui_impl_dx12.cpp         | 2 +-
 backends/imgui_impl_dx12.h           | 2 +-
 backends/imgui_impl_dx9.cpp          | 4 ++--
 backends/imgui_impl_dx9.h            | 4 ++--
 backends/imgui_impl_glfw.cpp         | 2 +-
 backends/imgui_impl_glfw.h           | 2 +-
 backends/imgui_impl_glut.cpp         | 2 +-
 backends/imgui_impl_glut.h           | 2 +-
 backends/imgui_impl_metal.h          | 2 +-
 backends/imgui_impl_metal.mm         | 2 +-
 backends/imgui_impl_opengl2.cpp      | 2 ++
 backends/imgui_impl_opengl2.h        | 2 ++
 backends/imgui_impl_opengl3.cpp      | 2 +-
 backends/imgui_impl_opengl3.h        | 2 +-
 backends/imgui_impl_osx.h            | 4 ++--
 backends/imgui_impl_osx.mm           | 4 ++--
 backends/imgui_impl_sdl2.cpp         | 2 +-
 backends/imgui_impl_sdl2.h           | 2 +-
 backends/imgui_impl_sdl3.cpp         | 3 ++-
 backends/imgui_impl_sdl3.h           | 3 ++-
 backends/imgui_impl_sdlrenderer2.cpp | 2 +-
 backends/imgui_impl_sdlrenderer2.h   | 2 +-
 backends/imgui_impl_sdlrenderer3.cpp | 2 +-
 backends/imgui_impl_sdlrenderer3.h   | 2 +-
 backends/imgui_impl_vulkan.cpp       | 4 ++--
 backends/imgui_impl_vulkan.h         | 4 ++--
 backends/imgui_impl_wgpu.cpp         | 2 +-
 backends/imgui_impl_wgpu.h           | 2 +-
 backends/imgui_impl_win32.cpp        | 2 +-
 backends/imgui_impl_win32.h          | 2 +-
 38 files changed, 54 insertions(+), 48 deletions(-)

diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp
index 3e6d76647..28d1b1536 100644
--- a/backends/imgui_impl_allegro5.cpp
+++ b/backends/imgui_impl_allegro5.cpp
@@ -4,9 +4,9 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
-//  [X] Platform: Clipboard support (from Allegro 5.1.12)
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
-// Issues:
+//  [X] Platform: Clipboard support (from Allegro 5.1.12).
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+// Missing features or Issues:
 //  [ ] Renderer: The renderer is suboptimal as we need to convert vertices manually.
 //  [ ] Platform: Missing gamepad support.
 
diff --git a/backends/imgui_impl_allegro5.h b/backends/imgui_impl_allegro5.h
index aba5c4770..356ec7d0a 100644
--- a/backends/imgui_impl_allegro5.h
+++ b/backends/imgui_impl_allegro5.h
@@ -4,9 +4,9 @@
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID!
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
-//  [X] Platform: Clipboard support (from Allegro 5.1.12)
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
-// Issues:
+//  [X] Platform: Clipboard support (from Allegro 5.1.12).
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+// Missing features or Issues:
 //  [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually.
 //  [ ] Platform: Missing gamepad support.
 
diff --git a/backends/imgui_impl_android.cpp b/backends/imgui_impl_android.cpp
index 05939293c..1c2d62476 100644
--- a/backends/imgui_impl_android.cpp
+++ b/backends/imgui_impl_android.cpp
@@ -4,10 +4,10 @@
 // Implemented features:
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
-// Missing features:
+// Missing features or Issues:
 //  [ ] Platform: Clipboard support.
 //  [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
+//  [ ] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
 // Important:
 //  - Consider using SDL or GLFW backend on Android, which will be more full-featured than this.
 //  - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446)
diff --git a/backends/imgui_impl_android.h b/backends/imgui_impl_android.h
index efe27dcb9..3eaeca725 100644
--- a/backends/imgui_impl_android.h
+++ b/backends/imgui_impl_android.h
@@ -4,10 +4,10 @@
 // Implemented features:
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
-// Missing features:
+// Missing features or Issues:
 //  [ ] Platform: Clipboard support.
 //  [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
+//  [ ] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
 // Important:
 //  - Consider using SDL or GLFW backend on Android, which will be more full-featured than this.
 //  - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446)
diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp
index 2638caf9c..f160803ee 100644
--- a/backends/imgui_impl_dx10.cpp
+++ b/backends/imgui_impl_dx10.cpp
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h
index 667f296f1..29f339370 100644
--- a/backends/imgui_impl_dx10.h
+++ b/backends/imgui_impl_dx10.h
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp
index 4a87c23a1..a2c67ec43 100644
--- a/backends/imgui_impl_dx11.cpp
+++ b/backends/imgui_impl_dx11.cpp
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h
index c3b8379b1..69ae49358 100644
--- a/backends/imgui_impl_dx11.h
+++ b/backends/imgui_impl_dx11.h
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index a02094128..bad823c4a 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index 34938fb56..0ade2ac99 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp
index ee0e23940..2cc8681a6 100644
--- a/backends/imgui_impl_dx9.cpp
+++ b/backends/imgui_impl_dx9.cpp
@@ -3,8 +3,8 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR is supported, as this is the optimal color encoding for DirectX9.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
+//  [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_dx9.h b/backends/imgui_impl_dx9.h
index c096b3398..b693054d9 100644
--- a/backends/imgui_impl_dx9.h
+++ b/backends/imgui_impl_dx9.h
@@ -3,8 +3,8 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
-//  [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR is supported, as this is the optimal color encoding for DirectX9.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
+//  [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp
index 1cdb2534f..01a6a5566 100644
--- a/backends/imgui_impl_glfw.cpp
+++ b/backends/imgui_impl_glfw.cpp
@@ -8,7 +8,7 @@
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h
index 5d8940a0c..53a22415d 100644
--- a/backends/imgui_impl_glfw.h
+++ b/backends/imgui_impl_glfw.h
@@ -7,7 +7,7 @@
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_glut.cpp b/backends/imgui_impl_glut.cpp
index 6bb9eae7e..ef7f17922 100644
--- a/backends/imgui_impl_glut.cpp
+++ b/backends/imgui_impl_glut.cpp
@@ -7,7 +7,7 @@
 
 // Implemented features:
 //  [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values are obsolete since 1.87 and not supported since 1.91.5]
-// Issues:
+// Missing features or Issues:
 //  [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I
 //  [ ] Platform: Missing horizontal mouse wheel support.
 //  [ ] Platform: Missing mouse cursor shape/visibility support.
diff --git a/backends/imgui_impl_glut.h b/backends/imgui_impl_glut.h
index feeca8b3f..20e77dbce 100644
--- a/backends/imgui_impl_glut.h
+++ b/backends/imgui_impl_glut.h
@@ -7,7 +7,7 @@
 
 // Implemented features:
 //  [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values are obsolete since 1.87 and not supported since 1.91.5]
-// Issues:
+// Missing features or Issues:
 //  [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I
 //  [ ] Platform: Missing horizontal mouse wheel support.
 //  [ ] Platform: Missing mouse cursor shape/visibility support.
diff --git a/backends/imgui_impl_metal.h b/backends/imgui_impl_metal.h
index 2402c02c6..351c2eff7 100644
--- a/backends/imgui_impl_metal.h
+++ b/backends/imgui_impl_metal.h
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm
index 12dc3d50f..5680dea9d 100644
--- a/backends/imgui_impl_metal.mm
+++ b/backends/imgui_impl_metal.mm
@@ -3,7 +3,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp
index 789d74afb..767731fb3 100644
--- a/backends/imgui_impl_opengl2.cpp
+++ b/backends/imgui_impl_opengl2.cpp
@@ -3,6 +3,8 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
+// Missing features or Issues:
+//  [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_opengl2.h b/backends/imgui_impl_opengl2.h
index e7f7a58c1..5832a1765 100644
--- a/backends/imgui_impl_opengl2.h
+++ b/backends/imgui_impl_opengl2.h
@@ -3,6 +3,8 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
+// Missing features or Issues:
+//  [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp
index 8f3177837..efcfb8217 100644
--- a/backends/imgui_impl_opengl3.cpp
+++ b/backends/imgui_impl_opengl3.cpp
@@ -5,7 +5,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
-//  [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only).
+//  [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!]
 
 // About WebGL/ES:
 // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h
index 54545f957..5de51cfdd 100644
--- a/backends/imgui_impl_opengl3.h
+++ b/backends/imgui_impl_opengl3.h
@@ -5,7 +5,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
-//  [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only).
+//  [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!]
 
 // About WebGL/ES:
 // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h
index 4caab8ff5..2e7eabb2b 100644
--- a/backends/imgui_impl_osx.h
+++ b/backends/imgui_impl_osx.h
@@ -4,11 +4,11 @@
 // - Requires linking with the GameController framework ("-framework GameController").
 
 // Implemented features:
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend).
 //  [X] Platform: Mouse support. Can discriminate Mouse/Pen.
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
-//  [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend).
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 //  [X] Platform: IME support.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm
index c99ba1f06..c2a5f6378 100644
--- a/backends/imgui_impl_osx.mm
+++ b/backends/imgui_impl_osx.mm
@@ -4,11 +4,11 @@
 // - Requires linking with the GameController framework ("-framework GameController").
 
 // Implemented features:
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend).
 //  [X] Platform: Mouse support. Can discriminate Mouse/Pen.
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
-//  [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend).
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 //  [X] Platform: IME support.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp
index af5f6b013..e937b5496 100644
--- a/backends/imgui_impl_sdl2.cpp
+++ b/backends/imgui_impl_sdl2.cpp
@@ -8,7 +8,7 @@
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 //  [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_sdl2.h b/backends/imgui_impl_sdl2.h
index e071e9715..3c4775697 100644
--- a/backends/imgui_impl_sdl2.h
+++ b/backends/imgui_impl_sdl2.h
@@ -7,7 +7,7 @@
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 //  [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp
index 0955859a5..a167c74cd 100644
--- a/backends/imgui_impl_sdl3.cpp
+++ b/backends/imgui_impl_sdl3.cpp
@@ -9,7 +9,8 @@
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: IME support.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h
index b86aa1901..0d906a65c 100644
--- a/backends/imgui_impl_sdl3.h
+++ b/backends/imgui_impl_sdl3.h
@@ -9,7 +9,8 @@
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: IME support.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp
index 485adabb3..6d0ee564f 100644
--- a/backends/imgui_impl_sdlrenderer2.cpp
+++ b/backends/imgui_impl_sdlrenderer2.cpp
@@ -9,7 +9,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h
index 804ca183d..7aed18d21 100644
--- a/backends/imgui_impl_sdlrenderer2.h
+++ b/backends/imgui_impl_sdlrenderer2.h
@@ -9,7 +9,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp
index 1238246c2..1bcf7a228 100644
--- a/backends/imgui_impl_sdlrenderer3.cpp
+++ b/backends/imgui_impl_sdlrenderer3.cpp
@@ -11,7 +11,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h
index 7d4c609e8..3a7a51ee5 100644
--- a/backends/imgui_impl_sdlrenderer3.h
+++ b/backends/imgui_impl_sdlrenderer3.h
@@ -11,7 +11,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index 1491ccabf..b41970304 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -2,8 +2,8 @@
 // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
 
 // Implemented features:
-//  [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h
index 8d9e19f9a..37f700b62 100644
--- a/backends/imgui_impl_vulkan.h
+++ b/backends/imgui_impl_vulkan.h
@@ -2,8 +2,8 @@
 // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
 
 // Implemented features:
-//  [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp
index 02a8caeb4..2f34c0e0b 100644
--- a/backends/imgui_impl_wgpu.cpp
+++ b/backends/imgui_impl_wgpu.cpp
@@ -4,7 +4,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h
index f9fb03776..7efb02afe 100644
--- a/backends/imgui_impl_wgpu.h
+++ b/backends/imgui_impl_wgpu.h
@@ -11,7 +11,7 @@
 
 // Implemented features:
 //  [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
-//  [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
+//  [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
 //  [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp
index 843ef161b..f1cf6eccc 100644
--- a/backends/imgui_impl_win32.cpp
+++ b/backends/imgui_impl_win32.cpp
@@ -6,7 +6,7 @@
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
diff --git a/backends/imgui_impl_win32.h b/backends/imgui_impl_win32.h
index 0dfd56a80..083fe385f 100644
--- a/backends/imgui_impl_win32.h
+++ b/backends/imgui_impl_win32.h
@@ -6,7 +6,7 @@
 //  [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
 //  [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values are obsolete since 1.87 and not supported since 1.91.5]
 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
-//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
+//  [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
 
 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.

From 18e5d769fd7fc48b809ee3b8f6bef6906289251d Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 5 Dec 2024 13:08:33 +0100
Subject: [PATCH 0526/2359] Backends: DX10: create sampler outside of
 ImGui_ImplDX11_CreateFontsTexture().

Analoguous to 90dd510 for DX11.
---
 backends/imgui_impl_dx10.cpp | 42 +++++++++++++++++++++++-------------
 1 file changed, 27 insertions(+), 15 deletions(-)

diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp
index f160803ee..15f0bb323 100644
--- a/backends/imgui_impl_dx10.cpp
+++ b/backends/imgui_impl_dx10.cpp
@@ -341,21 +341,16 @@ static void ImGui_ImplDX10_CreateFontsTexture()
 
     // Store our identifier
     io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView);
+}
 
-    // Create texture sampler
-    // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
+static void ImGui_ImplDX10_DestroyFontsTexture()
+{
+    ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
+    if (bd->pFontTextureView)
     {
-        D3D10_SAMPLER_DESC desc;
-        ZeroMemory(&desc, sizeof(desc));
-        desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
-        desc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
-        desc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
-        desc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
-        desc.MipLODBias = 0.f;
-        desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
-        desc.MinLOD = 0.f;
-        desc.MaxLOD = 0.f;
-        bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
+        bd->pFontTextureView->Release();
+        bd->pFontTextureView = nullptr;
+        ImGui::GetIO().Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
     }
 }
 
@@ -508,6 +503,22 @@ bool    ImGui_ImplDX10_CreateDeviceObjects()
         bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
     }
 
+    // Create texture sampler
+    // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
+    {
+        D3D10_SAMPLER_DESC desc;
+        ZeroMemory(&desc, sizeof(desc));
+        desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
+        desc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
+        desc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
+        desc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
+        desc.MipLODBias = 0.f;
+        desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
+        desc.MinLOD = 0.f;
+        desc.MaxLOD = 0.f;
+        bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
+    }
+
     ImGui_ImplDX10_CreateFontsTexture();
 
     return true;
@@ -519,8 +530,9 @@ void    ImGui_ImplDX10_InvalidateDeviceObjects()
     if (!bd->pd3dDevice)
         return;
 
+    ImGui_ImplDX10_DestroyFontsTexture();
+
     if (bd->pFontSampler)           { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
-    if (bd->pFontTextureView)       { bd->pFontTextureView->Release(); bd->pFontTextureView = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
     if (bd->pIB)                    { bd->pIB->Release(); bd->pIB = nullptr; }
     if (bd->pVB)                    { bd->pVB->Release(); bd->pVB = nullptr; }
     if (bd->pBlendState)            { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
@@ -582,7 +594,7 @@ void ImGui_ImplDX10_NewFrame()
     ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
     IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?");
 
-    if (!bd->pFontSampler)
+    if (!bd->pVertexShader)
         ImGui_ImplDX10_CreateDeviceObjects();
 }
 

From 3f3c62a3c999ae7004d6871c504c0694c9b9e2b1 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 9 Dec 2024 11:43:00 +0100
Subject: [PATCH 0527/2359] ScrollbarEx: clarify use of flags and make them
 optional. (#8215)

---
 imgui_internal.h  | 2 +-
 imgui_widgets.cpp | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index fd8a185a5..147e30c35 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -3398,7 +3398,7 @@ namespace ImGui
     IMGUI_API bool          CloseButton(ImGuiID id, const ImVec2& pos);
     IMGUI_API bool          CollapseButton(ImGuiID id, const ImVec2& pos);
     IMGUI_API void          Scrollbar(ImGuiAxis axis);
-    IMGUI_API bool          ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags flags);
+    IMGUI_API bool          ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags draw_rounding_flags = 0);
     IMGUI_API ImRect        GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis);
     IMGUI_API ImGuiID       GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis);
     IMGUI_API ImGuiID       GetWindowResizeCornerID(ImGuiWindow* window, int n); // 0..3: corners
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index f9939cec4..cf6891ea1 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -950,7 +950,7 @@ void ImGui::Scrollbar(ImGuiAxis axis)
 // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
 // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
 // Still, the code should probably be made simpler..
-bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 size_visible_v, ImS64 size_contents_v, ImDrawFlags flags)
+bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 size_visible_v, ImS64 size_contents_v, ImDrawFlags draw_rounding_flags)
 {
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = g.CurrentWindow;
@@ -1041,7 +1041,7 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6
     // Render
     const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg);
     const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);
-    window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, flags);
+    window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, draw_rounding_flags);
     ImRect grab_rect;
     if (axis == ImGuiAxis_X)
         grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y);

From 2671f68f7f8cb77bf951779c0c8e437f6171a324 Mon Sep 17 00:00:00 2001
From: slowriot 
Date: Fri, 6 Dec 2024 17:50:44 +0000
Subject: [PATCH 0528/2359] Don't enable SSE4 under Emscripten (#8213, #8169,
 #4933)

Amend 326dc95f9
---
 imgui.cpp        | 10 +++++-----
 imgui_internal.h |  4 ++++
 2 files changed, 9 insertions(+), 5 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 5f6c85900..5833691db 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -2150,7 +2150,7 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end,
     }
 }
 
-#ifndef IMGUI_ENABLE_SSE4_2
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
 // CRC32 needs a 1KB lookup table (not cache friendly)
 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
@@ -2184,7 +2184,7 @@ ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
     ImU32 crc = ~seed;
     const unsigned char* data = (const unsigned char*)data_p;
     const unsigned char *data_end = (const unsigned char*)data_p + data_size;
-#ifndef IMGUI_ENABLE_SSE4_2
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
     const ImU32* crc32_lut = GCrc32LookupTable;
     while (data < data_end)
         crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
@@ -2212,7 +2212,7 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
     seed = ~seed;
     ImU32 crc = seed;
     const unsigned char* data = (const unsigned char*)data_p;
-#ifndef IMGUI_ENABLE_SSE4_2
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
     const ImU32* crc32_lut = GCrc32LookupTable;
 #endif
     if (data_size != 0)
@@ -2222,7 +2222,7 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
             unsigned char c = *data++;
             if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
                 crc = seed;
-#ifndef IMGUI_ENABLE_SSE4_2
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
             crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
 #else
             crc = _mm_crc32_u8(crc, c);
@@ -2235,7 +2235,7 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
         {
             if (c == '#' && data[0] == '#' && data[1] == '#')
                 crc = seed;
-#ifndef IMGUI_ENABLE_SSE4_2
+#ifndef IMGUI_ENABLE_SSE4_2_CRC
             crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
 #else
             crc = _mm_crc32_u8(crc, c);
diff --git a/imgui_internal.h b/imgui_internal.h
index 147e30c35..f11f272c3 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -66,6 +66,10 @@ Index of this file:
 #include 
 #endif
 #endif
+// Emscripten has partial SSE 4.2 support where _mm_crc32_u32 is not available. See https://emscripten.org/docs/porting/simd.html#id11 and #8213
+#if defined(IMGUI_ENABLE_SSE4_2) || !defined(__EMSCRIPTEN__)
+#define IMGUI_ENABLE_SSE4_2_CRC
+#endif
 
 // Visual Studio warnings
 #ifdef _MSC_VER

From 53dd7552dcbef379a57f33bb5e35f12ae04a3d8d Mon Sep 17 00:00:00 2001
From: bmarques1995 
Date: Mon, 9 Dec 2024 01:19:23 -0300
Subject: [PATCH 0529/2359] Backends: DX12: let the user specifies the
 DepthStencilView format. (#8217)

This is particullarly important for those who use RenderPasses.
---
 backends/imgui_impl_dx12.cpp              | 4 ++++
 backends/imgui_impl_dx12.h                | 3 ++-
 docs/CHANGELOG.txt                        | 2 ++
 examples/example_win32_directx12/main.cpp | 1 +
 4 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp
index bad823c4a..16dcf5392 100644
--- a/backends/imgui_impl_dx12.cpp
+++ b/backends/imgui_impl_dx12.cpp
@@ -19,6 +19,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat. 
 //  2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
 //  2024-11-15: DirectX12: *BREAKING CHANGE* User is now required to pass function pointers to allocate/free SRV Descriptors. We provide convenience legacy fields to pass a single descriptor, matching the old API, but upcoming features will want multiple.
 //  2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
@@ -72,6 +73,7 @@ struct ImGui_ImplDX12_Data
     ID3D12RootSignature*        pRootSignature;
     ID3D12PipelineState*        pPipelineState;
     DXGI_FORMAT                 RTVFormat;
+    DXGI_FORMAT                 DSVFormat;
     ID3D12DescriptorHeap*       pd3dSrvDescHeap;
     UINT                        numFramesInFlight;
 
@@ -569,6 +571,7 @@ bool    ImGui_ImplDX12_CreateDeviceObjects()
     psoDesc.SampleMask = UINT_MAX;
     psoDesc.NumRenderTargets = 1;
     psoDesc.RTVFormats[0] = bd->RTVFormat;
+    psoDesc.DSVFormat = bd->DSVFormat;
     psoDesc.SampleDesc.Count = 1;
     psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
 
@@ -735,6 +738,7 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
 
     bd->pd3dDevice = init_info->Device;
     bd->RTVFormat = init_info->RTVFormat;
+    bd->DSVFormat = init_info->DSVFormat;
     bd->numFramesInFlight = init_info->NumFramesInFlight;
     bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
 
diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h
index 0ade2ac99..644c022ff 100644
--- a/backends/imgui_impl_dx12.h
+++ b/backends/imgui_impl_dx12.h
@@ -29,7 +29,8 @@ struct ImGui_ImplDX12_InitInfo
     ID3D12Device*               Device;
     ID3D12CommandQueue*         CommandQueue;
     int                         NumFramesInFlight;
-    DXGI_FORMAT                 RTVFormat;
+    DXGI_FORMAT                 RTVFormat;          // RenderTarget format.
+    DXGI_FORMAT                 DSVFormat;          // DepthStencilView format.
     void*                       UserData;
 
     // Allocating SRV descriptors for textures is up to the application, so we provide callbacks.
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 874c7502f..8a1cc931e 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -67,6 +67,8 @@ Other changes:
 - Fonts: fixed AddCustomRect() not being packed with TexGlyphPadding + not accounted
   for surface area used to determine best-guess texture size. (#8107) [@YarikTH, @ocornut]
 - Misc: use SSE 4.2 crc32 instructions when available. (#8169, #4933) [@Teselka]
+- Backends: DirectX12: Let user specifies the DepthStencilView format by setting 
+  ImGui_ImplDX12_InitInfo::DSVFormat. (#8217) [@bmarques1995]
 - Backends: Vulkan: Make user-provided descriptor pool optional. As a convenience,
   when setting init_info->DescriptorPoolSize then the backend will create and manage
   one itself. (#8172, #4867) [@zeux]
diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp
index eeff99c1b..392ba18aa 100644
--- a/examples/example_win32_directx12/main.cpp
+++ b/examples/example_win32_directx12/main.cpp
@@ -146,6 +146,7 @@ int main(int, char**)
     init_info.CommandQueue = g_pd3dCommandQueue;
     init_info.NumFramesInFlight = APP_NUM_FRAMES_IN_FLIGHT;
     init_info.RTVFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
+    init_info.DSVFormat = DXGI_FORMAT_UNKNOWN;
     // Allocating SRV descriptors (for textures) is up to the application, so we provide callbacks.
     // (current version of the backend will only allocate one descriptor, future versions will need to allocate more)
     init_info.SrvDescriptorHeap = g_pd3dSrvDescHeap;

From fce07bb1cb4cdd64dbf825223b74be1d9b28b76b Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 9 Dec 2024 12:43:49 +0100
Subject: [PATCH 0530/2359] Don't enable SSE4 under Emscripten - Fix. (#8213,
 #8169, #4933)

---
 imgui_internal.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index f11f272c3..cccecf702 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -67,7 +67,7 @@ Index of this file:
 #endif
 #endif
 // Emscripten has partial SSE 4.2 support where _mm_crc32_u32 is not available. See https://emscripten.org/docs/porting/simd.html#id11 and #8213
-#if defined(IMGUI_ENABLE_SSE4_2) || !defined(__EMSCRIPTEN__)
+#if defined(IMGUI_ENABLE_SSE4_2) && !defined(__EMSCRIPTEN__)
 #define IMGUI_ENABLE_SSE4_2_CRC
 #endif
 

From 6b348622bb8c0cd4adf5b5f4ec6da5d24ba55a93 Mon Sep 17 00:00:00 2001
From: Thomas Hope 
Date: Sat, 30 Nov 2024 16:55:46 +0100
Subject: [PATCH 0531/2359] Examples: SDL2+OpenGL3: Provide ES3 context
 creation code + failure handling. (#8197)

---
 examples/example_sdl2_opengl3/main.cpp | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp
index 2a4d7b9e7..cb0ade097 100644
--- a/examples/example_sdl2_opengl3/main.cpp
+++ b/examples/example_sdl2_opengl3/main.cpp
@@ -35,12 +35,19 @@ int main(int, char**)
 
     // Decide GL+GLSL versions
 #if defined(IMGUI_IMPL_OPENGL_ES2)
-    // GL ES 2.0 + GLSL 100
+    // GL ES 2.0 + GLSL 100 (WebGL 1.0)
     const char* glsl_version = "#version 100";
     SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
     SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
     SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
     SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
+#elif defined(IMGUI_IMPL_OPENGL_ES3)
+    // GL ES 3.0 + GLSL 300 es (WebGL 2.0)
+    const char* glsl_version = "#version 300 es";
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
 #elif defined(__APPLE__)
     // GL 3.2 Core + GLSL 150
     const char* glsl_version = "#version 150";
@@ -75,6 +82,12 @@ int main(int, char**)
     }
 
     SDL_GLContext gl_context = SDL_GL_CreateContext(window);
+    if (gl_context == nullptr)
+    {
+        printf("Error: SDL_GL_CreateContext(): %s\n", SDL_GetError());
+        return -1;
+    }
+    
     SDL_GL_MakeCurrent(window, gl_context);
     SDL_GL_SetSwapInterval(1); // Enable vsync
 

From 921c22f5adce8b5941cbf47bb7efcd02e6cc8fe5 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 9 Dec 2024 12:55:33 +0100
Subject: [PATCH 0532/2359] Examples: GLFW+OpenGL3, SDL3+OpenGL3: Provide ES3
 context creation code + failure handling. (#8197)

Untested for GLFW example.
---
 examples/example_glfw_opengl3/main.cpp |  8 +++++++-
 examples/example_sdl3_opengl3/main.cpp | 15 ++++++++++++++-
 2 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp
index 3afe251e3..e5f29d405 100644
--- a/examples/example_glfw_opengl3/main.cpp
+++ b/examples/example_glfw_opengl3/main.cpp
@@ -43,11 +43,17 @@ int main(int, char**)
 
     // Decide GL+GLSL versions
 #if defined(IMGUI_IMPL_OPENGL_ES2)
-    // GL ES 2.0 + GLSL 100
+    // GL ES 2.0 + GLSL 100 (WebGL 1.0)
     const char* glsl_version = "#version 100";
     glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
     glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
     glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
+#elif defined(IMGUI_IMPL_OPENGL_ES3)
+    // GL ES 3.0 + GLSL 300 es (WebGL 2.0)
+    const char* glsl_version = "#version 300 es";
+    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
+    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
+    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
 #elif defined(__APPLE__)
     // GL 3.2 + GLSL 150
     const char* glsl_version = "#version 150";
diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp
index e7f239f47..5520a7da9 100644
--- a/examples/example_sdl3_opengl3/main.cpp
+++ b/examples/example_sdl3_opengl3/main.cpp
@@ -35,12 +35,19 @@ int main(int, char**)
 
     // Decide GL+GLSL versions
 #if defined(IMGUI_IMPL_OPENGL_ES2)
-    // GL ES 2.0 + GLSL 100
+    // GL ES 2.0 + GLSL 100 (WebGL 1.0)
     const char* glsl_version = "#version 100";
     SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
     SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
     SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
     SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
+#elif defined(IMGUI_IMPL_OPENGL_ES3)
+    // GL ES 3.0 + GLSL 300 es (WebGL 2.0)
+    const char* glsl_version = "#version 300 es";
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
 #elif defined(__APPLE__)
     // GL 3.2 Core + GLSL 150
     const char* glsl_version = "#version 150";
@@ -70,6 +77,12 @@ int main(int, char**)
     }
     SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
     SDL_GLContext gl_context = SDL_GL_CreateContext(window);
+    if (gl_context == nullptr)
+    {
+        printf("Error: SDL_GL_CreateContext(): %s\n", SDL_GetError());
+        return -1;
+    }
+
     SDL_GL_MakeCurrent(window, gl_context);
     SDL_GL_SetSwapInterval(1); // Enable vsync
     SDL_ShowWindow(window);

From f3147f446a7f3ad79f642421a56d2742e6bd210d Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 9 Dec 2024 12:58:32 +0100
Subject: [PATCH 0533/2359] Backends: OpenGL3: call glGetString(GL_VERSION)
 even in GS ES 2.0 path. (#8197)

Apparently as per specs works. I reckon the best way to confirm it is to try.
---
 backends/imgui_impl_opengl3.cpp | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp
index efcfb8217..b47ac9ab1 100644
--- a/backends/imgui_impl_opengl3.cpp
+++ b/backends/imgui_impl_opengl3.cpp
@@ -297,15 +297,13 @@ bool    ImGui_ImplOpenGL3_Init(const char* glsl_version)
     io.BackendRendererName = "imgui_impl_opengl3";
 
     // Query for GL version (e.g. 320 for GL 3.2)
+    const char* gl_version_str = (const char*)glGetString(GL_VERSION);
 #if defined(IMGUI_IMPL_OPENGL_ES2)
     // GLES 2
-    const char* gl_version_str = "";
-    IM_UNUSED(gl_version_str); // For IMGUI_IMPL_OPENGL_DEBUG block below.
     bd->GlVersion = 200;
     bd->GlProfileIsES2 = true;
 #else
     // Desktop or GLES 3
-    const char* gl_version_str = (const char*)glGetString(GL_VERSION);
     GLint major = 0;
     GLint minor = 0;
     glGetIntegerv(GL_MAJOR_VERSION, &major);

From d2645423de8eb035a70de3cf1bed016d5c10161e Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 9 Dec 2024 14:26:53 +0100
Subject: [PATCH 0534/2359] InputText: reactivating last activated InputText()
 doesn't restore horizontal scrolling.

Honestly not sure if the opposite is preferable or not (added commented out in the inactivate render path to test that).
Current behavior added along with recycling: f9928e96c7c762f97bbdf8cf48e04097b56da84a
---
 docs/CHANGELOG.txt | 2 ++
 imgui_widgets.cpp  | 5 +++--
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 8a1cc931e..42026c9cd 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -58,6 +58,8 @@ Other changes:
   processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
 - Tables: fixed SetNextWindowScroll() value being ignored by BeginTable() during
   the first frame or when scrolling flags have changed. (#8196)
+- InputText: reactivating last activated InputText() doesn't restore horizontal scrolling
+  (which was disabled during deactivation anyway).
 - Misc: changed embedded ProggyClean encoding to save a bit of binary space (~12kb to 9.5kb).
 - Misc: added IMGUI_DISABLE_DEFAULT_FONT to strip embedded font from binary. (#8161)
   [@demonese]
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index cf6891ea1..65a58d53b 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4537,6 +4537,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         state->TextA.resize(buf_size + 1);          // we use +1 to make sure that .Data is always pointing to at least an empty string.
         state->TextLen = (int)strlen(buf);
         memcpy(state->TextA.Data, buf, state->TextLen + 1);
+        state->Scroll = ImVec2(0.0f, 0.0f);
 
         if (recycle_state)
         {
@@ -4546,7 +4547,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         }
         else
         {
-            state->Scroll = ImVec2(0.0f, 0.0f);
             stb_textedit_initialize_state(state->Stb, !is_multiline);
         }
 
@@ -5287,8 +5287,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
 
         if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
         {
+            const ImVec2 draw_scroll = /*state ? ImVec2(state->Scroll.x, 0.0f) :*/ ImVec2(0.0f, 0.0f); // Preserve scroll when inactive?
             ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
-            draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
+            draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
         }
     }
 

From d78e823449f491dbd3cd158b72fdee7cd4d72aa6 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 9 Dec 2024 14:31:28 +0100
Subject: [PATCH 0535/2359] InputText: added ImGuiInputTextFlags_ElideLeft.
 (#1442, #1440, #4391, #7208, #8216)

---
 docs/CHANGELOG.txt |  3 +++
 imgui.h            | 17 ++++++++++-------
 imgui_demo.cpp     | 10 ++++++++++
 imgui_widgets.cpp  |  9 +++++++++
 4 files changed, 32 insertions(+), 7 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 42026c9cd..70dfb7b9d 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -58,6 +58,9 @@ Other changes:
   processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
 - Tables: fixed SetNextWindowScroll() value being ignored by BeginTable() during
   the first frame or when scrolling flags have changed. (#8196)
+- InputText: added ImGuiInputTextFlags_ElideLeft to elide left side and ensure right side
+  of contents is visible when whole text is not fitting (useful for paths/filenames).
+  (#1442, #1440, #4391, #7208, #8216) [@kucoman, @ocornut]
 - InputText: reactivating last activated InputText() doesn't restore horizontal scrolling
   (which was disabled during deactivation anyway).
 - Misc: changed embedded ProggyClean encoding to save a bit of binary space (~12kb to 9.5kb).
diff --git a/imgui.h b/imgui.h
index b86c7d4e5..c9b42e4c7 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.6 WIP"
-#define IMGUI_VERSION_NUM   19152
+#define IMGUI_VERSION_NUM   19153
 #define IMGUI_HAS_TABLE
 
 /*
@@ -1171,13 +1171,16 @@ enum ImGuiInputTextFlags_
     ImGuiInputTextFlags_NoHorizontalScroll  = 1 << 15,  // Disable following the cursor horizontally
     ImGuiInputTextFlags_NoUndoRedo          = 1 << 16,  // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID().
 
+    // Elide display / Alignment
+    ImGuiInputTextFlags_ElideLeft			= 1 << 17,	// When text doesn't fit, elide left side to ensure right side stays visible. Useful for path/filenames. Single-line only!
+
     // Callback features
-    ImGuiInputTextFlags_CallbackCompletion  = 1 << 17,  // Callback on pressing TAB (for completion handling)
-    ImGuiInputTextFlags_CallbackHistory     = 1 << 18,  // Callback on pressing Up/Down arrows (for history handling)
-    ImGuiInputTextFlags_CallbackAlways      = 1 << 19,  // Callback on each iteration. User code may query cursor position, modify text buffer.
-    ImGuiInputTextFlags_CallbackCharFilter  = 1 << 20,  // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
-    ImGuiInputTextFlags_CallbackResize      = 1 << 21,  // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this)
-    ImGuiInputTextFlags_CallbackEdit        = 1 << 22,  // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)
+    ImGuiInputTextFlags_CallbackCompletion  = 1 << 18,  // Callback on pressing TAB (for completion handling)
+    ImGuiInputTextFlags_CallbackHistory     = 1 << 19,  // Callback on pressing Up/Down arrows (for history handling)
+    ImGuiInputTextFlags_CallbackAlways      = 1 << 20,  // Callback on each iteration. User code may query cursor position, modify text buffer.
+    ImGuiInputTextFlags_CallbackCharFilter  = 1 << 21,  // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
+    ImGuiInputTextFlags_CallbackResize      = 1 << 22,  // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this)
+    ImGuiInputTextFlags_CallbackEdit        = 1 << 23,  // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)
 
     // Obsolete names
     //ImGuiInputTextFlags_AlwaysInsertMode  = ImGuiInputTextFlags_AlwaysOverwrite   // [renamed in 1.82] name was not matching behavior
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 5efbe6304..ae91761a3 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1830,6 +1830,16 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data)
             ImGui::TreePop();
         }
 
+        IMGUI_DEMO_MARKER("Widgets/Text Input/Eliding, Alignment");
+        if (ImGui::TreeNode("Eliding, Alignment"))
+        {
+            static char buf1[128] = "/path/to/some/folder/with/long/filename.cpp";
+            static ImGuiInputTextFlags flags = ImGuiInputTextFlags_ElideLeft;
+            ImGui::CheckboxFlags("ImGuiInputTextFlags_ElideLeft", &flags, ImGuiInputTextFlags_ElideLeft);
+            ImGui::InputText("Path", buf1, IM_ARRAYSIZE(buf1), flags);
+            ImGui::TreePop();
+        }
+
         IMGUI_DEMO_MARKER("Widgets/Text Input/Miscellaneous");
         if (ImGui::TreeNode("Miscellaneous"))
         {
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 65a58d53b..4a579d4e3 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4403,6 +4403,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     IM_ASSERT(buf != NULL && buf_size >= 0);
     IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline)));        // Can't use both together (they both use up/down keys)
     IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
+    IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline)));               // Multiline will not work with left-trimming
 
     ImGuiContext& g = *GImGui;
     ImGuiIO& io = g.IO;
@@ -4537,7 +4538,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         state->TextA.resize(buf_size + 1);          // we use +1 to make sure that .Data is always pointing to at least an empty string.
         state->TextLen = (int)strlen(buf);
         memcpy(state->TextA.Data, buf, state->TextLen + 1);
+
+        // Find initial scroll position for right alignment
         state->Scroll = ImVec2(0.0f, 0.0f);
+        if (flags & ImGuiInputTextFlags_ElideLeft)
+            state->Scroll.x += ImMax(0.0f, CalcTextSize(buf).x - frame_size.x + style.FramePadding.x * 2.0f);
 
         if (recycle_state)
         {
@@ -5287,6 +5292,10 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
 
         if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
         {
+            // Find render position for right alignment
+            if (flags & ImGuiInputTextFlags_ElideLeft)
+                draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x);
+
             const ImVec2 draw_scroll = /*state ? ImVec2(state->Scroll.x, 0.0f) :*/ ImVec2(0.0f, 0.0f); // Preserve scroll when inactive?
             ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
             draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);

From c3ffd4c53e90276f5ad1504553bf5c628f15c9ec Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 11 Dec 2024 12:13:28 +0100
Subject: [PATCH 0536/2359] Misc: Added IMGUI_USE_LEGACY_CRC32_ADLER to use old
 tables. (#8169, #4933)

---
 docs/CHANGELOG.txt | 11 ++++++++---
 imconfig.h         |  3 +++
 imgui.cpp          | 26 ++++++++++++++++++++++++--
 imgui.h            |  2 +-
 imgui_internal.h   |  2 +-
 5 files changed, 37 insertions(+), 7 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 70dfb7b9d..7ef8580b8 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -48,9 +48,14 @@ Breaking changes:
   - We provide convenience legacy fields to pass a single descriptor,
     matching the old API, but upcoming features will want multiple.
   - Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
-- Misc: changed CRC32 table to use CRC32c polynomial in order to be compatible
-  with the result of SSE 4.2 instructions. As a result, old .ini data may be
-  partially lost. (#8169, #4933) [@Teselka]
+- Misc: changed CRC32 table from CRC32-adler to CRC32c polynomial in order to 
+  be compatible with the result of SSE 4.2 instructions. (#8169, #4933) [@Teselka]
+  - As a result, some .ini data may be partially lost when storing checksums
+    (docking and tables information particularly). 
+  - Because some users have crafted and storing .ini data as a way to workaround 
+    limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER'
+    compile-time option to keep using old CRC32 tables if you cannot afford invalidating
+    old .ini data.
 
 Other changes:
 
diff --git a/imconfig.h b/imconfig.h
index 6790f147a..8f8bc3b9a 100644
--- a/imconfig.h
+++ b/imconfig.h
@@ -62,6 +62,9 @@
 //---- Pack vertex colors as BGRA8 instead of RGBA8 (to avoid converting from one to another). Need dedicated backend support.
 //#define IMGUI_USE_BGRA_PACKED_COLOR
 
+//---- Use legacy CRC32-adler tables (used before 1.91.6), in order to preserve old .ini data that you cannot afford to invalidate.
+//#define IMGUI_USE_LEGACY_CRC32_ADLER
+
 //---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
 //#define IMGUI_USE_WCHAR32
 
diff --git a/imgui.cpp b/imgui.cpp
index 5833691db..e4199c2b0 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -429,7 +429,9 @@ CODE
  When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
  You can read releases logs https://github.com/ocornut/imgui/releases for more details.
 
- - 2024/11/27 (1.91.6) - changed CRC32 table to use CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions. As a result, old .ini data may be partially lost.
+ - 2024/11/27 (1.91.6) - changed CRC32 table from CRC32-adler to CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions.
+                         As a result, old .ini data may be partially lost (docking and tables information particularly).
+                         Because some users have crafted and storing .ini data as a way to workaround limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER' compile-time option to keep using old CRC32 tables if you cannot afford invalidating old .ini data.
  - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before)
                             - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022).
                             - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022).
@@ -2154,9 +2156,28 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end,
 // CRC32 needs a 1KB lookup table (not cache friendly)
 // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
 // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
-// On 2024/11/27 this was changed from crc32-adler to crc32c (polynomial 0x1EDC6F41), which invalidated some hashes stored in .ini files.
 static const ImU32 GCrc32LookupTable[256] =
 {
+#ifdef IMGUI_USE_LEGACY_CRC32_ADLER
+    // Legacy CRC32-adler table used pre 1.91.6 (before 2024/11/27). Only use if you cannot afford invalidating old .ini data.
+    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
+    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
+    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
+    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
+    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
+    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
+    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
+    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
+    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
+    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
+    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
+    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
+    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
+    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
+    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
+    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
+#else
+    // CRC32c table compatible with SSE 4.2 instructions
     0x00000000,0xF26B8303,0xE13B70F7,0x1350F3F4,0xC79A971F,0x35F1141C,0x26A1E7E8,0xD4CA64EB,0x8AD958CF,0x78B2DBCC,0x6BE22838,0x9989AB3B,0x4D43CFD0,0xBF284CD3,0xAC78BF27,0x5E133C24,
     0x105EC76F,0xE235446C,0xF165B798,0x030E349B,0xD7C45070,0x25AFD373,0x36FF2087,0xC494A384,0x9A879FA0,0x68EC1CA3,0x7BBCEF57,0x89D76C54,0x5D1D08BF,0xAF768BBC,0xBC267848,0x4E4DFB4B,
     0x20BD8EDE,0xD2D60DDD,0xC186FE29,0x33ED7D2A,0xE72719C1,0x154C9AC2,0x061C6936,0xF477EA35,0xAA64D611,0x580F5512,0x4B5FA6E6,0xB93425E5,0x6DFE410E,0x9F95C20D,0x8CC531F9,0x7EAEB2FA,
@@ -2173,6 +2194,7 @@ static const ImU32 GCrc32LookupTable[256] =
     0xD3D3E1AB,0x21B862A8,0x32E8915C,0xC083125F,0x144976B4,0xE622F5B7,0xF5720643,0x07198540,0x590AB964,0xAB613A67,0xB831C993,0x4A5A4A90,0x9E902E7B,0x6CFBAD78,0x7FAB5E8C,0x8DC0DD8F,
     0xE330A81A,0x115B2B19,0x020BD8ED,0xF0605BEE,0x24AA3F05,0xD6C1BC06,0xC5914FF2,0x37FACCF1,0x69E9F0D5,0x9B8273D6,0x88D28022,0x7AB90321,0xAE7367CA,0x5C18E4C9,0x4F48173D,0xBD23943E,
     0xF36E6F75,0x0105EC76,0x12551F82,0xE03E9C81,0x34F4F86A,0xC69F7B69,0xD5CF889D,0x27A40B9E,0x79B737BA,0x8BDCB4B9,0x988C474D,0x6AE7C44E,0xBE2DA0A5,0x4C4623A6,0x5F16D052,0xAD7D5351
+#endif
 };
 #endif
 
diff --git a/imgui.h b/imgui.h
index c9b42e4c7..8b5c358a9 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.6 WIP"
-#define IMGUI_VERSION_NUM   19153
+#define IMGUI_VERSION_NUM   19154
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index cccecf702..379f6cb14 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -67,7 +67,7 @@ Index of this file:
 #endif
 #endif
 // Emscripten has partial SSE 4.2 support where _mm_crc32_u32 is not available. See https://emscripten.org/docs/porting/simd.html#id11 and #8213
-#if defined(IMGUI_ENABLE_SSE4_2) && !defined(__EMSCRIPTEN__)
+#if defined(IMGUI_ENABLE_SSE4_2) && !defined(IMGUI_USE_LEGACY_CRC32_ADLER) && !defined(__EMSCRIPTEN__)
 #define IMGUI_ENABLE_SSE4_2_CRC
 #endif
 

From 2ca83f0bc72fcaca5631766b5fcb05fd3d0e102d Mon Sep 17 00:00:00 2001
From: Stewart Mccready 
Date: Wed, 11 Dec 2024 13:14:46 +0000
Subject: [PATCH 0537/2359] Fixed missing symbols when using
 IMGUI_DISABLE_DEMO_WINDOWS (e.g. with ImPlot) (#8221)

---
 imgui_demo.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index ae91761a3..9e5c03fa3 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -10397,6 +10397,8 @@ void ImGui::ShowAboutWindow(bool*) {}
 void ImGui::ShowDemoWindow(bool*) {}
 void ImGui::ShowUserGuide() {}
 void ImGui::ShowStyleEditor(ImGuiStyle*) {}
+bool ImGui::ShowStyleSelector(const char* label) { return false; }
+void ImGui::ShowFontSelector(const char* label) {}
 
 #endif
 

From 993fa347495860ed44b83574254ef2a317d0c14f Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 11 Dec 2024 14:17:45 +0100
Subject: [PATCH 0538/2359] Version 1.91.6

---
 docs/CHANGELOG.txt | 14 +++++++-------
 docs/README.md     |  2 +-
 imgui.cpp          |  6 +++---
 imgui.h            | 16 ++++++++--------
 imgui_demo.cpp     |  2 +-
 imgui_draw.cpp     |  4 ++--
 imgui_internal.h   | 10 ++++------
 imgui_tables.cpp   |  2 +-
 imgui_widgets.cpp  |  8 ++++----
 9 files changed, 31 insertions(+), 33 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 7ef8580b8..2d04ee093 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -36,7 +36,7 @@ HOW TO UPDATE?
 - Please report any issue!
 
 -----------------------------------------------------------------------
- VERSION 1.91.6 WIP (In Progress)
+ VERSION 1.91.6 (Released 2024-12-11)
 -----------------------------------------------------------------------
 
 Breaking changes:
@@ -48,18 +48,18 @@ Breaking changes:
   - We provide convenience legacy fields to pass a single descriptor,
     matching the old API, but upcoming features will want multiple.
   - Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
-- Misc: changed CRC32 table from CRC32-adler to CRC32c polynomial in order to 
+- Misc: changed CRC32 table from CRC32-adler to CRC32c polynomial in order to
   be compatible with the result of SSE 4.2 instructions. (#8169, #4933) [@Teselka]
   - As a result, some .ini data may be partially lost when storing checksums
-    (docking and tables information particularly). 
-  - Because some users have crafted and storing .ini data as a way to workaround 
+    (docking and tables information particularly).
+  - Because some users have crafted and storing .ini data as a way to workaround
     limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER'
     compile-time option to keep using old CRC32 tables if you cannot afford invalidating
     old .ini data.
 
 Other changes:
 
-- Error Handling: fixed cases where recoverable error handling would crash when 
+- Error Handling: fixed cases where recoverable error handling would crash when
   processing errors outside of the NewFrame()..EndFrame() scope. (#1651)
 - Tables: fixed SetNextWindowScroll() value being ignored by BeginTable() during
   the first frame or when scrolling flags have changed. (#8196)
@@ -71,13 +71,13 @@ Other changes:
 - Misc: changed embedded ProggyClean encoding to save a bit of binary space (~12kb to 9.5kb).
 - Misc: added IMGUI_DISABLE_DEFAULT_FONT to strip embedded font from binary. (#8161)
   [@demonese]
-- Tools: binary_to_compressed_c: added -u8/-u32/-base85 export options.
 - Demo: example tree used by Property Editor & Selection demos properly freed
   on application closure. (#8158) [@Legulysse]
 - Fonts: fixed AddCustomRect() not being packed with TexGlyphPadding + not accounted
   for surface area used to determine best-guess texture size. (#8107) [@YarikTH, @ocornut]
 - Misc: use SSE 4.2 crc32 instructions when available. (#8169, #4933) [@Teselka]
-- Backends: DirectX12: Let user specifies the DepthStencilView format by setting 
+- Tools: binary_to_compressed_c: added -u8/-u32/-base85 export options.
+- Backends: DirectX12: Let user specifies the DepthStencilView format by setting
   ImGui_ImplDX12_InitInfo::DSVFormat. (#8217) [@bmarques1995]
 - Backends: Vulkan: Make user-provided descriptor pool optional. As a convenience,
   when setting init_info->DescriptorPoolSize then the backend will create and manage
diff --git a/docs/README.md b/docs/README.md
index c47f03b9b..388d8eac6 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -110,7 +110,7 @@ Reading the changelogs is a good way to keep up to date with the things Dear ImG
 Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing a variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. [Here's how the demo looks](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png).
 
 You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here:
-- [imgui-demo-binaries-20240105.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20240105.zip) (Windows, 1.90.1 WIP, built 2024/01/05, master) or [older binaries](https://www.dearimgui.com/binaries).
+- [imgui-demo-binaries-20241211.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20241211.zip) (Windows, 1.91.6, built 2024/11/11, master) or [older binaries](https://www.dearimgui.com/binaries).
 
 The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at a different scale and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.com/faq)).
 
diff --git a/imgui.cpp b/imgui.cpp
index e4199c2b0..26e56b804 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6 WIP
+// dear imgui, v1.91.6
 // (main code and documentation)
 
 // Help:
@@ -4748,15 +4748,15 @@ void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr
     }
     if (size != (size_t)-1)
     {
+        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, (int)size, ptr);
         entry->AllocCount++;
         info->TotalAllocCount++;
-        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
     }
     else
     {
+        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
         entry->FreeCount++;
         info->TotalFreeCount++;
-        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
     }
 }
 
diff --git a/imgui.h b/imgui.h
index 8b5c358a9..64be995cb 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6 WIP
+// dear imgui, v1.91.6
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.6 WIP"
-#define IMGUI_VERSION_NUM   19154
+#define IMGUI_VERSION       "1.91.6"
+#define IMGUI_VERSION_NUM   19160
 #define IMGUI_HAS_TABLE
 
 /*
@@ -3429,24 +3429,24 @@ struct ImFontAtlas
 // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().
 struct ImFont
 {
-    // Members: Hot ~20/24 bytes (for CalcTextSize)
+    // [Internal] Members: Hot ~20/24 bytes (for CalcTextSize)
     ImVector             IndexAdvanceX;      // 12-16 // out //            // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI).
     float                       FallbackAdvanceX;   // 4     // out // = FallbackGlyph->AdvanceX
     float                       FontSize;           // 4     // in  //            // Height of characters/line, set during loading (don't change after loading)
 
-    // Members: Hot ~28/40 bytes (for CalcTextSize + render loop)
+    // [Internal] Members: Hot ~28/40 bytes (for RenderText loop)
     ImVector           IndexLookup;        // 12-16 // out //            // Sparse. Index glyphs by Unicode code-point.
     ImVector       Glyphs;             // 12-16 // out //            // All glyphs.
     const ImFontGlyph*          FallbackGlyph;      // 4-8   // out // = FindGlyph(FontFallbackChar)
 
-    // Members: Cold ~32/40 bytes
+    // [Internal] Members: Cold ~32/40 bytes
     // Conceptually ConfigData[] is the list of font sources merged to create this font.
     ImFontAtlas*                ContainerAtlas;     // 4-8   // out //            // What we has been loaded into
     const ImFontConfig*         ConfigData;         // 4-8   // in  //            // Pointer within ContainerAtlas->ConfigData to ConfigDataCount instances
     short                       ConfigDataCount;    // 2     // in  // ~ 1        // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont.
-    ImWchar                     FallbackChar;       // 2     // out // = FFFD/'?' // Character used if a glyph isn't found.
-    ImWchar                     EllipsisChar;       // 2     // out // = '...'/'.'// Character used for ellipsis rendering.
     short                       EllipsisCharCount;  // 1     // out // 1 or 3
+    ImWchar                     EllipsisChar;       // 2-4   // out // = '...'/'.'// Character used for ellipsis rendering.
+    ImWchar                     FallbackChar;       // 2-4   // out // = FFFD/'?' // Character used if a glyph isn't found.
     float                       EllipsisWidth;      // 4     // out               // Width
     float                       EllipsisCharStep;   // 4     // out               // Step between characters when EllipsisCount > 0
     bool                        DirtyLookupTables;  // 1     // out //
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 9e5c03fa3..a9f9d832b 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6 WIP
+// dear imgui, v1.91.6
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 631472a71..9ae0162e4 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6 WIP
+// dear imgui, v1.91.6
 // (drawing and font code)
 
 /*
@@ -396,7 +396,7 @@ void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error)
 
 ImDrawList::ImDrawList(ImDrawListSharedData* shared_data)
 {
-    memset(this, 0, sizeof(*this)); 
+    memset(this, 0, sizeof(*this));
     _Data = shared_data;
 }
 
diff --git a/imgui_internal.h b/imgui_internal.h
index 379f6cb14..45715cc31 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6 WIP
+// dear imgui, v1.91.6
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
@@ -778,11 +778,9 @@ struct IMGUI_API ImDrawListSharedData
     float           CircleSegmentMaxError;      // Number of circle segments to use per pixel of radius for AddCircle() etc
     ImVec4          ClipRectFullscreen;         // Value for PushClipRectFullscreen()
     ImDrawListFlags InitialFlags;               // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards)
+    ImVector TempBuffer;                // Temporary write buffer
 
-    // [Internal] Temp write buffer
-    ImVector TempBuffer;
-
-    // [Internal] Lookup tables
+    // Lookup tables
     ImVec2          ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle.
     float           ArcFastRadiusCutoff;                        // Cutoff radius after which arc drawing will fallback to slower PathArcTo()
     ImU8            CircleSegmentCounts[64];    // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead)
@@ -3392,7 +3390,7 @@ namespace ImGui
     IMGUI_API void          TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0);
     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          ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0);
+    IMGUI_API bool          ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, 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);
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index db34aa347..f4e76225a 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6 WIP
+// dear imgui, v1.91.6
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 4a579d4e3..3fc500ab8 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6 WIP
+// dear imgui, v1.91.6
 // (widgets code)
 
 /*
@@ -1073,7 +1073,7 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const I
     window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
 }
 
-bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags)
+bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags)
 {
     ImGuiContext& g = *GImGui;
     ImGuiWindow* window = GetCurrentWindow();
@@ -1095,7 +1095,7 @@ bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& imag
     RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding));
     if (bg_col.w > 0.0f)
         window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
-    window->DrawList->AddImage(texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
+    window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
 
     return pressed;
 }
@@ -1114,7 +1114,7 @@ bool ImGui::ImageButton(const char* str_id, ImTextureID user_texture_id, const I
 
 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
 // Legacy API obsoleted in 1.89. Two differences with new ImageButton()
-// - old ImageButton() used ImTextureId as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID)
+// - old ImageButton() used ImTextureID as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID)
 // - new ImageButton() requires an explicit 'const char* str_id'
 // - old ImageButton() had frame_padding' override argument.
 // - new ImageButton() always use style.FramePadding.

From f25665f36003abb5fa856b040b312344483f0031 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 11 Dec 2024 15:37:16 +0100
Subject: [PATCH 0539/2359] Version 1.91.7 WIP

---
 docs/CHANGELOG.txt | 11 +++++++++++
 imgui.cpp          |  2 +-
 imgui.h            |  6 +++---
 imgui_demo.cpp     |  2 +-
 imgui_draw.cpp     |  2 +-
 imgui_internal.h   |  2 +-
 imgui_tables.cpp   |  2 +-
 imgui_widgets.cpp  |  2 +-
 8 files changed, 20 insertions(+), 9 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 2d04ee093..68f5d8d4c 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -35,10 +35,21 @@ HOW TO UPDATE?
   and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users.
 - Please report any issue!
 
+-----------------------------------------------------------------------
+ VERSION 1.91.7 WIP (In Progress)
+-----------------------------------------------------------------------
+
+Breaking changes:
+
+Other changes:
+
+
 -----------------------------------------------------------------------
  VERSION 1.91.6 (Released 2024-12-11)
 -----------------------------------------------------------------------
 
+Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.6
+
 Breaking changes:
 
 - Backends: DX12: Changed ImGui_ImplDX12_Init() signature to take a
diff --git a/imgui.cpp b/imgui.cpp
index 26e56b804..7325c1952 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6
+// dear imgui, v1.91.7 WIP
 // (main code and documentation)
 
 // Help:
diff --git a/imgui.h b/imgui.h
index 64be995cb..0a61b1dea 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6
+// dear imgui, v1.91.7 WIP
 // (headers)
 
 // Help:
@@ -28,8 +28,8 @@
 
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
-#define IMGUI_VERSION       "1.91.6"
-#define IMGUI_VERSION_NUM   19160
+#define IMGUI_VERSION       "1.91.7 WIP"
+#define IMGUI_VERSION_NUM   19161
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index a9f9d832b..6010aad44 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6
+// dear imgui, v1.91.7 WIP
 // (demo code)
 
 // Help:
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 9ae0162e4..b231764b6 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6
+// dear imgui, v1.91.7 WIP
 // (drawing and font code)
 
 /*
diff --git a/imgui_internal.h b/imgui_internal.h
index 45715cc31..1f7426696 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6
+// dear imgui, v1.91.7 WIP
 // (internal structures/api)
 
 // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility.
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index f4e76225a..7dd97c6f2 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6
+// dear imgui, v1.91.7 WIP
 // (tables and columns code)
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 3fc500ab8..2d0fed4e0 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.91.6
+// dear imgui, v1.91.7 WIP
 // (widgets code)
 
 /*

From e487eb9da0805519261687339da2e77686ed9efc Mon Sep 17 00:00:00 2001
From: Mahmood - Zer0xFF <5013823+Zer0xFF@users.noreply.github.com>
Date: Wed, 11 Dec 2024 13:30:35 +0000
Subject: [PATCH 0540/2359] Backends: Vulkan: Fixed setting
 VkSwapchainCreateInfoKHR::preTransform for platforms not supporting
 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222)

---
 backends/imgui_impl_vulkan.cpp | 11 ++++++-----
 docs/CHANGELOG.txt             |  3 +++
 2 files changed, 9 insertions(+), 5 deletions(-)

diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp
index b41970304..1de6e2353 100644
--- a/backends/imgui_impl_vulkan.cpp
+++ b/backends/imgui_impl_vulkan.cpp
@@ -26,6 +26,7 @@
 
 // CHANGELOG
 // (minor and older changes stripped away, please see git history for details)
+//  2024-12-11: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222)
 //  2024-11-27: Vulkan: Make user-provided descriptor pool optional. As a convenience, when setting init_info->DescriptorPoolSize the backend will create one itself. (#8172, #4867)
 //  2024-10-07: Vulkan: Changed default texture sampler to Clamp instead of Repeat/Wrap.
 //  2024-10-07: Vulkan: Expose selected render state in ImGui_ImplVulkan_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
@@ -1426,6 +1427,10 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V
 
     // Create Swapchain
     {
+        VkSurfaceCapabilitiesKHR cap;
+        err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap);
+        check_vk_result(err);
+
         VkSwapchainCreateInfoKHR info = {};
         info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
         info.surface = wd->Surface;
@@ -1435,19 +1440,15 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V
         info.imageArrayLayers = 1;
         info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
         info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;           // Assume that graphics family == present family
-        info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
+        info.preTransform = (cap.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR : cap.currentTransform;
         info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
         info.presentMode = wd->PresentMode;
         info.clipped = VK_TRUE;
         info.oldSwapchain = old_swapchain;
-        VkSurfaceCapabilitiesKHR cap;
-        err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap);
-        check_vk_result(err);
         if (info.minImageCount < cap.minImageCount)
             info.minImageCount = cap.minImageCount;
         else if (cap.maxImageCount != 0 && info.minImageCount > cap.maxImageCount)
             info.minImageCount = cap.maxImageCount;
-
         if (cap.currentExtent.width == 0xffffffff)
         {
             info.imageExtent.width = wd->Width = w;
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 68f5d8d4c..d95012d9f 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,9 @@ Breaking changes:
 
 Other changes:
 
+- Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for
+  platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF]
+
 
 -----------------------------------------------------------------------
  VERSION 1.91.6 (Released 2024-12-11)

From 1d069cf43527bdf81b42289f7c385efac129c3a0 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 11 Dec 2024 16:43:29 +0100
Subject: [PATCH 0541/2359] Fonts: store 0 for unset EllipsisChar/FallbackChar.
 Pull config in BuildLookupTable().

---
 imgui.h        |  2 +-
 imgui_draw.cpp | 19 ++++++++-----------
 2 files changed, 9 insertions(+), 12 deletions(-)

diff --git a/imgui.h b/imgui.h
index 0a61b1dea..7fbb610f2 100644
--- a/imgui.h
+++ b/imgui.h
@@ -3244,7 +3244,7 @@ struct ImFontConfig
     unsigned int    FontBuilderFlags;       // 0        // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure.
     float           RasterizerMultiply;     // 1.0f     // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future.
     float           RasterizerDensity;      // 1.0f     // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display. IMPORTANT: If you increase this it is expected that you increase font scale accordingly, otherwise quality may look lowered.
-    ImWchar         EllipsisChar;           // -1       // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.
+    ImWchar         EllipsisChar;           // 0        // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.
 
     // [Internal]
     char            Name[40];               // Name (strictly to ease debugging)
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index b231764b6..f51fff3a6 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -2377,7 +2377,7 @@ ImFontConfig::ImFontConfig()
     GlyphMaxAdvanceX = FLT_MAX;
     RasterizerMultiply = 1.0f;
     RasterizerDensity = 1.0f;
-    EllipsisChar = (ImWchar)-1;
+    EllipsisChar = 0;
 }
 
 //-----------------------------------------------------------------------------
@@ -2564,9 +2564,6 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
     // - We may support it better later and remove this rounding.
     new_font_cfg.SizePixels = ImTrunc(new_font_cfg.SizePixels);
 
-    if (new_font_cfg.DstFont->EllipsisChar == (ImWchar)-1)
-        new_font_cfg.DstFont->EllipsisChar = font_cfg->EllipsisChar;
-
     // Pointers to ConfigData and BuilderData are otherwise dangling
     ImFontAtlasUpdateConfigDataPointers(this);
 
@@ -3635,8 +3632,8 @@ ImFont::ImFont()
 {
     FontSize = 0.0f;
     FallbackAdvanceX = 0.0f;
-    FallbackChar = (ImWchar)-1;
-    EllipsisChar = (ImWchar)-1;
+    FallbackChar = 0;
+    EllipsisChar = 0;
     EllipsisWidth = EllipsisCharStep = 0.0f;
     EllipsisCharCount = 0;
     FallbackGlyph = NULL;
@@ -3675,7 +3672,7 @@ static ImWchar FindFirstExistingGlyph(ImFont* font, const ImWchar* candidate_cha
     for (int n = 0; n < candidate_chars_count; n++)
         if (font->FindGlyphNoFallback(candidate_chars[n]) != NULL)
             return candidate_chars[n];
-    return (ImWchar)-1;
+    return 0;
 }
 
 void ImFont::BuildLookupTable()
@@ -3742,17 +3739,17 @@ void ImFont::BuildLookupTable()
     // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis).
     // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character.
     // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots.
-    const ImWchar ellipsis_chars[] = { (ImWchar)0x2026, (ImWchar)0x0085 };
+    const ImWchar ellipsis_chars[] = { ConfigData->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 };
     const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E };
-    if (EllipsisChar == (ImWchar)-1)
+    if (EllipsisChar == 0)
         EllipsisChar = FindFirstExistingGlyph(this, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars));
     const ImWchar dot_char = FindFirstExistingGlyph(this, dots_chars, IM_ARRAYSIZE(dots_chars));
-    if (EllipsisChar != (ImWchar)-1)
+    if (EllipsisChar != 0)
     {
         EllipsisCharCount = 1;
         EllipsisWidth = EllipsisCharStep = FindGlyph(EllipsisChar)->X1;
     }
-    else if (dot_char != (ImWchar)-1)
+    else if (dot_char != 0)
     {
         const ImFontGlyph* glyph = FindGlyph(dot_char);
         EllipsisChar = dot_char;

From 4cc464eadc12a158fb7ccd9b2843277ee894f163 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 12 Dec 2024 15:14:14 +0100
Subject: [PATCH 0542/2359] BeginListBox(): Comments (#8220)

---
 imgui.h           |  1 +
 imgui_widgets.cpp | 11 +++--------
 2 files changed, 4 insertions(+), 8 deletions(-)

diff --git a/imgui.h b/imgui.h
index 7fbb610f2..69f106dd6 100644
--- a/imgui.h
+++ b/imgui.h
@@ -692,6 +692,7 @@ namespace ImGui
 
     // Widgets: List Boxes
     // - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
+    // - If you don't need a label you can probably simply use BeginChild() with the ImGuiChildFlags_FrameStyle flag for the same result.
     // - You can submit contents and manage your selection state however you want it, by creating e.g. Selectable() or any other items.
     // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous 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
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 2d0fed4e0..9f4baef0f 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -8206,15 +8206,10 @@ void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
 //-------------------------------------------------------------------------
 
 // This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
-// This handle some subtleties with capturing info from the label, but for 99% uses it could essentially be rewritten as:
-//    if (ImGui::BeginChild("...", ImVec2(ImGui::CalcItemWidth(), ImGui::GetTextLineHeight() * 7.5f), ImGuiChildFlags_FrameStyle))
-//        { .... }
-//    ImGui::EndChild();
-//    ImGui::SameLine();
-//    ImGui::AlignTextToFramePadding();
-//    ImGui::Text("Label");
+// This handle some subtleties with capturing info from the label.
+// 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.25 * item_height).
+// 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)
 {
     ImGuiContext& g = *GImGui;

From f9f4e22f6f7d08e31152e9219d8533e4c265f4de Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 12 Dec 2024 16:40:08 +0100
Subject: [PATCH 0543/2359] InputText: some tidying up. (#7925)

---
 imgui_internal.h  |  5 +++--
 imgui_widgets.cpp | 49 +++++++++++++++++------------------------------
 2 files changed, 21 insertions(+), 33 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index 1f7426696..fed655e03 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1121,6 +1121,7 @@ struct IMGUI_API ImGuiInputTextState
 {
     ImGuiContext*           Ctx;                    // parent UI context (needs to be set explicitly by parent).
     ImStbTexteditState*     Stb;                    // State for stb_textedit.h
+    ImGuiInputTextFlags     Flags;                  // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set.
     ImGuiID                 ID;                     // widget id owning the text state
     int                     TextLen;                // UTF-8 length of the string in TextA (in bytes)
     ImVector          TextA;                  // main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1).
@@ -1132,9 +1133,8 @@ struct IMGUI_API ImGuiInputTextState
     bool                    CursorFollow;           // set when we want scrolling to follow the current cursor position (not always!)
     bool                    SelectedAllMouseLock;   // after a double-click to select all, we ignore further mouse drags to update selection
     bool                    Edited;                 // edited this frame
-    ImGuiInputTextFlags     Flags;                  // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set.
     bool                    ReloadUserBuf;          // force a reload of user buf so it may be modified externally. may be automatic in future version.
-    int                     ReloadSelectionStart;   // POSITIONS ARE IN IMWCHAR units *NOT* UTF-8 this is why this is not exposed yet.
+    int                     ReloadSelectionStart;
     int                     ReloadSelectionEnd;
 
     ImGuiInputTextState();
@@ -1159,6 +1159,7 @@ struct IMGUI_API ImGuiInputTextState
     //   strcpy(my_buf, "hello");
     //   if (ImGuiInputTextState* state = ImGui::GetInputTextState(id)) // id may be ImGui::GetItemID() is last item
     //       state->ReloadUserBufAndSelectAll();
+    // THIS CURRENTLY RESETS THE UNDO STACK.
     void        ReloadUserBufAndSelectAll();
     void        ReloadUserBufAndKeepSelection();
     void        ReloadUserBufAndMoveToEnd();
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 9f4baef0f..efe0c8f76 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4041,16 +4041,12 @@ static int  STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx)
 
 static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
 {
+    // Offset remaining text (+ copy zero terminator)
     char* dst = obj->TextA.Data + pos;
-
+    char* src = obj->TextA.Data + pos + n;
+    memmove(dst, src, obj->TextLen - n - pos + 1);
     obj->Edited = true;
     obj->TextLen -= n;
-
-    // Offset remaining text (FIXME-OPT: Use memmove)
-    const char* src = obj->TextA.Data + pos + n;
-    while (char c = *src++)
-        *dst++ = c;
-    *dst = '\0';
 }
 
 static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len)
@@ -4174,17 +4170,16 @@ ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
     memset(this, 0, sizeof(*this));
 }
 
-// Public API to manipulate UTF-8 text
-// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
+// Public API to manipulate UTF-8 text from within a callback.
 // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
+// Historically they existed because STB_TEXTEDIT_INSERTCHARS() etc. worked on our ImWchar
+// buffer, but nowadays they both work on UTF-8 data. Should aim to merge both.
 void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)
 {
     IM_ASSERT(pos + bytes_count <= BufTextLen);
     char* dst = Buf + pos;
     const char* src = Buf + pos + bytes_count;
-    while (char c = *src++)
-        *dst++ = c;
-    *dst = '\0';
+    memmove(dst, src, BufTextLen - bytes_count - pos + 1);
 
     if (CursorPos >= pos + bytes_count)
         CursorPos -= bytes_count;
@@ -4209,7 +4204,6 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons
         if (!is_resizable)
             return;
 
-        // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the mildly similar code (until we remove the U16 buffer altogether!)
         ImGuiContext& g = *Ctx;
         ImGuiInputTextState* edit_state = &g.InputTextState;
         IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID);
@@ -4333,26 +4327,23 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im
     return true;
 }
 
-// Find the shortest single replacement we can make to get the new text from the old text.
-// Important: needs to be run before TextW is rewritten with the new characters because calling STB_TEXTEDIT_GETCHAR() at the end.
+// Find the shortest single replacement we can make to get from old_buf to new_buf
+// Note that this doesn't directly alter state->TextA, state->TextLen. They are expected to be made valid separately.
 // FIXME: Ideally we should transition toward (1) making InsertChars()/DeleteChars() update undo-stack (2) discourage (and keep reconcile) or obsolete (and remove reconcile) accessing buffer directly.
-static void InputTextReconcileUndoStateAfterUserCallback(ImGuiInputTextState* state, const char* new_buf_a, int new_length_a)
+static void InputTextReconcileUndoState(ImGuiInputTextState* state, const char* old_buf, int old_length, const char* new_buf, int new_length)
 {
-    const char* old_buf = state->CallbackTextBackup.Data;
-    const int old_length = state->CallbackTextBackup.Size - 1;
-
-    const int shorter_length = ImMin(old_length, new_length_a);
+    const int shorter_length = ImMin(old_length, new_length);
     int first_diff;
     for (first_diff = 0; first_diff < shorter_length; first_diff++)
-        if (old_buf[first_diff] != new_buf_a[first_diff])
+        if (old_buf[first_diff] != new_buf[first_diff])
             break;
-    if (first_diff == old_length && first_diff == new_length_a)
+    if (first_diff == old_length && first_diff == new_length)
         return;
 
     int old_last_diff = old_length   - 1;
-    int new_last_diff = new_length_a - 1;
+    int new_last_diff = new_length - 1;
     for (; old_last_diff >= first_diff && new_last_diff >= first_diff; old_last_diff--, new_last_diff--)
-        if (old_buf[old_last_diff] != new_buf_a[new_last_diff])
+        if (old_buf[old_last_diff] != new_buf[new_last_diff])
             break;
 
     const int insert_len = new_last_diff - first_diff + 1;
@@ -4544,16 +4535,12 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         if (flags & ImGuiInputTextFlags_ElideLeft)
             state->Scroll.x += ImMax(0.0f, CalcTextSize(buf).x - frame_size.x + style.FramePadding.x * 2.0f);
 
+        // Recycle existing cursor/selection/undo stack but clamp position
+        // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
         if (recycle_state)
-        {
-            // Recycle existing cursor/selection/undo stack but clamp position
-            // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
             state->CursorClamp();
-        }
         else
-        {
             stb_textedit_initialize_state(state->Stb, !is_multiline);
-        }
 
         if (init_reload_from_user_buf)
         {
@@ -5039,7 +5026,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     {
                         // Callback may update buffer and thus set buf_dirty even in read-only mode.
                         IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
-                        InputTextReconcileUndoStateAfterUserCallback(state, callback_data.Buf, callback_data.BufTextLen); // FIXME: Move the rest of this block inside function and rename to InputTextReconcileStateAfterUserCallback() ?
+                        InputTextReconcileUndoState(state, state->CallbackTextBackup.Data, state->CallbackTextBackup.Size - 1, callback_data.Buf, callback_data.BufTextLen);
                         state->TextLen = callback_data.BufTextLen;  // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
                         state->CursorAnimReset();
                     }

From 4ad5496474b006376c2b5b55b54519335eadb873 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 12 Dec 2024 18:39:28 +0100
Subject: [PATCH 0544/2359] Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to
 disable keyboard modifiers altering the tweak speed. (#8223)

---
 docs/CHANGELOG.txt | 3 +++
 imgui.h            | 1 +
 imgui_demo.cpp     | 2 ++
 imgui_widgets.cpp  | 6 +++---
 4 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index d95012d9f..21a927f4b 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,9 @@ Breaking changes:
 
 Other changes:
 
+- Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard
+  modifiers altering the tweak speed. Useful if you want to alter tweak speed
+  yourself based on your own logic. (#8223)
 - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for
   platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF]
 
diff --git a/imgui.h b/imgui.h
index 69f106dd6..eec3dce65 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1788,6 +1788,7 @@ enum ImGuiSliderFlags_
     ImGuiSliderFlags_WrapAround         = 1 << 8,       // Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now.
     ImGuiSliderFlags_ClampOnInput       = 1 << 9,       // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.
     ImGuiSliderFlags_ClampZeroRange     = 1 << 10,      // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it.
+    ImGuiSliderFlags_NoSpeedTweaks      = 1 << 11,      // Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic.
     ImGuiSliderFlags_AlwaysClamp        = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange,
     ImGuiSliderFlags_InvalidMask_       = 0x7000000F,   // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed.
 };
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 6010aad44..c09c8eca7 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -2310,6 +2310,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data)
         ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits).");
         ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput);
         ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget.");
+        ImGui::CheckboxFlags("ImGuiSliderFlags_NoSpeedTweaks", &flags, ImGuiSliderFlags_NoSpeedTweaks);
+        ImGui::SameLine(); HelpMarker("Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic.");
         ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuiSliderFlags_WrapAround);
         ImGui::SameLine(); HelpMarker("Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions)");
 
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index efe0c8f76..82b5714fc 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -2434,9 +2434,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
     if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))
     {
         adjust_delta = g.IO.MouseDelta[axis];
-        if (g.IO.KeyAlt)
+        if (g.IO.KeyAlt && !(flags & ImGuiSliderFlags_NoSpeedTweaks))
             adjust_delta *= 1.0f / 100.0f;
-        if (g.IO.KeyShift)
+        if (g.IO.KeyShift && !(flags & ImGuiSliderFlags_NoSpeedTweaks))
             adjust_delta *= 10.0f;
     }
     else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
@@ -2444,7 +2444,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const
         const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
         const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow);
         const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast);
-        const float tweak_factor = tweak_slow ? 1.0f / 10.0f : tweak_fast ? 10.0f : 1.0f;
+        const float tweak_factor = (flags & ImGuiSliderFlags_NoSpeedTweaks) ? 1.0f : tweak_slow ? 1.0f / 10.0f : tweak_fast ? 10.0f : 1.0f;
         adjust_delta = GetNavTweakPressedAmount(axis) * tweak_factor;
         v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
     }

From 8237ab450e3825e0888892c23d657b2bfaf18e47 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 12 Dec 2024 18:48:42 +0100
Subject: [PATCH 0545/2359] Drags, Sliders: store initial value on activation,
 as a convenience for some mods. (#8223)

---
 imgui.cpp         | 1 +
 imgui_internal.h  | 1 +
 imgui_widgets.cpp | 8 ++++++++
 3 files changed, 10 insertions(+)

diff --git a/imgui.cpp b/imgui.cpp
index 7325c1952..3aa3b1fbf 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -3927,6 +3927,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas)
     ActiveIdPreviousFrameIsAlive = false;
     ActiveIdPreviousFrameHasBeenEditedBefore = false;
     ActiveIdPreviousFrameWindow = NULL;
+    memset(&ActiveIdValueOnActivation, 0, sizeof(ActiveIdValueOnActivation));
     LastActiveId = 0;
     LastActiveIdTimer = 0.0f;
 
diff --git a/imgui_internal.h b/imgui_internal.h
index fed655e03..14fea3691 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -2109,6 +2109,7 @@ struct ImGuiContext
     bool                    ActiveIdPreviousFrameIsAlive;
     bool                    ActiveIdPreviousFrameHasBeenEditedBefore;
     ImGuiWindow*            ActiveIdPreviousFrameWindow;
+    ImGuiDataTypeStorage    ActiveIdValueOnActivation;          // Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX.
     ImGuiID                 LastActiveId;                       // Store the last non-zero ActiveId, useful for animation.
     float                   LastActiveIdTimer;                  // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation.
 
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 82b5714fc..4074a9d73 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -2632,6 +2632,10 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data,
                 temp_input_is_active = true;
             }
 
+        // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
+        if (make_active)
+            memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size);
+
         if (make_active && !temp_input_is_active)
         {
             SetActiveID(id, window);
@@ -3222,6 +3226,10 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat
             if ((clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
                 temp_input_is_active = true;
 
+        // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
+        if (make_active)
+            memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size);
+
         if (make_active && !temp_input_is_active)
         {
             SetActiveID(id, window);

From 324d4bb1402e0d075a30f17b3d3859f813292bb7 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Thu, 12 Dec 2024 17:19:56 +0100
Subject: [PATCH 0546/2359] InputText: calling ReloadUserBuf doesn't clear undo
 stack. (#2890)

---
 imgui_internal.h  |  3 +--
 imgui_widgets.cpp | 42 ++++++++++++++++++++++--------------------
 2 files changed, 23 insertions(+), 22 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index 14fea3691..d371ab9e6 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1133,7 +1133,7 @@ struct IMGUI_API ImGuiInputTextState
     bool                    CursorFollow;           // set when we want scrolling to follow the current cursor position (not always!)
     bool                    SelectedAllMouseLock;   // after a double-click to select all, we ignore further mouse drags to update selection
     bool                    Edited;                 // edited this frame
-    bool                    ReloadUserBuf;          // force a reload of user buf so it may be modified externally. may be automatic in future version.
+    bool                    WantReloadUserBuf;      // force a reload of user buf so it may be modified externally. may be automatic in future version.
     int                     ReloadSelectionStart;
     int                     ReloadSelectionEnd;
 
@@ -1159,7 +1159,6 @@ struct IMGUI_API ImGuiInputTextState
     //   strcpy(my_buf, "hello");
     //   if (ImGuiInputTextState* state = ImGui::GetInputTextState(id)) // id may be ImGui::GetItemID() is last item
     //       state->ReloadUserBufAndSelectAll();
-    // THIS CURRENTLY RESETS THE UNDO STACK.
     void        ReloadUserBufAndSelectAll();
     void        ReloadUserBufAndKeepSelection();
     void        ReloadUserBufAndMoveToEnd();
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 4074a9d73..871759cec 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4169,9 +4169,9 @@ int  ImGuiInputTextState::GetCursorPos() const              { return Stb->cursor
 int  ImGuiInputTextState::GetSelectionStart() const         { return Stb->select_start; }
 int  ImGuiInputTextState::GetSelectionEnd() const           { return Stb->select_end; }
 void ImGuiInputTextState::SelectAll()                       { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; }
-void ImGuiInputTextState::ReloadUserBufAndSelectAll()       { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
-void ImGuiInputTextState::ReloadUserBufAndKeepSelection()   { ReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
-void ImGuiInputTextState::ReloadUserBufAndMoveToEnd()       { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
+void ImGuiInputTextState::ReloadUserBufAndSelectAll()       { WantReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
+void ImGuiInputTextState::ReloadUserBufAndKeepSelection()   { WantReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
+void ImGuiInputTextState::ReloadUserBufAndMoveToEnd()       { WantReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
 
 ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
 {
@@ -4503,32 +4503,40 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
 
     float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX;
 
-    const bool init_reload_from_user_buf = (state != NULL && state->ReloadUserBuf);
+    const bool init_reload_from_user_buf = (state != NULL && state->WantReloadUserBuf);
     const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state.
     const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav);
     const bool init_state = (init_make_active || user_scroll_active);
-    if ((init_state && g.ActiveId != id) || init_changed_specs || init_reload_from_user_buf)
+    if (init_reload_from_user_buf)
+    {
+        int new_len = (int)strlen(buf);
+        state->WantReloadUserBuf = false;
+        InputTextReconcileUndoState(state, state->TextA.Data, state->TextLen, buf, new_len);
+        state->TextA.resize(buf_size + 1);          // we use +1 to make sure that .Data is always pointing to at least an empty string.
+        state->TextLen = new_len;
+        memcpy(state->TextA.Data, buf, state->TextLen + 1);
+        state->Stb->select_start = state->ReloadSelectionStart;
+        state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd;
+        state->CursorClamp();
+    }
+    else if ((init_state && g.ActiveId != id) || init_changed_specs)
     {
         // Access state even if we don't own it yet.
         state = &g.InputTextState;
         state->CursorAnimReset();
-        state->ReloadUserBuf = false;
 
         // Backup state of deactivating item so they'll have a chance to do a write to output buffer on the same frame they report IsItemDeactivatedAfterEdit (#4714)
         InputTextDeactivateHook(state->ID);
 
+        // Take a copy of the initial buffer value.
         // From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode)
         const int buf_len = (int)strlen(buf);
-        if (!init_reload_from_user_buf)
-        {
-            // Take a copy of the initial buffer value.
-            state->TextToRevertTo.resize(buf_len + 1);    // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
-            memcpy(state->TextToRevertTo.Data, buf, buf_len + 1);
-        }
+        state->TextToRevertTo.resize(buf_len + 1);    // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
+        memcpy(state->TextToRevertTo.Data, buf, buf_len + 1);
 
         // Preserve cursor position and undo/redo stack if we come back to same widget
         // FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
-        bool recycle_state = (state->ID == id && !init_changed_specs && !init_reload_from_user_buf);
+        bool recycle_state = (state->ID == id && !init_changed_specs);
         if (recycle_state && (state->TextLen != buf_len || (strncmp(state->TextA.Data, buf, buf_len) != 0)))
             recycle_state = false;
 
@@ -4550,13 +4558,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         else
             stb_textedit_initialize_state(state->Stb, !is_multiline);
 
-        if (init_reload_from_user_buf)
-        {
-            state->Stb->select_start = state->ReloadSelectionStart;
-            state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd;
-            state->CursorClamp();
-        }
-        else if (!is_multiline)
+        if (!is_multiline)
         {
             if (flags & ImGuiInputTextFlags_AutoSelectAll)
                 select_all = true;

From f5f11e94be35078c3bbb5196f55269f88634b9bd Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Sun, 15 Dec 2024 15:46:33 +0100
Subject: [PATCH 0547/2359] InputText: Fixed a bug where character replacements
 performed from a callback were not applied when pasting from clipbard.
 (#8229)

---
 docs/CHANGELOG.txt |  2 ++
 imgui_widgets.cpp  | 22 ++++++++++++----------
 2 files changed, 14 insertions(+), 10 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 21a927f4b..b266f3a15 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -43,6 +43,8 @@ Breaking changes:
 
 Other changes:
 
+- InputText: Fixed a bug where character replacements performed from a callback
+  were not applied when pasting from clipbard. (#8229)
 - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard
   modifiers altering the tweak speed. Useful if you want to alter tweak speed
   yourself based on your own logic. (#8223)
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 871759cec..09c625d3d 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4895,25 +4895,27 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             {
                 // Filter pasted buffer
                 const int clipboard_len = (int)strlen(clipboard);
-                char* clipboard_filtered = (char*)IM_ALLOC(clipboard_len + 1);
-                int clipboard_filtered_len = 0;
+                ImVector clipboard_filtered;
+                clipboard_filtered.reserve(clipboard_len + 1);
                 for (const char* s = clipboard; *s != 0; )
                 {
                     unsigned int c;
-                    int len = ImTextCharFromUtf8(&c, s, NULL);
-                    s += len;
+                    int in_len = ImTextCharFromUtf8(&c, s, NULL);
+                    s += in_len;
                     if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true))
                         continue;
-                    memcpy(clipboard_filtered + clipboard_filtered_len, s - len, len);
-                    clipboard_filtered_len += len;
+                    char c_utf8[5];
+                    ImTextCharToUtf8(c_utf8, c);
+                    int out_len = (int)strlen(c_utf8);
+                    clipboard_filtered.resize(clipboard_filtered.Size + out_len);
+                    memcpy(clipboard_filtered.Data + clipboard_filtered.Size - out_len, c_utf8, out_len);
                 }
-                clipboard_filtered[clipboard_filtered_len] = 0;
-                if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
+                if (clipboard_filtered.Size > 0) // If everything was filtered, ignore the pasting operation
                 {
-                    stb_textedit_paste(state, state->Stb, clipboard_filtered, clipboard_filtered_len);
+                    clipboard_filtered.push_back(0);
+                    stb_textedit_paste(state, state->Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1);
                     state->CursorFollow = true;
                 }
-                MemFree(clipboard_filtered);
             }
         }
 

From 13c4084362b35ce58a25be70b9f1710dfe3377e9 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Mon, 16 Dec 2024 10:51:33 +0100
Subject: [PATCH 0548/2359] Nav: Fixed an issue where Alt key would clear
 current active item on windows with the ImGuiWindowFlags_NoNavInputs flag.
 (#8231)

---
 docs/CHANGELOG.txt |  2 ++
 imgui.cpp          | 21 +++++++++++----------
 2 files changed, 13 insertions(+), 10 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index b266f3a15..eb3db4909 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -48,6 +48,8 @@ Other changes:
 - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard
   modifiers altering the tweak speed. Useful if you want to alter tweak speed
   yourself based on your own logic. (#8223)
+- Nav: Fixed an issue where Alt key would clear current active item on
+  windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231)
 - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for
   platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF]
 
diff --git a/imgui.cpp b/imgui.cpp
index 3aa3b1fbf..896830575 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -4356,7 +4356,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
 
         // This could be written in a more general way (e.g associate a hook to ActiveId),
         // but since this is currently quite an exception we'll leave it as is.
-        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
+        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID()
         if (g.InputTextState.ID == g.ActiveId)
             InputTextDeactivateHook(g.ActiveId);
     }
@@ -13625,15 +13625,16 @@ static void ImGui::NavUpdateWindowing()
     // Keyboard: Press and Release ALT to toggle menu layer
     const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
     bool windowing_toggle_layer_start = false;
-    for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
-        if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
-        {
-            windowing_toggle_layer_start = true;
-            g.NavWindowingToggleLayer = true;
-            g.NavWindowingToggleKey = windowing_toggle_key;
-            g.NavInputSource = ImGuiInputSource_Keyboard;
-            break;
-        }
+    if (g.NavWindow != NULL && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
+        for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
+            if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
+            {
+                windowing_toggle_layer_start = true;
+                g.NavWindowingToggleLayer = true;
+                g.NavWindowingToggleKey = windowing_toggle_key;
+                g.NavInputSource = ImGuiInputSource_Keyboard;
+                break;
+            }
     if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
     {
         // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)

From f31d53093b5031a1de0d43adc2a82c0e93d4d0f6 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 18 Dec 2024 13:02:48 +0100
Subject: [PATCH 0549/2359] TestEngine: for consistency, title bar / window
 items are registered in _Menu layer.

---
 imgui.cpp | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/imgui.cpp b/imgui.cpp
index 896830575..87d0aaa47 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -7391,9 +7391,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
         {
             IM_ASSERT(window->IDStack.Size == 1);
             window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
+            window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
             IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
             IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
             window->IDStack.Size = 1;
+            window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
+
         }
 #endif
 
@@ -7653,7 +7656,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
         // [Test Engine] Register title bar / tab with MoveId.
 #ifdef IMGUI_ENABLE_TEST_ENGINE
         if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
+        {
+            window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
             IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
+            window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
+        }
 #endif
     }
     else

From e900571ac24039d41ebe934cd20d1d3bea7a8118 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 18 Dec 2024 16:14:04 +0100
Subject: [PATCH 0550/2359] InputText: Fixed issue when activating a ReadOnly
 field when the underlying value is being modified. (#8242)

---
 docs/CHANGELOG.txt |  2 ++
 imgui.h            |  2 +-
 imgui_widgets.cpp  | 43 +++++++++++++++++++++++++++++++++++--------
 3 files changed, 38 insertions(+), 9 deletions(-)

diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index eb3db4909..25649c16f 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -45,6 +45,8 @@ Other changes:
 
 - InputText: Fixed a bug where character replacements performed from a callback
   were not applied when pasting from clipbard. (#8229)
+- InputText: Fixed issue when activating a ReadOnly field when the underlying
+  value is being modified. (#8242)
 - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard
   modifiers altering the tweak speed. Useful if you want to alter tweak speed
   yourself based on your own logic. (#8223)
diff --git a/imgui.h b/imgui.h
index eec3dce65..98f0a4d20 100644
--- a/imgui.h
+++ b/imgui.h
@@ -29,7 +29,7 @@
 // Library Version
 // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345')
 #define IMGUI_VERSION       "1.91.7 WIP"
-#define IMGUI_VERSION_NUM   19161
+#define IMGUI_VERSION_NUM   19162
 #define IMGUI_HAS_TABLE
 
 /*
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 09c625d3d..3d135dca9 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -4507,12 +4507,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state.
     const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav);
     const bool init_state = (init_make_active || user_scroll_active);
+    bool readonly_swapped_text_data = false;
     if (init_reload_from_user_buf)
     {
         int new_len = (int)strlen(buf);
         state->WantReloadUserBuf = false;
         InputTextReconcileUndoState(state, state->TextA.Data, state->TextLen, buf, new_len);
-        state->TextA.resize(buf_size + 1);          // we use +1 to make sure that .Data is always pointing to at least an empty string.
+        state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
         state->TextLen = new_len;
         memcpy(state->TextA.Data, buf, state->TextLen + 1);
         state->Stb->select_start = state->ReloadSelectionStart;
@@ -4537,14 +4538,17 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         // Preserve cursor position and undo/redo stack if we come back to same widget
         // FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
         bool recycle_state = (state->ID == id && !init_changed_specs);
-        if (recycle_state && (state->TextLen != buf_len || (strncmp(state->TextA.Data, buf, buf_len) != 0)))
+        if (recycle_state && (state->TextLen != buf_len || (state->TextA.Data == NULL || strncmp(state->TextA.Data, buf, buf_len) != 0)))
             recycle_state = false;
 
         // Start edition
         state->ID = id;
-        state->TextA.resize(buf_size + 1);          // we use +1 to make sure that .Data is always pointing to at least an empty string.
         state->TextLen = (int)strlen(buf);
-        memcpy(state->TextA.Data, buf, state->TextLen + 1);
+        if (!is_readonly)
+        {
+            state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
+            memcpy(state->TextA.Data, buf, state->TextLen + 1);
+        }
 
         // Find initial scroll position for right alignment
         state->Scroll = ImVec2(0.0f, 0.0f);
@@ -4610,6 +4614,21 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             state->Scroll.y = draw_window->Scroll.y;
     }
 
+    if (g.ActiveId == id && is_readonly)
+    {
+        // FIXME: Refresh buffer because cursor/selection code uses that data (see repro #8242)
+        // The "simple" way would be to copy buf into state->TextA, like in the block above.
+        // But because we like to live dangerously, we do a little swap....
+        // Removing the swap and only doing a TextA.clear() is a way to identify who's using TextA.Data.
+        state->TextLen = (int)strlen(buf);
+        state->TextA.clear();
+        state->TextA.Data = buf; // Ouch
+        state->TextA.Size = state->TextLen + 1;
+        readonly_swapped_text_data = true; // Need to always ensure that every code path below lead to this being handled
+        //state->TextA.resize(buf_size + 1);
+        //memcpy(state->TextA.Data, buf, state->TextLen + 1);
+    }
+
     // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
     if (g.ActiveId == id && state == NULL)
         ClearActiveID();
@@ -5008,10 +5027,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
                     callback_data.UserData = callback_user_data;
 
                     // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925
-                    state->CallbackTextBackup.resize(state->TextLen + 1);
-                    memcpy(state->CallbackTextBackup.Data, state->TextA.Data, state->TextLen + 1);
-
                     char* callback_buf = is_readonly ? buf : state->TextA.Data;
+
+                    state->CallbackTextBackup.resize(state->TextLen + 1);
+                    memcpy(state->CallbackTextBackup.Data, callback_buf, state->TextLen + 1);
+
                     callback_data.EventKey = event_key;
                     callback_data.Buf = callback_buf;
                     callback_data.BufTextLen = state->TextLen;
@@ -5142,7 +5162,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         // - Measure text height (for scrollbar)
         // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
         // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
-        const char* text_begin = state->TextA.Data;
+        const char* text_begin = buf_display;
         const char* text_end = text_begin + state->TextLen;
         ImVec2 cursor_offset, select_start_offset;
 
@@ -5304,6 +5324,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     if (is_password && !is_displaying_hint)
         PopFont();
 
+    if (readonly_swapped_text_data)
+    {
+        IM_ASSERT(state->TextA.Data == buf);
+        state->TextA.Size = 0;
+        state->TextA.Data = NULL;
+    }
+
     if (is_multiline)
     {
         // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)...

From 32f11402f96f516be68b56f9eb338f382c544819 Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 18 Dec 2024 16:47:02 +0100
Subject: [PATCH 0551/2359] InputText: use TextSrc more consistently to
 facilitate accessing user buffer in text processing code. (#8242)

Followup to e900571
Removed SetClipboardText() trick used in abd07f6d (#7925)
---
 imgui_internal.h  |  1 +
 imgui_widgets.cpp | 79 +++++++++++++++++++++--------------------------
 2 files changed, 36 insertions(+), 44 deletions(-)

diff --git a/imgui_internal.h b/imgui_internal.h
index d371ab9e6..6be907bb5 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1124,6 +1124,7 @@ struct IMGUI_API ImGuiInputTextState
     ImGuiInputTextFlags     Flags;                  // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set.
     ImGuiID                 ID;                     // widget id owning the text state
     int                     TextLen;                // UTF-8 length of the string in TextA (in bytes)
+    const char*             TextSrc;                // == TextA.Data unless read-only, in which case == buf passed to InputText(). Field only set and valid _inside_ the call InputText() call.
     ImVector          TextA;                  // main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1).
     ImVector          TextToRevertTo;         // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
     ImVector          CallbackTextBackup;     // temporary storage for callback to support automatic reconcile of undo-stack
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 3d135dca9..b0f28903a 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -3938,12 +3938,12 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c
 namespace ImStb
 {
 static int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->TextLen; }
-static char    STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->TextLen); return obj->TextA[idx]; }
-static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
+static char    STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { IM_ASSERT(idx <= obj->TextLen); return obj->TextSrc[idx]; }
+static float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
 static char    STB_TEXTEDIT_NEWLINE = '\n';
 static void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
 {
-    const char* text = obj->TextA.Data;
+    const char* text = obj->TextSrc;
     const char* text_remaining = NULL;
     const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, &text_remaining, NULL, true);
     r->x0 = 0.0f;
@@ -3962,15 +3962,15 @@ static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int id
     if (idx >= obj->TextLen)
         return obj->TextLen + 1;
     unsigned int c;
-    return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->TextLen);
+    return idx + ImTextCharFromUtf8(&c, obj->TextSrc + idx, obj->TextSrc + obj->TextLen);
 }
 
 static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
 {
     if (idx <= 0)
         return -1;
-    const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, obj->TextA.Data + idx);
-    return (int)(p - obj->TextA.Data);
+    const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, obj->TextSrc + idx);
+    return (int)(p - obj->TextSrc);
 }
 
 static bool ImCharIsSeparatorW(unsigned int c)
@@ -3993,10 +3993,10 @@ static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
     if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
         return 0;
 
-    const char* curr_p = obj->TextA.Data + idx;
-    const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
-    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextA.Data + obj->TextLen);
-    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextA.Data + obj->TextLen);
+    const char* curr_p = obj->TextSrc + idx;
+    const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p);
+    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextSrc + obj->TextLen);
+    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextSrc + obj->TextLen);
 
     bool prev_white = ImCharIsBlankW(prev_c);
     bool prev_separ = ImCharIsSeparatorW(prev_c);
@@ -4009,10 +4009,10 @@ static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
     if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
         return 0;
 
-    const char* curr_p = obj->TextA.Data + idx;
-    const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
-    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextA.Data + obj->TextLen);
-    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextA.Data + obj->TextLen);
+    const char* curr_p = obj->TextSrc + idx;
+    const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p);
+    unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextSrc + obj->TextLen);
+    unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextSrc + obj->TextLen);
 
     bool prev_white = ImCharIsBlankW(prev_c);
     bool prev_separ = ImCharIsSeparatorW(prev_c);
@@ -4050,6 +4050,7 @@ static int  STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx)
 static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
 {
     // Offset remaining text (+ copy zero terminator)
+    IM_ASSERT(obj->TextSrc == obj->TextA.Data);
     char* dst = obj->TextA.Data + pos;
     char* src = obj->TextA.Data + pos + n;
     memmove(dst, src, obj->TextLen - n - pos + 1);
@@ -4067,11 +4068,13 @@ static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ch
         return false;
 
     // Grow internal buffer if needed
+    IM_ASSERT(obj->TextSrc == obj->TextA.Data);
     if (new_text_len + text_len + 1 > obj->TextA.Size)
     {
         if (!is_resizable)
             return false;
         obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1);
+        obj->TextSrc = obj->TextA.Data;
     }
 
     char* text = obj->TextA.Data;
@@ -4218,6 +4221,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons
         IM_ASSERT(Buf == edit_state->TextA.Data);
         int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
         edit_state->TextA.resize(new_buf_size + 1);
+        edit_state->TextSrc = edit_state->TextA.Data;
         Buf = edit_state->TextA.Data;
         BufSize = edit_state->BufCapacity = new_buf_size;
     }
@@ -4507,7 +4511,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state.
     const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav);
     const bool init_state = (init_make_active || user_scroll_active);
-    bool readonly_swapped_text_data = false;
     if (init_reload_from_user_buf)
     {
         int new_len = (int)strlen(buf);
@@ -4612,22 +4615,15 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
         // Expose scroll in a manner that is agnostic to us using a child window
         if (is_multiline && state != NULL)
             state->Scroll.y = draw_window->Scroll.y;
-    }
 
-    if (g.ActiveId == id && is_readonly)
-    {
-        // FIXME: Refresh buffer because cursor/selection code uses that data (see repro #8242)
-        // The "simple" way would be to copy buf into state->TextA, like in the block above.
-        // But because we like to live dangerously, we do a little swap....
-        // Removing the swap and only doing a TextA.clear() is a way to identify who's using TextA.Data.
-        state->TextLen = (int)strlen(buf);
-        state->TextA.clear();
-        state->TextA.Data = buf; // Ouch
-        state->TextA.Size = state->TextLen + 1;
-        readonly_swapped_text_data = true; // Need to always ensure that every code path below lead to this being handled
-        //state->TextA.resize(buf_size + 1);
-        //memcpy(state->TextA.Data, buf, state->TextLen + 1);
+        // Read-only mode always ever read from source buffer. Refresh TextLen when active.
+        if (is_readonly && state != NULL)
+            state->TextLen = (int)strlen(buf);
+        //if (is_readonly && state != NULL)
+        //    state->TextA.clear(); // Uncomment to facilitate debugging, but we otherwise prefer to keep/amortize th allocation.
     }
+    if (state != NULL)
+        state->TextSrc = is_readonly ? buf : state->TextA.Data;
 
     // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
     if (g.ActiveId == id && state == NULL)
@@ -4892,13 +4888,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             // Cut, Copy
             if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
             {
+                // SetClipboardText() only takes null terminated strings + state->TextSrc may point to read-only user buffer, so we need to make a copy.
                 const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0;
                 const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->TextLen;
-
-                char backup = state->TextA.Data[ie];
-                state->TextA.Data[ie] = 0; // A bit of a hack since SetClipboardText only takes null terminated strings
-                SetClipboardText(state->TextA.Data + ib);
-                state->TextA.Data[ie] = backup;
+                g.TempBuffer.reserve(ie - ib + 1);
+                memcpy(g.TempBuffer.Data, state->TextSrc, ie - ib);
+                g.TempBuffer.Data[ie] = 0;
+                SetClipboardText(g.TempBuffer.Data);
             }
             if (is_cut)
             {
@@ -5028,7 +5024,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
 
                     // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925
                     char* callback_buf = is_readonly ? buf : state->TextA.Data;
-
+                    IM_ASSERT(callback_buf == state->TextSrc);
                     state->CallbackTextBackup.resize(state->TextLen + 1);
                     memcpy(state->CallbackTextBackup.Data, callback_buf, state->TextLen + 1);
 
@@ -5066,9 +5062,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             }
 
             // Will copy result string if modified
-            if (!is_readonly && strcmp(state->TextA.Data, buf) != 0)
+            if (!is_readonly && strcmp(state->TextSrc, buf) != 0)
             {
-                apply_new_text = state->TextA.Data;
+                apply_new_text = state->TextSrc;
                 apply_new_text_length = state->TextLen;
                 value_changed = true;
             }
@@ -5324,13 +5320,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
     if (is_password && !is_displaying_hint)
         PopFont();
 
-    if (readonly_swapped_text_data)
-    {
-        IM_ASSERT(state->TextA.Data == buf);
-        state->TextA.Size = 0;
-        state->TextA.Data = NULL;
-    }
-
     if (is_multiline)
     {
         // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)...
@@ -5349,6 +5338,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
             g.LastItemData.StatusFlags = item_data_backup.StatusFlags;
         }
     }
+    if (state)
+        state->TextSrc = NULL;
 
     // Log as text
     if (g.LogEnabled && (!is_password || is_displaying_hint))

From cd6c83cdccb78fa1ab20cece35ccc8c3317ecdc8 Mon Sep 17 00:00:00 2001
From: Raffaello Bertini 
Date: Wed, 18 Dec 2024 10:54:16 +0100
Subject: [PATCH 0552/2359] Fixes GCC warnings (#8241)

---
 imgui.cpp         | 6 ++++--
 imgui.h           | 1 +
 imgui_demo.cpp    | 3 +++
 imgui_draw.cpp    | 6 ++++--
 imgui_internal.h  | 3 ++-
 imgui_tables.cpp  | 3 +++
 imgui_widgets.cpp | 4 ++++
 7 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/imgui.cpp b/imgui.cpp
index 87d0aaa47..cf59a5a53 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1095,7 +1095,7 @@ CODE
 #else
 #include 
 #endif
-#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
+#if defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
 // The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
 #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
 #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
@@ -1144,12 +1144,14 @@ CODE
 #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 "-Wint-to-pointer-cast"              // warning: cast to pointer from integer of different size
-#pragma GCC diagnostic ignored "-Wformat"                           // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
+#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 "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
 #pragma GCC diagnostic ignored "-Wconversion"                       // warning: conversion to 'xxxx' from 'xxxx' may alter its value
 #pragma GCC diagnostic ignored "-Wformat-nonliteral"                // warning: format not a string literal, format string not checked
 #pragma GCC diagnostic ignored "-Wstrict-overflow"                  // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
 #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 "-Wcast-qual"                        // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
 #endif
 
 // Debug options
diff --git a/imgui.h b/imgui.h
index 98f0a4d20..e1b8796f3 100644
--- a/imgui.h
+++ b/imgui.h
@@ -139,6 +139,7 @@ Index of this file:
 #elif defined(__GNUC__)
 #pragma GCC diagnostic push
 #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
 #endif
 
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index c09c8eca7..6425e318e 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -146,11 +146,14 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
 #elif defined(__GNUC__)
 #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 "-Wint-to-pointer-cast"              // warning: cast to pointer from integer of different size
+#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-security"                  // warning: format string is not a string literal (potentially insecure)
 #pragma GCC diagnostic ignored "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
 #pragma GCC diagnostic ignored "-Wconversion"                       // warning: conversion to 'xxxx' from 'xxxx' may alter its value
 #pragma GCC diagnostic ignored "-Wmisleading-indentation"           // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement      // GCC 6.0+ only. See #883 on GitHub.
+#pragma GCC diagnostic ignored "-Wcast-qual"                        // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
 #endif
 
 // Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!)
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index f51fff3a6..2b1e10c4e 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -67,13 +67,16 @@ Index of this file:
 #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
 #pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
+#pragma clang diagnostic ignored "-Wcast-qual"                      // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier
 #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 "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
 #pragma GCC diagnostic ignored "-Wconversion"                       // warning: conversion to 'xxxx' from 'xxxx' may alter its value
 #pragma GCC diagnostic ignored "-Wstack-protector"                  // warning: stack protector not protecting local variables: variable length buffer
 #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 "-Wcast-qual"                        // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
 #endif
 
 //-------------------------------------------------------------------------
@@ -105,13 +108,12 @@ namespace IMGUI_STB_NAMESPACE
 #pragma clang diagnostic ignored "-Wunused-function"        // warning: 'xxxx' defined but not used
 #pragma clang diagnostic ignored "-Wmissing-prototypes"
 #pragma clang diagnostic ignored "-Wimplicit-fallthrough"
-#pragma clang diagnostic ignored "-Wcast-qual"              // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier
 #endif
 
 #if defined(__GNUC__)
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wtype-limits"              // warning: comparison is always true due to limited range of data type [-Wtype-limits]
-#pragma GCC diagnostic ignored "-Wcast-qual"                // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
+#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"     // warning: this statement may fall through
 #endif
 
 #ifndef STB_RECT_PACK_IMPLEMENTATION                        // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
diff --git a/imgui_internal.h b/imgui_internal.h
index 6be907bb5..947277489 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -101,6 +101,7 @@ Index of this file:
 #elif defined(__GNUC__)
 #pragma GCC diagnostic push
 #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 "-Wdeprecated-enum-enum-conversion"  // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
 #endif
@@ -460,7 +461,7 @@ static inline double ImRsqrt(double x)          { return 1.0 / sqrt(x); }
 template static inline T ImMin(T lhs, T rhs)                        { return lhs < rhs ? lhs : rhs; }
 template static inline T ImMax(T lhs, T rhs)                        { return lhs >= rhs ? lhs : rhs; }
 template static inline T ImClamp(T v, T mn, T mx)                   { return (v < mn) ? mn : (v > mx) ? mx : v; }
-template static inline T ImLerp(T a, T b, float t)                  { return (T)(a + (b - a) * t); }
+template static inline T ImLerp(T a, T b, float t)                  { return (T)(a + (b - a) * (T)t); }
 template static inline void ImSwap(T& a, T& b)                      { T tmp = a; a = b; b = tmp; }
 template static inline 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 static inline 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; }
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 7dd97c6f2..96e461418 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -232,8 +232,11 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #elif defined(__GNUC__)
 #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 "-Wformat-nonliteral"                // warning: format not a string literal, format string not checked
 #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 "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wformat"                           // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
 #endif
 
 //-----------------------------------------------------------------------------
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index b0f28903a..4e6cbee9a 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -82,9 +82,13 @@ Index of this file:
 #pragma clang diagnostic ignored "-Wnontrivial-memaccess"           // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
 #elif defined(__GNUC__)
 #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 "-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
 #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 "-Wdeprecated-enum-enum-conversion"  // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
+#pragma GCC diagnostic ignored "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wcast-qual"                        // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
 #endif
 
 //-------------------------------------------------------------------------

From 457fae24e7a9fd30ad24b35e2f2ac714bca522bd Mon Sep 17 00:00:00 2001
From: ocornut 
Date: Wed, 18 Dec 2024 18:13:55 +0100
Subject: [PATCH 0553/2359] Silence more zealous GCC warning. (#8241)

---
 backends/imgui_impl_opengl3.cpp | 1 +
 imgui_demo.cpp                  | 1 +
 imgui_draw.cpp                  | 1 +
 imgui_tables.cpp                | 3 ++-
 imgui_widgets.cpp               | 3 ++-
 5 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp
index b47ac9ab1..efc1a3c49 100644
--- a/backends/imgui_impl_opengl3.cpp
+++ b/backends/imgui_impl_opengl3.cpp
@@ -137,6 +137,7 @@
 #pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
 #pragma GCC diagnostic ignored "-Wunknown-warning-option"   // warning: unknown warning group 'xxx'
 #pragma GCC diagnostic ignored "-Wcast-function-type"       // warning: cast between incompatible function types (for loader)
+#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1
 #endif
 
 // GL includes
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index 6425e318e..621fc4f43 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -153,6 +153,7 @@ Index of this file:
 #pragma GCC diagnostic ignored "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
 #pragma GCC diagnostic ignored "-Wconversion"                       // warning: conversion to 'xxxx' from 'xxxx' may alter its value
 #pragma GCC diagnostic ignored "-Wmisleading-indentation"           // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement      // GCC 6.0+ only. See #883 on GitHub.
+#pragma GCC diagnostic ignored "-Wstrict-overflow"                  // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1
 #pragma GCC diagnostic ignored "-Wcast-qual"                        // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
 #endif
 
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 2b1e10c4e..6caba22fa 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -75,6 +75,7 @@ Index of this file:
 #pragma GCC diagnostic ignored "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
 #pragma GCC diagnostic ignored "-Wconversion"                       // warning: conversion to 'xxxx' from 'xxxx' may alter its value
 #pragma GCC diagnostic ignored "-Wstack-protector"                  // warning: stack protector not protecting local variables: variable length buffer
+#pragma GCC diagnostic ignored "-Wstrict-overflow"                  // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1
 #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 "-Wcast-qual"                        // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
 #endif
diff --git a/imgui_tables.cpp b/imgui_tables.cpp
index 96e461418..e90da3ec7 100644
--- a/imgui_tables.cpp
+++ b/imgui_tables.cpp
@@ -234,9 +234,10 @@ 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 "-Wformat-nonliteral"                // warning: format not a string literal, format string not checked
-#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 "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
 #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 "-Wstrict-overflow"
+#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
 #endif
 
 //-----------------------------------------------------------------------------
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 4e6cbee9a..b8680ab34 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -85,9 +85,10 @@ Index of this file:
 #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
-#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 "-Wdeprecated-enum-enum-conversion"  // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
 #pragma GCC diagnostic ignored "-Wdouble-promotion"                 // warning: implicit conversion from 'float' to 'double' when passing argument to function
+#pragma GCC diagnostic ignored "-Wstrict-overflow"                  // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1
+#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 "-Wcast-qual"                        // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
 #endif
 

From ae839620b9670ee5303860a0adbb76c9780eb856 Mon Sep 17 00:00:00 2001
From: Tiamat-Defender <166345691+Tiamat-Defender@users.noreply.github.com>
Date: Thu, 19 Dec 2024 08:22:56 -0500
Subject: [PATCH 0554/2359] Docs: Updated EXAMPLES.md (#8246)

---
 docs/EXAMPLES.md | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md
index 66ad24ef7..f84f9497b 100644
--- a/docs/EXAMPLES.md
+++ b/docs/EXAMPLES.md
@@ -175,7 +175,7 @@ Raw Windows + OpenGL3 + example (modern, programmable pipeline) 
**Building** -Unfortunately nowadays it is still tedious to create and maintain portable build files using external +Unfortunately, nowadays it is still tedious to create and maintain portable build files using external libraries (the kind we're using here to create a window and render 3D triangles) without relying on third party software and build systems. For most examples here we choose to provide: - Makefiles for Linux/OSX @@ -191,22 +191,22 @@ If you are interested in using Cmake to build and links examples, see: **About mouse cursor latency** -Dear ImGui has no particular extra lag for most behaviors, +Dear ImGui does not introduce significant extra lag for most behaviors, e.g. the last value passed to 'io.AddMousePosEvent()' before NewFrame() will result in windows being moved to the right spot at the time of EndFrame()/Render(). At 60 FPS your experience should be pleasant. -However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated -path and will feel smoother than the majority of contents rendered via regular graphics API (including, +However, consider that OS mouse cursors are typically rendered through a very specific hardware-accelerated +path, which makes them feel smoother than the majority of content rendered via regular graphics API (including, but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane as the mouse, that disconnect may be jarring to particularly sensitive users. You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a regularly rendered software cursor. -However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at +However, rendering a mouse cursor at 60 FPS will feel sluggish, so you likely won't want to enable that at all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_ when an interactive drag is in progress. -Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings. -If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple -drawing a flat 2D shape directly under the mouse cursor! +Note that some setup configurations or GPU drivers may introduce additional display lag depending on their settings. +If you notice that dragging windows is laggy and you are not sure what the cause is: try drawing a simple +2D shape directly under the mouse cursor to help identify the issue! From 9b0e61aaaa7af2e39b8963d16542e2924813d3f5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Dec 2024 15:10:44 +0100 Subject: [PATCH 0555/2359] InputText: sanity checks to e.g. detect non zero-terminated buffers + removed a redundant strlen() call during activation. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 25649c16f..b6365be59 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Other changes: were not applied when pasting from clipbard. (#8229) - InputText: Fixed issue when activating a ReadOnly field when the underlying value is being modified. (#8242) +- InputText: Added sanity check to detect some cases of passing a non + zero-terminated input buffer. - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard modifiers altering the tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. (#8223) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b8680ab34..335ab4cde 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4389,6 +4389,7 @@ void ImGui::InputTextDeactivateHook(ImGuiID id) else { IM_ASSERT(state->TextA.Data != 0); + IM_ASSERT(state->TextA[state->TextLen] == 0); g.InputTextDeactivatedState.TextA.resize(state->TextLen + 1); memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->TextLen + 1); } @@ -4519,6 +4520,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (init_reload_from_user_buf) { int new_len = (int)strlen(buf); + IM_ASSERT(new_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?"); state->WantReloadUserBuf = false; InputTextReconcileUndoState(state, state->TextA.Data, state->TextLen, buf, new_len); state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string. @@ -4540,6 +4542,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Take a copy of the initial buffer value. // From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode) const int buf_len = (int)strlen(buf); + IM_ASSERT(buf_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?"); state->TextToRevertTo.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. memcpy(state->TextToRevertTo.Data, buf, buf_len + 1); @@ -4551,7 +4554,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Start edition state->ID = id; - state->TextLen = (int)strlen(buf); + state->TextLen = buf_len; if (!is_readonly) { state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string. From fd932297703c6da24b953f0be8e0733e0db4d9cf Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Dec 2024 18:14:22 +0100 Subject: [PATCH 0556/2359] Tables, MultiSelect: Fixed an issue where column width may be mismeasured when calling BeginMultiSelect() while inside a table. (#8250) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- imgui_widgets.cpp | 6 ++++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b6365be59..afd6c57c1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other changes: value is being modified. (#8242) - InputText: Added sanity check to detect some cases of passing a non zero-terminated input buffer. +- Tables, MultiSelect: Fixed an issue where column width may be mismeasured + when calling BeginMultiSelect() while inside a table. (#8250) - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard modifiers altering the tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. (#8223) diff --git a/imgui.h b/imgui.h index e1b8796f3..68558fb4d 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.7 WIP" -#define IMGUI_VERSION_NUM 19162 +#define IMGUI_VERSION_NUM 19163 #define IMGUI_HAS_TABLE /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 335ab4cde..0fef03ab5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7518,6 +7518,12 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel if (flags & ImGuiMultiSelectFlags_BoxSelect2d) flags &= ~ImGuiMultiSelectFlags_BoxSelect1d; + // FIXME: Workaround to the fact we override CursorMaxPos, meaning size measurement are lost. (#8250) + // They should perhaps be stacked properly? + if (ImGuiTable* table = g.CurrentTable) + if (table->CurrentColumn != -1) + TableEndCell(table); // This is currently safe to call multiple time. If that properly is lost we can extract the "save measurement" part of it. + // FIXME: BeginFocusScope() const ImGuiID id = window->IDStack.back(); ms->Clear(); From eed95027956805f83caddc0fd82dd05cdb2ee082 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Dec 2024 14:28:04 +0100 Subject: [PATCH 0557/2359] Error Handling: Fixed bugs recovering from within a table that created a child window, and from nested child windows. (#1651) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 29 +++++++++++++++++++---------- imgui_internal.h | 2 +- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index afd6c57c1..f91342903 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking changes: Other changes: +- Error Handling: Fixed bugs recovering from within a table that created + a child window, and from nested child windows. (#1651) - InputText: Fixed a bug where character replacements performed from a callback were not applied when pasting from clipbard. (#8229) - InputText: Fixed issue when activating a ReadOnly field when the underlying diff --git a/imgui.cpp b/imgui.cpp index cf59a5a53..c5ede70a3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3884,7 +3884,8 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) Time = 0.0f; FrameCount = 0; FrameCountEnded = FrameCountRendered = -1; - WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false; + WithinEndChildID = 0; + WithinFrameScope = WithinFrameScopeWithImplicitWindow = false; GcCompactAll = false; TestEngineHookItems = false; TestEngine = NULL; @@ -6106,10 +6107,10 @@ void ImGui::EndChild() ImGuiContext& g = *GImGui; ImGuiWindow* child_window = g.CurrentWindow; - IM_ASSERT(g.WithinEndChild == false); + const ImGuiID backup_within_end_child_id = g.WithinEndChildID; IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls - g.WithinEndChild = true; + g.WithinEndChildID = child_window->ID; ImVec2 child_size = child_window->Size; End(); if (child_window->BeginCount == 1) @@ -6141,7 +6142,7 @@ void ImGui::EndChild() if (g.HoveredWindow == child_window) g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; } - g.WithinEndChild = false; + g.WithinEndChildID = backup_within_end_child_id; g.LogLinePosY = -FLT_MAX; // To enforce a carriage return } @@ -7773,7 +7774,7 @@ void ImGui::End() // Error checking: verify that user doesn't directly call End() on a child window. if (window->Flags & ImGuiWindowFlags_ChildWindow) - IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!"); + IM_ASSERT_USER_ERROR(g.WithinEndChildID == window->ID, "Must call EndChild() and not End()!"); // Close anything that is open if (window->DC.CurrentColumns) @@ -10485,8 +10486,16 @@ void ImGui::ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_ ImGuiWindow* window = g.CurrentWindow; if (window->Flags & ImGuiWindowFlags_ChildWindow) { - IM_ASSERT_USER_ERROR(0, "Missing EndChild()"); - EndChild(); + if (g.CurrentTable != NULL && g.CurrentTable->InnerWindow == g.CurrentWindow) + { + IM_ASSERT_USER_ERROR(0, "Missing EndTable()"); + EndTable(); + } + else + { + IM_ASSERT_USER_ERROR(0, "Missing EndChild()"); + EndChild(); + } } else { @@ -11921,11 +11930,11 @@ void ImGui::EndPopup() NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); // Child-popups don't need to be laid out - IM_ASSERT(g.WithinEndChild == false); + const ImGuiID backup_within_end_child_id = g.WithinEndChildID; if (window->Flags & ImGuiWindowFlags_ChildWindow) - g.WithinEndChild = true; + g.WithinEndChildID = window->ID; End(); - g.WithinEndChild = false; + g.WithinEndChildID = backup_within_end_child_id; } // Helper to open a popup if mouse button is released over the item diff --git a/imgui_internal.h b/imgui_internal.h index 947277489..316ac1844 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2045,9 +2045,9 @@ struct ImGuiContext int FrameCount; int FrameCountEnded; int FrameCountRendered; + ImGuiID WithinEndChildID; // Set within EndChild() bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed - bool WithinEndChild; // Set within EndChild() bool GcCompactAll; // Request full GC bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() void* TestEngine; // Test engine user data From 91e8f2b0febbbcb2c7eddf3f4f500fda71089118 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Dec 2024 15:13:49 +0100 Subject: [PATCH 0558/2359] Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f91342903..8ecf76cde 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,8 @@ Other changes: yourself based on your own logic. (#8223) - Nav: Fixed an issue where Alt key would clear current active item on windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) +- Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even + if a popup is blocking mouse access to the debug log window. (#5855) - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF] diff --git a/imgui.cpp b/imgui.cpp index c5ede70a3..7d324a194 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16501,7 +16501,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open) void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end) { TextUnformatted(line_begin, line_end); - if (!IsItemHovered()) + if (!IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) return; ImGuiContext& g = *GImGui; ImRect text_rect = g.LastItemData.Rect; From d30e102f3adab20865fd74864ddadd94d7559973 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Dec 2024 15:22:34 +0100 Subject: [PATCH 0559/2359] Scrollbar, TestEngine: for consistency, scrollbars are registered in _Menu layer. Amend f31d530. --- imgui.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 7d324a194..797f968d9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6731,9 +6731,10 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar ImGuiStyle& style = g.Style; ImGuiWindowFlags flags = window->Flags; - // Ensure that ScrollBar doesn't read last frame's SkipItems + // Ensure that Scrollbar() doesn't read last frame's SkipItems IM_ASSERT(window->BeginCount == 0); window->SkipItems = false; + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; // Draw window + handle manual resize // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame. @@ -6810,6 +6811,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar if (handle_borders_and_resize_grips) RenderWindowOuterBorders(window); } + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; } // Render title text, collapse button, close button From 61d4bf95dc5345c77b97b279011fce2c46efcaa8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Dec 2024 17:17:40 +0100 Subject: [PATCH 0560/2359] Fonts: Allowing PushFont()/PopFont() to be called outside the imgui frame scope. (#3621) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8ecf76cde..8a091be6a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,7 @@ Other changes: yourself based on your own logic. (#8223) - Nav: Fixed an issue where Alt key would clear current active item on windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) +- Fonts: Allowing PushFont()/PopFont() to be called outside the imgui frame scope. (#3621) - Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for diff --git a/imgui.cpp b/imgui.cpp index 797f968d9..f074f4fe5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8018,7 +8018,8 @@ void ImGui::PushFont(ImFont* font) font = GetDefaultFont(); g.FontStack.push_back(font); SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); + if (ImGuiWindow* window = g.CurrentWindow) + window->DrawList->_SetTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() @@ -8032,7 +8033,8 @@ void ImGui::PopFont() g.FontStack.pop_back(); ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); + if (ImGuiWindow* window = g.CurrentWindow) + window->DrawList->_SetTextureID(font->ContainerAtlas->TexID); } void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) From 7219fa65c0212de1d352b5db8f7dfe43b11f00c9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Dec 2024 17:20:57 +0100 Subject: [PATCH 0561/2359] Revert "Fonts: Allowing PushFont()/PopFont() to be called outside the imgui frame scope. (#3621)" This reverts commit 61d4bf95dc5345c77b97b279011fce2c46efcaa8. --- docs/CHANGELOG.txt | 1 - imgui.cpp | 6 ++---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8a091be6a..8ecf76cde 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,7 +58,6 @@ Other changes: yourself based on your own logic. (#8223) - Nav: Fixed an issue where Alt key would clear current active item on windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) -- Fonts: Allowing PushFont()/PopFont() to be called outside the imgui frame scope. (#3621) - Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for diff --git a/imgui.cpp b/imgui.cpp index f074f4fe5..797f968d9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8018,8 +8018,7 @@ void ImGui::PushFont(ImFont* font) font = GetDefaultFont(); g.FontStack.push_back(font); SetCurrentFont(font); - if (ImGuiWindow* window = g.CurrentWindow) - window->DrawList->_SetTextureID(font->ContainerAtlas->TexID); + g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() @@ -8033,8 +8032,7 @@ void ImGui::PopFont() g.FontStack.pop_back(); ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); SetCurrentFont(font); - if (ImGuiWindow* window = g.CurrentWindow) - window->DrawList->_SetTextureID(font->ContainerAtlas->TexID); + g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); } void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) From 006721fbd6b0ee0f08256b89282e4b62e3378a79 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Dec 2024 18:15:28 +0100 Subject: [PATCH 0562/2359] Added ImFontAtlas section index in comments + minor tweaks to DX12 backends. --- backends/imgui_impl_dx12.cpp | 8 +++---- imgui_draw.cpp | 42 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 16dcf5392..24fdb7aa0 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -19,7 +19,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat. +// 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat. // 2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete). // 2024-11-15: DirectX12: *BREAKING CHANGE* User is now required to pass function pointers to allocate/free SRV Descriptors. We provide convenience legacy fields to pass a single descriptor, matching the old API, but upcoming features will want multiple. // 2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools. @@ -409,7 +409,7 @@ static void ImGui_ImplDX12_CreateFontsTexture() hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); IM_ASSERT(SUCCEEDED(hr)); - HANDLE event = CreateEvent(0, 0, 0, 0); + HANDLE event = ::CreateEvent(0, 0, 0, 0); IM_ASSERT(event != nullptr); D3D12_COMMAND_QUEUE_DESC queueDesc = {}; @@ -440,12 +440,12 @@ static void ImGui_ImplDX12_CreateFontsTexture() IM_ASSERT(SUCCEEDED(hr)); fence->SetEventOnCompletion(1, event); - WaitForSingleObject(event, INFINITE); + ::WaitForSingleObject(event, INFINITE); cmdList->Release(); cmdAlloc->Release(); cmdQueue->Release(); - CloseHandle(event); + ::CloseHandle(event); fence->Release(); uploadBuffer->Release(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6caba22fa..42bfb7162 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2386,6 +2386,38 @@ ImFontConfig::ImFontConfig() //----------------------------------------------------------------------------- // [SECTION] ImFontAtlas //----------------------------------------------------------------------------- +// - Default texture data encoded in ASCII +// - ImFontAtlas::ClearInputData() +// - ImFontAtlas::ClearTexData() +// - ImFontAtlas::ClearFonts() +// - ImFontAtlas::Clear() +// - ImFontAtlas::GetTexDataAsAlpha8() +// - ImFontAtlas::GetTexDataAsRGBA32() +// - ImFontAtlas::AddFont() +// - ImFontAtlas::AddFontDefault() +// - ImFontAtlas::AddFontFromFileTTF() +// - ImFontAtlas::AddFontFromMemoryTTF() +// - ImFontAtlas::AddFontFromMemoryCompressedTTF() +// - ImFontAtlas::AddFontFromMemoryCompressedBase85TTF() +// - ImFontAtlas::AddCustomRectRegular() +// - ImFontAtlas::AddCustomRectFontGlyph() +// - ImFontAtlas::CalcCustomRectUV() +// - ImFontAtlas::GetMouseCursorTexData() +// - ImFontAtlas::Build() +// - ImFontAtlasBuildMultiplyCalcLookupTable() +// - ImFontAtlasBuildMultiplyRectAlpha8() +// - ImFontAtlasBuildWithStbTruetype() +// - ImFontAtlasGetBuilderForStbTruetype() +// - ImFontAtlasUpdateConfigDataPointers() +// - ImFontAtlasBuildSetupFont() +// - ImFontAtlasBuildPackCustomRects() +// - ImFontAtlasBuildRender8bppRectFromString() +// - ImFontAtlasBuildRender32bppRectFromString() +// - ImFontAtlasBuildRenderDefaultTexData() +// - ImFontAtlasBuildRenderLinesTexData() +// - ImFontAtlasBuildInit() +// - ImFontAtlasBuildFinish() +//----------------------------------------------------------------------------- // A work of art lies ahead! (. = white layer, X = black layer, others are blank) // The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. @@ -3327,6 +3359,16 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) //------------------------------------------------------------------------- // [SECTION] ImFontAtlas: glyph ranges helpers //------------------------------------------------------------------------- +// - GetGlyphRangesDefault() +// - GetGlyphRangesGreek() +// - GetGlyphRangesKorean() +// - GetGlyphRangesChineseFull() +// - GetGlyphRangesChineseSimplifiedCommon() +// - GetGlyphRangesJapanese() +// - GetGlyphRangesCyrillic() +// - GetGlyphRangesThai() +// - GetGlyphRangesVietnamese() +//----------------------------------------------------------------------------- // Retrieve list of range (2 int per range, values are inclusive) const ImWchar* ImFontAtlas::GetGlyphRangesDefault() From 2a600bddcbe20fb7832cb0dfafb305704c0422be Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Dec 2024 23:11:37 +0100 Subject: [PATCH 0563/2359] ImGuiDebugLogFlags_EventFont should not be set by default (had no effect on master tho) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 797f968d9..efa9c4501 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4062,7 +4062,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) StackSizesInBeginForCurrentWindow = NULL; DebugDrawIdConflictsCount = 0; - DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY | ImGuiDebugLogFlags_EventFont; + DebugLogFlags = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_OutputToTTY; DebugLocateId = 0; DebugLogSkippedErrors = 0; DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None; From 18929bd6d6cffbacdae7a10732f58de9fdb540a0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Dec 2024 23:26:21 +0100 Subject: [PATCH 0564/2359] Internals: merge ScaleWindowsInViewport() from docking branch. --- imgui.cpp | 19 +++++++++++++++++++ imgui_internal.h | 1 + 2 files changed, 20 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index efa9c4501..47ac6046a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14788,6 +14788,7 @@ void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count) //----------------------------------------------------------------------------- // - GetMainViewport() // - SetWindowViewport() [Internal] +// - ScaleWindowsInViewport() [Internal] // - UpdateViewportsNewFrame() [Internal] // (this section is more complete in the 'docking' branch) //----------------------------------------------------------------------------- @@ -14803,6 +14804,24 @@ void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport) window->Viewport = viewport; } +static void ScaleWindow(ImGuiWindow* window, float scale) +{ + ImVec2 origin = window->Viewport->Pos; + window->Pos = ImFloor((window->Pos - origin) * scale + origin); + window->Size = ImTrunc(window->Size * scale); + window->SizeFull = ImTrunc(window->SizeFull * scale); + window->ContentSize = ImTrunc(window->ContentSize * scale); +} + +// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) +void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) +{ + ImGuiContext& g = *GImGui; + for (ImGuiWindow* window : g.Windows) + if (window->Viewport == viewport) + ScaleWindow(window, scale); +} + // Update viewports and monitor infos static void ImGui::UpdateViewportsNewFrame() { diff --git a/imgui_internal.h b/imgui_internal.h index 316ac1844..881e2ffd6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3020,6 +3020,7 @@ namespace ImGui IMGUI_API void CallContextHooks(ImGuiContext* context, ImGuiContextHookType type); // Viewports + IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale); IMGUI_API void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport); // Settings From 6982ce43f5b143c5dce5fab0ce07dd4867b705ae Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 22 Dec 2024 17:53:09 +0100 Subject: [PATCH 0565/2359] InputText: fixed badly broken clipboard copy/bug (#8254, #8242) Broken by 32f1140 --- imgui_widgets.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0fef03ab5..e19974f66 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4900,8 +4900,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0; const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->TextLen; g.TempBuffer.reserve(ie - ib + 1); - memcpy(g.TempBuffer.Data, state->TextSrc, ie - ib); - g.TempBuffer.Data[ie] = 0; + memcpy(g.TempBuffer.Data, state->TextSrc + ib, ie - ib); + g.TempBuffer.Data[ie - ib] = 0; SetClipboardText(g.TempBuffer.Data); } if (is_cut) From 87f3109c1af835be0e5b4b4410baa1c66ced7b33 Mon Sep 17 00:00:00 2001 From: "Admiral H. Curtiss" Date: Fri, 3 Jan 2025 21:07:42 +0100 Subject: [PATCH 0566/2359] Fix capitalization of ImGuiID in comment. (#8283) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 68558fb4d..ca9d9bf37 100644 --- a/imgui.h +++ b/imgui.h @@ -2895,7 +2895,7 @@ struct ImGuiSelectionBasicStorage IMGUI_API void Clear(); // Clear selection IMGUI_API void Swap(ImGuiSelectionBasicStorage& r); // Swap two selections IMGUI_API void SetItemSelected(ImGuiID id, bool selected); // Add/remove an item from selection (generally done by ApplyRequests() function) - IMGUI_API bool GetNextSelectedItem(void** opaque_it, ImGuiID* out_id); // Iterate selection with 'void* it = NULL; ImGuiId id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' + IMGUI_API bool GetNextSelectedItem(void** opaque_it, ImGuiID* out_id); // Iterate selection with 'void* it = NULL; ImGuiID id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' inline ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } // Convert index to item id based on provided adapter. }; From 2d2c7d3f9557074d7a24de4a5b8724ef09fad118 Mon Sep 17 00:00:00 2001 From: Helodity Date: Sun, 22 Dec 2024 22:48:07 -0500 Subject: [PATCH 0567/2359] Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). --- backends/imgui_impl_allegro5.cpp | 14 ++++++++++++-- docs/CHANGELOG.txt | 2 ++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 28d1b1536..3718b64ea 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-06: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn @@ -95,6 +96,7 @@ struct ImGui_ImplAllegro5_Data ALLEGRO_MOUSE_CURSOR* MouseCursorInvisible; ALLEGRO_VERTEX_DECL* VertexDecl; char* ClipboardTextData; + ImGuiMouseCursor LastCursor; ImVector BufVertices; ImVector BufIndices; @@ -438,6 +440,7 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) bd->Display = display; + bd->LastCursor = ALLEGRO_SYSTEM_MOUSE_CURSOR_NONE; // Create custom vertex declaration. // Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 floats. @@ -568,9 +571,16 @@ static void ImGui_ImplAllegro5_UpdateMouseCursor() ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); - if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) + + // Hide OS mouse cursor if imgui is drawing it + if (io.MouseDrawCursor) + imgui_cursor = ImGuiMouseCursor_None; + + if (bd->LastCursor == imgui_cursor) + return; + bd->LastCursor = imgui_cursor; + if (imgui_cursor == ImGuiMouseCursor_None) { - // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor al_set_mouse_cursor(bd->Display, bd->MouseCursorInvisible); } else diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8ecf76cde..1ef576c3d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,8 @@ Other changes: windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) - Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) +- Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears + to leak on on X11 (#8256). [@Helodity] - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF] From c147a59bb0e9ad57ee0cac0056a744ff2d97bb3e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 13:58:02 +0100 Subject: [PATCH 0568/2359] Clarified alternative for ImGuiButtonFlags_Repeat being ImGuiItemFlags_ButtonRepeat. (#8293) --- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 881e2ffd6..db3c089eb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -914,7 +914,7 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_PressedOnRelease = 1 << 7, // return true on release (default requires click+release) ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, // return true on double-click (default requires click+release) ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) - //ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat + //ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat -> use ImGuiItemFlags_ButtonRepeat instead. ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping ImGuiButtonFlags_AllowOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable. //ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e19974f66..f8c5ad7a9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -477,7 +477,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // - PressedOnDragDropHold can generally be associated with any flag. // - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported. //------------------------------------------------------------------------------------------------------------------------------------------------ -// The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set: +// The behavior of the return-value changes when ImGuiItemFlags_ButtonRepeat is set: // Repeat+ Repeat+ Repeat+ Repeat+ // PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick //------------------------------------------------------------------------------------------------------------------------------------------------- From a0f907933d8def4ffcb29fffe887889339c82f11 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 14:07:06 +0100 Subject: [PATCH 0569/2359] Happy new year! --- LICENSE.txt | 2 +- imgui.cpp | 2 +- imgui.h | 1 + imgui_demo.cpp | 3 ++- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 3282f5b5b..00ae473ab 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014-2024 Omar Cornut +Copyright (c) 2014-2025 Omar Cornut Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/imgui.cpp b/imgui.cpp index 47ac6046a..3bb95bfce 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -25,7 +25,7 @@ // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. -// Copyright (c) 2014-2024 Omar Cornut +// Copyright (c) 2014-2025 Omar Cornut // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // See LICENSE.txt for copyright and licensing details (standard MIT License). // This library is free but needs your support to sustain development and maintenance. diff --git a/imgui.h b/imgui.h index ca9d9bf37..294eaee00 100644 --- a/imgui.h +++ b/imgui.h @@ -2694,6 +2694,7 @@ struct ImGuiListClipper // - It is important that we are keeping those disabled by default so they don't leak in user space. // - This is in order to allow user enabling implicit cast operators between ImVec2/ImVec4 and their own types (using IM_VEC2_CLASS_EXTRA in imconfig.h) // - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. +// - We intentionally provide ImVec2*float but not float*ImVec2: this is rare enough and we want to reduce the surface for possible user mistake. #ifdef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED IM_MSVC_RUNTIME_CHECKS_OFF diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 621fc4f43..c4d93bb74 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7692,7 +7692,8 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::TextLinkOpenURL("Funding", "https://github.com/ocornut/imgui/wiki/Funding"); ImGui::Separator(); - ImGui::Text("By Omar Cornut and all Dear ImGui contributors."); + ImGui::Text("(c) 2014-2025 Omar Cornut"); + ImGui::Text("Developed by Omar Cornut and all Dear ImGui contributors."); ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information."); ImGui::Text("If your company uses this, please consider funding the project."); From f169102c8eac86efba55aeca33bce5cc77626ae4 Mon Sep 17 00:00:00 2001 From: juur Date: Mon, 6 Jan 2025 12:58:05 +0000 Subject: [PATCH 0570/2359] Misc: fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) --- docs/CHANGELOG.txt | 1 + misc/cpp/imgui_stdlib.cpp | 3 +++ misc/cpp/imgui_stdlib.h | 4 ++++ 3 files changed, 8 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1ef576c3d..aa5f96e0f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,7 @@ Other changes: windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) - Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) +- Misc: fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). [@Helodity] - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for diff --git a/misc/cpp/imgui_stdlib.cpp b/misc/cpp/imgui_stdlib.cpp index cf69aa89a..c04d487cc 100644 --- a/misc/cpp/imgui_stdlib.cpp +++ b/misc/cpp/imgui_stdlib.cpp @@ -8,6 +8,7 @@ // https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_stdlib.h" // Clang warnings with -Weverything @@ -83,3 +84,5 @@ bool ImGui::InputTextWithHint(const char* label, const char* hint, std::string* #if defined(__clang__) #pragma clang diagnostic pop #endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/misc/cpp/imgui_stdlib.h b/misc/cpp/imgui_stdlib.h index 835a808f2..697fc34ad 100644 --- a/misc/cpp/imgui_stdlib.h +++ b/misc/cpp/imgui_stdlib.h @@ -9,6 +9,8 @@ #pragma once +#ifndef IMGUI_DISABLE + #include namespace ImGui @@ -19,3 +21,5 @@ namespace ImGui IMGUI_API bool InputTextMultiline(const char* label, std::string* str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = nullptr, void* user_data = nullptr); IMGUI_API bool InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = nullptr, void* user_data = nullptr); } + +#endif // #ifndef IMGUI_DISABLE From 80aafbc81b0956f9d657ab80838b6fcb2116a8b3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 14:22:03 +0100 Subject: [PATCH 0571/2359] Data types: moved ImGuiDataType_String to public API as a convenience enum value only. (#8266) --- imgui.h | 3 ++- imgui_internal.h | 3 +-- imgui_widgets.cpp | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 294eaee00..0f7a99862 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.7 WIP" -#define IMGUI_VERSION_NUM 19163 +#define IMGUI_VERSION_NUM 19164 #define IMGUI_HAS_TABLE /* @@ -1399,6 +1399,7 @@ enum ImGuiDataType_ ImGuiDataType_Float, // float ImGuiDataType_Double, // double ImGuiDataType_Bool, // bool (provided for user convenience, not supported by scalar widgets) + ImGuiDataType_String, // char* (provided for user convenience, not supported by scalar widgets) ImGuiDataType_COUNT }; diff --git a/imgui_internal.h b/imgui_internal.h index db3c089eb..850136b0d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -827,8 +827,7 @@ struct ImGuiDataTypeInfo // Extend ImGuiDataType_ enum ImGuiDataTypePrivate_ { - ImGuiDataType_String = ImGuiDataType_COUNT + 1, - ImGuiDataType_Pointer, + ImGuiDataType_Pointer = ImGuiDataType_COUNT + 1, ImGuiDataType_ID, }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f8c5ad7a9..854f09634 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2171,6 +2171,7 @@ static const ImGuiDataTypeInfo GDataTypeInfo[] = { sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg) { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double { sizeof(bool), "bool", "%d", "%d" }, // ImGuiDataType_Bool + { 0, "char*","%s", "%s" }, // ImGuiDataType_String }; IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT); From 2f1194a29618b9ca19d8902643deb6efafe2769c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 14:35:57 +0100 Subject: [PATCH 0572/2359] Demo: Added label edition to Property Editor demo + fix an ID issue. (#8266) --- docs/CHANGELOG.txt | 3 ++- imgui_demo.cpp | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index aa5f96e0f..ab226ebaa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,7 +60,8 @@ Other changes: windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) - Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) -- Misc: fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] +- Demo: Added label edition to Property Editor demo + fix an ID issue. (#8266) [@moritz-h] +- Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). [@Helodity] - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c4d93bb74..36d8f4415 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -295,6 +295,7 @@ struct ExampleMemberInfo // Metadata description of ExampleTreeNode struct. static const ExampleMemberInfo ExampleTreeNodeMemberInfos[] { + { "MyName", ImGuiDataType_String, 1, offsetof(ExampleTreeNode, Name) }, { "MyBool", ImGuiDataType_Bool, 1, offsetof(ExampleTreeNode, DataMyBool) }, { "MyInt", ImGuiDataType_S32, 1, offsetof(ExampleTreeNode, DataMyInt) }, { "MyVec2", ImGuiDataType_Float, 2, offsetof(ExampleTreeNode, DataMyVec2) }, @@ -8957,6 +8958,8 @@ struct ExampleAppPropertyEditor ImGui::Separator(); if (ImGui::BeginTable("##properties", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY)) { + // Push object ID after we entered the table, so table is shared for all objects + ImGui::PushID((int)node->UID); ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger if (node->HasData) @@ -8995,10 +8998,16 @@ struct ExampleAppPropertyEditor ImGui::SliderScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, &v_min, &v_max); break; } + case ImGuiDataType_String: + { + ImGui::InputText("##Editor", reinterpret_cast(field_ptr), 28); + break; + } } ImGui::PopID(); } } + ImGui::PopID(); ImGui::EndTable(); } } From d0021e16215309e3b4f5180cdd35f916ebc7c12a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 15:01:59 +0100 Subject: [PATCH 0573/2359] Backends: Metal: Fixed resource leak when using multiple contexts. (#7419) --- backends/imgui_impl_metal.mm | 11 ++++------- docs/CHANGELOG.txt | 1 + 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 5680dea9d..edd7fa181 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -306,17 +306,14 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); } + __block MetalContext* sharedMetalContext = bd->SharedMetalContext; [commandBuffer addCompletedHandler:^(id) { dispatch_async(dispatch_get_main_queue(), ^{ - ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); - if (bd != nullptr) + @synchronized(bd->SharedMetalContext.bufferCache) { - @synchronized(bd->SharedMetalContext.bufferCache) - { - [bd->SharedMetalContext.bufferCache addObject:vertexBuffer]; - [bd->SharedMetalContext.bufferCache addObject:indexBuffer]; - } + [sharedMetalContext.bufferCache addObject:vertexBuffer]; + [sharedMetalContext.bufferCache addObject:indexBuffer]; } }); }]; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ab226ebaa..da95a1aac 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,7 @@ Other changes: - Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). [@Helodity] +- Backends: Metal: Fixed resource leak when using multiple contexts. (#7419) [@anszom] - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF] From e7e898ea179cfeb5a4d62f2387691e8e28395d5e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 16:12:33 +0100 Subject: [PATCH 0574/2359] Tables: Fixed TableAngledHeadersRow() creating an infinite horizontal scrolling region when the table is hosted in a viewport with negative coordinates. --- docs/CHANGELOG.txt | 3 +++ imgui_tables.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index da95a1aac..f440a7c63 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,9 @@ Other changes: value is being modified. (#8242) - InputText: Added sanity check to detect some cases of passing a non zero-terminated input buffer. +- Tables: Fixed TableAngledHeadersRow() creating an infinite horizontal + scrolling region when the table is hosted in a viewport with negative + coordinates. - Tables, MultiSelect: Fixed an issue where column width may be mismeasured when calling BeginMultiSelect() while inside a table. (#8250) - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e90da3ec7..1ab9c703e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3299,7 +3299,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label const ImVec2 align = g.Style.TableAngledHeadersTextAlign; // Draw background and labels in first pass, then all borders. - float max_x = 0.0f; + float max_x = -FLT_MAX; for (int pass = 0; pass < 2; pass++) for (int order_n = 0; order_n < data_count; order_n++) { From dbf76f62f9e1fbbc38d5cd2c50661994ff4956a1 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 Jan 2025 17:17:48 +0100 Subject: [PATCH 0575/2359] Update issue_template.yml --- .github/ISSUE_TEMPLATE/issue_template.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/issue_template.yml b/.github/ISSUE_TEMPLATE/issue_template.yml index 792d8f63e..c1b57de4b 100644 --- a/.github/ISSUE_TEMPLATE/issue_template.yml +++ b/.github/ISSUE_TEMPLATE/issue_template.yml @@ -5,9 +5,11 @@ body: attributes: value: | FOR FIRST-TIME USERS ISSUES COMPILING/LINKING/RUNNING or LOADING FONTS, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions) - For anything else: we are happy to use 'GitHub Issues' for many types of open-ended questions. We are encouraging 'Issues' becoming a large, centralized and cross-referenced database of Dear ImGui contents. + For anything else: **we are happy to use 'GitHub Issues' for many types of open-ended questions**. We are encouraging 'Issues' becoming a large, centralized, tagged, cross-referenced database of Dear ImGui contents. Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users. + + **If you are using Dear ImGui as part of a job that you are being well-paid for** and your company is not a sponsor. Please be mindful that this is a Free Software and you might be about to ask volunteers to help you doing your job. Please put extra effort describing your issue or question properly. If your company is wealthy, please read [Funding](https://github.com/ocornut/imgui/wiki/Funding) and consider getting in touch. - type: markdown attributes: value: | From a2e21727c0196beb3848b77483662f70f9245c5c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 17:29:04 +0100 Subject: [PATCH 0576/2359] Backends: Vulkan: moved helpers to backend: ImGui_ImplVulkanH_SelectPhysicalDevice(), ImGui_ImplVulkanH_SelectQueueFamilyIndex(). (#8180) --- backends/imgui_impl_vulkan.cpp | 44 +++++++++++++++++++++++ backends/imgui_impl_vulkan.h | 18 +++++++--- docs/CHANGELOG.txt | 2 ++ examples/example_glfw_vulkan/main.cpp | 48 +++----------------------- examples/example_sdl2_opengl3/main.cpp | 2 +- examples/example_sdl2_vulkan/main.cpp | 48 +++----------------------- examples/example_sdl3_vulkan/main.cpp | 48 +++----------------------- 7 files changed, 72 insertions(+), 138 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 1de6e2353..1953288d9 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -26,6 +26,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-06: Vulkan: Added more ImGui_ImplVulkanH_XXXX helper functions to simplify our examples. // 2024-12-11: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) // 2024-11-27: Vulkan: Make user-provided descriptor pool optional. As a convenience, when setting init_info->DescriptorPoolSize the backend will create one itself. (#8172, #4867) // 2024-10-07: Vulkan: Changed default texture sampler to Clamp instead of Repeat/Wrap. @@ -1334,6 +1335,49 @@ VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_d return VK_PRESENT_MODE_FIFO_KHR; // Always available } +VkPhysicalDevice ImGui_ImplVulkanH_SelectPhysicalDevice(VkInstance instance) +{ + uint32_t gpu_count; + VkResult err = vkEnumeratePhysicalDevices(instance, &gpu_count, nullptr); + check_vk_result(err); + IM_ASSERT(gpu_count > 0); + + ImVector gpus; + gpus.resize(gpu_count); + err = vkEnumeratePhysicalDevices(instance, &gpu_count, gpus.Data); + check_vk_result(err); + + // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers + // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple + // dedicated GPUs) is out of scope of this sample. + for (VkPhysicalDevice& device : gpus) + { + VkPhysicalDeviceProperties properties; + vkGetPhysicalDeviceProperties(device, &properties); + if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) + return device; + } + + // Use first GPU (Integrated) is a Discrete one is not available. + if (gpu_count > 0) + return gpus[0]; + return VK_NULL_HANDLE; +} + + +uint32_t ImGui_ImplVulkanH_SelectQueueFamilyIndex(VkPhysicalDevice physical_device) +{ + uint32_t count; + vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &count, nullptr); + ImVector queues_properties; + queues_properties.resize((int)count); + vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &count, queues_properties.Data); + for (uint32_t i = 0; i < count; i++) + if (queues_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) + return i; + return (uint32_t)-1; +} + void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) { IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 37f700b62..5621acbdd 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -135,18 +135,24 @@ struct ImGui_ImplVulkan_RenderState //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers -// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.) //------------------------------------------------------------------------- +// Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app. +// // You probably do NOT need to use or care about those functions. // Those functions only exist because: // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. // 2) the multi-viewport / platform window implementation needs them internally. -// Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, +// Generally we avoid exposing any kind of superfluous high-level helpers in the backends, // but it is too much code to duplicate everywhere so we exceptionally expose them. // -// Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). -// You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. -// (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) +// Your engine/app will likely _already_ have code to setup all that stuff (swap chain, +// render pass, frame buffers, etc.). You may read this code if you are curious, but +// it is recommended you use you own custom tailored code to do equivalent work. +// +// We don't provide a strong guarantee that we won't change those functions API. +// +// The ImGui_ImplVulkanH_XXX functions should NOT interact with any of the state used +// by the regular ImGui_ImplVulkan_XXX functions). //------------------------------------------------------------------------- struct ImGui_ImplVulkanH_Frame; @@ -157,6 +163,8 @@ IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkIns IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); +IMGUI_IMPL_API VkPhysicalDevice ImGui_ImplVulkanH_SelectPhysicalDevice(VkInstance instance); +IMGUI_IMPL_API uint32_t ImGui_ImplVulkanH_SelectQueueFamilyIndex(VkPhysicalDevice physical_device); IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); // Helper structure to hold the data needed by one rendering frame diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f440a7c63..01d00e0ca 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,8 @@ Other changes: - Backends: Metal: Fixed resource leak when using multiple contexts. (#7419) [@anszom] - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF] +- Backends: Vulkan: Added a few more ImGui_ImplVulkanH_XXX helper functions + primarily for the purpose of making our examples simpler. ----------------------------------------------------------------------- diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 901b46c4c..1197ca4e6 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -85,35 +85,6 @@ static bool IsExtensionAvailable(const ImVector& properti return false; } -static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice() -{ - uint32_t gpu_count; - VkResult err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, nullptr); - check_vk_result(err); - IM_ASSERT(gpu_count > 0); - - ImVector gpus; - gpus.resize(gpu_count); - err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus.Data); - check_vk_result(err); - - // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers - // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple - // dedicated GPUs) is out of scope of this sample. - for (VkPhysicalDevice& device : gpus) - { - VkPhysicalDeviceProperties properties; - vkGetPhysicalDeviceProperties(device, &properties); - if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) - return device; - } - - // Use first GPU (Integrated) is a Discrete one is not available. - if (gpu_count > 0) - return gpus[0]; - return VK_NULL_HANDLE; -} - static void SetupVulkan(ImVector instance_extensions) { VkResult err; @@ -177,23 +148,12 @@ static void SetupVulkan(ImVector instance_extensions) } // Select Physical Device (GPU) - g_PhysicalDevice = SetupVulkan_SelectPhysicalDevice(); + g_PhysicalDevice = ImGui_ImplVulkanH_SelectPhysicalDevice(g_Instance); + IM_ASSERT(g_PhysicalDevice != VK_NULL_HANDLE); // Select graphics queue family - { - uint32_t count; - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, nullptr); - VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count); - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues); - for (uint32_t i = 0; i < count; i++) - if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) - { - g_QueueFamily = i; - break; - } - free(queues); - IM_ASSERT(g_QueueFamily != (uint32_t)-1); - } + g_QueueFamily = ImGui_ImplVulkanH_SelectQueueFamilyIndex(g_PhysicalDevice); + IM_ASSERT(g_QueueFamily != (uint32_t)-1); // Create Logical Device (with 1 queue) { diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index cb0ade097..51add5c1f 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -87,7 +87,7 @@ int main(int, char**) printf("Error: SDL_GL_CreateContext(): %s\n", SDL_GetError()); return -1; } - + SDL_GL_MakeCurrent(window, gl_context); SDL_GL_SetSwapInterval(1); // Enable vsync diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index cb116b76e..fafa8ea42 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -73,35 +73,6 @@ static bool IsExtensionAvailable(const ImVector& properti return false; } -static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice() -{ - uint32_t gpu_count; - VkResult err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, nullptr); - check_vk_result(err); - IM_ASSERT(gpu_count > 0); - - ImVector gpus; - gpus.resize(gpu_count); - err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus.Data); - check_vk_result(err); - - // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers - // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple - // dedicated GPUs) is out of scope of this sample. - for (VkPhysicalDevice& device : gpus) - { - VkPhysicalDeviceProperties properties; - vkGetPhysicalDeviceProperties(device, &properties); - if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) - return device; - } - - // Use first GPU (Integrated) is a Discrete one is not available. - if (gpu_count > 0) - return gpus[0]; - return VK_NULL_HANDLE; -} - static void SetupVulkan(ImVector instance_extensions) { VkResult err; @@ -165,23 +136,12 @@ static void SetupVulkan(ImVector instance_extensions) } // Select Physical Device (GPU) - g_PhysicalDevice = SetupVulkan_SelectPhysicalDevice(); + g_PhysicalDevice = ImGui_ImplVulkanH_SelectPhysicalDevice(g_Instance); + IM_ASSERT(g_PhysicalDevice != VK_NULL_HANDLE); // Select graphics queue family - { - uint32_t count; - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, nullptr); - VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count); - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues); - for (uint32_t i = 0; i < count; i++) - if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) - { - g_QueueFamily = i; - break; - } - free(queues); - IM_ASSERT(g_QueueFamily != (uint32_t)-1); - } + g_QueueFamily = ImGui_ImplVulkanH_SelectQueueFamilyIndex(g_PhysicalDevice); + IM_ASSERT(g_QueueFamily != (uint32_t)-1); // Create Logical Device (with 1 queue) { diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index dde3c0d4c..569eaeffb 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -78,35 +78,6 @@ static bool IsExtensionAvailable(const ImVector& properti return false; } -static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice() -{ - uint32_t gpu_count; - VkResult err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, nullptr); - check_vk_result(err); - IM_ASSERT(gpu_count > 0); - - ImVector gpus; - gpus.resize(gpu_count); - err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus.Data); - check_vk_result(err); - - // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers - // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple - // dedicated GPUs) is out of scope of this sample. - for (VkPhysicalDevice& device : gpus) - { - VkPhysicalDeviceProperties properties; - vkGetPhysicalDeviceProperties(device, &properties); - if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) - return device; - } - - // Use first GPU (Integrated) is a Discrete one is not available. - if (gpu_count > 0) - return gpus[0]; - return VK_NULL_HANDLE; -} - static void SetupVulkan(ImVector instance_extensions) { VkResult err; @@ -170,23 +141,12 @@ static void SetupVulkan(ImVector instance_extensions) } // Select Physical Device (GPU) - g_PhysicalDevice = SetupVulkan_SelectPhysicalDevice(); + g_PhysicalDevice = ImGui_ImplVulkanH_SelectPhysicalDevice(g_Instance); + IM_ASSERT(g_PhysicalDevice != VK_NULL_HANDLE); // Select graphics queue family - { - uint32_t count; - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, nullptr); - VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count); - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues); - for (uint32_t i = 0; i < count; i++) - if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) - { - g_QueueFamily = i; - break; - } - free(queues); - IM_ASSERT(g_QueueFamily != (uint32_t)-1); - } + g_QueueFamily = ImGui_ImplVulkanH_SelectQueueFamilyIndex(g_PhysicalDevice); + IM_ASSERT(g_QueueFamily != (uint32_t)-1); // Create Logical Device (with 1 queue) { From 38e606a153b9e52f166ccfbd4ae105627fb12ae7 Mon Sep 17 00:00:00 2001 From: Jovan Ristic Date: Sat, 23 Nov 2024 12:41:19 -0800 Subject: [PATCH 0577/2359] Examples: Add Win32+Vulkan example. (#8180) --- examples/example_win32_vulkan/build_win32.bat | 9 + examples/example_win32_vulkan/build_win64.bat | 9 + .../example_win32_vulkan.vcxproj | 180 ++++++ .../example_win32_vulkan.vcxproj.filters | 65 ++ examples/example_win32_vulkan/main.cpp | 600 ++++++++++++++++++ examples/imgui_examples.sln | 10 + 6 files changed, 873 insertions(+) create mode 100644 examples/example_win32_vulkan/build_win32.bat create mode 100644 examples/example_win32_vulkan/build_win64.bat create mode 100644 examples/example_win32_vulkan/example_win32_vulkan.vcxproj create mode 100644 examples/example_win32_vulkan/example_win32_vulkan.vcxproj.filters create mode 100644 examples/example_win32_vulkan/main.cpp diff --git a/examples/example_win32_vulkan/build_win32.bat b/examples/example_win32_vulkan/build_win32.bat new file mode 100644 index 000000000..4bfb7cafc --- /dev/null +++ b/examples/example_win32_vulkan/build_win32.bat @@ -0,0 +1,9 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@set OUT_DIR=Debug +@set OUT_EXE=example_win32_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp +@set LIBS=/libpath:%VULKAN_SDK%\lib32 vulkan-1.lib + +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_vulkan/build_win64.bat b/examples/example_win32_vulkan/build_win64.bat new file mode 100644 index 000000000..f8c66f799 --- /dev/null +++ b/examples/example_win32_vulkan/build_win64.bat @@ -0,0 +1,9 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@set OUT_DIR=Debug +@set OUT_EXE=example_win32_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp +@set LIBS=/libpath:%VULKAN_SDK%\lib vulkan-1.lib + +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj new file mode 100644 index 000000000..cbf01a4ab --- /dev/null +++ b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj @@ -0,0 +1,180 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47} + example_win32_vulkan + 10.0 + + + + Application + true + Unicode + v143 + + + Application + true + Unicode + v143 + + + Application + false + true + Unicode + v143 + + + Application + false + true + Unicode + v143 + + + + + + + + + + + + + + + + + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + + Level4 + Disabled + ..\..;..\..\backends;%VULKAN_SDK%\include;%(AdditionalIncludeDirectories) + _UNICODE;UNICODE;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) + + + true + vulkan-1.lib;%(AdditionalDependencies) + %VULKAN_SDK%\lib32;%(AdditionalLibraryDirectories) + Console + + + + + Level4 + Disabled + ..\..;..\..\backends;%VULKAN_SDK%\include;%(AdditionalIncludeDirectories) + _UNICODE;UNICODE;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) + + + true + vulkan-1.lib;%(AdditionalDependencies) + %VULKAN_SDK%\lib;%(AdditionalLibraryDirectories) + Console + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%VULKAN_SDK%\include;%(AdditionalIncludeDirectories) + _UNICODE;UNICODE;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) + + + true + true + true + vulkan-1.lib;%(AdditionalDependencies) + %VULKAN_SDK%\lib32;%(AdditionalLibraryDirectories) + Console + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%VULKAN_SDK%\include;%(AdditionalIncludeDirectories) + _UNICODE;UNICODE;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) + + + true + true + true + vulkan-1.lib;%(AdditionalDependencies) + %VULKAN_SDK%\lib;%(AdditionalLibraryDirectories) + Console + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj.filters b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj.filters new file mode 100644 index 000000000..a514e6830 --- /dev/null +++ b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj.filters @@ -0,0 +1,65 @@ + + + + + {fb3d294f-51ec-478e-a627-25831c80fefd} + + + {4f33ddea-9910-456d-b868-4267eb3c2b19} + + + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + + + imgui + + + sources + + + imgui + + + imgui + + + sources + + + sources + + + imgui + + + imgui + + + + + + imgui + + + + + imgui + + + \ No newline at end of file diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp new file mode 100644 index 000000000..f3f6367b0 --- /dev/null +++ b/examples/example_win32_vulkan/main.cpp @@ -0,0 +1,600 @@ +// Dear ImGui: standalone example application for Vulkan + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. +// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// You will use those if you want to use this rendering backend in your engine/app. +// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by +// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// Read comments in imgui_impl_vulkan.h. + +#include "imgui.h" +#include "imgui_impl_win32.h" +#define VK_USE_PLATFORM_WIN32_KHR +#include "imgui_impl_vulkan.h" +#include +#include // printf, fprintf +#include // abort +#include + +// Volk headers +#ifdef IMGUI_IMPL_VULKAN_USE_VOLK +#define VOLK_IMPLEMENTATION +#include +#endif + +//#define APP_USE_UNLIMITED_FRAME_RATE +#ifdef _DEBUG +#define APP_USE_VULKAN_DEBUG_REPORT +#endif + +// Data +static VkAllocationCallbacks* g_Allocator = nullptr; +static VkInstance g_Instance = VK_NULL_HANDLE; +static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; +static VkDevice g_Device = VK_NULL_HANDLE; +static uint32_t g_QueueFamily = (uint32_t)-1; +static VkQueue g_Queue = VK_NULL_HANDLE; +static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; +static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; +static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; + +static ImGui_ImplVulkanH_Window g_MainWindowData; +static uint32_t g_MinImageCount = 2; +static bool g_SwapChainRebuild = false; + +static void check_vk_result(VkResult err) +{ + if (err == 0) + return; + fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); + if (err < 0) + abort(); +} + +#ifdef APP_USE_VULKAN_DEBUG_REPORT +static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) +{ + (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments + fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); + return VK_FALSE; +} +#endif // APP_USE_VULKAN_DEBUG_REPORT + +static bool IsExtensionAvailable(const ImVector& properties, const char* extension) +{ + for (const VkExtensionProperties& p : properties) + if (strcmp(p.extensionName, extension) == 0) + return true; + return false; +} + +static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice() +{ + uint32_t gpu_count; + VkResult err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, nullptr); + check_vk_result(err); + IM_ASSERT(gpu_count > 0); + + ImVector gpus; + gpus.resize(gpu_count); + err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus.Data); + check_vk_result(err); + + // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers + // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple + // dedicated GPUs) is out of scope of this sample. + for (VkPhysicalDevice& device : gpus) + { + VkPhysicalDeviceProperties properties; + vkGetPhysicalDeviceProperties(device, &properties); + if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) + return device; + } + + // Use first GPU (Integrated) is a Discrete one is not available. + if (gpu_count > 0) + return gpus[0]; + return VK_NULL_HANDLE; +} + +static void SetupVulkan(ImVector instance_extensions) +{ + VkResult err; +#ifdef IMGUI_IMPL_VULKAN_USE_VOLK + volkInitialize(); +#endif + + // Create Vulkan Instance + { + VkInstanceCreateInfo create_info = {}; + create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + + // Enumerate available extensions + uint32_t properties_count; + ImVector properties; + vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, nullptr); + properties.resize(properties_count); + err = vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, properties.Data); + check_vk_result(err); + + // Enable required extensions + if (IsExtensionAvailable(properties, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) + instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); +#ifdef VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME + if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME)) + { + instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); + create_info.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR; + } +#endif + + // Enabling validation layers +#ifdef APP_USE_VULKAN_DEBUG_REPORT + const char* layers[] = { "VK_LAYER_KHRONOS_validation" }; + create_info.enabledLayerCount = 1; + create_info.ppEnabledLayerNames = layers; + instance_extensions.push_back("VK_EXT_debug_report"); +#endif + + // Create Vulkan Instance + create_info.enabledExtensionCount = (uint32_t)instance_extensions.Size; + create_info.ppEnabledExtensionNames = instance_extensions.Data; + err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); + check_vk_result(err); +#ifdef IMGUI_IMPL_VULKAN_USE_VOLK + volkLoadInstance(g_Instance); +#endif + + // Setup the debug report callback +#ifdef APP_USE_VULKAN_DEBUG_REPORT + auto f_vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT"); + IM_ASSERT(f_vkCreateDebugReportCallbackEXT != nullptr); + VkDebugReportCallbackCreateInfoEXT debug_report_ci = {}; + debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; + debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; + debug_report_ci.pfnCallback = debug_report; + debug_report_ci.pUserData = nullptr; + err = f_vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport); + check_vk_result(err); +#endif + } + + // Select Physical Device (GPU) + g_PhysicalDevice = SetupVulkan_SelectPhysicalDevice(); + + // Select graphics queue family + { + uint32_t count; + vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, nullptr); + VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count); + vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues); + for (uint32_t i = 0; i < count; i++) + if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) + { + g_QueueFamily = i; + break; + } + free(queues); + IM_ASSERT(g_QueueFamily != (uint32_t)-1); + } + + // Create Logical Device (with 1 queue) + { + ImVector device_extensions; + device_extensions.push_back("VK_KHR_swapchain"); + + // Enumerate physical device extension + uint32_t properties_count; + ImVector properties; + vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, nullptr); + properties.resize(properties_count); + vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, properties.Data); +#ifdef VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME + if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME)) + device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME); +#endif + + const float queue_priority[] = { 1.0f }; + VkDeviceQueueCreateInfo queue_info[1] = {}; + queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_info[0].queueFamilyIndex = g_QueueFamily; + queue_info[0].queueCount = 1; + queue_info[0].pQueuePriorities = queue_priority; + VkDeviceCreateInfo create_info = {}; + create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + create_info.queueCreateInfoCount = sizeof(queue_info) / sizeof(queue_info[0]); + create_info.pQueueCreateInfos = queue_info; + create_info.enabledExtensionCount = (uint32_t)device_extensions.Size; + create_info.ppEnabledExtensionNames = device_extensions.Data; + err = vkCreateDevice(g_PhysicalDevice, &create_info, g_Allocator, &g_Device); + check_vk_result(err); + vkGetDeviceQueue(g_Device, g_QueueFamily, 0, &g_Queue); + } + + // Create Descriptor Pool + // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that) + // If you wish to load e.g. additional textures you may need to alter pools sizes. + { + VkDescriptorPoolSize pool_sizes[] = + { + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, + }; + VkDescriptorPoolCreateInfo pool_info = {}; + pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; + pool_info.maxSets = 1; + pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); + pool_info.pPoolSizes = pool_sizes; + err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); + check_vk_result(err); + } +} + +// All the ImGui_ImplVulkanH_XXX structures/functions are optional helpers used by the demo. +// Your real engine/app may not use them. +static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) +{ + wd->Surface = surface; + + // Check for WSI support + VkBool32 res; + vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, wd->Surface, &res); + if (res != VK_TRUE) + { + fprintf(stderr, "Error no WSI support on physical device 0\n"); + exit(-1); + } + + // Select Surface Format + const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; + const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; + wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); + + // Select Present Mode +#ifdef APP_UNLIMITED_FRAME_RATE + VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; +#else + VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; +#endif + wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_ARRAYSIZE(present_modes)); + //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); + + // Create SwapChain, RenderPass, Framebuffer, etc. + IM_ASSERT(g_MinImageCount >= 2); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); +} + +static void CleanupVulkan() +{ + vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); + +#ifdef APP_USE_VULKAN_DEBUG_REPORT + // Remove the debug report callback + auto f_vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT"); + f_vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator); +#endif // APP_USE_VULKAN_DEBUG_REPORT + + vkDestroyDevice(g_Device, g_Allocator); + vkDestroyInstance(g_Instance, g_Allocator); +} + +static void CleanupVulkanWindow() +{ + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); +} + +static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) +{ + VkResult err; + + VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; + err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) + { + g_SwapChainRebuild = true; + return; + } + check_vk_result(err); + + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; + { + err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking + check_vk_result(err); + + err = vkResetFences(g_Device, 1, &fd->Fence); + check_vk_result(err); + } + { + err = vkResetCommandPool(g_Device, fd->CommandPool, 0); + check_vk_result(err); + VkCommandBufferBeginInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + err = vkBeginCommandBuffer(fd->CommandBuffer, &info); + check_vk_result(err); + } + { + VkRenderPassBeginInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + info.renderPass = wd->RenderPass; + info.framebuffer = fd->Framebuffer; + info.renderArea.extent.width = wd->Width; + info.renderArea.extent.height = wd->Height; + info.clearValueCount = 1; + info.pClearValues = &wd->ClearValue; + vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE); + } + + // Record dear imgui primitives into command buffer + ImGui_ImplVulkan_RenderDrawData(draw_data, fd->CommandBuffer); + + // Submit command buffer + vkCmdEndRenderPass(fd->CommandBuffer); + { + VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + info.waitSemaphoreCount = 1; + info.pWaitSemaphores = &image_acquired_semaphore; + info.pWaitDstStageMask = &wait_stage; + info.commandBufferCount = 1; + info.pCommandBuffers = &fd->CommandBuffer; + info.signalSemaphoreCount = 1; + info.pSignalSemaphores = &render_complete_semaphore; + + err = vkEndCommandBuffer(fd->CommandBuffer); + check_vk_result(err); + err = vkQueueSubmit(g_Queue, 1, &info, fd->Fence); + check_vk_result(err); + } +} + +static void FramePresent(ImGui_ImplVulkanH_Window* wd) +{ + if (g_SwapChainRebuild) + return; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; + VkPresentInfoKHR info = {}; + info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + info.waitSemaphoreCount = 1; + info.pWaitSemaphores = &render_complete_semaphore; + info.swapchainCount = 1; + info.pSwapchains = &wd->Swapchain; + info.pImageIndices = &wd->FrameIndex; + VkResult err = vkQueuePresentKHR(g_Queue, &info); + if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) + { + g_SwapChainRebuild = true; + return; + } + check_vk_result(err); + wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores +} + +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Main code +int main(int, char**) +{ + // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); + WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; + ::RegisterClassExW(&wc); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Vulkan Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + + ImVector extensions; + extensions.push_back("VK_KHR_surface"); + extensions.push_back("VK_KHR_win32_surface"); + SetupVulkan(extensions); + + // Create Window Surface + VkSurfaceKHR surface; + VkResult err; + VkWin32SurfaceCreateInfoKHR createInfo = {}; + createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; + createInfo.hwnd = hwnd; + createInfo.hinstance = GetModuleHandle(nullptr); + if (vkCreateWin32SurfaceKHR(g_Instance, &createInfo, nullptr, &surface) != VK_SUCCESS) + { + printf("Failed to create Vulkan surface.\n"); + return 1; + } + + // Show the window + ImGui_ImplVulkanH_Window* wd = &g_MainWindowData; + SetupVulkanWindow(wd, surface, 1280, 800); + ::ShowWindow(hwnd, SW_SHOWDEFAULT); + ::UpdateWindow(hwnd); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup Platform/Renderer backends + ImGui_ImplWin32_Init(hwnd); + ImGui_ImplVulkan_InitInfo init_info = {}; + init_info.Instance = g_Instance; + init_info.PhysicalDevice = g_PhysicalDevice; + init_info.Device = g_Device; + init_info.QueueFamily = g_QueueFamily; + init_info.Queue = g_Queue; + init_info.PipelineCache = g_PipelineCache; + init_info.DescriptorPool = g_DescriptorPool; + init_info.RenderPass = wd->RenderPass; + init_info.Subpass = 0; + init_info.MinImageCount = g_MinImageCount; + init_info.ImageCount = wd->ImageCount; + init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; + init_info.Allocator = g_Allocator; + init_info.CheckVkResultFn = check_vk_result; + ImGui_ImplVulkan_Init(&init_info); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; + while (!done) + { + // Poll and handle messages (inputs, window resize, etc.) + // See the WndProc() function below for our to dispatch events to the Win32 backend. + MSG msg; + while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) + { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + if (msg.message == WM_QUIT) + done = true; + } + if (done) + break; + + // Start the Dear ImGui frame + ImGui_ImplVulkan_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + + ImDrawData* draw_data = ImGui::GetDrawData(); + const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); + if (!is_minimized) + { + wd->ClearValue.color.float32[0] = clear_color.x * clear_color.w; + wd->ClearValue.color.float32[1] = clear_color.y * clear_color.w; + wd->ClearValue.color.float32[2] = clear_color.z * clear_color.w; + wd->ClearValue.color.float32[3] = clear_color.w; + FrameRender(wd, draw_data); + FramePresent(wd); + } + } + + err = vkDeviceWaitIdle(g_Device); + check_vk_result(err); + + // Cleanup + ImGui_ImplVulkan_Shutdown(); + ImGui_ImplWin32_Shutdown(); + ImGui::DestroyContext(); + + CleanupVulkanWindow(); + CleanupVulkan(); + + ::DestroyWindow(hwnd); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); + + return 0; +} + +// Helper functions + +// Forward declare message handler from imgui_impl_win32.cpp +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Win32 message handler +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_SIZE: + if (g_Device != VK_NULL_HANDLE && wParam != SIZE_MINIMIZED) + { + // Resize swap chain + int fb_width = (UINT)LOWORD(lParam); + int fb_height = (UINT)HIWORD(lParam); + if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) + { + ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount); + g_MainWindowData.FrameIndex = 0; + g_SwapChainRebuild = false; + } + } + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + } + return ::DefWindowProcW(hWnd, msg, wParam, lParam); +} diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index ea9f65cbd..3a856462a 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -35,6 +35,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlrenderer3", EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_vulkan", "example_sdl3_vulkan\example_sdl3_vulkan.vcxproj", "{663A7E89-1E42-4222-921C-177F5B5910DF}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_vulkan", "example_win32_vulkan\example_win32_vulkan.vcxproj", "{4CB8C22A-96F8-4D31-B747-FDAA6B742E47}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -171,6 +173,14 @@ Global {663A7E89-1E42-4222-921C-177F5B5910DF}.Release|Win32.Build.0 = Release|Win32 {663A7E89-1E42-4222-921C-177F5B5910DF}.Release|x64.ActiveCfg = Release|x64 {663A7E89-1E42-4222-921C-177F5B5910DF}.Release|x64.Build.0 = Release|x64 + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Debug|Win32.ActiveCfg = Debug|Win32 + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Debug|Win32.Build.0 = Debug|Win32 + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Debug|x64.ActiveCfg = Debug|x64 + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Debug|x64.Build.0 = Debug|x64 + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Release|Win32.ActiveCfg = Release|Win32 + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Release|Win32.Build.0 = Release|Win32 + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Release|x64.ActiveCfg = Release|x64 + {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 93a93071a27fc733c96368d179c51bb8e43ddc86 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 17:43:52 +0100 Subject: [PATCH 0578/2359] Examples: Add Win32+Vulkan example, amends. (#8180) --- docs/CHANGELOG.txt | 1 + docs/EXAMPLES.md | 6 +- examples/example_glfw_vulkan/main.cpp | 2 +- .../example_win32_vulkan.vcxproj | 18 +++--- .../example_win32_vulkan.vcxproj.filters | 26 ++++---- examples/example_win32_vulkan/main.cpp | 61 +++---------------- examples/imgui_examples.sln | 18 +++--- 7 files changed, 46 insertions(+), 86 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 01d00e0ca..412ddabda 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -72,6 +72,7 @@ Other changes: platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF] - Backends: Vulkan: Added a few more ImGui_ImplVulkanH_XXX helper functions primarily for the purpose of making our examples simpler. +- Examples: Added Win32+Vulkan example for completeness. (#8180) [@jristic] ----------------------------------------------------------------------- diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index f84f9497b..224beb1c1 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -167,9 +167,13 @@ DirectX12 example, Windows only.
This is quite long and tedious, because: DirectX12. [example_win32_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_opengl3/)
-Raw Windows + OpenGL3 + example (modern, programmable pipeline)
+Raw Windows + OpenGL3 example (modern, programmable pipeline)
= main.cpp + imgui_impl_win32.cpp + imgui_impl_opengl3.cpp
+[example_win32_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_vulkan/)
+Raw Windows + Vulkan example
+= main.cpp + imgui_impl_win32.cpp + imgui_impl_vulkan.cpp
+ ### Miscellaneous diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 1197ca4e6..9f8dced2f 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -52,7 +52,7 @@ static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; -static int g_MinImageCount = 2; +static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; static void glfw_error_callback(int error, const char* description) diff --git a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj index cbf01a4ab..dab8afd4e 100644 --- a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj +++ b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj @@ -19,36 +19,35 @@ - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47} - example_win32_vulkan - 10.0 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88} + example_win32_directx11 Application true Unicode - v143 + v140 Application true Unicode - v143 + v140 Application false true Unicode - v143 + v140 Application false true Unicode - v143 + v140 @@ -120,6 +119,7 @@ true ..\..;..\..\backends;%VULKAN_SDK%\include;%(AdditionalIncludeDirectories) _UNICODE;UNICODE;%(PreprocessorDefinitions) + false /utf-8 %(AdditionalOptions) @@ -169,11 +169,9 @@ + - - - diff --git a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj.filters b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj.filters index a514e6830..c91a95810 100644 --- a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj.filters +++ b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj.filters @@ -2,10 +2,10 @@ - {fb3d294f-51ec-478e-a627-25831c80fefd} + {0587d7a3-f2ce-4d56-b84f-a0005d3bfce6} - {4f33ddea-9910-456d-b868-4267eb3c2b19} + {08e36723-ce4f-4cff-9662-c40801cf1acf} @@ -18,10 +18,10 @@ imgui - + sources - + sources @@ -38,28 +38,26 @@ imgui - - sources + + imgui sources + + sources + imgui - - imgui - + + imgui + imgui - - - imgui - - \ No newline at end of file diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index f3f6367b0..3fabf7a2d 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for Vulkan +// Dear ImGui: standalone example application for Win32 + Vulkan // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq @@ -74,35 +74,6 @@ static bool IsExtensionAvailable(const ImVector& properti return false; } -static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice() -{ - uint32_t gpu_count; - VkResult err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, nullptr); - check_vk_result(err); - IM_ASSERT(gpu_count > 0); - - ImVector gpus; - gpus.resize(gpu_count); - err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus.Data); - check_vk_result(err); - - // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers - // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple - // dedicated GPUs) is out of scope of this sample. - for (VkPhysicalDevice& device : gpus) - { - VkPhysicalDeviceProperties properties; - vkGetPhysicalDeviceProperties(device, &properties); - if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) - return device; - } - - // Use first GPU (Integrated) is a Discrete one is not available. - if (gpu_count > 0) - return gpus[0]; - return VK_NULL_HANDLE; -} - static void SetupVulkan(ImVector instance_extensions) { VkResult err; @@ -166,23 +137,12 @@ static void SetupVulkan(ImVector instance_extensions) } // Select Physical Device (GPU) - g_PhysicalDevice = SetupVulkan_SelectPhysicalDevice(); + g_PhysicalDevice = ImGui_ImplVulkanH_SelectPhysicalDevice(g_Instance); + IM_ASSERT(g_PhysicalDevice != VK_NULL_HANDLE); // Select graphics queue family - { - uint32_t count; - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, nullptr); - VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count); - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues); - for (uint32_t i = 0; i < count; i++) - if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) - { - g_QueueFamily = i; - break; - } - free(queues); - IM_ASSERT(g_QueueFamily != (uint32_t)-1); - } + g_QueueFamily = ImGui_ImplVulkanH_SelectQueueFamilyIndex(g_PhysicalDevice); + IM_ASSERT(g_QueueFamily != (uint32_t)-1); // Create Logical Device (with 1 queue) { @@ -257,7 +217,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode -#ifdef APP_UNLIMITED_FRAME_RATE +#ifdef APP_USE_UNLIMITED_FRAME_RATE VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; @@ -387,7 +347,7 @@ int main(int, char**) //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; ::RegisterClassExW(&wc); - HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Vulkan Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+Vulkan Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); ImVector extensions; extensions.push_back("VK_KHR_surface"); @@ -400,7 +360,7 @@ int main(int, char**) VkWin32SurfaceCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; createInfo.hwnd = hwnd; - createInfo.hinstance = GetModuleHandle(nullptr); + createInfo.hinstance = ::GetModuleHandle(nullptr); if (vkCreateWin32SurfaceKHR(g_Instance, &createInfo, nullptr, &surface) != VK_SUCCESS) { printf("Failed to create Vulkan surface.\n"); @@ -408,6 +368,7 @@ int main(int, char**) } // Show the window + // FIXME: Retrieve client size from window itself. ImGui_ImplVulkanH_Window* wd = &g_MainWindowData; SetupVulkanWindow(wd, surface, 1280, 800); ::ShowWindow(hwnd, SW_SHOWDEFAULT); @@ -525,7 +486,6 @@ int main(int, char**) // Rendering ImGui::Render(); - ImDrawData* draw_data = ImGui::GetDrawData(); const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); if (!is_minimized) @@ -539,10 +499,9 @@ int main(int, char**) } } + // Cleanup err = vkDeviceWaitIdle(g_Device); check_vk_result(err); - - // Cleanup ImGui_ImplVulkan_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index 3a856462a..85f7451d4 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -35,7 +35,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlrenderer3", EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_vulkan", "example_sdl3_vulkan\example_sdl3_vulkan.vcxproj", "{663A7E89-1E42-4222-921C-177F5B5910DF}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_vulkan", "example_win32_vulkan\example_win32_vulkan.vcxproj", "{4CB8C22A-96F8-4D31-B747-FDAA6B742E47}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_vulkan", "example_win32_vulkan\example_win32_vulkan.vcxproj", "{0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -173,14 +173,14 @@ Global {663A7E89-1E42-4222-921C-177F5B5910DF}.Release|Win32.Build.0 = Release|Win32 {663A7E89-1E42-4222-921C-177F5B5910DF}.Release|x64.ActiveCfg = Release|x64 {663A7E89-1E42-4222-921C-177F5B5910DF}.Release|x64.Build.0 = Release|x64 - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Debug|Win32.ActiveCfg = Debug|Win32 - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Debug|Win32.Build.0 = Debug|Win32 - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Debug|x64.ActiveCfg = Debug|x64 - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Debug|x64.Build.0 = Debug|x64 - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Release|Win32.ActiveCfg = Release|Win32 - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Release|Win32.Build.0 = Release|Win32 - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Release|x64.ActiveCfg = Release|x64 - {4CB8C22A-96F8-4D31-B747-FDAA6B742E47}.Release|x64.Build.0 = Release|x64 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Debug|Win32.ActiveCfg = Debug|Win32 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Debug|Win32.Build.0 = Debug|Win32 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Debug|x64.ActiveCfg = Debug|x64 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Debug|x64.Build.0 = Debug|x64 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Release|Win32.ActiveCfg = Release|Win32 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Release|Win32.Build.0 = Release|Win32 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Release|x64.ActiveCfg = Release|x64 + {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From af271e733039548d62eb7b56e94fd3672304f343 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 18:20:56 +0100 Subject: [PATCH 0579/2359] Backends: DX11: Expose vertex constant buffer in ImGui_ImplDX11_RenderState. DX9 and DX12 users can already alter the projection matrix (in undocumented ways, but possible) --- backends/imgui_impl_dx11.cpp | 45 ++++++++++++++++++------------------ backends/imgui_impl_dx11.h | 2 ++ docs/CHANGELOG.txt | 2 ++ 3 files changed, 27 insertions(+), 22 deletions(-) diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index a2c67ec43..bbd1633a2 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -16,6 +16,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-06: DirectX11: Expose VertexConstantBuffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handler. // 2024-10-07: DirectX11: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-10-07: DirectX11: Expose selected render state in ImGui_ImplDX11_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. @@ -98,6 +99,27 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC vp.TopLeftX = vp.TopLeftY = 0; device_ctx->RSSetViewports(1, &vp); + // Setup orthographic projection matrix into our constant buffer + // 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. + D3D11_MAPPED_SUBRESOURCE mapped_resource; + if (device_ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK) + { + VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData; + float L = draw_data->DisplayPos.x; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; + float T = draw_data->DisplayPos.y; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + float mvp[4][4] = + { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.5f, 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, + }; + memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); + device_ctx->Unmap(bd->pVertexConstantBuffer, 0); + } + // Setup shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; @@ -179,28 +201,6 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) device->Unmap(bd->pVB, 0); device->Unmap(bd->pIB, 0); - // Setup orthographic projection matrix into our constant buffer - // 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. - { - D3D11_MAPPED_SUBRESOURCE mapped_resource; - if (device->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) - return; - VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData; - float L = draw_data->DisplayPos.x; - float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; - float T = draw_data->DisplayPos.y; - float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; - float mvp[4][4] = - { - { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, - { 0.0f, 0.0f, 0.5f, 0.0f }, - { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, - }; - memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); - device->Unmap(bd->pVertexConstantBuffer, 0); - } - // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!) struct BACKUP_DX11_STATE { @@ -255,6 +255,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) render_state.Device = bd->pd3dDevice; render_state.DeviceContext = bd->pd3dDeviceContext; render_state.SamplerDefault = bd->pFontSampler; + render_state.VertexConstantBuffer = bd->pVertexConstantBuffer; platform_io.Renderer_RenderState = &render_state; // Render command lists diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h index 69ae49358..772c1b920 100644 --- a/backends/imgui_impl_dx11.h +++ b/backends/imgui_impl_dx11.h @@ -21,6 +21,7 @@ struct ID3D11Device; struct ID3D11DeviceContext; struct ID3D11SamplerState; +struct ID3D11Buffer; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context); @@ -40,6 +41,7 @@ struct ImGui_ImplDX11_RenderState ID3D11Device* Device; ID3D11DeviceContext* DeviceContext; ID3D11SamplerState* SamplerDefault; + ID3D11Buffer* VertexConstantBuffer; }; #endif // #ifndef IMGUI_DISABLE diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 412ddabda..4500f5a1f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -72,6 +72,8 @@ Other changes: platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF] - Backends: Vulkan: Added a few more ImGui_ImplVulkanH_XXX helper functions primarily for the purpose of making our examples simpler. +- Backends: DX11: Expose vertex constant buffer in ImGui_ImplDX11_RenderState. + Reset projection matrix in ImDrawCallback_ResetRenderState handlers. (#6969, #5834, #7468, #3590) - Examples: Added Win32+Vulkan example for completeness. (#8180) [@jristic] From f04d3cbdaaf037e5f57bc39c0bd3f0d0c43b98fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 18:28:01 +0100 Subject: [PATCH 0580/2359] Backends: DirectX10: Expose selected render state in ImGui_ImplDX10_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. (#6969, #5834, #7468, #3590) Amend e94f95d --- backends/imgui_impl_dx10.cpp | 56 ++++++++++++++++++++---------------- backends/imgui_impl_dx10.h | 12 ++++++++ backends/imgui_impl_dx11.cpp | 2 +- docs/CHANGELOG.txt | 1 + 4 files changed, 46 insertions(+), 25 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 15f0bb323..89499af0c 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-06: DirectX10: Expose selected render state in ImGui_ImplDX10_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). @@ -95,7 +96,28 @@ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* vp.TopLeftX = vp.TopLeftY = 0; device->RSSetViewports(1, &vp); - // Bind shader and vertex buffers + // Setup orthographic projection matrix into our constant buffer + // 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. + void* mapped_resource; + if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK) + { + VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource; + float L = draw_data->DisplayPos.x; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; + float T = draw_data->DisplayPos.y; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + float mvp[4][4] = + { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.5f, 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, + }; + memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); + bd->pVertexConstantBuffer->Unmap(); + } + + // Setup shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; device->IASetInputLayout(bd->pInputLayout); @@ -171,28 +193,6 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) bd->pVB->Unmap(); bd->pIB->Unmap(); - // Setup orthographic projection matrix into our constant buffer - // 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. - { - void* mapped_resource; - if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) - return; - VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource; - float L = draw_data->DisplayPos.x; - float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; - float T = draw_data->DisplayPos.y; - float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; - float mvp[4][4] = - { - { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, - { 0.0f, 0.0f, 0.5f, 0.0f }, - { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, - }; - memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); - bd->pVertexConstantBuffer->Unmap(); - } - // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!) struct BACKUP_DX10_STATE { @@ -236,6 +236,13 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) // Setup desired DX state ImGui_ImplDX10_SetupRenderState(draw_data, device); + // Setup render state structure (for callbacks and custom texture bindings) + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + ImGui_ImplDX10_RenderState render_state; + render_state.Device = bd->pd3dDevice; + render_state.SamplerDefault = bd->pFontSampler; + render_state.VertexConstantBuffer = bd->pVertexConstantBuffer; + platform_io.Renderer_RenderState = &render_state; // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) @@ -248,7 +255,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) + if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) @@ -278,6 +285,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) global_idx_offset += draw_list->IdxBuffer.Size; global_vtx_offset += draw_list->VtxBuffer.Size; } + platform_io.Renderer_RenderState = nullptr; // Restore modified DX state device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects); diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h index 29f339370..d9f29987d 100644 --- a/backends/imgui_impl_dx10.h +++ b/backends/imgui_impl_dx10.h @@ -18,6 +18,8 @@ #ifndef IMGUI_DISABLE struct ID3D10Device; +struct ID3D10SamplerState; +struct ID3D10Buffer; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplDX10_Init(ID3D10Device* device); @@ -29,4 +31,14 @@ IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects(); +// [BETA] Selected render state data shared with callbacks. +// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX10_RenderDrawData() call. +// (Please open an issue if you feel you need access to more data) +struct ImGui_ImplDX10_RenderState +{ + ID3D10Device* Device; + ID3D10SamplerState* SamplerDefault; + ID3D10Buffer* VertexConstantBuffer; +}; + #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index bbd1633a2..b38fece26 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -136,7 +136,7 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC device_ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. device_ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. - // Setup blend state + // Setup render state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; device_ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff); device_ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4500f5a1f..81763b99c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -74,6 +74,7 @@ Other changes: primarily for the purpose of making our examples simpler. - Backends: DX11: Expose vertex constant buffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handlers. (#6969, #5834, #7468, #3590) +- Backends: DX10: Expose ImGui_ImplDX10_RenderState for completeness. (#6969, #5834, #7468, #3590) - Examples: Added Win32+Vulkan example for completeness. (#8180) [@jristic] From cec8ff1885deb4728cafca5b37bf532f68572e66 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Jan 2025 18:41:17 +0100 Subject: [PATCH 0581/2359] Backends: Vulkan: Fixed building with using VK_NO_PROTOTYPES. (#8180) Broken by a2e2172 --- backends/imgui_impl_vulkan.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 1953288d9..de4c5a4aa 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -164,6 +164,7 @@ static bool g_FunctionsLoaded = true; IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySurfaceKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySwapchainKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDeviceWaitIdle) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkEnumeratePhysicalDevices) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkEndCommandBuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFlushMappedMemoryRanges) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeCommandBuffers) \ @@ -171,7 +172,9 @@ static bool g_FunctionsLoaded = true; IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetBufferMemoryRequirements) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetImageMemoryRequirements) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceProperties) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceMemoryProperties) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceQueueFamilyProperties) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfaceFormatsKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfacePresentModesKHR) \ From 3115ae081591fe75b98747a7737eab065f2628f8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 27 Dec 2024 11:49:39 +0100 Subject: [PATCH 0582/2359] Demo: Font selector combo sets default focus. --- imgui_demo.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 36d8f4415..c9a21759d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7851,6 +7851,8 @@ void ImGui::ShowFontSelector(const char* label) ImGui::PushID((void*)font); if (ImGui::Selectable(font->GetDebugName(), font == font_current)) io.FontDefault = font; + if (font == font_current) + ImGui::SetItemDefaultFocus(); ImGui::PopID(); } ImGui::EndCombo(); From 0514332474fc3ffbb19e886de1b3b167e6aac521 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Jan 2025 11:44:00 +0100 Subject: [PATCH 0583/2359] Avoid clang/gcc warnings: -Wnontrivial-memaccess in backends. (#8295, #8129, #8135) --- backends/imgui_impl_dx12.h | 2 +- backends/imgui_impl_vulkan.cpp | 2 +- misc/freetype/imgui_freetype.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 644c022ff..a57c1694d 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -43,7 +43,7 @@ struct ImGui_ImplDX12_InitInfo D3D12_GPU_DESCRIPTOR_HANDLE LegacySingleSrvGpuDescriptor; #endif - ImGui_ImplDX12_InitInfo() { memset(this, 0, sizeof(*this)); } + ImGui_ImplDX12_InitInfo() { memset((void*)this, 0, sizeof(*this)); } }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index de4c5a4aa..4345f2b11 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -225,7 +225,7 @@ struct ImGui_ImplVulkan_Texture VkImageView ImageView; VkDescriptorSet DescriptorSet; - ImGui_ImplVulkan_Texture() { memset(this, 0, sizeof(*this)); } + ImGui_ImplVulkan_Texture() { memset((void*)this, 0, sizeof(*this)); } }; // Vulkan data diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index aeab6dfa0..997bc4340 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -169,7 +169,7 @@ namespace const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info); void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr); - FreeTypeFont() { memset(this, 0, sizeof(*this)); } + FreeTypeFont() { memset((void*)this, 0, sizeof(*this)); } ~FreeTypeFont() { CloseFont(); } // [Internals] From e6a7c7689f57038b2519fe43e55e3d57103ad0f7 Mon Sep 17 00:00:00 2001 From: Selim Sandal <49725809+selimsandal@users.noreply.github.com> Date: Wed, 8 Jan 2025 12:00:40 +0100 Subject: [PATCH 0584/2359] Backends: Metal: Fixed memory leaks. (#8276, #8166) --- backends/imgui_impl_metal.mm | 10 ++++++++-- docs/CHANGELOG.txt | 1 + 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index edd7fa181..3ff905a60 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419). // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. // 2022-07-05: Metal: Add dispatch synchronization. // 2022-06-30: Metal: Use __bridge for ARC based systems. @@ -156,8 +157,11 @@ void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor) { ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?"); +#ifdef IMGUI_IMPL_METAL_CPP + bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; +#else bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; - +#endif if (bd->SharedMetalContext.depthStencilState == nil) ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device); } @@ -364,8 +368,10 @@ bool ImGui_ImplMetal_CreateDeviceObjects(id device) depthStencilDescriptor.depthWriteEnabled = NO; depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways; bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor]; +#ifdef IMGUI_IMPL_METAL_CPP + [depthStencilDescriptor release]; +#endif ImGui_ImplMetal_CreateFontsTexture(device); - return true; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 81763b99c..a24d6ea4e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,7 @@ Other changes: - Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). [@Helodity] +- Backends: Metal: Fixed leaks when using metal-cpp. (#8276, #8166) [@selimsandal] - Backends: Metal: Fixed resource leak when using multiple contexts. (#7419) [@anszom] - Backends: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF] From bbbdc70f26b15db176a0b93f9dde3cd5f6d84d8c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Jan 2025 12:43:56 +0100 Subject: [PATCH 0585/2359] Refactor: moved FindBlockingModal() in its section. --- imgui.cpp | 96 ++++++++++++++++++++++++++----------------------------- 1 file changed, 45 insertions(+), 51 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3bb95bfce..00d66f857 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3542,7 +3542,6 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) return "Unknown"; } - //----------------------------------------------------------------------------- // [SECTION] RENDER HELPERS // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, @@ -4252,7 +4251,6 @@ void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type) hook.Callback(&g, &hook); } - //----------------------------------------------------------------------------- // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) //----------------------------------------------------------------------------- @@ -6957,42 +6955,6 @@ static void SetWindowActiveForSkipRefresh(ImGuiWindow* window) } } -// 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. -// - WindowA // FindBlockingModal() returns Modal1 -// - WindowB // .. returns Modal1 -// - Modal1 // .. returns Modal2 -// - WindowC // .. returns Modal2 -// - WindowD // .. returns Modal2 -// - Modal2 // .. returns Modal2 -// - WindowE // .. returns NULL -// Notes: -// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL. -// Only difference is here we check for ->Active/WasActive but it may be unnecessary. -ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window) -{ - ImGuiContext& g = *GImGui; - if (g.OpenPopupStack.Size <= 0) - return NULL; - - // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal. - for (ImGuiPopupData& popup_data : g.OpenPopupStack) - { - ImGuiWindow* popup_window = popup_data.Window; - if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal)) - continue; - if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows. - continue; - if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click. - return popup_window; - if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal - continue; - return popup_window; // Place window right below first block modal - } - return NULL; -} - // Push a new Dear ImGui window to add widgets to. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. // - Begin/End can be called multiple times during the frame with the same window name to append content. @@ -8276,14 +8238,6 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) return (ref_window == cur_window); } -// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) -// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. -// If you want a window to never be focused, you may use the e.g. NoInputs flag. -bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) -{ - return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); -} - float ImGui::GetWindowWidth() { ImGuiWindow* window = GImGui->CurrentWindow; @@ -10308,7 +10262,6 @@ bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID own return true; } - //----------------------------------------------------------------------------- // [SECTION] ERROR CHECKING, STATE RECOVERY //----------------------------------------------------------------------------- @@ -11655,6 +11608,43 @@ 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. +// - WindowA // FindBlockingModal() returns Modal1 +// - WindowB // .. returns Modal1 +// - Modal1 // .. returns Modal2 +// - WindowC // .. returns Modal2 +// - WindowD // .. returns Modal2 +// - Modal2 // .. returns Modal2 +// - WindowE // .. returns NULL +// Notes: +// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL. +// Only difference is here we check for ->Active/WasActive but it may be unnecessary. +ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.Size <= 0) + return NULL; + + // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal. + for (ImGuiPopupData& popup_data : g.OpenPopupStack) + { + ImGuiWindow* popup_window = popup_data.Window; + if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal)) + continue; + if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows. + continue; + if (window == NULL) // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click. + return popup_window; + if (IsWindowWithinBeginStackOf(window, popup_window)) // Window may be over modal + continue; + return popup_window; // Place window right below first block modal + } + return NULL; +} + void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; @@ -13524,6 +13514,14 @@ static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) return order; } +// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) +// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. +// If you want a window to never be focused, you may use the e.g. NoInputs flag. +bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) +{ + return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); +} + static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; @@ -13801,7 +13799,6 @@ void ImGui::NavUpdateWindowingOverlay() PopStyleVar(); } - //----------------------------------------------------------------------------- // [SECTION] DRAG AND DROP //----------------------------------------------------------------------------- @@ -14410,7 +14407,6 @@ void ImGui::LogButtons() LogToClipboard(); } - //----------------------------------------------------------------------------- // [SECTION] SETTINGS //----------------------------------------------------------------------------- @@ -14770,7 +14766,6 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl } } - //----------------------------------------------------------------------------- // [SECTION] LOCALIZATION //----------------------------------------------------------------------------- @@ -14782,7 +14777,6 @@ void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count) g.LocalizationTable[entries[n].Key] = entries[n].Text; } - //----------------------------------------------------------------------------- // [SECTION] VIEWPORTS, PLATFORM WINDOWS //----------------------------------------------------------------------------- From 2b8545684caea55032b48c7c62d493e7cf169e01 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Jan 2025 14:22:37 +0100 Subject: [PATCH 0586/2359] Refactor: moved Window Focus related functions to a dedicated section. --- imgui.cpp | 522 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 272 insertions(+), 250 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 00d66f857..5f898a389 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -85,6 +85,7 @@ CODE // [SECTION] SCROLLING // [SECTION] TOOLTIPS // [SECTION] POPUPS +// [SECTION] WINDOW FOCUS // [SECTION] KEYBOARD/GAMEPAD NAVIGATION // [SECTION] DRAG AND DROP // [SECTION] LOGGING/CAPTURING @@ -1202,6 +1203,10 @@ namespace ImGui // Item static void ItemHandleShortcut(ImGuiID id); +// Window Focus +static int FindWindowFocusIndex(ImGuiWindow* window); +static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags); + // Navigation static void NavUpdate(); static void NavUpdateWindowing(); @@ -1222,7 +1227,6 @@ static ImVec2 NavCalcPreferredRefPos(); static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window); static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); static void NavRestoreLayer(ImGuiNavLayer layer); -static int FindWindowFocusIndex(ImGuiWindow* window); // Error Checking and Debug Tools static void ErrorCheckNewFrameSanityChecks(); @@ -6171,29 +6175,6 @@ static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settin window->Collapsed = settings->Collapsed; } -static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags) -{ - ImGuiContext& g = *GImGui; - - const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0); - const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild; - if ((just_created || child_flag_changed) && !new_is_explicit_child) - { - IM_ASSERT(!g.WindowsFocusOrder.contains(window)); - g.WindowsFocusOrder.push_back(window); - window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1); - } - else if (!just_created && child_flag_changed && new_is_explicit_child) - { - IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window); - for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++) - g.WindowsFocusOrder[n]->FocusOrder--; - g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder); - window->FocusOrder = -1; - } - window->IsExplicitChild = new_is_explicit_child; -} - static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) { // Initial window state with e.g. default/arbitrary window position @@ -7777,176 +7758,6 @@ void ImGui::End() SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window); } -void ImGui::BringWindowToFocusFront(ImGuiWindow* window) -{ - ImGuiContext& g = *GImGui; - IM_ASSERT(window == window->RootWindow); - - const int cur_order = window->FocusOrder; - IM_ASSERT(g.WindowsFocusOrder[cur_order] == window); - if (g.WindowsFocusOrder.back() == window) - return; - - const int new_order = g.WindowsFocusOrder.Size - 1; - for (int n = cur_order; n < new_order; n++) - { - g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1]; - g.WindowsFocusOrder[n]->FocusOrder--; - IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n); - } - g.WindowsFocusOrder[new_order] = window; - window->FocusOrder = (short)new_order; -} - -void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* current_front_window = g.Windows.back(); - if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better) - return; - for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window - if (g.Windows[i] == window) - { - memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*)); - g.Windows[g.Windows.Size - 1] = window; - break; - } -} - -void ImGui::BringWindowToDisplayBack(ImGuiWindow* window) -{ - ImGuiContext& g = *GImGui; - if (g.Windows[0] == window) - return; - for (int i = 0; i < g.Windows.Size; i++) - if (g.Windows[i] == window) - { - memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*)); - g.Windows[0] = window; - break; - } -} - -void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window) -{ - IM_ASSERT(window != NULL && behind_window != NULL); - ImGuiContext& g = *GImGui; - window = window->RootWindow; - behind_window = behind_window->RootWindow; - int pos_wnd = FindWindowDisplayIndex(window); - int pos_beh = FindWindowDisplayIndex(behind_window); - if (pos_wnd < pos_beh) - { - size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*); - memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes); - g.Windows[pos_beh - 1] = window; - } - else - { - size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*); - memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes); - g.Windows[pos_beh] = window; - } -} - -int ImGui::FindWindowDisplayIndex(ImGuiWindow* window) -{ - ImGuiContext& g = *GImGui; - return g.Windows.index_from_ptr(g.Windows.find(window)); -} - -// Moving window to front of display and set focus (which happens to be back of our sorted list) -void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags) -{ - ImGuiContext& g = *GImGui; - - // Modal check? - if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case. - if (ImGuiWindow* blocking_modal = FindBlockingModal(window)) - { - // This block would typically be reached in two situations: - // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag. - // - User clicking on void or anything behind a modal while a modal is open (window == NULL) - IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "", blocking_modal->Name); - if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) - BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?) - ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals - return; - } - - // Find last focused child (if any) and focus it instead. - if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL) - window = NavRestoreLastChildNavWindow(window); - - // Apply focus - if (g.NavWindow != window) - { - SetNavWindow(window); - if (window && g.NavHighlightItemUnderNav) - g.NavMousePosDirty = true; - g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId - g.NavLayer = ImGuiNavLayer_Main; - SetNavFocusScope(window ? window->NavRootFocusScopeId : 0); - g.NavIdIsAlive = false; - g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; - - // Close popups if any - ClosePopupsOverWindow(window, false); - } - - // Move the root window to the top of the pile - IM_ASSERT(window == NULL || window->RootWindow != NULL); - ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop - ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; - - // Steal active widgets. Some of the cases it triggers includes: - // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. - // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) - if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) - if (!g.ActiveIdNoClearOnFocusLoss) - ClearActiveID(); - - // Passing NULL allow to disable keyboard focus - if (!window) - return; - - // Bring to front - BringWindowToFocusFront(focus_front_window); - if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) - BringWindowToDisplayFront(display_front_window); -} - -void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags) -{ - ImGuiContext& g = *GImGui; - IM_UNUSED(filter_viewport); // Unused in master branch. - int start_idx = g.WindowsFocusOrder.Size - 1; - if (under_this_window != NULL) - { - // Aim at root window behind us, if we are in a child window that's our own root (see #4640) - int offset = -1; - while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow) - { - under_this_window = under_this_window->ParentWindow; - offset = 0; - } - start_idx = FindWindowFocusIndex(under_this_window) + offset; - } - for (int i = start_idx; i >= 0; i--) - { - // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user. - ImGuiWindow* window = g.WindowsFocusOrder[i]; - if (window == ignore_window || !window->WasActive) - continue; - if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) - { - FocusWindow(window, flags); - return; - } - } - FocusWindow(NULL, flags); -} - // Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only. void ImGui::SetCurrentFont(ImFont* font) { @@ -8216,28 +8027,6 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) return true; } -bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* ref_window = g.NavWindow; - ImGuiWindow* cur_window = g.CurrentWindow; - - if (ref_window == NULL) - return false; - if (flags & ImGuiFocusedFlags_AnyWindow) - return true; - - IM_ASSERT(cur_window); // Not inside a Begin()/End() - const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0; - if (flags & ImGuiHoveredFlags_RootWindow) - cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy); - - if (flags & ImGuiHoveredFlags_ChildWindows) - return IsWindowChildOf(ref_window, cur_window, popup_hierarchy); - else - return (ref_window == cur_window); -} - float ImGui::GetWindowWidth() { ImGuiWindow* window = GImGui->CurrentWindow; @@ -8385,24 +8174,6 @@ void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond) SetWindowCollapsed(window, collapsed, cond); } -void ImGui::SetWindowFocus() -{ - FocusWindow(GImGui->CurrentWindow); -} - -void ImGui::SetWindowFocus(const char* name) -{ - if (name) - { - if (ImGuiWindow* window = FindWindowByName(name)) - FocusWindow(window); - } - else - { - FocusWindow(NULL); - } -} - void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot) { ImGuiContext& g = *GImGui; @@ -8460,12 +8231,6 @@ void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; } -void ImGui::SetNextWindowFocus() -{ - ImGuiContext& g = *GImGui; - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus; -} - void ImGui::SetNextWindowBgAlpha(float alpha) { ImGuiContext& g = *GImGui; @@ -12148,6 +11913,273 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) return window->Pos; } +//----------------------------------------------------------------------------- +// [SECTION] WINDOW FOCUS +//---------------------------------------------------------------------------- +// - SetWindowFocus() +// - SetNextWindowFocus() +// - IsWindowFocused() +// - UpdateWindowInFocusOrderList() [Internal] +// - BringWindowToFocusFront() [Internal] +// - BringWindowToDisplayFront() [Internal] +// - BringWindowToDisplayBack() [Internal] +// - BringWindowToDisplayBehind() [Internal] +// - FindWindowDisplayIndex() [Internal] +// - FocusWindow() [Internal] +// - FocusTopMostWindowUnderOne() [Internal] +//----------------------------------------------------------------------------- + +void ImGui::SetWindowFocus() +{ + FocusWindow(GImGui->CurrentWindow); +} + +void ImGui::SetWindowFocus(const char* name) +{ + if (name) + { + if (ImGuiWindow* window = FindWindowByName(name)) + FocusWindow(window); + } + else + { + FocusWindow(NULL); + } +} + +void ImGui::SetNextWindowFocus() +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus; +} + +// Similar to IsWindowHovered() +bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* ref_window = g.NavWindow; + ImGuiWindow* cur_window = g.CurrentWindow; + + if (ref_window == NULL) + return false; + if (flags & ImGuiFocusedFlags_AnyWindow) + return true; + + IM_ASSERT(cur_window); // Not inside a Begin()/End() + const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0; + if (flags & ImGuiHoveredFlags_RootWindow) + cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy); + + if (flags & ImGuiHoveredFlags_ChildWindows) + return IsWindowChildOf(ref_window, cur_window, popup_hierarchy); + else + return (ref_window == cur_window); +} + +static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_UNUSED(g); + int order = window->FocusOrder; + IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking) + IM_ASSERT(g.WindowsFocusOrder[order] == window); + return order; +} + +static void ImGui::UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags) +{ + ImGuiContext& g = *GImGui; + + const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0); + const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild; + if ((just_created || child_flag_changed) && !new_is_explicit_child) + { + IM_ASSERT(!g.WindowsFocusOrder.contains(window)); + g.WindowsFocusOrder.push_back(window); + window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1); + } + else if (!just_created && child_flag_changed && new_is_explicit_child) + { + IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window); + for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++) + g.WindowsFocusOrder[n]->FocusOrder--; + g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder); + window->FocusOrder = -1; + } + window->IsExplicitChild = new_is_explicit_child; +} + +void ImGui::BringWindowToFocusFront(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(window == window->RootWindow); + + const int cur_order = window->FocusOrder; + IM_ASSERT(g.WindowsFocusOrder[cur_order] == window); + if (g.WindowsFocusOrder.back() == window) + return; + + const int new_order = g.WindowsFocusOrder.Size - 1; + for (int n = cur_order; n < new_order; n++) + { + g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1]; + g.WindowsFocusOrder[n]->FocusOrder--; + IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n); + } + g.WindowsFocusOrder[new_order] = window; + window->FocusOrder = (short)new_order; +} + +// Note technically focus related but rather adjacent and close to BringWindowToFocusFront() +void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* current_front_window = g.Windows.back(); + if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better) + return; + for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window + if (g.Windows[i] == window) + { + memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*)); + g.Windows[g.Windows.Size - 1] = window; + break; + } +} + +void ImGui::BringWindowToDisplayBack(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.Windows[0] == window) + return; + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i] == window) + { + memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*)); + g.Windows[0] = window; + break; + } +} + +void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window) +{ + IM_ASSERT(window != NULL && behind_window != NULL); + ImGuiContext& g = *GImGui; + window = window->RootWindow; + behind_window = behind_window->RootWindow; + int pos_wnd = FindWindowDisplayIndex(window); + int pos_beh = FindWindowDisplayIndex(behind_window); + if (pos_wnd < pos_beh) + { + size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*); + memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes); + g.Windows[pos_beh - 1] = window; + } + else + { + size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*); + memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes); + g.Windows[pos_beh] = window; + } +} + +int ImGui::FindWindowDisplayIndex(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + return g.Windows.index_from_ptr(g.Windows.find(window)); +} + +// Moving window to front of display and set focus (which happens to be back of our sorted list) +void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags) +{ + ImGuiContext& g = *GImGui; + + // Modal check? + if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case. + if (ImGuiWindow* blocking_modal = FindBlockingModal(window)) + { + // This block would typically be reached in two situations: + // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag. + // - User clicking on void or anything behind a modal while a modal is open (window == NULL) + IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "", blocking_modal->Name); + if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) + BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?) + ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals + return; + } + + // Find last focused child (if any) and focus it instead. + if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL) + window = NavRestoreLastChildNavWindow(window); + + // Apply focus + if (g.NavWindow != window) + { + SetNavWindow(window); + if (window && g.NavHighlightItemUnderNav) + g.NavMousePosDirty = true; + g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId + g.NavLayer = ImGuiNavLayer_Main; + SetNavFocusScope(window ? window->NavRootFocusScopeId : 0); + g.NavIdIsAlive = false; + g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; + + // Close popups if any + ClosePopupsOverWindow(window, false); + } + + // Move the root window to the top of the pile + IM_ASSERT(window == NULL || window->RootWindow != NULL); + ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop + ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; + + // Steal active widgets. Some of the cases it triggers includes: + // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. + // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) + if (!g.ActiveIdNoClearOnFocusLoss) + ClearActiveID(); + + // Passing NULL allow to disable keyboard focus + if (!window) + return; + + // Bring to front + BringWindowToFocusFront(focus_front_window); + if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) + BringWindowToDisplayFront(display_front_window); +} + +void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags) +{ + ImGuiContext& g = *GImGui; + IM_UNUSED(filter_viewport); // Unused in master branch. + int start_idx = g.WindowsFocusOrder.Size - 1; + if (under_this_window != NULL) + { + // Aim at root window behind us, if we are in a child window that's our own root (see #4640) + int offset = -1; + while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow) + { + under_this_window = under_this_window->ParentWindow; + offset = 0; + } + start_idx = FindWindowFocusIndex(under_this_window) + offset; + } + for (int i = start_idx; i >= 0; i--) + { + // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user. + ImGuiWindow* window = g.WindowsFocusOrder[i]; + if (window == ignore_window || !window->WasActive) + continue; + if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) + { + FocusWindow(window, flags); + return; + } + } + FocusWindow(NULL, flags); +} + //----------------------------------------------------------------------------- // [SECTION] KEYBOARD/GAMEPAD NAVIGATION //----------------------------------------------------------------------------- @@ -13504,16 +13536,6 @@ static void ImGui::NavUpdateCreateWrappingRequest() NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags); } -static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) -{ - ImGuiContext& g = *GImGui; - IM_UNUSED(g); - int order = window->FocusOrder; - IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking) - IM_ASSERT(g.WindowsFocusOrder[order] == window); - return order; -} - // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. // If you want a window to never be focused, you may use the e.g. NoInputs flag. From 1c67a3412e1540700494f4c0d76d389d0232606f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Jan 2025 14:55:51 +0100 Subject: [PATCH 0587/2359] BeginChild: also caller to manually set ImGuiNextWindowDataFlags_HasChildFlags / ChildFlags. (#8280) --- imgui.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5f898a389..ededc3d00 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6049,9 +6049,12 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I } SetNextWindowSize(size); - // Forward child flags + // Forward child flags (we allow prior settings to merge but it'll only work for adding flags) + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) + g.NextWindowData.ChildFlags |= child_flags; + else + g.NextWindowData.ChildFlags = child_flags; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags; - g.NextWindowData.ChildFlags = child_flags; // 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. From 90094a871a5379d78a1b38b8364e0bd2ee65f796 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Jan 2025 18:13:53 +0100 Subject: [PATCH 0588/2359] Fonts: Fixed miscalculation of Ellipsis ("...") character width when automatically created from a single comma character. --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a24d6ea4e..89c4140b5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,6 +63,8 @@ Other changes: windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) - Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) +- Fonts: Fixed miscalculation of Ellipsis ("...") character width when automatically + created from a single comma character, affecting some fonts/settings (not all). - Demo: Added label edition to Property Editor demo + fix an ID issue. (#8266) [@moritz-h] - Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 42bfb7162..9e155f592 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3799,8 +3799,8 @@ void ImFont::BuildLookupTable() const ImFontGlyph* glyph = FindGlyph(dot_char); EllipsisChar = dot_char; EllipsisCharCount = 3; - EllipsisCharStep = (glyph->X1 - glyph->X0) + 1.0f; - EllipsisWidth = EllipsisCharStep * 3.0f - 1.0f; + EllipsisCharStep = (float)(int)(glyph->X1 - glyph->X0) + 1.0f; + EllipsisWidth = glyph->X0 + EllipsisCharStep * 3.0f - 1.0f; } } From c7983115e9f7bdee8bc76ec17612ef1a45bdc05e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Jan 2025 18:27:01 +0100 Subject: [PATCH 0589/2359] Fonts: Further tweaks for Ellipsis ("...") character width when automatically created from a single comma character: use AdvanceX as min. --- imgui_draw.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 9e155f592..8baaf8b11 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3796,11 +3796,11 @@ void ImFont::BuildLookupTable() } else if (dot_char != 0) { - const ImFontGlyph* glyph = FindGlyph(dot_char); + const ImFontGlyph* dot_glyph = FindGlyph(dot_char); EllipsisChar = dot_char; EllipsisCharCount = 3; - EllipsisCharStep = (float)(int)(glyph->X1 - glyph->X0) + 1.0f; - EllipsisWidth = glyph->X0 + EllipsisCharStep * 3.0f - 1.0f; + EllipsisCharStep = (float)(int)(dot_glyph->X1 - dot_glyph->X0) + 1.0f; + EllipsisWidth = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + EllipsisCharStep * 3.0f - 1.0f); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. } } From 940d9540f3f7efc9e79fdcba859a24162b383a6f Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 9 Jan 2025 15:28:48 +0100 Subject: [PATCH 0590/2359] Fixed MinGW builds uses UTF-8 friendly _wfopen(). (#8300) Amend bbd0a37bd, 40db2ca09 --- docs/CHANGELOG.txt | 1 + imgui.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 89c4140b5..00df8a746 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,7 @@ Other changes: created from a single comma character, affecting some fonts/settings (not all). - Demo: Added label edition to Property Editor demo + fix an ID issue. (#8266) [@moritz-h] - Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] +- Misc: Fixed MinGW builds uses UTF-8 friendly _wfopen(). (#8300) - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). [@Helodity] - Backends: Metal: Fixed leaks when using metal-cpp. (#8276, #8166) [@selimsandal] diff --git a/imgui.cpp b/imgui.cpp index ededc3d00..bad766f03 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2282,7 +2282,7 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed) ImFileHandle ImFileOpen(const char* filename, const char* mode) { -#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__) +#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); From 8bbccf7a9779c45c15e201c18eb3971d40fc0e76 Mon Sep 17 00:00:00 2001 From: Delta <98419797+DeltaW0x@users.noreply.github.com> Date: Thu, 9 Jan 2025 15:37:13 +0100 Subject: [PATCH 0591/2359] Backends: SDLGPU3: Added sdl_gpu backend. (#8163, #7998, #7988) +Squashed: Optimized shader source code encoding by ocornut (#8163, #7998, #7988) (squashed to avoid storing both in git history, 130 KB->62 KB) --- backends/imgui_impl_sdlgpu3.cpp | 630 ++++++++++++++++++ backends/imgui_impl_sdlgpu3.h | 46 ++ backends/imgui_impl_sdlgpu3_shaders.h | 372 +++++++++++ backends/sdlgpu3/build_instructions.txt | 36 + backends/sdlgpu3/shader.frag | 14 + backends/sdlgpu3/shader.vert | 22 + examples/example_sdl3_sdlgpu3/Makefile | 73 ++ examples/example_sdl3_sdlgpu3/build_win64.bat | 14 + .../example_sdl3_sdlgpu3.vcxproj | 189 ++++++ .../example_sdl3_sdlgpu3.vcxproj.filters | 60 ++ examples/example_sdl3_sdlgpu3/main.cpp | 210 ++++++ examples/imgui_examples.sln | 10 + 12 files changed, 1676 insertions(+) create mode 100644 backends/imgui_impl_sdlgpu3.cpp create mode 100644 backends/imgui_impl_sdlgpu3.h create mode 100644 backends/imgui_impl_sdlgpu3_shaders.h create mode 100644 backends/sdlgpu3/build_instructions.txt create mode 100644 backends/sdlgpu3/shader.frag create mode 100644 backends/sdlgpu3/shader.vert create mode 100644 examples/example_sdl3_sdlgpu3/Makefile create mode 100644 examples/example_sdl3_sdlgpu3/build_win64.bat create mode 100644 examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj create mode 100644 examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj.filters create mode 100644 examples/example_sdl3_sdlgpu3/main.cpp diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp new file mode 100644 index 000000000..31e899b77 --- /dev/null +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -0,0 +1,630 @@ +// dear imgui: Renderer Backend for SDL_Gpu +// This needs to be used along with the SDL3 Platform Backend + +// Implemented features: +// [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification. +// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. +// - Unline other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. +// Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. + +// CHANGELOG +// 2024-11-18: SDL_Gpu: Added the SDL_Gpu backend. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_sdlgpu3.h" +#include "imgui_impl_sdlgpu3_shaders.h" + +// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU_RenderDrawData() +struct ImGui_ImplSDLGPU_FrameData +{ + SDL_GPUBuffer* VertexBuffer = nullptr; + SDL_GPUBuffer* IndexBuffer = nullptr; + uint32_t VertexBufferSize = 0; + uint32_t IndexBufferSize = 0; +}; + +// SDL_Gpu Data +struct ImGui_ImplSDLGPU_Data +{ + ImGui_ImplSDLGPU_InitInfo GPUInitInfo; + + // Graphics pipeline & shaders + SDL_GPUShader* VertexShader = nullptr; + SDL_GPUShader* FragmentShader = nullptr; + SDL_GPUGraphicsPipeline* Pipeline = nullptr; + + // Font data + SDL_GPUSampler* FontSampler = nullptr; + SDL_GPUTexture* FontTexture = nullptr; + SDL_GPUTextureSamplerBinding FontBinding = {nullptr,nullptr}; + + // Frame data for main window + ImGui_ImplSDLGPU_FrameData MainWindowFrameData; +}; + +// Forward Declarations +static bool ImGui_ImplSDLGPU_CreateDeviceObjects(); +static void ImGui_ImplSDLGPU_DestroyDeviceObjects(); +static void ImGui_ImplSDLGPU_DestroyFrameData(); + +//----------------------------------------------------------------------------- +// FUNCTIONS +//----------------------------------------------------------------------------- + +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +// FIXME: multi-context support has never been tested. +static ImGui_ImplSDLGPU_Data* ImGui_ImplSDLGPU_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; +} + +static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer,uint32_t* old_size, uint32_t new_size,SDL_GPUBufferUsageFlags usage) +{ + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + + SDL_WaitForGPUIdle(v->GpuDevice); + SDL_ReleaseGPUBuffer(v->GpuDevice, *buffer); + + SDL_GPUBufferCreateInfo buffer_info = {}; + buffer_info.usage = usage; + buffer_info.size = new_size; + buffer_info.props = 0; + *buffer = SDL_CreateGPUBuffer(v->GpuDevice,&buffer_info); + *old_size = new_size; + IM_ASSERT(*buffer != nullptr && "Failed to create GPU Buffer, call SDL_GetError() for more information"); +} + +static void ImGui_ImplSDLGPU_SetupRenderState(ImDrawData* draw_data,SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer,SDL_GPURenderPass * render_pass, ImGui_ImplSDLGPU_FrameData* fd, uint32_t fb_width, uint32_t fb_height) +{ + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + + // Bind graphics pipeline: + { + SDL_BindGPUGraphicsPipeline(render_pass,pipeline); + } + + // Bind Vertex And Index Buffers: + if (draw_data->TotalVtxCount > 0) + { + SDL_GPUBufferBinding vertex_buffer_binding = {}; + vertex_buffer_binding.buffer = fd->VertexBuffer; + vertex_buffer_binding.offset = 0; + SDL_GPUBufferBinding index_buffer_binding = {}; + index_buffer_binding.buffer = fd->IndexBuffer; + index_buffer_binding.offset = 0; + SDL_BindGPUVertexBuffers(render_pass,0,&vertex_buffer_binding,1); + SDL_BindGPUIndexBuffer(render_pass,&index_buffer_binding,sizeof(ImDrawIdx) == 2 ? SDL_GPU_INDEXELEMENTSIZE_16BIT : SDL_GPU_INDEXELEMENTSIZE_32BIT); + } + + // Setup viewport: + { + SDL_GPUViewport viewport = {}; + viewport.x = 0; + viewport.y = 0; + viewport.w = fb_width; + viewport.h = fb_height; + viewport.min_depth = 0.0f; + viewport.min_depth = 1.0f; + SDL_SetGPUViewport(render_pass,&viewport); + } + + // Setup scale and translation: + // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. + { + struct UBO{ + float scale[2]; + float translation[2]; + } ubo; + ubo.scale[0] = 2.0f / draw_data->DisplaySize.x; + ubo.scale[1] = 2.0f / draw_data->DisplaySize.y; + ubo.translation[0] = -1.0f - draw_data->DisplayPos.x * ubo.scale[0]; + ubo.translation[1] = -1.0f - draw_data->DisplayPos.y * ubo.scale[1]; + SDL_PushGPUVertexUniformData(command_buffer,0,&ubo,sizeof(UBO)); + } +} + +// SDL_GPU doesn't allow copy passes to occur while a render or compute pass is bound +// The only way to allow a user to supply their own RenderPass (to render to a texture instead of the window for example), +// is to split the upload part of ImGui_ImplSDLGPU_RenderDrawData to another function that needs to be called by the user before rendering +void Imgui_ImplSDLGPU_PrepareDrawData(ImDrawData* draw_data,SDL_GPUCommandBuffer* command_buffer) +{ + // 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); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if(fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount <= 0) + return; + + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU_FrameData* fd = &bd->MainWindowFrameData; + + uint32_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); + uint32_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); + + if(fd->VertexBuffer == nullptr || fd->VertexBufferSize < vertex_size) + CreateOrResizeBuffer(&fd->VertexBuffer,&fd->VertexBufferSize,vertex_size, SDL_GPU_BUFFERUSAGE_VERTEX); + if (fd->IndexBuffer == nullptr || fd->IndexBufferSize < index_size) + CreateOrResizeBuffer(&fd->IndexBuffer,&fd->IndexBufferSize,index_size, SDL_GPU_BUFFERUSAGE_INDEX); + + SDL_GPUTransferBufferCreateInfo vertex_transferbuffer_info = {}; + vertex_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; + vertex_transferbuffer_info.size = vertex_size; + SDL_GPUTransferBufferCreateInfo index_transferbuffer_info = {}; + index_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; + index_transferbuffer_info.size = index_size; + + SDL_GPUTransferBuffer* vertex_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice,&vertex_transferbuffer_info); + IM_ASSERT(vertex_transferbuffer != nullptr && "Failed to create the vertex transfer buffer, call SDL_GetError() for more information"); + SDL_GPUTransferBuffer* index_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice,&index_transferbuffer_info); + IM_ASSERT(index_transferbuffer != nullptr && "Failed to create the index transfer buffer, call SDL_GetError() for more information"); + + ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->GpuDevice,vertex_transferbuffer,true); + ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->GpuDevice,index_transferbuffer,true); + for(int n = 0; n < draw_data->CmdListsCount; n++){ + const ImDrawList* draw_list = draw_data->CmdLists[n]; + memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); + memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + vtx_dst += draw_list->VtxBuffer.Size; + idx_dst += draw_list->IdxBuffer.Size; + } + SDL_UnmapGPUTransferBuffer(v->GpuDevice,vertex_transferbuffer); + SDL_UnmapGPUTransferBuffer(v->GpuDevice,index_transferbuffer); + + SDL_GPUTransferBufferLocation vertex_buffer_location = {}; + vertex_buffer_location.offset = 0; + vertex_buffer_location.transfer_buffer = vertex_transferbuffer; + SDL_GPUTransferBufferLocation index_buffer_location = {}; + index_buffer_location.offset = 0; + index_buffer_location.transfer_buffer = index_transferbuffer; + + SDL_GPUBufferRegion vertex_buffer_region = {}; + vertex_buffer_region.buffer = fd->VertexBuffer; + vertex_buffer_region.offset = 0; + vertex_buffer_region.size = vertex_size; + SDL_GPUBufferRegion index_buffer_region = {}; + index_buffer_region.buffer = fd->IndexBuffer; + index_buffer_region.offset = 0; + index_buffer_region.size = index_size; + + SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(command_buffer); + SDL_UploadToGPUBuffer(copy_pass,&vertex_buffer_location,&vertex_buffer_region,true); + SDL_UploadToGPUBuffer(copy_pass,&index_buffer_location,&index_buffer_region,true); + SDL_EndGPUCopyPass(copy_pass); + SDL_ReleaseGPUTransferBuffer(v->GpuDevice, index_transferbuffer); + SDL_ReleaseGPUTransferBuffer(v->GpuDevice, vertex_transferbuffer); +} + +void ImGui_ImplSDLGPU_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline) +{ + // 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); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if(fb_width <= 0 || fb_height <= 0) + return; + + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_FrameData* fd = &bd->MainWindowFrameData; + + if (pipeline == nullptr) + pipeline = bd->Pipeline; + + ImGui_ImplSDLGPU_SetupRenderState(draw_data,pipeline,command_buffer,render_pass,fd,fb_width,fb_height); + + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + + // Render command lists + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_vtx_offset = 0; + int global_idx_offset = 0; + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* draw_list = draw_data->CmdLists[n]; + for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback != nullptr) + { + pcmd->UserCallback(draw_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + + // Clamp to viewport as SDL_SetGPUScissor() won't accept values that are off bounds + if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } + if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } + if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } + if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + // Apply scissor/clipping rectangle + SDL_Rect scissor_rect = {}; + scissor_rect.x = (int)clip_min.x; + scissor_rect.y = (int)clip_min.y; + scissor_rect.w = (int)(clip_max.x - clip_min.x); + scissor_rect.h = (int)(clip_max.y - clip_min.y); + SDL_SetGPUScissor(render_pass,&scissor_rect); + + // Bind DescriptorSet with font or user texture + SDL_BindGPUFragmentSamplers(render_pass,0,(SDL_GPUTextureSamplerBinding*)pcmd->GetTexID(),1); + + // Draw + SDL_DrawGPUIndexedPrimitives(render_pass,pcmd->ElemCount,1,pcmd->IdxOffset + global_idx_offset,pcmd->VtxOffset + global_vtx_offset,0); + } + } + global_idx_offset += draw_list->IdxBuffer.Size; + global_vtx_offset += draw_list->VtxBuffer.Size; + } + + // Note: at this point both SDL_SetGPUViewport() and SDL_SetGPUScissor() have been called. + // Our last values will leak into user/application rendering if you forgot to call SDL_SetGPUViewport() and SDL_SetGPUScissor() yourself to explicitly set that state + // In theory we should aim to backup/restore those values but I am not sure this is possible. + // We perform a call to SDL_SetGPUScissor() to set back a full viewport which is likely to fix things for 99% users but technically this is not perfect. (See github #4644) + SDL_Rect scissor_rect {0,0,fb_width,fb_height}; + SDL_SetGPUScissor(render_pass,&scissor_rect); +} + +bool ImGui_ImplSDLGPU_CreateFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + + // Destroy existing texture (if any) + if (bd->FontTexture) + { + SDL_WaitForGPUIdle(v->GpuDevice); + ImGui_ImplSDLGPU_DestroyFontsTexture(); + } + + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + uint32_t upload_size = width * height * 4 * sizeof(char); + + // Create the Image: + { + SDL_GPUTextureCreateInfo texture_info = {}; + texture_info.type = SDL_GPU_TEXTURETYPE_2D; + texture_info.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + texture_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER; + texture_info.width = width; + texture_info.height = height; + texture_info.layer_count_or_depth = 1; + texture_info.num_levels = 1; + texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1; + + bd->FontTexture = SDL_CreateGPUTexture(v->GpuDevice,&texture_info); + IM_ASSERT(bd->FontTexture && "Failed to create font texture, call SDL_GetError() for more info"); + } + + // Assign the texture to the TextureSamplerBinding + bd->FontBinding.texture = bd->FontTexture; + + // Create all the upload structures and upload: + { + SDL_GPUTransferBufferCreateInfo font_transferbuffer_info = {}; + font_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; + font_transferbuffer_info.size = upload_size; + + SDL_GPUTransferBuffer* font_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice,&font_transferbuffer_info); + IM_ASSERT(font_transferbuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information"); + + void* texture_ptr = SDL_MapGPUTransferBuffer(v->GpuDevice,font_transferbuffer,false); + memcpy(texture_ptr,pixels,upload_size); + SDL_UnmapGPUTransferBuffer(v->GpuDevice,font_transferbuffer); + + SDL_GPUTextureTransferInfo font_transfer_info = {}; + font_transfer_info.offset = 0; + font_transfer_info.transfer_buffer = font_transferbuffer; + + SDL_GPUTextureRegion font_texture_region = {}; + font_texture_region.texture = bd->FontTexture; + font_texture_region.w = width; + font_texture_region.h = height; + font_texture_region.d = 1; + + SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->GpuDevice); + SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(cmd); + SDL_UploadToGPUTexture(copy_pass,&font_transfer_info,&font_texture_region,false); + SDL_EndGPUCopyPass(copy_pass); + SDL_SubmitGPUCommandBuffer(cmd); + SDL_ReleaseGPUTransferBuffer(v->GpuDevice, font_transferbuffer); + } + + // Store our identifier + io.Fonts->SetTexID((ImTextureID)&bd->FontBinding); + + return true; +} + +// You probably never need to call this, as it is called by ImGui_ImplSDLGPU_CreateFontsTexture() and ImGui_ImplSDLGPU_Shutdown(). +void ImGui_ImplSDLGPU_DestroyFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + + if(bd->FontTexture) + { + SDL_ReleaseGPUTexture(v->GpuDevice,bd->FontTexture); + bd->FontBinding.texture = nullptr; + bd->FontTexture = nullptr; + } + + io.Fonts->SetTexID(0); +} + +static void Imgui_ImplSDLGPU_CreateShaders() +{ + // Create the shader modules + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + + const char* driver = SDL_GetGPUDeviceDriver(v->GpuDevice); + + SDL_GPUShaderCreateInfo vertex_shader_info = {}; + vertex_shader_info.entrypoint = "main"; + vertex_shader_info.stage = SDL_GPU_SHADERSTAGE_VERTEX; + vertex_shader_info.num_uniform_buffers = 1; + vertex_shader_info.num_storage_buffers = 0; + vertex_shader_info.num_storage_textures = 0; + vertex_shader_info.num_samplers = 0; + + SDL_GPUShaderCreateInfo fragment_shader_info = {}; + fragment_shader_info.entrypoint = "main"; + fragment_shader_info.stage = SDL_GPU_SHADERSTAGE_FRAGMENT; + fragment_shader_info.num_samplers = 1; + fragment_shader_info.num_storage_buffers = 0; + fragment_shader_info.num_storage_textures = 0; + fragment_shader_info.num_uniform_buffers = 0; + + if(strcmp(driver,"vulkan") == 0) + { + vertex_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV; + vertex_shader_info.code = spirv_vertex; + vertex_shader_info.code_size = sizeof(spirv_vertex); + + fragment_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV; + fragment_shader_info.code = spirv_fragment; + fragment_shader_info.code_size = sizeof(spirv_fragment); + } + else if (strcmp(driver,"direct3d12") == 0) + { + vertex_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC; + vertex_shader_info.code = dxbc_vertex; + vertex_shader_info.code_size = sizeof(dxbc_vertex); + + fragment_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC; + fragment_shader_info.code = dxbc_fragment; + fragment_shader_info.code_size = sizeof(dxbc_fragment); + } +#ifdef __APPLE__ + else + { + vertex_shader_info.entrypoint = "main0"; + vertex_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; + vertex_shader_info.code = metallib_vertex; + vertex_shader_info.code_size = sizeof(metallib_vertex); + + fragment_shader_info.entrypoint = "main0"; + fragment_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; + fragment_shader_info.code = metallib_fragment; + fragment_shader_info.code_size = sizeof(metallib_fragment); + } +#endif + bd->VertexShader = SDL_CreateGPUShader(v->GpuDevice,&vertex_shader_info); + bd->FragmentShader = SDL_CreateGPUShader(v->GpuDevice,&fragment_shader_info); + + IM_ASSERT(bd->VertexShader != nullptr && "Failed to create vertex shader, call SDL_GetError() for more information"); + IM_ASSERT(bd->FragmentShader != nullptr && "Failed to create fragment shader, call SDL_GetError() for more information"); +} + +static void ImGui_ImplSDLGPU_CreateGraphicsPipeline() +{ + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + Imgui_ImplSDLGPU_CreateShaders(); + + SDL_GPUVertexBufferDescription vertex_buffer_desc[1]; + vertex_buffer_desc[0].slot = 0; + vertex_buffer_desc[0].input_rate = SDL_GPU_VERTEXINPUTRATE_VERTEX; + vertex_buffer_desc[0].instance_step_rate = 0; + vertex_buffer_desc[0].pitch = sizeof(ImDrawVert); + + SDL_GPUVertexAttribute vertex_attributes[3]; + vertex_attributes[0].buffer_slot = 0; + vertex_attributes[0].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2; + vertex_attributes[0].location = 0; + vertex_attributes[0].offset = offsetof(ImDrawVert,pos); + + vertex_attributes[1].buffer_slot = 0; + vertex_attributes[1].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2; + vertex_attributes[1].location = 1; + vertex_attributes[1].offset = offsetof(ImDrawVert, uv); + + vertex_attributes[2].buffer_slot = 0; + vertex_attributes[2].format = SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM; + vertex_attributes[2].location = 2; + vertex_attributes[2].offset = offsetof(ImDrawVert, col); + + SDL_GPUVertexInputState vertex_input_state = {}; + vertex_input_state.num_vertex_attributes = 3; + vertex_input_state.vertex_attributes = vertex_attributes; + vertex_input_state.num_vertex_buffers = 1; + vertex_input_state.vertex_buffer_descriptions = vertex_buffer_desc; + + SDL_GPURasterizerState rasterizer_state = {}; + rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL; + rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE; + rasterizer_state.front_face = SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; + rasterizer_state.enable_depth_bias = false; + rasterizer_state.enable_depth_clip = false; + + SDL_GPUMultisampleState multisample_state = {}; + multisample_state.sample_count = v->MSAASamples; + multisample_state.enable_mask = false; + + SDL_GPUDepthStencilState depth_stencil_state = {}; + depth_stencil_state.enable_depth_test = false; + depth_stencil_state.enable_depth_write = false; + depth_stencil_state.enable_stencil_test = false; + + SDL_GPUColorTargetBlendState blend_state = {}; + blend_state.enable_blend = true; + blend_state.src_color_blendfactor = SDL_GPU_BLENDFACTOR_SRC_ALPHA; + blend_state.dst_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; + blend_state.color_blend_op = SDL_GPU_BLENDOP_ADD; + blend_state.src_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE; + blend_state.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; + blend_state.alpha_blend_op = SDL_GPU_BLENDOP_ADD; + blend_state.color_write_mask = SDL_GPU_COLORCOMPONENT_R | SDL_GPU_COLORCOMPONENT_G | SDL_GPU_COLORCOMPONENT_B | SDL_GPU_COLORCOMPONENT_A; + + SDL_GPUColorTargetDescription color_target_desc[1]; + color_target_desc[0].format = v->ColorTargetFormat; + color_target_desc[0].blend_state = blend_state; + + SDL_GPUGraphicsPipelineTargetInfo target_info = {}; + target_info.num_color_targets = 1; + target_info.color_target_descriptions = color_target_desc; + target_info.has_depth_stencil_target = false; + + SDL_GPUGraphicsPipelineCreateInfo pipeline_info = {}; + pipeline_info.vertex_shader = bd->VertexShader; + pipeline_info.fragment_shader = bd->FragmentShader; + pipeline_info.vertex_input_state = vertex_input_state; + pipeline_info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + pipeline_info.rasterizer_state = rasterizer_state; + pipeline_info.multisample_state = multisample_state; + pipeline_info.depth_stencil_state = depth_stencil_state; + pipeline_info.target_info = target_info; + + bd->Pipeline = SDL_CreateGPUGraphicsPipeline(v->GpuDevice,&pipeline_info); + IM_ASSERT(bd->Pipeline != nullptr && "Failed to create graphics pipeline, call SDL_GetError() for more information"); +} + +bool ImGui_ImplSDLGPU_CreateDeviceObjects() +{ + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + + if (!bd->FontSampler) + { + // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. + SDL_GPUSamplerCreateInfo sampler_info = {}; + sampler_info.min_filter = SDL_GPU_FILTER_LINEAR; + sampler_info.mag_filter = SDL_GPU_FILTER_LINEAR; + sampler_info.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR; + sampler_info.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + sampler_info.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + sampler_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + sampler_info.mip_lod_bias = 0.0f; + sampler_info.min_lod = -1000.0f; + sampler_info.max_lod = 1000.0f; + sampler_info.enable_anisotropy = true; + sampler_info.max_anisotropy = 1.0f; + sampler_info.enable_compare = false; + + bd->FontSampler = SDL_CreateGPUSampler(v->GpuDevice,&sampler_info); + bd->FontBinding.sampler = bd->FontSampler; + IM_ASSERT(bd->FontSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information"); + } + + ImGui_ImplSDLGPU_CreateGraphicsPipeline(); + + return true; +} + +void ImGui_ImplSDLGPU_DestroyFrameData() +{ + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + + SDL_ReleaseGPUBuffer(v->GpuDevice,bd->MainWindowFrameData.VertexBuffer); + SDL_ReleaseGPUBuffer(v->GpuDevice,bd->MainWindowFrameData.IndexBuffer); + bd->MainWindowFrameData.VertexBuffer = nullptr; + bd->MainWindowFrameData.IndexBuffer = nullptr; + bd->MainWindowFrameData.VertexBufferSize = 0; + bd->MainWindowFrameData.IndexBufferSize = 0; +} + +void ImGui_ImplSDLGPU_DestroyDeviceObjects() +{ + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + + ImGui_ImplSDLGPU_DestroyFrameData(); + ImGui_ImplSDLGPU_DestroyFontsTexture(); + + if(bd->VertexShader) { SDL_ReleaseGPUShader(v->GpuDevice,bd->VertexShader); bd->VertexShader = nullptr;} + if(bd->FragmentShader) { SDL_ReleaseGPUShader(v->GpuDevice,bd->FragmentShader); bd->FragmentShader = nullptr;} + if(bd->FontSampler) { SDL_ReleaseGPUSampler(v->GpuDevice, bd->FontSampler); bd->FontSampler = nullptr;} + if(bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->GpuDevice,bd->Pipeline); bd->Pipeline = nullptr;} +} + +bool ImGui_ImplSDLGPU_Init(ImGui_ImplSDLGPU_InitInfo* info) +{ + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + + // Setup backend capabilities flags + ImGui_ImplSDLGPU_Data* bd = IM_NEW(ImGui_ImplSDLGPU_Data)(); + io.BackendRendererUserData = (void*)bd; + io.BackendRendererName = "imgui_impl_sdlgpu"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + + IM_ASSERT(info->GpuDevice != nullptr); + IM_ASSERT(info->ColorTargetFormat != SDL_GPU_TEXTUREFORMAT_INVALID); + + bd->GPUInitInfo = *info; + + ImGui_ImplSDLGPU_CreateDeviceObjects(); + + return true; +} + +void ImGui_ImplSDLGPU_Shutdown() +{ + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + ImGui_ImplSDLGPU_DestroyDeviceObjects(); + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + IM_DELETE(bd); +} + +void ImGui_ImplSDLGPU_NewFrame() +{ + ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplVulkan_Init()?"); + + if(!bd->FontTexture) + ImGui_ImplSDLGPU_CreateFontsTexture(); +} + +#endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h new file mode 100644 index 000000000..18d3001e4 --- /dev/null +++ b/backends/imgui_impl_sdlgpu3.h @@ -0,0 +1,46 @@ +// dear imgui: Renderer Backend for SDL_Gpu +// This needs to be used along with the SDL3 Platform Backend + +// Implemented features: +// [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification. +// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. +// - Unline other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. +// Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE +#include + +// Initialization data, for ImGui_ImplSDLGPU_Init() +// - Remember to set ColorTargetFormat to the correct format. If you're rendering to the swapchain, call SDL_GetGPUSwapchainTextureFormat to query the right value +struct ImGui_ImplSDLGPU_InitInfo +{ + SDL_GPUDevice* GpuDevice = nullptr; + SDL_GPUTextureFormat ColorTargetFormat = SDL_GPU_TEXTUREFORMAT_INVALID; + SDL_GPUSampleCount MSAASamples = SDL_GPU_SAMPLECOUNT_1; +}; + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplSDLGPU_Init(ImGui_ImplSDLGPU_InitInfo* info); +IMGUI_IMPL_API void ImGui_ImplSDLGPU_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDLGPU_NewFrame(); +IMGUI_IMPL_API void Imgui_ImplSDLGPU_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer); +IMGUI_IMPL_API void ImGui_ImplSDLGPU_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline = nullptr); +IMGUI_IMPL_API bool ImGui_ImplSDLGPU_CreateFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplSDLGPU_DestroyFontsTexture(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlgpu3_shaders.h b/backends/imgui_impl_sdlgpu3_shaders.h new file mode 100644 index 000000000..f792aa6ab --- /dev/null +++ b/backends/imgui_impl_sdlgpu3_shaders.h @@ -0,0 +1,372 @@ +#pragma once +#ifndef IMGUI_DISABLE +#include + +// Data exported using +// misc/fonts/binary_to_compressed_c.exe -u8 -nocompress filename symbolname >filename.h +// With some manual pasting. + +// Check sdlgpu3/ folder for the shaders' source code and instruction on how to build them +const uint8_t spirv_vertex[1732] = { + 3,2,35,7,0,0,1,0,11,0,13,0,55,0,0,0,0,0,0,0,17,0,2,0,1,0,0,0,11,0,6,0,1,0,0,0,71,76,83,76,46,115,116,100,46,52,53,48,0,0,0,0,14,0,3,0,0,0,0,0,1,0,0,0,15,0,10,0,0,0,0,0,4,0,0,0,109, + 97,105,110,0,0,0,0,11,0,0,0,15,0,0,0,21,0,0,0,30,0,0,0,31,0,0,0,3,0,3,0,2,0,0,0,194,1,0,0,4,0,10,0,71,76,95,71,79,79,71,76,69,95,99,112,112,95,115,116,121,108,101,95,108,105,110,101, + 95,100,105,114,101,99,116,105,118,101,0,0,4,0,8,0,71,76,95,71,79,79,71,76,69,95,105,110,99,108,117,100,101,95,100,105,114,101,99,116,105,118,101,0,5,0,4,0,4,0,0,0,109,97,105,110,0, + 0,0,0,5,0,3,0,9,0,0,0,0,0,0,0,6,0,5,0,9,0,0,0,0,0,0,0,67,111,108,111,114,0,0,0,6,0,4,0,9,0,0,0,1,0,0,0,85,86,0,0,5,0,3,0,11,0,0,0,79,117,116,0,5,0,4,0,15,0,0,0,97,67,111,108,111,114, + 0,0,5,0,3,0,21,0,0,0,97,85,86,0,5,0,6,0,28,0,0,0,103,108,95,80,101,114,86,101,114,116,101,120,0,0,0,0,6,0,6,0,28,0,0,0,0,0,0,0,103,108,95,80,111,115,105,116,105,111,110,0,6,0,7,0,28, + 0,0,0,1,0,0,0,103,108,95,80,111,105,110,116,83,105,122,101,0,0,0,0,6,0,7,0,28,0,0,0,2,0,0,0,103,108,95,67,108,105,112,68,105,115,116,97,110,99,101,0,6,0,7,0,28,0,0,0,3,0,0,0,103,108, + 95,67,117,108,108,68,105,115,116,97,110,99,101,0,5,0,3,0,30,0,0,0,0,0,0,0,5,0,4,0,31,0,0,0,97,80,111,115,0,0,0,0,5,0,6,0,33,0,0,0,117,80,117,115,104,67,111,110,115,116,97,110,116,0, + 0,0,6,0,5,0,33,0,0,0,0,0,0,0,117,83,99,97,108,101,0,0,6,0,6,0,33,0,0,0,1,0,0,0,117,84,114,97,110,115,108,97,116,101,0,0,5,0,3,0,35,0,0,0,112,99,0,0,71,0,4,0,11,0,0,0,30,0,0,0,0,0,0, + 0,71,0,4,0,15,0,0,0,30,0,0,0,2,0,0,0,71,0,4,0,21,0,0,0,30,0,0,0,1,0,0,0,71,0,3,0,28,0,0,0,2,0,0,0,72,0,5,0,28,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,72,0,5,0,28,0,0,0,1,0,0,0,11,0,0,0,1,0, + 0,0,72,0,5,0,28,0,0,0,2,0,0,0,11,0,0,0,3,0,0,0,72,0,5,0,28,0,0,0,3,0,0,0,11,0,0,0,4,0,0,0,71,0,4,0,31,0,0,0,30,0,0,0,0,0,0,0,71,0,3,0,33,0,0,0,2,0,0,0,72,0,5,0,33,0,0,0,0,0,0,0,35, + 0,0,0,0,0,0,0,72,0,5,0,33,0,0,0,1,0,0,0,35,0,0,0,8,0,0,0,71,0,4,0,35,0,0,0,33,0,0,0,0,0,0,0,71,0,4,0,35,0,0,0,34,0,0,0,1,0,0,0,19,0,2,0,2,0,0,0,33,0,3,0,3,0,0,0,2,0,0,0,22,0,3,0,6, + 0,0,0,32,0,0,0,23,0,4,0,7,0,0,0,6,0,0,0,4,0,0,0,23,0,4,0,8,0,0,0,6,0,0,0,2,0,0,0,30,0,4,0,9,0,0,0,7,0,0,0,8,0,0,0,32,0,4,0,10,0,0,0,3,0,0,0,9,0,0,0,59,0,4,0,10,0,0,0,11,0,0,0,3,0,0, + 0,21,0,4,0,12,0,0,0,32,0,0,0,1,0,0,0,43,0,4,0,12,0,0,0,13,0,0,0,0,0,0,0,32,0,4,0,14,0,0,0,1,0,0,0,7,0,0,0,59,0,4,0,14,0,0,0,15,0,0,0,1,0,0,0,32,0,4,0,17,0,0,0,3,0,0,0,7,0,0,0,43,0, + 4,0,12,0,0,0,19,0,0,0,1,0,0,0,32,0,4,0,20,0,0,0,1,0,0,0,8,0,0,0,59,0,4,0,20,0,0,0,21,0,0,0,1,0,0,0,32,0,4,0,23,0,0,0,3,0,0,0,8,0,0,0,21,0,4,0,25,0,0,0,32,0,0,0,0,0,0,0,43,0,4,0,25, + 0,0,0,26,0,0,0,1,0,0,0,28,0,4,0,27,0,0,0,6,0,0,0,26,0,0,0,30,0,6,0,28,0,0,0,7,0,0,0,6,0,0,0,27,0,0,0,27,0,0,0,32,0,4,0,29,0,0,0,3,0,0,0,28,0,0,0,59,0,4,0,29,0,0,0,30,0,0,0,3,0,0,0, + 59,0,4,0,20,0,0,0,31,0,0,0,1,0,0,0,30,0,4,0,33,0,0,0,8,0,0,0,8,0,0,0,32,0,4,0,34,0,0,0,2,0,0,0,33,0,0,0,59,0,4,0,34,0,0,0,35,0,0,0,2,0,0,0,32,0,4,0,36,0,0,0,2,0,0,0,8,0,0,0,43,0,4, + 0,6,0,0,0,43,0,0,0,0,0,0,0,43,0,4,0,6,0,0,0,44,0,0,0,0,0,128,63,43,0,4,0,6,0,0,0,49,0,0,0,0,0,128,191,32,0,4,0,50,0,0,0,3,0,0,0,6,0,0,0,54,0,5,0,2,0,0,0,4,0,0,0,0,0,0,0,3,0,0,0,248, + 0,2,0,5,0,0,0,61,0,4,0,7,0,0,0,16,0,0,0,15,0,0,0,65,0,5,0,17,0,0,0,18,0,0,0,11,0,0,0,13,0,0,0,62,0,3,0,18,0,0,0,16,0,0,0,61,0,4,0,8,0,0,0,22,0,0,0,21,0,0,0,65,0,5,0,23,0,0,0,24,0,0, + 0,11,0,0,0,19,0,0,0,62,0,3,0,24,0,0,0,22,0,0,0,61,0,4,0,8,0,0,0,32,0,0,0,31,0,0,0,65,0,5,0,36,0,0,0,37,0,0,0,35,0,0,0,13,0,0,0,61,0,4,0,8,0,0,0,38,0,0,0,37,0,0,0,133,0,5,0,8,0,0,0, + 39,0,0,0,32,0,0,0,38,0,0,0,65,0,5,0,36,0,0,0,40,0,0,0,35,0,0,0,19,0,0,0,61,0,4,0,8,0,0,0,41,0,0,0,40,0,0,0,129,0,5,0,8,0,0,0,42,0,0,0,39,0,0,0,41,0,0,0,81,0,5,0,6,0,0,0,45,0,0,0,42, + 0,0,0,0,0,0,0,81,0,5,0,6,0,0,0,46,0,0,0,42,0,0,0,1,0,0,0,80,0,7,0,7,0,0,0,47,0,0,0,45,0,0,0,46,0,0,0,43,0,0,0,44,0,0,0,65,0,5,0,17,0,0,0,48,0,0,0,30,0,0,0,13,0,0,0,62,0,3,0,48,0,0, + 0,47,0,0,0,65,0,6,0,50,0,0,0,51,0,0,0,30,0,0,0,13,0,0,0,26,0,0,0,61,0,4,0,6,0,0,0,52,0,0,0,51,0,0,0,133,0,5,0,6,0,0,0,53,0,0,0,52,0,0,0,49,0,0,0,65,0,6,0,50,0,0,0,54,0,0,0,30,0,0,0, + 13,0,0,0,26,0,0,0,62,0,3,0,54,0,0,0,53,0,0,0,253,0,1,0,56,0,1,0, +}; +const uint8_t spirv_fragment[844] = { + 3,2,35,7,0,0,1,0,11,0,13,0,30,0,0,0,0,0,0,0,17,0,2,0,1,0,0,0,11,0,6,0,1,0,0,0,71,76,83,76,46,115,116,100,46,52,53,48,0,0,0,0,14,0,3,0,0,0,0,0,1,0,0,0,15,0,7,0,4,0,0,0,4,0,0,0,109,97, + 105,110,0,0,0,0,9,0,0,0,13,0,0,0,16,0,3,0,4,0,0,0,7,0,0,0,3,0,3,0,2,0,0,0,194,1,0,0,4,0,10,0,71,76,95,71,79,79,71,76,69,95,99,112,112,95,115,116,121,108,101,95,108,105,110,101,95,100, + 105,114,101,99,116,105,118,101,0,0,4,0,8,0,71,76,95,71,79,79,71,76,69,95,105,110,99,108,117,100,101,95,100,105,114,101,99,116,105,118,101,0,5,0,4,0,4,0,0,0,109,97,105,110,0,0,0,0,5, + 0,4,0,9,0,0,0,102,67,111,108,111,114,0,0,5,0,3,0,11,0,0,0,0,0,0,0,6,0,5,0,11,0,0,0,0,0,0,0,67,111,108,111,114,0,0,0,6,0,4,0,11,0,0,0,1,0,0,0,85,86,0,0,5,0,3,0,13,0,0,0,73,110,0,0,5, + 0,5,0,22,0,0,0,115,84,101,120,116,117,114,101,0,0,0,0,71,0,4,0,9,0,0,0,30,0,0,0,0,0,0,0,71,0,4,0,13,0,0,0,30,0,0,0,0,0,0,0,71,0,4,0,22,0,0,0,33,0,0,0,0,0,0,0,71,0,4,0,22,0,0,0,34,0, + 0,0,2,0,0,0,19,0,2,0,2,0,0,0,33,0,3,0,3,0,0,0,2,0,0,0,22,0,3,0,6,0,0,0,32,0,0,0,23,0,4,0,7,0,0,0,6,0,0,0,4,0,0,0,32,0,4,0,8,0,0,0,3,0,0,0,7,0,0,0,59,0,4,0,8,0,0,0,9,0,0,0,3,0,0,0,23, + 0,4,0,10,0,0,0,6,0,0,0,2,0,0,0,30,0,4,0,11,0,0,0,7,0,0,0,10,0,0,0,32,0,4,0,12,0,0,0,1,0,0,0,11,0,0,0,59,0,4,0,12,0,0,0,13,0,0,0,1,0,0,0,21,0,4,0,14,0,0,0,32,0,0,0,1,0,0,0,43,0,4,0, + 14,0,0,0,15,0,0,0,0,0,0,0,32,0,4,0,16,0,0,0,1,0,0,0,7,0,0,0,25,0,9,0,19,0,0,0,6,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,27,0,3,0,20,0,0,0,19,0,0,0,32,0,4,0,21,0,0,0,0, + 0,0,0,20,0,0,0,59,0,4,0,21,0,0,0,22,0,0,0,0,0,0,0,43,0,4,0,14,0,0,0,24,0,0,0,1,0,0,0,32,0,4,0,25,0,0,0,1,0,0,0,10,0,0,0,54,0,5,0,2,0,0,0,4,0,0,0,0,0,0,0,3,0,0,0,248,0,2,0,5,0,0,0,65, + 0,5,0,16,0,0,0,17,0,0,0,13,0,0,0,15,0,0,0,61,0,4,0,7,0,0,0,18,0,0,0,17,0,0,0,61,0,4,0,20,0,0,0,23,0,0,0,22,0,0,0,65,0,5,0,25,0,0,0,26,0,0,0,13,0,0,0,24,0,0,0,61,0,4,0,10,0,0,0,27,0, + 0,0,26,0,0,0,87,0,5,0,7,0,0,0,28,0,0,0,23,0,0,0,27,0,0,0,133,0,5,0,7,0,0,0,29,0,0,0,18,0,0,0,28,0,0,0,62,0,3,0,9,0,0,0,29,0,0,0,253,0,1,0,56,0,1,0, +}; + +const uint8_t dxbc_vertex[1064] = { + 68,88,66,67,32,50,127,204,241,196,165,104,216,114,216,116,220,164,29,45,1,0,0,0,40,4,0,0,5,0,0,0,52,0,0,0,136,1,0,0,236,1,0,0,92,2,0,0,140,3,0,0,82,68,69,70,76,1,0,0,1,0,0,0,116,0, + 0,0,1,0,0,0,60,0,0,0,1,5,254,255,0,5,0,0,34,1,0,0,19,19,68,37,60,0,0,0,24,0,0,0,40,0,0,0,40,0,0,0,36,0,0,0,12,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, + 0,1,0,0,0,1,0,0,0,0,0,0,0,117,80,117,115,104,67,111,110,115,116,97,110,116,0,171,171,100,0,0,0,2,0,0,0,140,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,220,0,0,0,0,0,0,0,8,0,0,0,2,0,0,0,240,0,0, + 0,0,0,0,0,255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0,20,1,0,0,8,0,0,0,8,0,0,0,2,0,0,0,240,0,0,0,0,0,0,0,255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0,112,99,95,117,83,99,97, + 108,101,0,102,108,111,97,116,50,0,171,171,171,1,0,3,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,230,0,0,0,112,99,95,117,84,114,97,110,115,108,97,116,101,0,77,105,99,114, + 111,115,111,102,116,32,40,82,41,32,72,76,83,76,32,83,104,97,100,101,114,32,67,111,109,112,105,108,101,114,32,49,48,46,49,0,171,171,73,83,71,78,92,0,0,0,3,0,0,0,8,0,0,0,80,0,0,0,0,0, + 0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,3,0,0,80,0,0,0,1,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,3,3,0,0,80,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,2,0,0,0,15,15,0,0,84,69,88,67,79,79,82,68,0,171,171,171,79,83, + 71,78,104,0,0,0,3,0,0,0,8,0,0,0,80,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,15,0,0,0,80,0,0,0,1,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,3,12,0,0,89,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0,2,0,0,0,15,0,0, + 0,84,69,88,67,79,79,82,68,0,83,86,95,80,111,115,105,116,105,111,110,0,171,171,171,83,72,69,88,40,1,0,0,81,0,1,0,74,0,0,0,106,8,0,1,89,0,0,7,70,142,48,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, + 0,0,1,0,0,0,95,0,0,3,50,16,16,0,0,0,0,0,95,0,0,3,50,16,16,0,1,0,0,0,95,0,0,3,242,16,16,0,2,0,0,0,101,0,0,3,242,32,16,0,0,0,0,0,101,0,0,3,50,32,16,0,1,0,0,0,103,0,0,4,242,32,16,0,2, + 0,0,0,1,0,0,0,104,0,0,2,1,0,0,0,50,0,0,13,50,0,16,0,0,0,0,0,70,16,16,0,0,0,0,0,70,128,48,0,0,0,0,0,0,0,0,0,0,0,0,0,230,138,48,0,0,0,0,0,0,0,0,0,0,0,0,0,54,0,0,6,34,32,16,0,2,0,0,0, + 26,0,16,128,65,0,0,0,0,0,0,0,54,0,0,5,242,32,16,0,0,0,0,0,70,30,16,0,2,0,0,0,54,0,0,5,18,32,16,0,2,0,0,0,10,0,16,0,0,0,0,0,54,0,0,8,194,32,16,0,2,0,0,0,2,64,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,128,63,54,0,0,5,50,32,16,0,1,0,0,0,70,16,16,0,1,0,0,0,62,0,0,1,83,84,65,84,148,0,0,0,7,0,0,0,1,0,0,0,0,0,0,0,6,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; +const uint8_t dxbc_fragment[744] = { + 68,88,66,67,235,219,43,109,38,151,39,223,98,41,193,28,215,98,67,110,1,0,0,0,232,2,0,0,5,0,0,0,52,0,0,0,12,1,0,0,88,1,0,0,140,1,0,0,76,2,0,0,82,68,69,70,208,0,0,0,0,0,0,0,0,0,0,0,2, + 0,0,0,60,0,0,0,1,5,255,255,0,5,0,0,167,0,0,0,19,19,68,37,60,0,0,0,24,0,0,0,40,0,0,0,40,0,0,0,36,0,0,0,12,0,0,0,0,0,0,0,140,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0, + 0,0,2,0,0,0,0,0,0,0,158,0,0,0,2,0,0,0,5,0,0,0,4,0,0,0,255,255,255,255,0,0,0,0,1,0,0,0,12,0,0,0,2,0,0,0,0,0,0,0,95,115,84,101,120,116,117,114,101,95,115,97,109,112,108,101,114,0,115, + 84,101,120,116,117,114,101,0,77,105,99,114,111,115,111,102,116,32,40,82,41,32,72,76,83,76,32,83,104,97,100,101,114,32,67,111,109,112,105,108,101,114,32,49,48,46,49,0,171,73,83,71,78, + 68,0,0,0,2,0,0,0,8,0,0,0,56,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,15,15,0,0,56,0,0,0,1,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,3,3,0,0,84,69,88,67,79,79,82,68,0,171,171,171,79,83,71,78,44,0, + 0,0,1,0,0,0,8,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,15,0,0,0,83,86,95,84,97,114,103,101,116,0,171,171,83,72,69,88,184,0,0,0,81,0,0,0,46,0,0,0,106,8,0,1,90,0,0,6,70,110,48, + 0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,88,24,0,7,70,126,48,0,0,0,0,0,0,0,0,0,0,0,0,0,85,85,0,0,2,0,0,0,98,16,0,3,242,16,16,0,0,0,0,0,98,16,0,3,50,16,16,0,1,0,0,0,101,0,0,3,242,32,16,0,0, + 0,0,0,104,0,0,2,1,0,0,0,69,0,0,11,242,0,16,0,0,0,0,0,70,16,16,0,1,0,0,0,70,126,32,0,0,0,0,0,0,0,0,0,0,96,32,0,0,0,0,0,0,0,0,0,56,0,0,7,242,32,16,0,0,0,0,0,70,14,16,0,0,0,0,0,70,30, + 16,0,0,0,0,0,62,0,0,1,83,84,65,84,148,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +#ifdef __APPLE__ +#include +#if TARGET_OS_MAC +const uint8_t metallib_vertex[3892] = { + 77,84,76,66,1,128,2,0,7,0,0,129,14,0,0,0,52,15,0,0,0,0,0,0,88,0,0,0,0,0,0,0,123,0,0,0,0,0,0,0,219,0,0,0,0,0,0,0,49,0,0,0,0,0,0,0,12,1,0,0,0,0,0,0,8,0,0,0,0,0,0,0,20,1,0,0,0,0,0,0,32, + 14,0,0,0,0,0,0,1,0,0,0,123,0,0,0,78,65,77,69,6,0,109,97,105,110,48,0,84,89,80,69,1,0,0,72,65,83,72,32,0,62,81,190,157,8,240,236,158,164,213,65,62,170,226,96,136,231,243,238,160,100, + 26,13,254,254,64,19,129,180,3,149,75,77,68,83,90,8,0,32,14,0,0,0,0,0,0,79,70,70,84,24,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,86,69,82,83,8,0,2,0,6,0,3,0,1,0,69,78,68,84, + 69,78,68,84,45,0,0,0,86,65,84,84,24,0,3,0,97,80,111,115,0,0,128,97,85,86,0,1,128,97,67,111,108,111,114,0,2,128,86,65,84,89,5,0,3,0,4,4,6,69,78,68,84,4,0,0,0,69,78,68,84,222,192,23, + 11,0,0,0,0,20,0,0,0,8,14,0,0,255,255,255,255,66,67,192,222,53,20,0,0,3,0,0,0,98,12,48,36,128,16,5,200,20,0,0,0,33,12,0,0,74,3,0,0,11,2,33,0,2,0,0,0,22,0,0,0,7,129,35,145,65,200,4,73, + 6,16,50,57,146,1,132,12,37,5,8,25,30,4,139,98,128,16,69,2,66,146,11,66,132,16,50,20,56,8,24,75,10,50,66,136,72,112,196,33,35,68,18,135,140,16,65,146,2,100,200,8,177,20,32,67,70,136, + 32,201,1,50,66,132,24,42,40,42,144,49,124,176,92,145,32,196,200,0,0,0,137,32,0,0,24,0,0,0,50,34,8,9,32,98,70,0,33,43,36,152,16,33,37,36,152,16,25,39,12,133,164,144,96,66,100,92,32, + 36,100,130,224,153,1,24,70,32,128,97,4,1,184,67,72,32,37,77,17,37,76,62,149,82,210,193,57,141,52,1,205,148,4,145,65,4,66,48,197,136,68,145,13,4,204,17,128,129,10,228,28,1,40,12,34, + 8,194,48,2,145,140,0,0,0,0,0,81,24,0,0,100,0,0,0,27,246,35,248,255,255,255,255,1,48,5,192,15,0,56,0,254,0,144,0,10,232,3,34,28,224,1,30,228,225,29,240,161,13,204,161,30,220,97,28,218, + 192,28,224,161,13,218,33,28,232,1,29,0,122,144,135,122,40,7,128,48,7,121,8,135,118,40,135,54,128,135,119,72,7,119,160,135,114,144,7,32,28,216,129,29,0,162,29,210,193,29,218,128,29, + 202,225,28,194,129,29,218,192,30,202,97,28,232,225,29,228,161,13,238,33,29,200,129,30,208,1,136,3,57,192,3,96,112,135,119,104,3,113,168,135,116,96,7,122,72,7,119,152,7,128,112,135, + 119,104,131,116,112,7,115,152,135,54,48,7,120,104,131,118,8,7,122,64,7,128,30,228,161,30,202,1,32,220,225,29,218,192,29,194,193,29,230,161,13,204,1,30,218,160,29,194,129,30,208,1,160, + 7,121,168,135,114,0,8,119,120,135,54,152,135,116,56,7,119,40,7,114,104,3,125,40,7,121,120,135,121,104,3,115,128,135,54,104,135,112,160,7,116,0,232,65,30,234,161,28,0,194,29,222,161, + 13,232,65,30,194,1,30,224,33,29,220,225,28,218,160,29,194,129,30,208,1,160,7,121,168,135,114,0,136,121,160,135,112,24,135,117,104,3,120,144,135,119,160,135,114,24,7,122,120,7,121,104, + 3,113,168,7,115,48,135,114,144,135,54,152,135,116,208,135,114,0,240,0,32,234,193,29,230,33,28,204,161,28,218,192,28,224,161,13,218,33,28,232,1,29,0,122,144,135,122,40,7,96,195,24,8, + 4,176,0,164,0,84,65,128,4,105,0,13,225,144,14,242,208,6,226,80,15,230,96,14,229,32,15,109,224,14,239,208,6,225,192,14,233,16,14,243,0,0,0,73,24,0,0,1,0,0,0,19,132,64,0,19,176,112,72, + 7,121,176,3,58,104,131,112,128,7,120,96,135,114,104,131,118,8,135,113,120,135,121,192,135,56,160,3,55,128,3,55,128,131,13,183,81,14,109,0,15,122,96,7,116,160,7,118,64,7,122,96,7,116, + 208,6,233,16,7,122,128,7,122,128,7,109,144,14,120,160,7,120,160,7,120,208,6,233,16,7,118,160,7,113,96,7,122,16,7,118,208,6,233,48,7,114,160,7,115,32,7,122,48,7,114,208,6,233,96,7,116, + 160,7,118,64,7,122,96,7,116,208,6,230,48,7,114,160,7,115,32,7,122,48,7,114,208,6,230,96,7,116,160,7,118,64,7,122,96,7,116,208,6,246,16,7,118,160,7,113,96,7,122,16,7,118,208,6,246,32, + 7,116,160,7,115,32,7,122,48,7,114,208,6,246,48,7,114,160,7,115,32,7,122,48,7,114,208,6,246,64,7,120,160,7,118,64,7,122,96,7,116,208,6,246,96,7,116,160,7,118,64,7,122,96,7,116,208,6, + 246,144,7,118,160,7,113,32,7,120,160,7,113,32,7,120,208,6,246,16,7,114,128,7,122,16,7,114,128,7,122,16,7,114,128,7,109,96,15,113,144,7,114,160,7,114,80,7,118,160,7,114,80,7,118,208, + 6,246,32,7,117,96,7,122,32,7,117,96,7,122,32,7,117,96,7,109,96,15,117,16,7,114,160,7,117,16,7,114,160,7,117,16,7,114,208,6,246,16,7,112,32,7,116,160,7,113,0,7,114,64,7,122,16,7,112, + 32,7,116,208,6,238,128,7,122,16,7,118,160,7,115,32,7,26,33,12,89,48,0,210,208,67,42,160,48,0,0,8,0,0,0,4,0,0,0,0,0,10,64,98,131,64,81,166,1,0,128,44,16,0,11,0,0,0,50,30,152,16,25,17, + 76,144,140,9,38,71,198,4,67,202,34,40,129,66,40,135,242,41,64,129,130,40,144,98,24,1,40,3,218,17,0,210,177,132,39,0,0,0,177,24,0,0,165,0,0,0,51,8,128,28,196,225,28,102,20,1,61,136, + 67,56,132,195,140,66,128,7,121,120,7,115,152,113,12,230,0,15,237,16,14,244,128,14,51,12,66,30,194,193,29,206,161,28,102,48,5,61,136,67,56,132,131,27,204,3,61,200,67,61,140,3,61,204, + 120,140,116,112,7,123,8,7,121,72,135,112,112,7,122,112,3,118,120,135,112,32,135,25,204,17,14,236,144,14,225,48,15,110,48,15,227,240,14,240,80,14,51,16,196,29,222,33,28,216,33,29,194, + 97,30,102,48,137,59,188,131,59,208,67,57,180,3,60,188,131,60,132,3,59,204,240,20,118,96,7,123,104,7,55,104,135,114,104,7,55,128,135,112,144,135,112,96,7,118,40,7,118,248,5,118,120, + 135,119,128,135,95,8,135,113,24,135,114,152,135,121,152,129,44,238,240,14,238,224,14,245,192,14,236,48,3,98,200,161,28,228,161,28,204,161,28,228,161,28,220,97,28,202,33,28,196,129, + 29,202,97,6,214,144,67,57,200,67,57,152,67,57,200,67,57,184,195,56,148,67,56,136,3,59,148,195,47,188,131,60,252,130,59,212,3,59,176,195,12,199,105,135,112,88,135,114,112,131,116,104, + 7,120,96,135,116,24,135,116,160,135,25,206,83,15,238,0,15,242,80,14,228,144,14,227,64,15,225,32,14,236,80,14,51,32,40,29,220,193,30,194,65,30,210,33,28,220,129,30,220,224,28,228,225, + 29,234,1,30,102,24,81,56,176,67,58,156,131,59,204,80,36,118,96,7,123,104,7,55,96,135,119,120,7,120,152,81,76,244,144,15,240,80,14,51,30,106,30,202,97,28,232,33,29,222,193,29,126,1, + 30,228,161,28,204,33,29,240,97,6,84,133,131,56,204,195,59,176,67,61,208,67,57,252,194,60,228,67,59,136,195,59,176,195,140,197,10,135,121,152,135,119,24,135,116,8,7,122,40,7,114,152, + 129,92,227,16,14,236,192,14,229,80,14,243,48,35,193,210,65,30,228,225,23,216,225,29,222,1,30,102,72,25,59,176,131,61,180,131,27,132,195,56,140,67,57,204,195,60,184,193,57,200,195,59, + 212,3,60,204,72,180,113,8,7,118,96,7,113,8,135,113,88,135,25,219,198,14,236,96,15,237,224,6,240,32,15,229,48,15,229,32,15,246,80,14,110,16,14,227,48,14,229,48,15,243,224,6,233,224, + 14,228,80,14,248,48,35,226,236,97,28,194,129,29,216,225,23,236,33,29,230,33,29,196,33,29,216,33,29,232,33,31,102,32,157,59,188,67,61,184,3,57,148,131,57,204,88,188,112,112,7,119,120, + 7,122,8,7,122,72,135,119,112,135,25,206,135,14,229,16,14,240,16,14,236,192,14,239,48,14,243,144,14,244,80,14,51,40,48,8,135,116,144,7,55,48,135,122,112,135,113,160,135,116,120,7,119, + 248,133,115,144,135,119,168,7,120,152,7,0,0,0,0,121,32,0,0,26,1,0,0,114,30,72,32,67,136,12,25,9,114,50,72,32,35,129,140,145,145,209,68,160,16,40,100,60,49,50,66,142,144,33,163,152, + 6,100,208,82,0,0,0,139,210,88,216,6,109,80,28,20,27,71,6,209,18,25,76,178,24,6,179,64,18,49,24,202,131,68,148,161,68,87,35,0,0,0,0,83,68,75,32,86,101,114,115,105,111,110,119,99,104, + 97,114,95,115,105,122,101,102,114,97,109,101,45,112,111,105,110,116,101,114,97,105,114,46,109,97,120,95,100,101,118,105,99,101,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120, + 95,99,111,110,115,116,97,110,116,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,116,104,114,101,97,100,103,114,111,117,112,95,98,117,102,102,101,114,115,97,105,114,46,109, + 97,120,95,116,101,120,116,117,114,101,115,97,105,114,46,109,97,120,95,114,101,97,100,95,119,114,105,116,101,95,116,101,120,116,117,114,101,115,97,105,114,46,109,97,120,95,115,97,109, + 112,108,101,114,115,65,112,112,108,101,32,109,101,116,97,108,32,118,101,114,115,105,111,110,32,51,50,48,50,51,46,51,54,56,32,40,109,101,116,97,108,102,101,45,51,50,48,50,51,46,51,54, + 56,41,77,101,116,97,108,97,105,114,46,99,111,109,112,105,108,101,46,100,101,110,111,114,109,115,95,100,105,115,97,98,108,101,97,105,114,46,99,111,109,112,105,108,101,46,102,97,115, + 116,95,109,97,116,104,95,101,110,97,98,108,101,97,105,114,46,99,111,109,112,105,108,101,46,102,114,97,109,101,98,117,102,102,101,114,95,102,101,116,99,104,95,101,110,97,98,108,101, + 97,105,114,46,118,101,114,116,101,120,95,111,117,116,112,117,116,117,115,101,114,40,108,111,99,110,48,41,97,105,114,46,97,114,103,95,116,121,112,101,95,110,97,109,101,102,108,111,97, + 116,52,97,105,114,46,97,114,103,95,110,97,109,101,79,117,116,95,67,111,108,111,114,117,115,101,114,40,108,111,99,110,49,41,102,108,111,97,116,50,79,117,116,95,85,86,97,105,114,46,112, + 111,115,105,116,105,111,110,103,108,95,80,111,115,105,116,105,111,110,97,105,114,46,118,101,114,116,101,120,95,105,110,112,117,116,97,105,114,46,108,111,99,97,116,105,111,110,95,105, + 110,100,101,120,97,80,111,115,97,85,86,97,67,111,108,111,114,97,105,114,46,98,117,102,102,101,114,97,105,114,46,98,117,102,102,101,114,95,115,105,122,101,97,105,114,46,114,101,97,100, + 97,105,114,46,97,100,100,114,101,115,115,95,115,112,97,99,101,97,105,114,46,115,116,114,117,99,116,95,116,121,112,101,95,105,110,102,111,117,83,99,97,108,101,117,84,114,97,110,115, + 108,97,116,101,97,105,114,46,97,114,103,95,116,121,112,101,95,115,105,122,101,97,105,114,46,97,114,103,95,116,121,112,101,95,97,108,105,103,110,95,115,105,122,101,117,80,117,115,104, + 67,111,110,115,116,97,110,116,112,99,0,0,0,166,119,0,0,0,0,0,0,48,130,144,4,35,8,74,51,130,144,8,35,8,201,48,130,144,16,35,8,73,49,130,144,24,35,8,201,49,130,144,32,35,8,73,50,130, + 144,40,35,8,201,50,130,112,0,51,12,106,16,172,193,12,3,27,8,109,48,195,224,6,131,26,204,48,184,1,241,6,51,12,110,80,188,193,12,131,27,24,111,48,195,224,6,7,28,204,48,184,1,18,7,51, + 12,110,144,200,193,12,129,50,195,160,6,115,64,7,51,16,75,29,176,1,29,204,16,48,51,4,205,12,129,51,131,241,64,145,52,81,51,24,79,21,89,211,53,67,129,69,210,148,205,48,152,194,41,160, + 194,12,9,29,104,27,29,176,65,100,77,220,12,9,27,104,27,27,176,65,100,77,221,12,137,26,104,155,26,176,65,36,77,222,12,10,29,196,1,29,88,100,16,7,113,64,7,86,25,204,64,213,193,7,6,114, + 176,209,1,27,132,129,24,168,193,24,180,130,25,200,193,25,196,65,132,6,83,26,204,64,168,194,42,176,130,43,204,48,216,65,42,188,194,157,1,192,113,28,199,113,28,199,113,28,199,185,129, + 27,184,129,27,184,129,27,184,129,27,184,129,69,7,122,96,89,22,29,208,129,27,208,1,46,224,2,46,240,3,122,128,130,140,4,38,40,35,54,54,187,54,151,182,55,178,58,182,50,23,51,182,176,179, + 185,81,18,59,184,3,60,200,3,61,216,3,62,232,3,63,72,133,141,205,174,205,37,141,172,204,141,110,148,224,15,114,9,75,147,115,177,43,147,155,75,123,115,27,37,0,133,164,194,210,228,92, + 216,194,220,206,234,194,206,202,190,236,202,228,230,210,222,220,70,9,66,33,167,176,52,57,151,177,183,54,184,52,182,178,175,55,56,186,180,55,183,185,81,6,81,24,5,82,72,37,44,77,206, + 197,174,76,142,174,12,111,148,224,21,0,0,0,169,24,0,0,37,0,0,0,11,10,114,40,135,119,128,7,122,88,112,152,67,61,184,195,56,176,67,57,208,195,130,230,28,198,161,13,232,65,30,194,193, + 29,230,33,29,232,33,29,222,193,29,22,52,227,96,14,231,80,15,225,32,15,228,64,15,225,32,15,231,80,14,244,176,128,129,7,121,40,135,112,96,7,118,120,135,113,8,7,122,40,7,114,88,112,156, + 195,56,180,1,59,164,131,61,148,195,2,107,28,216,33,28,220,225,28,220,32,28,228,97,28,220,32,28,232,129,30,194,97,28,208,161,28,200,97,28,194,129,29,216,97,193,1,15,244,32,15,225,80, + 15,244,128,14,0,0,0,0,209,16,0,0,6,0,0,0,7,204,60,164,131,59,156,3,59,148,3,61,160,131,60,148,67,56,144,195,1,0,0,0,97,32,0,0,68,0,0,0,19,4,65,44,16,0,0,0,11,0,0,0,148,51,0,180,37, + 64,61,7,161,72,146,52,7,161,72,9,65,48,26,48,2,48,70,0,130,32,136,127,20,115,16,150,117,97,36,163,1,52,51,0,0,0,0,0,241,48,0,0,32,0,0,0,34,71,200,144,81,18,196,43,0,0,0,0,207,115,89, + 0,111,109,110,105,112,111,116,101,110,116,32,99,104,97,114,83,105,109,112,108,101,32,67,43,43,32,84,66,65,65,97,105,114,45,97,108,105,97,115,45,115,99,111,112,101,115,40,109,97,105, + 110,48,41,97,105,114,45,97,108,105,97,115,45,115,99,111,112,101,45,97,114,103,40,51,41,0,19,132,133,89,33,216,194,44,172,24,110,193,22,104,97,67,32,11,27,134,88,192,133,90,216,48,228, + 66,46,212,194,134,224,22,0,0,157,134,5,146,40,16,130,1,36,254,157,6,103,234,40,16,130,67,0,254,131,12,1,226,12,50,4,138,51,134,48,68,22,128,255,28,195,16,76,179,13,204,5,204,54,4,89, + 48,219,16,12,194,6,1,49,0,4,0,0,0,91,138,32,200,133,67,23,182,20,68,144,11,135,46,0,0,0,0,0,0,113,32,0,0,3,0,0,0,50,14,16,34,132,0,134,6,0,0,0,0,0,0,0,0,101,12,0,0,31,0,0,0,18,3,148, + 240,0,0,0,0,3,0,0,0,5,0,0,0,9,0,0,0,76,0,0,0,1,0,0,0,88,0,0,0,0,0,0,0,88,0,0,0,1,0,0,0,112,0,0,0,0,0,0,0,14,0,0,0,24,0,0,0,0,0,0,0,5,0,0,0,5,0,0,0,0,0,0,0,112,0,0,0,0,0,0,0,0,0,0,0, + 1,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,5,0,0,0,255,255,255,255,0,36,0,0,0,0,0,0,93,12,0,0,13,0,0,0,18,3,148,102,0,0,0,0,109,97,105,110,48,51,50,48,50,51,46,51,54,56,97,105,114,54, + 52,45,97,112,112,108,101,45,109,97,99,111,115,120,49,52,46,48,46,48,0,0,0,0,0,0,0,0,0,0, +}; +const uint8_t metallib_fragment[3787] = { + 77,84,76,66,1,128,2,0,7,0,0,129,14,0,0,0,203,14,0,0,0,0,0,0,88,0,0,0,0,0,0,0,123,0,0,0,0,0,0,0,219,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,227,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,235,0,0,0,0,0,0,0, + 224,13,0,0,0,0,0,0,1,0,0,0,123,0,0,0,78,65,77,69,6,0,109,97,105,110,48,0,84,89,80,69,1,0,1,72,65,83,72,32,0,201,103,233,140,10,95,185,107,79,93,85,82,78,218,248,8,95,184,8,139,191, + 155,174,56,51,95,203,135,255,117,44,62,77,68,83,90,8,0,224,13,0,0,0,0,0,0,79,70,70,84,24,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,86,69,82,83,8,0,2,0,6,0,3,0,1,0,69,78,68, + 84,69,78,68,84,4,0,0,0,69,78,68,84,4,0,0,0,69,78,68,84,222,192,23,11,0,0,0,0,20,0,0,0,196,13,0,0,255,255,255,255,66,67,192,222,53,20,0,0,3,0,0,0,98,12,48,36,128,16,5,200,20,0,0,0,33, + 12,0,0,44,3,0,0,11,2,33,0,2,0,0,0,22,0,0,0,7,129,35,145,65,200,4,73,6,16,50,57,146,1,132,12,37,5,8,25,30,4,139,98,128,20,69,2,66,146,11,66,164,16,50,20,56,8,24,75,10,50,82,136,72,112, + 196,33,35,68,18,135,140,16,65,146,2,100,200,8,177,20,32,67,70,136,32,201,1,50,82,132,24,42,40,42,144,49,124,176,92,145,32,197,200,0,0,0,137,32,0,0,31,0,0,0,50,34,72,9,32,98,70,0,33, + 43,36,152,20,33,37,36,152,20,25,39,12,133,164,144,96,82,100,92,32,36,101,130,128,154,1,24,70,32,128,27,132,97,4,1,64,74,154,34,74,152,252,127,34,174,137,138,136,223,30,254,105,140, + 0,24,68,32,2,140,164,41,162,132,201,255,37,128,121,22,34,250,167,49,2,96,16,193,16,76,33,194,40,135,208,28,1,114,132,160,230,8,130,57,2,48,24,70,16,26,163,172,114,6,115,12,128,70,111, + 32,64,5,218,8,0,0,81,24,0,0,105,0,0,0,27,246,35,248,255,255,255,255,1,104,3,96,13,0,83,0,252,0,144,128,10,232,3,34,28,224,1,30,228,225,29,240,161,13,204,161,30,220,97,28,218,192,28, + 224,161,13,218,33,28,232,1,29,0,122,144,135,122,40,7,128,48,7,121,8,135,118,40,135,54,128,135,119,72,7,119,160,135,114,144,7,32,28,216,129,29,0,162,29,210,193,29,218,128,29,202,225, + 28,194,129,29,218,192,30,202,97,28,232,225,29,228,161,13,238,33,29,200,129,30,208,1,136,3,57,192,3,96,112,135,119,104,3,113,168,135,116,96,7,122,72,7,119,152,7,128,112,135,119,104, + 131,116,112,7,115,152,135,54,48,7,120,104,131,118,8,7,122,64,7,128,30,228,161,30,202,1,32,220,225,29,218,192,29,194,193,29,230,161,13,204,1,30,218,160,29,194,129,30,208,1,160,7,121, + 168,135,114,0,8,119,120,135,54,152,135,116,56,7,119,40,7,114,104,3,125,40,7,121,120,135,121,104,3,115,128,135,54,104,135,112,160,7,116,0,232,65,30,234,161,28,0,194,29,222,161,13,232, + 65,30,194,1,30,224,33,29,220,225,28,218,160,29,194,129,30,208,1,160,7,121,168,135,114,0,136,121,160,135,112,24,135,117,104,3,120,144,135,119,160,135,114,24,7,122,120,7,121,104,3,113, + 168,7,115,48,135,114,144,135,54,152,135,116,208,135,114,0,240,0,32,234,193,29,230,33,28,204,161,28,218,192,28,224,161,13,218,33,28,232,1,29,0,122,144,135,122,40,7,96,131,33,12,192, + 2,84,27,140,129,0,22,160,218,0,17,255,255,255,255,63,0,109,0,172,1,96,10,128,31,0,18,80,1,125,176,193,40,2,96,1,170,13,134,33,0,11,80,109,96,142,255,255,255,255,31,128,54,0,214,0,144, + 128,10,232,3,0,73,24,0,0,4,0,0,0,19,134,64,24,38,12,68,97,76,24,142,194,0,0,0,0,19,176,112,72,7,121,176,3,58,104,131,112,128,7,120,96,135,114,104,131,118,8,135,113,120,135,121,192, + 135,56,160,3,55,128,3,55,128,131,13,183,81,14,109,0,15,122,96,7,116,160,7,118,64,7,122,96,7,116,208,6,233,16,7,122,128,7,122,128,7,109,144,14,120,160,7,120,160,7,120,208,6,233,16,7, + 118,160,7,113,96,7,122,16,7,118,208,6,233,48,7,114,160,7,115,32,7,122,48,7,114,208,6,233,96,7,116,160,7,118,64,7,122,96,7,116,208,6,230,48,7,114,160,7,115,32,7,122,48,7,114,208,6,230, + 96,7,116,160,7,118,64,7,122,96,7,116,208,6,246,16,7,118,160,7,113,96,7,122,16,7,118,208,6,246,32,7,116,160,7,115,32,7,122,48,7,114,208,6,246,48,7,114,160,7,115,32,7,122,48,7,114,208, + 6,246,64,7,120,160,7,118,64,7,122,96,7,116,208,6,246,96,7,116,160,7,118,64,7,122,96,7,116,208,6,246,144,7,118,160,7,113,32,7,120,160,7,113,32,7,120,208,6,246,16,7,114,128,7,122,16, + 7,114,128,7,122,16,7,114,128,7,109,96,15,113,144,7,114,160,7,114,80,7,118,160,7,114,80,7,118,208,6,246,32,7,117,96,7,122,32,7,117,96,7,122,32,7,117,96,7,109,96,15,117,16,7,114,160, + 7,117,16,7,114,160,7,117,16,7,114,208,6,246,16,7,112,32,7,116,160,7,113,0,7,114,64,7,122,16,7,112,32,7,116,208,6,238,128,7,122,16,7,118,160,7,115,32,7,26,33,12,89,48,0,210,208,67,42, + 160,64,0,0,8,0,0,0,4,0,0,0,0,0,10,96,72,85,108,15,16,0,2,0,0,128,0,0,0,0,0,64,1,72,108,16,40,234,50,0,0,144,5,2,0,0,0,10,0,0,0,50,30,152,16,25,17,76,144,140,9,38,71,198,4,67,106,69, + 80,2,133,80,14,229,83,128,2,5,81,32,197,48,2,80,6,36,199,18,158,0,0,177,24,0,0,165,0,0,0,51,8,128,28,196,225,28,102,20,1,61,136,67,56,132,195,140,66,128,7,121,120,7,115,152,113,12, + 230,0,15,237,16,14,244,128,14,51,12,66,30,194,193,29,206,161,28,102,48,5,61,136,67,56,132,131,27,204,3,61,200,67,61,140,3,61,204,120,140,116,112,7,123,8,7,121,72,135,112,112,7,122, + 112,3,118,120,135,112,32,135,25,204,17,14,236,144,14,225,48,15,110,48,15,227,240,14,240,80,14,51,16,196,29,222,33,28,216,33,29,194,97,30,102,48,137,59,188,131,59,208,67,57,180,3,60, + 188,131,60,132,3,59,204,240,20,118,96,7,123,104,7,55,104,135,114,104,7,55,128,135,112,144,135,112,96,7,118,40,7,118,248,5,118,120,135,119,128,135,95,8,135,113,24,135,114,152,135,121, + 152,129,44,238,240,14,238,224,14,245,192,14,236,48,3,98,200,161,28,228,161,28,204,161,28,228,161,28,220,97,28,202,33,28,196,129,29,202,97,6,214,144,67,57,200,67,57,152,67,57,200,67, + 57,184,195,56,148,67,56,136,3,59,148,195,47,188,131,60,252,130,59,212,3,59,176,195,12,199,105,135,112,88,135,114,112,131,116,104,7,120,96,135,116,24,135,116,160,135,25,206,83,15,238, + 0,15,242,80,14,228,144,14,227,64,15,225,32,14,236,80,14,51,32,40,29,220,193,30,194,65,30,210,33,28,220,129,30,220,224,28,228,225,29,234,1,30,102,24,81,56,176,67,58,156,131,59,204,80, + 36,118,96,7,123,104,7,55,96,135,119,120,7,120,152,81,76,244,144,15,240,80,14,51,30,106,30,202,97,28,232,33,29,222,193,29,126,1,30,228,161,28,204,33,29,240,97,6,84,133,131,56,204,195, + 59,176,67,61,208,67,57,252,194,60,228,67,59,136,195,59,176,195,140,197,10,135,121,152,135,119,24,135,116,8,7,122,40,7,114,152,129,92,227,16,14,236,192,14,229,80,14,243,48,35,193,210, + 65,30,228,225,23,216,225,29,222,1,30,102,72,25,59,176,131,61,180,131,27,132,195,56,140,67,57,204,195,60,184,193,57,200,195,59,212,3,60,204,72,180,113,8,7,118,96,7,113,8,135,113,88, + 135,25,219,198,14,236,96,15,237,224,6,240,32,15,229,48,15,229,32,15,246,80,14,110,16,14,227,48,14,229,48,15,243,224,6,233,224,14,228,80,14,248,48,35,226,236,97,28,194,129,29,216,225, + 23,236,33,29,230,33,29,196,33,29,216,33,29,232,33,31,102,32,157,59,188,67,61,184,3,57,148,131,57,204,88,188,112,112,7,119,120,7,122,8,7,122,72,135,119,112,135,25,206,135,14,229,16, + 14,240,16,14,236,192,14,239,48,14,243,144,14,244,80,14,51,40,48,8,135,116,144,7,55,48,135,122,112,135,113,160,135,116,120,7,119,248,133,115,144,135,119,168,7,120,152,7,0,0,0,0,121, + 32,0,0,252,0,0,0,114,30,72,32,67,136,12,25,9,114,50,72,32,35,129,140,145,145,209,68,160,16,40,100,60,49,50,66,142,144,33,163,56,6,220,41,1,0,0,0,139,210,88,216,6,109,80,28,20,27,71, + 6,81,100,48,134,180,40,15,178,24,197,34,41,24,178,28,13,83,68,75,32,86,101,114,115,105,111,110,119,99,104,97,114,95,115,105,122,101,102,114,97,109,101,45,112,111,105,110,116,101,114, + 97,105,114,46,109,97,120,95,100,101,118,105,99,101,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,99,111,110,115,116,97,110,116,95,98,117,102,102,101,114,115,97,105,114, + 46,109,97,120,95,116,104,114,101,97,100,103,114,111,117,112,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,116,101,120,116,117,114,101,115,97,105,114,46,109,97,120,95,114, + 101,97,100,95,119,114,105,116,101,95,116,101,120,116,117,114,101,115,97,105,114,46,109,97,120,95,115,97,109,112,108,101,114,115,65,112,112,108,101,32,109,101,116,97,108,32,118,101, + 114,115,105,111,110,32,51,50,48,50,51,46,51,54,56,32,40,109,101,116,97,108,102,101,45,51,50,48,50,51,46,51,54,56,41,77,101,116,97,108,97,105,114,46,99,111,109,112,105,108,101,46,100, + 101,110,111,114,109,115,95,100,105,115,97,98,108,101,97,105,114,46,99,111,109,112,105,108,101,46,102,97,115,116,95,109,97,116,104,95,101,110,97,98,108,101,97,105,114,46,99,111,109, + 112,105,108,101,46,102,114,97,109,101,98,117,102,102,101,114,95,102,101,116,99,104,95,101,110,97,98,108,101,97,105,114,46,114,101,110,100,101,114,95,116,97,114,103,101,116,97,105,114, + 46,97,114,103,95,116,121,112,101,95,110,97,109,101,102,108,111,97,116,52,97,105,114,46,97,114,103,95,110,97,109,101,102,67,111,108,111,114,97,105,114,46,102,114,97,103,109,101,110, + 116,95,105,110,112,117,116,117,115,101,114,40,108,111,99,110,48,41,97,105,114,46,99,101,110,116,101,114,97,105,114,46,112,101,114,115,112,101,99,116,105,118,101,73,110,95,67,111,108, + 111,114,117,115,101,114,40,108,111,99,110,49,41,102,108,111,97,116,50,73,110,95,85,86,97,105,114,46,116,101,120,116,117,114,101,97,105,114,46,108,111,99,97,116,105,111,110,95,105,110, + 100,101,120,97,105,114,46,115,97,109,112,108,101,116,101,120,116,117,114,101,50,100,60,102,108,111,97,116,44,32,115,97,109,112,108,101,62,115,84,101,120,116,117,114,101,97,105,114, + 46,115,97,109,112,108,101,114,115,97,109,112,108,101,114,115,84,101,120,116,117,114,101,83,109,112,108,114,0,198,96,0,0,0,0,0,0,48,130,208,8,35,8,82,51,130,208,12,35,8,13,49,130,208, + 20,35,8,141,49,130,208,28,35,8,13,50,130,208,36,35,8,141,50,130,208,44,35,8,13,51,130,144,0,51,12,100,16,148,193,12,131,25,8,103,48,195,128,6,3,25,204,48,160,1,145,6,51,12,104,80,164, + 193,12,3,26,24,105,48,195,128,6,135,26,204,48,160,1,178,6,51,12,104,144,176,193,12,129,50,195,64,6,109,224,6,51,16,203,27,152,129,27,204,16,48,51,4,205,12,129,51,195,241,184,129,27, + 64,145,52,205,16,128,194,12,137,27,80,149,117,65,145,132,205,144,152,1,149,89,23,164,73,219,12,10,25,112,157,27,152,129,7,125,18,24,204,144,188,65,24,116,110,96,6,144,24,72,99,48,3, + 33,10,163,64,10,165,48,195,0,7,161,96,10,71,6,0,199,113,28,199,113,28,199,113,28,231,6,110,224,6,110,224,6,110,224,6,110,224,6,22,29,232,129,101,89,166,192,177,2,43,144,131,58,128, + 130,140,4,38,40,35,54,54,187,54,151,182,55,178,58,182,50,23,51,182,176,179,185,81,18,56,136,3,57,152,3,58,168,3,59,184,3,60,72,133,141,205,174,205,37,141,172,204,141,110,148,32,15, + 114,9,75,147,115,177,43,147,155,75,123,115,27,37,208,131,164,194,210,228,92,216,194,220,206,234,194,206,202,190,236,202,228,230,210,222,220,70,9,246,32,167,176,52,57,151,177,183,54, + 184,52,182,178,175,55,56,186,180,55,183,185,81,6,62,232,3,63,72,38,44,77,206,197,76,46,236,172,173,204,141,110,148,192,20,0,0,0,0,169,24,0,0,37,0,0,0,11,10,114,40,135,119,128,7,122, + 88,112,152,67,61,184,195,56,176,67,57,208,195,130,230,28,198,161,13,232,65,30,194,193,29,230,33,29,232,33,29,222,193,29,22,52,227,96,14,231,80,15,225,32,15,228,64,15,225,32,15,231, + 80,14,244,176,128,129,7,121,40,135,112,96,7,118,120,135,113,8,7,122,40,7,114,88,112,156,195,56,180,1,59,164,131,61,148,195,2,107,28,216,33,28,220,225,28,220,32,28,228,97,28,220,32, + 28,232,129,30,194,97,28,208,161,28,200,97,28,194,129,29,216,97,193,1,15,244,32,15,225,80,15,244,128,14,0,0,0,0,209,16,0,0,6,0,0,0,7,204,60,164,131,59,156,3,59,148,3,61,160,131,60,148, + 67,56,144,195,1,0,0,0,97,32,0,0,49,0,0,0,19,4,65,44,16,0,0,0,4,0,0,0,196,106,96,4,128,220,8,0,129,17,0,18,51,0,0,0,241,48,0,0,28,0,0,0,34,71,200,144,81,14,196,42,0,0,0,0,23,134,1,0, + 97,105,114,45,97,108,105,97,115,45,115,99,111,112,101,115,40,109,97,105,110,48,41,97,105,114,45,97,108,105,97,115,45,115,99,111,112,101,45,115,97,109,112,108,101,114,115,97,105,114, + 45,97,108,105,97,115,45,115,99,111,112,101,45,116,101,120,116,117,114,101,115,0,43,132,85,64,133,21,3,43,172,66,42,172,24,90,97,21,84,97,131,208,10,172,0,0,35,6,205,16,130,96,240,88, + 135,129,20,3,33,8,204,104,66,0,96,176,136,255,108,3,17,0,27,4,196,0,0,0,2,0,0,0,91,6,224,104,5,0,0,0,0,0,0,0,113,32,0,0,3,0,0,0,50,14,16,34,132,0,251,5,0,0,0,0,0,0,0,0,101,12,0,0,37, + 0,0,0,18,3,148,40,1,0,0,0,3,0,0,0,32,0,0,0,9,0,0,0,76,0,0,0,1,0,0,0,88,0,0,0,0,0,0,0,88,0,0,0,2,0,0,0,136,0,0,0,0,0,0,0,41,0,0,0,24,0,0,0,0,0,0,0,5,0,0,0,5,0,0,0,0,0,0,0,136,0,0,0, + 0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,5,0,0,0,255,255,255,255,0,36,0,0,5,0,0,0,27,0,0,0,5,0,0,0,27,0,0,0,255,255,255,255,8,36,0,0,0,0,0,0,93,12,0,0,20,0,0,0,18,3, + 148,161,0,0,0,0,109,97,105,110,48,97,105,114,46,115,97,109,112,108,101,95,116,101,120,116,117,114,101,95,50,100,46,118,52,102,51,50,51,50,48,50,51,46,51,54,56,97,105,114,54,52,45,97, + 112,112,108,101,45,109,97,99,111,115,120,49,52,46,48,46,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; +#elif TARGET_OS_IPHONE +const uint8_t metallib_vertex[3876] = { + 77,84,76,66,1,0,2,0,7,0,0,130,18,0,1,0,36,15,0,0,0,0,0,0,88,0,0,0,0,0,0,0,123,0,0,0,0,0,0,0,219,0,0,0,0,0,0,0,49,0,0,0,0,0,0,0,12,1,0,0,0,0,0,0,8,0,0,0,0,0,0,0,20,1,0,0,0,0,0,0,16, + 14,0,0,0,0,0,0,1,0,0,0,123,0,0,0,78,65,77,69,6,0,109,97,105,110,48,0,84,89,80,69,1,0,0,72,65,83,72,32,0,240,54,230,217,232,66,102,78,35,5,77,235,101,252,229,192,148,96,126,162,111, + 77,253,247,211,52,17,198,182,137,68,244,77,68,83,90,8,0,16,14,0,0,0,0,0,0,79,70,70,84,24,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,86,69,82,83,8,0,2,0,7,0,3,0,2,0,69,78,68, + 84,69,78,68,84,45,0,0,0,86,65,84,84,24,0,3,0,97,80,111,115,0,0,128,97,85,86,0,1,128,97,67,111,108,111,114,0,2,128,86,65,84,89,5,0,3,0,4,4,6,69,78,68,84,4,0,0,0,69,78,68,84,222,192, + 23,11,0,0,0,0,20,0,0,0,252,13,0,0,255,255,255,255,66,67,192,222,53,20,0,0,3,0,0,0,98,12,48,36,128,16,5,200,20,0,0,0,33,12,0,0,72,3,0,0,11,2,33,0,2,0,0,0,22,0,0,0,7,129,35,145,65,200, + 4,73,6,16,50,57,146,1,132,12,37,5,8,25,30,4,139,98,128,16,69,2,66,146,11,66,132,16,50,20,56,8,24,75,10,50,66,136,72,112,196,33,35,68,18,135,140,16,65,146,2,100,200,8,177,20,32,67,70, + 136,32,201,1,50,66,132,24,42,40,42,144,49,124,176,92,145,32,196,200,0,0,0,137,32,0,0,24,0,0,0,50,34,8,9,32,98,70,0,33,43,36,152,16,33,37,36,152,16,25,39,12,133,164,144,96,66,100,92, + 32,36,100,130,224,153,1,24,70,32,128,97,4,1,184,67,72,32,37,77,17,37,76,62,149,82,210,193,57,141,52,1,205,148,4,145,65,4,66,48,197,136,68,145,13,4,204,17,128,129,10,228,28,1,40,12, + 34,8,194,48,2,145,140,0,0,0,0,0,81,24,0,0,100,0,0,0,27,246,35,248,255,255,255,255,1,48,5,192,15,0,56,0,254,0,144,0,10,232,3,34,28,224,1,30,228,225,29,240,161,13,204,161,30,220,97,28, + 218,192,28,224,161,13,218,33,28,232,1,29,0,122,144,135,122,40,7,128,48,7,121,8,135,118,40,135,54,128,135,119,72,7,119,160,135,114,144,7,32,28,216,129,29,0,162,29,210,193,29,218,128, + 29,202,225,28,194,129,29,218,192,30,202,97,28,232,225,29,228,161,13,238,33,29,200,129,30,208,1,136,3,57,192,3,96,112,135,119,104,3,113,168,135,116,96,7,122,72,7,119,152,7,128,112,135, + 119,104,131,116,112,7,115,152,135,54,48,7,120,104,131,118,8,7,122,64,7,128,30,228,161,30,202,1,32,220,225,29,218,192,29,194,193,29,230,161,13,204,1,30,218,160,29,194,129,30,208,1,160, + 7,121,168,135,114,0,8,119,120,135,54,152,135,116,56,7,119,40,7,114,104,3,125,40,7,121,120,135,121,104,3,115,128,135,54,104,135,112,160,7,116,0,232,65,30,234,161,28,0,194,29,222,161, + 13,232,65,30,194,1,30,224,33,29,220,225,28,218,160,29,194,129,30,208,1,160,7,121,168,135,114,0,136,121,160,135,112,24,135,117,104,3,120,144,135,119,160,135,114,24,7,122,120,7,121,104, + 3,113,168,7,115,48,135,114,144,135,54,152,135,116,208,135,114,0,240,0,32,234,193,29,230,33,28,204,161,28,218,192,28,224,161,13,218,33,28,232,1,29,0,122,144,135,122,40,7,96,195,24,8, + 4,176,0,164,0,84,65,128,4,105,0,13,225,144,14,242,208,6,226,80,15,230,96,14,229,32,15,109,224,14,239,208,6,225,192,14,233,16,14,243,0,0,0,73,24,0,0,1,0,0,0,19,132,64,0,19,170,112,72, + 7,121,176,3,58,104,131,112,128,7,120,96,135,114,104,131,116,120,135,121,136,3,60,112,131,56,112,3,56,216,112,27,229,208,6,240,160,7,118,64,7,122,96,7,116,160,7,118,64,7,109,144,14, + 113,160,7,120,160,7,120,208,6,233,128,7,122,128,7,122,128,7,109,144,14,113,96,7,122,16,7,118,160,7,113,96,7,109,144,14,115,32,7,122,48,7,114,160,7,115,32,7,109,144,14,118,64,7,122, + 96,7,116,160,7,118,64,7,109,96,14,115,32,7,122,48,7,114,160,7,115,32,7,109,96,14,118,64,7,122,96,7,116,160,7,118,64,7,109,96,15,113,96,7,122,16,7,118,160,7,113,96,7,109,96,15,114,64, + 7,122,48,7,114,160,7,115,32,7,109,96,15,115,32,7,122,48,7,114,160,7,115,32,7,109,96,15,116,128,7,122,96,7,116,160,7,118,64,7,109,96,15,118,64,7,122,96,7,116,160,7,118,64,7,109,96,15, + 121,96,7,122,16,7,114,128,7,122,16,7,114,128,7,109,96,15,113,32,7,120,160,7,113,32,7,120,160,7,113,32,7,120,208,6,246,16,7,121,32,7,122,32,7,117,96,7,122,32,7,117,96,7,109,96,15,114, + 80,7,118,160,7,114,80,7,118,160,7,114,80,7,118,208,6,246,80,7,113,32,7,122,80,7,113,32,7,122,80,7,113,32,7,109,96,15,113,0,7,114,64,7,122,16,7,112,32,7,116,160,7,113,0,7,114,64,7,109, + 224,14,120,160,7,113,96,7,122,48,7,114,160,17,194,144,5,3,32,13,61,164,2,10,3,0,128,0,0,0,64,0,0,0,0,0,160,0,36,54,8,20,85,26,0,0,200,2,1,0,11,0,0,0,50,30,152,16,25,17,76,144,140,9, + 38,71,198,4,67,202,34,40,129,66,40,135,242,41,64,129,130,40,144,17,128,50,160,29,1,32,29,75,144,2,0,0,0,0,177,24,0,0,165,0,0,0,51,8,128,28,196,225,28,102,20,1,61,136,67,56,132,195, + 140,66,128,7,121,120,7,115,152,113,12,230,0,15,237,16,14,244,128,14,51,12,66,30,194,193,29,206,161,28,102,48,5,61,136,67,56,132,131,27,204,3,61,200,67,61,140,3,61,204,120,140,116,112, + 7,123,8,7,121,72,135,112,112,7,122,112,3,118,120,135,112,32,135,25,204,17,14,236,144,14,225,48,15,110,48,15,227,240,14,240,80,14,51,16,196,29,222,33,28,216,33,29,194,97,30,102,48,137, + 59,188,131,59,208,67,57,180,3,60,188,131,60,132,3,59,204,240,20,118,96,7,123,104,7,55,104,135,114,104,7,55,128,135,112,144,135,112,96,7,118,40,7,118,248,5,118,120,135,119,128,135,95, + 8,135,113,24,135,114,152,135,121,152,129,44,238,240,14,238,224,14,245,192,14,236,48,3,98,200,161,28,228,161,28,204,161,28,228,161,28,220,97,28,202,33,28,196,129,29,202,97,6,214,144, + 67,57,200,67,57,152,67,57,200,67,57,184,195,56,148,67,56,136,3,59,148,195,47,188,131,60,252,130,59,212,3,59,176,195,12,199,105,135,112,88,135,114,112,131,116,104,7,120,96,135,116,24, + 135,116,160,135,25,206,83,15,238,0,15,242,80,14,228,144,14,227,64,15,225,32,14,236,80,14,51,32,40,29,220,193,30,194,65,30,210,33,28,220,129,30,220,224,28,228,225,29,234,1,30,102,24, + 81,56,176,67,58,156,131,59,204,80,36,118,96,7,123,104,7,55,96,135,119,120,7,120,152,81,76,244,144,15,240,80,14,51,30,106,30,202,97,28,232,33,29,222,193,29,126,1,30,228,161,28,204,33, + 29,240,97,6,84,133,131,56,204,195,59,176,67,61,208,67,57,252,194,60,228,67,59,136,195,59,176,195,140,197,10,135,121,152,135,119,24,135,116,8,7,122,40,7,114,152,129,92,227,16,14,236, + 192,14,229,80,14,243,48,35,193,210,65,30,228,225,23,216,225,29,222,1,30,102,72,25,59,176,131,61,180,131,27,132,195,56,140,67,57,204,195,60,184,193,57,200,195,59,212,3,60,204,72,180, + 113,8,7,118,96,7,113,8,135,113,88,135,25,219,198,14,236,96,15,237,224,6,240,32,15,229,48,15,229,32,15,246,80,14,110,16,14,227,48,14,229,48,15,243,224,6,233,224,14,228,80,14,248,48, + 35,226,236,97,28,194,129,29,216,225,23,236,33,29,230,33,29,196,33,29,216,33,29,232,33,31,102,32,157,59,188,67,61,184,3,57,148,131,57,204,88,188,112,112,7,119,120,7,122,8,7,122,72,135, + 119,112,135,25,206,135,14,229,16,14,240,16,14,236,192,14,239,48,14,243,144,14,244,80,14,51,40,48,8,135,116,144,7,55,48,135,122,112,135,113,160,135,116,120,7,119,248,133,115,144,135, + 119,168,7,120,152,7,0,0,0,0,121,32,0,0,25,1,0,0,114,30,72,32,67,136,12,25,9,114,50,72,32,35,129,140,145,145,209,68,160,16,40,100,60,49,50,66,142,144,33,163,152,6,100,208,82,0,0,0,139, + 210,88,216,6,109,80,28,20,27,71,6,209,18,25,76,178,24,6,179,64,18,49,24,202,131,68,148,161,68,87,35,0,0,0,0,83,68,75,32,86,101,114,115,105,111,110,119,99,104,97,114,95,115,105,122, + 101,102,114,97,109,101,45,112,111,105,110,116,101,114,97,105,114,46,109,97,120,95,100,101,118,105,99,101,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,99,111,110,115,116, + 97,110,116,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,116,104,114,101,97,100,103,114,111,117,112,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,116,101,120, + 116,117,114,101,115,97,105,114,46,109,97,120,95,114,101,97,100,95,119,114,105,116,101,95,116,101,120,116,117,114,101,115,97,105,114,46,109,97,120,95,115,97,109,112,108,101,114,115, + 65,112,112,108,101,32,109,101,116,97,108,32,118,101,114,115,105,111,110,32,51,50,48,50,51,46,51,54,56,32,40,109,101,116,97,108,102,101,45,51,50,48,50,51,46,51,54,56,41,77,101,116,97, + 108,97,105,114,46,99,111,109,112,105,108,101,46,100,101,110,111,114,109,115,95,100,105,115,97,98,108,101,97,105,114,46,99,111,109,112,105,108,101,46,102,97,115,116,95,109,97,116,104, + 95,101,110,97,98,108,101,97,105,114,46,99,111,109,112,105,108,101,46,102,114,97,109,101,98,117,102,102,101,114,95,102,101,116,99,104,95,101,110,97,98,108,101,97,105,114,46,118,101, + 114,116,101,120,95,111,117,116,112,117,116,117,115,101,114,40,108,111,99,110,48,41,97,105,114,46,97,114,103,95,116,121,112,101,95,110,97,109,101,102,108,111,97,116,52,97,105,114,46, + 97,114,103,95,110,97,109,101,79,117,116,95,67,111,108,111,114,117,115,101,114,40,108,111,99,110,49,41,102,108,111,97,116,50,79,117,116,95,85,86,97,105,114,46,112,111,115,105,116,105, + 111,110,103,108,95,80,111,115,105,116,105,111,110,97,105,114,46,118,101,114,116,101,120,95,105,110,112,117,116,97,105,114,46,108,111,99,97,116,105,111,110,95,105,110,100,101,120,97, + 80,111,115,97,85,86,97,67,111,108,111,114,97,105,114,46,98,117,102,102,101,114,97,105,114,46,98,117,102,102,101,114,95,115,105,122,101,97,105,114,46,114,101,97,100,97,105,114,46,97, + 100,100,114,101,115,115,95,115,112,97,99,101,97,105,114,46,115,116,114,117,99,116,95,116,121,112,101,95,105,110,102,111,117,83,99,97,108,101,117,84,114,97,110,115,108,97,116,101,97, + 105,114,46,97,114,103,95,116,121,112,101,95,115,105,122,101,97,105,114,46,97,114,103,95,116,121,112,101,95,97,108,105,103,110,95,115,105,122,101,117,80,117,115,104,67,111,110,115,116, + 97,110,116,112,99,0,0,0,230,117,0,0,0,0,0,0,48,130,144,4,35,8,10,51,130,144,8,35,8,201,48,130,144,16,35,8,73,49,130,144,24,35,8,201,49,130,144,32,35,8,73,50,130,144,40,35,8,7,48,195, + 160,6,193,26,204,48,176,129,208,6,51,12,110,48,168,193,12,131,27,16,111,48,195,224,6,197,27,204,48,184,129,241,6,51,12,110,112,192,193,12,131,27,32,113,48,195,224,6,137,28,204,16,40, + 51,12,106,224,6,115,48,3,177,208,129,26,204,193,12,1,51,67,208,204,16,56,51,24,15,20,73,19,53,131,241,84,145,53,93,51,20,88,36,77,217,12,67,41,152,194,41,204,144,204,129,182,205,1, + 27,68,214,196,205,144,176,129,182,177,1,27,68,214,212,205,144,168,129,182,169,1,27,68,210,228,205,160,204,65,28,204,129,69,6,113,16,7,115,96,149,193,12,20,29,124,96,32,7,219,28,176, + 65,24,136,129,26,140,1,43,152,129,28,156,65,28,68,104,48,165,193,12,68,42,168,194,42,180,194,12,67,29,160,130,43,156,25,0,28,199,113,28,199,113,28,199,113,110,224,6,110,224,6,110,224, + 6,110,224,6,110,96,209,129,30,88,150,69,7,116,224,6,116,128,11,184,128,11,252,128,30,160,32,35,129,9,202,136,141,205,174,205,165,237,141,172,142,173,204,197,140,45,236,108,110,148, + 164,14,236,224,14,240,32,15,244,96,15,248,160,15,82,97,99,179,107,115,73,35,43,115,163,27,37,240,131,92,194,210,228,92,236,202,228,230,210,222,220,70,9,254,32,169,176,52,57,23,182, + 48,183,179,186,176,179,178,47,187,50,185,185,180,55,183,81,2,80,200,41,44,77,206,101,236,173,13,46,141,173,236,235,13,142,46,237,205,109,110,148,33,20,68,97,20,82,9,75,147,115,177, + 43,147,163,43,195,27,37,112,5,0,0,0,169,24,0,0,37,0,0,0,11,10,114,40,135,119,128,7,122,88,112,152,67,61,184,195,56,176,67,57,208,195,130,230,28,198,161,13,232,65,30,194,193,29,230, + 33,29,232,33,29,222,193,29,22,52,227,96,14,231,80,15,225,32,15,228,64,15,225,32,15,231,80,14,244,176,128,129,7,121,40,135,112,96,7,118,120,135,113,8,7,122,40,7,114,88,112,156,195,56, + 180,1,59,164,131,61,148,195,2,107,28,216,33,28,220,225,28,220,32,28,228,97,28,220,32,28,232,129,30,194,97,28,208,161,28,200,97,28,194,129,29,216,97,193,1,15,244,32,15,225,80,15,244, + 128,14,0,0,0,0,209,16,0,0,6,0,0,0,7,204,60,164,131,59,156,3,59,148,3,61,160,131,60,148,67,56,144,195,1,0,0,0,97,32,0,0,68,0,0,0,19,4,65,44,16,0,0,0,11,0,0,0,148,51,0,197,64,91,2,212, + 115,16,73,20,69,115,16,73,36,17,4,163,1,35,0,99,4,32,8,130,248,71,49,7,97,89,23,70,50,26,64,51,3,0,0,0,241,48,0,0,32,0,0,0,34,71,200,144,81,18,196,43,0,0,0,0,207,115,89,0,111,109,110, + 105,112,111,116,101,110,116,32,99,104,97,114,83,105,109,112,108,101,32,67,43,43,32,84,66,65,65,97,105,114,45,97,108,105,97,115,45,115,99,111,112,101,115,40,109,97,105,110,48,41,97, + 105,114,45,97,108,105,97,115,45,115,99,111,112,101,45,97,114,103,40,51,41,0,19,132,101,89,33,212,130,44,172,24,108,161,22,102,97,67,16,11,27,6,88,184,5,90,216,48,224,2,46,208,194,134, + 192,22,0,0,157,6,38,154,40,16,130,65,36,254,157,134,135,234,40,16,130,67,0,254,131,12,1,226,12,50,4,138,51,134,48,68,22,128,255,28,195,16,76,179,13,12,6,204,54,4,90,48,219,16,12,194, + 6,1,49,0,4,0,0,0,91,138,32,192,133,35,23,182,20,68,128,11,71,46,0,0,0,0,0,0,113,32,0,0,3,0,0,0,50,14,16,34,132,0,132,6,0,0,0,0,0,0,0,0,101,12,0,0,31,0,0,0,18,3,148,240,0,0,0,0,3,0, + 0,0,5,0,0,0,9,0,0,0,76,0,0,0,1,0,0,0,88,0,0,0,0,0,0,0,88,0,0,0,1,0,0,0,112,0,0,0,0,0,0,0,14,0,0,0,21,0,0,0,0,0,0,0,5,0,0,0,5,0,0,0,0,0,0,0,112,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, + 0,0,0,0,5,0,0,0,0,0,0,0,5,0,0,0,255,255,255,255,0,36,0,0,0,0,0,0,93,12,0,0,12,0,0,0,18,3,148,99,0,0,0,0,109,97,105,110,48,51,50,48,50,51,46,51,54,56,97,105,114,54,52,45,97,112,112, + 108,101,45,105,111,115,49,56,46,49,46,48,0,0,0,0,0, +}; +const uint8_t metallib_fragment[3771] = { + 77,84,76,66,1,0,2,0,7,0,0,130,18,0,1,0,187,14,0,0,0,0,0,0,88,0,0,0,0,0,0,0,123,0,0,0,0,0,0,0,219,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,227,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,235,0,0,0,0,0,0,0,208, + 13,0,0,0,0,0,0,1,0,0,0,123,0,0,0,78,65,77,69,6,0,109,97,105,110,48,0,84,89,80,69,1,0,1,72,65,83,72,32,0,167,26,51,31,140,153,203,226,66,149,243,47,185,58,96,202,28,176,71,121,86,159, + 244,234,235,69,155,58,121,67,241,212,77,68,83,90,8,0,208,13,0,0,0,0,0,0,79,70,70,84,24,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,86,69,82,83,8,0,2,0,7,0,3,0,2,0,69,78,68,84, + 69,78,68,84,4,0,0,0,69,78,68,84,4,0,0,0,69,78,68,84,222,192,23,11,0,0,0,0,20,0,0,0,180,13,0,0,255,255,255,255,66,67,192,222,53,20,0,0,3,0,0,0,98,12,48,36,128,16,5,200,20,0,0,0,33,12, + 0,0,41,3,0,0,11,2,33,0,2,0,0,0,22,0,0,0,7,129,35,145,65,200,4,73,6,16,50,57,146,1,132,12,37,5,8,25,30,4,139,98,128,20,69,2,66,146,11,66,164,16,50,20,56,8,24,75,10,50,82,136,72,112, + 196,33,35,68,18,135,140,16,65,146,2,100,200,8,177,20,32,67,70,136,32,201,1,50,82,132,24,42,40,42,144,49,124,176,92,145,32,197,200,0,0,0,137,32,0,0,31,0,0,0,50,34,72,9,32,98,70,0,33, + 43,36,152,20,33,37,36,152,20,25,39,12,133,164,144,96,82,100,92,32,36,101,130,128,154,1,24,70,32,128,27,132,97,4,1,64,74,154,34,74,152,252,127,34,174,137,138,136,223,30,254,105,140, + 0,24,68,32,2,140,164,41,162,132,201,255,37,128,121,22,34,250,167,49,2,96,16,193,16,76,33,194,40,135,208,28,1,114,132,160,230,8,130,57,2,48,24,70,16,26,163,172,114,6,115,12,128,70,111, + 32,64,5,218,8,0,0,81,24,0,0,105,0,0,0,27,246,35,248,255,255,255,255,1,104,3,96,13,0,83,0,252,0,144,128,10,232,3,34,28,224,1,30,228,225,29,240,161,13,204,161,30,220,97,28,218,192,28, + 224,161,13,218,33,28,232,1,29,0,122,144,135,122,40,7,128,48,7,121,8,135,118,40,135,54,128,135,119,72,7,119,160,135,114,144,7,32,28,216,129,29,0,162,29,210,193,29,218,128,29,202,225, + 28,194,129,29,218,192,30,202,97,28,232,225,29,228,161,13,238,33,29,200,129,30,208,1,136,3,57,192,3,96,112,135,119,104,3,113,168,135,116,96,7,122,72,7,119,152,7,128,112,135,119,104, + 131,116,112,7,115,152,135,54,48,7,120,104,131,118,8,7,122,64,7,128,30,228,161,30,202,1,32,220,225,29,218,192,29,194,193,29,230,161,13,204,1,30,218,160,29,194,129,30,208,1,160,7,121, + 168,135,114,0,8,119,120,135,54,152,135,116,56,7,119,40,7,114,104,3,125,40,7,121,120,135,121,104,3,115,128,135,54,104,135,112,160,7,116,0,232,65,30,234,161,28,0,194,29,222,161,13,232, + 65,30,194,1,30,224,33,29,220,225,28,218,160,29,194,129,30,208,1,160,7,121,168,135,114,0,136,121,160,135,112,24,135,117,104,3,120,144,135,119,160,135,114,24,7,122,120,7,121,104,3,113, + 168,7,115,48,135,114,144,135,54,152,135,116,208,135,114,0,240,0,32,234,193,29,230,33,28,204,161,28,218,192,28,224,161,13,218,33,28,232,1,29,0,122,144,135,122,40,7,96,131,33,12,192, + 2,84,27,140,129,0,22,160,218,0,17,255,255,255,255,63,0,109,0,172,1,96,10,128,31,0,18,80,1,125,176,193,40,2,96,1,170,13,134,33,0,11,80,109,96,142,255,255,255,255,31,128,54,0,214,0,144, + 128,10,232,3,0,73,24,0,0,4,0,0,0,19,134,64,24,38,12,68,97,76,24,142,194,0,0,0,0,19,170,112,72,7,121,176,3,58,104,131,112,128,7,120,96,135,114,104,131,116,120,135,121,136,3,60,112,131, + 56,112,3,56,216,112,27,229,208,6,240,160,7,118,64,7,122,96,7,116,160,7,118,64,7,109,144,14,113,160,7,120,160,7,120,208,6,233,128,7,122,128,7,122,128,7,109,144,14,113,96,7,122,16,7, + 118,160,7,113,96,7,109,144,14,115,32,7,122,48,7,114,160,7,115,32,7,109,144,14,118,64,7,122,96,7,116,160,7,118,64,7,109,96,14,115,32,7,122,48,7,114,160,7,115,32,7,109,96,14,118,64,7, + 122,96,7,116,160,7,118,64,7,109,96,15,113,96,7,122,16,7,118,160,7,113,96,7,109,96,15,114,64,7,122,48,7,114,160,7,115,32,7,109,96,15,115,32,7,122,48,7,114,160,7,115,32,7,109,96,15,116, + 128,7,122,96,7,116,160,7,118,64,7,109,96,15,118,64,7,122,96,7,116,160,7,118,64,7,109,96,15,121,96,7,122,16,7,114,128,7,122,16,7,114,128,7,109,96,15,113,32,7,120,160,7,113,32,7,120, + 160,7,113,32,7,120,208,6,246,16,7,121,32,7,122,32,7,117,96,7,122,32,7,117,96,7,109,96,15,114,80,7,118,160,7,114,80,7,118,160,7,114,80,7,118,208,6,246,80,7,113,32,7,122,80,7,113,32, + 7,122,80,7,113,32,7,109,96,15,113,0,7,114,64,7,122,16,7,112,32,7,116,160,7,113,0,7,114,64,7,109,224,14,120,160,7,113,96,7,122,48,7,114,160,17,194,144,5,3,32,13,61,164,2,10,4,0,128, + 0,0,0,64,0,0,0,0,0,160,0,134,84,197,246,0,1,32,0,0,0,8,0,0,0,0,0,20,128,196,6,129,162,43,3,0,0,89,32,10,0,0,0,50,30,152,16,25,17,76,144,140,9,38,71,198,4,67,106,69,80,2,133,80,14,229, + 83,128,2,5,81,32,35,0,101,64,114,44,65,10,0,0,0,177,24,0,0,165,0,0,0,51,8,128,28,196,225,28,102,20,1,61,136,67,56,132,195,140,66,128,7,121,120,7,115,152,113,12,230,0,15,237,16,14,244, + 128,14,51,12,66,30,194,193,29,206,161,28,102,48,5,61,136,67,56,132,131,27,204,3,61,200,67,61,140,3,61,204,120,140,116,112,7,123,8,7,121,72,135,112,112,7,122,112,3,118,120,135,112,32, + 135,25,204,17,14,236,144,14,225,48,15,110,48,15,227,240,14,240,80,14,51,16,196,29,222,33,28,216,33,29,194,97,30,102,48,137,59,188,131,59,208,67,57,180,3,60,188,131,60,132,3,59,204, + 240,20,118,96,7,123,104,7,55,104,135,114,104,7,55,128,135,112,144,135,112,96,7,118,40,7,118,248,5,118,120,135,119,128,135,95,8,135,113,24,135,114,152,135,121,152,129,44,238,240,14, + 238,224,14,245,192,14,236,48,3,98,200,161,28,228,161,28,204,161,28,228,161,28,220,97,28,202,33,28,196,129,29,202,97,6,214,144,67,57,200,67,57,152,67,57,200,67,57,184,195,56,148,67, + 56,136,3,59,148,195,47,188,131,60,252,130,59,212,3,59,176,195,12,199,105,135,112,88,135,114,112,131,116,104,7,120,96,135,116,24,135,116,160,135,25,206,83,15,238,0,15,242,80,14,228, + 144,14,227,64,15,225,32,14,236,80,14,51,32,40,29,220,193,30,194,65,30,210,33,28,220,129,30,220,224,28,228,225,29,234,1,30,102,24,81,56,176,67,58,156,131,59,204,80,36,118,96,7,123,104, + 7,55,96,135,119,120,7,120,152,81,76,244,144,15,240,80,14,51,30,106,30,202,97,28,232,33,29,222,193,29,126,1,30,228,161,28,204,33,29,240,97,6,84,133,131,56,204,195,59,176,67,61,208,67, + 57,252,194,60,228,67,59,136,195,59,176,195,140,197,10,135,121,152,135,119,24,135,116,8,7,122,40,7,114,152,129,92,227,16,14,236,192,14,229,80,14,243,48,35,193,210,65,30,228,225,23,216, + 225,29,222,1,30,102,72,25,59,176,131,61,180,131,27,132,195,56,140,67,57,204,195,60,184,193,57,200,195,59,212,3,60,204,72,180,113,8,7,118,96,7,113,8,135,113,88,135,25,219,198,14,236, + 96,15,237,224,6,240,32,15,229,48,15,229,32,15,246,80,14,110,16,14,227,48,14,229,48,15,243,224,6,233,224,14,228,80,14,248,48,35,226,236,97,28,194,129,29,216,225,23,236,33,29,230,33, + 29,196,33,29,216,33,29,232,33,31,102,32,157,59,188,67,61,184,3,57,148,131,57,204,88,188,112,112,7,119,120,7,122,8,7,122,72,135,119,112,135,25,206,135,14,229,16,14,240,16,14,236,192, + 14,239,48,14,243,144,14,244,80,14,51,40,48,8,135,116,144,7,55,48,135,122,112,135,113,160,135,116,120,7,119,248,133,115,144,135,119,168,7,120,152,7,0,0,0,0,121,32,0,0,251,0,0,0,114, + 30,72,32,67,136,12,25,9,114,50,72,32,35,129,140,145,145,209,68,160,16,40,100,60,49,50,66,142,144,33,163,56,6,220,41,1,0,0,0,139,210,88,216,6,109,80,28,20,27,71,6,81,100,48,134,180, + 40,15,178,24,197,34,41,24,178,28,13,83,68,75,32,86,101,114,115,105,111,110,119,99,104,97,114,95,115,105,122,101,102,114,97,109,101,45,112,111,105,110,116,101,114,97,105,114,46,109, + 97,120,95,100,101,118,105,99,101,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,99,111,110,115,116,97,110,116,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,116, + 104,114,101,97,100,103,114,111,117,112,95,98,117,102,102,101,114,115,97,105,114,46,109,97,120,95,116,101,120,116,117,114,101,115,97,105,114,46,109,97,120,95,114,101,97,100,95,119,114, + 105,116,101,95,116,101,120,116,117,114,101,115,97,105,114,46,109,97,120,95,115,97,109,112,108,101,114,115,65,112,112,108,101,32,109,101,116,97,108,32,118,101,114,115,105,111,110,32, + 51,50,48,50,51,46,51,54,56,32,40,109,101,116,97,108,102,101,45,51,50,48,50,51,46,51,54,56,41,77,101,116,97,108,97,105,114,46,99,111,109,112,105,108,101,46,100,101,110,111,114,109,115, + 95,100,105,115,97,98,108,101,97,105,114,46,99,111,109,112,105,108,101,46,102,97,115,116,95,109,97,116,104,95,101,110,97,98,108,101,97,105,114,46,99,111,109,112,105,108,101,46,102,114, + 97,109,101,98,117,102,102,101,114,95,102,101,116,99,104,95,101,110,97,98,108,101,97,105,114,46,114,101,110,100,101,114,95,116,97,114,103,101,116,97,105,114,46,97,114,103,95,116,121, + 112,101,95,110,97,109,101,102,108,111,97,116,52,97,105,114,46,97,114,103,95,110,97,109,101,102,67,111,108,111,114,97,105,114,46,102,114,97,103,109,101,110,116,95,105,110,112,117,116, + 117,115,101,114,40,108,111,99,110,48,41,97,105,114,46,99,101,110,116,101,114,97,105,114,46,112,101,114,115,112,101,99,116,105,118,101,73,110,95,67,111,108,111,114,117,115,101,114,40, + 108,111,99,110,49,41,102,108,111,97,116,50,73,110,95,85,86,97,105,114,46,116,101,120,116,117,114,101,97,105,114,46,108,111,99,97,116,105,111,110,95,105,110,100,101,120,97,105,114,46, + 115,97,109,112,108,101,116,101,120,116,117,114,101,50,100,60,102,108,111,97,116,44,32,115,97,109,112,108,101,62,115,84,101,120,116,117,114,101,97,105,114,46,115,97,109,112,108,101, + 114,115,97,109,112,108,101,114,115,84,101,120,116,117,114,101,83,109,112,108,114,0,6,95,0,0,0,0,0,0,48,130,208,8,35,8,18,51,130,208,12,35,8,13,49,130,208,20,35,8,141,49,130,208,28, + 35,8,13,50,130,208,36,35,8,141,50,130,208,44,35,8,9,48,195,64,6,65,25,204,48,152,129,112,6,51,12,104,48,144,193,12,3,26,16,105,48,195,128,6,69,26,204,48,160,129,145,6,51,12,104,112, + 168,193,12,3,26,32,107,48,195,128,6,9,27,204,16,40,51,12,100,128,6,109,48,3,177,184,1,25,180,193,12,1,51,67,208,204,16,56,51,28,79,27,180,1,20,73,211,12,193,31,204,144,180,1,85,89, + 23,20,73,216,12,137,25,80,153,117,65,154,180,205,160,144,1,215,181,129,25,120,208,39,129,193,12,137,27,132,65,215,6,102,0,137,129,52,6,51,16,161,32,10,163,64,10,51,12,111,0,10,165, + 112,99,0,112,28,199,113,28,199,113,28,199,185,129,27,184,129,27,184,129,27,184,129,27,184,129,69,7,122,96,89,150,41,112,172,192,10,228,160,14,160,32,35,129,9,202,136,141,205,174,205, + 165,237,141,172,142,173,204,197,140,45,236,108,110,148,228,13,224,32,14,228,96,14,232,160,14,236,224,14,82,97,99,179,107,115,73,35,43,115,163,27,37,192,131,92,194,210,228,92,236,202, + 228,230,210,222,220,70,9,242,32,169,176,52,57,23,182,48,183,179,186,176,179,178,47,187,50,185,185,180,55,183,81,2,61,200,41,44,77,206,101,236,173,13,46,141,173,236,235,13,142,46,237, + 205,109,110,148,97,15,248,160,15,146,9,75,147,115,49,147,11,59,107,43,115,163,27,37,40,5,0,0,0,0,169,24,0,0,37,0,0,0,11,10,114,40,135,119,128,7,122,88,112,152,67,61,184,195,56,176, + 67,57,208,195,130,230,28,198,161,13,232,65,30,194,193,29,230,33,29,232,33,29,222,193,29,22,52,227,96,14,231,80,15,225,32,15,228,64,15,225,32,15,231,80,14,244,176,128,129,7,121,40,135, + 112,96,7,118,120,135,113,8,7,122,40,7,114,88,112,156,195,56,180,1,59,164,131,61,148,195,2,107,28,216,33,28,220,225,28,220,32,28,228,97,28,220,32,28,232,129,30,194,97,28,208,161,28, + 200,97,28,194,129,29,216,97,193,1,15,244,32,15,225,80,15,244,128,14,0,0,0,0,209,16,0,0,6,0,0,0,7,204,60,164,131,59,156,3,59,148,3,61,160,131,60,148,67,56,144,195,1,0,0,0,97,32,0,0, + 49,0,0,0,19,4,65,44,16,0,0,0,4,0,0,0,196,106,96,4,128,220,8,0,129,17,0,18,51,0,0,0,241,48,0,0,28,0,0,0,34,71,200,144,81,14,196,42,0,0,0,0,23,134,1,0,97,105,114,45,97,108,105,97,115, + 45,115,99,111,112,101,115,40,109,97,105,110,48,41,97,105,114,45,97,108,105,97,115,45,115,99,111,112,101,45,115,97,109,112,108,101,114,115,97,105,114,45,97,108,105,97,115,45,115,99, + 111,112,101,45,116,101,120,116,117,114,101,115,0,43,4,85,56,133,21,195,42,168,2,42,172,24,88,65,21,82,97,131,192,10,171,0,0,35,6,205,16,130,96,240,84,135,129,20,3,33,8,204,104,66,0, + 96,176,136,255,108,3,17,0,27,4,196,0,0,0,2,0,0,0,91,6,224,96,5,0,0,0,0,0,0,0,113,32,0,0,3,0,0,0,50,14,16,34,132,0,248,5,0,0,0,0,0,0,0,0,101,12,0,0,37,0,0,0,18,3,148,40,1,0,0,0,3,0, + 0,0,32,0,0,0,9,0,0,0,76,0,0,0,1,0,0,0,88,0,0,0,0,0,0,0,88,0,0,0,2,0,0,0,136,0,0,0,0,0,0,0,41,0,0,0,21,0,0,0,0,0,0,0,5,0,0,0,5,0,0,0,0,0,0,0,136,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0, + 0,0,0,0,0,5,0,0,0,0,0,0,0,5,0,0,0,255,255,255,255,0,36,0,0,5,0,0,0,27,0,0,0,5,0,0,0,27,0,0,0,255,255,255,255,8,36,0,0,0,0,0,0,93,12,0,0,19,0,0,0,18,3,148,126,0,0,0,0,109,97,105,110, + 48,97,105,114,46,115,97,109,112,108,101,95,116,101,120,116,117,114,101,95,50,100,46,118,52,102,51,50,51,50,48,50,51,46,51,54,56,97,105,114,54,52,45,97,112,112,108,101,45,105,111,115, + 49,56,46,49,46,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; +#elif TARGET_IPHONE_SIMULATOR +#error "SDL_GPU does not support the iphone simulator" +#endif +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/backends/sdlgpu3/build_instructions.txt b/backends/sdlgpu3/build_instructions.txt new file mode 100644 index 000000000..751dc97a4 --- /dev/null +++ b/backends/sdlgpu3/build_instructions.txt @@ -0,0 +1,36 @@ +1) Compile the raw shader files to SPIRV: + + glslc -o vertex.spv -c shader.vert + glslc -o fragment.spv -c shader.frag + + +2) Build SDL_shadercross (https://github.com/libsdl-org/SDL_shadercross) + + +3-A) Compiling for the Vulkan Driver: + + Nothing to do, you just need the previous vertex.spv/fragment.spv, proceed to step 4 + + +3-B) Compiling for the DirectX 12 Driver: + + ./shadercross vertex.spv -s SPIRV -d DXBC -t vertex -e main -o vertex.dxbc + ./shadercross fragment.spv -s SPIRV -d DXBC -t fragment -e main -o fragment.dxbc + + Proceed to step 4 + + +3-C) Compiling for Metal (On windows you'll need the Metal Developer Tools for Windows, on linux you might use wine, but I never tested it): + + ./shadercross vertex.spv -s SPIRV -d MSL -t vertex -e main -o vertex.metal + ./shadercross fragment.spv -s SPIRV -d MSL -t fragment -e main -o fragment.metal + + xcrun -sdk macosx metal -o vertex.ir -c vertex.metal + xcrun -sdk macosx metal -o fragment.ir -c fragment.metal + xcrun -sdk macosx metallib -o vertex.metallib -c vertex.ir + xcrun -sdk macosx metallib -o fragment.metallib -c fragment.ir + + Proceed to step 4 + + +4) Either find a way to load the shader bytecode from file, or use a tool like https://notisrac.github.io/FileToCArray/ to convert the file to a uint8_t array \ No newline at end of file diff --git a/backends/sdlgpu3/shader.frag b/backends/sdlgpu3/shader.frag new file mode 100644 index 000000000..2de1f76a3 --- /dev/null +++ b/backends/sdlgpu3/shader.frag @@ -0,0 +1,14 @@ +#version 450 core +layout(location = 0) out vec4 fColor; + +layout(set=2, binding=0) uniform sampler2D sTexture; + +layout(location = 0) in struct { + vec4 Color; + vec2 UV; +} In; + +void main() +{ + fColor = In.Color * texture(sTexture, In.UV.st); +} \ No newline at end of file diff --git a/backends/sdlgpu3/shader.vert b/backends/sdlgpu3/shader.vert new file mode 100644 index 000000000..3363da8b2 --- /dev/null +++ b/backends/sdlgpu3/shader.vert @@ -0,0 +1,22 @@ +#version 450 core +layout(location = 0) in vec2 aPos; +layout(location = 1) in vec2 aUV; +layout(location = 2) in vec4 aColor; + +layout(set=1,binding=0) uniform UBO { + vec2 uScale; + vec2 uTranslate; +} ubo; + +layout(location = 0) out struct { + vec4 Color; + vec2 UV; +} Out; + +void main() +{ + Out.Color = aColor; + Out.UV = aUV; + gl_Position = vec4(aPos * ubo.uScale + ubo.uTranslate, 0, 1); + gl_Position.y *= -1.0f; +} \ No newline at end of file diff --git a/examples/example_sdl3_sdlgpu3/Makefile b/examples/example_sdl3_sdlgpu3/Makefile new file mode 100644 index 000000000..f6239e0fa --- /dev/null +++ b/examples/example_sdl3_sdlgpu3/Makefile @@ -0,0 +1,73 @@ +# +# Cross Platform Makefile +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X +# +# You will need SDL3 (http://www.libsdl.org) which is still unreleased/unpackaged. + +#CXX = g++ +#CXX = clang++ + +EXE = example_sdl3_sdlgpu3 +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl3.cpp $(IMGUI_DIR)/backends/imgui_impl_sdlgpu3.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) + +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS += -g -Wall -Wformat +LIBS = + + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- + +ifeq ($(UNAME_S), Linux) #LINUX + ECHO_MESSAGE = "Linux" + LIBS += -ldl `pkg-config sdl3 --libs` + + CXXFLAGS += `pkg-config sdl3 --cflags` + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(UNAME_S), Darwin) #APPLE + ECHO_MESSAGE = "Mac OS X" + LIBS += -framework Cocoa -framework IOKit -framework CoreVideo `pkg-config --libs sdl3` + LIBS += -L/usr/local/lib -L/opt/local/lib + + CXXFLAGS += `pkg-config sdl3 --cflags` + CXXFLAGS += -I/usr/local/include -I/opt/local/include + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(OS), Windows_NT) + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -limm32 `pkg-config --static --libs sdl3` + + CXXFLAGS += `pkg-config --cflags sdl3` + CFLAGS = $(CXXFLAGS) +endif + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(ECHO_MESSAGE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/examples/example_sdl3_sdlgpu3/build_win64.bat b/examples/example_sdl3_sdlgpu3/build_win64.bat new file mode 100644 index 000000000..ad7a2d603 --- /dev/null +++ b/examples/example_sdl3_sdlgpu3/build_win64.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. + +@set OUT_EXE=example_sdl3_sdlgpu3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_sdlgpu3.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x64 SDL3.lib shell32.lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj b/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj new file mode 100644 index 000000000..3d034f52c --- /dev/null +++ b/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj @@ -0,0 +1,189 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {c22cb6f8-39a5-4dda-90ed-4aca4e81e1e5} + example_sdl3_sdlgpu3 + 8.1 + + + + Application + true + MultiByte + v140 + + + Application + true + MultiByte + v140 + + + Application + false + true + MultiByte + v140 + + + Application + false + true + MultiByte + v140 + + + + + + + + + + + + + + + + + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + + Level4 + Disabled + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + _MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) + + + true + %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) + SDL3.lib;%(AdditionalDependencies) + Console + msvcrt.lib + + + + + Level4 + Disabled + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + _MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) + + + true + %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) + SDL3.lib;%(AdditionalDependencies) + Console + msvcrt.lib + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + false + _MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) + + + true + true + true + %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) + SDL3.lib;%(AdditionalDependencies) + Console + + + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + false + _MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) + + + true + true + true + %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) + SDL3.lib;%(AdditionalDependencies) + Console + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj.filters b/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj.filters new file mode 100644 index 000000000..4710b550c --- /dev/null +++ b/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj.filters @@ -0,0 +1,60 @@ + + + + + sources + + + sources + + + sources + + + imgui + + + imgui + + + imgui + + + imgui + + + imgui + + + + + sources + + + sources + + + sources + + + imgui + + + imgui + + + imgui + + + + + + + + {9044ef92-2afa-42f2-92df-ac473c7c32b3} + + + {ef84458b-039a-4902-8455-4e33df5a8578} + + + \ No newline at end of file diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp new file mode 100644 index 000000000..6c29962dd --- /dev/null +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -0,0 +1,210 @@ +// Dear ImGui: standalone example application for SDL_Gpu + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. +// - Unline other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. +// Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. + +#include "imgui.h" +#include "imgui_impl_sdl3.h" +#include "imgui_impl_sdlgpu3.h" +#include // printf, fprintf +#include // abort +#include + + +// This example doesn't compile with Emscripten yet! Awaiting SDL3 support. +#ifdef __EMSCRIPTEN__ +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#endif + +// Main code +int main(int, char**) +{ + // Setup SDL + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD) != 0) + { + printf("Error: SDL_Init(): %s\n", SDL_GetError()); + return -1; + } + + // Create SDL window graphics context + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDLGpu example", 1280, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } + + // Create SDL Gpu Device + SDL_GPUDevice* gpuDevice = SDL_CreateGPUDevice(SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_DXIL | SDL_GPU_SHADERFORMAT_METALLIB,true,nullptr); + if (gpuDevice == nullptr) + { + printf("Error: SDL_CreateGPUDevice(): %s\n", SDL_GetError()); + return -1; + } + + // Claim window for GPU Device + if (!SDL_ClaimWindowForGPUDevice(gpuDevice, window)) + { + printf("Error: SDL_ClaimWindowForGPUDevice(): %s\n", SDL_GetError()); + return -1; + } + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup Platform/Renderer backends + ImGui_ImplSDL3_InitForOther(window); + ImGui_ImplSDLGPU_InitInfo init_info = {}; + init_info.GpuDevice = gpuDevice; + init_info.ColorTargetFormat = SDL_GetGPUSwapchainTextureFormat(gpuDevice, window); + init_info.MSAASamples = SDL_GPU_SAMPLECOUNT_1; + ImGui_ImplSDLGPU_Init(&init_info); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; + while (!done) + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL3_ProcessEvent(&event); + if (event.type == SDL_EVENT_QUIT) + done = true; + if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) + done = true; + } + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } + + // Start the Dear ImGui frame + ImGui_ImplSDLGPU_NewFrame(); + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + ImDrawData* draw_data = ImGui::GetDrawData(); + const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); + + // Acquire a GPU command buffer + SDL_GPUCommandBuffer* command_buffer = SDL_AcquireGPUCommandBuffer(gpuDevice); + + //Acquire a swapchain texture + SDL_GPUTexture* swapchain_texture; + SDL_AcquireGPUSwapchainTexture(command_buffer, window, &swapchain_texture, nullptr, nullptr); + + if (swapchain_texture != nullptr && !is_minimized) + { + // !!! THIS IS MANDATORY !!! + // Call Imgui_ImplSDLGPU_PrepareDrawData to upload the vertex/index buffer + Imgui_ImplSDLGPU_PrepareDrawData(draw_data, command_buffer); + + // Setup and start a render pass + SDL_GPUColorTargetInfo target_info = {}; + target_info.texture = swapchain_texture; + target_info.clear_color = SDL_FColor{ clear_color.x,clear_color.y,clear_color.z,clear_color.w }; + target_info.load_op = SDL_GPU_LOADOP_CLEAR; + target_info.store_op = SDL_GPU_STOREOP_STORE; + target_info.mip_level = 0; + target_info.layer_or_depth_plane = 0; + target_info.cycle = false; + SDL_GPURenderPass* render_pass = SDL_BeginGPURenderPass(command_buffer, &target_info, 1, nullptr); + /// Render ImGui + ImGui_ImplSDLGPU_RenderDrawData(draw_data, command_buffer, render_pass); + SDL_EndGPURenderPass(render_pass); + } + // Submit the command buffer + SDL_SubmitGPUCommandBuffer(command_buffer); + } + // Cleanup + SDL_WaitForGPUIdle(gpuDevice); + ImGui_ImplSDL3_Shutdown(); + ImGui_ImplSDLGPU_Shutdown(); + ImGui::DestroyContext(); + SDL_ReleaseWindowFromGPUDevice(gpuDevice, window); + SDL_DestroyGPUDevice(gpuDevice); + SDL_DestroyWindow(window); + SDL_Quit(); + return 0; +} diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index 85f7451d4..cf1c5ad50 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -37,6 +37,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_vulkan", "exam EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_vulkan", "example_win32_vulkan\example_win32_vulkan.vcxproj", "{0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlgpu3", "example_sdl3_sdlgpu3\example_sdl3_sdlgpu3.vcxproj", "{C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -181,6 +183,14 @@ Global {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Release|Win32.Build.0 = Release|Win32 {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Release|x64.ActiveCfg = Release|x64 {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88}.Release|x64.Build.0 = Release|x64 + {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Debug|Win32.ActiveCfg = Debug|Win32 + {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Debug|Win32.Build.0 = Debug|Win32 + {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Debug|x64.ActiveCfg = Debug|x64 + {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Debug|x64.Build.0 = Debug|x64 + {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Release|Win32.ActiveCfg = Release|Win32 + {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Release|Win32.Build.0 = Release|Win32 + {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Release|x64.ActiveCfg = Release|x64 + {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From e79984927266f9b44302b2b43e70cf674513cffd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 9 Jan 2025 16:08:14 +0100 Subject: [PATCH 0592/2359] Backends: SDLGPU3: Added sdl_gpu backend (amends). (#8163, #7998, #7988) --- backends/imgui_impl_sdlgpu3.cpp | 299 ++++++++++++------------ backends/imgui_impl_sdlgpu3.h | 18 +- backends/sdlgpu3/build_instructions.txt | 6 +- backends/sdlgpu3/shader.frag | 5 +- backends/sdlgpu3/shader.vert | 8 +- backends/vulkan/build_instructions.txt | 4 + docs/CHANGELOG.txt | 1 + docs/EXAMPLES.md | 24 +- docs/README.md | 2 +- examples/example_sdl3_sdlgpu3/main.cpp | 53 ++--- 10 files changed, 220 insertions(+), 200 deletions(-) create mode 100644 backends/vulkan/build_instructions.txt diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 31e899b77..e681efdc3 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -1,4 +1,4 @@ -// dear imgui: Renderer Backend for SDL_Gpu +// dear imgui: Renderer Backend for SDL_GPU // This needs to be used along with the SDL3 Platform Backend // Implemented features: @@ -17,19 +17,19 @@ // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. -// - Unline other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. +// - Unlike other backends, the user must call the function Imgui_ImplSDLGPU3_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU3_RenderDrawData. // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG -// 2024-11-18: SDL_Gpu: Added the SDL_Gpu backend. +// 2025-01-09: SDL_Gpu: Added the SDL_GPU3 backend. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_sdlgpu3.h" #include "imgui_impl_sdlgpu3_shaders.h" -// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU_RenderDrawData() -struct ImGui_ImplSDLGPU_FrameData +// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData() +struct ImGui_ImplSDLGPU3_FrameData { SDL_GPUBuffer* VertexBuffer = nullptr; SDL_GPUBuffer* IndexBuffer = nullptr; @@ -37,10 +37,10 @@ struct ImGui_ImplSDLGPU_FrameData uint32_t IndexBufferSize = 0; }; -// SDL_Gpu Data -struct ImGui_ImplSDLGPU_Data +// SDL_GPU Data +struct ImGui_ImplSDLGPU3_Data { - ImGui_ImplSDLGPU_InitInfo GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo GPUInitInfo; // Graphics pipeline & shaders SDL_GPUShader* VertexShader = nullptr; @@ -50,16 +50,16 @@ struct ImGui_ImplSDLGPU_Data // Font data SDL_GPUSampler* FontSampler = nullptr; SDL_GPUTexture* FontTexture = nullptr; - SDL_GPUTextureSamplerBinding FontBinding = {nullptr,nullptr}; + SDL_GPUTextureSamplerBinding FontBinding = { nullptr, nullptr }; // Frame data for main window - ImGui_ImplSDLGPU_FrameData MainWindowFrameData; + ImGui_ImplSDLGPU3_FrameData MainWindowFrameData; }; // Forward Declarations -static bool ImGui_ImplSDLGPU_CreateDeviceObjects(); -static void ImGui_ImplSDLGPU_DestroyDeviceObjects(); -static void ImGui_ImplSDLGPU_DestroyFrameData(); +static bool ImGui_ImplSDLGPU3_CreateDeviceObjects(); +static void ImGui_ImplSDLGPU3_DestroyDeviceObjects(); +static void ImGui_ImplSDLGPU3_DestroyFrameData(); //----------------------------------------------------------------------------- // FUNCTIONS @@ -68,38 +68,19 @@ static void ImGui_ImplSDLGPU_DestroyFrameData(); // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. // FIXME: multi-context support has never been tested. -static ImGui_ImplSDLGPU_Data* ImGui_ImplSDLGPU_GetBackendData() +static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; + return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer,uint32_t* old_size, uint32_t new_size,SDL_GPUBufferUsageFlags usage) +static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass * render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height) { - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + //ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - SDL_WaitForGPUIdle(v->GpuDevice); - SDL_ReleaseGPUBuffer(v->GpuDevice, *buffer); + // Bind graphics pipeline + SDL_BindGPUGraphicsPipeline(render_pass,pipeline); - SDL_GPUBufferCreateInfo buffer_info = {}; - buffer_info.usage = usage; - buffer_info.size = new_size; - buffer_info.props = 0; - *buffer = SDL_CreateGPUBuffer(v->GpuDevice,&buffer_info); - *old_size = new_size; - IM_ASSERT(*buffer != nullptr && "Failed to create GPU Buffer, call SDL_GetError() for more information"); -} - -static void ImGui_ImplSDLGPU_SetupRenderState(ImDrawData* draw_data,SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer,SDL_GPURenderPass * render_pass, ImGui_ImplSDLGPU_FrameData* fd, uint32_t fb_width, uint32_t fb_height) -{ - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - - // Bind graphics pipeline: - { - SDL_BindGPUGraphicsPipeline(render_pass,pipeline); - } - - // Bind Vertex And Index Buffers: + // Bind Vertex And Index Buffers if (draw_data->TotalVtxCount > 0) { SDL_GPUBufferBinding vertex_buffer_binding = {}; @@ -112,56 +93,66 @@ static void ImGui_ImplSDLGPU_SetupRenderState(ImDrawData* draw_data,SDL_GPUGraph SDL_BindGPUIndexBuffer(render_pass,&index_buffer_binding,sizeof(ImDrawIdx) == 2 ? SDL_GPU_INDEXELEMENTSIZE_16BIT : SDL_GPU_INDEXELEMENTSIZE_32BIT); } - // Setup viewport: - { - SDL_GPUViewport viewport = {}; - viewport.x = 0; - viewport.y = 0; - viewport.w = fb_width; - viewport.h = fb_height; - viewport.min_depth = 0.0f; - viewport.min_depth = 1.0f; - SDL_SetGPUViewport(render_pass,&viewport); - } + // Setup viewport + SDL_GPUViewport viewport = {}; + viewport.x = 0; + viewport.y = 0; + viewport.w = (float)fb_width; + viewport.h = (float)fb_height; + viewport.min_depth = 0.0f; + viewport.min_depth = 1.0f; + SDL_SetGPUViewport(render_pass,&viewport); - // Setup scale and translation: + // Setup scale and translation // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. - { - struct UBO{ - float scale[2]; - float translation[2]; - } ubo; - ubo.scale[0] = 2.0f / draw_data->DisplaySize.x; - ubo.scale[1] = 2.0f / draw_data->DisplaySize.y; - ubo.translation[0] = -1.0f - draw_data->DisplayPos.x * ubo.scale[0]; - ubo.translation[1] = -1.0f - draw_data->DisplayPos.y * ubo.scale[1]; - SDL_PushGPUVertexUniformData(command_buffer,0,&ubo,sizeof(UBO)); - } + struct UBO { float scale[2]; float translation[2]; } ubo; + ubo.scale[0] = 2.0f / draw_data->DisplaySize.x; + ubo.scale[1] = 2.0f / draw_data->DisplaySize.y; + ubo.translation[0] = -1.0f - draw_data->DisplayPos.x * ubo.scale[0]; + ubo.translation[1] = -1.0f - draw_data->DisplayPos.y * ubo.scale[1]; + SDL_PushGPUVertexUniformData(command_buffer, 0, &ubo, sizeof(UBO)); } -// SDL_GPU doesn't allow copy passes to occur while a render or compute pass is bound +static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer, uint32_t* old_size, uint32_t new_size, SDL_GPUBufferUsageFlags usage) +{ + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + + SDL_WaitForGPUIdle(v->GpuDevice); + SDL_ReleaseGPUBuffer(v->GpuDevice, *buffer); + + SDL_GPUBufferCreateInfo buffer_info = {}; + buffer_info.usage = usage; + buffer_info.size = new_size; + buffer_info.props = 0; + *buffer = SDL_CreateGPUBuffer(v->GpuDevice, &buffer_info); + *old_size = new_size; + IM_ASSERT(*buffer != nullptr && "Failed to create GPU Buffer, call SDL_GetError() for more information"); +} + +// SDL_GPU doesn't allow copy passes to occur while a render or compute pass is bound! // The only way to allow a user to supply their own RenderPass (to render to a texture instead of the window for example), -// is to split the upload part of ImGui_ImplSDLGPU_RenderDrawData to another function that needs to be called by the user before rendering -void Imgui_ImplSDLGPU_PrepareDrawData(ImDrawData* draw_data,SDL_GPUCommandBuffer* command_buffer) +// is to split the upload part of ImGui_ImplSDLGPU3_RenderDrawData() to another function that needs to be called by the user before rendering. +void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer) { // 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); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); - if(fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount <= 0) + if (fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount <= 0) return; - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; - ImGui_ImplSDLGPU_FrameData* fd = &bd->MainWindowFrameData; + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData; uint32_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); uint32_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); - - if(fd->VertexBuffer == nullptr || fd->VertexBufferSize < vertex_size) - CreateOrResizeBuffer(&fd->VertexBuffer,&fd->VertexBufferSize,vertex_size, SDL_GPU_BUFFERUSAGE_VERTEX); + if (fd->VertexBuffer == nullptr || fd->VertexBufferSize < vertex_size) + CreateOrResizeBuffer(&fd->VertexBuffer, &fd->VertexBufferSize, vertex_size, SDL_GPU_BUFFERUSAGE_VERTEX); if (fd->IndexBuffer == nullptr || fd->IndexBufferSize < index_size) - CreateOrResizeBuffer(&fd->IndexBuffer,&fd->IndexBufferSize,index_size, SDL_GPU_BUFFERUSAGE_INDEX); + CreateOrResizeBuffer(&fd->IndexBuffer, &fd->IndexBufferSize, index_size, SDL_GPU_BUFFERUSAGE_INDEX); + // FIXME: It feels like more code could be shared there. SDL_GPUTransferBufferCreateInfo vertex_transferbuffer_info = {}; vertex_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; vertex_transferbuffer_info.size = vertex_size; @@ -169,22 +160,23 @@ void Imgui_ImplSDLGPU_PrepareDrawData(ImDrawData* draw_data,SDL_GPUCommandBuffer index_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; index_transferbuffer_info.size = index_size; - SDL_GPUTransferBuffer* vertex_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice,&vertex_transferbuffer_info); + SDL_GPUTransferBuffer* vertex_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice, &vertex_transferbuffer_info); IM_ASSERT(vertex_transferbuffer != nullptr && "Failed to create the vertex transfer buffer, call SDL_GetError() for more information"); - SDL_GPUTransferBuffer* index_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice,&index_transferbuffer_info); + SDL_GPUTransferBuffer* index_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice, &index_transferbuffer_info); IM_ASSERT(index_transferbuffer != nullptr && "Failed to create the index transfer buffer, call SDL_GetError() for more information"); - ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->GpuDevice,vertex_transferbuffer,true); - ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->GpuDevice,index_transferbuffer,true); - for(int n = 0; n < draw_data->CmdListsCount; n++){ + ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->GpuDevice, vertex_transferbuffer, true); + ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->GpuDevice, index_transferbuffer, true); + for (int n = 0; n < draw_data->CmdListsCount; n++) + { const ImDrawList* draw_list = draw_data->CmdLists[n]; memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += draw_list->VtxBuffer.Size; idx_dst += draw_list->IdxBuffer.Size; } - SDL_UnmapGPUTransferBuffer(v->GpuDevice,vertex_transferbuffer); - SDL_UnmapGPUTransferBuffer(v->GpuDevice,index_transferbuffer); + SDL_UnmapGPUTransferBuffer(v->GpuDevice, vertex_transferbuffer); + SDL_UnmapGPUTransferBuffer(v->GpuDevice, index_transferbuffer); SDL_GPUTransferBufferLocation vertex_buffer_location = {}; vertex_buffer_location.offset = 0; @@ -197,34 +189,35 @@ void Imgui_ImplSDLGPU_PrepareDrawData(ImDrawData* draw_data,SDL_GPUCommandBuffer vertex_buffer_region.buffer = fd->VertexBuffer; vertex_buffer_region.offset = 0; vertex_buffer_region.size = vertex_size; + SDL_GPUBufferRegion index_buffer_region = {}; index_buffer_region.buffer = fd->IndexBuffer; index_buffer_region.offset = 0; index_buffer_region.size = index_size; SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(command_buffer); - SDL_UploadToGPUBuffer(copy_pass,&vertex_buffer_location,&vertex_buffer_region,true); - SDL_UploadToGPUBuffer(copy_pass,&index_buffer_location,&index_buffer_region,true); + SDL_UploadToGPUBuffer(copy_pass, &vertex_buffer_location, &vertex_buffer_region,true); + SDL_UploadToGPUBuffer(copy_pass, &index_buffer_location, &index_buffer_region,true); SDL_EndGPUCopyPass(copy_pass); SDL_ReleaseGPUTransferBuffer(v->GpuDevice, index_transferbuffer); SDL_ReleaseGPUTransferBuffer(v->GpuDevice, vertex_transferbuffer); } -void ImGui_ImplSDLGPU_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline) +void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline) { // 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); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); - if(fb_width <= 0 || fb_height <= 0) + if (fb_width <= 0 || fb_height <= 0) return; - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_FrameData* fd = &bd->MainWindowFrameData; + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData; if (pipeline == nullptr) pipeline = bd->Pipeline; - ImGui_ImplSDLGPU_SetupRenderState(draw_data,pipeline,command_buffer,render_pass,fd,fb_width,fb_height); + ImGui_ImplSDLGPU3_SetupRenderState(draw_data, pipeline, command_buffer, render_pass, fd, fb_width, fb_height); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports @@ -267,10 +260,10 @@ void ImGui_ImplSDLGPU_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer SDL_SetGPUScissor(render_pass,&scissor_rect); // Bind DescriptorSet with font or user texture - SDL_BindGPUFragmentSamplers(render_pass,0,(SDL_GPUTextureSamplerBinding*)pcmd->GetTexID(),1); + SDL_BindGPUFragmentSamplers(render_pass, 0, (SDL_GPUTextureSamplerBinding*)pcmd->GetTexID(), 1); // Draw - SDL_DrawGPUIndexedPrimitives(render_pass,pcmd->ElemCount,1,pcmd->IdxOffset + global_idx_offset,pcmd->VtxOffset + global_vtx_offset,0); + SDL_DrawGPUIndexedPrimitives(render_pass, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } } global_idx_offset += draw_list->IdxBuffer.Size; @@ -281,21 +274,21 @@ void ImGui_ImplSDLGPU_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer // Our last values will leak into user/application rendering if you forgot to call SDL_SetGPUViewport() and SDL_SetGPUScissor() yourself to explicitly set that state // In theory we should aim to backup/restore those values but I am not sure this is possible. // We perform a call to SDL_SetGPUScissor() to set back a full viewport which is likely to fix things for 99% users but technically this is not perfect. (See github #4644) - SDL_Rect scissor_rect {0,0,fb_width,fb_height}; - SDL_SetGPUScissor(render_pass,&scissor_rect); + SDL_Rect scissor_rect { 0, 0, fb_width, fb_height }; + SDL_SetGPUScissor(render_pass, &scissor_rect); } -bool ImGui_ImplSDLGPU_CreateFontsTexture() +bool ImGui_ImplSDLGPU3_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; // Destroy existing texture (if any) if (bd->FontTexture) { SDL_WaitForGPUIdle(v->GpuDevice); - ImGui_ImplSDLGPU_DestroyFontsTexture(); + ImGui_ImplSDLGPU3_DestroyFontsTexture(); } unsigned char* pixels; @@ -315,7 +308,7 @@ bool ImGui_ImplSDLGPU_CreateFontsTexture() texture_info.num_levels = 1; texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1; - bd->FontTexture = SDL_CreateGPUTexture(v->GpuDevice,&texture_info); + bd->FontTexture = SDL_CreateGPUTexture(v->GpuDevice, &texture_info); IM_ASSERT(bd->FontTexture && "Failed to create font texture, call SDL_GetError() for more info"); } @@ -328,12 +321,12 @@ bool ImGui_ImplSDLGPU_CreateFontsTexture() font_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; font_transferbuffer_info.size = upload_size; - SDL_GPUTransferBuffer* font_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice,&font_transferbuffer_info); + SDL_GPUTransferBuffer* font_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice, &font_transferbuffer_info); IM_ASSERT(font_transferbuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information"); - void* texture_ptr = SDL_MapGPUTransferBuffer(v->GpuDevice,font_transferbuffer,false); - memcpy(texture_ptr,pixels,upload_size); - SDL_UnmapGPUTransferBuffer(v->GpuDevice,font_transferbuffer); + void* texture_ptr = SDL_MapGPUTransferBuffer(v->GpuDevice, font_transferbuffer, false); + memcpy(texture_ptr, pixels, upload_size); + SDL_UnmapGPUTransferBuffer(v->GpuDevice, font_transferbuffer); SDL_GPUTextureTransferInfo font_transfer_info = {}; font_transfer_info.offset = 0; @@ -347,7 +340,7 @@ bool ImGui_ImplSDLGPU_CreateFontsTexture() SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->GpuDevice); SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(cmd); - SDL_UploadToGPUTexture(copy_pass,&font_transfer_info,&font_texture_region,false); + SDL_UploadToGPUTexture(copy_pass, &font_transfer_info, &font_texture_region, false); SDL_EndGPUCopyPass(copy_pass); SDL_SubmitGPUCommandBuffer(cmd); SDL_ReleaseGPUTransferBuffer(v->GpuDevice, font_transferbuffer); @@ -359,28 +352,26 @@ bool ImGui_ImplSDLGPU_CreateFontsTexture() return true; } -// You probably never need to call this, as it is called by ImGui_ImplSDLGPU_CreateFontsTexture() and ImGui_ImplSDLGPU_Shutdown(). -void ImGui_ImplSDLGPU_DestroyFontsTexture() +// You probably never need to call this, as it is called by ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_Shutdown(). +void ImGui_ImplSDLGPU3_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; - - if(bd->FontTexture) + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + if (bd->FontTexture) { - SDL_ReleaseGPUTexture(v->GpuDevice,bd->FontTexture); + SDL_ReleaseGPUTexture(v->GpuDevice, bd->FontTexture); bd->FontBinding.texture = nullptr; bd->FontTexture = nullptr; } - io.Fonts->SetTexID(0); } -static void Imgui_ImplSDLGPU_CreateShaders() +static void Imgui_ImplSDLGPU3_CreateShaders() { // Create the shader modules - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; const char* driver = SDL_GetGPUDeviceDriver(v->GpuDevice); @@ -400,22 +391,20 @@ static void Imgui_ImplSDLGPU_CreateShaders() fragment_shader_info.num_storage_textures = 0; fragment_shader_info.num_uniform_buffers = 0; - if(strcmp(driver,"vulkan") == 0) + if (strcmp(driver, "vulkan") == 0) { vertex_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV; vertex_shader_info.code = spirv_vertex; vertex_shader_info.code_size = sizeof(spirv_vertex); - fragment_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV; fragment_shader_info.code = spirv_fragment; fragment_shader_info.code_size = sizeof(spirv_fragment); } - else if (strcmp(driver,"direct3d12") == 0) + else if (strcmp(driver, "direct3d12") == 0) { vertex_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC; vertex_shader_info.code = dxbc_vertex; vertex_shader_info.code_size = sizeof(dxbc_vertex); - fragment_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC; fragment_shader_info.code = dxbc_fragment; fragment_shader_info.code_size = sizeof(dxbc_fragment); @@ -427,25 +416,23 @@ static void Imgui_ImplSDLGPU_CreateShaders() vertex_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; vertex_shader_info.code = metallib_vertex; vertex_shader_info.code_size = sizeof(metallib_vertex); - fragment_shader_info.entrypoint = "main0"; fragment_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; fragment_shader_info.code = metallib_fragment; fragment_shader_info.code_size = sizeof(metallib_fragment); } #endif - bd->VertexShader = SDL_CreateGPUShader(v->GpuDevice,&vertex_shader_info); - bd->FragmentShader = SDL_CreateGPUShader(v->GpuDevice,&fragment_shader_info); - + bd->VertexShader = SDL_CreateGPUShader(v->GpuDevice, &vertex_shader_info); + bd->FragmentShader = SDL_CreateGPUShader(v->GpuDevice, &fragment_shader_info); IM_ASSERT(bd->VertexShader != nullptr && "Failed to create vertex shader, call SDL_GetError() for more information"); IM_ASSERT(bd->FragmentShader != nullptr && "Failed to create fragment shader, call SDL_GetError() for more information"); } -static void ImGui_ImplSDLGPU_CreateGraphicsPipeline() +static void ImGui_ImplSDLGPU3_CreateGraphicsPipeline() { - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; - Imgui_ImplSDLGPU_CreateShaders(); + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + Imgui_ImplSDLGPU3_CreateShaders(); SDL_GPUVertexBufferDescription vertex_buffer_desc[1]; vertex_buffer_desc[0].slot = 0; @@ -520,14 +507,14 @@ static void ImGui_ImplSDLGPU_CreateGraphicsPipeline() pipeline_info.depth_stencil_state = depth_stencil_state; pipeline_info.target_info = target_info; - bd->Pipeline = SDL_CreateGPUGraphicsPipeline(v->GpuDevice,&pipeline_info); + bd->Pipeline = SDL_CreateGPUGraphicsPipeline(v->GpuDevice, &pipeline_info); IM_ASSERT(bd->Pipeline != nullptr && "Failed to create graphics pipeline, call SDL_GetError() for more information"); } -bool ImGui_ImplSDLGPU_CreateDeviceObjects() +bool ImGui_ImplSDLGPU3_CreateDeviceObjects() { - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; if (!bd->FontSampler) { @@ -546,53 +533,53 @@ bool ImGui_ImplSDLGPU_CreateDeviceObjects() sampler_info.max_anisotropy = 1.0f; sampler_info.enable_compare = false; - bd->FontSampler = SDL_CreateGPUSampler(v->GpuDevice,&sampler_info); + bd->FontSampler = SDL_CreateGPUSampler(v->GpuDevice, &sampler_info); bd->FontBinding.sampler = bd->FontSampler; IM_ASSERT(bd->FontSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information"); } - ImGui_ImplSDLGPU_CreateGraphicsPipeline(); + ImGui_ImplSDLGPU3_CreateGraphicsPipeline(); return true; } -void ImGui_ImplSDLGPU_DestroyFrameData() +void ImGui_ImplSDLGPU3_DestroyFrameData() { - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; - SDL_ReleaseGPUBuffer(v->GpuDevice,bd->MainWindowFrameData.VertexBuffer); - SDL_ReleaseGPUBuffer(v->GpuDevice,bd->MainWindowFrameData.IndexBuffer); + SDL_ReleaseGPUBuffer(v->GpuDevice, bd->MainWindowFrameData.VertexBuffer); + SDL_ReleaseGPUBuffer(v->GpuDevice, bd->MainWindowFrameData.IndexBuffer); bd->MainWindowFrameData.VertexBuffer = nullptr; bd->MainWindowFrameData.IndexBuffer = nullptr; bd->MainWindowFrameData.VertexBufferSize = 0; bd->MainWindowFrameData.IndexBufferSize = 0; } -void ImGui_ImplSDLGPU_DestroyDeviceObjects() +void ImGui_ImplSDLGPU3_DestroyDeviceObjects() { - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - ImGui_ImplSDLGPU_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; - ImGui_ImplSDLGPU_DestroyFrameData(); - ImGui_ImplSDLGPU_DestroyFontsTexture(); + ImGui_ImplSDLGPU3_DestroyFrameData(); + ImGui_ImplSDLGPU3_DestroyFontsTexture(); - if(bd->VertexShader) { SDL_ReleaseGPUShader(v->GpuDevice,bd->VertexShader); bd->VertexShader = nullptr;} - if(bd->FragmentShader) { SDL_ReleaseGPUShader(v->GpuDevice,bd->FragmentShader); bd->FragmentShader = nullptr;} - if(bd->FontSampler) { SDL_ReleaseGPUSampler(v->GpuDevice, bd->FontSampler); bd->FontSampler = nullptr;} - if(bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->GpuDevice,bd->Pipeline); bd->Pipeline = nullptr;} + if (bd->VertexShader) { SDL_ReleaseGPUShader(v->GpuDevice, bd->VertexShader); bd->VertexShader = nullptr;} + if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->GpuDevice, bd->FragmentShader); bd->FragmentShader = nullptr;} + if (bd->FontSampler) { SDL_ReleaseGPUSampler(v->GpuDevice, bd->FontSampler); bd->FontSampler = nullptr;} + if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->GpuDevice, bd->Pipeline); bd->Pipeline = nullptr;} } -bool ImGui_ImplSDLGPU_Init(ImGui_ImplSDLGPU_InitInfo* info) +bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags - ImGui_ImplSDLGPU_Data* bd = IM_NEW(ImGui_ImplSDLGPU_Data)(); + ImGui_ImplSDLGPU3_Data* bd = IM_NEW(ImGui_ImplSDLGPU3_Data)(); io.BackendRendererUserData = (void*)bd; - io.BackendRendererName = "imgui_impl_sdlgpu"; + io.BackendRendererName = "imgui_impl_sdlgpu3"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. IM_ASSERT(info->GpuDevice != nullptr); @@ -600,31 +587,31 @@ bool ImGui_ImplSDLGPU_Init(ImGui_ImplSDLGPU_InitInfo* info) bd->GPUInitInfo = *info; - ImGui_ImplSDLGPU_CreateDeviceObjects(); + ImGui_ImplSDLGPU3_CreateDeviceObjects(); return true; } -void ImGui_ImplSDLGPU_Shutdown() +void ImGui_ImplSDLGPU3_Shutdown() { - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLGPU_DestroyDeviceObjects(); + ImGui_ImplSDLGPU3_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } -void ImGui_ImplSDLGPU_NewFrame() +void ImGui_ImplSDLGPU3_NewFrame() { - ImGui_ImplSDLGPU_Data* bd = ImGui_ImplSDLGPU_GetBackendData(); - IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplVulkan_Init()?"); + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLGPU3_Init()?"); - if(!bd->FontTexture) - ImGui_ImplSDLGPU_CreateFontsTexture(); + if (!bd->FontTexture) + ImGui_ImplSDLGPU3_CreateFontsTexture(); } #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index 18d3001e4..ff9c751c8 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -1,4 +1,4 @@ -// dear imgui: Renderer Backend for SDL_Gpu +// dear imgui: Renderer Backend for SDL_GPU // This needs to be used along with the SDL3 Platform Backend // Implemented features: @@ -27,7 +27,7 @@ // Initialization data, for ImGui_ImplSDLGPU_Init() // - Remember to set ColorTargetFormat to the correct format. If you're rendering to the swapchain, call SDL_GetGPUSwapchainTextureFormat to query the right value -struct ImGui_ImplSDLGPU_InitInfo +struct ImGui_ImplSDLGPU3_InitInfo { SDL_GPUDevice* GpuDevice = nullptr; SDL_GPUTextureFormat ColorTargetFormat = SDL_GPU_TEXTUREFORMAT_INVALID; @@ -35,12 +35,12 @@ struct ImGui_ImplSDLGPU_InitInfo }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! -IMGUI_IMPL_API bool ImGui_ImplSDLGPU_Init(ImGui_ImplSDLGPU_InitInfo* info); -IMGUI_IMPL_API void ImGui_ImplSDLGPU_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplSDLGPU_NewFrame(); -IMGUI_IMPL_API void Imgui_ImplSDLGPU_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer); -IMGUI_IMPL_API void ImGui_ImplSDLGPU_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline = nullptr); -IMGUI_IMPL_API bool ImGui_ImplSDLGPU_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplSDLGPU_DestroyFontsTexture(); +IMGUI_IMPL_API bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_NewFrame(); +IMGUI_IMPL_API void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline = nullptr); +IMGUI_IMPL_API bool ImGui_ImplSDLGPU3_CreateFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_DestroyFontsTexture(); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/sdlgpu3/build_instructions.txt b/backends/sdlgpu3/build_instructions.txt index 751dc97a4..25f4a5d28 100644 --- a/backends/sdlgpu3/build_instructions.txt +++ b/backends/sdlgpu3/build_instructions.txt @@ -1,3 +1,7 @@ + +Instructions to rebuild imgui_impl_sdlgpu3_shaders.h +(You don't need to copy this folder if you are using the backend as-is) + 1) Compile the raw shader files to SPIRV: glslc -o vertex.spv -c shader.vert @@ -33,4 +37,4 @@ Proceed to step 4 -4) Either find a way to load the shader bytecode from file, or use a tool like https://notisrac.github.io/FileToCArray/ to convert the file to a uint8_t array \ No newline at end of file +4) Use a tool like https://notisrac.github.io/FileToCArray/ or misc/fonts/binary_to_compressed_c.cpp in imgui repository to convert the file to a uint8_t array. diff --git a/backends/sdlgpu3/shader.frag b/backends/sdlgpu3/shader.frag index 2de1f76a3..ab9ce184e 100644 --- a/backends/sdlgpu3/shader.frag +++ b/backends/sdlgpu3/shader.frag @@ -3,7 +3,8 @@ layout(location = 0) out vec4 fColor; layout(set=2, binding=0) uniform sampler2D sTexture; -layout(location = 0) in struct { +layout(location = 0) in struct +{ vec4 Color; vec2 UV; } In; @@ -11,4 +12,4 @@ layout(location = 0) in struct { void main() { fColor = In.Color * texture(sTexture, In.UV.st); -} \ No newline at end of file +} diff --git a/backends/sdlgpu3/shader.vert b/backends/sdlgpu3/shader.vert index 3363da8b2..3a85a9038 100644 --- a/backends/sdlgpu3/shader.vert +++ b/backends/sdlgpu3/shader.vert @@ -3,12 +3,14 @@ layout(location = 0) in vec2 aPos; layout(location = 1) in vec2 aUV; layout(location = 2) in vec4 aColor; -layout(set=1,binding=0) uniform UBO { +layout(set=1,binding=0) uniform UBO +{ vec2 uScale; vec2 uTranslate; } ubo; -layout(location = 0) out struct { +layout(location = 0) out struct +{ vec4 Color; vec2 UV; } Out; @@ -19,4 +21,4 @@ void main() Out.UV = aUV; gl_Position = vec4(aPos * ubo.uScale + ubo.uTranslate, 0, 1); gl_Position.y *= -1.0f; -} \ No newline at end of file +} diff --git a/backends/vulkan/build_instructions.txt b/backends/vulkan/build_instructions.txt new file mode 100644 index 000000000..1f028d96f --- /dev/null +++ b/backends/vulkan/build_instructions.txt @@ -0,0 +1,4 @@ + +Script to rebuild shaders stored inside imgui_impl_vulkan.h +(You don't need to copy this folder if you are using the backend as-is) + diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 00df8a746..80b956810 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,7 @@ Other changes: - Demo: Added label edition to Property Editor demo + fix an ID issue. (#8266) [@moritz-h] - Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] - Misc: Fixed MinGW builds uses UTF-8 friendly _wfopen(). (#8300) +- Backends: SDL_GPU for SDL3: Added backend for SDL_GPU! (#8163, #7998, #7988) [@DeltaW0x]. - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). [@Helodity] - Backends: Metal: Fixed leaks when using metal-cpp. (#8276, #8166) [@selimsandal] diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index 224beb1c1..0df73059b 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -139,8 +139,8 @@ This support building with Emscripten and targeting WebGL.
Prefer using that if you are using modern GL or WebGL in your application. [example_sdl2_sdlrenderer2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_sdlrenderer2/)
-SDL2 (Win32, Mac, Linux, etc.) + SDL_Renderer for SDL2 (most graphics backends are supported underneath)
-= main.cpp + imgui_impl_sdl2.cpp + imgui_impl_sdlrenderer.cpp
+SDL2 (Win32, Mac, Linux, etc.) + SDL_Renderer for SDL2 example.
+= main.cpp + imgui_impl_sdl2.cpp + imgui_impl_sdlrenderer2.cpp
This requires SDL 2.0.18+ (released November 2021)
[example_sdl2_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_vulkan/)
@@ -149,6 +149,26 @@ SDL2 (Win32, Mac, Linux, etc.) + Vulkan example.
This is quite long and tedious, because: Vulkan.
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. +[example_sdl3_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_opengl3/)
+SDL3 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example.
+= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_opengl3.cpp
+This uses more modern GL calls and custom shaders.
+This support building with Emscripten and targeting WebGL.
+ +[example_sdl3_sdlgpu3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_sdlgpu3/)
+SDL3 (Win32, Mac, Linux, etc.) + SDL_GPU for SDL3 example.
+= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_sdlrenderer3.cpp
+ +[example_sdl3_sdlrenderer3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_sdlrenderer3/)
+SDL3 (Win32, Mac, Linux, etc.) + SDL_Renderer for SDL3 example.
+= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_sdlrenderer3.cpp
+ +[example_sdl3_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_vulkan/)
+SDL3 (Win32, Mac, Linux, etc.) + Vulkan example.
+= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_vulkan.cpp
+This is quite long and tedious, because: Vulkan.
+For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. + [example_win32_directx9/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx9/)
DirectX9 example, Windows only.
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp diff --git a/docs/README.md b/docs/README.md index 388d8eac6..9b437311a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -123,7 +123,7 @@ On most platforms and when using C++, **you should be able to use a combination Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading a texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles, which is essentially what Backends are doing. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that: setting up a window and using backends. If you follow the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide it should in theory takes you less than an hour to integrate Dear ImGui. **Make sure to spend time reading the [FAQ](https://www.dearimgui.com/faq), comments, and the examples applications!** Officially maintained backends/bindings (in repository): -- Renderers: DirectX9, DirectX10, DirectX11, DirectX12, Metal, OpenGL/ES/ES2, SDL_Renderer, Vulkan, WebGPU. +- Renderers: DirectX9, DirectX10, DirectX11, DirectX12, Metal, OpenGL/ES/ES2, SDL_GPU, SDL_Renderer2/3, Vulkan, WebGPU. - Platforms: GLFW, SDL2/SDL3, Win32, Glut, OSX, Android. - Frameworks: Allegro5, Emscripten. diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 6c29962dd..353c10857 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for SDL_Gpu +// Dear ImGui: standalone example application for SDL3 + SDL_GPU // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq @@ -17,7 +17,6 @@ #include // abort #include - // This example doesn't compile with Emscripten yet! Awaiting SDL3 support. #ifdef __EMSCRIPTEN__ #include "../libs/emscripten/emscripten_mainloop_stub.h" @@ -34,23 +33,23 @@ int main(int, char**) } // Create SDL window graphics context - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDLGpu example", 1280, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", 1280, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); return -1; } - // Create SDL Gpu Device - SDL_GPUDevice* gpuDevice = SDL_CreateGPUDevice(SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_DXIL | SDL_GPU_SHADERFORMAT_METALLIB,true,nullptr); - if (gpuDevice == nullptr) + // Create GPU Device + SDL_GPUDevice* gpu_device = SDL_CreateGPUDevice(SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_DXIL | SDL_GPU_SHADERFORMAT_METALLIB,true,nullptr); + if (gpu_device == nullptr) { printf("Error: SDL_CreateGPUDevice(): %s\n", SDL_GetError()); return -1; } // Claim window for GPU Device - if (!SDL_ClaimWindowForGPUDevice(gpuDevice, window)) + if (!SDL_ClaimWindowForGPUDevice(gpu_device, window)) { printf("Error: SDL_ClaimWindowForGPUDevice(): %s\n", SDL_GetError()); return -1; @@ -69,11 +68,11 @@ int main(int, char**) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForOther(window); - ImGui_ImplSDLGPU_InitInfo init_info = {}; - init_info.GpuDevice = gpuDevice; - init_info.ColorTargetFormat = SDL_GetGPUSwapchainTextureFormat(gpuDevice, window); + ImGui_ImplSDLGPU3_InitInfo init_info = {}; + init_info.GpuDevice = gpu_device; + init_info.ColorTargetFormat = SDL_GetGPUSwapchainTextureFormat(gpu_device, window); init_info.MSAASamples = SDL_GPU_SAMPLECOUNT_1; - ImGui_ImplSDLGPU_Init(&init_info); + ImGui_ImplSDLGPU3_Init(&init_info); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. @@ -119,9 +118,9 @@ int main(int, char**) SDL_Delay(10); continue; } - + // Start the Dear ImGui frame - ImGui_ImplSDLGPU_NewFrame(); + ImGui_ImplSDLGPU3_NewFrame(); ImGui_ImplSDL3_NewFrame(); ImGui::NewFrame(); @@ -167,18 +166,15 @@ int main(int, char**) ImDrawData* draw_data = ImGui::GetDrawData(); const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); - // Acquire a GPU command buffer - SDL_GPUCommandBuffer* command_buffer = SDL_AcquireGPUCommandBuffer(gpuDevice); + SDL_GPUCommandBuffer* command_buffer = SDL_AcquireGPUCommandBuffer(gpu_device); // Acquire a GPU command buffer - //Acquire a swapchain texture SDL_GPUTexture* swapchain_texture; - SDL_AcquireGPUSwapchainTexture(command_buffer, window, &swapchain_texture, nullptr, nullptr); + SDL_AcquireGPUSwapchainTexture(command_buffer, window, &swapchain_texture, nullptr, nullptr); // Acquire a swapchain texture if (swapchain_texture != nullptr && !is_minimized) { - // !!! THIS IS MANDATORY !!! - // Call Imgui_ImplSDLGPU_PrepareDrawData to upload the vertex/index buffer - Imgui_ImplSDLGPU_PrepareDrawData(draw_data, command_buffer); + // This is mandatory: call Imgui_ImplSDLGPU3_PrepareDrawData() to upload the vertex/index buffer! + Imgui_ImplSDLGPU3_PrepareDrawData(draw_data, command_buffer); // Setup and start a render pass SDL_GPUColorTargetInfo target_info = {}; @@ -190,21 +186,26 @@ int main(int, char**) target_info.layer_or_depth_plane = 0; target_info.cycle = false; SDL_GPURenderPass* render_pass = SDL_BeginGPURenderPass(command_buffer, &target_info, 1, nullptr); - /// Render ImGui - ImGui_ImplSDLGPU_RenderDrawData(draw_data, command_buffer, render_pass); + + // Render ImGui + ImGui_ImplSDLGPU3_RenderDrawData(draw_data, command_buffer, render_pass); + SDL_EndGPURenderPass(render_pass); } + // Submit the command buffer SDL_SubmitGPUCommandBuffer(command_buffer); } // Cleanup - SDL_WaitForGPUIdle(gpuDevice); + SDL_WaitForGPUIdle(gpu_device); ImGui_ImplSDL3_Shutdown(); - ImGui_ImplSDLGPU_Shutdown(); + ImGui_ImplSDLGPU3_Shutdown(); ImGui::DestroyContext(); - SDL_ReleaseWindowFromGPUDevice(gpuDevice, window); - SDL_DestroyGPUDevice(gpuDevice); + + SDL_ReleaseWindowFromGPUDevice(gpu_device, window); + SDL_DestroyGPUDevice(gpu_device); SDL_DestroyWindow(window); SDL_Quit(); + return 0; } From 596e09770d351fad21adbfa7b4f88383c6da1440 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 9 Jan 2025 17:07:53 +0100 Subject: [PATCH 0593/2359] Backends: SDL3: Added ImGui_ImplSDL3_InitForSDLGPU() for consistency. (#8163, #7998, #7988) --- backends/imgui_impl_sdl3.cpp | 5 +++++ backends/imgui_impl_sdl3.h | 1 + docs/CHANGELOG.txt | 2 ++ examples/example_sdl3_sdlgpu3/main.cpp | 2 +- 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index a167c74cd..c3935b2ab 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -531,6 +531,11 @@ bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* rendere return ImGui_ImplSDL3_Init(window, renderer, nullptr); } +bool ImGui_ImplSDL3_InitForSDLGPU(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + bool ImGui_ImplSDL3_InitForOther(SDL_Window* window) { return ImGui_ImplSDL3_Init(window, nullptr, nullptr); diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h index 0d906a65c..ff0e2aed3 100644 --- a/backends/imgui_impl_sdl3.h +++ b/backends/imgui_impl_sdl3.h @@ -35,6 +35,7 @@ IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLGPU(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOther(SDL_Window* window); IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame(); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 80b956810..56ad9b8d0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,8 @@ Other changes: - Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] - Misc: Fixed MinGW builds uses UTF-8 friendly _wfopen(). (#8300) - Backends: SDL_GPU for SDL3: Added backend for SDL_GPU! (#8163, #7998, #7988) [@DeltaW0x]. +- Backends: SDL3: Added ImGui_ImplSDL3_InitForSDLGPU() for consistency, even + though it is currently not doing anything particular. (#8163, #7998, #7988) - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). [@Helodity] - Backends: Metal: Fixed leaks when using metal-cpp. (#8276, #8166) [@selimsandal] diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 353c10857..f025c537d 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -67,7 +67,7 @@ int main(int, char**) //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends - ImGui_ImplSDL3_InitForOther(window); + ImGui_ImplSDL3_InitForSDLGPU(window); ImGui_ImplSDLGPU3_InitInfo init_info = {}; init_info.GpuDevice = gpu_device; init_info.ColorTargetFormat = SDL_GetGPUSwapchainTextureFormat(gpu_device, window); From e7fb97208a876a2c57143e9cda0372d878c6abe9 Mon Sep 17 00:00:00 2001 From: Daniel Walz Date: Thu, 9 Jan 2025 23:12:07 +0100 Subject: [PATCH 0594/2359] Backends: Metal: Added missing IM_UNUSED (#8302) --- backends/imgui_impl_metal.mm | 1 + 1 file changed, 1 insertion(+) diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 3ff905a60..1e0c47f52 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -143,6 +143,7 @@ bool ImGui_ImplMetal_Init(id device) void ImGui_ImplMetal_Shutdown() { ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + IM_UNUSED(bd); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGui_ImplMetal_DestroyDeviceObjects(); ImGui_ImplMetal_DestroyBackendData(); From 0b8ff4b2382d4bbd5c168b1a5373f86ea3145957 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 9 Jan 2025 23:15:59 +0100 Subject: [PATCH 0595/2359] Backends, Examples: Vulkan: add IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE. use in descriptor pools sizes. (#6642) --- backends/imgui_impl_vulkan.cpp | 4 +++- backends/imgui_impl_vulkan.h | 6 ++++-- docs/CHANGELOG.txt | 4 ++++ examples/example_glfw_vulkan/main.cpp | 9 +++++---- examples/example_sdl2_vulkan/main.cpp | 9 +++++---- examples/example_sdl3_vulkan/main.cpp | 9 +++++---- examples/example_win32_vulkan/main.cpp | 9 +++++---- 7 files changed, 31 insertions(+), 19 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 4345f2b11..940ea2d79 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -26,6 +26,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-09: Vulkan: Added IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE to clarify how many image sampler descriptors are expected to be available in descriptor pool. (#6642) // 2025-01-06: Vulkan: Added more ImGui_ImplVulkanH_XXXX helper functions to simplify our examples. // 2024-12-11: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) // 2024-11-27: Vulkan: Make user-provided descriptor pool optional. As a convenience, when setting init_info->DescriptorPoolSize the backend will create one itself. (#8172, #4867) @@ -1022,8 +1023,9 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() check_vk_result(err); } - if (v->DescriptorPoolSize) + if (v->DescriptorPoolSize != 0) { + IM_ASSERT(v->DescriptorPoolSize > IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE); VkDescriptorPoolSize pool_size = { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, v->DescriptorPoolSize }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 5621acbdd..3bd994864 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -61,14 +61,16 @@ #define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #endif +// Current version of the backend use 1 descriptor for the font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture(). +// It is expected that as early as Q1 2025 the backend will use a few more descriptors. Use this value + number of desired calls to ImGui_ImplVulkan_AddTexture(). +#define IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE (1) // Minimum per atlas + // Initialization data, for ImGui_ImplVulkan_Init() // [Please zero-clear before use!] // - About descriptor pool: // - A VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, // and must contain a pool size large enough to hold a small number of VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptors. // - As an convenience, by setting DescriptorPoolSize > 0 the backend will create one for you. -// - Current version of the backend use 1 descriptor for the font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture(). -// - It is expected that as early as Q1 2025 the backend will use a few more descriptors, so aim at 10 + number of desierd calls to ImGui_ImplVulkan_AddTexture(). // - About dynamic rendering: // - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure. struct ImGui_ImplVulkan_InitInfo diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 56ad9b8d0..1b713e17f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -79,6 +79,10 @@ Other changes: platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) [@Zer0xFF] - Backends: Vulkan: Added a few more ImGui_ImplVulkanH_XXX helper functions primarily for the purpose of making our examples simpler. +- Backends: Vulkan: Added IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE to clarify + how many image sampler descriptors are expected to be available in the provided + descriptor pool. Current backend needs 1 but it is expected that by end of Q1 2025 + this number will grow (will staying a very small number). (#6642) - Backends: DX11: Expose vertex constant buffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handlers. (#6969, #5834, #7468, #3590) - Backends: DX10: Expose ImGui_ImplDX10_RenderState for completeness. (#6969, #5834, #7468, #3590) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 9f8dced2f..b61dcaae0 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -189,17 +189,18 @@ static void SetupVulkan(ImVector instance_extensions) } // Create Descriptor Pool - // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that) - // If you wish to load e.g. additional textures you may need to alter pools sizes. + // If you wish to load e.g. additional textures you may need to alter pools sizes and maxSets. { VkDescriptorPoolSize pool_sizes[] = { - { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE }, }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; - pool_info.maxSets = 1; + pool_info.maxSets = 0; + for (VkDescriptorPoolSize& pool_size : pool_sizes) + pool_info.maxSets += pool_size.descriptorCount; pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index fafa8ea42..b82ed0b7a 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -177,17 +177,18 @@ static void SetupVulkan(ImVector instance_extensions) } // Create Descriptor Pool - // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that) - // If you wish to load e.g. additional textures you may need to alter pools sizes. + // If you wish to load e.g. additional textures you may need to alter pools sizes and maxSets. { VkDescriptorPoolSize pool_sizes[] = { - { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE }, }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; - pool_info.maxSets = 1; + pool_info.maxSets = 0; + for (VkDescriptorPoolSize& pool_size : pool_sizes) + pool_info.maxSets += pool_size.descriptorCount; pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 569eaeffb..e36f87194 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -182,17 +182,18 @@ static void SetupVulkan(ImVector instance_extensions) } // Create Descriptor Pool - // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that) - // If you wish to load e.g. additional textures you may need to alter pools sizes. + // If you wish to load e.g. additional textures you may need to alter pools sizes and maxSets. { VkDescriptorPoolSize pool_sizes[] = { - { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE }, }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; - pool_info.maxSets = 1; + pool_info.maxSets = 0; + for (VkDescriptorPoolSize& pool_size : pool_sizes) + pool_info.maxSets += pool_size.descriptorCount; pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 3fabf7a2d..c6c138695 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -178,17 +178,18 @@ static void SetupVulkan(ImVector instance_extensions) } // Create Descriptor Pool - // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that) - // If you wish to load e.g. additional textures you may need to alter pools sizes. + // If you wish to load e.g. additional textures you may need to alter pools sizes and maxSets. { VkDescriptorPoolSize pool_sizes[] = { - { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE }, }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; - pool_info.maxSets = 1; + pool_info.maxSets = 0; + for (VkDescriptorPoolSize& pool_size : pool_sizes) + pool_info.maxSets += pool_size.descriptorCount; pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); From 1d962820d8b972d93a4627afc3cb4c09837c298c Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 12 Jan 2025 15:11:30 +0100 Subject: [PATCH 0596/2359] Error Handling: Turned common EndTable() and other TableXXX functions fail cases into recoverable errors. (#1651, #8314) --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 45 ++++++++++++++++++++++++++++++++++++--------- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1b713e17f..bf9f209c4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,8 @@ Other changes: - Error Handling: Fixed bugs recovering from within a table that created a child window, and from nested child windows. (#1651) +- Error Handling: Turned common EndTable() and other TableXXX functions + fail cases into a recoverable error. (#1651, #8314) - InputText: Fixed a bug where character replacements performed from a callback were not applied when pasting from clipbard. (#8229) - InputText: Fixed issue when activating a ReadOnly field when the underlying diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 1ab9c703e..ec25bf906 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1337,7 +1337,11 @@ void ImGui::EndTable() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!"); + if (table == NULL) + { + IM_ASSERT_USER_ERROR(table != NULL, "EndTable() call should only be done while in BeginTable() scope!"); + return; + } // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) @@ -1560,8 +1564,12 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!"); - IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!"); + if (table == NULL) + { + IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); + return; + } + IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!"); IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()"); if (table->DeclColumnsCount >= table->ColumnsCount) { @@ -1634,7 +1642,11 @@ void ImGui::TableSetupScrollFreeze(int columns, int rows) { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!"); + if (table == NULL) + { + IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); + return; + } IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!"); IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS); IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit @@ -1711,9 +1723,11 @@ void ImGui::TableSetColumnEnabled(int column_n, bool enabled) { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL); - if (!table) + if (table == NULL) + { + IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); return; + } IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above if (column_n < 0) column_n = table->CurrentColumn; @@ -3034,7 +3048,11 @@ void ImGui::TableHeadersRow() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!"); + if (table == NULL) + { + IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); + return; + } // Call layout if not already done. This is automatically done by TableNextRow: we do it here _only_ to make // it easier to debug-step in TableUpdateLayout(). Your own version of this function doesn't need this. @@ -3079,7 +3097,12 @@ void ImGui::TableHeader(const char* label) return; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Need to call TableHeader() after BeginTable()!"); + if (table == NULL) + { + IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); + return; + } + IM_ASSERT(table->CurrentColumn != -1); const int column_n = table->CurrentColumn; ImGuiTableColumn* column = &table->Columns[column_n]; @@ -3254,7 +3277,11 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label ImGuiTable* table = g.CurrentTable; ImGuiWindow* window = g.CurrentWindow; ImDrawList* draw_list = window->DrawList; - IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!"); + if (table == NULL) + { + IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); + return; + } IM_ASSERT(table->CurrentRow == -1 && "Must be first row"); if (max_label_width == 0.0f) From a28ffa81c4a8e244e2682587285a63e3d0f2c67e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 13:26:15 +0100 Subject: [PATCH 0597/2359] Docs: added more references to IsKeyDown(), InFlags. (#8317) --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 2 +- imgui_internal.h | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bf9f209c4..9c1b280b3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -153,11 +153,12 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v Breaking changes: - Commented out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before). - - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022). + - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022). Use IsKeyDown() instead. - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022). - Pre-1.87 backends are not supported: - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields. - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields. + - you can use IsKeyDown() instead of reading from io.KeysDown[]. - For more references: - read 1.87 and 1.88 part of API BREAKING CHANGES in imgui.cpp or read Changelog for 1.87 and 1.88. - read https://github.com/ocornut/imgui/issues/4921 @@ -2390,6 +2391,7 @@ Breaking Changes: - For all calls to IO new functions, the Dear ImGui context should be bound/current. - Reworked IO keyboard input API: (#4921, #2625, #3724) [@thedmd, @ocornut] - Added io.AddKeyEvent() function, obsoleting writing directly to io.KeyMap[], io.KeysDown[] arrays. + - You can use IsKeyDown() instead of reading from io.KeysDown[]. - For keyboard modifiers, you can call io.AddKeyEvent() with ImGuiKey_ModXXX values, obsoleting writing directly to io.KeyCtrl, io.KeyShift etc. - Added io.SetKeyEventNativeData() function (optional) to pass native and old legacy indices. diff --git a/imgui.cpp b/imgui.cpp index bad766f03..c676172ef 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -647,7 +647,7 @@ CODE - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only] note: for all calls to IO new functions, the Dear ImGui context should be bound/current. read https://github.com/ocornut/imgui/issues/4921 for details. - - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details. + - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(), ImGui::IsKeyDown(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details. - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX) - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX) - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes). diff --git a/imgui_internal.h b/imgui_internal.h index 850136b0d..9ff2b6d3e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1247,11 +1247,11 @@ struct ImGuiNextItemData struct ImGuiLastItemData { ImGuiID ID; - ImGuiItemFlags ItemFlags; // See ImGuiItemFlags_ + ImGuiItemFlags ItemFlags; // See ImGuiItemFlags_ (called 'InFlags' before v1.91.4). ImGuiItemStatusFlags StatusFlags; // See ImGuiItemStatusFlags_ ImRect Rect; // Full rectangle ImRect NavRect; // Navigation scoring rectangle (not displayed) - // Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags ar set. + // Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags are set. ImRect DisplayRect; // Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) is set. ImRect ClipRect; // Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasClipRect) is set.. ImGuiKeyChord Shortcut; // Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasShortcut) is set.. From a604d4f717bb99a704fcb17d29a6f0dbac78c060 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 10 Jan 2025 17:08:09 +0100 Subject: [PATCH 0598/2359] Fixed IsItemDeactivated(), IsItemDeactivatedAfterEdit() to work when interrupted before/after the active id is submitted. (#5184, #5904, #6766, #8303, #8004) --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 40 ++++++++++++++++++++++++---------------- imgui.h | 2 +- imgui_internal.h | 16 ++++++++++++---- 4 files changed, 46 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9c1b280b3..1f1eb05a9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,15 @@ Breaking changes: Other changes: +- Fixed issues with IsItemDeactivated() and IsItemDeactivatedAfterEdit() not + emitting a reliable signal when an item is deactivated externally: e.g. + via an explicit clear of focus, clear of active id, opening of modal etc. + (#5184, #5904, #6766, #8303, #8004) + - It used to work when the interruption happened in the frame before the + active item as submitted, but not after. It should work in both cases now. + - While this is not specific to a certain widgets, typically it would + mostly be noticeable on InputText() because it keeps ActiveId for a + longer time while allowing other interaction to happen. - Error Handling: Fixed bugs recovering from within a table that created a child window, and from nested child windows. (#1651) - Error Handling: Turned common EndTable() and other TableXXX functions diff --git a/imgui.cpp b/imgui.cpp index c676172ef..6b9f47164 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3930,9 +3930,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) ActiveIdSource = ImGuiInputSource_None; ActiveIdMouseButton = -1; ActiveIdPreviousFrame = 0; - ActiveIdPreviousFrameIsAlive = false; - ActiveIdPreviousFrameHasBeenEditedBefore = false; - ActiveIdPreviousFrameWindow = NULL; + memset(&DeactivatedItemData, 0, sizeof(DeactivatedItemData)); memset(&ActiveIdValueOnActivation, 0, sizeof(ActiveIdValueOnActivation)); LastActiveId = 0; LastActiveIdTimer = 0.0f; @@ -4175,7 +4173,7 @@ void ImGui::Shutdown() g.WindowsById.Clear(); g.NavWindow = NULL; g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL; - g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; + g.ActiveIdWindow = NULL; g.MovingWindow = NULL; g.KeysRoutingTable.Clear(); @@ -4359,6 +4357,13 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) g.MovingWindow = NULL; } + // Store deactivate data + ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData; + deactivated_data->ID = g.ActiveId; + deactivated_data->ElapseFrame = (g.LastItemData.ID == g.ActiveId) ? g.FrameCount : g.FrameCount + 1; // FIXME: OK to use LastItemData? + deactivated_data->HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore; + deactivated_data->IsAlive = (g.ActiveIdIsAlive == g.ActiveId); + // This could be written in a more general way (e.g associate a hook to ActiveId), // but since this is currently quite an exception we'll leave it as is. // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID() @@ -5189,11 +5194,8 @@ void ImGui::NewFrame() g.ActiveIdTimer += g.IO.DeltaTime; g.LastActiveIdTimer += g.IO.DeltaTime; g.ActiveIdPreviousFrame = g.ActiveId; - g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow; - g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore; g.ActiveIdIsAlive = 0; g.ActiveIdHasBeenEditedThisFrame = false; - g.ActiveIdPreviousFrameIsAlive = false; g.ActiveIdIsJustActivated = false; if (g.TempInputId != 0 && g.ActiveId != g.TempInputId) g.TempInputId = 0; @@ -5202,6 +5204,9 @@ void ImGui::NewFrame() g.ActiveIdUsingNavDirMask = 0x00; g.ActiveIdUsingAllKeyboardKeys = false; } + if (g.DeactivatedItemData.ElapseFrame < g.FrameCount) + g.DeactivatedItemData.ID = 0; + g.DeactivatedItemData.IsAlive = false; // Record when we have been stationary as this state is preserved while over same item. // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values. @@ -5833,13 +5838,13 @@ bool ImGui::IsItemDeactivated() ImGuiContext& g = *GImGui; if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated) return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0; - return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID); + return (g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount); } bool ImGui::IsItemDeactivatedAfterEdit() { ImGuiContext& g = *GImGui; - return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore)); + return IsItemDeactivated() && g.DeactivatedItemData.HasBeenEditedBefore; } // == (GetItemID() == GetFocusID() && GetFocusID() != 0) @@ -10443,8 +10448,8 @@ void ImGui::KeepAliveID(ImGuiID id) ImGuiContext& g = *GImGui; if (g.ActiveId == id) g.ActiveIdIsAlive = id; - if (g.ActiveIdPreviousFrame == id) - g.ActiveIdPreviousFrameIsAlive = true; + if (g.DeactivatedItemData.ID == id) + g.DeactivatedItemData.IsAlive = true; } // Declare item bounding box for clipping and interaction. @@ -10529,6 +10534,9 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu // window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG] #endif + if (id != 0 && g.DeactivatedItemData.ID == id) + g.DeactivatedItemData.ElapseFrame = g.FrameCount; + // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them) if (is_rect_visible) g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible; @@ -10888,7 +10896,7 @@ void ImGui::BeginGroup() group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; group_data.BackupHoveredIdIsAlive = g.HoveredId != 0; group_data.BackupIsSameLine = window->DC.IsSameLine; - group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive; + group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive; group_data.EmitItem = true; window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x; @@ -10939,11 +10947,11 @@ void ImGui::EndGroup() // Also if you grep for LastItemId you'll notice it is only used in that context. // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.) const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId; - const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true); + const bool group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) && (g.DeactivatedItemData.IsAlive == true); if (group_contains_curr_active_id) g.LastItemData.ID = g.ActiveId; - else if (group_contains_prev_active_id) - g.LastItemData.ID = g.ActiveIdPreviousFrame; + else if (group_contains_deactivated_id) + g.LastItemData.ID = g.DeactivatedItemData.ID; g.LastItemData.Rect = group_bb; // Forward Hovered flag @@ -10957,7 +10965,7 @@ void ImGui::EndGroup() // Forward Deactivated flag g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated; - if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame) + if (group_contains_deactivated_id) g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated; g.GroupStack.pop_back(); diff --git a/imgui.h b/imgui.h index 0f7a99862..5a3a7af65 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.7 WIP" -#define IMGUI_VERSION_NUM 19164 +#define IMGUI_VERSION_NUM 19165 #define IMGUI_HAS_TABLE /* diff --git a/imgui_internal.h b/imgui_internal.h index 9ff2b6d3e..bb5a56774 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -140,6 +140,7 @@ struct ImGuiContext; // Main Dear ImGui context struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine struct ImGuiDataVarInfo; // Variable information (e.g. to access style variables from an enum) struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum +struct ImGuiDeactivatedItemData; // Data for IsItemDeactivated()/IsItemDeactivatedAfterEdit() function. struct ImGuiErrorRecoveryState; // Storage of stack sizes for error handling and recovery struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box @@ -1070,7 +1071,7 @@ struct IMGUI_API ImGuiGroupData ImVec2 BackupCurrLineSize; float BackupCurrLineTextBaseOffset; ImGuiID BackupActiveIdIsAlive; - bool BackupActiveIdPreviousFrameIsAlive; + bool BackupDeactivatedIdIsAlive; bool BackupHoveredIdIsAlive; bool BackupIsSameLine; bool EmitItem; @@ -1314,6 +1315,15 @@ struct ImGuiPtrOrIndex ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } }; +// Data used by IsItemDeactivated()/IsItemDeactivatedAfterEdit() functions +struct ImGuiDeactivatedItemData +{ + ImGuiID ID; + int ElapseFrame; + bool HasBeenEditedBefore; + bool IsAlive; +}; + //----------------------------------------------------------------------------- // [SECTION] Popup support //----------------------------------------------------------------------------- @@ -2106,9 +2116,7 @@ struct ImGuiContext ImGuiWindow* ActiveIdWindow; ImGuiInputSource ActiveIdSource; // Activating source: ImGuiInputSource_Mouse OR ImGuiInputSource_Keyboard OR ImGuiInputSource_Gamepad ImGuiID ActiveIdPreviousFrame; - bool ActiveIdPreviousFrameIsAlive; - bool ActiveIdPreviousFrameHasBeenEditedBefore; - ImGuiWindow* ActiveIdPreviousFrameWindow; + ImGuiDeactivatedItemData DeactivatedItemData; ImGuiDataTypeStorage ActiveIdValueOnActivation; // Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX. ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation. float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. From 00f12b9a09d2a39831eb8dfc4f75f11460768a6e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 15:22:45 +0100 Subject: [PATCH 0599/2359] InputText: Fixed not calling CallbackEdit on revert/clear with Escape key. (#8273) + rework comments. Seems like there is no reason to not run that path. Amend ancient 9501cd99, f3ab5e625 --- docs/CHANGELOG.txt | 2 ++ imgui.h | 4 ++-- imgui_widgets.cpp | 14 ++++++-------- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1f1eb05a9..5753d10db 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,8 @@ Other changes: value is being modified. (#8242) - InputText: Added sanity check to detect some cases of passing a non zero-terminated input buffer. +- InputText: Fixed not calling CallbackEdit on revert/clear with Escape key, + although IsItemEdited() was behaving correctly. (#8273) - Tables: Fixed TableAngledHeadersRow() creating an infinite horizontal scrolling region when the table is hosted in a viewport with negative coordinates. diff --git a/imgui.h b/imgui.h index 5a3a7af65..a89a6c621 100644 --- a/imgui.h +++ b/imgui.h @@ -1182,7 +1182,7 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_CallbackAlways = 1 << 20, // Callback on each iteration. User code may query cursor position, modify text buffer. ImGuiInputTextFlags_CallbackCharFilter = 1 << 21, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. ImGuiInputTextFlags_CallbackResize = 1 << 22, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) - ImGuiInputTextFlags_CallbackEdit = 1 << 23, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) + ImGuiInputTextFlags_CallbackEdit = 1 << 23, // Callback on any edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. // Obsolete names //ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior @@ -2442,7 +2442,7 @@ struct ImGuiIO // Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. // The callback function should return 0 by default. // Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) -// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) +// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. // - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration // - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB // - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 854f09634..725f6de2a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4977,19 +4977,17 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } } - // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer - // before clearing ActiveId, even though strictly speaking it wasn't modified on this frame. - // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. - // This also allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage + // FIXME-OPT: We always reapply the live buffer back to the input buffer before clearing ActiveId, + // even though strictly speaking it wasn't modified on this frame. Should mark dirty state from the stb_textedit callbacks. + // If we do that, need to ensure that as special case, 'validated == true' also writes back. + // This also allows the user to use InputText() without maintaining any user-side storage. // (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object // unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize). - const bool apply_edit_back_to_user_buffer = !revert_edit || (validated && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0); + const bool apply_edit_back_to_user_buffer = true;// !revert_edit || (validated && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0); if (apply_edit_back_to_user_buffer) { - // Apply new value immediately - copy modified buffer back + // Apply current edited text immediately. // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer - // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. - // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. // User callback if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0) From 32cea853317c6ee1dbfb4f08925b410956366ed7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 15:51:39 +0100 Subject: [PATCH 0600/2359] Debug Tools: Item Picker: Always available in menu. Tweak Demo Debug Options. (#2673, #1651) --- docs/CHANGELOG.txt | 3 +++ imgui_demo.cpp | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5753d10db..8d3ced68e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,7 @@ Other changes: a child window, and from nested child windows. (#1651) - Error Handling: Turned common EndTable() and other TableXXX functions fail cases into a recoverable error. (#1651, #8314) +- Error Handling: Exposed some options in Demo->Tools->Debug Options. (#1651) - InputText: Fixed a bug where character replacements performed from a callback were not applied when pasting from clipbard. (#8229) - InputText: Fixed issue when activating a ReadOnly field when the underlying @@ -76,6 +77,8 @@ Other changes: windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) - Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) +- Debug Tools: Item Picker: Always available regardless of value of + io.ConfigDebugIsDebuggerPresent. (#2673) - Fonts: Fixed miscalculation of Ellipsis ("...") character width when automatically created from a single comma character, affecting some fonts/settings (not all). - Demo: Added label edition to Property Editor demo + fix an ID issue. (#8266) [@moritz-h] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c9a21759d..7bb15d737 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -743,19 +743,27 @@ static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data) #else const bool has_debug_tools = false; #endif + if (ImGui::BeginMenu("Debug Options")) + { + ImGui::BeginDisabled(!has_debug_tools); + ImGui::Checkbox("Highlight ID Conflicts", &io.ConfigDebugHighlightIdConflicts); + ImGui::EndDisabled(); + ImGui::Checkbox("Assert on error recovery", &io.ConfigErrorRecoveryEnableAssert); + ImGui::TextDisabled("(see Demo->Configuration for details & more)"); + ImGui::EndMenu(); + } + ImGui::MenuItem("Metrics/Debugger", NULL, &demo_data->ShowMetrics, has_debug_tools); ImGui::MenuItem("Debug Log", NULL, &demo_data->ShowDebugLog, has_debug_tools); ImGui::MenuItem("ID Stack Tool", NULL, &demo_data->ShowIDStackTool, has_debug_tools); bool is_debugger_present = io.ConfigDebugIsDebuggerPresent; - if (ImGui::MenuItem("Item Picker", NULL, false, has_debug_tools && is_debugger_present)) + if (ImGui::MenuItem("Item Picker", NULL, false, has_debug_tools))// && is_debugger_present)) ImGui::DebugStartItemPicker(); if (!is_debugger_present) - ImGui::SetItemTooltip("Requires io.ConfigDebugIsDebuggerPresent=true to be set.\n\nWe otherwise disable the menu option to avoid casual users crashing the application.\n\nYou can however always access the Item Picker in Metrics->Tools."); + ImGui::SetItemTooltip("Requires io.ConfigDebugIsDebuggerPresent=true to be set.\n\nWe otherwise disable some extra features to avoid casual users crashing the application."); ImGui::MenuItem("Style Editor", NULL, &demo_data->ShowStyleEditor); ImGui::MenuItem("About Dear ImGui", NULL, &demo_data->ShowAbout); - ImGui::SeparatorText("Debug Options"); - ImGui::MenuItem("Highlight ID Conflicts", NULL, &io.ConfigDebugHighlightIdConflicts, has_debug_tools); ImGui::EndMenu(); } ImGui::EndMenuBar(); From 6fb7d442559a4540d3bbbe70d9dfc4a04d60109b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 16:46:29 +0100 Subject: [PATCH 0601/2359] Backends: SDL2/SDL3: Comments. (#7672, #7670) --- backends/imgui_impl_sdl2.cpp | 2 ++ backends/imgui_impl_sdl3.cpp | 3 ++- imgui_demo.cpp | 3 +-- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index e937b5496..0aaf9830a 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -399,6 +399,8 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) if (ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID) == nullptr) return false; ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod); + //IMGUI_DEBUG_LOG("SDL_KEY_%s : key=%d ('%s'), scancode=%d ('%s'), mod=%X\n", + // (event->type == SDL_KEYDOWN) ? "DOWN" : "UP ", event->key.keysym.sym, SDL_GetKeyName(event->key.keysym.sym), event->key.keysym.scancode, SDL_GetScancodeName(event->key.keysym.scancode), event->key.keysym.mod); ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode); io.AddKeyEvent(key, (event->type == SDL_KEYDOWN)); io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index c3935b2ab..b8e4dec5e 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -375,8 +375,9 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) { if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == nullptr) return false; - //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod); ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); + //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%s : key=%d ('%s'), scancode=%d ('%s'), mod=%X\n", + // (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP ", event->key.key, SDL_GetKeyName(event->key.key), event->key.scancode, SDL_GetScancodeName(event->key.scancode), event->key.mod); ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode); io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN)); io.SetKeyEventNativeData(key, event->key.key, event->key.scancode, event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7bb15d737..4bc70fe42 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -743,6 +743,7 @@ static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data) #else const bool has_debug_tools = false; #endif + ImGui::MenuItem("Metrics/Debugger", NULL, &demo_data->ShowMetrics, has_debug_tools); if (ImGui::BeginMenu("Debug Options")) { ImGui::BeginDisabled(!has_debug_tools); @@ -752,8 +753,6 @@ static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data) ImGui::TextDisabled("(see Demo->Configuration for details & more)"); ImGui::EndMenu(); } - - ImGui::MenuItem("Metrics/Debugger", NULL, &demo_data->ShowMetrics, has_debug_tools); ImGui::MenuItem("Debug Log", NULL, &demo_data->ShowDebugLog, has_debug_tools); ImGui::MenuItem("ID Stack Tool", NULL, &demo_data->ShowIDStackTool, has_debug_tools); bool is_debugger_present = io.ConfigDebugIsDebuggerPresent; From 290e402a0206e9c0fb6868f60a007e4f93273d13 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 18:55:09 +0100 Subject: [PATCH 0602/2359] TreeNode, Tables: added ImGuiTreeNodeFlags_LabelSpanAllColumns. (#8318, #3565) --- docs/CHANGELOG.txt | 4 ++++ imgui.h | 7 ++++--- imgui_demo.cpp | 2 ++ imgui_widgets.cpp | 10 +++++++--- 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8d3ced68e..8e2a9419a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,10 @@ Other changes: coordinates. - Tables, MultiSelect: Fixed an issue where column width may be mismeasured when calling BeginMultiSelect() while inside a table. (#8250) +- TreeNode, Tables: Added ImGuiTreeNodeFlags_LabelSpanAllColumns to make + the label (not only the frame) also spans all columns. This can be useful + for table rows where you know nothing else is submitted. (#8318, #3565) + Obviously best used with ImGuiTableFlags_NoBordersInBodyUntilResize. - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard modifiers altering the tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. (#8223) diff --git a/imgui.h b/imgui.h index a89a6c621..8e2821643 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.7 WIP" -#define IMGUI_VERSION_NUM 19165 +#define IMGUI_VERSION_NUM 19166 #define IMGUI_HAS_TABLE /* @@ -1206,9 +1206,10 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode. ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (cover the indent area). ImGuiTreeNodeFlags_SpanTextWidth = 1 << 13, // Narrow hit box + narrow hovering highlight, will only cover the label text. - ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (text will still fit in current column) - ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 15, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) + ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (label will still fit in current column) + ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, // Label will span all columns of its container table //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 17, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4bc70fe42..548ce1b05 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6363,6 +6363,8 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &tree_node_flags, ImGuiTreeNodeFlags_SpanFullWidth); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanTextWidth", &tree_node_flags, ImGuiTreeNodeFlags_SpanTextWidth); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &tree_node_flags, ImGuiTreeNodeFlags_SpanAllColumns); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_LabelSpanAllColumns", &tree_node_flags, ImGuiTreeNodeFlags_LabelSpanAllColumns); + ImGui::SameLine(); HelpMarker("Useful if you know that you aren't displaying contents in other columns"); HelpMarker("See \"Columns flags\" section to configure how indentation is applied to individual columns."); if (ImGui::BeginTable("3ways", 3, flags)) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 725f6de2a..44fe25f1a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6532,6 +6532,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // We vertically grow up to current line height up the typical widget height. const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2); const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL); + const bool span_all_columns_label = (flags & ImGuiTreeNodeFlags_LabelSpanAllColumns) != 0 && (g.CurrentTable != NULL); ImRect frame_bb; frame_bb.Min.x = span_all_columns ? window->ParentWorkRect.Min.x : (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x; frame_bb.Min.y = window->DC.CursorPos.y; @@ -6557,7 +6558,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l bool is_open = TreeNodeUpdateNextOpen(storage_id, flags); bool is_visible; - if (span_all_columns) + if (span_all_columns || span_all_columns_label) { // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. const float backup_clip_rect_min_x = window->ClipRect.Min.x; @@ -6598,7 +6599,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l return is_open; } - if (span_all_columns) + if (span_all_columns || span_all_columns_label) { TablePushBackgroundChannel(); g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect; @@ -6751,7 +6752,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l LogSetNextTextDecoration(">", NULL); } - if (span_all_columns) + if (span_all_columns && !span_all_columns_label) TablePopBackgroundChannel(); // Label @@ -6759,6 +6760,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); else RenderText(text_pos, label, label_end, false); + + if (span_all_columns_label) + TablePopBackgroundChannel(); } if (store_tree_node_stack_data && is_open) From c5f60942bdd9f1fb0ae61f3d82510b0c05c16191 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 19:18:05 +0100 Subject: [PATCH 0603/2359] Demo: tweak demo for ImGuiTreeNodeFlags_LabelSpanAllColumns. (#8318, #3565) --- imgui_demo.cpp | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 548ce1b05..cc8afe388 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6357,17 +6357,17 @@ static void ShowDemoWindowTables() IMGUI_DEMO_MARKER("Tables/Tree view"); if (ImGui::TreeNode("Tree view")) { - static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; + static ImGuiTableFlags table_flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; - static ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAllColumns; - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &tree_node_flags, ImGuiTreeNodeFlags_SpanFullWidth); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanTextWidth", &tree_node_flags, ImGuiTreeNodeFlags_SpanTextWidth); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &tree_node_flags, ImGuiTreeNodeFlags_SpanAllColumns); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_LabelSpanAllColumns", &tree_node_flags, ImGuiTreeNodeFlags_LabelSpanAllColumns); + static ImGuiTreeNodeFlags tree_node_flags_base = ImGuiTreeNodeFlags_SpanAllColumns; + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanTextWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanTextWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanAllColumns); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_LabelSpanAllColumns", &tree_node_flags_base, ImGuiTreeNodeFlags_LabelSpanAllColumns); ImGui::SameLine(); HelpMarker("Useful if you know that you aren't displaying contents in other columns"); HelpMarker("See \"Columns flags\" section to configure how indentation is applied to individual columns."); - if (ImGui::BeginTable("3ways", 3, flags)) + if (ImGui::BeginTable("3ways", 3, table_flags)) { // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide); @@ -6388,13 +6388,21 @@ static void ShowDemoWindowTables() ImGui::TableNextRow(); ImGui::TableNextColumn(); const bool is_folder = (node->ChildCount > 0); + + ImGuiTreeNodeFlags node_flags = tree_node_flags_base; + if (node != &all_nodes[0]) + node_flags &= ~ImGuiTreeNodeFlags_LabelSpanAllColumns; // Only demonstrate this on the root node. + if (is_folder) { - bool open = ImGui::TreeNodeEx(node->Name, tree_node_flags); - ImGui::TableNextColumn(); - ImGui::TextDisabled("--"); - ImGui::TableNextColumn(); - ImGui::TextUnformatted(node->Type); + bool open = ImGui::TreeNodeEx(node->Name, node_flags); + if ((node_flags & ImGuiTreeNodeFlags_LabelSpanAllColumns) == 0) + { + ImGui::TableNextColumn(); + ImGui::TextDisabled("--"); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(node->Type); + } if (open) { for (int child_n = 0; child_n < node->ChildCount; child_n++) @@ -6404,7 +6412,7 @@ static void ShowDemoWindowTables() } else { - ImGui::TreeNodeEx(node->Name, tree_node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen); + ImGui::TreeNodeEx(node->Name, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen); ImGui::TableNextColumn(); ImGui::Text("%d", node->Size); ImGui::TableNextColumn(); @@ -6414,7 +6422,7 @@ static void ShowDemoWindowTables() }; static const MyTreeNode nodes[] = { - { "Root", "Folder", -1, 1, 3 }, // 0 + { "Root with Long Name", "Folder", -1, 1, 3 }, // 0 { "Music", "Folder", -1, 4, 2 }, // 1 { "Textures", "Folder", -1, 6, 3 }, // 2 { "desktop.ini", "System file", 1024, -1,-1 }, // 3 From c38c18c1a072d2f31a15722c81393f0585cef9e7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 19:39:57 +0100 Subject: [PATCH 0604/2359] Avoid using 1<<31 for ImGuiWindowFlags_NavFlattened as it seems to confuse some binding generators. --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 8e2821643..c71e7521f 100644 --- a/imgui.h +++ b/imgui.h @@ -1099,8 +1099,8 @@ enum ImGuiWindowFlags_ // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiWindowFlags_NavFlattened = 1 << 29, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call. ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90.0: Use ImGuiChildFlags_AlwaysUseWindowPadding in BeginChild() call. - ImGuiWindowFlags_NavFlattened = 1 << 31, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call. #endif }; From 21902e2f53602ff85e4f23fe4d974864997f4648 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 19:51:15 +0100 Subject: [PATCH 0605/2359] Backends: SDL_GPU: fixed SDL_GPUViewport initialisation. (#8163, #7998, #7988) Probably harmless. Amend 8bbccf7 --- backends/imgui_impl_sdlgpu3.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index e681efdc3..7eb5eeb08 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -100,7 +100,7 @@ static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGra viewport.w = (float)fb_width; viewport.h = (float)fb_height; viewport.min_depth = 0.0f; - viewport.min_depth = 1.0f; + viewport.max_depth = 1.0f; SDL_SetGPUViewport(render_pass,&viewport); // Setup scale and translation From 9f8481a842e45c6490a36818841cc8e34ca003c4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 14 Jan 2025 13:14:50 +0100 Subject: [PATCH 0606/2359] (Breaking) TreeNode: renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth. (#6937) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 1 + imgui.h | 5 +++-- imgui_demo.cpp | 8 ++++---- imgui_widgets.cpp | 4 ++-- 5 files changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8e2a9419a..5e581d0bd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ HOW TO UPDATE? Breaking changes: +- TreeNode: renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth + for consistency with other names. Kept redirection enum (will obsolete). (#6937) + Other changes: - Fixed issues with IsItemDeactivated() and IsItemDeactivatedAfterEdit() not diff --git a/imgui.cpp b/imgui.cpp index 6b9f47164..c0540d697 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937) - 2024/11/27 (1.91.6) - changed CRC32 table from CRC32-adler to CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions. As a result, old .ini data may be partially lost (docking and tables information particularly). Because some users have crafted and storing .ini data as a way to workaround limitations of the docking API, we are providing a '#define IMGUI_USE_LEGACY_CRC32_ADLER' compile-time option to keep using old CRC32 tables if you cannot afford invalidating old .ini data. diff --git a/imgui.h b/imgui.h index c71e7521f..44c1027ec 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.7 WIP" -#define IMGUI_VERSION_NUM 19166 +#define IMGUI_VERSION_NUM 19167 #define IMGUI_HAS_TABLE /* @@ -1205,7 +1205,7 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding() before the node. ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode. ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (cover the indent area). - ImGuiTreeNodeFlags_SpanTextWidth = 1 << 13, // Narrow hit box + narrow hovering highlight, will only cover the label text. + ImGuiTreeNodeFlags_SpanLabelWidth = 1 << 13, // Narrow hit box + narrow hovering highlight, will only cover the label text. ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (label will still fit in current column) ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, // Label will span all columns of its container table //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible @@ -1214,6 +1214,7 @@ enum ImGuiTreeNodeFlags_ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 + ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth,// Renamed in 1.90.7 #endif }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index cc8afe388..0cb45a508 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1122,7 +1122,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &base_flags, ImGuiTreeNodeFlags_SpanFullWidth); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanTextWidth", &base_flags, ImGuiTreeNodeFlags_SpanTextWidth); ImGui::SameLine(); HelpMarker("Reduce hit area to the text label and a bit of margin."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanLabelWidth", &base_flags, ImGuiTreeNodeFlags_SpanLabelWidth); ImGui::SameLine(); HelpMarker("Reduce hit area to the text label and a bit of margin."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); @@ -1159,9 +1159,9 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::Text("This is a drag and drop source"); ImGui::EndDragDropSource(); } - if (i == 2 && (base_flags & ImGuiTreeNodeFlags_SpanTextWidth)) + if (i == 2 && (base_flags & ImGuiTreeNodeFlags_SpanLabelWidth)) { - // Item 2 has an additional inline button to help demonstrate SpanTextWidth. + // Item 2 has an additional inline button to help demonstrate SpanLabelWidth. ImGui::SameLine(); if (ImGui::SmallButton("button")) {} } @@ -6361,7 +6361,7 @@ static void ShowDemoWindowTables() static ImGuiTreeNodeFlags tree_node_flags_base = ImGuiTreeNodeFlags_SpanAllColumns; ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanFullWidth); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanTextWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanTextWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanLabelWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanLabelWidth); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_LabelSpanAllColumns", &tree_node_flags_base, ImGuiTreeNodeFlags_LabelSpanAllColumns); ImGui::SameLine(); HelpMarker("Useful if you know that you aren't displaying contents in other columns"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 44fe25f1a..7fc082df3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6536,7 +6536,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l ImRect frame_bb; frame_bb.Min.x = span_all_columns ? window->ParentWorkRect.Min.x : (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x; frame_bb.Min.y = window->DC.CursorPos.y; - frame_bb.Max.x = span_all_columns ? window->ParentWorkRect.Max.x : (flags & ImGuiTreeNodeFlags_SpanTextWidth) ? window->DC.CursorPos.x + text_width + padding.x : window->WorkRect.Max.x; + frame_bb.Max.x = span_all_columns ? window->ParentWorkRect.Max.x : (flags & ImGuiTreeNodeFlags_SpanLabelWidth) ? window->DC.CursorPos.x + text_width + padding.x : window->WorkRect.Max.x; frame_bb.Max.y = window->DC.CursorPos.y + frame_height; if (display_frame) { @@ -6550,7 +6550,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing ImRect interact_bb = frame_bb; - if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanTextWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0) + if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanLabelWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0) interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f); // Compute open and multi-select states before ItemAdd() as it clear NextItem data. From 5c1d2d1e4c562a2ed3efbc64476e703a655b45fd Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 14 Jan 2025 13:16:43 +0100 Subject: [PATCH 0607/2359] Version 1.91.7 --- docs/CHANGELOG.txt | 22 ++++++++++++---------- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 21 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5e581d0bd..462de35fb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.91.7 WIP (In Progress) + VERSION 1.91.7 (Released 2025-01-14) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.7 + Breaking changes: - TreeNode: renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth @@ -59,9 +61,9 @@ Other changes: a child window, and from nested child windows. (#1651) - Error Handling: Turned common EndTable() and other TableXXX functions fail cases into a recoverable error. (#1651, #8314) -- Error Handling: Exposed some options in Demo->Tools->Debug Options. (#1651) +- Error Handling: Basic error handling options in Demo->Tools->Debug Options. (#1651) - InputText: Fixed a bug where character replacements performed from a callback - were not applied when pasting from clipbard. (#8229) + were not applied when pasting from clipboard. (#8229) - InputText: Fixed issue when activating a ReadOnly field when the underlying value is being modified. (#8242) - InputText: Added sanity check to detect some cases of passing a non @@ -70,12 +72,12 @@ Other changes: although IsItemEdited() was behaving correctly. (#8273) - Tables: Fixed TableAngledHeadersRow() creating an infinite horizontal scrolling region when the table is hosted in a viewport with negative - coordinates. + coordinates (left of primary monitor, with multi-viewports enabled). - Tables, MultiSelect: Fixed an issue where column width may be mismeasured when calling BeginMultiSelect() while inside a table. (#8250) - TreeNode, Tables: Added ImGuiTreeNodeFlags_LabelSpanAllColumns to make - the label (not only the frame) also spans all columns. This can be useful - for table rows where you know nothing else is submitted. (#8318, #3565) + the label (not only the highlight/frame) also spans all columns. This is + useful for table rows where you know nothing else is submitted. (#8318, #3565) Obviously best used with ImGuiTableFlags_NoBordersInBodyUntilResize. - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard modifiers altering the tweak speed. Useful if you want to alter tweak speed @@ -84,13 +86,13 @@ Other changes: windows with the ImGuiWindowFlags_NoNavInputs flag. (#8231) - Debug Tools: Debug Log: hovering 0xXXXXXXXX values in log is allowed even if a popup is blocking mouse access to the debug log window. (#5855) -- Debug Tools: Item Picker: Always available regardless of value of - io.ConfigDebugIsDebuggerPresent. (#2673) +- Debug Tools: Item Picker: Always available in Tools menu regardless of value + of io.ConfigDebugIsDebuggerPresent. (#2673) - Fonts: Fixed miscalculation of Ellipsis ("...") character width when automatically created from a single comma character, affecting some fonts/settings (not all). - Demo: Added label edition to Property Editor demo + fix an ID issue. (#8266) [@moritz-h] - Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] -- Misc: Fixed MinGW builds uses UTF-8 friendly _wfopen(). (#8300) +- Misc: Fixed MinGW builds not using UTF-8 friendly _wfopen(). (#8300) - Backends: SDL_GPU for SDL3: Added backend for SDL_GPU! (#8163, #7998, #7988) [@DeltaW0x]. - Backends: SDL3: Added ImGui_ImplSDL3_InitForSDLGPU() for consistency, even though it is currently not doing anything particular. (#8163, #7998, #7988) @@ -105,7 +107,7 @@ Other changes: - Backends: Vulkan: Added IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE to clarify how many image sampler descriptors are expected to be available in the provided descriptor pool. Current backend needs 1 but it is expected that by end of Q1 2025 - this number will grow (will staying a very small number). (#6642) + this number will grow (will stay a small number). (#6642) - Backends: DX11: Expose vertex constant buffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handlers. (#6969, #5834, #7468, #3590) - Backends: DX10: Expose ImGui_ImplDX10_RenderState for completeness. (#6969, #5834, #7468, #3590) diff --git a/imgui.cpp b/imgui.cpp index c0540d697..63dbd1fe8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 WIP +// dear imgui, v1.91.7 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 44c1027ec..0f7bdbbc6 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 WIP +// dear imgui, v1.91.7 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.7 WIP" -#define IMGUI_VERSION_NUM 19167 +#define IMGUI_VERSION "1.91.7" +#define IMGUI_VERSION_NUM 19170 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0cb45a508..d0e41f370 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 WIP +// dear imgui, v1.91.7 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8baaf8b11..344eae9e8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 WIP +// dear imgui, v1.91.7 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index bb5a56774..f3f915d7e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 WIP +// dear imgui, v1.91.7 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ec25bf906..efef5ff74 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 WIP +// dear imgui, v1.91.7 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7fc082df3..dd27400cd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 WIP +// dear imgui, v1.91.7 // (widgets code) /* From c59a2267d0977d7261a78c884ccf7735345c4060 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 11:58:47 +0100 Subject: [PATCH 0608/2359] Version 1.91.8 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 462de35fb..373dcd108 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.91.8 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking changes: + +Other changes: + + ----------------------------------------------------------------------- VERSION 1.91.7 (Released 2025-01-14) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 63dbd1fe8..678ff2e52 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 +// dear imgui, v1.91.8 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 0f7bdbbc6..cd7c92593 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 +// dear imgui, v1.91.8 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.7" -#define IMGUI_VERSION_NUM 19170 +#define IMGUI_VERSION "1.91.8 WIP" +#define IMGUI_VERSION_NUM 19171 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d0e41f370..26c246db6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 +// dear imgui, v1.91.8 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 344eae9e8..e8c445dd3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 +// dear imgui, v1.91.8 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index f3f915d7e..9db5fde5e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 +// dear imgui, v1.91.8 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index efef5ff74..e0df575c4 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 +// dear imgui, v1.91.8 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index dd27400cd..71a5c5b9a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.7 +// dear imgui, v1.91.8 WIP // (widgets code) /* From 100075f2be6a16d6569f6c591c2a908394f414eb Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 12:05:33 +0100 Subject: [PATCH 0609/2359] Backends: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. + minor tweaks to faciliate branch merging. --- backends/imgui_impl_dx12.cpp | 53 ++++++++++++++++-------------------- docs/CHANGELOG.txt | 3 ++ imgui.cpp | 1 + 3 files changed, 28 insertions(+), 29 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 24fdb7aa0..6f17f587a 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -19,6 +19,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat. // 2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete). // 2024-11-15: DirectX12: *BREAKING CHANGE* User is now required to pass function pointers to allocate/free SRV Descriptors. We provide convenience legacy fields to pass a single descriptor, matching the old API, but upcoming features will want multiple. @@ -64,6 +65,8 @@ struct ImGui_ImplDX12_Texture ID3D12Resource* pTextureResource; D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle; D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle; + + ImGui_ImplDX12_Texture() { memset((void*)this, 0, sizeof(*this)); } }; struct ImGui_ImplDX12_Data @@ -180,8 +183,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; - // FIXME: I'm assuming that this only gets called once per frame! - // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. + // FIXME: We are assuming that this only gets called once per frame! ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); bd->frameIndex = bd->frameIndex + 1; ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight]; @@ -352,11 +354,11 @@ static void ImGui_ImplDX12_CreateFontsTexture() bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture)); - UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); - UINT uploadSize = height * uploadPitch; + UINT upload_pitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); + UINT upload_size = height * upload_pitch; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Alignment = 0; - desc.Width = uploadSize; + desc.Width = upload_size; desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; @@ -376,26 +378,28 @@ static void ImGui_ImplDX12_CreateFontsTexture() IM_ASSERT(SUCCEEDED(hr)); void* mapped = nullptr; - D3D12_RANGE range = { 0, uploadSize }; + D3D12_RANGE range = { 0, upload_size }; hr = uploadBuffer->Map(0, &range, &mapped); IM_ASSERT(SUCCEEDED(hr)); for (int y = 0; y < height; y++) - memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4); + memcpy((void*) ((uintptr_t) mapped + y * upload_pitch), pixels + y * width * 4, width * 4); uploadBuffer->Unmap(0, &range); D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; - srcLocation.pResource = uploadBuffer; - srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - srcLocation.PlacedFootprint.Footprint.Width = width; - srcLocation.PlacedFootprint.Footprint.Height = height; - srcLocation.PlacedFootprint.Footprint.Depth = 1; - srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch; - D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; - dstLocation.pResource = pTexture; - dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - dstLocation.SubresourceIndex = 0; + { + srcLocation.pResource = uploadBuffer; + srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srcLocation.PlacedFootprint.Footprint.Width = width; + srcLocation.PlacedFootprint.Footprint.Height = height; + srcLocation.PlacedFootprint.Footprint.Depth = 1; + srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch; + + dstLocation.pResource = pTexture; + dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dstLocation.SubresourceIndex = 0; + } D3D12_RESOURCE_BARRIER barrier = {}; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; @@ -412,15 +416,6 @@ static void ImGui_ImplDX12_CreateFontsTexture() HANDLE event = ::CreateEvent(0, 0, 0, 0); IM_ASSERT(event != nullptr); - D3D12_COMMAND_QUEUE_DESC queueDesc = {}; - queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; - queueDesc.NodeMask = 1; - - ID3D12CommandQueue* cmdQueue = nullptr; - hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue)); - IM_ASSERT(SUCCEEDED(hr)); - ID3D12CommandAllocator* cmdAlloc = nullptr; hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); IM_ASSERT(SUCCEEDED(hr)); @@ -435,6 +430,7 @@ static void ImGui_ImplDX12_CreateFontsTexture() hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); + ID3D12CommandQueue* cmdQueue = bd->InitInfo.CommandQueue; cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); hr = cmdQueue->Signal(fence, 1); IM_ASSERT(SUCCEEDED(hr)); @@ -444,7 +440,6 @@ static void ImGui_ImplDX12_CreateFontsTexture() cmdList->Release(); cmdAlloc->Release(); - cmdQueue->Release(); ::CloseHandle(event); fence->Release(); uploadBuffer->Release(); @@ -707,11 +702,11 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() if (!bd || !bd->pd3dDevice) return; - ImGuiIO& io = ImGui::GetIO(); SafeRelease(bd->pRootSignature); SafeRelease(bd->pPipelineState); // Free SRV descriptor used by texture + ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture; bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, font_tex->hFontSrvCpuDescHandle, font_tex->hFontSrvGpuDescHandle); SafeRelease(font_tex->pTextureResource); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 373dcd108..7b0f545ee 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- Backends: DirectX12: Texture upload use the command queue provided in + ImGui_ImplDX12_InitInfo instead of creating its own. + ----------------------------------------------------------------------- VERSION 1.91.7 (Released 2025-01-14) diff --git a/imgui.cpp b/imgui.cpp index 678ff2e52..009a9abf1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5086,6 +5086,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() } // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. +// FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! static void SetupDrawListSharedData() { ImGuiContext& g = *GImGui; From 8a9de84cd0130110ce6d1411558a8d59d7169ae3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 13:47:52 +0100 Subject: [PATCH 0610/2359] FontAtlas: reduced baked IM_DRAWLIST_TEX_LINES_WIDTH_MAX from 63 to 32. (#3245) --- docs/CHANGELOG.txt | 1 + imgui.h | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7b0f545ee..0ca9af5a2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,7 @@ Breaking changes: Other changes: +- ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) - Backends: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. diff --git a/imgui.h b/imgui.h index cd7c92593..d4c8edb36 100644 --- a/imgui.h +++ b/imgui.h @@ -2923,7 +2923,7 @@ struct ImGuiSelectionExternalStorage // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. #ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (63) +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) #endif // ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] @@ -2997,7 +2997,6 @@ struct ImDrawChannel ImVector _IdxBuffer; }; - // Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. // This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call. struct ImDrawListSplitter From 0e21bde77b0647b872cc4e571b3c05f54d2e556e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 13:58:38 +0100 Subject: [PATCH 0611/2359] Misc shallow merge to reduce diff in other branches. --- backends/imgui_impl_dx10.cpp | 2 +- backends/imgui_impl_opengl2.cpp | 12 +++++++++++- imgui.h | 8 +++++--- imgui_internal.h | 8 ++++++++ 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 89499af0c..5471eef53 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -47,7 +47,7 @@ #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif -// DirectX data +// DirectX10 data struct ImGui_ImplDX10_Data { ID3D10Device* pd3dDevice; diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp index 767731fb3..2a255be4c 100644 --- a/backends/imgui_impl_opengl2.cpp +++ b/backends/imgui_impl_opengl2.cpp @@ -69,6 +69,16 @@ #include #endif +// [Debugging] +//#define IMGUI_IMPL_OPENGL_DEBUG +#ifdef IMGUI_IMPL_OPENGL_DEBUG +#include +#define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) fprintf(stderr, "GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check +#else +#define GL_CALL(_CALL) _CALL // Call without error check +#endif + +// OpenGL data struct ImGui_ImplOpenGL2_Data { GLuint FontTexture; @@ -155,7 +165,7 @@ static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_wid // Setup viewport, 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. - glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); + GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height)); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); diff --git a/imgui.h b/imgui.h index d4c8edb36..b9a4fe158 100644 --- a/imgui.h +++ b/imgui.h @@ -158,7 +158,7 @@ typedef unsigned int ImU32; // 32-bit unsigned integer (often used to st typedef signed long long ImS64; // 64-bit signed integer typedef unsigned long long ImU64; // 64-bit unsigned integer -// Forward declarations +// Forward declarations: ImDrawList, ImFontAtlas layer struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit() struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback) struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix. @@ -173,6 +173,8 @@ struct ImFontConfig; // Configuration data when adding a font or struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) + +// Forward declarations: ImGui layer struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h) struct ImGuiIO; // Main configuration and I/O between your application and ImGui (also see: ImGuiPlatformIO) struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) @@ -3374,7 +3376,7 @@ struct ImFontAtlas IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters //------------------------------------------- - // [BETA] Custom Rectangles/Glyphs API + // [ALPHA] Custom Rectangles/Glyphs API //------------------------------------------- // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. @@ -3400,11 +3402,11 @@ struct ImFontAtlas ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). - bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). // [Internal] // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. + bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. bool TexReady; // Set when texture was built matching current font input bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format. unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight diff --git a/imgui_internal.h b/imgui_internal.h index 9db5fde5e..12d8f7a51 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -130,10 +130,17 @@ Index of this file: // [SECTION] Forward declarations //----------------------------------------------------------------------------- +// Utilities +// (other types which are not forwarded declared are: ImBitArray<>, ImSpan<>, ImSpanAllocator<>, ImPool<>, ImChunkStream<>) struct ImBitVector; // Store 1-bit per value struct ImRect; // An axis-aligned rectangle (2 points) +struct ImGuiTextIndex; // Maintain a line index for a text buffer. + +// ImDrawList/ImFontAtlas struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances + +// ImGui struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it struct ImGuiContext; // Main Dear ImGui context @@ -736,6 +743,7 @@ struct ImGuiTextIndex // Helper: ImGuiStorage IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key); + //----------------------------------------------------------------------------- // [SECTION] ImDrawList support //----------------------------------------------------------------------------- From 6684984c49bf2975b2f1e257daf0cd216d55f1e8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 15:13:05 +0100 Subject: [PATCH 0612/2359] Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. --- docs/CHANGELOG.txt | 2 ++ examples/example_win32_directx12/main.cpp | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0ca9af5a2..27e447ec3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,8 @@ Breaking changes: Other changes: - ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) +- Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in + provided example, to reduce latency. - Backends: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 392ba18aa..5b1a7af37 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -23,8 +23,8 @@ #endif // Config for example app -static const int APP_NUM_FRAMES_IN_FLIGHT = 3; -static const int APP_NUM_BACK_BUFFERS = 3; +static const int APP_NUM_FRAMES_IN_FLIGHT = 2; +static const int APP_NUM_BACK_BUFFERS = 2; static const int APP_SRV_HEAP_SIZE = 64; struct FrameContext From 8ebf22d3c11ee89840d43f415cb48c947908a927 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 16:10:47 +0100 Subject: [PATCH 0613/2359] Backends: Vulkan: use ImVector<> for simplicity. --- backends/imgui_impl_vulkan.cpp | 32 +++++++++++++------------------- backends/imgui_impl_vulkan.h | 4 ++-- 2 files changed, 15 insertions(+), 21 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 940ea2d79..f4bd50694 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -216,7 +216,7 @@ struct ImGui_ImplVulkan_WindowRenderBuffers { uint32_t Index; uint32_t Count; - ImGui_ImplVulkan_FrameRenderBuffers* FrameRenderBuffers; + ImVector FrameRenderBuffers; }; struct ImGui_ImplVulkan_Texture @@ -501,12 +501,12 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Allocate array to store enough vertex/index buffers ImGui_ImplVulkan_WindowRenderBuffers* wrb = &bd->MainWindowRenderBuffers; - if (wrb->FrameRenderBuffers == nullptr) + if (wrb->FrameRenderBuffers.Size == 0) { wrb->Index = 0; wrb->Count = v->ImageCount; - wrb->FrameRenderBuffers = (ImGui_ImplVulkan_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count); - memset((void*)wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count); + wrb->FrameRenderBuffers.resize(wrb->Count); + memset((void*)wrb->FrameRenderBuffers.Data, 0, wrb->FrameRenderBuffers.size_in_bytes()); } IM_ASSERT(wrb->Count == v->ImageCount); wrb->Index = (wrb->Index + 1) % wrb->Count; @@ -1250,8 +1250,7 @@ void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulk { for (uint32_t n = 0; n < buffers->Count; n++) ImGui_ImplVulkan_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator); - IM_FREE(buffers->FrameRenderBuffers); - buffers->FrameRenderBuffers = nullptr; + buffers->FrameRenderBuffers.clear(); buffers->Index = 0; buffers->Count = 0; } @@ -1460,10 +1459,8 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); for (uint32_t i = 0; i < wd->SemaphoreCount; i++) ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); - IM_FREE(wd->Frames); - IM_FREE(wd->FrameSemaphores); - wd->Frames = nullptr; - wd->FrameSemaphores = nullptr; + wd->Frames.clear(); + wd->FrameSemaphores.clear(); wd->ImageCount = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); @@ -1518,12 +1515,11 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers); check_vk_result(err); - IM_ASSERT(wd->Frames == nullptr && wd->FrameSemaphores == nullptr); wd->SemaphoreCount = wd->ImageCount + 1; - wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount); - wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->SemaphoreCount); - memset((void*)wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount); - memset((void*)wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->SemaphoreCount); + wd->Frames.resize(wd->ImageCount); + wd->FrameSemaphores.resize(wd->SemaphoreCount); + memset(wd->Frames.Data, 0, wd->Frames.size_in_bytes()); + memset(wd->FrameSemaphores.Data, 0, wd->FrameSemaphores.size_in_bytes()); for (uint32_t i = 0; i < wd->ImageCount; i++) wd->Frames[i].Backbuffer = backbuffers[i]; } @@ -1633,10 +1629,8 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); for (uint32_t i = 0; i < wd->SemaphoreCount; i++) ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); - IM_FREE(wd->Frames); - IM_FREE(wd->FrameSemaphores); - wd->Frames = nullptr; - wd->FrameSemaphores = nullptr; + wd->Frames.clear(); + wd->FrameSemaphores.clear(); vkDestroyPipeline(device, wd->Pipeline, allocator); vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 3bd994864..6f4839c13 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -207,8 +207,8 @@ struct ImGui_ImplVulkanH_Window uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) - ImGui_ImplVulkanH_Frame* Frames; - ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; + ImVector Frames; + ImVector FrameSemaphores; ImGui_ImplVulkanH_Window() { From 0f33d7185fefb5351858e288eb28da698867d461 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 17:25:44 +0100 Subject: [PATCH 0614/2359] Examples: Vulkan: vkAcquireNextImageKHR() and vkQueuePresentKHR() returning VK_SUBOPTIMAL_KHR keeps moving forward. (#7825, #7831) --- docs/CHANGELOG.txt | 2 ++ examples/example_glfw_vulkan/main.cpp | 18 ++++++++---------- examples/example_sdl2_vulkan/main.cpp | 18 ++++++++---------- examples/example_sdl3_vulkan/main.cpp | 18 ++++++++---------- examples/example_win32_vulkan/main.cpp | 18 ++++++++---------- 5 files changed, 34 insertions(+), 40 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 27e447ec3..429785637 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,8 @@ Other changes: - ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. +- Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by + vkAcquireNextImageKHR() or vkQueuePresentKHR(). (#7825, #7831) [@NostraMagister] - Backends: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index b61dcaae0..31da972df 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -61,7 +61,7 @@ static void glfw_error_callback(int error, const char* description) } static void check_vk_result(VkResult err) { - if (err == 0) + if (err == VK_SUCCESS) return; fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) @@ -263,17 +263,15 @@ static void CleanupVulkanWindow() static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { - VkResult err; - VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; - err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + VkResult err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) - { g_SwapChainRebuild = true; + if (err == VK_ERROR_OUT_OF_DATE_KHR) return; - } - check_vk_result(err); + if (err != VK_SUBOPTIMAL_KHR) + check_vk_result(err); ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; { @@ -342,11 +340,11 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) - { g_SwapChainRebuild = true; + if (err == VK_ERROR_OUT_OF_DATE_KHR) return; - } - check_vk_result(err); + if (err != VK_SUBOPTIMAL_KHR) + check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores } diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index b82ed0b7a..0d7a4586e 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -49,7 +49,7 @@ static bool g_SwapChainRebuild = false; static void check_vk_result(VkResult err) { - if (err == 0) + if (err == VK_SUCCESS) return; fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) @@ -251,17 +251,15 @@ static void CleanupVulkanWindow() static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { - VkResult err; - VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; - err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + VkResult err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) - { g_SwapChainRebuild = true; + if (err == VK_ERROR_OUT_OF_DATE_KHR) return; - } - check_vk_result(err); + if (err != VK_SUBOPTIMAL_KHR) + check_vk_result(err); ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; { @@ -330,11 +328,11 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) - { g_SwapChainRebuild = true; + if (err == VK_ERROR_OUT_OF_DATE_KHR) return; - } - check_vk_result(err); + if (err != VK_SUBOPTIMAL_KHR) + check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores } diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index e36f87194..81f0581e9 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -54,7 +54,7 @@ static bool g_SwapChainRebuild = false; static void check_vk_result(VkResult err) { - if (err == 0) + if (err == VK_SUCCESS) return; fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) @@ -256,17 +256,15 @@ static void CleanupVulkanWindow() static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { - VkResult err; - VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; - err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + VkResult err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) - { g_SwapChainRebuild = true; + if (err == VK_ERROR_OUT_OF_DATE_KHR) return; - } - check_vk_result(err); + if (err != VK_SUBOPTIMAL_KHR) + check_vk_result(err); ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; { @@ -335,11 +333,11 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) - { g_SwapChainRebuild = true; + if (err == VK_ERROR_OUT_OF_DATE_KHR) return; - } - check_vk_result(err); + if (err != VK_SUBOPTIMAL_KHR) + check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores } diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index c6c138695..f337d8e7d 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -50,7 +50,7 @@ static bool g_SwapChainRebuild = false; static void check_vk_result(VkResult err) { - if (err == 0) + if (err == VK_SUCCESS) return; fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) @@ -252,17 +252,15 @@ static void CleanupVulkanWindow() static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { - VkResult err; - VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; - err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + VkResult err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) - { g_SwapChainRebuild = true; + if (err == VK_ERROR_OUT_OF_DATE_KHR) return; - } - check_vk_result(err); + if (err != VK_SUBOPTIMAL_KHR) + check_vk_result(err); ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; { @@ -331,11 +329,11 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) - { g_SwapChainRebuild = true; + if (err == VK_ERROR_OUT_OF_DATE_KHR) return; - } - check_vk_result(err); + if (err != VK_SUBOPTIMAL_KHR) + check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores } From b4a5d1dc531254d7079c3bebdc564fa5817c3be7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 12:42:54 +0100 Subject: [PATCH 0615/2359] Backends: SDLGPU3: Rename GpuDevice->Device. Expose ImGui_ImplSDLGPU3_CreateDeviceObjects(), ImGui_ImplSDLGPU3_DestroyDeviceObjects(). Misc renaming. (#8163, #7998, #7988) --- backends/imgui_impl_sdlgpu3.cpp | 127 ++++++++++++------------- backends/imgui_impl_sdlgpu3.h | 19 ++-- docs/CHANGELOG.txt | 7 +- examples/example_sdl3_sdlgpu3/main.cpp | 2 +- 4 files changed, 80 insertions(+), 75 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 7eb5eeb08..b508e091a 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -21,13 +21,16 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG -// 2025-01-09: SDL_Gpu: Added the SDL_GPU3 backend. +// 2025-01-16: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device. +// 2025-01-09: SDL_GPU: Added the SDL_GPU3 backend. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_sdlgpu3.h" #include "imgui_impl_sdlgpu3_shaders.h" +// SDL_GPU Data + // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData() struct ImGui_ImplSDLGPU3_FrameData { @@ -37,10 +40,9 @@ struct ImGui_ImplSDLGPU3_FrameData uint32_t IndexBufferSize = 0; }; -// SDL_GPU Data struct ImGui_ImplSDLGPU3_Data { - ImGui_ImplSDLGPU3_InitInfo GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo InitInfo; // Graphics pipeline & shaders SDL_GPUShader* VertexShader = nullptr; @@ -57,8 +59,6 @@ struct ImGui_ImplSDLGPU3_Data }; // Forward Declarations -static bool ImGui_ImplSDLGPU3_CreateDeviceObjects(); -static void ImGui_ImplSDLGPU3_DestroyDeviceObjects(); static void ImGui_ImplSDLGPU3_DestroyFrameData(); //----------------------------------------------------------------------------- @@ -116,16 +116,16 @@ static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGra static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer, uint32_t* old_size, uint32_t new_size, SDL_GPUBufferUsageFlags usage) { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - SDL_WaitForGPUIdle(v->GpuDevice); - SDL_ReleaseGPUBuffer(v->GpuDevice, *buffer); + SDL_WaitForGPUIdle(v->Device); + SDL_ReleaseGPUBuffer(v->Device, *buffer); SDL_GPUBufferCreateInfo buffer_info = {}; buffer_info.usage = usage; buffer_info.size = new_size; buffer_info.props = 0; - *buffer = SDL_CreateGPUBuffer(v->GpuDevice, &buffer_info); + *buffer = SDL_CreateGPUBuffer(v->Device, &buffer_info); *old_size = new_size; IM_ASSERT(*buffer != nullptr && "Failed to create GPU Buffer, call SDL_GetError() for more information"); } @@ -142,7 +142,7 @@ void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff return; ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData; uint32_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); @@ -160,13 +160,13 @@ void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff index_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; index_transferbuffer_info.size = index_size; - SDL_GPUTransferBuffer* vertex_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice, &vertex_transferbuffer_info); + SDL_GPUTransferBuffer* vertex_transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &vertex_transferbuffer_info); IM_ASSERT(vertex_transferbuffer != nullptr && "Failed to create the vertex transfer buffer, call SDL_GetError() for more information"); - SDL_GPUTransferBuffer* index_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice, &index_transferbuffer_info); + SDL_GPUTransferBuffer* index_transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &index_transferbuffer_info); IM_ASSERT(index_transferbuffer != nullptr && "Failed to create the index transfer buffer, call SDL_GetError() for more information"); - ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->GpuDevice, vertex_transferbuffer, true); - ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->GpuDevice, index_transferbuffer, true); + ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->Device, vertex_transferbuffer, true); + ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->Device, index_transferbuffer, true); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* draw_list = draw_data->CmdLists[n]; @@ -175,8 +175,8 @@ void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff vtx_dst += draw_list->VtxBuffer.Size; idx_dst += draw_list->IdxBuffer.Size; } - SDL_UnmapGPUTransferBuffer(v->GpuDevice, vertex_transferbuffer); - SDL_UnmapGPUTransferBuffer(v->GpuDevice, index_transferbuffer); + SDL_UnmapGPUTransferBuffer(v->Device, vertex_transferbuffer); + SDL_UnmapGPUTransferBuffer(v->Device, index_transferbuffer); SDL_GPUTransferBufferLocation vertex_buffer_location = {}; vertex_buffer_location.offset = 0; @@ -199,8 +199,8 @@ void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff SDL_UploadToGPUBuffer(copy_pass, &vertex_buffer_location, &vertex_buffer_region,true); SDL_UploadToGPUBuffer(copy_pass, &index_buffer_location, &index_buffer_region,true); SDL_EndGPUCopyPass(copy_pass); - SDL_ReleaseGPUTransferBuffer(v->GpuDevice, index_transferbuffer); - SDL_ReleaseGPUTransferBuffer(v->GpuDevice, vertex_transferbuffer); + SDL_ReleaseGPUTransferBuffer(v->Device, index_transferbuffer); + SDL_ReleaseGPUTransferBuffer(v->Device, vertex_transferbuffer); } void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline) @@ -278,16 +278,16 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe SDL_SetGPUScissor(render_pass, &scissor_rect); } -bool ImGui_ImplSDLGPU3_CreateFontsTexture() +void ImGui_ImplSDLGPU3_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; // Destroy existing texture (if any) if (bd->FontTexture) { - SDL_WaitForGPUIdle(v->GpuDevice); + SDL_WaitForGPUIdle(v->Device); ImGui_ImplSDLGPU3_DestroyFontsTexture(); } @@ -308,7 +308,7 @@ bool ImGui_ImplSDLGPU3_CreateFontsTexture() texture_info.num_levels = 1; texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1; - bd->FontTexture = SDL_CreateGPUTexture(v->GpuDevice, &texture_info); + bd->FontTexture = SDL_CreateGPUTexture(v->Device, &texture_info); IM_ASSERT(bd->FontTexture && "Failed to create font texture, call SDL_GetError() for more info"); } @@ -317,39 +317,37 @@ bool ImGui_ImplSDLGPU3_CreateFontsTexture() // Create all the upload structures and upload: { - SDL_GPUTransferBufferCreateInfo font_transferbuffer_info = {}; - font_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; - font_transferbuffer_info.size = upload_size; + SDL_GPUTransferBufferCreateInfo transferbuffer_info = {}; + transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; + transferbuffer_info.size = upload_size; - SDL_GPUTransferBuffer* font_transferbuffer = SDL_CreateGPUTransferBuffer(v->GpuDevice, &font_transferbuffer_info); - IM_ASSERT(font_transferbuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information"); + SDL_GPUTransferBuffer* transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info); + IM_ASSERT(transferbuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information"); - void* texture_ptr = SDL_MapGPUTransferBuffer(v->GpuDevice, font_transferbuffer, false); + void* texture_ptr = SDL_MapGPUTransferBuffer(v->Device, transferbuffer, false); memcpy(texture_ptr, pixels, upload_size); - SDL_UnmapGPUTransferBuffer(v->GpuDevice, font_transferbuffer); + SDL_UnmapGPUTransferBuffer(v->Device, transferbuffer); - SDL_GPUTextureTransferInfo font_transfer_info = {}; - font_transfer_info.offset = 0; - font_transfer_info.transfer_buffer = font_transferbuffer; + SDL_GPUTextureTransferInfo transfer_info = {}; + transfer_info.offset = 0; + transfer_info.transfer_buffer = transferbuffer; - SDL_GPUTextureRegion font_texture_region = {}; - font_texture_region.texture = bd->FontTexture; - font_texture_region.w = width; - font_texture_region.h = height; - font_texture_region.d = 1; + SDL_GPUTextureRegion texture_region = {}; + texture_region.texture = bd->FontTexture; + texture_region.w = width; + texture_region.h = height; + texture_region.d = 1; - SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->GpuDevice); + SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->Device); SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(cmd); - SDL_UploadToGPUTexture(copy_pass, &font_transfer_info, &font_texture_region, false); + SDL_UploadToGPUTexture(copy_pass, &transfer_info, &texture_region, false); SDL_EndGPUCopyPass(copy_pass); SDL_SubmitGPUCommandBuffer(cmd); - SDL_ReleaseGPUTransferBuffer(v->GpuDevice, font_transferbuffer); + SDL_ReleaseGPUTransferBuffer(v->Device, transferbuffer); } // Store our identifier io.Fonts->SetTexID((ImTextureID)&bd->FontBinding); - - return true; } // You probably never need to call this, as it is called by ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_Shutdown(). @@ -357,10 +355,10 @@ void ImGui_ImplSDLGPU3_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; if (bd->FontTexture) { - SDL_ReleaseGPUTexture(v->GpuDevice, bd->FontTexture); + SDL_ReleaseGPUTexture(v->Device, bd->FontTexture); bd->FontBinding.texture = nullptr; bd->FontTexture = nullptr; } @@ -371,9 +369,9 @@ static void Imgui_ImplSDLGPU3_CreateShaders() { // Create the shader modules ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - const char* driver = SDL_GetGPUDeviceDriver(v->GpuDevice); + const char* driver = SDL_GetGPUDeviceDriver(v->Device); SDL_GPUShaderCreateInfo vertex_shader_info = {}; vertex_shader_info.entrypoint = "main"; @@ -422,8 +420,8 @@ static void Imgui_ImplSDLGPU3_CreateShaders() fragment_shader_info.code_size = sizeof(metallib_fragment); } #endif - bd->VertexShader = SDL_CreateGPUShader(v->GpuDevice, &vertex_shader_info); - bd->FragmentShader = SDL_CreateGPUShader(v->GpuDevice, &fragment_shader_info); + bd->VertexShader = SDL_CreateGPUShader(v->Device, &vertex_shader_info); + bd->FragmentShader = SDL_CreateGPUShader(v->Device, &fragment_shader_info); IM_ASSERT(bd->VertexShader != nullptr && "Failed to create vertex shader, call SDL_GetError() for more information"); IM_ASSERT(bd->FragmentShader != nullptr && "Failed to create fragment shader, call SDL_GetError() for more information"); } @@ -431,7 +429,7 @@ static void Imgui_ImplSDLGPU3_CreateShaders() static void ImGui_ImplSDLGPU3_CreateGraphicsPipeline() { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; Imgui_ImplSDLGPU3_CreateShaders(); SDL_GPUVertexBufferDescription vertex_buffer_desc[1]; @@ -507,14 +505,14 @@ static void ImGui_ImplSDLGPU3_CreateGraphicsPipeline() pipeline_info.depth_stencil_state = depth_stencil_state; pipeline_info.target_info = target_info; - bd->Pipeline = SDL_CreateGPUGraphicsPipeline(v->GpuDevice, &pipeline_info); + bd->Pipeline = SDL_CreateGPUGraphicsPipeline(v->Device, &pipeline_info); IM_ASSERT(bd->Pipeline != nullptr && "Failed to create graphics pipeline, call SDL_GetError() for more information"); } -bool ImGui_ImplSDLGPU3_CreateDeviceObjects() +void ImGui_ImplSDLGPU3_CreateDeviceObjects() { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; if (!bd->FontSampler) { @@ -533,23 +531,22 @@ bool ImGui_ImplSDLGPU3_CreateDeviceObjects() sampler_info.max_anisotropy = 1.0f; sampler_info.enable_compare = false; - bd->FontSampler = SDL_CreateGPUSampler(v->GpuDevice, &sampler_info); + bd->FontSampler = SDL_CreateGPUSampler(v->Device, &sampler_info); bd->FontBinding.sampler = bd->FontSampler; IM_ASSERT(bd->FontSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information"); } ImGui_ImplSDLGPU3_CreateGraphicsPipeline(); - - return true; + ImGui_ImplSDLGPU3_CreateFontsTexture(); } void ImGui_ImplSDLGPU3_DestroyFrameData() { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - SDL_ReleaseGPUBuffer(v->GpuDevice, bd->MainWindowFrameData.VertexBuffer); - SDL_ReleaseGPUBuffer(v->GpuDevice, bd->MainWindowFrameData.IndexBuffer); + SDL_ReleaseGPUBuffer(v->Device, bd->MainWindowFrameData.VertexBuffer); + SDL_ReleaseGPUBuffer(v->Device, bd->MainWindowFrameData.IndexBuffer); bd->MainWindowFrameData.VertexBuffer = nullptr; bd->MainWindowFrameData.IndexBuffer = nullptr; bd->MainWindowFrameData.VertexBufferSize = 0; @@ -559,15 +556,15 @@ void ImGui_ImplSDLGPU3_DestroyFrameData() void ImGui_ImplSDLGPU3_DestroyDeviceObjects() { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->GPUInitInfo; + ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; ImGui_ImplSDLGPU3_DestroyFrameData(); ImGui_ImplSDLGPU3_DestroyFontsTexture(); - if (bd->VertexShader) { SDL_ReleaseGPUShader(v->GpuDevice, bd->VertexShader); bd->VertexShader = nullptr;} - if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->GpuDevice, bd->FragmentShader); bd->FragmentShader = nullptr;} - if (bd->FontSampler) { SDL_ReleaseGPUSampler(v->GpuDevice, bd->FontSampler); bd->FontSampler = nullptr;} - if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->GpuDevice, bd->Pipeline); bd->Pipeline = nullptr;} + if (bd->VertexShader) { SDL_ReleaseGPUShader(v->Device, bd->VertexShader); bd->VertexShader = nullptr;} + if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->Device, bd->FragmentShader); bd->FragmentShader = nullptr;} + if (bd->FontSampler) { SDL_ReleaseGPUSampler(v->Device, bd->FontSampler); bd->FontSampler = nullptr;} + if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->Device, bd->Pipeline); bd->Pipeline = nullptr;} } bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info) @@ -582,10 +579,10 @@ bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info) io.BackendRendererName = "imgui_impl_sdlgpu3"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. - IM_ASSERT(info->GpuDevice != nullptr); + IM_ASSERT(info->Device != nullptr); IM_ASSERT(info->ColorTargetFormat != SDL_GPU_TEXTUREFORMAT_INVALID); - bd->GPUInitInfo = *info; + bd->InitInfo = *info; ImGui_ImplSDLGPU3_CreateDeviceObjects(); diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index ff9c751c8..865139e26 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -29,18 +29,21 @@ // - Remember to set ColorTargetFormat to the correct format. If you're rendering to the swapchain, call SDL_GetGPUSwapchainTextureFormat to query the right value struct ImGui_ImplSDLGPU3_InitInfo { - SDL_GPUDevice* GpuDevice = nullptr; + SDL_GPUDevice* Device = nullptr; SDL_GPUTextureFormat ColorTargetFormat = SDL_GPU_TEXTUREFORMAT_INVALID; SDL_GPUSampleCount MSAASamples = SDL_GPU_SAMPLECOUNT_1; }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! -IMGUI_IMPL_API bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info); -IMGUI_IMPL_API void ImGui_ImplSDLGPU3_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplSDLGPU3_NewFrame(); -IMGUI_IMPL_API void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer); -IMGUI_IMPL_API void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline = nullptr); -IMGUI_IMPL_API bool ImGui_ImplSDLGPU3_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplSDLGPU3_DestroyFontsTexture(); +IMGUI_IMPL_API bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_NewFrame(); +IMGUI_IMPL_API void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline = nullptr); + +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_DestroyDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_CreateFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_DestroyFontsTexture(); #endif // #ifndef IMGUI_DISABLE diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 429785637..f04436ac0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ HOW TO UPDATE? Breaking changes: +- Backends: SDLGPU3: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device + for consistency. (#8163, #7998, #7988) + Other changes: - ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) @@ -48,6 +51,8 @@ Other changes: provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by vkAcquireNextImageKHR() or vkQueuePresentKHR(). (#7825, #7831) [@NostraMagister] +- Backends: SDLGPU3: Exposed ImGui_ImplSDLGPU3_CreateDeviceObjects()/_DestroyDeviceObjects(). + Removed return value from ImGui_ImplSDLGPU3_CreateFontsTexture(). (#8163, #7998, #7988) - Backends: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. @@ -110,7 +115,7 @@ Other changes: - Demo: Added label edition to Property Editor demo + fix an ID issue. (#8266) [@moritz-h] - Misc: Fixed misc/cpp/imgui_stdlib.h/.cpp not supporting IMGUI_DISABLE. (#8294) [@juur] - Misc: Fixed MinGW builds not using UTF-8 friendly _wfopen(). (#8300) -- Backends: SDL_GPU for SDL3: Added backend for SDL_GPU! (#8163, #7998, #7988) [@DeltaW0x]. +- Backends: SDLGPU3 for SDL3: Added backend for SDL_GPU! (#8163, #7998, #7988) [@DeltaW0x]. - Backends: SDL3: Added ImGui_ImplSDL3_InitForSDLGPU() for consistency, even though it is currently not doing anything particular. (#8163, #7998, #7988) - Backends: Allegro5: Avoid calling al_set_mouse_cursor() repeatedly since it appears diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index f025c537d..1077639e7 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -69,7 +69,7 @@ int main(int, char**) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForSDLGPU(window); ImGui_ImplSDLGPU3_InitInfo init_info = {}; - init_info.GpuDevice = gpu_device; + init_info.Device = gpu_device; init_info.ColorTargetFormat = SDL_GetGPUSwapchainTextureFormat(gpu_device, window); init_info.MSAASamples = SDL_GPU_SAMPLECOUNT_1; ImGui_ImplSDLGPU3_Init(&init_info); From 007735737a4f1895fc9e578ce5420874d6875bd9 Mon Sep 17 00:00:00 2001 From: Diego Mateos Date: Thu, 16 Jan 2025 17:10:26 +0100 Subject: [PATCH 0616/2359] Ignore vscode artifacts (#8324) --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index f632636e0..15a908273 100644 --- a/.gitignore +++ b/.gitignore @@ -49,6 +49,9 @@ examples/example_sdl2_opengl3/web/* .idea cmake-build-* +## VS code artifacts +.vscode + ## Unix executables from our example Makefiles examples/example_glfw_metal/example_glfw_metal examples/example_glfw_opengl2/example_glfw_opengl2 From 4c64ba16c54823e77a719d6b599e824f066f5f92 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 17:42:00 +0100 Subject: [PATCH 0617/2359] imgui_freetype: fixed issue where glyph advances would incorrectly be snapped to pixels. --- docs/CHANGELOG.txt | 4 ++++ misc/freetype/imgui_freetype.cpp | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f04436ac0..f543799f0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,10 @@ Breaking changes: Other changes: - ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) +- imgui_freetype: fixed issue where glyph advances would incorrectly be + snapped to pixels. Effectively it would only be noticeable when hinting + is disabled with ImGuiFreeTypeBuilderFlags_NoHinting, as hinting itself + snaps glyph advances. - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 997bc4340..421fdba63 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -104,6 +104,9 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ // Code //------------------------------------------------------------------------- +#define FT_CEIL(X) (((X + 63) & -64) / 64) // From SDL_ttf: Handy routines for converting from fixed point +#define FT_SCALEFACTOR 64.0f + namespace { // Glyph metrics: @@ -182,9 +185,6 @@ namespace float InvRasterizationDensity; }; - // From SDL_ttf: Handy routines for converting from fixed point - #define FT_CEIL(X) (((X + 63) & -64) / 64) - bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_font_builder_flags) { FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)cfg.FontData, (uint32_t)cfg.FontDataSize, (uint32_t)cfg.FontNo, &Face); @@ -316,7 +316,7 @@ namespace out_glyph_info->Height = (int)ft_bitmap->rows; out_glyph_info->OffsetX = Face->glyph->bitmap_left; out_glyph_info->OffsetY = -Face->glyph->bitmap_top; - out_glyph_info->AdvanceX = (float)FT_CEIL(slot->advance.x); + out_glyph_info->AdvanceX = (float)slot->advance.x / FT_SCALEFACTOR; out_glyph_info->IsColored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); return ft_bitmap; From b7c27c5333bca2d9b7958b3a12a1438ab18d20d7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 19:07:09 +0100 Subject: [PATCH 0618/2359] Windows: legacy SetWindowFontScale() is properly inherited by nested child windows. (#2701, #8138, #1018) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 5 ++++- imgui.h | 2 +- imgui_internal.h | 3 ++- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f543799f0..c69c017d9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,9 @@ Other changes: snapped to pixels. Effectively it would only be noticeable when hinting is disabled with ImGuiFreeTypeBuilderFlags_NoHinting, as hinting itself snaps glyph advances. +- Windows: legacy SetWindowFontScale() is properly inherited by nested child + windows. Note that an upcoming major release should make this obsolete, + but in the meanwhile it works better now. (#2701, #8138, #1018) - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by diff --git a/imgui.cpp b/imgui.cpp index 009a9abf1..613bef69a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4276,7 +4276,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; LastTimeActive = -1.0f; - FontWindowScale = 1.0f; + FontWindowScale = FontWindowScaleParents = 1.0f; SettingsOffset = -1; DrawList = &DrawListInst; DrawList->_OwnerName = Name; @@ -7037,6 +7037,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack, // e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798) window->ParentWindowForFocusRoute = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window_in_stack : NULL; + + // Inherent SetWindowFontScale() from parent until we fix this system... + window->FontWindowScaleParents = parent_window ? parent_window->FontWindowScaleParents * parent_window->FontWindowScale : 1.0f; } // Add to focus scope stack diff --git a/imgui.h b/imgui.h index b9a4fe158..b111407e2 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.8 WIP" -#define IMGUI_VERSION_NUM 19171 +#define IMGUI_VERSION_NUM 19172 #define IMGUI_HAS_TABLE /* diff --git a/imgui_internal.h b/imgui_internal.h index 12d8f7a51..b98aafca8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2551,6 +2551,7 @@ struct IMGUI_API ImGuiWindow ImGuiStorage StateStorage; ImVector ColumnsStorage; float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() + float FontWindowScaleParents; int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) @@ -2585,7 +2586,7 @@ public: // We don't use g.FontSize because the window may be != g.CurrentWindow. ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } - float CalcFontSize() const { ImGuiContext& g = *Ctx; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } + float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontBaseSize * FontWindowScale * FontWindowScaleParents; } ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } }; From f2262eb81aa2a86f8acc9d9ef5996f6a14429d4d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 19:46:54 +0100 Subject: [PATCH 0619/2359] Windows: latch FontRefSize at time of Begin(), consistent with e.g. TitleBarHeight, and to avoid calling CalcFontSize() on non-current window. --- imgui.cpp | 14 ++++++++------ imgui_internal.h | 1 + 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 613bef69a..7c08e6e87 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4276,6 +4276,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; LastTimeActive = -1.0f; + FontRefSize = 0.0f; FontWindowScale = FontWindowScaleParents = 1.0f; SettingsOffset = -1; DrawList = &DrawListInst; @@ -7201,6 +7202,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f; window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f; + window->FontRefSize = g.FontSize; // Lock this to discourage calling window->CalcFontSize() outside of current window. // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible. // Those flags will be altered further down in the function depending on more conditions. @@ -9649,7 +9651,7 @@ void ImGui::UpdateMouseWheel() { LockWheelingWindow(window, wheel.x); float max_step = window->InnerRect.GetWidth() * 0.67f; - float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step)); + float scroll_step = ImTrunc(ImMin(2 * window->FontRefSize, max_step)); SetScrollX(window, window->Scroll.x - wheel.x * scroll_step); g.WheelingWindowScrolledFrame = g.FrameCount; } @@ -9657,7 +9659,7 @@ void ImGui::UpdateMouseWheel() { LockWheelingWindow(window, wheel.y); float max_step = window->InnerRect.GetHeight() * 0.67f; - float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step)); + float scroll_step = ImTrunc(ImMin(5 * window->FontRefSize, max_step)); SetScrollY(window, window->Scroll.y - wheel.y * scroll_step); g.WheelingWindowScrolledFrame = g.FrameCount; } @@ -12987,7 +12989,7 @@ static void ImGui::NavUpdate() { // *Fallback* manual-scroll with Nav directional keys when window has no navigable item ImGuiWindow* window = g.NavWindow; - const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. + const float scroll_speed = IM_ROUND(window->FontRefSize * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. const ImGuiDir move_dir = g.NavMoveDir; if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None) { @@ -13177,8 +13179,8 @@ void ImGui::NavUpdateCreateMoveRequest() if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer])) { IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n"); - float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f); - float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item + float pad_x = ImMin(inner_rect_rel.GetWidth(), window->FontRefSize * 0.5f); + float pad_y = ImMin(inner_rect_rel.GetHeight(), window->FontRefSize * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX; inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX; inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX; @@ -13436,7 +13438,7 @@ static float ImGui::NavUpdatePageUpPageDown() else { ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; - const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); + const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->FontRefSize * 1.0f + nav_rect_rel.GetHeight()); float nav_scoring_rect_offset_y = 0.0f; if (IsKeyPressed(ImGuiKey_PageUp, true)) { diff --git a/imgui_internal.h b/imgui_internal.h index b98aafca8..736031d32 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2552,6 +2552,7 @@ struct IMGUI_API ImGuiWindow ImVector ColumnsStorage; float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() float FontWindowScaleParents; + float FontRefSize; // This is a copy of window->CalcFontSize() at the time of Begin(), trying to phase out CalcFontSize() especially as it may be called on non-current window. int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) From 487d7f9a296cec2af496b64f6eb9d939fc8fae33 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 22:30:43 +0100 Subject: [PATCH 0620/2359] Font: Internals: make used page maps smaller. Since it's extremely rarely used and for iterations only. ~34->16 bytes with ImWchar32. --- imgui.cpp | 4 ++-- imgui.h | 2 +- imgui_draw.cpp | 20 ++++++++++---------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7c08e6e87..b326c444d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16177,9 +16177,9 @@ void ImGui::DebugNodeFont(ImFont* font) // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) - if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) + if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191)) { - base += 4096 - 256; + base += 8192 - 256; continue; } diff --git a/imgui.h b/imgui.h index b111407e2..bcf0ac403 100644 --- a/imgui.h +++ b/imgui.h @@ -3461,7 +3461,7 @@ struct ImFont float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) - ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. // Methods IMGUI_API ImFont(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e8c445dd3..67a993de5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3689,7 +3689,7 @@ ImFont::ImFont() Scale = 1.0f; Ascent = Descent = 0.0f; MetricsTotalSurface = 0; - memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap)); + memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); } ImFont::~ImFont() @@ -3709,7 +3709,7 @@ void ImFont::ClearOutputData() DirtyLookupTables = true; Ascent = Descent = 0.0f; MetricsTotalSurface = 0; - memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap)); + memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); } static ImWchar FindFirstExistingGlyph(ImFont* font, const ImWchar* candidate_chars, int candidate_chars_count) @@ -3732,7 +3732,7 @@ void ImFont::BuildLookupTable() IndexAdvanceX.clear(); IndexLookup.clear(); DirtyLookupTables = false; - memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap)); + memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); GrowIndex(max_codepoint + 1); for (int i = 0; i < Glyphs.Size; i++) { @@ -3741,8 +3741,8 @@ void ImFont::BuildLookupTable() IndexLookup[codepoint] = (ImWchar)i; // Mark 4K page as used - const int page_n = codepoint / 4096; - Used4kPagesMap[page_n >> 3] |= 1 << (page_n & 7); + const int page_n = codepoint / 8192; + Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); } // Create a glyph to handle TAB @@ -3804,15 +3804,15 @@ void ImFont::BuildLookupTable() } } -// API is designed this way to avoid exposing the 4K page size +// API is designed this way to avoid exposing the 8K page size // e.g. use with IsGlyphRangeUnused(0, 255) bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) { - unsigned int page_begin = (c_begin / 4096); - unsigned int page_last = (c_last / 4096); + unsigned int page_begin = (c_begin / 8192); + unsigned int page_last = (c_last / 8192); for (unsigned int page_n = page_begin; page_n <= page_last; page_n++) - if ((page_n >> 3) < sizeof(Used4kPagesMap)) - if (Used4kPagesMap[page_n >> 3] & (1 << (page_n & 7))) + if ((page_n >> 3) < sizeof(Used8kPagesMap)) + if (Used8kPagesMap[page_n >> 3] & (1 << (page_n & 7))) return false; return true; } From dd89a3741b1d05ab0997d80bfe0377070251d300 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 17 Jan 2025 17:11:22 +0100 Subject: [PATCH 0621/2359] Backends: Vulkan: sharing duplicate code. (#5446, #8326) --- backends/imgui_impl_vulkan.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index f4bd50694..2bd40f624 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1079,6 +1079,15 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() if (bd->DescriptorPool) { vkDestroyDescriptorPool(v->Device, bd->DescriptorPool, v->Allocator); bd->DescriptorPool = VK_NULL_HANDLE; } } +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING +static void ImGui_ImplVulkan_LoadDynamicRenderingFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) +{ + // Manually load those two (see #5446) + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func("vkCmdBeginRenderingKHR", user_data)); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func("vkCmdEndRenderingKHR", user_data)); +} +#endif + bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) { // Load function pointers @@ -1094,9 +1103,7 @@ bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const ch #undef IMGUI_VULKAN_FUNC_LOAD #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - // Manually load those two (see #5446) - ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func("vkCmdBeginRenderingKHR", user_data)); - ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func("vkCmdEndRenderingKHR", user_data)); + ImGui_ImplVulkan_LoadDynamicRenderingFunctions(loader_func, user_data); #endif #else IM_UNUSED(loader_func); @@ -1115,8 +1122,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) { #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #ifndef IMGUI_IMPL_VULKAN_USE_LOADER - ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(vkGetInstanceProcAddr(info->Instance, "vkCmdBeginRenderingKHR")); - ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(vkGetInstanceProcAddr(info->Instance, "vkCmdEndRenderingKHR")); + ImGui_ImplVulkan_LoadDynamicRenderingFunctions([](const char* function_name, void* user_data) { return vkGetInstanceProcAddr((VkInstance)user_data, function_name); }, (void*)info->Instance); #endif IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR != nullptr); IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR != nullptr); From d7454de80a2d51cee6601d275c441987e7aebb5e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 17 Jan 2025 18:09:28 +0100 Subject: [PATCH 0622/2359] Font: minor tweak to struct alignment. --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index bcf0ac403..b42fa0637 100644 --- a/imgui.h +++ b/imgui.h @@ -3457,10 +3457,10 @@ struct ImFont ImWchar FallbackChar; // 2-4 // out // = FFFD/'?' // Character used if a glyph isn't found. float EllipsisWidth; // 4 // out // Width float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 - bool DirtyLookupTables; // 1 // out // float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + bool DirtyLookupTables; // 1 // out // ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. // Methods From 80c9cd1f6e4ec84034f918de21aba3953dfa9893 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 18 Jan 2025 16:43:17 +0100 Subject: [PATCH 0623/2359] Font: reduce unnecessary padding in ImFontConfig struct too. --- imgui.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui.h b/imgui.h index b42fa0637..82903424a 100644 --- a/imgui.h +++ b/imgui.h @@ -3233,26 +3233,27 @@ struct ImDrawData // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) //----------------------------------------------------------------------------- +// A font input/source (we may rename this to ImFontSource in the future) struct ImFontConfig { void* FontData; // // TTF/OTF data int FontDataSize; // // TTF/OTF data size bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. + bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. int FontNo; // 0 // Index of font within TTF/OTF file - float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). int OversampleH; // 2 // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis. - bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs - bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. float RasterizerDensity; // 1.0f // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display. IMPORTANT: If you increase this it is expected that you increase font scale accordingly, otherwise quality may look lowered. - ImWchar EllipsisChar; // 0 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. // [Internal] char Name[40]; // Name (strictly to ease debugging) From aa23f3801b7414989093abf7388144bc4dfd221c Mon Sep 17 00:00:00 2001 From: "Daniel K. O. (dkosmari)" Date: Fri, 17 Jan 2025 19:18:05 -0300 Subject: [PATCH 0624/2359] Backends: SDL_Renderer2/3: Use endian-dependent RGBA32 texture format, to match SDL_Color. (#8327) --- backends/imgui_impl_sdlrenderer2.cpp | 3 ++- backends/imgui_impl_sdlrenderer3.cpp | 3 ++- docs/CHANGELOG.txt | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index 6d0ee564f..fcc6d5dd3 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -21,6 +21,7 @@ // - Introduction, links and more at the top of imgui.cpp // CHANGELOG +// 2025-01-18: Use endian-dependent RGBA32 texture format, to match SDL_Color. // 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer2_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter. // 2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3. @@ -228,7 +229,7 @@ bool ImGui_ImplSDLRenderer2_CreateFontsTexture() // Upload texture to graphics system // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); + bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height); if (bd->FontTexture == nullptr) { SDL_Log("error creating texture"); diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 1bcf7a228..0cede09be 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -23,6 +23,7 @@ // - Introduction, links and more at the top of imgui.cpp // CHANGELOG +// 2025-01-18: Use endian-dependent RGBA32 texture format, to match SDL_Color. // 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer3_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-07-01: Update for SDL3 api changes: SDL_RenderGeometryRaw() uint32 version was removed (SDL#9009). // 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter. @@ -247,7 +248,7 @@ bool ImGui_ImplSDLRenderer3_CreateFontsTexture() // Upload texture to graphics system // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); + bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height); if (bd->FontTexture == nullptr) { SDL_Log("error creating texture"); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c69c017d9..f2812a661 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,8 @@ Other changes: vkAcquireNextImageKHR() or vkQueuePresentKHR(). (#7825, #7831) [@NostraMagister] - Backends: SDLGPU3: Exposed ImGui_ImplSDLGPU3_CreateDeviceObjects()/_DestroyDeviceObjects(). Removed return value from ImGui_ImplSDLGPU3_CreateFontsTexture(). (#8163, #7998, #7988) +- Backends: SDL_Renderer2/3: Use endian-dependent RGBA32 texture format, to match + SDL_Color. (#8327) [@dkosmari] - Backends: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. From aa1b4ea861173109a64eef644243f632f388d567 Mon Sep 17 00:00:00 2001 From: Julian Rachele Date: Sun, 19 Jan 2025 16:30:15 -0500 Subject: [PATCH 0625/2359] Backends: OSX: Remove notification observer when shutting down. (#8331) --- backends/imgui_impl_osx.mm | 2 ++ docs/CHANGELOG.txt | 1 + 2 files changed, 3 insertions(+) diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index c2a5f6378..92c26418f 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-20: Removed notification observer when shutting down. (#8331) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn @@ -497,6 +498,7 @@ void ImGui_ImplOSX_Shutdown() ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); + [[NSNotificationCenter defaultCenter] removeObserver:bd->Observer]; bd->Observer = nullptr; if (bd->Monitor != nullptr) { diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f2812a661..c81fc8df0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,7 @@ Other changes: SDL_Color. (#8327) [@dkosmari] - Backends: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. +- Backends: OSX: Removed notification observer when shutting down. (#8331) [@jrachele] ----------------------------------------------------------------------- From 8b0af7fddcba41d2c091b6752451ed9082af777e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 20 Jan 2025 14:30:40 +0100 Subject: [PATCH 0626/2359] Backends: SDL: update comments regarding API stability, regarding SDL_GPU and SDL_Renderer. --- backends/imgui_impl_sdl3.cpp | 6 ++---- backends/imgui_impl_sdl3.h | 6 ++---- backends/imgui_impl_sdlrenderer2.cpp | 12 +++++++----- backends/imgui_impl_sdlrenderer2.h | 12 +++++++----- backends/imgui_impl_sdlrenderer3.cpp | 16 ++++++++-------- backends/imgui_impl_sdlrenderer3.h | 16 ++++++++-------- 6 files changed, 34 insertions(+), 34 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index b8e4dec5e..eb0eef89f 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -1,9 +1,7 @@ -// dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) -// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) +// dear imgui: Platform Backend for SDL3 +// This needs to be used along with a Renderer (e.g. SDL_GPU, DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) -// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) - // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h index ff0e2aed3..5b8973738 100644 --- a/backends/imgui_impl_sdl3.h +++ b/backends/imgui_impl_sdl3.h @@ -1,9 +1,7 @@ -// dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) -// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) +// dear imgui: Platform Backend for SDL3 +// This needs to be used along with a Renderer (e.g. SDL_GPU, DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) -// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) - // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index fcc6d5dd3..8245854c2 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -1,11 +1,13 @@ // dear imgui: Renderer Backend for SDL_Renderer for SDL2 // (Requires: SDL 2.0.17+) -// Note how SDL_Renderer is an _optional_ component of SDL2. -// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. -// If your application will want to render any non trivial amount of graphics other than UI, -// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and -// it might be difficult to step out of those boundaries. +// Note that SDL_Renderer is an _optional_ component of SDL2, which IMHO is now largely obsolete. +// For a multi-platform app consider using other technologies: +// - SDL3+SDL_GPU: SDL_GPU is SDL3 new graphics abstraction API. You will need to update to SDL3. +// - SDL2+DirectX, SDL2+OpenGL, SDL2+Vulkan: combine SDL with dedicated renderers. +// If your application wants to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user +// and it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h index 7aed18d21..a0337d314 100644 --- a/backends/imgui_impl_sdlrenderer2.h +++ b/backends/imgui_impl_sdlrenderer2.h @@ -1,11 +1,13 @@ // dear imgui: Renderer Backend for SDL_Renderer for SDL2 // (Requires: SDL 2.0.17+) -// Note how SDL_Renderer is an _optional_ component of SDL2. -// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. -// If your application will want to render any non trivial amount of graphics other than UI, -// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and -// it might be difficult to step out of those boundaries. +// Note that SDL_Renderer is an _optional_ component of SDL2, which IMHO is now largely obsolete. +// For a multi-platform app consider using other technologies: +// - SDL3+SDL_GPU: SDL_GPU is SDL3 new graphics abstraction API. You will need to update to SDL3. +// - SDL2+DirectX, SDL2+OpenGL, SDL2+Vulkan: combine SDL with dedicated renderers. +// If your application wants to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user +// and it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 0cede09be..99253d964 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -1,13 +1,13 @@ // dear imgui: Renderer Backend for SDL_Renderer for SDL3 -// (Requires: SDL 3.0.0+) +// (Requires: SDL 3.1.8+) -// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) - -// Note how SDL_Renderer is an _optional_ component of SDL3. -// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. -// If your application will want to render any non trivial amount of graphics other than UI, -// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and -// it might be difficult to step out of those boundaries. +// Note that SDL_Renderer is an _optional_ component of SDL3, which IMHO is now largely obsolete. +// For a multi-platform app consider using other technologies: +// - SDL3+SDL_GPU: SDL_GPU is SDL3 new graphics abstraction API. +// - SDL3+DirectX, SDL3+OpenGL, SDL3+Vulkan: combine SDL with dedicated renderers. +// If your application wants to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user +// and it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h index 3a7a51ee5..3473bcc77 100644 --- a/backends/imgui_impl_sdlrenderer3.h +++ b/backends/imgui_impl_sdlrenderer3.h @@ -1,13 +1,13 @@ // dear imgui: Renderer Backend for SDL_Renderer for SDL3 -// (Requires: SDL 3.0.0+) +// (Requires: SDL 3.1.8+) -// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) - -// Note how SDL_Renderer is an _optional_ component of SDL3. -// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. -// If your application will want to render any non trivial amount of graphics other than UI, -// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and -// it might be difficult to step out of those boundaries. +// Note that SDL_Renderer is an _optional_ component of SDL3, which IMHO is now largely obsolete. +// For a multi-platform app consider using other technologies: +// - SDL3+SDL_GPU: SDL_GPU is SDL3 new graphics abstraction API. +// - SDL3+DirectX, SDL3+OpenGL, SDL3+Vulkan: combine SDL with dedicated renderers. +// If your application wants to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user +// and it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! From 4c2e7bb03557dd28f0a6b6809c3466485cc4c3df Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 20 Jan 2025 15:24:46 +0100 Subject: [PATCH 0627/2359] Backends: SDL2,SDL3: removed assert preventing using ImGui_ImplSDL2_SetGamepadMode()/ImGui_ImplSDL3_SetGamepadMode() with ImGui_ImplSDL2_GamepadMode_Manual/ImGui_ImplSDL3_GamepadMode_Manual and an empty array. (#8329) --- backends/imgui_impl_sdl2.cpp | 3 ++- backends/imgui_impl_sdl3.cpp | 3 ++- docs/CHANGELOG.txt | 4 ++++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 0aaf9830a..a27962a31 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-20: Made ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode_Manual) accept an empty array. // 2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f. // 2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: @@ -665,7 +666,7 @@ void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_ ImGui_ImplSDL2_CloseGamepads(); if (mode == ImGui_ImplSDL2_GamepadMode_Manual) { - IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0); + IM_ASSERT(manual_gamepads_array != nullptr || manual_gamepads_count <= 0); for (int n = 0; n < manual_gamepads_count; n++) bd->Gamepads.push_back(manual_gamepads_array[n]); } diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index eb0eef89f..d5de5443e 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-01-20: Made ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode_Manual) accept an empty array. // 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten. // 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: @@ -635,7 +636,7 @@ void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad* ImGui_ImplSDL3_CloseGamepads(); if (mode == ImGui_ImplSDL3_GamepadMode_Manual) { - IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0); + IM_ASSERT(manual_gamepads_array != nullptr || manual_gamepads_count <= 0); for (int n = 0; n < manual_gamepads_count; n++) bd->Gamepads.push_back(manual_gamepads_array[n]); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c81fc8df0..17f62c386 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,10 @@ Other changes: provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by vkAcquireNextImageKHR() or vkQueuePresentKHR(). (#7825, #7831) [@NostraMagister] +- Backends: SDL2: removed assert preventing using ImGui_ImplSDL2_SetGamepadMode() + with ImGui_ImplSDL2_GamepadMode_Manual and an empty array. (#8329) +- Backends: SDL3: removed assert preventing using ImGui_ImplSDL3_SetGamepadMode() + with ImGui_ImplSDL3_GamepadMode_Manual and an empty array. (#8329) - Backends: SDLGPU3: Exposed ImGui_ImplSDLGPU3_CreateDeviceObjects()/_DestroyDeviceObjects(). Removed return value from ImGui_ImplSDLGPU3_CreateFontsTexture(). (#8163, #7998, #7988) - Backends: SDL_Renderer2/3: Use endian-dependent RGBA32 texture format, to match From e8779a67b1498ba345dc139a2b2303b17408e14b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 20 Jan 2025 17:55:09 +0100 Subject: [PATCH 0628/2359] Font: direct AddText()/RenderText() calls don't need to call strlen() if below clipping region. Unlikely to meaningful affect anyone but still.. --- imgui_draw.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 67a993de5..97342b35b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1669,8 +1669,7 @@ void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 // Accept null ranges if (text_begin == text_end || text_begin[0] == 0) return; - if (text_end == NULL) - text_end = text_begin + strlen(text_begin); + // 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) @@ -1693,7 +1692,7 @@ void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) { - AddText(NULL, 0.0f, pos, col, text_begin, text_end); + AddText(_Data->Font, _Data->FontSize, pos, col, text_begin, text_end); } void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) @@ -4125,15 +4124,15 @@ 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. 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, bool cpu_fine_clip) { - if (!text_end) - text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. - // Align to be pixel perfect float x = IM_TRUNC(pos.x); float y = IM_TRUNC(pos.y); if (y > clip_rect.w) return; + if (!text_end) + text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. + const float scale = size / FontSize; const float line_height = FontSize * scale; const float origin_x = x; From 7ae7c9079038050a3c19d6e768d183301d8a303c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 21 Jan 2025 13:55:44 +0100 Subject: [PATCH 0629/2359] Tabs, Style: reworked selected overline rendering to better accommodate for rounded tabs. (#8334) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 4 ++-- imgui_demo.cpp | 2 +- imgui_widgets.cpp | 20 +++++++++++++++----- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 17f62c386..ccb4882da 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,10 @@ Other changes: - Windows: legacy SetWindowFontScale() is properly inherited by nested child windows. Note that an upcoming major release should make this obsolete, but in the meanwhile it works better now. (#2701, #8138, #1018) +- Tabs, Style: reworked selected overline rendering to better accommodate + for rounded tabs. Reduced default thickness (style.TabBarOverlineSize), + increased default rounding (style.TabRounding). (#8334) [@Kian738, @ocornut] + styles as the current look is not right (but ImGuiCol_TabSelectedOverline stays the same). - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by diff --git a/imgui.cpp b/imgui.cpp index b326c444d..f448ab90d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1334,11 +1334,11 @@ ImGuiStyle::ImGuiStyle() GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. - TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. + TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. - TabBarOverlineSize = 2.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar. + TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar. TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees). TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 26c246db6..e41c0ac5c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7966,7 +7966,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); - ImGui::SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 2.0f, "%.0f"); + ImGui::SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); ImGui::SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); ImGui::SeparatorText("Rounding"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 71a5c5b9a..4f58c4cd2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10150,11 +10150,21 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, TabItemBackground(display_draw_list, bb, flags, tab_col); if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f) { - float x_offset = IM_TRUNC(0.4f * style.TabRounding); - if (x_offset < 2.0f * g.CurrentDpiScale) - x_offset = 0.0f; - float y_offset = 1.0f * g.CurrentDpiScale; - display_draw_list->AddLine(bb.GetTL() + ImVec2(x_offset, y_offset), bb.GetTR() + ImVec2(-x_offset, y_offset), GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline), style.TabBarOverlineSize); + // Might be moved to TabItemBackground() ? + ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale); + ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale); + ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline); + if (style.TabRounding > 0.0f) + { + float rounding = style.TabRounding; + display_draw_list->PathArcToFast(tl + ImVec2(+rounding, +rounding), rounding, 7, 9); + display_draw_list->PathArcToFast(tr + ImVec2(-rounding, +rounding), rounding, 9, 11); + display_draw_list->PathStroke(overline_col, 0, style.TabBarOverlineSize); + } + else + { + display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize); + } } RenderNavCursor(bb, id); From 2af26b75d13e6f2be97c53d2d3ebf17b1b18a150 Mon Sep 17 00:00:00 2001 From: David Maas Date: Tue, 21 Jan 2025 14:25:39 +0100 Subject: [PATCH 0630/2359] ColorEdit, ColorPicker: Fixed alpha preview broken in 1.91.7. (#8336, #8241). [@PathogenDavid] ImAlphaBlendColors() was broken by ImLerp() change. (cd6c83c) --- docs/CHANGELOG.txt | 1 + imgui_internal.h | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ccb4882da..c7f26c3b7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,7 @@ Other changes: - Windows: legacy SetWindowFontScale() is properly inherited by nested child windows. Note that an upcoming major release should make this obsolete, but in the meanwhile it works better now. (#2701, #8138, #1018) +- ColorEdit, ColorPicker: Fixed alpha preview broken in 1.91.7. (#8336, #8241). [@PathogenDavid] - Tabs, Style: reworked selected overline rendering to better accommodate for rounded tabs. Reduced default thickness (style.TabBarOverlineSize), increased default rounding (style.TabRounding). (#8334) [@Kian738, @ocornut] diff --git a/imgui_internal.h b/imgui_internal.h index 736031d32..33a6ec8b0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -469,7 +469,7 @@ static inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } template static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } template static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } template static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } -template static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * (T)t); } +template static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } template static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } template static inline 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 static inline 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; } From bf13442c7cf4a082466dae31d50981ec103a7af7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 21 Jan 2025 14:59:29 +0100 Subject: [PATCH 0631/2359] Moved ImGuiColorEditFlags_AlphaPreview/ImGuiColorEditFlags_AlphaPreviewHalf flags. Demo: reorganized some of color edit/picker demo section. --- imgui.h | 4 ++-- imgui_demo.cpp | 65 +++++++++++++++++++++++++------------------------- 2 files changed, 34 insertions(+), 35 deletions(-) diff --git a/imgui.h b/imgui.h index 82903424a..2306667cf 100644 --- a/imgui.h +++ b/imgui.h @@ -1752,11 +1752,11 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) + ImGuiColorEditFlags_AlphaPreview = 1 << 11, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 12, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. // User Options (right-click on widget to change some of them). ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. - ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. - ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // " diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e41c0ac5c..5100356b3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2117,19 +2117,15 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) if (ImGui::TreeNode("Color/Picker Widgets")) { static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f); + static ImGuiColorEditFlags base_flags = ImGuiColorEditFlags_AlphaPreview; - static bool alpha_preview = true; - static bool alpha_half_preview = false; - static bool drag_and_drop = true; - static bool options_menu = true; - static bool hdr = false; ImGui::SeparatorText("Options"); - ImGui::Checkbox("With Alpha Preview", &alpha_preview); - ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview); - ImGui::Checkbox("With Drag and Drop", &drag_and_drop); - ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); - ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); - ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &base_flags, ImGuiColorEditFlags_NoAlpha); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaPreview", &base_flags, ImGuiColorEditFlags_AlphaPreview); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaPreviewHalf", &base_flags, ImGuiColorEditFlags_AlphaPreviewHalf); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoDragDrop", &base_flags, ImGuiColorEditFlags_NoDragDrop); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoOptions", &base_flags, ImGuiColorEditFlags_NoOptions); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); + ImGui::CheckboxFlags("ImGuiColorEditFlags_HDR", &base_flags, ImGuiColorEditFlags_HDR); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit"); ImGui::SeparatorText("Inline color editor"); @@ -2137,15 +2133,15 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::SameLine(); HelpMarker( "Click on the color square to open a color picker.\n" "CTRL+click on individual component to input value.\n"); - ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); + ImGui::ColorEdit3("MyColor##1", (float*)&color, base_flags); IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (HSV, with Alpha)"); ImGui::Text("Color widget HSV with Alpha:"); - ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | misc_flags); + ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | base_flags); IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (float display)"); ImGui::Text("Color widget with Float Display:"); - ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags); + ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | base_flags); IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with Picker)"); ImGui::Text("Color button with Picker:"); @@ -2153,7 +2149,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n" "With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only " "be used for the tooltip and picker popup."); - ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags); + ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | base_flags); IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with custom Picker popup)"); ImGui::Text("Color button with Custom Picker Popup:"); @@ -2173,7 +2169,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) } static ImVec4 backup_color; - bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags); + bool open_popup = ImGui::ColorButton("MyColor##3b", color, base_flags); ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x); open_popup |= ImGui::Button("Palette"); if (open_popup) @@ -2185,7 +2181,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) { ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!"); ImGui::Separator(); - ImGui::ColorPicker4("##picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); + ImGui::ColorPicker4("##picker", (float*)&color, base_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); ImGui::SameLine(); ImGui::BeginGroup(); // Lock X position @@ -2227,40 +2223,42 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::Text("Color button only:"); static bool no_border = false; ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); - ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); + ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, base_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); IMGUI_DEMO_MARKER("Widgets/Color/ColorPicker"); ImGui::SeparatorText("Color picker"); - static bool alpha = true; - static bool alpha_bar = true; - static bool side_preview = true; + static bool ref_color = false; static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f); - static int display_mode = 0; static int picker_mode = 0; - ImGui::Checkbox("With Alpha", &alpha); - ImGui::Checkbox("With Alpha Bar", &alpha_bar); - ImGui::Checkbox("With Side Preview", &side_preview); - if (side_preview) + static int display_mode = 0; + static ImGuiColorEditFlags color_picker_flags = ImGuiColorEditFlags_AlphaBar; + + ImGui::PushID("Color picker"); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &color_picker_flags, ImGuiColorEditFlags_NoAlpha); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaBar", &color_picker_flags, ImGuiColorEditFlags_AlphaBar); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoSidePreview", &color_picker_flags, ImGuiColorEditFlags_NoSidePreview); + if (color_picker_flags & ImGuiColorEditFlags_NoSidePreview) { ImGui::SameLine(); ImGui::Checkbox("With Ref Color", &ref_color); if (ref_color) { ImGui::SameLine(); - ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags); + ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | base_flags); } } - ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0"); + + ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0ImGuiColorEditFlags_PickerHueBar\0ImGuiColorEditFlags_PickerHueWheel\0"); + ImGui::SameLine(); HelpMarker("When not specified explicitly, user can right-click the picker to change mode."); + + ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0ImGuiColorEditFlags_NoInputs\0ImGuiColorEditFlags_DisplayRGB\0ImGuiColorEditFlags_DisplayHSV\0ImGuiColorEditFlags_DisplayHex\0"); ImGui::SameLine(); HelpMarker( "ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, " "but the user can change it with a right-click on those inputs.\n\nColorPicker defaults to displaying RGB+HSV+Hex " "if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); - ImGui::SameLine(); HelpMarker("When not specified explicitly (Auto/Current mode), user can right-click the picker to change mode."); - ImGuiColorEditFlags flags = misc_flags; - if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4() - if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar; - if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview; + + ImGuiColorEditFlags flags = base_flags | color_picker_flags; if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; // Disable all RGB/HSV/Hex displays @@ -2289,6 +2287,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::SameLine(); ImGui::SetNextItemWidth(w); ImGui::ColorPicker3("##MyColor##6", (float*)&color, ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); + ImGui::PopID(); // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV! From 3e6bdc2242ca2e29346b380f76212e64e480a146 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Jan 2025 10:22:31 +0100 Subject: [PATCH 0632/2359] Examples: SDL3+SDL_GPU: use SDL_GPU_PRESENTMODE_MAILBOX swapchain parameters. --- examples/example_sdl3_sdlgpu3/main.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 1077639e7..dbc7759ba 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -7,7 +7,7 @@ // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. -// - Unline other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. +// - Unlike other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. #include "imgui.h" @@ -54,6 +54,7 @@ int main(int, char**) printf("Error: SDL_ClaimWindowForGPUDevice(): %s\n", SDL_GetError()); return -1; } + SDL_SetGPUSwapchainParameters(gpu_device, window, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, SDL_GPU_PRESENTMODE_MAILBOX); // Setup Dear ImGui context IMGUI_CHECKVERSION(); @@ -140,7 +141,7 @@ int main(int, char**) ImGui::Checkbox("Another Window", &show_another_window); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + ImGui::ColorEdit4("clear color", (float*)&clear_color); // Edit 3 floats representing a color if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) counter++; @@ -179,7 +180,7 @@ int main(int, char**) // Setup and start a render pass SDL_GPUColorTargetInfo target_info = {}; target_info.texture = swapchain_texture; - target_info.clear_color = SDL_FColor{ clear_color.x,clear_color.y,clear_color.z,clear_color.w }; + target_info.clear_color = SDL_FColor { clear_color.x, clear_color.y, clear_color.z, clear_color.w }; target_info.load_op = SDL_GPU_LOADOP_CLEAR; target_info.store_op = SDL_GPU_STOREOP_STORE; target_info.mip_level = 0; @@ -196,6 +197,7 @@ int main(int, char**) // Submit the command buffer SDL_SubmitGPUCommandBuffer(command_buffer); } + // Cleanup SDL_WaitForGPUIdle(gpu_device); ImGui_ImplSDL3_Shutdown(); From d17e9fc107ef561743e335aaa62641fcd8ce1952 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Jan 2025 10:32:09 +0100 Subject: [PATCH 0633/2359] Backends: SDL_GPU: shallow tweaks + disable anisotropy in sampler. Examples: SDL+Vulkan: Fixed incorrect defines. --- backends/imgui_impl_sdlgpu3.cpp | 13 +++++++------ examples/example_sdl2_vulkan/main.cpp | 2 +- examples/example_sdl3_vulkan/main.cpp | 2 +- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index b508e091a..74b966227 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -89,8 +89,8 @@ static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGra SDL_GPUBufferBinding index_buffer_binding = {}; index_buffer_binding.buffer = fd->IndexBuffer; index_buffer_binding.offset = 0; - SDL_BindGPUVertexBuffers(render_pass,0,&vertex_buffer_binding,1); - SDL_BindGPUIndexBuffer(render_pass,&index_buffer_binding,sizeof(ImDrawIdx) == 2 ? SDL_GPU_INDEXELEMENTSIZE_16BIT : SDL_GPU_INDEXELEMENTSIZE_32BIT); + SDL_BindGPUVertexBuffers(render_pass,0, &vertex_buffer_binding, 1); + SDL_BindGPUIndexBuffer(render_pass, &index_buffer_binding, sizeof(ImDrawIdx) == 2 ? SDL_GPU_INDEXELEMENTSIZE_16BIT : SDL_GPU_INDEXELEMENTSIZE_32BIT); } // Setup viewport @@ -101,7 +101,7 @@ static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGra viewport.h = (float)fb_height; viewport.min_depth = 0.0f; viewport.max_depth = 1.0f; - SDL_SetGPUViewport(render_pass,&viewport); + SDL_SetGPUViewport(render_pass, &viewport); // Setup scale and translation // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. @@ -118,6 +118,7 @@ static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer, uint32_t* old_size, uin ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; + // Even though this is fairly rarely called. SDL_WaitForGPUIdle(v->Device); SDL_ReleaseGPUBuffer(v->Device, *buffer); @@ -196,8 +197,8 @@ void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff index_buffer_region.size = index_size; SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(command_buffer); - SDL_UploadToGPUBuffer(copy_pass, &vertex_buffer_location, &vertex_buffer_region,true); - SDL_UploadToGPUBuffer(copy_pass, &index_buffer_location, &index_buffer_region,true); + SDL_UploadToGPUBuffer(copy_pass, &vertex_buffer_location, &vertex_buffer_region, true); + SDL_UploadToGPUBuffer(copy_pass, &index_buffer_location, &index_buffer_region, true); SDL_EndGPUCopyPass(copy_pass); SDL_ReleaseGPUTransferBuffer(v->Device, index_transferbuffer); SDL_ReleaseGPUTransferBuffer(v->Device, vertex_transferbuffer); @@ -527,7 +528,7 @@ void ImGui_ImplSDLGPU3_CreateDeviceObjects() sampler_info.mip_lod_bias = 0.0f; sampler_info.min_lod = -1000.0f; sampler_info.max_lod = 1000.0f; - sampler_info.enable_anisotropy = true; + sampler_info.enable_anisotropy = false; sampler_info.max_anisotropy = 1.0f; sampler_info.enable_compare = false; diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 0d7a4586e..c0282f932 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -217,7 +217,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode -#ifdef APP_UNLIMITED_FRAME_RATE +#ifdef APP_USE_UNLIMITED_FRAME_RATE VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 81f0581e9..52544c342 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -222,7 +222,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode -#ifdef APP_UNLIMITED_FRAME_RATE +#ifdef APP_USE_UNLIMITED_FRAME_RATE VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; From fdca6c08adbd71f711261e28f4d75124c14d1cc5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Jan 2025 11:28:47 +0100 Subject: [PATCH 0634/2359] Inputs: added IsMouseReleasedWithDelay() helper. (#8337, #8320) --- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 13 +++++++++++++ imgui.h | 2 ++ imgui_demo.cpp | 2 ++ 4 files changed, 23 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c7f26c3b7..3cce5f1c3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,12 @@ Other changes: snapped to pixels. Effectively it would only be noticeable when hinting is disabled with ImGuiFreeTypeBuilderFlags_NoHinting, as hinting itself snaps glyph advances. +- Inputs: added IsMouseReleasedWithDelay() helper. (#8337, #8320) + Use if you absolutely need to distinguish single-click from double-clicks + by introducing a delay. This is a very rarely used UI idiom, but some apps + use this: e.g. MS Explorer single-click on an icon triggers a rename. + Generally use with 'delay >= io.MouseDoubleClickTime' + combine with a + 'io.MouseClickedLastCount == 1' check. - Windows: legacy SetWindowFontScale() is properly inherited by nested child windows. Note that an upcoming major release should make this obsolete, but in the meanwhile it works better now. (#2701, #8138, #1018) diff --git a/imgui.cpp b/imgui.cpp index f448ab90d..90639578e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9210,6 +9210,17 @@ bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id) return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id) } +// Use if you absolutely need to distinguish single-click from double-click by introducing a delay. +// Generally use with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount == 1' test. +// This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename. +bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]); + return !IsMouseDown(button) && (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay); +} + bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; @@ -9483,6 +9494,8 @@ static void ImGui::UpdateMouseInputs() io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f; io.MouseClickedCount[i] = 0; // Will be filled below io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f; + if (io.MouseReleased[i]) + io.MouseReleasedTime[i] = g.Time; io.MouseDownDurationPrev[i] = io.MouseDownDuration[i]; io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f; if (io.MouseClicked[i]) diff --git a/imgui.h b/imgui.h index 2306667cf..e27c3a3d1 100644 --- a/imgui.h +++ b/imgui.h @@ -1011,6 +1011,7 @@ namespace ImGui IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1. IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true) + IMGUI_API bool IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay); // delayed mouse release (use very sparingly!). Generally used with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount==1' test. This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename. IMGUI_API int GetMouseClickedCount(ImGuiMouseButton button); // return the number of successive mouse-clicks at the time where a click happen (otherwise 0). IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available @@ -2405,6 +2406,7 @@ struct ImGuiIO ImU16 MouseClickedCount[5]; // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down ImU16 MouseClickedLastCount[5]; // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. bool MouseReleased[5]; // Mouse button went from Down to !Down + double MouseReleasedTime[5]; // Time of last released (rarely used! but useful to handle delayed single-click when trying to disambiguate them from double-click). bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding SHIFT requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5100356b3..9f6264a5d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7407,6 +7407,8 @@ static void ShowDemoWindowInputs() ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDown(i)) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); + ImGui::Text("Mouse clicked count:"); + for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseClickedCount[i] > 0) { ImGui::SameLine(); ImGui::Text("b%d: %d", i, io.MouseClickedCount[i]); } // We iterate both legacy native range and named ImGuiKey ranges. This is a little unusual/odd but this allows // displaying the data for old/new backends. From 6906ac979e51ca9b2b60f3d820dd43f8f689884c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Jan 2025 12:12:07 +0100 Subject: [PATCH 0635/2359] ColorEdit, ColorPicker: (Breaking) redesigned how alpha is displayed in the preview square. (#8335, #1578, #346) Added ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg. Removed ImGuiColorEditFlags_AlphaPreview. --- docs/CHANGELOG.txt | 8 ++++++++ imgui.cpp | 3 +++ imgui.h | 16 +++++++++++++--- imgui_demo.cpp | 11 ++++++----- imgui_widgets.cpp | 22 +++++++++++++--------- 5 files changed, 43 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3cce5f1c3..f0aeebbb3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,14 @@ HOW TO UPDATE? Breaking changes: +- ColorEdit, ColorPicker: redesigned how alpha is displayed in the preview square. (#8335, #1578, #346) + - Removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. + - Prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. + - We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. + - The new flags may be combined better and allow finer controls: + - ImGuiColorEditFlags_AlphaOpaque: disable alpha in the preview, but alpha value still editable. + - ImGuiColorEditFlags_AlphaNoBg: disable rendering a checkerboard background behind transparent color. + - ImGuiColorEditFlags_AlphaPreviewHalf: display half opaque / half transparent preview. - Backends: SDLGPU3: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device for consistency. (#8163, #7998, #7988) diff --git a/imgui.cpp b/imgui.cpp index 90639578e..0b988f2b4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,9 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. + prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. + the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls: - 2025/01/14 (1.91.7) - renamed ImGuiTreeNodeFlags_SpanTextWidth to ImGuiTreeNodeFlags_SpanLabelWidth for consistency with other names. Kept redirection enum (will obsolete). (#6937) - 2024/11/27 (1.91.6) - changed CRC32 table from CRC32-adler to CRC32c polynomial in order to be compatible with the result of SSE 4.2 instructions. As a result, old .ini data may be partially lost (docking and tables information particularly). diff --git a/imgui.h b/imgui.h index e27c3a3d1..d42a932c2 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.8 WIP" -#define IMGUI_VERSION_NUM 19172 +#define IMGUI_VERSION_NUM 19173 #define IMGUI_HAS_TABLE /* @@ -1753,8 +1753,14 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) - ImGuiColorEditFlags_AlphaPreview = 1 << 11, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. - ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 12, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. + + // Alpha preview + // - Prior to 1.91.8 (2025/01/21): alpha was made opaque in the preview by default using old name ImGuiColorEditFlags_AlphaPreview. + // - We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. + // - The new flags may be combined better and allow finer controls. + ImGuiColorEditFlags_AlphaOpaque = 1 << 11, // // ColorEdit, ColorPicker, ColorButton: disable alpha in the preview,. Contrary to _NoAlpha it may still be edited when calling ColorEdit4()/ColorPicker4(). For ColorButton() this does the same as _NoAlpha. + ImGuiColorEditFlags_AlphaNoBg = 1 << 12, // // ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 13, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. // User Options (right-click on widget to change some of them). ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. @@ -1774,12 +1780,16 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, // [Internal] Masks + ImGuiColorEditFlags_AlphaMask_ = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf, ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, ImGuiColorEditFlags_InputMask_ = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV, // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiColorEditFlags_AlphaPreview = 0, // [Removed in 1.91.8] This is the default now. Will display a checkerboard unless ImGuiColorEditFlags_AlphaNoBg is set. +#endif //ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9f6264a5d..43344f3fc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2117,11 +2117,12 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) if (ImGui::TreeNode("Color/Picker Widgets")) { static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f); - static ImGuiColorEditFlags base_flags = ImGuiColorEditFlags_AlphaPreview; + static ImGuiColorEditFlags base_flags = ImGuiColorEditFlags_None; ImGui::SeparatorText("Options"); ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &base_flags, ImGuiColorEditFlags_NoAlpha); - ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaPreview", &base_flags, ImGuiColorEditFlags_AlphaPreview); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaOpaque", &base_flags, ImGuiColorEditFlags_AlphaOpaque); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaNoBg", &base_flags, ImGuiColorEditFlags_AlphaNoBg); ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaPreviewHalf", &base_flags, ImGuiColorEditFlags_AlphaPreviewHalf); ImGui::CheckboxFlags("ImGuiColorEditFlags_NoDragDrop", &base_flags, ImGuiColorEditFlags_NoDragDrop); ImGui::CheckboxFlags("ImGuiColorEditFlags_NoOptions", &base_flags, ImGuiColorEditFlags_NoOptions); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); @@ -8047,9 +8048,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) filter.Draw("Filter colors", ImGui::GetFontSize() * 16); static ImGuiColorEditFlags alpha_flags = 0; - if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine(); - if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine(); - if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); + if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) { alpha_flags = ImGuiColorEditFlags_AlphaOpaque; } ImGui::SameLine(); + if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine(); + if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); HelpMarker( "In the color list:\n" "Left-click on color square to open color picker,\n" diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4f58c4cd2..e0fec9122 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5902,7 +5902,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl if ((flags & ImGuiColorEditFlags_NoLabel)) Text("Current"); - ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip; + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoTooltip; ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)); if (ref_col != NULL) { @@ -5942,7 +5942,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl if ((flags & ImGuiColorEditFlags_NoInputs) == 0) { PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); - ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoSmallPreview; ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags_DisplayMask_) == 0) if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB)) @@ -6118,8 +6118,8 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); - if (flags & ImGuiColorEditFlags_NoAlpha) - flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf); + if (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque)) + flags &= ~(ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf); ImVec4 col_rgb = col; if (flags & ImGuiColorEditFlags_InputHSV) @@ -6138,14 +6138,17 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f) { float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f); - RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags_RoundCornersRight); + if ((flags & ImGuiColorEditFlags_AlphaNoBg) == 0) + RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags_RoundCornersRight); + else + window->DrawList->AddRectFilled(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundCornersRight); window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft); } else { // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha - ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha; - if (col_source.w < 1.0f) + ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaOpaque) ? col_rgb_without_alpha : col_rgb; + if (col_source.w < 1.0f && (flags & ImGuiColorEditFlags_AlphaNoBg) == 0) RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding); else window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding); @@ -6175,7 +6178,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl // Tooltip if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered && IsItemHovered(ImGuiHoveredFlags_ForTooltip)) - ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)); + ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_)); return pressed; } @@ -6216,7 +6219,8 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); - ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); + ImGuiColorEditFlags flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_; + ColorButton("##preview", cf, (flags & flags_to_forward) | ImGuiColorEditFlags_NoTooltip, sz); SameLine(); if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags_InputMask_)) { From 71da34c48cf70f1f553a7a8b4edfbb0babdcfbef Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Jan 2025 16:56:18 +0100 Subject: [PATCH 0636/2359] Debug Tools: Tweaked font preview + indent "Glyphs" block. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 103 ++++++++++++++++++++++++--------------------- 2 files changed, 57 insertions(+), 47 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f0aeebbb3..ab01011c7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -73,6 +73,7 @@ Other changes: for rounded tabs. Reduced default thickness (style.TabBarOverlineSize), increased default rounding (style.TabRounding). (#8334) [@Kian738, @ocornut] styles as the current look is not right (but ImGuiCol_TabSelectedOverline stays the same). +- Debug Tools: Tweaked font preview. - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by diff --git a/imgui.cpp b/imgui.cpp index 0b988f2b4..0fe7c8209 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16147,18 +16147,24 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co // [DEBUG] Display details for a single font, called by ShowStyleEditor(). void ImGui::DebugNodeFont(ImFont* font) { - bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)", + bool opened = TreeNode(font, "Font: \"%s\": %.2f px, %d glyphs, %d sources(s)", font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); - SameLine(); - if (SmallButton("Set as default")) - GetIO().FontDefault = font; - if (!opened) - return; // Display preview text + if (!opened) + Indent(); + Indent(); PushFont(font); Text("The quick brown fox jumps over the lazy dog"); PopFont(); + if (!opened) + { + Unindent(); + Unindent(); + return; + } + if (SmallButton("Set as default")) + GetIO().FontDefault = font; // Display details SetNextItemWidth(GetFontSize() * 8); @@ -16182,57 +16188,60 @@ void ImGui::DebugNodeFont(ImFont* font) config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y); // Display all glyphs of the fonts in separate pages of 256 characters - if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) { - ImDrawList* draw_list = GetWindowDrawList(); - const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); - const float cell_size = font->FontSize * 1; - const float cell_spacing = GetStyle().ItemSpacing.y; - for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) + if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) { - // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) - // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT - // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) - if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191)) + ImDrawList* draw_list = GetWindowDrawList(); + const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); + const float cell_size = font->FontSize * 1; + const float cell_spacing = GetStyle().ItemSpacing.y; + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) { - base += 8192 - 256; - continue; - } - - int count = 0; - for (unsigned int n = 0; n < 256; n++) - if (font->FindGlyphNoFallback((ImWchar)(base + n))) - count++; - if (count <= 0) - continue; - if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) - continue; - - // Draw a 16x16 grid of glyphs - ImVec2 base_pos = GetCursorScreenPos(); - for (unsigned int n = 0; n < 256; n++) - { - // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions - // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. - ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); - ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); - const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); - draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); - if (!glyph) - continue; - font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); - if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip()) + // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) + // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT + // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) + if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191)) { - DebugNodeFontGlyph(font, glyph); - EndTooltip(); + base += 8192 - 256; + continue; } + + int count = 0; + for (unsigned int n = 0; n < 256; n++) + if (font->FindGlyphNoFallback((ImWchar)(base + n))) + count++; + if (count <= 0) + continue; + if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) + continue; + + // Draw a 16x16 grid of glyphs + ImVec2 base_pos = GetCursorScreenPos(); + for (unsigned int n = 0; n < 256; n++) + { + // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions + // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); + const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); + if (!glyph) + continue; + font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); + if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip()) + { + DebugNodeFontGlyph(font, glyph); + EndTooltip(); + } + } + Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); + TreePop(); } - Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); TreePop(); } - TreePop(); } TreePop(); + Unindent(); } void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph) From 10199341b1d5c193a9f2748fdeeeac2e57ce354e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Jan 2025 11:31:32 +0100 Subject: [PATCH 0637/2359] ImFontAtlas: made calling ClearFonts() call ClearInputData(). (#8174, #6556, #6336, #4723) --- docs/CHANGELOG.txt | 4 +++- imgui.h | 2 +- imgui_draw.cpp | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ab01011c7..f0021b2ab 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,7 +54,6 @@ Breaking changes: Other changes: -- ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) - imgui_freetype: fixed issue where glyph advances would incorrectly be snapped to pixels. Effectively it would only be noticeable when hinting is disabled with ImGuiFreeTypeBuilderFlags_NoHinting, as hinting itself @@ -74,6 +73,9 @@ Other changes: increased default rounding (style.TabRounding). (#8334) [@Kian738, @ocornut] styles as the current look is not right (but ImGuiCol_TabSelectedOverline stays the same). - Debug Tools: Tweaked font preview. +- ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) +- ImFontAtlas: made calling ClearFonts() call ClearInputData(), as calling + one without the other is never correct. (#8174, #6556, #6336, #4723) - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by diff --git a/imgui.h b/imgui.h index d42a932c2..48910ea75 100644 --- a/imgui.h +++ b/imgui.h @@ -3355,8 +3355,8 @@ struct ImFontAtlas 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(const char* 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 ClearInputData(); // 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 ClearFonts(); // Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. - IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates). IMGUI_API void Clear(); // Clear all input and output. // Build atlas, retrieve pixel data. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 97342b35b..eb5cfd51b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2520,6 +2520,7 @@ void ImFontAtlas::ClearTexData() void ImFontAtlas::ClearFonts() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + ClearInputData(); Fonts.clear_delete(); TexReady = false; } From 9bc5b0406d36508a3167b0a069f3f18987f838e6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 14:39:07 +0100 Subject: [PATCH 0638/2359] Windows, Style: Fixed small rendering issues with menu bar, resize grip and scrollbar when using thick border sizes. (#8267, #7887) Amend e.g. 742b5f4c. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 14 ++++++++------ imgui_widgets.cpp | 10 ++++++---- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f0021b2ab..c6e9d26f3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,8 @@ Other changes: - Windows: legacy SetWindowFontScale() is properly inherited by nested child windows. Note that an upcoming major release should make this obsolete, but in the meanwhile it works better now. (#2701, #8138, #1018) +- Windows, Style: Fixed small rendering issues with menu bar, resize grip and + scrollbar when using thick border sizes. (#8267, #7887) - ColorEdit, ColorPicker: Fixed alpha preview broken in 1.91.7. (#8336, #8241). [@PathogenDavid] - Tabs, Style: reworked selected overline rendering to better accommodate for rounded tabs. Reduced default thickness (style.TabBarOverlineSize), diff --git a/imgui.cpp b/imgui.cpp index 0fe7c8209..ac91f490b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6712,7 +6712,7 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) { float y = window->Pos.y + window->TitleBarHeight - 1; - window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize); + window->DrawList->AddLine(ImVec2(window->Pos.x + border_size * 0.5f, y), ImVec2(window->Pos.x + window->Size.x - border_size * 0.5f, y), border_col, g.Style.FrameBorderSize); } } @@ -6772,9 +6772,10 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar { ImRect menu_bar_rect = window->MenuBarRect(); menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. - window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); + window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); + float window_border_size = window->WindowBorderSize; if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) - window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + window->DrawList->AddLine(menu_bar_rect.GetBL() + ImVec2(window_border_size * 0.5f, 0.0f), menu_bar_rect.GetBR() - ImVec2(window_border_size * 0.5f, 0.0f), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } // Scrollbars @@ -6793,9 +6794,10 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar continue; const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); - window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size))); - window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size))); - window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12); + const float border_inner = IM_ROUND(window_border_size * 0.5f); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(border_inner, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, border_inner))); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, border_inner) : ImVec2(border_inner, resize_grip_draw_size))); + window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12); window->DrawList->PathFillConvex(col); } } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e0fec9122..9ce939fd3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -911,13 +911,14 @@ ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis) { const ImRect outer_rect = window->Rect(); const ImRect inner_rect = window->InnerRect; - const float border_size = window->WindowBorderSize; const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar) IM_ASSERT(scrollbar_size > 0.0f); + const float border_size = IM_ROUND(window->WindowBorderSize * 0.5f); + const float border_top = (window->Flags & ImGuiWindowFlags_MenuBar) ? IM_ROUND(GImGui->Style.FrameBorderSize * 0.5f) : 0.0f; if (axis == ImGuiAxis_X) - return ImRect(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x - border_size, outer_rect.Max.y - border_size); + return ImRect(inner_rect.Min.x + border_size, ImMax(outer_rect.Min.y + border_size, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x - border_size, outer_rect.Max.y - border_size); else - return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y, outer_rect.Max.x - border_size, inner_rect.Max.y - border_size); + return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y + border_top, outer_rect.Max.x - border_size, inner_rect.Max.y - border_size); } void ImGui::Scrollbar(ImGuiAxis axis) @@ -8630,8 +8631,9 @@ bool ImGui::BeginMenuBar() // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy. + const float border_top = ImMax(window->WindowBorderSize * 0.5f - window->TitleBarHeight, 0.0f); ImRect bar_rect = window->MenuBarRect(); - ImRect clip_rect(IM_ROUND(bar_rect.Min.x + window->WindowBorderSize), IM_ROUND(bar_rect.Min.y + window->WindowBorderSize), IM_ROUND(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize))), IM_ROUND(bar_rect.Max.y)); + ImRect clip_rect(IM_ROUND(bar_rect.Min.x + window->WindowBorderSize * 0.5f), IM_ROUND(bar_rect.Min.y + border_top), IM_ROUND(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize * 0.5f))), IM_ROUND(bar_rect.Max.y)); clip_rect.ClipWith(window->OuterRectClipped); PushClipRect(clip_rect.Min, clip_rect.Max, false); From bbf957875bbca8fb8b459997fba571eba964f4d2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 14:43:16 +0100 Subject: [PATCH 0639/2359] Amend 9bc5b04 to avoid using GImGui mid-function. --- imgui_widgets.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9ce939fd3..1bd19fe7c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -909,12 +909,13 @@ ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis) // Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set. ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis) { + ImGuiContext& g = *GImGui; const ImRect outer_rect = window->Rect(); const ImRect inner_rect = window->InnerRect; const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar) IM_ASSERT(scrollbar_size > 0.0f); const float border_size = IM_ROUND(window->WindowBorderSize * 0.5f); - const float border_top = (window->Flags & ImGuiWindowFlags_MenuBar) ? IM_ROUND(GImGui->Style.FrameBorderSize * 0.5f) : 0.0f; + const float border_top = (window->Flags & ImGuiWindowFlags_MenuBar) ? IM_ROUND(g.Style.FrameBorderSize * 0.5f) : 0.0f; if (axis == ImGuiAxis_X) return ImRect(inner_rect.Min.x + border_size, ImMax(outer_rect.Min.y + border_size, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x - border_size, outer_rect.Max.y - border_size); else From ed7551c1d4443b92513337fd6653f0fac8268da9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 14:59:37 +0100 Subject: [PATCH 0640/2359] Selectable: Fixed horizontal label alignment when combined with using ImGuiSelectableFlags_SpanAllColumns. (#8338) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 9 +++------ 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c6e9d26f3..eac83b090 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -139,6 +139,8 @@ Other changes: the label (not only the highlight/frame) also spans all columns. This is useful for table rows where you know nothing else is submitted. (#8318, #3565) Obviously best used with ImGuiTableFlags_NoBordersInBodyUntilResize. +- Selectable: Fixed horizontal label alignment when combined with using + ImGuiSelectableFlags_SpanAllColumns. (#8338) - Drags: Added ImGuiSliderFlags_NoSpeedTweaks flag to disable keyboard modifiers altering the tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. (#8223) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1bd19fe7c..ad4820827 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6943,13 +6943,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) size.x = ImMax(label_size.x, max_x - min_x); - // Text stays at the submission position, but bounding box may be extended on both sides - const ImVec2 text_min = pos; - const ImVec2 text_max(min_x + size.x, pos.y + size.y); - // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable. // FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos. - ImRect bb(min_x, pos.y, text_max.x, text_max.y); + ImRect bb(min_x, pos.y, min_x + size.x, pos.y + size.y); if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) { const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x; @@ -7085,8 +7081,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl PopColumnsBackground(); } + // Text stays at the submission position. Alignment/clipping extents ignore SpanAllColumns. if (is_visible) - RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); + RenderTextClipped(pos, ImVec2(window->WorkRect.Max.x, pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb); // Automatically close popups if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups)) From 53244aaac72f3986dd29d79c2aecb2cc2cdf58f5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 15:00:21 +0100 Subject: [PATCH 0641/2359] Amend 9bc5b04 with a shadowed variable warning fix. --- imgui.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index ac91f490b..5468951d7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6773,7 +6773,6 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar ImRect menu_bar_rect = window->MenuBarRect(); menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); - float window_border_size = window->WindowBorderSize; if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) window->DrawList->AddLine(menu_bar_rect.GetBL() + ImVec2(window_border_size * 0.5f, 0.0f), menu_bar_rect.GetBR() - ImVec2(window_border_size * 0.5f, 0.0f), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } From 9eafb7bbfb7b281029056f042514a76a9b17bc5a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 16:54:59 +0100 Subject: [PATCH 0642/2359] ImFont: IndexLookup[] table hold 16-bit values even in ImWchar32 mode. --- docs/CHANGELOG.txt | 3 +++ imgui.h | 2 +- imgui_draw.cpp | 19 ++++++++++--------- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index eac83b090..d9a95e3c1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -78,6 +78,9 @@ Other changes: - ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) - ImFontAtlas: made calling ClearFonts() call ClearInputData(), as calling one without the other is never correct. (#8174, #6556, #6336, #4723) +- ImFont: IndexLookup[] table hold 16-bit values even in ImWchar32 mode, + as it accounts for number of glyphs in same font. This is favorable to + CalcTextSize() calls touching less memory. - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by diff --git a/imgui.h b/imgui.h index 48910ea75..8c6082d9e 100644 --- a/imgui.h +++ b/imgui.h @@ -3456,7 +3456,7 @@ struct ImFont float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) // [Internal] Members: Hot ~28/40 bytes (for RenderText loop) - ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. + ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. ImVector Glyphs; // 12-16 // out // // All glyphs. const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index eb5cfd51b..1a30b9a9b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3738,7 +3738,7 @@ void ImFont::BuildLookupTable() { int codepoint = (int)Glyphs[i].Codepoint; IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX; - IndexLookup[codepoint] = (ImWchar)i; + IndexLookup[codepoint] = (ImU16)i; // Mark 4K page as used const int page_n = codepoint / 8192; @@ -3756,7 +3756,7 @@ void ImFont::BuildLookupTable() tab_glyph.Codepoint = '\t'; tab_glyph.AdvanceX *= IM_TABSIZE; IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; - IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size - 1); + IndexLookup[(int)tab_glyph.Codepoint] = (ImU16)(Glyphs.Size - 1); } // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons) @@ -3829,7 +3829,7 @@ void ImFont::GrowIndex(int new_size) if (new_size <= IndexLookup.Size) return; IndexAdvanceX.resize(new_size, -1.0f); - IndexLookup.resize(new_size, (ImWchar)-1); + IndexLookup.resize(new_size, (ImU16)-1); } // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. @@ -3872,6 +3872,7 @@ void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, floa glyph.U1 = u1; glyph.V1 = v1; glyph.AdvanceX = advance_x; + IM_ASSERT(Glyphs.Size < 0xFFFF); // IndexLookup[] hold 16-bit values and -1 is reserved. // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round) // We use (U1-U0)*TexWidth instead of X1-X0 to account for oversampling. @@ -3885,13 +3886,13 @@ void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. unsigned int index_size = (unsigned int)IndexLookup.Size; - if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists + if (dst < index_size && IndexLookup.Data[dst] == (ImU16)-1 && !overwrite_dst) // 'dst' already exists return; if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op return; GrowIndex(dst + 1); - IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImWchar)-1; + IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImU16)-1; IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f; } @@ -3900,8 +3901,8 @@ const ImFontGlyph* ImFont::FindGlyph(ImWchar c) { if (c >= (size_t)IndexLookup.Size) return FallbackGlyph; - const ImWchar i = IndexLookup.Data[c]; - if (i == (ImWchar)-1) + const ImU16 i = IndexLookup.Data[c]; + if (i == (ImU16)-1) return FallbackGlyph; return &Glyphs.Data[i]; } @@ -3910,8 +3911,8 @@ const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) { if (c >= (size_t)IndexLookup.Size) return NULL; - const ImWchar i = IndexLookup.Data[c]; - if (i == (ImWchar)-1) + const ImU16 i = IndexLookup.Data[c]; + if (i == (ImU16)-1) return NULL; return &Glyphs.Data[i]; } From 4211fdc70bac319543d4fedac1d6d42c9f1a94a5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Jan 2025 15:44:51 +0100 Subject: [PATCH 0643/2359] ImFont: compact comments in header section. --- imgui.h | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/imgui.h b/imgui.h index 8c6082d9e..ba763da86 100644 --- a/imgui.h +++ b/imgui.h @@ -3451,28 +3451,28 @@ struct ImFontAtlas struct ImFont { // [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) - ImVector IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). + ImVector IndexAdvanceX; // 12-16 // out // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX - float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) + float FontSize; // 4 // in // Height of characters/line, set during loading (don't change after loading) // [Internal] Members: Hot ~28/40 bytes (for RenderText loop) - ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. - ImVector Glyphs; // 12-16 // out // // All glyphs. + ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. + ImVector Glyphs; // 12-16 // out // All glyphs. const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) // [Internal] Members: Cold ~32/40 bytes // Conceptually ConfigData[] is the list of font sources merged to create this font. - ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into - const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData to ConfigDataCount instances - short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImFontAtlas* ContainerAtlas; // 4-8 // out // What we has been loaded into + const ImFontConfig* ConfigData; // 4-8 // in // Pointer within ContainerAtlas->ConfigData to ConfigDataCount instances + short ConfigDataCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. short EllipsisCharCount; // 1 // out // 1 or 3 - ImWchar EllipsisChar; // 2-4 // out // = '...'/'.'// Character used for ellipsis rendering. - ImWchar FallbackChar; // 2-4 // out // = FFFD/'?' // Character used if a glyph isn't found. - float EllipsisWidth; // 4 // out // Width - float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 - float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() - float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) - int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). + ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') + float EllipsisWidth; // 4 // out // Total ellipsis Width + float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 + float Scale; // 4 // in // Base font scale (1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() + float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) + int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) bool DirtyLookupTables; // 1 // out // ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. @@ -3481,9 +3481,9 @@ struct ImFont IMGUI_API ~ImFont(); IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c); IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c); - float GetCharAdvance(ImWchar c) { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } - bool IsLoaded() const { return ContainerAtlas != NULL; } - const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } + float GetCharAdvance(ImWchar c) { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } + bool IsLoaded() const { return ContainerAtlas != NULL; } + const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } // '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. From 8a1613a382f81d321355efe47698a34520fe2c8a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 19:27:50 +0100 Subject: [PATCH 0644/2359] Fonts: OversampleH/OversampleV value defaults to 0 for automatic selection. --- docs/CHANGELOG.txt | 10 +++++++--- docs/FONTS.md | 2 -- imgui.cpp | 10 +++++++--- imgui.h | 4 ++-- imgui_draw.cpp | 30 ++++++++++++++++++++---------- imgui_internal.h | 1 + misc/freetype/imgui_freetype.cpp | 2 +- 7 files changed, 38 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d9a95e3c1..3e0080ac3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,11 +76,15 @@ Other changes: styles as the current look is not right (but ImGuiCol_TabSelectedOverline stays the same). - Debug Tools: Tweaked font preview. - ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) -- ImFontAtlas: made calling ClearFonts() call ClearInputData(), as calling - one without the other is never correct. (#8174, #6556, #6336, #4723) -- ImFont: IndexLookup[] table hold 16-bit values even in ImWchar32 mode, +- Fonts: IndexLookup[] table hold 16-bit values even in ImWchar32 mode, as it accounts for number of glyphs in same font. This is favorable to CalcTextSize() calls touching less memory. +- Fonts: OversampleH/OversampleV defaults to 0 for automatic selection. + - OversampleH == 0 --> use 1 or 2 depending on font size and use of PixelSnapH. + - OversampleV == 0 --> always use 1. + This also +- ImFontAtlas: made calling ClearFonts() call ClearInputData(), as calling + one without the other is never correct. (#8174, #6556, #6336, #4723) - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in provided example, to reduce latency. - Examples: Vulkan: better handle VK_SUBOPTIMAL_KHR being returned by diff --git a/docs/FONTS.md b/docs/FONTS.md index c451af61c..e36afdf81 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -110,8 +110,6 @@ ImGui::PopFont(); **For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** ```cpp ImFontConfig config; -config.OversampleH = 2; -config.OversampleV = 1; config.GlyphExtraSpacing.x = 1.0f; ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); ``` diff --git a/imgui.cpp b/imgui.cpp index 5468951d7..3764b5663 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16184,9 +16184,13 @@ void ImGui::DebugNodeFont(ImFont* font) Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt); for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) if (font->ConfigData) - if (const ImFontConfig* cfg = &font->ConfigData[config_i]) - BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", - config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y); + { + const ImFontConfig* cfg = &font->ConfigData[config_i]; + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(cfg, &oversample_h, &oversample_v); + BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", + config_i, cfg->Name, cfg->OversampleH, oversample_h, cfg->OversampleV, oversample_v, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y); + } // Display all glyphs of the fonts in separate pages of 256 characters { diff --git a/imgui.h b/imgui.h index ba763da86..8e240b390 100644 --- a/imgui.h +++ b/imgui.h @@ -3254,8 +3254,8 @@ struct ImFontConfig bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. int FontNo; // 0 // Index of font within TTF/OTF file - int OversampleH; // 2 // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. - int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis. + int OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. + int OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1a30b9a9b..c7f8044c6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2374,8 +2374,8 @@ ImFontConfig::ImFontConfig() { memset(this, 0, sizeof(*this)); FontDataOwnedByAtlas = true; - OversampleH = 2; - OversampleV = 1; + OversampleH = 0; // Auto == 1 or 2 depending on size + OversampleV = 0; // Auto == 1 GlyphMaxAdvanceX = FLT_MAX; RasterizerMultiply = 1.0f; RasterizerDensity = 1.0f; @@ -2573,8 +2573,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); - IM_ASSERT(font_cfg->OversampleH > 0 && font_cfg->OversampleV > 0 && "Is ImFontConfig struct correctly initialized?"); - IM_ASSERT(font_cfg->RasterizerDensity > 0.0f); + IM_ASSERT(font_cfg->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); // Create new font if (!font_cfg->MergeMode) @@ -2858,6 +2857,13 @@ static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector* out->push_back((int)(((it - it_begin) << 5) + bit_n)); } +void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* cfg, int* out_oversample_h, int* out_oversample_v) +{ + // Automatically disable horizontal oversampling over size 32 + *out_oversample_h = (cfg->OversampleH != 0) ? cfg->OversampleH : (cfg->SizePixels * cfg->RasterizerDensity > 32.0f || cfg->PixelSnapH) ? 1 : 2; + *out_oversample_v = (cfg->OversampleV != 0) ? cfg->OversampleV : 1; +} + static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) { IM_ASSERT(atlas->ConfigData.Size > 0); @@ -2985,15 +2991,19 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) buf_rects_out_n += src_tmp.GlyphsCount; buf_packedchars_out_n += src_tmp.GlyphsCount; - // Convert our ranges in the format stb_truetype wants + // Automatic selection of oversampling parameters ImFontConfig& cfg = atlas->ConfigData[src_i]; + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(&cfg, &oversample_h, &oversample_v); + + // Convert our ranges in the format stb_truetype wants src_tmp.PackRange.font_size = cfg.SizePixels * cfg.RasterizerDensity; src_tmp.PackRange.first_unicode_codepoint_in_range = 0; src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data; src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size; src_tmp.PackRange.chardata_for_range = src_tmp.PackedChars; - src_tmp.PackRange.h_oversample = (unsigned char)cfg.OversampleH; - src_tmp.PackRange.v_oversample = (unsigned char)cfg.OversampleV; + src_tmp.PackRange.h_oversample = (unsigned char)oversample_h; + src_tmp.PackRange.v_oversample = (unsigned char)oversample_v; // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects) const float scale = (cfg.SizePixels > 0.0f) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels * cfg.RasterizerDensity) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels * cfg.RasterizerDensity); @@ -3002,9 +3012,9 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) int x0, y0, x1, y1; const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]); IM_ASSERT(glyph_index_in_font != 0); - stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * cfg.OversampleH, scale * cfg.OversampleV, 0, 0, &x0, &y0, &x1, &y1); - src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + pack_padding + cfg.OversampleH - 1); - src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + pack_padding + cfg.OversampleV - 1); + stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * oversample_h, scale * oversample_v, 0, 0, &x0, &y0, &x1, &y1); + src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + pack_padding + oversample_h - 1); + src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + pack_padding + oversample_v - 1); total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h; } } diff --git a/imgui_internal.h b/imgui_internal.h index 33a6ec8b0..e78659adc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3571,6 +3571,7 @@ IMGUI_API void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, IMGUI_API void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value); IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); +IMGUI_API void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* cfg, int* out_oversample_h, int* out_oversample_v); //----------------------------------------------------------------------------- // [SECTION] Test Engine specific hooks (imgui_test_engine) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 421fdba63..029991bbd 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -33,7 +33,7 @@ // - For correct results you need to be using sRGB and convert to linear space in the pixel shader output. // - The default dear imgui styles will be impacted by this change (alpha values will need tweaking). -// FIXME: cfg.OversampleH, OversampleV are not supported (but perhaps not so necessary with this rasterizer). +// FIXME: cfg.OversampleH, OversampleV are not supported, but generally not necessary with this rasterizer because Hinting makes everything look better. #include "imgui.h" #ifndef IMGUI_DISABLE From afb6e9a879cbac8346601a5b4984e3991c30cc8f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 20:03:04 +0100 Subject: [PATCH 0645/2359] Fonts: OversampleH auto-selection uses 36 as heuristic for now. --- imgui_draw.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c7f8044c6..f00a68361 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2859,8 +2859,8 @@ static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector* void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* cfg, int* out_oversample_h, int* out_oversample_v) { - // Automatically disable horizontal oversampling over size 32 - *out_oversample_h = (cfg->OversampleH != 0) ? cfg->OversampleH : (cfg->SizePixels * cfg->RasterizerDensity > 32.0f || cfg->PixelSnapH) ? 1 : 2; + // Automatically disable horizontal oversampling over size 36 + *out_oversample_h = (cfg->OversampleH != 0) ? cfg->OversampleH : (cfg->SizePixels * cfg->RasterizerDensity > 36.0f || cfg->PixelSnapH) ? 1 : 2; *out_oversample_v = (cfg->OversampleV != 0) ? cfg->OversampleV : 1; } From 96e3b147f0ad8a0b70e818d6d845aa7956e8e7b2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 25 Jan 2025 01:14:46 +0100 Subject: [PATCH 0646/2359] Fixed build with IMGUI_ENABLE_FREETYPE (#8346) --- imgui_draw.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f00a68361..4b59d6775 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2819,6 +2819,13 @@ void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsig *data = table[*data]; } +void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* cfg, int* out_oversample_h, int* out_oversample_v) +{ + // Automatically disable horizontal oversampling over size 36 + *out_oversample_h = (cfg->OversampleH != 0) ? cfg->OversampleH : (cfg->SizePixels * cfg->RasterizerDensity > 36.0f || cfg->PixelSnapH) ? 1 : 2; + *out_oversample_v = (cfg->OversampleV != 0) ? cfg->OversampleV : 1; +} + #ifdef IMGUI_ENABLE_STB_TRUETYPE // Temporary data for one source font (multiple source fonts can be merged into one destination ImFont) // (C++03 doesn't allow instancing ImVector<> with function-local types so we declare the type here.) @@ -2857,13 +2864,6 @@ static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector* out->push_back((int)(((it - it_begin) << 5) + bit_n)); } -void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* cfg, int* out_oversample_h, int* out_oversample_v) -{ - // Automatically disable horizontal oversampling over size 36 - *out_oversample_h = (cfg->OversampleH != 0) ? cfg->OversampleH : (cfg->SizePixels * cfg->RasterizerDensity > 36.0f || cfg->PixelSnapH) ? 1 : 2; - *out_oversample_v = (cfg->OversampleV != 0) ? cfg->OversampleV : 1; -} - static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) { IM_ASSERT(atlas->ConfigData.Size > 0); From 5a28f188ff0f502e63336f2993235308ea775267 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jan 2025 12:27:10 +0100 Subject: [PATCH 0647/2359] Fixed parameter names to SetLastItemData() to align with current names. --- imgui.cpp | 6 +++--- imgui_internal.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3764b5663..9416757c8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4695,12 +4695,12 @@ bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id) // This is also inlined in ItemAdd() // Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect. -void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect) +void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect) { ImGuiContext& g = *GImGui; g.LastItemData.ID = item_id; - g.LastItemData.ItemFlags = in_flags; - g.LastItemData.StatusFlags = item_flags; + g.LastItemData.ItemFlags = item_flags; + g.LastItemData.StatusFlags = status_flags; g.LastItemData.Rect = g.LastItemData.NavRect = item_rect; } diff --git a/imgui_internal.h b/imgui_internal.h index e78659adc..a8cd3719e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3095,7 +3095,7 @@ namespace ImGui IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags); IMGUI_API bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags = 0); IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id); - IMGUI_API void SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect); + IMGUI_API void SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect); IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); IMGUI_API void PushMultiItemsWidths(int components, float width_full); From 134fbe12451c4538c17a7730c1fa30663372e06e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jan 2025 12:39:44 +0100 Subject: [PATCH 0648/2359] Windows: Fixed IsItemXXXX() functions not working on append-version of EndChild(). (#8350) Also made some of the fields accessible after BeginChild() to match Begin() logic. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 28 ++++++++++++++++++++++------ imgui_internal.h | 1 + 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3e0080ac3..e9952a080 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,8 @@ Other changes: but in the meanwhile it works better now. (#2701, #8138, #1018) - Windows, Style: Fixed small rendering issues with menu bar, resize grip and scrollbar when using thick border sizes. (#8267, #7887) +- Windows: Fixed IsItemXXXX() functions not working on append-version of EndChild(). (#8350) + Also made some of the fields accessible after BeginChild() to match Begin() logic. - ColorEdit, ColorPicker: Fixed alpha preview broken in 1.91.7. (#8336, #8241). [@PathogenDavid] - Tabs, Style: reworked selected overline rendering to better accommodate for rounded tabs. Reduced default thickness (style.TabBarOverlineSize), diff --git a/imgui.cpp b/imgui.cpp index 9416757c8..7afea92bc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1256,6 +1256,7 @@ static void RenderWindowTitleBarContents(ImGuiWindow* window, const static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col); static void RenderDimmedBackgrounds(); static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect); +static void SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect); // Viewports const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter. @@ -4704,6 +4705,18 @@ void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiIte g.LastItemData.Rect = g.LastItemData.NavRect = item_rect; } +static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect) +{ + ImGuiContext& g = *GImGui; + SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DC.WindowItemStatusFlags, rect); +} + +static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect) +{ + ImGuiContext& g = *GImGui; + SetLastItemData(window->ChildId, g.CurrentItemFlags, window->DC.WindowItemStatusFlags, rect); +} + float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { if (wrap_pos_x < 0.0f) @@ -6157,7 +6170,14 @@ void ImGui::EndChild() } if (g.HoveredWindow == child_window) g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + child_window->DC.WindowItemStatusFlags = g.LastItemData.StatusFlags; + //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd() } + else + { + SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); + } + g.WithinEndChildID = backup_within_end_child_id; g.LogLinePosY = -FLT_MAX; // To enforce a carriage return } @@ -7612,6 +7632,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). // This is useful to allow creating context menus on title bar only, etc. + window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None; + window->DC.WindowItemStatusFlags |= IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; SetLastItemDataForWindow(window, title_bar_rect); // [DEBUG] @@ -7717,12 +7739,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) return !window->SkipItems; } -static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect) -{ - ImGuiContext& g = *GImGui; - SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect); -} - void ImGui::End() { ImGuiContext& g = *GImGui; diff --git a/imgui_internal.h b/imgui_internal.h index a8cd3719e..b7b81c2e2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2456,6 +2456,7 @@ struct IMGUI_API ImGuiWindowTempData ImGuiLayoutType LayoutType; ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() ImU32 ModalDimBgColor; + ImGuiItemStatusFlags WindowItemStatusFlags; // Local parameters stacks // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. From a05d547ae88c228a392153bbee6a1fa88abc926e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jan 2025 14:39:26 +0100 Subject: [PATCH 0649/2359] Windows: separating WindowItemStatusFlags from ChildItemStatusFlag, because IsItemXXX _after_ BeginChild()>Begin() shouldn't return last status emitted by e.g. EndChild() As IsItemXXX() after is specced as returning title bar data we don't want to lock ourselves up from adding them to child window (e.g. MDI idea using windows to host child windows). --- imgui.cpp | 4 ++-- imgui_internal.h | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7afea92bc..e4c2f2a2e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4714,7 +4714,7 @@ static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& r static void ImGui::SetLastItemDataForChildWindowItem(ImGuiWindow* window, const ImRect& rect) { ImGuiContext& g = *GImGui; - SetLastItemData(window->ChildId, g.CurrentItemFlags, window->DC.WindowItemStatusFlags, rect); + SetLastItemData(window->ChildId, g.CurrentItemFlags, window->DC.ChildItemStatusFlags, rect); } float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) @@ -6170,7 +6170,7 @@ void ImGui::EndChild() } if (g.HoveredWindow == child_window) g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; - child_window->DC.WindowItemStatusFlags = g.LastItemData.StatusFlags; + child_window->DC.ChildItemStatusFlags = g.LastItemData.StatusFlags; //SetLastItemDataForChildWindowItem(child_window, child_window->Rect()); // Not needed, effectively done by ItemAdd() } else diff --git a/imgui_internal.h b/imgui_internal.h index b7b81c2e2..2922993b3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2457,6 +2457,7 @@ struct IMGUI_API ImGuiWindowTempData ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() ImU32 ModalDimBgColor; ImGuiItemStatusFlags WindowItemStatusFlags; + ImGuiItemStatusFlags ChildItemStatusFlags; // Local parameters stacks // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. From 9c4948a4d1a24237a63546de2e79e331bb5722b4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jan 2025 15:41:24 +0100 Subject: [PATCH 0650/2359] TabBar: Internals: added TabItemSpacing(). (#8349, #3291) --- imgui_internal.h | 3 ++ imgui_widgets.cpp | 116 ++++++++++++++++++++++++++++------------------ 2 files changed, 73 insertions(+), 46 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 2922993b3..0b19c63e3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2612,6 +2612,8 @@ enum ImGuiTabItemFlagsPrivate_ ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing, ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) ImGuiTabItemFlags_Button = 1 << 21, // Used by TabItemButton, change the tab item behavior to mimic a button + ImGuiTabItemFlags_Invisible = 1 << 22, // To reserve space e.g. with ImGuiTabItemFlags_Leading + //ImGuiTabItemFlags_Unsorted = 1 << 23, // [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window. }; // Storage for one active tab item (sizeof() 40 bytes) @@ -3378,6 +3380,7 @@ namespace ImGui 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 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 ImVec2 TabItemCalcSize(ImGuiWindow* window); IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ad4820827..22f738660 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9925,7 +9925,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; } - IM_ASSERT(!(flags & ImGuiTabItemFlags_Button)); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! + IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL); if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) @@ -9971,6 +9971,23 @@ 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) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + if (tab_bar == NULL) + { + IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); + return; + } + SetNextItemWidth(width); + 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) { // Layout whole tab bar if not already done @@ -10116,8 +10133,11 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowOverlap); if (g.DragDropActive) button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; - bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + bool hovered, held, pressed; + if (flags & ImGuiTabItemFlags_Invisible) + hovered = held = pressed = false; + else + pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); if (pressed && !is_tab_button) TabBarQueueFocus(tab_bar, tab); @@ -10149,46 +10169,59 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, #endif // Render tab shape - ImDrawList* display_draw_list = window->DrawList; - const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed)); - TabItemBackground(display_draw_list, bb, flags, tab_col); - if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f) + const bool is_visible = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) && !(flags & ImGuiTabItemFlags_Invisible); + if (is_visible) { - // Might be moved to TabItemBackground() ? - ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale); - ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale); - ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline); - if (style.TabRounding > 0.0f) + ImDrawList* display_draw_list = window->DrawList; + const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed)); + TabItemBackground(display_draw_list, bb, flags, tab_col); + if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f) { - float rounding = style.TabRounding; - display_draw_list->PathArcToFast(tl + ImVec2(+rounding, +rounding), rounding, 7, 9); - display_draw_list->PathArcToFast(tr + ImVec2(-rounding, +rounding), rounding, 9, 11); - display_draw_list->PathStroke(overline_col, 0, style.TabBarOverlineSize); + // Might be moved to TabItemBackground() ? + ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale); + ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale); + ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline); + if (style.TabRounding > 0.0f) + { + float rounding = style.TabRounding; + display_draw_list->PathArcToFast(tl + ImVec2(+rounding, +rounding), rounding, 7, 9); + display_draw_list->PathArcToFast(tr + ImVec2(-rounding, +rounding), rounding, 9, 11); + display_draw_list->PathStroke(overline_col, 0, style.TabBarOverlineSize); + } + else + { + display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize); + } } - else + RenderNavCursor(bb, id); + + // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. + const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button) + TabBarQueueFocus(tab_bar, tab); + + if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) + flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; + + // Render tab label, process close button + const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, id) : 0; + bool just_closed; + bool text_clipped; + TabItemLabelAndCloseButton(display_draw_list, bb, tab_just_unsaved ? (flags & ~ImGuiTabItemFlags_UnsavedDocument) : flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped); + if (just_closed && p_open != NULL) { - display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize); + *p_open = false; + TabBarCloseTab(tab_bar, tab); } - } - RenderNavCursor(bb, id); - // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. - const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); - if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button) - TabBarQueueFocus(tab_bar, tab); - - if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) - flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; - - // Render tab label, process close button - const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, id) : 0; - bool just_closed; - bool text_clipped; - TabItemLabelAndCloseButton(display_draw_list, bb, tab_just_unsaved ? (flags & ~ImGuiTabItemFlags_UnsavedDocument) : flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped); - if (just_closed && p_open != NULL) - { - *p_open = false; - TabBarCloseTab(tab_bar, tab); + // Tooltip + // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok) + // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores) + // FIXME: This is a mess. + // 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); } // Restore main window position so user can draw there @@ -10196,15 +10229,6 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, PopClipRect(); window->DC.CursorPos = backup_main_cursor_pos; - // Tooltip - // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok) - // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores) - // FIXME: This is a mess. - // 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); - IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected if (is_tab_button) return pressed; From ea0da0bf4736692cff7dd28eeba6ae3c95daf1aa Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jan 2025 18:04:44 +0100 Subject: [PATCH 0651/2359] Extracted PushPasswordFont() out of InputText code. --- imgui_internal.h | 1 + imgui_widgets.cpp | 31 ++++++++++++++++++------------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 0b19c63e3..667c4ea1f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3018,6 +3018,7 @@ namespace ImGui // Fonts, drawing IMGUI_API void SetCurrentFont(ImFont* font); inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } + IMGUI_API void PushPasswordFont(); inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport); // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport); // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 22f738660..e37a2fb45 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4246,6 +4246,23 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons BufTextLen += new_text_len; } +void ImGui::PushPasswordFont() +{ + ImGuiContext& g = *GImGui; + ImFont* in_font = g.Font; + ImFont* out_font = &g.InputTextPasswordFont; + const ImFontGlyph* glyph = in_font->FindGlyph('*'); + out_font->FontSize = in_font->FontSize; + out_font->Scale = in_font->Scale; + out_font->Ascent = in_font->Ascent; + out_font->Descent = in_font->Descent; + out_font->ContainerAtlas = in_font->ContainerAtlas; + out_font->FallbackGlyph = glyph; + out_font->FallbackAdvanceX = glyph->AdvanceX; + IM_ASSERT(out_font->Glyphs.Size == 0 && out_font->IndexAdvanceX.Size == 0 && out_font->IndexLookup.Size == 0); + PushFont(out_font); +} + // Return false to discard a character. static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard) { @@ -4656,19 +4673,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Password pushes a temporary font with only a fallback glyph if (is_password && !is_displaying_hint) - { - const ImFontGlyph* glyph = g.Font->FindGlyph('*'); - ImFont* password_font = &g.InputTextPasswordFont; - password_font->FontSize = g.Font->FontSize; - password_font->Scale = g.Font->Scale; - password_font->Ascent = g.Font->Ascent; - password_font->Descent = g.Font->Descent; - password_font->ContainerAtlas = g.Font->ContainerAtlas; - password_font->FallbackGlyph = glyph; - password_font->FallbackAdvanceX = glyph->AdvanceX; - IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty()); - PushFont(password_font); - } + PushPasswordFont(); // Process mouse inputs and character inputs if (g.ActiveId == id) From 4230e98720357c5e770e3a078a9e4d09f0923279 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jan 2025 14:39:00 +0100 Subject: [PATCH 0652/2359] Error Handling, Debug Log: IMGUI_DEBUG_LOG_ERROR() doesn't need the extra variable. Amend 236006152 --- imgui_internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 667c4ea1f..ea6479ec3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -229,7 +229,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #endif // Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam. -#define IMGUI_DEBUG_LOG_ERROR(...) do { ImGuiContext& g2 = *GImGui; if (g2.DebugLogFlags & ImGuiDebugLogFlags_EventError) IMGUI_DEBUG_LOG(__VA_ARGS__); else g2.DebugLogSkippedErrors++; } while (0) +#define IMGUI_DEBUG_LOG_ERROR(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventError) IMGUI_DEBUG_LOG(__VA_ARGS__); else g.DebugLogSkippedErrors++; } while (0) #define IMGUI_DEBUG_LOG_ACTIVEID(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventActiveId) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_FOCUS(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFocus) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_POPUP(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) From dfd1bc3c5b35ed9d4203b39e1bdf43d60a061b74 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Jan 2025 19:05:18 +0100 Subject: [PATCH 0653/2359] Tables, Menus: Fixed using BeginTable() in menu layer (any menu bar). (#8355) --- docs/CHANGELOG.txt | 3 +++ imgui_internal.h | 1 + imgui_tables.cpp | 8 +++++--- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e9952a080..be448d16f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,9 @@ Other changes: scrollbar when using thick border sizes. (#8267, #7887) - Windows: Fixed IsItemXXXX() functions not working on append-version of EndChild(). (#8350) Also made some of the fields accessible after BeginChild() to match Begin() logic. +- Tables, Menus: Fixed using BeginTable() in menu layer (any menu bar). (#8355) + It previously overrode the current layer back to main layer, which caused an issue + with MainMenuBar attempted to release focus when leaving the menu layer. - ColorEdit, ColorPicker: Fixed alpha preview broken in 1.91.7. (#8336, #8241). [@PathogenDavid] - Tabs, Style: reworked selected overline rendering to better accommodate for rounded tabs. Reduced default thickness (style.TabBarOverlineSize), diff --git a/imgui_internal.h b/imgui_internal.h index ea6479ec3..d4154daba 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2877,6 +2877,7 @@ struct IMGUI_API ImGuiTable ImGuiTableDrawChannelIdx DummyDrawChannel; // Redirect non-visible columns here. ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; // For Selectable() and other widgets drawing across columns after the freezing line. Index within DrawSplitter.Channels[] ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen; + ImS8 NavLayer; // ImGuiNavLayer at the time of BeginTable(). bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). bool IsInitializing; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e0df575c4..d5e952d8f 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -374,6 +374,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->ColumnsCount = columns_count; table->IsLayoutLocked = false; table->InnerWidth = inner_width; + table->NavLayer = (ImS8)outer_window->DC.NavLayerCurrent; temp_data->UserOuterSize = outer_size; // Instance data (for instance 0, TableID == TableInstanceID) @@ -1050,7 +1051,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; - column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main); // Use Count NOT request so Header line changes layer when frozen + // Initial nav layer: using FreezeRowsCount, NOT FreezeRowsRequest, so Header line changes layer when frozen + column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : table->NavLayer); if (offset_x_frozen && table->FreezeColumnsCount == visible_n) { @@ -1493,7 +1495,7 @@ void ImGui::EndTable() if (inner_window != outer_window) { short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask; - inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently. + inner_window->DC.NavLayersActiveMask |= 1 << table->NavLayer; // So empty table don't appear to navigate differently. g.CurrentTable = NULL; // To avoid error recovery recursing EndChild(); g.CurrentTable = table; @@ -2032,7 +2034,7 @@ void ImGui::TableEndRow(ImGuiTable* table) if (unfreeze_rows_request) { for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - table->Columns[column_n].NavLayerCurrent = ImGuiNavLayer_Main; + table->Columns[column_n].NavLayerCurrent = table->NavLayer; const float y0 = ImMax(table->RowPosY2 + 1, table->InnerClipRect.Min.y); table_instance->LastFrozenHeight = y0 - table->OuterRect.Min.y; From a71191515ac29725ee2aa94b6f5d59cc9ffa108c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Jan 2025 19:07:28 +0100 Subject: [PATCH 0654/2359] EndMainMenuBar doesn't attempt to restore focus when there's an active id. (#8355) I don't have a specific issue in mind but it seems sane to add that test. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e37a2fb45..f772f309c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8769,7 +8769,7 @@ void ImGui::EndMainMenuBar() // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window // FIXME: With this strategy we won't be able to restore a NULL focus. ImGuiContext& g = *GImGui; - if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest) + if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest && g.ActiveId == 0) FocusTopMostWindowUnderOne(g.NavWindow, NULL, NULL, ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild); End(); From dabc99018915a534d11d22abc65a6f4d6898d2d4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Jan 2025 19:59:41 +0100 Subject: [PATCH 0655/2359] Rename internal id for standardizing naming convention. "##menubar" -> "##MenuBar", "###NavWindowingList" -> "###NavWindowingOverlay" "###NavUpdateWindowing" one should have zero side effect on anyone. --- imgui.cpp | 6 +++--- imgui.h | 2 +- imgui_widgets.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e4c2f2a2e..5223ed76c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13649,7 +13649,7 @@ static void ImGui::NavUpdateWindowing() // Start CTRL+Tab or Square+L/R window selection // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab) - const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing"); + const ImGuiID owner_id = ImHashStr("##NavUpdateWindowing"); const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); @@ -13849,12 +13849,12 @@ void ImGui::NavUpdateWindowingOverlay() return; if (g.NavWindowingListWindow == NULL) - g.NavWindowingListWindow = FindWindowByName("###NavWindowingList"); + g.NavWindowingListWindow = FindWindowByName("##NavWindowingOverlay"); const ImGuiViewport* viewport = GetMainViewport(); SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); - Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); + Begin("##NavWindowingOverlay", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); if (g.ContextName[0] != 0) SeparatorText(g.ContextName); for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--) diff --git a/imgui.h b/imgui.h index 8e240b390..7d2f33334 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.8 WIP" -#define IMGUI_VERSION_NUM 19173 +#define IMGUI_VERSION_NUM 19174 #define IMGUI_HAS_TABLE /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f772f309c..dccb7a535 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8630,7 +8630,7 @@ bool ImGui::BeginMenuBar() IM_ASSERT(!window->DC.MenuBarAppending); BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore - PushID("##menubar"); + PushID("##MenuBar"); // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy. From c0308da665dd1553955ba340a82e0b969631c1ad Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Jan 2025 20:13:22 +0100 Subject: [PATCH 0656/2359] Fixed zealous GCC warning. (#8355) Amend dfd1bc3 --- imgui_tables.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index d5e952d8f..5411e8a1b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1052,7 +1052,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; // Initial nav layer: using FreezeRowsCount, NOT FreezeRowsRequest, so Header line changes layer when frozen - column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : table->NavLayer); + column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : (ImGuiNavLayer)table->NavLayer); if (offset_x_frozen && table->FreezeColumnsCount == visible_n) { From fa178f42350598f853f2ec36b5aeb231e0e08c75 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jan 2025 14:30:14 +0100 Subject: [PATCH 0657/2359] Error Handling: Recovery from missing EndMenuBar() call. (#1651) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 5 +++++ imgui_widgets.cpp | 9 +++++---- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index be448d16f..99333efda 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,7 @@ Other changes: scrollbar when using thick border sizes. (#8267, #7887) - Windows: Fixed IsItemXXXX() functions not working on append-version of EndChild(). (#8350) Also made some of the fields accessible after BeginChild() to match Begin() logic. +- Error Handling: Recovery from missing EndMenuBar() call. (#1651) - Tables, Menus: Fixed using BeginTable() in menu layer (any menu bar). (#8355) It previously overrode the current layer back to main layer, which caused an issue with MainMenuBar attempted to release focus when leaving the menu layer. diff --git a/imgui.cpp b/imgui.cpp index 5223ed76c..dffd37b45 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10301,6 +10301,11 @@ void ImGui::ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryStat IM_ASSERT_USER_ERROR(0, "Missing EndMultiSelect()"); EndMultiSelect(); } + if (window->DC.MenuBarAppending) //-V1044 + { + IM_ASSERT_USER_ERROR(0, "Missing EndMenuBar()"); + EndMenuBar(); + } while (window->DC.TreeDepth > state_in->SizeOfTreeStack) //-V1044 { IM_ASSERT_USER_ERROR(0, "Missing TreePop()"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index dccb7a535..9335da9fd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8657,6 +8657,10 @@ void ImGui::EndMenuBar() return; ImGuiContext& g = *GImGui; + IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'" + IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); + IM_ASSERT(window->DC.MenuBarAppending); + // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) { @@ -8683,9 +8687,6 @@ void ImGui::EndMenuBar() } } - IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'" - IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); - IM_ASSERT(window->DC.MenuBarAppending); PopClipRect(); PopID(); window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->Pos.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos. @@ -8764,11 +8765,11 @@ bool ImGui::BeginMainMenuBar() void ImGui::EndMainMenuBar() { + ImGuiContext& g = *GImGui; EndMenuBar(); // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window // FIXME: With this strategy we won't be able to restore a NULL focus. - ImGuiContext& g = *GImGui; if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest && g.ActiveId == 0) FocusTopMostWindowUnderOne(g.NavWindow, NULL, NULL, ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild); From ae6cfd32a0372f5ac4bec3ae304e78746d7fca23 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jan 2025 14:34:05 +0100 Subject: [PATCH 0658/2359] Tables, Menus: Fixed tables or child windows submitted inside BeginMainMenuBar() being unable to save their settings. (#8356) Amend error handling (fa178f4) to avoid us setting ImGuiWindowFlags_NoSavedSettings on the wrong window. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 19 +++++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 99333efda..c07fcf766 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -75,6 +75,8 @@ Other changes: - Tables, Menus: Fixed using BeginTable() in menu layer (any menu bar). (#8355) It previously overrode the current layer back to main layer, which caused an issue with MainMenuBar attempted to release focus when leaving the menu layer. +- Tables, Menus: Fixed tables or child windows submitted inside BeginMainMenuBar() + being unable to save their settings, as the main menu bar uses _NoSavedSettings. (#8356) - ColorEdit, ColorPicker: Fixed alpha preview broken in 1.91.7. (#8336, #8241). [@PathogenDavid] - Tabs, Style: reworked selected overline rendering to better accommodate for rounded tabs. Reduced default thickness (style.TabBarOverlineSize), diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9335da9fd..0981b447e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8755,18 +8755,29 @@ bool ImGui::BeginMainMenuBar() float height = GetFrameHeight(); bool is_open = BeginViewportSideBar("##MainMenuBar", viewport, ImGuiDir_Up, height, window_flags); g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f); - - if (is_open) - BeginMenuBar(); - else + if (!is_open) + { End(); + return false; + } + + // Temporarily disable _NoSavedSettings, in the off-chance that tables or child windows submitted within the menu-bar may want to use settings. (#8356) + g.CurrentWindow->Flags &= ~ImGuiWindowFlags_NoSavedSettings; + BeginMenuBar(); return is_open; } void ImGui::EndMainMenuBar() { ImGuiContext& g = *GImGui; + if (!g.CurrentWindow->DC.MenuBarAppending) + { + IM_ASSERT_USER_ERROR(0, "Calling EndMainMenuBar() not from a menu-bar!"); // Not technically testing that it is the main menu bar + return; + } + EndMenuBar(); + g.CurrentWindow->Flags |= ImGuiWindowFlags_NoSavedSettings; // Restore _NoSavedSettings (#8356) // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window // FIXME: With this strategy we won't be able to restore a NULL focus. From e6c5296f30a5111fa1dc926d2c15abd0f809fbb1 Mon Sep 17 00:00:00 2001 From: Konstantin Podsvirov Date: Fri, 31 Jan 2025 16:11:33 +0300 Subject: [PATCH 0659/2359] Examples: SDL3: Fix for Emscripten platform (#8363) --- examples/example_sdl3_opengl3/main.cpp | 1 - examples/example_sdl3_sdlrenderer3/main.cpp | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 5520a7da9..8cd54bd4e 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -18,7 +18,6 @@ #include #endif -// This example doesn't compile with Emscripten yet! Awaiting SDL3 support. #ifdef __EMSCRIPTEN__ #include "../libs/emscripten/emscripten_mainloop_stub.h" #endif diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 4b9b86e9b..483350fcb 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -21,6 +21,10 @@ #include #endif +#ifdef __EMSCRIPTEN__ +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#endif + // Main code int main(int, char**) { From dbb5eeaadffb6a3ba6a60de1290312e5802dba5a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jan 2025 15:57:48 +0100 Subject: [PATCH 0660/2359] Version 1.91.8 --- docs/CHANGELOG.txt | 11 ++++++----- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 15 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c07fcf766..eaedb9c1b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,12 +36,15 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.91.8 WIP (In Progress) + VERSION 1.91.8 (Released 2025-01-31) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.8 + Breaking changes: -- ColorEdit, ColorPicker: redesigned how alpha is displayed in the preview square. (#8335, #1578, #346) +- ColorEdit, ColorPicker: redesigned how alpha is displayed in the preview + square. (#8335, #1578, #346) - Removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. - Prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. - We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. @@ -63,7 +66,7 @@ Other changes: by introducing a delay. This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single-click on an icon triggers a rename. Generally use with 'delay >= io.MouseDoubleClickTime' + combine with a - 'io.MouseClickedLastCount == 1' check. + 'GetMouseClickedCount() == 1' check. - Windows: legacy SetWindowFontScale() is properly inherited by nested child windows. Note that an upcoming major release should make this obsolete, but in the meanwhile it works better now. (#2701, #8138, #1018) @@ -81,7 +84,6 @@ Other changes: - Tabs, Style: reworked selected overline rendering to better accommodate for rounded tabs. Reduced default thickness (style.TabBarOverlineSize), increased default rounding (style.TabRounding). (#8334) [@Kian738, @ocornut] - styles as the current look is not right (but ImGuiCol_TabSelectedOverline stays the same). - Debug Tools: Tweaked font preview. - ImDrawList: texture baked storage for thick line reduced from ~64x64 to ~32x32. (#3245) - Fonts: IndexLookup[] table hold 16-bit values even in ImWchar32 mode, @@ -90,7 +92,6 @@ Other changes: - Fonts: OversampleH/OversampleV defaults to 0 for automatic selection. - OversampleH == 0 --> use 1 or 2 depending on font size and use of PixelSnapH. - OversampleV == 0 --> always use 1. - This also - ImFontAtlas: made calling ClearFonts() call ClearInputData(), as calling one without the other is never correct. (#8174, #6556, #6336, #4723) - Examples: DirectX12: Reduced number of frame in flight from 3 to 2 in diff --git a/imgui.cpp b/imgui.cpp index dffd37b45..5ca57dfc6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 WIP +// dear imgui, v1.91.8 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 7d2f33334..7b037a584 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 WIP +// dear imgui, v1.91.8 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.8 WIP" -#define IMGUI_VERSION_NUM 19174 +#define IMGUI_VERSION "1.91.8" +#define IMGUI_VERSION_NUM 19180 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 43344f3fc..03ce4710a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 WIP +// dear imgui, v1.91.8 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4b59d6775..e426f0e5d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 WIP +// dear imgui, v1.91.8 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index d4154daba..af52d0fea 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 WIP +// dear imgui, v1.91.8 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 5411e8a1b..e7a3b8e8d 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 WIP +// dear imgui, v1.91.8 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0981b447e..1e4297fcb 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 WIP +// dear imgui, v1.91.8 // (widgets code) /* From e2a99b57605982c50f2df4fefaf0767aadde9cd8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jan 2025 18:26:52 +0100 Subject: [PATCH 0661/2359] Internals: renamed GetIOEx() to GetIO(). Added GetPlatformIO() explicit context variant. --- imgui.cpp | 9 ++++++++- imgui_internal.h | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5ca57dfc6..7d4da4550 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4814,7 +4814,7 @@ ImGuiIO& ImGui::GetIO() } // This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856) -ImGuiIO& ImGui::GetIOEx(ImGuiContext* ctx) +ImGuiIO& ImGui::GetIO(ImGuiContext* ctx) { IM_ASSERT(ctx != NULL); return ctx->IO; @@ -4826,6 +4826,13 @@ ImGuiPlatformIO& ImGui::GetPlatformIO() return GImGui->PlatformIO; } +// This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856) +ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx) +{ + IM_ASSERT(ctx != NULL; + return ctx->PlatformIO; +} + // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { diff --git a/imgui_internal.h b/imgui_internal.h index af52d0fea..2d2ea02df 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2980,7 +2980,8 @@ namespace ImGui // If this ever crashes because g.CurrentWindow is NULL, it means that either: // - ImGui::NewFrame() has never been called, which is illegal. // - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. - IMGUI_API ImGuiIO& GetIOEx(ImGuiContext* ctx); + IMGUI_API ImGuiIO& GetIO(ImGuiContext* ctx); + IMGUI_API ImGuiPlatformIO& GetPlatformIO(ImGuiContext* ctx); 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); From e4db4e423d78bce7e6c050f1f0710b3b635a9871 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jan 2025 19:50:18 +0100 Subject: [PATCH 0662/2359] Internals: renamed GetIOEx() to GetIO(). Added GetPlatformIO() explicit context variant. - OOPS --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 7d4da4550..88f508851 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4829,7 +4829,7 @@ ImGuiPlatformIO& ImGui::GetPlatformIO() // This variant exists to facilitate backends experimenting with multi-threaded parallel context. (#8069, #6293, #5856) ImGuiPlatformIO& ImGui::GetPlatformIO(ImGuiContext* ctx) { - IM_ASSERT(ctx != NULL; + IM_ASSERT(ctx != NULL); return ctx->PlatformIO; } From f820bf7cd4bd92cfbe5bbd3bab51e7cb81442e53 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 12:33:40 +0100 Subject: [PATCH 0663/2359] Version 1.91.9 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index eaedb9c1b..296c4202d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.91.9 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking changes: + +Other changes: + + ----------------------------------------------------------------------- VERSION 1.91.8 (Released 2025-01-31) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 88f508851..09c5175a3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 +// dear imgui, v1.91.9 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 7b037a584..9b1a8323d 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 +// dear imgui, v1.91.9 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.8" -#define IMGUI_VERSION_NUM 19180 +#define IMGUI_VERSION "1.91.9 WIP" +#define IMGUI_VERSION_NUM 19181 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 03ce4710a..530ed6cc4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 +// dear imgui, v1.91.9 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e426f0e5d..3fa5adae1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 +// dear imgui, v1.91.9 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 2d2ea02df..d59c19c60 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 +// dear imgui, v1.91.9 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e7a3b8e8d..71d1e7d8b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 +// dear imgui, v1.91.9 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1e4297fcb..1ddaf71be 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.8 +// dear imgui, v1.91.9 WIP // (widgets code) /* From 626533999502662a9f507b34d9ae0d8579d55a95 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 14:01:48 +0100 Subject: [PATCH 0664/2359] Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), RadioButton(), Selectable(). (#8370) Item is already made inactive at the time of calling MarkItemEdited(). Fix a604d4f71 --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 +++ 2 files changed, 6 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 296c4202d..10dc36bb8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), Selectable(). (#8370) + Regression from 2025/01/13. + ----------------------------------------------------------------------- VERSION 1.91.8 (Released 2025-01-31) diff --git a/imgui.cpp b/imgui.cpp index 09c5175a3..5f0ca9d81 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4440,8 +4440,11 @@ void ImGui::MarkItemEdited(ImGuiID id) return; if (g.ActiveId == id || g.ActiveId == 0) { + // FIXME: Can't we fully rely on LastItemData yet? g.ActiveIdHasBeenEditedThisFrame = true; g.ActiveIdHasBeenEditedBefore = true; + if (g.DeactivatedItemData.ID == id) + g.DeactivatedItemData.HasBeenEditedBefore = true; } // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343) From 204cebc8fc5678c446037f232945bde58003fa76 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 14:21:53 +0100 Subject: [PATCH 0665/2359] Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] --- backends/imgui_impl_metal.mm | 4 ++-- docs/CHANGELOG.txt | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 1e0c47f52..5df9176a0 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -311,11 +311,11 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); } - __block MetalContext* sharedMetalContext = bd->SharedMetalContext; + MetalContext* sharedMetalContext = bd->SharedMetalContext; [commandBuffer addCompletedHandler:^(id) { dispatch_async(dispatch_get_main_queue(), ^{ - @synchronized(bd->SharedMetalContext.bufferCache) + @synchronized(sharedMetalContext.bufferCache) { [sharedMetalContext.bufferCache addObject:vertexBuffer]; [sharedMetalContext.bufferCache addObject:indexBuffer]; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 10dc36bb8..935d453ab 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,9 +43,9 @@ Breaking changes: Other changes: -- Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), Selectable(). (#8370) - Regression from 2025/01/13. - +- Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), + RadioButton(), Selectable(). Regression from 2025/01/13. (#8370) +- Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] ----------------------------------------------------------------------- VERSION 1.91.8 (Released 2025-01-31) From 5dd84082ab333453e50f08ba4dc9ebf0d8860254 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 15:11:03 +0100 Subject: [PATCH 0666/2359] InputTextWithHint(): Fixed buffer overflow when user callback modifies the buffer contents in a way that alters hint visibility. (#8368) --- backends/imgui_impl_metal.mm | 1 + docs/CHANGELOG.txt | 3 +++ imgui.cpp | 1 + imgui_widgets.cpp | 14 +++++++++++++- 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 5df9176a0..1cd2308d1 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-03: Metal: Crash fix. (#8367) // 2024-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419). // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. // 2022-07-05: Metal: Add dispatch synchronization. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 935d453ab..e472ffcf2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,9 @@ Other changes: - Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), RadioButton(), Selectable(). Regression from 2025/01/13. (#8370) +- InputTextWithHint(): Fixed buffer-overflow (luckily often with no visible effect) + when a user callback modified the buffer contents in a way that altered the + visibility of the preview/hint buffer. (#8368) [@m9710797, @ocornut] - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 5f0ca9d81..8f99608b2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2012,6 +2012,7 @@ const char* ImStreolRange(const char* str, const char* str_end) const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line { + IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + strlen(buf_begin)); while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') buf_mid_line--; return buf_mid_line; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1ddaf71be..be015a6f4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4669,7 +4669,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; - const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); + bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); // Password pushes a temporary font with only a fallback glyph if (is_password && !is_displaying_hint) @@ -5151,6 +5151,18 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const int buf_display_max_length = 2 * 1024 * 1024; const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595 const char* buf_display_end = NULL; // We have specialized paths below for setting the length + + // 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); + if (new_is_displaying_hint != is_displaying_hint) + { + if (is_password && !is_displaying_hint) + PopFont(); + is_displaying_hint = new_is_displaying_hint; + if (is_password && !is_displaying_hint) + PushPasswordFont(); + } if (is_displaying_hint) { buf_display = hint; From da0ba9e2fef6a60bae033580499a74e2764ce635 Mon Sep 17 00:00:00 2001 From: PhantomCloak Date: Sun, 2 Feb 2025 19:25:09 +0300 Subject: [PATCH 0667/2359] Backends: WebGPU: add type alias for dawn WGPUProgrammableStageDescriptor -> WGPUComputeState. (#8369) --- backends/imgui_impl_wgpu.cpp | 6 ++++++ docs/CHANGELOG.txt | 2 ++ 2 files changed, 8 insertions(+) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 2f34c0e0b..84de56df2 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -58,6 +58,12 @@ #include #include +#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN +// Dawn renamed WGPUProgrammableStageDescriptor to WGPUComputeState (see: https://github.com/webgpu-native/webgpu-headers/pull/413) +// Using type alias until WGPU adopts the same naming convention (#8369) +using WGPUProgrammableStageDescriptor = WGPUComputeState; +#endif + // Dear ImGui prototypes from imgui_internal.h extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0); #define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro). diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e472ffcf2..bf4037020 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other changes: when a user callback modified the buffer contents in a way that altered the visibility of the preview/hint buffer. (#8368) [@m9710797, @ocornut] - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] +- Backends: WebGPU: Fix for DAWN API rename WGPUProgrammableStageDescriptor -> WGPUComputeState. + [@PhantomCloak] (#8369) ----------------------------------------------------------------------- VERSION 1.91.8 (Released 2025-01-31) From de962e83d0095a0676a42da184cad8e4066669a9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 17:50:12 +0100 Subject: [PATCH 0668/2359] ImFont: remove SetGlyphVisible() Which was never marked public. Added by d284a6cff. (#2149, #515) Making room by removing stuff that are inconvenient to implement in our scaling system. If you were using this function please post an issue to report it. --- imgui.h | 1 - imgui_draw.cpp | 12 ++++-------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index 9b1a8323d..f80e9d255 100644 --- a/imgui.h +++ b/imgui.h @@ -3498,7 +3498,6 @@ struct ImFont IMGUI_API void GrowIndex(int new_size); IMGUI_API void AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. - IMGUI_API void SetGlyphVisible(ImWchar c, bool visible); IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3fa5adae1..c66f52cd4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3770,8 +3770,10 @@ void ImFont::BuildLookupTable() } // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons) - SetGlyphVisible((ImWchar)' ', false); - SetGlyphVisible((ImWchar)'\t', false); + if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)' ')) + glyph->Visible = false; + if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)'\t')) + glyph->Visible = false; // Setup Fallback character const ImWchar fallback_chars[] = { (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; @@ -3827,12 +3829,6 @@ bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) return true; } -void ImFont::SetGlyphVisible(ImWchar c, bool visible) -{ - if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)c)) - glyph->Visible = visible ? 1 : 0; -} - void ImFont::GrowIndex(int new_size) { IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); From 1a31e31ae92db10431a35bc5fbb5465848659e9a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 17:55:35 +0100 Subject: [PATCH 0669/2359] (Breaking) Fonts: removed ImFontConfig::GlyphExtraSpacing option which seems largely obsolete and unused. (#242) --- docs/CHANGELOG.txt | 3 +++ docs/FONTS.md | 2 +- imgui.cpp | 1 + imgui.h | 6 +++--- imgui_draw.cpp | 5 +---- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bf4037020..72f0ed126 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ HOW TO UPDATE? Breaking changes: +- Removed ImFontConfig::GlyphExtraSpacing option which seems largely obsolete and + unused. If you were using this please report it! (#242). + Other changes: - Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), diff --git a/docs/FONTS.md b/docs/FONTS.md index e36afdf81..e9fbcbe42 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -110,7 +110,7 @@ ImGui::PopFont(); **For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** ```cpp ImFontConfig config; -config.GlyphExtraSpacing.x = 1.0f; +config.RasterizerDensity = 2.0f; ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); ``` diff --git a/imgui.cpp b/imgui.cpp index 8f99608b2..3a7e60005 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,6 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/02/03 (1.91.9) - removed ImFontConfig::GlyphExtraSpacing option which seems largely obsolete and unused. If you were using this please report it! - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls: diff --git a/imgui.h b/imgui.h index f80e9d255..f6bfa4e5d 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.9 WIP" -#define IMGUI_VERSION_NUM 19181 +#define IMGUI_VERSION_NUM 19182 #define IMGUI_HAS_TABLE /* @@ -3257,7 +3257,7 @@ struct ImFontConfig int OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. int OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). - ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. + //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font @@ -3281,7 +3281,7 @@ struct ImFontGlyph unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. unsigned int Codepoint : 30; // 0x0000..0x10FFFF - float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in) + float AdvanceX; // Horizontal distance to advance layout with float X0, Y0, X1, Y1; // Glyph corners float U0, V0, U1, V1; // Texture coordinates }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c66f52cd4..78fa4c1ea 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3349,7 +3349,7 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) if (r->Font == NULL || r->GlyphID == 0) continue; - // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, GlyphExtraSpacing, PixelSnapH + // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, PixelSnapH IM_ASSERT(r->Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; atlas->CalcCustomRectUV(r, &uv0, &uv1); @@ -3858,9 +3858,6 @@ void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, floa // Snap to pixel if (cfg->PixelSnapH) advance_x = IM_ROUND(advance_x); - - // Bake spacing - advance_x += cfg->GlyphExtraSpacing.x; } int glyph_idx = Glyphs.Size; From 2d20e13746c05bfe36d4a57ac465e7a9fe9005d9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 4 Feb 2025 20:19:57 +0100 Subject: [PATCH 0670/2359] Backends: GLFW: Added comment about io.AddMouseSourceEvent() not being properly called. (#8374) --- backends/imgui_impl_glfw.cpp | 2 ++ backends/imgui_impl_glfw.h | 2 ++ 2 files changed, 4 insertions(+) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 01a6a5566..66183561f 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -9,6 +9,8 @@ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// Missing features or Issues: +// [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index 53a22415d..bba6d09ea 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -8,6 +8,8 @@ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// Missing features or Issues: +// [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. From cfed18afc79c1bdea142cccd74639734edbfbaf6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Feb 2025 12:34:37 +0100 Subject: [PATCH 0671/2359] Add ImFontConfig::GlyphExtraAdvanceX as a replacement for GlyphExtraSpacing.x (#242) Partly restore 1a31e31. --- docs/CHANGELOG.txt | 3 +-- imgui.cpp | 2 +- imgui.h | 5 +++-- imgui_draw.cpp | 3 +++ 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 72f0ed126..a81ef2038 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,8 +41,7 @@ HOW TO UPDATE? Breaking changes: -- Removed ImFontConfig::GlyphExtraSpacing option which seems largely obsolete and - unused. If you were using this please report it! (#242). +- Renamed ImFontConfig::GlyphExtraSpacing.x option to GlyphExtraAdvanceX. (#242) Other changes: diff --git a/imgui.cpp b/imgui.cpp index 3a7e60005..4de75457d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -430,7 +430,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - - 2025/02/03 (1.91.9) - removed ImFontConfig::GlyphExtraSpacing option which seems largely obsolete and unused. If you were using this please report it! + - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX. - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. the new flags (ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg + existing ImGuiColorEditFlags_AlphaPreviewHalf) may be combined better and allow finer controls: diff --git a/imgui.h b/imgui.h index f6bfa4e5d..a3f660366 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.9 WIP" -#define IMGUI_VERSION_NUM 19182 +#define IMGUI_VERSION_NUM 19183 #define IMGUI_HAS_TABLE /* @@ -3257,11 +3257,12 @@ struct ImFontConfig int OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. int OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). - //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. + //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED IN 1.91.9: use GlyphExtraAdvanceX) ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs + float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. float RasterizerDensity; // 1.0f // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display. IMPORTANT: If you increase this it is expected that you increase font scale accordingly, otherwise quality may look lowered. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 78fa4c1ea..ed5164bb7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3858,6 +3858,9 @@ void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, floa // Snap to pixel if (cfg->PixelSnapH) advance_x = IM_ROUND(advance_x); + + // Bake extra spacing + advance_x += cfg->GlyphExtraAdvanceX; } int glyph_idx = Glyphs.Size; From 0625b37760215f2b890e8605e7070bb8c9521a22 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Feb 2025 18:37:32 +0100 Subject: [PATCH 0672/2359] Scrollbar: Rework logic that fades-out scrollbar when it becomes too small. Amend 0236bc246f --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a81ef2038..7977ef681 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Other changes: - InputTextWithHint(): Fixed buffer-overflow (luckily often with no visible effect) when a user callback modified the buffer contents in a way that altered the visibility of the preview/hint buffer. (#8368) [@m9710797, @ocornut] +- Scrollbar: Rework logic that fades-out scrollbar when it becomes too small, + which amusingly made it disappear when using very big font/frame size. - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] - Backends: WebGPU: Fix for DAWN API rename WGPUProgrammableStageDescriptor -> WGPUComputeState. [@PhantomCloak] (#8369) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index be015a6f4..612ff62a6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -971,8 +971,8 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the window resize grab) float alpha = 1.0f; - if ((axis == ImGuiAxis_Y) && bb_frame_height < g.FontSize + g.Style.FramePadding.y * 2.0f) - alpha = ImSaturate((bb_frame_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f)); + if ((axis == ImGuiAxis_Y) && bb_frame_height < bb_frame_width) + alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0f, 1.0f)); if (alpha <= 0.0f) return false; @@ -989,7 +989,8 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 // But we maintain a minimum size in pixel to allow for the user to still aim inside. IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. const ImS64 win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), (ImS64)1); - const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_visible_v / (float)win_size_v), style.GrabMinSize, scrollbar_size_v); + const float grab_h_minsize = ImMin(bb.GetSize()[axis], style.GrabMinSize); + const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_visible_v / (float)win_size_v), grab_h_minsize, scrollbar_size_v); const float grab_h_norm = grab_h_pixels / scrollbar_size_v; // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). From 4f1d3809c32b0dd8745273bf7e22b4aa37494ce8 Mon Sep 17 00:00:00 2001 From: fdsa <14tanks999@gmail.com> Date: Wed, 5 Feb 2025 18:41:03 -0800 Subject: [PATCH 0673/2359] Fixed tabs and spaces (#8377) --- .github/ISSUE_TEMPLATE/issue_template.yml | 2 +- backends/imgui_impl_glfw.cpp | 2 +- backends/imgui_impl_glut.cpp | 2 +- backends/imgui_impl_sdlrenderer2.cpp | 34 +++++++++---------- backends/imgui_impl_sdlrenderer3.cpp | 34 +++++++++---------- backends/imgui_impl_wgpu.cpp | 8 ++--- backends/imgui_impl_win32.cpp | 30 ++++++++-------- docs/CONTRIBUTING.md | 10 +++--- docs/FAQ.md | 2 +- docs/TODO.txt | 2 +- examples/example_allegro5/README.md | 6 ++-- .../project.pbxproj | 12 +++---- examples/example_apple_metal/main.mm | 4 +-- examples/example_sdl3_opengl3/Makefile | 8 ++--- examples/example_sdl3_sdlgpu3/Makefile | 8 ++--- examples/example_sdl3_sdlrenderer3/Makefile | 8 ++--- .../example_win32_opengl3/build_mingw.bat | 2 +- imgui.h | 2 +- imgui_demo.cpp | 18 +++++----- misc/freetype/README.md | 2 +- misc/freetype/imgui_freetype.cpp | 10 +++--- 21 files changed, 103 insertions(+), 103 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/issue_template.yml b/.github/ISSUE_TEMPLATE/issue_template.yml index c1b57de4b..46ed826d5 100644 --- a/.github/ISSUE_TEMPLATE/issue_template.yml +++ b/.github/ISSUE_TEMPLATE/issue_template.yml @@ -8,7 +8,7 @@ body: For anything else: **we are happy to use 'GitHub Issues' for many types of open-ended questions**. We are encouraging 'Issues' becoming a large, centralized, tagged, cross-referenced database of Dear ImGui contents. Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users. - + **If you are using Dear ImGui as part of a job that you are being well-paid for** and your company is not a sponsor. Please be mindful that this is a Free Software and you might be about to ask volunteers to help you doing your job. Please put extra effort describing your issue or question properly. If your company is wealthy, please read [Funding](https://github.com/ocornut/imgui/wiki/Funding) and consider getting in touch. - type: markdown attributes: diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 66183561f..454a36d36 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -469,7 +469,7 @@ void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c) void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int) { - // Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too. + // Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too. } #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 diff --git a/backends/imgui_impl_glut.cpp b/backends/imgui_impl_glut.cpp index ef7f17922..a68f9dbc8 100644 --- a/backends/imgui_impl_glut.cpp +++ b/backends/imgui_impl_glut.cpp @@ -50,7 +50,7 @@ static int g_Time = 0; // Current time, in milliseconds -// Glut has 1 function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above. +// Glut has one function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above. static ImGuiKey ImGui_ImplGLUT_KeyToImGuiKey(int key) { switch (key) diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index 8245854c2..bfaeb9138 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -100,10 +100,10 @@ void ImGui_ImplSDLRenderer2_Shutdown() static void ImGui_ImplSDLRenderer2_SetupRenderState(SDL_Renderer* renderer) { - // Clear out any viewports and cliprect set by the user + // Clear out any viewports and cliprect set by the user // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. - SDL_RenderSetViewport(renderer, nullptr); - SDL_RenderSetClipRect(renderer, nullptr); + SDL_RenderSetViewport(renderer, nullptr); + SDL_RenderSetClipRect(renderer, nullptr); } void ImGui_ImplSDLRenderer2_NewFrame() @@ -117,21 +117,21 @@ void ImGui_ImplSDLRenderer2_NewFrame() void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer) { - // If there's a scale factor set by the user, use that instead + // If there's a scale factor set by the user, use that instead // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. float rsx = 1.0f; - float rsy = 1.0f; - SDL_RenderGetScale(renderer, &rsx, &rsy); + float rsy = 1.0f; + SDL_RenderGetScale(renderer, &rsx, &rsy); ImVec2 render_scale; - render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; - render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; + render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; + render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; - // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); - int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); - if (fb_width == 0 || fb_height == 0) - return; + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); + int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); + if (fb_width == 0 || fb_height == 0) + return; // Backup SDL_Renderer state that will be modified to restore it afterwards struct BackupSDLRendererState @@ -154,9 +154,9 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* render_state.Renderer = renderer; platform_io.Renderer_RenderState = &render_state; - // Will project scissor/clipping rectangles into framebuffer space - ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports - ImVec2 clip_scale = render_scale; + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = render_scale; // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) @@ -201,7 +201,7 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* #endif // Bind texture, Draw - SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); + SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); SDL_RenderGeometryRaw(renderer, tex, xy, (int)sizeof(ImDrawVert), color, (int)sizeof(ImDrawVert), diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 99253d964..42fefa0cd 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -99,10 +99,10 @@ void ImGui_ImplSDLRenderer3_Shutdown() static void ImGui_ImplSDLRenderer3_SetupRenderState(SDL_Renderer* renderer) { - // Clear out any viewports and cliprect set by the user + // Clear out any viewports and cliprect set by the user // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. - SDL_SetRenderViewport(renderer, nullptr); - SDL_SetRenderClipRect(renderer, nullptr); + SDL_SetRenderViewport(renderer, nullptr); + SDL_SetRenderClipRect(renderer, nullptr); } void ImGui_ImplSDLRenderer3_NewFrame() @@ -136,21 +136,21 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* { ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); - // If there's a scale factor set by the user, use that instead + // If there's a scale factor set by the user, use that instead // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. float rsx = 1.0f; - float rsy = 1.0f; - SDL_GetRenderScale(renderer, &rsx, &rsy); + float rsy = 1.0f; + SDL_GetRenderScale(renderer, &rsx, &rsy); ImVec2 render_scale; - render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; - render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; + render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; + render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; - // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); - int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); - if (fb_width == 0 || fb_height == 0) - return; + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); + int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); + if (fb_width == 0 || fb_height == 0) + return; // Backup SDL_Renderer state that will be modified to restore it afterwards struct BackupSDLRendererState @@ -175,9 +175,9 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* render_state.Renderer = renderer; platform_io.Renderer_RenderState = &render_state; - // Will project scissor/clipping rectangles into framebuffer space - ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports - ImVec2 clip_scale = render_scale; + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = render_scale; // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) @@ -218,7 +218,7 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+ // Bind texture, Draw - SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); + SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); SDL_RenderGeometryRaw8BitColor(renderer, bd->ColorBuffer, tex, xy, (int)sizeof(ImDrawVert), color, (int)sizeof(ImDrawVert), diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 84de56df2..a81662d84 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -268,13 +268,13 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN - WGPUShaderSourceWGSL wgsl_desc = {}; + WGPUShaderSourceWGSL wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL; - wgsl_desc.code = { wgsl_source, WGPU_STRLEN }; + wgsl_desc.code = { wgsl_source, WGPU_STRLEN }; #else - WGPUShaderModuleWGSLDescriptor wgsl_desc = {}; + WGPUShaderModuleWGSLDescriptor wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor; - wgsl_desc.code = wgsl_source; + wgsl_desc.code = wgsl_source; #endif WGPUShaderModuleDescriptor desc = {}; diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index f1cf6eccc..03ab53523 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -790,9 +790,9 @@ static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD) { typedef LONG(WINAPI* PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG); static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = nullptr; - if (RtlVerifyVersionInfoFn == nullptr) - if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll")) - RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo"); + if (RtlVerifyVersionInfoFn == nullptr) + if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll")) + RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo"); if (RtlVerifyVersionInfoFn == nullptr) return FALSE; @@ -800,10 +800,10 @@ static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD) ULONGLONG conditionMask = 0; versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); versionInfo.dwMajorVersion = major; - versionInfo.dwMinorVersion = minor; - VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); - VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); - return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE; + versionInfo.dwMinorVersion = minor; + VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); + VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); + return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE; } #define _IsWindowsVistaOrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA @@ -861,16 +861,16 @@ float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) UINT xdpi = 96, ydpi = 96; if (_IsWindows8Point1OrGreater()) { - static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process - static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr; - if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr) + static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process + static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr; + if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr) GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"); - if (GetDpiForMonitorFn != nullptr) - { - GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); + if (GetDpiForMonitorFn != nullptr) + { + GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! - return xdpi / 96.0f; - } + return xdpi / 96.0f; + } } #ifndef NOGDI const HDC dc = ::GetDC(nullptr); diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 5cc9cdb53..f70cf0e23 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -34,7 +34,7 @@ Only if you: Then please [use the Discussions forums](https://github.com/ocornut/imgui/discussions) instead of opening an issue. -If Dear ImGui is successfully showing in your app and you have used Dear ImGui before, you can open an Issue. Any form of discussions is welcome as a new issue. +If Dear ImGui is successfully showing in your app and you have used Dear ImGui before, you can open an Issue. Any form of discussions is welcome as a new issue. ## How to open an issue @@ -52,7 +52,7 @@ Steps: - **Please INCLUDE CODE. Provide a Minimal, Complete, and Verifiable Example ([MCVE](https://stackoverflow.com/help/mcve)) to demonstrate your problem**. An ideal submission includes a small piece of code that anyone can paste into one of the examples applications (examples/../main.cpp) or demo (imgui_demo.cpp) to understand and reproduce it. **Narrowing your problem to its shortest and purest form is the easiest way to understand it, explain it and fix it**. Please test your shortened code to ensure it exhibits the problem. **Often while creating the MCVE you will solve the problem!** Many questions that are missing a standalone verifiable example are missing the actual cause of their issue in the description, which ends up wasting everyone's time. - **Attach screenshots (or GIF/video) to clarify the context**. They often convey useful information that is omitted by the description. You can drag pictures/files in the message edit box. Avoid using 3rd party image hosting services, prefer the long-term longevity of GitHub attachments (you can drag pictures into your post). On Windows, you can use [ScreenToGif](https://www.screentogif.com/) to easily capture .gif files. - **If you are discussing an assert or a crash, please provide a debugger callstack**. Never state "it crashes" without additional information. If you don't know how to use a debugger and retrieve a callstack, learning about it will be useful. -- **Please make sure that your project has asserts enabled.** Calls to IM_ASSERT() are scattered in the code to help catch common issues. When an assert is triggered read the comments around it. By default IM_ASSERT() calls the standard assert() function. To verify that your asserts are enabled, add the line `IM_ASSERT(false);` in your main() function. Your application should display an error message and abort. If your application doesn't report an error, your asserts are disabled. +- **Please make sure that your project has asserts enabled.** Calls to IM_ASSERT() are scattered in the code to help catch common issues. When an assert is triggered read the comments around it. By default IM_ASSERT() calls the standard assert() function. To verify that your asserts are enabled, add the line `IM_ASSERT(false);` in your main() function. Your application should display an error message and abort. If your application doesn't report an error, your asserts are disabled. - Please state if you have made substantial modifications to your copy of Dear ImGui or the back-end. - If you are not calling Dear ImGui directly from C++, please provide information about your Language and the wrapper/binding you are using. - Be mindful that messages are being sent to the mailbox of "Watching" users. Try to proofread your messages before sending them. Edits are not seen by those users unless they browse the site. @@ -65,12 +65,12 @@ If you have been using Dear ImGui for a while or have been using C/C++ for sever ## How to open a Pull Request -- **Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance.** PR should be crafted both in the interest of the end-users and also to ease the maintainer into understanding and accepting it. +- **Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance.** PR should be crafted both in the interest of the end-users and also to ease the maintainer into understanding and accepting it. - Many PRs are useful to demonstrate a need and a possible solution but aren't adequate for merging (causing other issues, not seeing other aspects of the big picture, etc.). In doubt, don't hesitate to push a PR because that is always the first step toward pointing toward a problem, and finding the mergeable solution! Even if a PR stays unmerged for a long time, its presence can be useful for other users and helps toward finding a general solution. -- **When adding a feature,** please describe the usage context (how you intend to use it, why you need it, etc.). Be mindful of [The XY Problem](http://xyproblem.info/). +- **When adding a feature,** please describe the usage context (how you intend to use it, why you need it, etc.). Be mindful of [The XY Problem](http://xyproblem.info/). - **When fixing a warning or compilation problem,** please post the compiler log and specify the compiler version and platform you are using. - **Attach screenshots (or GIF/video) to clarify the context and demonstrate the feature at a glance.** You can drag pictures/files in the message edit box. Prefer the long-term longevity of GitHub attachments over 3rd party hosting (you can drag pictures into your post). -- **Make sure your code follows the coding style already used in the codebase:** 4 spaces indentations (no tabs), `local_variable`, `FunctionName()`, `MemberName`, `// Text Comment`, `//CodeComment();`, C-style casts, etc.. We don't use modern C++ idioms and tend to use only a minimum of C++11 features. The applications under examples/ are generally less consistent because they sometimes try to mimic the coding style often adopted by a certain ecosystem (e.g. DirectX-related code tend to use the style of their sample). +- **Make sure your code follows the coding style already used in the codebase:** 4 spaces indentations (no tabs), `local_variable`, `FunctionName()`, `MemberName`, `// Text Comment`, `//CodeComment();`, C-style casts, etc.. We don't use modern C++ idioms and tend to use only a minimum of C++11 features. The applications under examples/ are generally less consistent because they sometimes try to mimic the coding style often adopted by a certain ecosystem (e.g. DirectX-related code tend to use the style of their sample). - **Make sure you create a branch dedicated to the pull request**. In Git, 1 PR is associated to 1 branch. If you keep pushing to the same branch after you submitted the PR, your new commits will appear in the PR (we can still cherry-pick individual commits). ## Copyright / Contributor License Agreement diff --git a/docs/FAQ.md b/docs/FAQ.md index 8dde1967b..6e8d6c26f 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -233,7 +233,7 @@ for (int n = 0; n < 3; n++) ImGui::End();
A primer on labels and the ID Stack... diff --git a/docs/TODO.txt b/docs/TODO.txt index 2a42874cd..31238ff83 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -9,7 +9,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - doc: add a proper documentation system (maybe relying on automation? #435) - doc: checklist app to verify backends/integration of imgui (test inputs, rendering, callback, etc.). - doc/tips: tips of the day: website? applet in imgui_club? - + - window: preserve/restore relative focus ordering (persistent or not), and e.g. of multiple reappearing windows (#2304) -> also see docking reference to same #. - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis). (#690) - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. diff --git a/examples/example_allegro5/README.md b/examples/example_allegro5/README.md index 4af31f6f3..940b47fdb 100644 --- a/examples/example_allegro5/README.md +++ b/examples/example_allegro5/README.md @@ -24,9 +24,9 @@ You may install Allegro using vcpkg: git clone https://github.com/Microsoft/vcpkg cd vcpkg bootstrap-vcpkg.bat -vcpkg install allegro5 --triplet=x86-windows ; for win32 -vcpkg install allegro5 --triplet=x64-windows ; for win64 -vcpkg integrate install ; register include / libs in Visual Studio +vcpkg install allegro5 --triplet=x86-windows ; for win32 +vcpkg install allegro5 --triplet=x64-windows ; for win64 +vcpkg integrate install ; register include / libs in Visual Studio ``` Build: diff --git a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj index 4bb4fc288..5f657eab9 100644 --- a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj +++ b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj @@ -268,9 +268,9 @@ 8309BDBB253CCCAD0045E2A1 /* imgui_impl_metal.mm in Sources */, 83BBEA0920EB54E700295997 /* imgui.cpp in Sources */, 83BBEA0720EB54E700295997 /* imgui_demo.cpp in Sources */, - 83BBEA0520EB54E700295997 /* imgui_draw.cpp in Sources */, + 83BBEA0520EB54E700295997 /* imgui_draw.cpp in Sources */, 5079822E257677DB0038A28D /* imgui_tables.cpp in Sources */, - 07A82ED82139413D0078D120 /* imgui_widgets.cpp in Sources */, + 07A82ED82139413D0078D120 /* imgui_widgets.cpp in Sources */, 8309BDA5253CCC070045E2A1 /* main.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -281,10 +281,10 @@ files = ( 8309BDBE253CCCB60045E2A1 /* imgui_impl_metal.mm in Sources */, 8309BDBF253CCCB60045E2A1 /* imgui_impl_osx.mm in Sources */, - 83BBEA0A20EB54E700295997 /* imgui.cpp in Sources */, - 83BBEA0820EB54E700295997 /* imgui_demo.cpp in Sources */, - 83BBEA0620EB54E700295997 /* imgui_draw.cpp in Sources */, - 5079822E257677DB0038A28D /* imgui_tables.cpp in Sources */, + 83BBEA0A20EB54E700295997 /* imgui.cpp in Sources */, + 83BBEA0820EB54E700295997 /* imgui_demo.cpp in Sources */, + 83BBEA0620EB54E700295997 /* imgui_draw.cpp in Sources */, + 5079822E257677DB0038A28D /* imgui_tables.cpp in Sources */, 07A82ED92139418F0078D120 /* imgui_widgets.cpp in Sources */, 8309BDA8253CCC080045E2A1 /* main.mm in Sources */, ); diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 109ef6153..830f1aed3 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -129,7 +129,7 @@ if (renderPassDescriptor == nil) { [commandBuffer commit]; - return; + return; } // Start the Dear ImGui frame @@ -192,7 +192,7 @@ [renderEncoder popDebugGroup]; [renderEncoder endEncoding]; - // Present + // Present [commandBuffer presentDrawable:view.currentDrawable]; [commandBuffer commit]; } diff --git a/examples/example_sdl3_opengl3/Makefile b/examples/example_sdl3_opengl3/Makefile index 741e97d0c..c2ef3ba55 100644 --- a/examples/example_sdl3_opengl3/Makefile +++ b/examples/example_sdl3_opengl3/Makefile @@ -54,11 +54,11 @@ ifeq ($(UNAME_S), Darwin) #APPLE endif ifeq ($(OS), Windows_NT) - ECHO_MESSAGE = "MinGW" - LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl3` + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl3` - CXXFLAGS += `pkg-config --cflags sdl3` - CFLAGS = $(CXXFLAGS) + CXXFLAGS += `pkg-config --cflags sdl3` + CFLAGS = $(CXXFLAGS) endif ##--------------------------------------------------------------------- diff --git a/examples/example_sdl3_sdlgpu3/Makefile b/examples/example_sdl3_sdlgpu3/Makefile index f6239e0fa..c3159d888 100644 --- a/examples/example_sdl3_sdlgpu3/Makefile +++ b/examples/example_sdl3_sdlgpu3/Makefile @@ -43,11 +43,11 @@ ifeq ($(UNAME_S), Darwin) #APPLE endif ifeq ($(OS), Windows_NT) - ECHO_MESSAGE = "MinGW" - LIBS += -lgdi32 -limm32 `pkg-config --static --libs sdl3` + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -limm32 `pkg-config --static --libs sdl3` - CXXFLAGS += `pkg-config --cflags sdl3` - CFLAGS = $(CXXFLAGS) + CXXFLAGS += `pkg-config --cflags sdl3` + CFLAGS = $(CXXFLAGS) endif ##--------------------------------------------------------------------- diff --git a/examples/example_sdl3_sdlrenderer3/Makefile b/examples/example_sdl3_sdlrenderer3/Makefile index 238576c7c..2ca986545 100644 --- a/examples/example_sdl3_sdlrenderer3/Makefile +++ b/examples/example_sdl3_sdlrenderer3/Makefile @@ -43,11 +43,11 @@ ifeq ($(UNAME_S), Darwin) #APPLE endif ifeq ($(OS), Windows_NT) - ECHO_MESSAGE = "MinGW" - LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl3` + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl3` - CXXFLAGS += `pkg-config --cflags sdl3` - CFLAGS = $(CXXFLAGS) + CXXFLAGS += `pkg-config --cflags sdl3` + CFLAGS = $(CXXFLAGS) endif ##--------------------------------------------------------------------- diff --git a/examples/example_win32_opengl3/build_mingw.bat b/examples/example_win32_opengl3/build_mingw.bat index 767218585..e9f804f5d 100644 --- a/examples/example_win32_opengl3/build_mingw.bat +++ b/examples/example_win32_opengl3/build_mingw.bat @@ -1,4 +1,4 @@ -@REM Build for MINGW64 or 32 from MSYS2. +@REM Build for MINGW64 or 32 from MSYS2. @set OUT_DIR=Debug @set OUT_EXE=example_win32_opengl3 @set INCLUDES=-I../.. -I../../backends diff --git a/imgui.h b/imgui.h index a3f660366..acec7bf99 100644 --- a/imgui.h +++ b/imgui.h @@ -1177,7 +1177,7 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). // Elide display / Alignment - ImGuiInputTextFlags_ElideLeft = 1 << 17, // When text doesn't fit, elide left side to ensure right side stays visible. Useful for path/filenames. Single-line only! + ImGuiInputTextFlags_ElideLeft = 1 << 17, // When text doesn't fit, elide left side to ensure right side stays visible. Useful for path/filenames. Single-line only! // Callback features ImGuiInputTextFlags_CallbackCompletion = 1 << 18, // Callback on pressing TAB (for completion handling) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 530ed6cc4..dd6ebb93e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -584,7 +584,7 @@ void ImGui::ShowDemoWindow(bool* p_open) "- Error recovery is not perfect nor guaranteed! It is a feature to ease development.\n" "- You not are not supposed to rely on it in the course of a normal application run.\n" "- Possible usage: facilitate recovery from errors triggered from a scripting language or after specific exceptions handlers.\n" - "- Always ensure that on programmers seat you have at minimum Asserts or Tooltips enabled when making direct imgui API call!" + "- Always ensure that on programmers seat you have at minimum Asserts or Tooltips enabled when making direct imgui API call! " "Otherwise it would severely hinder your ability to catch and correct mistakes!"); ImGui::Checkbox("io.ConfigErrorRecoveryEnableAssert", &io.ConfigErrorRecoveryEnableAssert); ImGui::Checkbox("io.ConfigErrorRecoveryEnableDebugLog", &io.ConfigErrorRecoveryEnableDebugLog); @@ -1035,8 +1035,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::SeparatorText("Custom"); HelpMarker( - "Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize" - "tooltip activation details across your application. You may however decide to use custom" + "Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize " + "tooltip activation details across your application. You may however decide to use custom " "flags for a specific tooltip instance."); // The following examples are passed for documentation purpose but may not be useful to most users. @@ -2271,8 +2271,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::Text("Set defaults in code:"); ImGui::SameLine(); HelpMarker( "SetColorEditOptions() is designed to allow you to set boot-time default.\n" - "We don't have Push/Pop functions because you can force options on a per-widget basis if needed," - "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid" + "We don't have Push/Pop functions because you can force options on a per-widget basis if needed, " + "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid " "encouraging you to persistently save values that aren't forward-compatible."); if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar); @@ -2295,8 +2295,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::Spacing(); ImGui::Text("HSV encoded colors"); ImGui::SameLine(); HelpMarker( - "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV" - "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the" + "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV " + "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the " "added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); ImGui::Text("Color widget with InputHSV:"); ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); @@ -3558,7 +3558,7 @@ static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) if (ImGui::TreeNode("Multi-Select (trees)")) { HelpMarker( - "This is rather advanced and experimental. If you are getting started with multi-select," + "This is rather advanced and experimental. If you are getting started with multi-select, " "please don't start by looking at how to use it for a tree!\n\n" "Future versions will try to simplify and formalize some of this."); @@ -9493,7 +9493,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) float th = (n == 0) ? 1.0f : thickness; draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle - draw_list->AddEllipse(ImVec2(x + sz*0.5f, y + sz*0.5f), ImVec2(sz*0.5f, sz*0.3f), col, -0.3f, circle_segments, th); x += sz + spacing; // Ellipse + draw_list->AddEllipse(ImVec2(x + sz*0.5f, y + sz*0.5f), ImVec2(sz*0.5f, sz*0.3f), col, -0.3f, circle_segments, th); x += sz + spacing; // Ellipse draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, ImDrawFlags_None, th); x += sz + spacing; // Square draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, ImDrawFlags_None, th); x += sz + spacing; // Square with all rounded corners draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners diff --git a/misc/freetype/README.md b/misc/freetype/README.md index 3955b080e..6e2e8671e 100644 --- a/misc/freetype/README.md +++ b/misc/freetype/README.md @@ -38,7 +38,7 @@ You can use the `ImGuiFreeTypeBuilderFlags_LoadColor` flag to load certain color ### Using OpenType SVG fonts (SVGinOT) - *SVG in Open Type* is a standard by Adobe and Mozilla for color OpenType and Open Font Format fonts. It allows font creators to embed complete SVG files within a font enabling full color and even animations. -- Popular fonts such as [twemoji](https://github.com/13rac1/twemoji-color-font) and fonts made with [scfbuild](https://github.com/13rac1/scfbuild) is SVGinOT +- Popular fonts such as [twemoji](https://github.com/13rac1/twemoji-color-font) and fonts made with [scfbuild](https://github.com/13rac1/scfbuild) is SVGinOT. - Two alternatives are possible to render SVG fonts: use "lunasvg" or "plutosvg". plutosvg will support some more fonts (e.g. NotoColorEmoji-Regular) and may load them faster. #### Using lunasvg diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 029991bbd..875060d7f 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -269,11 +269,11 @@ namespace if (glyph_index == 0) return nullptr; - // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts. - // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076 - // - https://github.com/ocornut/imgui/issues/4567 - // - https://github.com/ocornut/imgui/issues/4566 - // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. + // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts. + // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076 + // - https://github.com/ocornut/imgui/issues/4567 + // - https://github.com/ocornut/imgui/issues/4566 + // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. FT_Error error = FT_Load_Glyph(Face, glyph_index, LoadFlags); if (error) return nullptr; From 914fbcf2e52d43db71d13f12f1a9971719f1c560 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 16:23:00 +0100 Subject: [PATCH 0674/2359] Fonts: removed unnecessary const qualifier from ImFont::FindGlyph() Amend 0bde57c --- imgui.h | 16 +++++++++------- imgui_draw.cpp | 4 ++-- imgui_widgets.cpp | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/imgui.h b/imgui.h index acec7bf99..24f8fc2b0 100644 --- a/imgui.h +++ b/imgui.h @@ -3412,6 +3412,7 @@ struct ImFontAtlas // Members //------------------------------------------- + // Input ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. @@ -3443,8 +3444,8 @@ struct ImFontAtlas int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines // [Obsolete] - //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ - //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ + //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ + //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ }; // Font runtime data and rendering @@ -3459,7 +3460,7 @@ struct ImFont // [Internal] Members: Hot ~28/40 bytes (for RenderText loop) ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. ImVector Glyphs; // 12-16 // out // All glyphs. - const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) + ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) // [Internal] Members: Cold ~32/40 bytes // Conceptually ConfigData[] is the list of font sources merged to create this font. @@ -3480,12 +3481,13 @@ struct ImFont // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); - IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c); - IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c); + IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); + IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); float GetCharAdvance(ImWchar c) { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } bool IsLoaded() const { return ContainerAtlas != NULL; } const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } + // [Internal] Don't use! // '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 ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL); // utf8 @@ -3552,7 +3554,7 @@ struct ImGuiPlatformIO IMGUI_API ImGuiPlatformIO(); //------------------------------------------------------------------ - // Interface with OS and Platform backend + // Input - Interface with OS and Platform backend (most common stuff) //------------------------------------------------------------------ // Optional: Access OS clipboard @@ -3577,7 +3579,7 @@ struct ImGuiPlatformIO ImWchar Platform_LocaleDecimalPoint; // '.' //------------------------------------------------------------------ - // Interface with Renderer Backend + // Input - Interface with Renderer Backend //------------------------------------------------------------------ // Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ed5164bb7..5bf0f0b18 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3903,7 +3903,7 @@ void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) } // Find glyph, return fallback if missing -const ImFontGlyph* ImFont::FindGlyph(ImWchar c) +ImFontGlyph* ImFont::FindGlyph(ImWchar c) { if (c >= (size_t)IndexLookup.Size) return FallbackGlyph; @@ -3913,7 +3913,7 @@ const ImFontGlyph* ImFont::FindGlyph(ImWchar c) return &Glyphs.Data[i]; } -const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) +ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) { if (c >= (size_t)IndexLookup.Size) return NULL; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 612ff62a6..d246147bd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4252,7 +4252,7 @@ void ImGui::PushPasswordFont() ImGuiContext& g = *GImGui; ImFont* in_font = g.Font; ImFont* out_font = &g.InputTextPasswordFont; - const ImFontGlyph* glyph = in_font->FindGlyph('*'); + ImFontGlyph* glyph = in_font->FindGlyph('*'); out_font->FontSize = in_font->FontSize; out_font->Scale = in_font->Scale; out_font->Ascent = in_font->Ascent; From 4982602f6feb0df9fe67e20a197aa074bfde3780 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 18:16:04 +0100 Subject: [PATCH 0675/2359] Windows, Style: Added style.WindowBorderHoverPadding setting to configure inner/outer padding applied to hit-testing of windows borders. Amend 3c7177c6, 59f3c4fc2, ae7f833c6. Could be latched inside windows to be multi-dpi friendly, but likely won't matter soon. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 21 ++++++++++----------- imgui.h | 1 + imgui_demo.cpp | 5 ++++- imgui_internal.h | 2 +- 5 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7977ef681..b9888b134 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,9 @@ Other changes: - Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), RadioButton(), Selectable(). Regression from 2025/01/13. (#8370) +- Windows, Style: Added style.WindowBorderHoverPadding setting to configure + inner/outer padding applied to hit-testing of windows borders and detection + of hovered window. - InputTextWithHint(): Fixed buffer-overflow (luckily often with no visible effect) when a user callback modified the buffer contents in a way that altered the visibility of the preview/hint buffer. (#8368) [@m9710797, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index 4de75457d..29fe4a220 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1167,11 +1167,7 @@ CODE // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear - static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut. - -// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend) -static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow(). static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. @@ -1318,6 +1314,7 @@ ImGuiStyle::ImGuiStyle() WindowPadding = ImVec2(8,8); // Padding within a window WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. + WindowBorderHoverPadding = 4.0f; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders. WindowMinSize = ImVec2(32,32); // Minimum window size WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left. @@ -1379,6 +1376,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) WindowPadding = ImTrunc(WindowPadding * scale_factor); WindowRounding = ImTrunc(WindowRounding * scale_factor); WindowMinSize = ImTrunc(WindowMinSize * scale_factor); + WindowBorderHoverPadding = ImTrunc(WindowBorderHoverPadding * scale_factor); ChildRounding = ImTrunc(ChildRounding * scale_factor); PopupRounding = ImTrunc(PopupRounding * scale_factor); FramePadding = ImTrunc(FramePadding * scale_factor); @@ -5037,7 +5035,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow. - g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING)); + g.WindowsBorderHoverPadding = ImMax(ImMax(g.Style.TouchExtraPadding.x, g.Style.TouchExtraPadding.y), g.Style.WindowBorderHoverPadding); // Find the window hovered by mouse: // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. @@ -5800,7 +5798,7 @@ void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_vi hovered_window = g.MovingWindow; ImVec2 padding_regular = g.Style.TouchExtraPadding; - ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular; + ImVec2 padding_for_resize = ImMax(g.Style.TouchExtraPadding, ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding)); for (int i = g.Windows.Size - 1; i >= 0; i--) { ImGuiWindow* window = g.Windows[i]; @@ -6502,7 +6500,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si int ret_auto_fit_mask = 0x00; const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f; - const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f; + const float grip_hover_outer_size = g.WindowsBorderHoverPadding; ImRect clamp_rect = visibility_rect; const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar); @@ -6570,7 +6568,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; bool hovered, held; - ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING); + ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding); ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID() ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav); ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); @@ -6608,7 +6606,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size); const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis]; - const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above. + const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding; // Match ButtonBehavior() padding above. // Use absolute mode position ImVec2 border_target = window->Pos; @@ -6697,7 +6695,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si // Recalculate next expected border expected coordinates if (*border_held != -1) - g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING); + g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding); return ret_auto_fit_mask; } @@ -10184,7 +10182,8 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations - IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting."); + IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting!"); + IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders. IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right); diff --git a/imgui.h b/imgui.h index 24f8fc2b0..d58473801 100644 --- a/imgui.h +++ b/imgui.h @@ -2146,6 +2146,7 @@ struct ImGuiStyle ImVec2 WindowPadding; // Padding within a window. float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + float WindowBorderHoverPadding; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders. ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constrain individual windows, use SetNextWindowSizeConstraints(). ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index dd6ebb93e..3c40de2e7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7985,11 +7985,14 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderAngle("TableAngledHeadersAngle", &style.TableAngledHeadersAngle, -50.0f, +50.0f); ImGui::SliderFloat2("TableAngledHeadersTextAlign", (float*)&style.TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SeparatorText("Widgets"); + ImGui::SeparatorText("Windows"); ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + ImGui::SliderFloat("WindowBorderHoverPadding", &style.WindowBorderHoverPadding, 1.0f, 20.0f, "%.0f"); int window_menu_button_position = style.WindowMenuButtonPosition + 1; if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1); + + ImGui::SeparatorText("Widgets"); ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); diff --git a/imgui_internal.h b/imgui_internal.h index d59c19c60..0aa894d56 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2083,7 +2083,7 @@ struct ImGuiContext ImVector CurrentWindowStack; ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow* int WindowsActiveCount; // Number of unique windows submitted by frame - ImVec2 WindowsHoverPadding; // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, WINDOWS_HOVER_PADDING). + float WindowsBorderHoverPadding; // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, style.WindowBorderHoverPadding). This isn't so multi-dpi friendly. ImGuiID DebugBreakInWindow; // Set to break in Begin() call. ImGuiWindow* CurrentWindow; // Window being drawn into ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. From e5668b8c738bd76d372a46e6a3d10812193be12f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 22:48:31 +0100 Subject: [PATCH 0676/2359] Internals: rename ImGuiNextWindowData::Flags to HasFlags for consistency and to reduce mistakes. --- imgui.cpp | 52 +++++++++++++++++++++++------------------------ imgui_internal.h | 9 +++++--- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 12 +++++------ 4 files changed, 39 insertions(+), 36 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 29fe4a220..4ba2051d5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6068,7 +6068,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I // A SetNextWindowSize() call always has priority (#8020) // (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now) // FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer. - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) != 0 && (g.NextWindowData.SizeCond & ImGuiCond_Always) != 0) { if (g.NextWindowData.SizeVal.x > 0.0f) { @@ -6084,11 +6084,11 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I SetNextWindowSize(size); // Forward child flags (we allow prior settings to merge but it'll only work for adding flags) - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) g.NextWindowData.ChildFlags |= child_flags; else g.NextWindowData.ChildFlags = child_flags; - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasChildFlags; // 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. @@ -6302,7 +6302,7 @@ static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& s { ImGuiContext& g = *GImGui; ImVec2 new_size = size_desired; - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint) { // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max. ImRect cr = g.NextWindowData.SizeConstraintRect; @@ -6780,7 +6780,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window)); bool override_alpha = false; float alpha = 1.0f; - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasBgAlpha) { alpha = g.NextWindowData.BgAlphaVal; override_alpha = true; @@ -6950,7 +6950,7 @@ void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window) { ImGuiContext& g = *GImGui; window->SkipRefresh = false; - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0) return; if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh) { @@ -7031,7 +7031,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { UpdateWindowInFocusOrderList(window, window_just_created, flags); window->Flags = (ImGuiWindowFlags)flags; - window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0; + window->ChildFlags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0; window->LastFrameActive = current_frame; window->LastTimeActive = (float)g.Time; window->BeginOrderWithinParent = 0; @@ -7095,7 +7095,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // (FIXME: Consider splitting the HasXXX flags into X/Y components bool window_pos_set_by_api = false; bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) { window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0; if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f) @@ -7111,7 +7111,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond); } } - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) { window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f); window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f); @@ -7121,7 +7121,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) g.NextWindowData.SizeVal.y = window->SizeFull.y; SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); } - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll) { if (g.NextWindowData.ScrollVal.x >= 0.0f) { @@ -7134,13 +7134,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->ScrollTargetCenterRatio.y = 0.0f; } } - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasContentSize) window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal; else if (first_begin_of_the_frame) window->ContentSizeExplicit = ImVec2(0.0f, 0.0f); - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasCollapsed) SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasFocus) FocusWindow(window); if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false); @@ -8223,7 +8223,7 @@ void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pi { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasPos; g.NextWindowData.PosVal = pos; g.NextWindowData.PosPivotVal = pivot; g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; @@ -8233,7 +8233,7 @@ void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSize; g.NextWindowData.SizeVal = size; g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always; } @@ -8245,7 +8245,7 @@ void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data) { ImGuiContext& g = *GImGui; - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasSizeConstraint; g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max); g.NextWindowData.SizeCallback = custom_callback; g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; @@ -8256,14 +8256,14 @@ void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& s void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasContentSize; g.NextWindowData.ContentSizeVal = ImTrunc(size); } void ImGui::SetNextWindowScroll(const ImVec2& scroll) { ImGuiContext& g = *GImGui; - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasScroll; g.NextWindowData.ScrollVal = scroll; } @@ -8271,7 +8271,7 @@ void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasCollapsed; g.NextWindowData.CollapsedVal = collapsed; g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; } @@ -8279,7 +8279,7 @@ void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) void ImGui::SetNextWindowBgAlpha(float alpha) { ImGuiContext& g = *GImGui; - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasBgAlpha; g.NextWindowData.BgAlphaVal = alpha; } @@ -8287,7 +8287,7 @@ void ImGui::SetNextWindowBgAlpha(float alpha) void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags) { ImGuiContext& g = *GImGui; - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasRefreshPolicy; g.NextWindowData.RefreshFlagsVal = flags; } @@ -11301,7 +11301,7 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones). //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen); - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0) { ImVec2 tooltip_pos = is_touchscreen ? (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * g.Style.MouseCursorScale) : (g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * g.Style.MouseCursorScale); ImVec2 tooltip_pivot = is_touchscreen ? TOOLTIP_DEFAULT_PIVOT_TOUCH : ImVec2(0.0f, 0.0f); @@ -11724,7 +11724,7 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla // Center modal windows by default for increased visibility // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves) // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0) { const ImGuiViewport* viewport = GetMainViewport(); SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); @@ -12017,7 +12017,7 @@ void ImGui::SetWindowFocus(const char* name) void ImGui::SetNextWindowFocus() { ImGuiContext& g = *GImGui; - g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus; + g.NextWindowData.HasFlags |= ImGuiNextWindowDataFlags_HasFocus; } // Similar to IsWindowHovered() @@ -16548,7 +16548,7 @@ static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags) void ImGui::ShowDebugLogWindow(bool* p_open) { ImGuiContext& g = *GImGui; - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0) SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver); if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1) { @@ -16868,7 +16868,7 @@ static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_f void ImGui::ShowIDStackToolWindow(bool* p_open) { ImGuiContext& g = *GImGui; - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0) SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver); if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1) { diff --git a/imgui_internal.h b/imgui_internal.h index 0aa894d56..ad9dc91e8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1201,7 +1201,9 @@ enum ImGuiNextWindowDataFlags_ // Storage for SetNexWindow** functions struct ImGuiNextWindowData { - ImGuiNextWindowDataFlags Flags; + ImGuiNextWindowDataFlags HasFlags; + + // Members below are NOT cleared. Always rely on HasFlags. ImGuiCond PosCond; ImGuiCond SizeCond; ImGuiCond CollapsedCond; @@ -1220,7 +1222,7 @@ struct ImGuiNextWindowData ImGuiWindowRefreshFlags RefreshFlagsVal; ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); } - inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; } + inline void ClearFlags() { HasFlags = ImGuiNextWindowDataFlags_None; } }; enum ImGuiNextItemDataFlags_ @@ -1237,7 +1239,8 @@ struct ImGuiNextItemData { ImGuiNextItemDataFlags HasFlags; // Called HasFlags instead of Flags to avoid mistaking this ImGuiItemFlags ItemFlags; // Currently only tested/used for ImGuiItemFlags_AllowOverlap and ImGuiItemFlags_HasSelectionUserData. - // Non-flags members are NOT cleared by ItemAdd() meaning they are still valid during NavProcessItem() + + // Members below are NOT cleared by ItemAdd() meaning they are still valid during e.g. NavProcessItem(). Always rely on HasFlags. ImGuiID FocusScopeId; // Set by SetNextItemSelectionUserData() ImGuiSelectionUserData SelectionUserData; // Set by SetNextItemSelectionUserData() (note that NULL/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) float Width; // Set by SetNextItemWidth() diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 71d1e7d8b..3bd9502d0 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -415,7 +415,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Reset scroll if we are reactivating it if ((previous_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0) - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll) == 0) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll) == 0) SetNextWindowScroll(ImVec2(0.0f, 0.0f)); // Create scrolling region (without border and zero window padding) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d246147bd..2b95c0dd5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1829,7 +1829,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.Flags; + ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.HasFlags; g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values if (window->SkipItems) return false; @@ -1898,7 +1898,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF if (!popup_open) return false; - g.NextWindowData.Flags = backup_next_window_data_flags; + g.NextWindowData.HasFlags = backup_next_window_data_flags; return BeginComboPopup(popup_id, bb, flags); } @@ -1913,7 +1913,7 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags // Set popup size float w = bb.GetWidth(); - if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) + if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint) { g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w); } @@ -1927,9 +1927,9 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4; else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20; ImVec2 constraint_min(0.0f, 0.0f), constraint_max(FLT_MAX, FLT_MAX); - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.x <= 0.0f) // Don't apply constraints if user specified a size + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.x <= 0.0f) // Don't apply constraints if user specified a size constraint_min.x = w; - if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.y <= 0.0f) + if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.y <= 0.0f) constraint_max.y = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items); SetNextWindowSizeConstraints(constraint_min, constraint_max); } @@ -2061,7 +2061,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* (*getter)(vo 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.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)) + if (popup_max_height_in_items != -1 && !(g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)) SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); if (!BeginCombo(label, preview_value, ImGuiComboFlags_None)) From e368015d79a9deffc45894fcd33586092f968395 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 22:56:02 +0100 Subject: [PATCH 0677/2359] Tables: a clipped scrolling table correctly clears SetNextWindowXXX flags. (#8196) Amend 43c51eb12 --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 1 + 2 files changed, 3 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b9888b134..8fa53fc25 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,8 @@ Other changes: visibility of the preview/hint buffer. (#8368) [@m9710797, @ocornut] - Scrollbar: Rework logic that fades-out scrollbar when it becomes too small, which amusingly made it disappear when using very big font/frame size. +- Tables: fixed calling SetNextWindowScroll() on clipped scrolling table + to not leak the value into a subsequent window. (#8196) - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] - Backends: WebGPU: Fix for DAWN API rename WGPUProgrammableStageDescriptor -> WGPUComputeState. [@PhantomCloak] (#8369) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 3bd9502d0..2c1a0d362 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -340,6 +340,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG { ItemSize(outer_rect); ItemAdd(outer_rect, id); + g.NextWindowData.ClearFlags(); return false; } From 50dbb086f23594c1b3b8db8ecaf255b6cbace832 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 22:57:15 +0100 Subject: [PATCH 0678/2359] Tables: sneakily honor ImGuiNextWindowDataFlags_HasChildFlags/ImGuiNextWindowDataFlags_HasWindowFlags as a way to facilitate various hacks/workarounds. --- imgui_internal.h | 6 ++++-- imgui_tables.cpp | 7 +++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ad9dc91e8..f2aaeaa83 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1194,8 +1194,9 @@ enum ImGuiNextWindowDataFlags_ ImGuiNextWindowDataFlags_HasFocus = 1 << 5, ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6, ImGuiNextWindowDataFlags_HasScroll = 1 << 7, - ImGuiNextWindowDataFlags_HasChildFlags = 1 << 8, - ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 9, + ImGuiNextWindowDataFlags_HasWindowFlags = 1 << 8, + ImGuiNextWindowDataFlags_HasChildFlags = 1 << 9, + ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 10, }; // Storage for SetNexWindow** functions @@ -1212,6 +1213,7 @@ struct ImGuiNextWindowData ImVec2 SizeVal; ImVec2 ContentSizeVal; ImVec2 ScrollVal; + ImGuiWindowFlags WindowFlags; // Only honored by BeginTable() ImGuiChildFlags ChildFlags; bool CollapsedVal; ImRect SizeConstraintRect; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2c1a0d362..c2e012776 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -420,8 +420,11 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG SetNextWindowScroll(ImVec2(0.0f, 0.0f)); // Create scrolling region (without border and zero window padding) - ImGuiWindowFlags child_window_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None; - BeginChildEx(name, instance_id, outer_rect.GetSize(), ImGuiChildFlags_None, child_window_flags); + ImGuiChildFlags child_child_flags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : ImGuiChildFlags_None; + ImGuiWindowFlags child_window_flags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowFlags) ? g.NextWindowData.WindowFlags : ImGuiWindowFlags_None; + if (flags & ImGuiTableFlags_ScrollX) + child_window_flags |= ImGuiWindowFlags_HorizontalScrollbar; + BeginChildEx(name, instance_id, outer_rect.GetSize(), child_child_flags, child_window_flags); table->InnerWindow = g.CurrentWindow; table->WorkRect = table->InnerWindow->WorkRect; table->OuterRect = table->InnerWindow->Rect(); From e8ad60cc4f7ade30db505f739772befd3eb62b26 Mon Sep 17 00:00:00 2001 From: edenware <52419657+edenoftheware@users.noreply.github.com> Date: Fri, 7 Feb 2025 21:01:46 -0600 Subject: [PATCH 0679/2359] Fix typo (#8382) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index d58473801..6f9f11ebc 100644 --- a/imgui.h +++ b/imgui.h @@ -3132,7 +3132,7 @@ struct ImDrawList // General polygon // - Only simple polygons are supported by filling functions (no self-intersections, no holes). - // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience fo user but not used by main library. + // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library. IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); From 2206e31e5449217b7298d7d704ef5da1763a128f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 11:37:55 +0100 Subject: [PATCH 0680/2359] Demo: Combos: demonstrate a very simple way to add a filter to a combo. (#718) --- docs/CHANGELOG.txt | 2 ++ imgui_demo.cpp | 32 +++++++++++++++++++++++++++----- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8fa53fc25..c30f81817 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,6 +57,8 @@ Other changes: which amusingly made it disappear when using very big font/frame size. - Tables: fixed calling SetNextWindowScroll() on clipped scrolling table to not leak the value into a subsequent window. (#8196) +- Demo: Combos: demonstrate a very simple way to add a filter to a combo, + by showing the filter inside the combo contents. (#718) - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] - Backends: WebGPU: Fix for DAWN API rename WGPUProgrammableStageDescriptor -> WGPUComputeState. [@PhantomCloak] (#8369) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3c40de2e7..0898ef251 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1435,7 +1435,6 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) // Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[]) const char* combo_preview_value = items[item_selected_idx]; - if (ImGui::BeginCombo("combo 1", combo_preview_value, flags)) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) @@ -1451,23 +1450,46 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::EndCombo(); } + // Show case embedding a filter using a simple trick: displaying the filter inside combo contents. + // See https://github.com/ocornut/imgui/issues/718 for advanced/esoteric alternatives. + if (ImGui::BeginCombo("combo 2 (w/ filter)", combo_preview_value, flags)) + { + static ImGuiTextFilter filter; + if (ImGui::IsWindowAppearing()) + { + ImGui::SetKeyboardFocusHere(); + filter.Clear(); + } + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); + filter.Draw("##Filter", -FLT_MIN); + + for (int n = 0; n < IM_ARRAYSIZE(items); n++) + { + const bool is_selected = (item_selected_idx == n); + if (filter.PassFilter(items[n])) + if (ImGui::Selectable(items[n], is_selected)) + item_selected_idx = n; + } + ImGui::EndCombo(); + } + ImGui::Spacing(); ImGui::SeparatorText("One-liner variants"); - HelpMarker("Flags above don't apply to this section."); + HelpMarker("The Combo() function is not greatly useful apart from cases were you want to embed all options in a single strings.\nFlags above don't apply to this section."); // Simplified one-liner Combo() API, using values packed in a single constant string // This is a convenience for when the selection set is small and known at compile-time. static int item_current_2 = 0; - ImGui::Combo("combo 2 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); + ImGui::Combo("combo 3 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); // Simplified one-liner Combo() using an array of const char* // This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview - ImGui::Combo("combo 3 (array)", &item_current_3, items, IM_ARRAYSIZE(items)); + ImGui::Combo("combo 4 (array)", &item_current_3, items, IM_ARRAYSIZE(items)); // Simplified one-liner Combo() using an accessor function static int item_current_4 = 0; - ImGui::Combo("combo 4 (function)", &item_current_4, [](void* data, int n) { return ((const char**)data)[n]; }, items, IM_ARRAYSIZE(items)); + ImGui::Combo("combo 5 (function)", &item_current_4, [](void* data, int n) { return ((const char**)data)[n]; }, items, IM_ARRAYSIZE(items)); ImGui::TreePop(); } From a18622c3695c8fb178acefad2da26f3ba2e50ffc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 12:02:01 +0100 Subject: [PATCH 0681/2359] TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 6 +++++- imgui.h | 2 +- imgui_demo.cpp | 3 +++ 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c30f81817..ab4345fb3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,6 +57,8 @@ Other changes: which amusingly made it disappear when using very big font/frame size. - Tables: fixed calling SetNextWindowScroll() on clipped scrolling table to not leak the value into a subsequent window. (#8196) +- TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to + handle UTF-8 regardless of system regional settings. (#7660) [@achabense] - Demo: Combos: demonstrate a very simple way to add a filter to a combo, by showing the filter inside the combo contents. (#718) - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] diff --git a/imgui.cpp b/imgui.cpp index 4ba2051d5..2402bf109 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15090,7 +15090,11 @@ static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const cha #endif static bool Platform_OpenInShellFn_DefaultImpl(ImGuiContext*, const char* path) { - return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32; + const int path_wsize = ::MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0); + ImVector path_wbuf; + path_wbuf.resize(path_wsize); + ::MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wbuf.Data, path_wsize); + return (INT_PTR)::ShellExecuteW(NULL, L"open", path_wbuf.Data, NULL, NULL, SW_SHOWDEFAULT) > 32; } #else #include diff --git a/imgui.h b/imgui.h index 6f9f11ebc..29daaae7e 100644 --- a/imgui.h +++ b/imgui.h @@ -3565,7 +3565,7 @@ struct ImGuiPlatformIO void* Platform_ClipboardUserData; // Optional: Open link/folder/file in OS Shell - // (default to use ShellExecuteA() on Windows, system() on Linux/Mac) + // (default to use ShellExecuteW() on Windows, system() on Linux/Mac) bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); void* Platform_OpenInShellUserData; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0898ef251..2774fbc96 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7771,6 +7771,9 @@ void ImGui::ShowAboutWindow(bool* p_open) #ifdef IMGUI_DISABLE_WIN32_FUNCTIONS ImGui::Text("define: IMGUI_DISABLE_WIN32_FUNCTIONS"); #endif +#ifdef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS"); +#endif #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS"); #endif From a431e1277e8f4907ff874b466b71b98696cdc227 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 12:09:44 +0100 Subject: [PATCH 0682/2359] Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. (#7660) --- backends/imgui_impl_sdl2.cpp | 3 +++ backends/imgui_impl_sdl3.cpp | 2 ++ docs/CHANGELOG.txt | 2 ++ 3 files changed, 7 insertions(+) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index a27962a31..abe0e4342 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. // 2025-01-20: Made ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode_Manual) accept an empty array. // 2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f. // 2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) @@ -480,6 +481,8 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; +#else + platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url) == 0; }; #endif // Gamepad handling diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index d5de5443e..16ab5706b 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. // 2025-01-20: Made ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode_Manual) accept an empty array. // 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten. // 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807) @@ -464,6 +465,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; + platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url) == 0; }; // Gamepad handling bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ab4345fb3..74416e373 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,8 @@ Other changes: handle UTF-8 regardless of system regional settings. (#7660) [@achabense] - Demo: Combos: demonstrate a very simple way to add a filter to a combo, by showing the filter inside the combo contents. (#718) +- Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn + handler. (#7660) [@achabense] - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] - Backends: WebGPU: Fix for DAWN API rename WGPUProgrammableStageDescriptor -> WGPUComputeState. [@PhantomCloak] (#8369) From 88cda0cab6f369c2629f6a32b0eaae4436d77c1c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 12:39:54 +0100 Subject: [PATCH 0683/2359] Fixed minor warning. Added comment. --- backends/imgui_impl_opengl3.cpp | 1 + imgui.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index efc1a3c49..9465388a6 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -303,6 +303,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) // GLES 2 bd->GlVersion = 200; bd->GlProfileIsES2 = true; + IM_UNUSED(gl_version_str); #else // Desktop or GLES 3 GLint major = 0; diff --git a/imgui.cpp b/imgui.cpp index 2402bf109..b909e0c30 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2399,7 +2399,7 @@ int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* int e = 0; e = (*out_char < mins[len]) << 6; // non-canonical encoding e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half? - e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range? + e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range we can store in ImWchar (FIXME: May evolve) e |= (s[1] & 0xc0) >> 2; e |= (s[2] & 0xc0) >> 4; e |= (s[3] ) >> 6; From 4dc9df6aae8ff1f09701c13c053ed9fd55efaff4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 19:29:18 +0100 Subject: [PATCH 0684/2359] Tables: fixed an issue where Columns Visible/Hidden state wouldn't be correctly overridden when hot-reloading .ini state. (#7934) --- docs/CHANGELOG.txt | 3 +++ imgui_internal.h | 4 ++-- imgui_tables.cpp | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 74416e373..b76f7455b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,6 +57,8 @@ Other changes: which amusingly made it disappear when using very big font/frame size. - Tables: fixed calling SetNextWindowScroll() on clipped scrolling table to not leak the value into a subsequent window. (#8196) +- Tables: fixed an issue where Columns Visible/Hidden state wouldn't be correctly + overridden when hot-reloading .ini state. (#7934) - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] - Demo: Combos: demonstrate a very simple way to add a filter to a combo, @@ -67,6 +69,7 @@ Other changes: - Backends: WebGPU: Fix for DAWN API rename WGPUProgrammableStageDescriptor -> WGPUComputeState. [@PhantomCloak] (#8369) + ----------------------------------------------------------------------- VERSION 1.91.8 (Released 2025-01-31) ----------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index f2aaeaa83..b904909d7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2944,7 +2944,7 @@ struct ImGuiTableColumnSettings ImGuiTableColumnIdx DisplayOrder; ImGuiTableColumnIdx SortOrder; ImU8 SortDirection : 2; - ImU8 IsEnabled : 1; // "Visible" in ini file + ImS8 IsEnabled : 2; // "Visible" in ini file ImU8 IsStretch : 1; ImGuiTableColumnSettings() @@ -2954,7 +2954,7 @@ struct ImGuiTableColumnSettings Index = -1; DisplayOrder = SortOrder = -1; SortDirection = ImGuiSortDirection_None; - IsEnabled = 1; + IsEnabled = -1; IsStretch = 0; } }; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index c2e012776..3a023d426 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3741,7 +3741,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) else column->DisplayOrder = (ImGuiTableColumnIdx)column_n; display_order_mask |= (ImU64)1 << column->DisplayOrder; - column->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled; + column->IsUserEnabled = column->IsUserEnabledNextFrame = (column_settings->IsEnabled != -1 ? column_settings->IsEnabled == 1 : (column->Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1); column->SortOrder = column_settings->SortOrder; column->SortDirection = column_settings->SortDirection; } From 3b2f2602b4d6ecb0d7c09865dccbf8036afc002a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 21:33:49 +0100 Subject: [PATCH 0685/2359] Windows: Fixed an issue where BeginChild() inside a collapsed Begin() wouldn't inherit the SkipItems flag. Amend/fix a89f05a10 (old!) Discovered while looking at glyph being processed in WIP branch. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 +- imgui.h | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b76f7455b..1253dc41d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,9 @@ Other changes: - Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), RadioButton(), Selectable(). Regression from 2025/01/13. (#8370) +- Windows: Fixed an issue where BeginChild() inside a collapsed Begin() + wouldn't inherit the SkipItems flag, resulting in missing coarse clipping + opportunity for code not checking the BeginChild() return value. - Windows, Style: Added style.WindowBorderHoverPadding setting to configure inner/outer padding applied to hit-testing of windows borders and detection of hovered window. diff --git a/imgui.cpp b/imgui.cpp index b909e0c30..1945dd6c4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7702,7 +7702,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Hide along with parent or if parent is collapsed if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) window->HiddenFramesCanSkipItems = 1; - if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0)) + if (parent_window && parent_window->HiddenFramesCannotSkipItems > 0) window->HiddenFramesCannotSkipItems = 1; } diff --git a/imgui.h b/imgui.h index 29daaae7e..86137e5e1 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.9 WIP" -#define IMGUI_VERSION_NUM 19183 +#define IMGUI_VERSION_NUM 19184 #define IMGUI_HAS_TABLE /* From 6916f935eb221b351178349deb33282cbc24f7a9 Mon Sep 17 00:00:00 2001 From: fdsa <14tanks999@gmail.com> Date: Tue, 11 Feb 2025 13:12:55 -0800 Subject: [PATCH 0686/2359] InputText: Allow CTRL+Shift+Z to redo even outside of OSX. (#8389) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 3 ++- imgui_demo.cpp | 8 ++++---- imgui_widgets.cpp | 4 ++-- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1253dc41d..cdb5e3845 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,7 @@ Other changes: - Windows, Style: Added style.WindowBorderHoverPadding setting to configure inner/outer padding applied to hit-testing of windows borders and detection of hovered window. +- InputText: Allow CTRL+Shift+Z to redo even outside of OSX. (#8389) [@tanksdude] - InputTextWithHint(): Fixed buffer-overflow (luckily often with no visible effect) when a user callback modified the buffer contents in a way that altered the visibility of the preview/hint buffer. (#8368) [@m9710797, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index 1945dd6c4..af4aa2068 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -142,7 +142,8 @@ CODE - CTRL+Shift+Left/Right: Select words. - CTRL+A or Double-Click: Select All. - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard. - - CTRL+Z, CTRL+Y: Undo, Redo. + - CTRL+Z Undo. + - CTRL+Y or CTRL+Shift+Z: Redo. - ESCAPE: Revert text to its original value. - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2774fbc96..db9a6de1a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -861,8 +861,8 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) "Hold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or Double-Click to select all.\n" - "CTRL+X,CTRL+C,CTRL+V clipboard.\n" - "CTRL+Z,CTRL+Y undo/redo.\n" + "CTRL+X,CTRL+C,CTRL+V for clipboard.\n" + "CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo.\n" "ESCAPE to revert.\n\n" "PROGRAMMER:\n" "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() " @@ -8237,7 +8237,7 @@ void ImGui::ShowUserGuide() ImGui::BulletText("CTRL+Left/Right to word jump."); ImGui::BulletText("CTRL+A or double-click to select all."); ImGui::BulletText("CTRL+X/C/V to use clipboard cut/copy/paste."); - ImGui::BulletText("CTRL+Z,CTRL+Y to undo/redo."); + ImGui::BulletText("CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo."); ImGui::BulletText("ESCAPE to revert."); ImGui::Unindent(); ImGui::BulletText("With keyboard navigation enabled:"); @@ -8273,7 +8273,7 @@ static void ShowExampleAppMainMenuBar() if (ImGui::BeginMenu("Edit")) { if (ImGui::MenuItem("Undo", "CTRL+Z")) {} - if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item + if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item ImGui::Separator(); if (ImGui::MenuItem("Cut", "CTRL+X")) {} if (ImGui::MenuItem("Copy", "CTRL+C")) {} diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2b95c0dd5..6676a96d5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4804,14 +4804,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl const bool is_startend_key_down = is_osx && io.KeyCtrl && !io.KeySuper && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End - // Using Shortcut() with ImGuiInputFlags_RouteFocused (default policy) to allow routing operations for other code (e.g. calling window trying to use CTRL+A and CTRL+B: formet would be handled by InputText) + // Using Shortcut() with ImGuiInputFlags_RouteFocused (default policy) to allow routing operations for other code (e.g. calling window trying to use CTRL+A and CTRL+B: former would be handled by InputText) // Otherwise we could simply assume that we own the keys as we are active. const ImGuiInputFlags f_repeat = ImGuiInputFlags_Repeat; const bool is_cut = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_X, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Delete, f_repeat, id)) && !is_readonly && !is_password && (!is_multiline || state->HasSelection()); const bool is_copy = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, id) || Shortcut(ImGuiMod_Ctrl | ImGuiKey_Insert, 0, id)) && !is_password && (!is_multiline || state->HasSelection()); const bool is_paste = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_V, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Insert, f_repeat, id)) && !is_readonly; const bool is_undo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable; - const bool is_redo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Y, f_repeat, id) || (is_osx && Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Z, f_repeat, id))) && !is_readonly && is_undoable; + const bool is_redo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Y, f_repeat, id) || Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable; const bool is_select_all = Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, 0, id); // We allow validate/cancel with Nav source (gamepad) to makes it easier to undo an accidental NavInput press with no keyboard wired, but otherwise it isn't very useful. From 3d900edba7c47bf957a7c7bfcf9773ecf923fa53 Mon Sep 17 00:00:00 2001 From: PuPuHX <654524200@qq.com> Date: Tue, 11 Feb 2025 10:57:47 +0800 Subject: [PATCH 0687/2359] Examples: Win32+DirectX12: Fixed ExampleDescriptorHeapAllocator overflow free index. Amend 40b2286d1. --- examples/example_win32_directx12/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 5b1a7af37..e83ce7dcb 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -54,7 +54,7 @@ struct ExampleDescriptorHeapAllocator HeapHandleIncrement = device->GetDescriptorHandleIncrementSize(HeapType); FreeIndices.reserve((int)desc.NumDescriptors); for (int n = desc.NumDescriptors; n > 0; n--) - FreeIndices.push_back(n); + FreeIndices.push_back(n - 1); } void Destroy() { From ef7ffaff7425ceabb2145ff4cf1df3cdadd252c9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Feb 2025 15:46:17 +0100 Subject: [PATCH 0688/2359] Styles, Tabs: (Breaking) Renamed TabMinWidthForCloseButton to TabCloseButtonMinWidthUnselected. Added TabCloseButtonMinWidthSelected. (#8387) --- docs/CHANGELOG.txt | 8 ++++++++ imgui.cpp | 6 ++++-- imgui.h | 8 +++++++- imgui_demo.cpp | 12 ++++++++---- imgui_widgets.cpp | 10 +++++++--- 5 files changed, 34 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cdb5e3845..7036ba64d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,6 +42,7 @@ HOW TO UPDATE? Breaking changes: - Renamed ImFontConfig::GlyphExtraSpacing.x option to GlyphExtraAdvanceX. (#242) +- Renamed style.TabMinWidthForCloseButton to style.TabCloseButtonMinWidthUnselected. Other changes: @@ -63,6 +64,13 @@ Other changes: to not leak the value into a subsequent window. (#8196) - Tables: fixed an issue where Columns Visible/Hidden state wouldn't be correctly overridden when hot-reloading .ini state. (#7934) +- Styles, Tabs: made the Close Button of selected tabs always visible by default, + without requiring to hover the tab. (#8387) + - Added style.TabCloseButtonMinWidthSelected/TabCloseButtonMinWidthUnselected settings + to configure visibility of the Close Button for selected and unselected tabs. + (-1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width) + - Default for selected tabs: TabCloseButtonMinWidthSelected = -1.0f (always visible) + - Default for unselected tabs: TabCloseButtonMinWidthUnselected = 0.0f (visible when hovered) - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] - Demo: Combos: demonstrate a very simple way to add a filter to a combo, diff --git a/imgui.cpp b/imgui.cpp index af4aa2068..d6b763631 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1339,7 +1339,8 @@ ImGuiStyle::ImGuiStyle() LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. - TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. + TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. + TabCloseButtonMinWidthUnselected = 0.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar. TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees). @@ -1394,7 +1395,8 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) GrabRounding = ImTrunc(GrabRounding * scale_factor); LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); - TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX; + TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : FLT_MAX; + TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : FLT_MAX; TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); diff --git a/imgui.h b/imgui.h index 86137e5e1..6174b8a89 100644 --- a/imgui.h +++ b/imgui.h @@ -2170,7 +2170,8 @@ struct ImGuiStyle float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. - float TabMinWidthForCloseButton; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. + float TabCloseButtonMinWidthSelected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. + float TabCloseButtonMinWidthUnselected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. float TabBarBorderSize; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. float TabBarOverlineSize; // Thickness of tab-bar overline, which highlights the selected tab-bar. float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees). @@ -2201,6 +2202,11 @@ struct ImGuiStyle IMGUI_API ImGuiStyle(); IMGUI_API void ScaleAllSizes(float scale_factor); + + // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // TabMinWidthForCloseButton = TabCloseButtonMinWidthUnselected // Renamed in 1.91.9. +#endif }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index db9a6de1a..7671b7764 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7991,10 +7991,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); - ImGui::SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); - ImGui::SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); ImGui::SeparatorText("Rounding"); ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); @@ -8003,6 +7999,14 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); + + ImGui::SeparatorText("Tabs"); + ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); + ImGui::SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); + ImGui::SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); + ImGui::SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); + ImGui::DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); + ImGui::DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); ImGui::SeparatorText("Tables"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6676a96d5..1b56d5944 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10369,9 +10369,13 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, bool close_button_pressed = false; bool close_button_visible = false; if (close_button_id != 0) - if (is_contents_visible || bb.GetWidth() >= ImMax(button_sz, g.Style.TabMinWidthForCloseButton)) - if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id) - close_button_visible = true; + { + bool is_hovered = g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id; // Any interaction account for this too. + if (is_contents_visible) + close_button_visible = (g.Style.TabCloseButtonMinWidthSelected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthSelected)); + else + close_button_visible = (g.Style.TabCloseButtonMinWidthUnselected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthUnselected)); + } bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x); if (close_button_visible) From 7221f5e739c78e8367ac368f120248b2fed93b19 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Feb 2025 19:01:02 +0100 Subject: [PATCH 0689/2359] Styles, Tabs: Fixed ef7ffaf. (#8387) --- imgui.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d6b763631..a69ae6c03 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1395,8 +1395,8 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) GrabRounding = ImTrunc(GrabRounding * scale_factor); LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); - TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : FLT_MAX; - TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : FLT_MAX; + TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected; + TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); From 7cd31c3557caadcf095fcf6da513b1a763ac77dc Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Feb 2025 19:08:52 +0100 Subject: [PATCH 0690/2359] Tables: tamed some .ini settings optimizations to more accurately allow overwriting/hot-reloading settings. (#7934) --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 23 +++++++++++++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7036ba64d..d897ace83 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,8 @@ Other changes: to not leak the value into a subsequent window. (#8196) - Tables: fixed an issue where Columns Visible/Hidden state wouldn't be correctly overridden when hot-reloading .ini state. (#7934) +- Tables: tamed some .ini settings optimizations to more accurately allow + overwriting/hot-reloading settings in more situations. (#7934) - Styles, Tabs: made the Close Button of selected tabs always visible by default, without requiring to hover the tab. (#8387) - Added style.TabCloseButtonMinWidthSelected/TabCloseButtonMinWidthUnselected settings diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 3a023d426..b7726e908 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -577,6 +577,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Initialize table->SettingsOffset = -1; table->IsSortSpecsDirty = true; + table->IsSettingsDirty = true; // Records itself into .ini file even when in default state (#7934) table->InstanceInteracted = -1; table->ContextPopupColumn = -1; table->ReorderColumn = table->ResizedColumn = table->LastResizedColumn = -1; @@ -3718,6 +3719,19 @@ void ImGui::TableLoadSettings(ImGuiTable* table) table->SettingsLoadedFlags = settings->SaveFlags; table->RefScale = settings->RefScale; + // Initialize default columns settings + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + column->StretchWeight = -1.0f; + column->WidthRequest = -1.0f; + column->AutoFitQueue = 0x00; + column->DisplayOrder = (ImGuiTableColumnIdx)column_n; + column->IsUserEnabled = column->IsUserEnabledNextFrame = (column->Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1; + column->SortOrder = (column->Flags & ImGuiTableColumnFlags_DefaultSort) ? 0 : -1; + column->SortDirection = (column->Flags & ImGuiTableColumnFlags_DefaultSort) ? (ImS8)ImGuiSortDirection_None : (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); + } + // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); ImU64 display_order_mask = 0; @@ -3734,14 +3748,12 @@ void ImGui::TableLoadSettings(ImGuiTable* table) column->StretchWeight = column_settings->WidthOrWeight; else column->WidthRequest = column_settings->WidthOrWeight; - column->AutoFitQueue = 0x00; } if (settings->SaveFlags & ImGuiTableFlags_Reorderable) column->DisplayOrder = column_settings->DisplayOrder; - else - column->DisplayOrder = (ImGuiTableColumnIdx)column_n; display_order_mask |= (ImU64)1 << column->DisplayOrder; - column->IsUserEnabled = column->IsUserEnabledNextFrame = (column_settings->IsEnabled != -1 ? column_settings->IsEnabled == 1 : (column->Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1); + if ((settings->SaveFlags & ImGuiTableFlags_Hideable) && column_settings->IsEnabled != -1) + column->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled == 1; column->SortOrder = column_settings->SortOrder; column->SortDirection = column_settings->SortDirection; } @@ -3837,8 +3849,7 @@ static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandle const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0; const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0; const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0; - if (!save_size && !save_visible && !save_order && !save_sort) - continue; + // We need to save the [Table] entry even if all the bools are false, since this records a table with "default settings". buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount); From a931fb7f51269edda025180710fbd7a286e09688 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Feb 2025 19:15:00 +0100 Subject: [PATCH 0691/2359] Fixed static analyzer warning. (was harmless as initialized in NewFrame) --- imgui.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui.cpp b/imgui.cpp index a69ae6c03..251e46819 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3906,6 +3906,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) InputEventsNextEventId = 1; WindowsActiveCount = 0; + WindowsBorderHoverPadding = 0.0f; CurrentWindow = NULL; HoveredWindow = NULL; HoveredWindowUnderMovingWindow = NULL; From b78cc37891608c582cd71b2bdc299f6ff8392432 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Feb 2025 19:27:43 +0100 Subject: [PATCH 0692/2359] Backends: SDL2: Fixed build for versions older than 2.0.14. (#7660) --- backends/imgui_impl_sdl2.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index abe0e4342..24585a9d3 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -116,6 +116,7 @@ #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 #endif #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) +#define SDL_HAS_OPEN_URL SDL_VERSION_ATLEAST(2,0,14) #if SDL_HAS_VULKAN #include #endif @@ -481,7 +482,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; -#else +#elif SDL_HAS_OPEN_URL platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url) == 0; }; #endif From f94a5f0e8c4b22476891cc18372ff5caaebe8492 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Tassoux?= Date: Thu, 13 Feb 2025 14:30:49 +0100 Subject: [PATCH 0693/2359] Docs: Update doc about plutosvg (#8395) --- imconfig.h | 3 +-- misc/freetype/README.md | 16 ++++------------ 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/imconfig.h b/imconfig.h index 8f8bc3b9a..a1e29e849 100644 --- a/imconfig.h +++ b/imconfig.h @@ -88,8 +88,7 @@ //---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT) // Only works in combination with IMGUI_ENABLE_FREETYPE. -// - lunasvg is currently easier to acquire/install, as e.g. it is part of vcpkg. -// - plutosvg will support more fonts and may load them faster. It currently requires to be built manually but it is fairly easy. See misc/freetype/README for instructions. +// - plutosvg is currently easier to install, as e.g. it is part of vcpkg. It will support more fonts and may load them faster. See misc/freetype/README for instructions. // - Both require headers to be available in the include path + program to be linked with the library code (not provided). // - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement) //#define IMGUI_ENABLE_FREETYPE_PLUTOSVG diff --git a/misc/freetype/README.md b/misc/freetype/README.md index 6e2e8671e..e1bd0198b 100644 --- a/misc/freetype/README.md +++ b/misc/freetype/README.md @@ -48,15 +48,7 @@ Requires: [lunasvg](https://github.com/sammycage/lunasvg) v2.3.2 and above #### Using plutosvg (and plutovg) - Add `#define IMGUI_ENABLE_FREETYPE_PLUTOSVG` in your `imconfig.h`. -- Compile and link with plutosvg *and* plutovg (which is required by plutosvg) - -_Compilation hints for plutovg_ -- Compile all source files in `plutovg/source/*.c` -- Add include directory: `plutovg/include` + `plutovg/stb` - -_Compilation hints for plutosvg_ -- Compile `plutosvg/source/plutosvg.c` -- Add include directory: `plutosvg/source` -- Add define: `PLUTOSVG_HAS_FREETYPE` -- Link with: plutovg, freetype - +- Get latest plutosvg binaries or build yourself. Under Windows you may use vcpkg with: `vcpkg install plutosvg --triplet=x64-windows`. Alternatively, if you build imgui from vcpkg, you just need to enable the plutosvg feature: `vcpkg install imgui[plutosvg] --triplet=x64-windows` +- If you prefer to build plutosvg manually: + - Compilation hints for plutovg: Compile all source files in `plutovg/source/*.c` + Add include directory: `plutovg/include` + `plutovg/stb` + - Compilation hints for plutosvg: Compile `plutosvg/source/plutosvg.c` + Add include directory: `plutosvg/source` + Add define: `PLUTOSVG_HAS_FREETYPE` + Link with: plutovg, freetype From 890ead6a718c95c730012d7c2c3e5844a4a93bb9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Feb 2025 15:40:49 +0100 Subject: [PATCH 0694/2359] Backends: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" without -KHR on API 1.3. (#8326, #8365) --- backends/imgui_impl_vulkan.cpp | 11 ++++++++--- backends/imgui_impl_vulkan.h | 13 +++++++------ docs/CHANGELOG.txt | 4 ++++ 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 2bd40f624..7be2ed1d1 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -26,6 +26,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-13: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. Default to header version if unspecified. Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" (without -KHR suffix) on API 1.3. (#8326) // 2025-01-09: Vulkan: Added IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE to clarify how many image sampler descriptors are expected to be available in descriptor pool. (#6642) // 2025-01-06: Vulkan: Added more ImGui_ImplVulkanH_XXXX helper functions to simplify our examples. // 2024-12-11: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) @@ -1082,9 +1083,11 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING static void ImGui_ImplVulkan_LoadDynamicRenderingFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) { - // Manually load those two (see #5446) - ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func("vkCmdBeginRenderingKHR", user_data)); - ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func("vkCmdEndRenderingKHR", user_data)); + // Manually load those two (see #5446, #8326, #8365) + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func(v->ApiVersion < VK_API_VERSION_1_3 ? "vkCmdBeginRenderingKHR" : "vkCmdBeginRendering", user_data)); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func(v->ApiVersion < VK_API_VERSION_1_3 ? "vkCmdEndRenderingKHR" : "vkCmdEndRendering", user_data)); } #endif @@ -1155,6 +1158,8 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); bd->VulkanInitInfo = *info; + if (bd->VulkanInitInfo.ApiVersion == 0) + bd->VulkanInitInfo.ApiVersion = VK_HEADER_VERSION_COMPLETE; ImGui_ImplVulkan_CreateDeviceObjects(); diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 6f4839c13..9b79d3250 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -75,16 +75,17 @@ // - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure. struct ImGui_ImplVulkan_InitInfo { + uint32_t ApiVersion; // Fill with API version of Instance, e.g. VK_API_VERSION_1_3, which might be lower than header version (VK_HEADER_VERSION_COMPLETE) VkInstance Instance; VkPhysicalDevice PhysicalDevice; VkDevice Device; uint32_t QueueFamily; VkQueue Queue; - VkDescriptorPool DescriptorPool; // See requirements in note above; ignored if using DescriptorPoolSize > 0 - VkRenderPass RenderPass; // Ignored if using dynamic rendering - uint32_t MinImageCount; // >= 2 - uint32_t ImageCount; // >= MinImageCount - VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT + VkDescriptorPool DescriptorPool; // See requirements in note above; ignored if using DescriptorPoolSize > 0 + VkRenderPass RenderPass; // Ignored if using dynamic rendering + uint32_t MinImageCount; // >= 2 + uint32_t ImageCount; // >= MinImageCount + VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT // (Optional) VkPipelineCache PipelineCache; @@ -103,7 +104,7 @@ struct ImGui_ImplVulkan_InitInfo // (Optional) Allocation, Debugging const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); - VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. + VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d897ace83..ec2180fac 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,6 +80,10 @@ Other changes: - Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. (#7660) [@achabense] - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] +- Backends: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. + Default to header version if unspecified. (#8326, #8365) [@mklefrancois] +- Backends: Vulkan: Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" + (without -KHR suffix) on API 1.3. (#8326, #8365) [@mklefrancois] - Backends: WebGPU: Fix for DAWN API rename WGPUProgrammableStageDescriptor -> WGPUComputeState. [@PhantomCloak] (#8369) From 12963f52314d126817da333675fe2f6bcde44ffe Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Feb 2025 15:49:47 +0100 Subject: [PATCH 0695/2359] Examples: Vulkan: make ApiVersion a little more visible in examples. (#8326, #8365) --- backends/imgui_impl_vulkan.h | 2 +- examples/example_glfw_vulkan/main.cpp | 1 + examples/example_sdl2_vulkan/main.cpp | 1 + examples/example_sdl3_vulkan/main.cpp | 1 + examples/example_win32_vulkan/main.cpp | 1 + 5 files changed, 5 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 9b79d3250..c8afc92ac 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -75,7 +75,7 @@ // - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure. struct ImGui_ImplVulkan_InitInfo { - uint32_t ApiVersion; // Fill with API version of Instance, e.g. VK_API_VERSION_1_3, which might be lower than header version (VK_HEADER_VERSION_COMPLETE) + uint32_t ApiVersion; // Fill with API version of Instance, e.g. VK_API_VERSION_1_3 or your value of VkApplicationInfo::apiVersion. May be lower than header version (VK_HEADER_VERSION_COMPLETE) VkInstance Instance; VkPhysicalDevice PhysicalDevice; VkDevice Device; diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 31da972df..ce7fcde5e 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -396,6 +396,7 @@ int main(int, char**) // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForVulkan(window, true); ImGui_ImplVulkan_InitInfo init_info = {}; + //init_info.ApiVersion = VK_API_VERSION_1_3; // Pass in your value of VkApplicationInfo::apiVersion, otherwise will default to header version. init_info.Instance = g_Instance; init_info.PhysicalDevice = g_PhysicalDevice; init_info.Device = g_Device; diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index c0282f932..0c29154bc 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -396,6 +396,7 @@ int main(int, char**) // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForVulkan(window); ImGui_ImplVulkan_InitInfo init_info = {}; + //init_info.ApiVersion = VK_API_VERSION_1_3; // Pass in your value of VkApplicationInfo::apiVersion, otherwise will default to header version. init_info.Instance = g_Instance; init_info.PhysicalDevice = g_PhysicalDevice; init_info.Device = g_Device; diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 52544c342..99e441d7e 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -400,6 +400,7 @@ int main(int, char**) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForVulkan(window); ImGui_ImplVulkan_InitInfo init_info = {}; + //init_info.ApiVersion = VK_API_VERSION_1_3; // Pass in your value of VkApplicationInfo::apiVersion, otherwise will default to header version. init_info.Instance = g_Instance; init_info.PhysicalDevice = g_PhysicalDevice; init_info.Device = g_Device; diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index f337d8e7d..427a2494a 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -387,6 +387,7 @@ int main(int, char**) // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplVulkan_InitInfo init_info = {}; + //init_info.ApiVersion = VK_API_VERSION_1_3; // Pass in your value of VkApplicationInfo::apiVersion, otherwise will default to header version. init_info.Instance = g_Instance; init_info.PhysicalDevice = g_PhysicalDevice; init_info.Device = g_Device; From e1ae7db4cccf1cb6a516a43dd8f63899f504ca52 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Feb 2025 16:03:40 +0100 Subject: [PATCH 0696/2359] Backends: Vulkan: Fixed building with older headers not supporting VK_HEADER_VERSION_COMPLETE. (#8326, #8365) --- backends/imgui_impl_vulkan.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 7be2ed1d1..af084cc0e 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1159,7 +1159,14 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) bd->VulkanInitInfo = *info; if (bd->VulkanInitInfo.ApiVersion == 0) + { + // We don't care about other versions for now, so don't need to make this exhaustive (with #ifdef VK_VERSION_1_X checks) +#ifdef VK_HEADER_VERSION_COMPLETE bd->VulkanInitInfo.ApiVersion = VK_HEADER_VERSION_COMPLETE; +#else + bd->VulkanInitInfo.ApiVersion = VK_API_VERSION_1_0; +#endif + } ImGui_ImplVulkan_CreateDeviceObjects(); From 98c2f6b0c450b2401a2db97a6c96c042b2bfd404 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Feb 2025 16:19:41 +0100 Subject: [PATCH 0697/2359] Tables, Error Handling: Recovery from invalid index in TableSetColumnIndex(). (#1651) --- docs/CHANGELOG.txt | 1 + imgui_tables.cpp | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ec2180fac..283d485df 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,7 @@ Other changes: overridden when hot-reloading .ini state. (#7934) - Tables: tamed some .ini settings optimizations to more accurately allow overwriting/hot-reloading settings in more situations. (#7934) +- Tables, Error Handling: Recovery from invalid index in TableSetColumnIndex(). (#1651) - Styles, Tabs: made the Close Button of selected tabs always visible by default, without requiring to hover the tab. (#8387) - Added style.TabCloseButtonMinWidthSelected/TabCloseButtonMinWidthUnselected settings diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b7726e908..6486dccd6 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2106,7 +2106,11 @@ bool ImGui::TableSetColumnIndex(int column_n) { if (table->CurrentColumn != -1) TableEndCell(table); - IM_ASSERT(column_n >= 0 && table->ColumnsCount); + if ((column_n >= 0 && column_n < table->ColumnsCount) == false) + { + IM_ASSERT_USER_ERROR(column_n >= 0 && column_n < table->ColumnsCount, "TableSetColumnIndex() invalid column index!"); + return false; + } TableBeginCell(table, column_n); } From ec4cd2cb8cf144ea16935806d11d5639a84f73dd Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 14 Feb 2025 12:19:24 +0100 Subject: [PATCH 0698/2359] Backends: Vulkan: Fixed crash with using no prototypes + *BREAKING* Added ApiVersion to ImGui_ImplVulkan_LoadFunctions(). (#8326, #8365, #8400) --- backends/imgui_impl_vulkan.cpp | 43 ++++++++++++++++++++-------------- backends/imgui_impl_vulkan.h | 2 +- docs/CHANGELOG.txt | 4 ++++ 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index af084cc0e..7379e000b 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -26,6 +26,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-14: *BREAKING CHANGE*: Added uint32_t api_version to ImGui_ImplVulkan_LoadFunctions(). // 2025-02-13: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. Default to header version if unspecified. Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" (without -KHR suffix) on API 1.3. (#8326) // 2025-01-09: Vulkan: Added IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE to clarify how many image sampler descriptors are expected to be available in descriptor pool. (#6642) // 2025-01-06: Vulkan: Added more ImGui_ImplVulkanH_XXXX helper functions to simplify our examples. @@ -1081,22 +1082,34 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() } #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING -static void ImGui_ImplVulkan_LoadDynamicRenderingFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) +static void ImGui_ImplVulkan_LoadDynamicRenderingFunctions(uint32_t api_version, PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) { // Manually load those two (see #5446, #8326, #8365) - ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; - ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func(v->ApiVersion < VK_API_VERSION_1_3 ? "vkCmdBeginRenderingKHR" : "vkCmdBeginRendering", user_data)); - ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func(v->ApiVersion < VK_API_VERSION_1_3 ? "vkCmdEndRenderingKHR" : "vkCmdEndRendering", user_data)); + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func(api_version < VK_API_VERSION_1_3 ? "vkCmdBeginRenderingKHR" : "vkCmdBeginRendering", user_data)); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func(api_version < VK_API_VERSION_1_3 ? "vkCmdEndRenderingKHR" : "vkCmdEndRendering", user_data)); } #endif -bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) +// If unspecified by user, assume that ApiVersion == HeaderVersion + // We don't care about other versions than 1.3 for our checks, so don't need to make this exhaustive (e.g. with all #ifdef VK_VERSION_1_X checks) +static uint32_t ImGui_ImplVulkan_GetDefaultApiVersion() +{ +#ifdef VK_HEADER_VERSION_COMPLETE + return VK_HEADER_VERSION_COMPLETE; +#else + return VK_API_VERSION_1_0; +#endif +} + +bool ImGui_ImplVulkan_LoadFunctions(uint32_t api_version, PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) { // Load function pointers // You can use the default Vulkan loader using: - // ImGui_ImplVulkan_LoadFunctions([](const char* function_name, void*) { return vkGetInstanceProcAddr(your_vk_isntance, function_name); }); + // ImGui_ImplVulkan_LoadFunctions(VK_API_VERSION_1_3, [](const char* function_name, void*) { return vkGetInstanceProcAddr(your_vk_isntance, function_name); }); // But this would be roughly equivalent to not setting VK_NO_PROTOTYPES. + if (api_version == 0) + api_version = ImGui_ImplVulkan_GetDefaultApiVersion(); + #ifdef IMGUI_IMPL_VULKAN_USE_LOADER #define IMGUI_VULKAN_FUNC_LOAD(func) \ func = reinterpret_cast(loader_func(#func, user_data)); \ @@ -1106,7 +1119,7 @@ bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const ch #undef IMGUI_VULKAN_FUNC_LOAD #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - ImGui_ImplVulkan_LoadDynamicRenderingFunctions(loader_func, user_data); + ImGui_ImplVulkan_LoadDynamicRenderingFunctions(api_version, loader_func, user_data); #endif #else IM_UNUSED(loader_func); @@ -1121,11 +1134,14 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); + if (info->ApiVersion == 0) + info->ApiVersion = ImGui_ImplVulkan_GetDefaultApiVersion(); + if (info->UseDynamicRendering) { #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #ifndef IMGUI_IMPL_VULKAN_USE_LOADER - ImGui_ImplVulkan_LoadDynamicRenderingFunctions([](const char* function_name, void* user_data) { return vkGetInstanceProcAddr((VkInstance)user_data, function_name); }, (void*)info->Instance); + ImGui_ImplVulkan_LoadDynamicRenderingFunctions(info->ApiVersion, [](const char* function_name, void* user_data) { return vkGetInstanceProcAddr((VkInstance)user_data, function_name); }, (void*)info->Instance); #endif IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR != nullptr); IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR != nullptr); @@ -1158,15 +1174,6 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); bd->VulkanInitInfo = *info; - if (bd->VulkanInitInfo.ApiVersion == 0) - { - // We don't care about other versions for now, so don't need to make this exhaustive (with #ifdef VK_VERSION_1_X checks) -#ifdef VK_HEADER_VERSION_COMPLETE - bd->VulkanInitInfo.ApiVersion = VK_HEADER_VERSION_COMPLETE; -#else - bd->VulkanInitInfo.ApiVersion = VK_API_VERSION_1_0; -#endif - } ImGui_ImplVulkan_CreateDeviceObjects(); diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index c8afc92ac..c3f40e138 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -124,7 +124,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet d // Optional: load Vulkan functions with a custom function loader // This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES -IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr); +IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(uint32_t api_version, PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr); // [BETA] Selected render state data shared with callbacks. // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplVulkan_RenderDrawData() call. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 283d485df..9ca3a0c81 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,10 @@ Breaking changes: - Renamed ImFontConfig::GlyphExtraSpacing.x option to GlyphExtraAdvanceX. (#242) - Renamed style.TabMinWidthForCloseButton to style.TabCloseButtonMinWidthUnselected. +- Backends: Vulkan: Added 'uint32_t api_version' argument to ImGui_ImplVulkan_LoadFunctions(). + Note that it was also added to ImGui_ImplVulkan_InitInfo but for the later it is optional. + (#8326, #8365, #8400) + Other changes: From 474305c476a777c94db750c961af5a94c6df4237 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 14 Feb 2025 16:15:09 +0100 Subject: [PATCH 0699/2359] ImFont: simpler constructor. --- imgui_draw.cpp | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5bf0f0b18..ca66b6d79 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3685,21 +3685,8 @@ void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) ImFont::ImFont() { - FontSize = 0.0f; - FallbackAdvanceX = 0.0f; - FallbackChar = 0; - EllipsisChar = 0; - EllipsisWidth = EllipsisCharStep = 0.0f; - EllipsisCharCount = 0; - FallbackGlyph = NULL; - ContainerAtlas = NULL; - ConfigData = NULL; - ConfigDataCount = 0; - DirtyLookupTables = false; + memset(this, 0, sizeof(*this)); Scale = 1.0f; - Ascent = Descent = 0.0f; - MetricsTotalSurface = 0; - memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); } ImFont::~ImFont() From 2860d7ba05667be5e2e51cf27d658352884800b8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 14 Feb 2025 19:44:35 +0100 Subject: [PATCH 0700/2359] Selectable: Fixed horizontal label alignment with SelectableTextAlign.x > 0 and specifying a selectable size. (#8338) Regression from ed7551c1d --- docs/CHANGELOG.txt | 3 ++- imgui_widgets.cpp | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9ca3a0c81..938b83aaf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,7 +47,6 @@ Breaking changes: Note that it was also added to ImGui_ImplVulkan_InitInfo but for the later it is optional. (#8326, #8365, #8400) - Other changes: - Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), @@ -71,6 +70,8 @@ Other changes: - Tables: tamed some .ini settings optimizations to more accurately allow overwriting/hot-reloading settings in more situations. (#7934) - Tables, Error Handling: Recovery from invalid index in TableSetColumnIndex(). (#1651) +- Selectable: Fixed horizontal label alignment with SelectableTextAlign.x > 0 and + specifying a selectable size. (#8338) - Styles, Tabs: made the Close Button of selected tabs always visible by default, without requiring to hover the tab. (#8387) - Added style.TabCloseButtonMinWidthSelected/TabCloseButtonMinWidthUnselected settings diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1b56d5944..eb2b26bd0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7101,7 +7101,7 @@ 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(window->WorkRect.Max.x, pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb); + RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb); // Automatically close popups if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups)) From 78ec1272e962ec9ca5515222cde87ee9f0b1c105 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 14 Feb 2025 21:39:45 +0100 Subject: [PATCH 0701/2359] ImDrawList: added InitialFringeScale in ImDrawListSharedData. Default to 1.0f. This is to allow some DPI mods with less changes. Only the initial value in SetupDrawListSharedData() will need change. --- imgui.cpp | 1 + imgui_draw.cpp | 3 ++- imgui_internal.h | 3 ++- imgui_widgets.cpp | 2 +- 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 251e46819..c27095fd4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5136,6 +5136,7 @@ static void SetupDrawListSharedData() g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; + g.DrawListSharedData.InitialFringeScale = 1.0f; // FIXME-DPI: Change this for some DPI scaling experiments. } void ImGui::NewFrame() diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ca66b6d79..3953212a1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -374,6 +374,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) ImDrawListSharedData::ImDrawListSharedData() { memset(this, 0, sizeof(*this)); + InitialFringeScale = 1.0f; for (int i = 0; i < IM_ARRAYSIZE(ArcFastVtx); i++) { const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(ArcFastVtx); @@ -433,7 +434,7 @@ void ImDrawList::_ResetForNewFrame() _Path.resize(0); _Splitter.Clear(); CmdBuffer.push_back(ImDrawCmd()); - _FringeScale = 1.0f; + _FringeScale = _Data->InitialFringeScale; } void ImDrawList::_ClearFreeMemory() diff --git a/imgui_internal.h b/imgui_internal.h index b904909d7..e272d5479 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -786,8 +786,9 @@ struct IMGUI_API ImDrawListSharedData float FontScale; // Current/default font scale (== FontSize / Font->FontSize) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc - ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() + float InitialFringeScale; // Initial scale to apply to AA fringe ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) + ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() ImVector TempBuffer; // Temporary write buffer // Lookup tables diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index eb2b26bd0..2d45c5d51 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -913,7 +913,7 @@ ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis) const ImRect outer_rect = window->Rect(); const ImRect inner_rect = window->InnerRect; const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar) - IM_ASSERT(scrollbar_size > 0.0f); + IM_ASSERT(scrollbar_size >= 0.0f); const float border_size = IM_ROUND(window->WindowBorderSize * 0.5f); const float border_top = (window->Flags & ImGuiWindowFlags_MenuBar) ? IM_ROUND(g.Style.FrameBorderSize * 0.5f) : 0.0f; if (axis == ImGuiAxis_X) From c4a32a129d55eb66158408b61f51d40907a5aace Mon Sep 17 00:00:00 2001 From: Nico van Bentum Date: Thu, 13 Feb 2025 21:50:12 +0100 Subject: [PATCH 0702/2359] Tabs: fixed middle-button to close not checking hovering, only close button visibility. (#8399, #8387) Main bug has been here since 54a60aaa4, but it's only ef7ffaff7 which made it very visible. --- docs/CHANGELOG.txt | 4 +++- imgui_widgets.cpp | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 938b83aaf..19b334ba6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -72,13 +72,15 @@ Other changes: - Tables, Error Handling: Recovery from invalid index in TableSetColumnIndex(). (#1651) - Selectable: Fixed horizontal label alignment with SelectableTextAlign.x > 0 and specifying a selectable size. (#8338) -- Styles, Tabs: made the Close Button of selected tabs always visible by default, +- Tabs, Style: made the Close Button of selected tabs always visible by default, without requiring to hover the tab. (#8387) - Added style.TabCloseButtonMinWidthSelected/TabCloseButtonMinWidthUnselected settings to configure visibility of the Close Button for selected and unselected tabs. (-1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width) - Default for selected tabs: TabCloseButtonMinWidthSelected = -1.0f (always visible) - Default for unselected tabs: TabCloseButtonMinWidthUnselected = 0.0f (visible when hovered) +- Tabs: fixed middle-mouse-button to close tab not checking that close button + is hovered, merely it's visibility. (#8399, #8387) [@nicovanbentum] - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] - Demo: Combos: demonstrate a very simple way to add a filter to a combo, diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2d45c5d51..6e08cec22 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10368,9 +10368,10 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false bool close_button_pressed = false; bool close_button_visible = false; + bool is_hovered = g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id; // Any interaction account for this too. + if (close_button_id != 0) { - bool is_hovered = g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id; // Any interaction account for this too. if (is_contents_visible) close_button_visible = (g.Style.TabCloseButtonMinWidthSelected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthSelected)); else @@ -10386,7 +10387,7 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, g.LastItemData = last_item_backup; // Close with middle mouse button - if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2)) + if (is_hovered && !(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2)) close_button_pressed = true; } else if (unsaved_marker_visible) From 8f0411ff037790ec65bfb3118473dde532c47785 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Feb 2025 18:19:10 +0100 Subject: [PATCH 0703/2359] Backends: OpenGL3: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) --- backends/imgui_impl_opengl3.cpp | 30 +++++++++++++++++++++++------- docs/CHANGELOG.txt | 2 ++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 9465388a6..14ae90a7e 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-18: OpenGL: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) // 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562) @@ -169,6 +170,7 @@ // - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases // Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version. #define IMGL3W_IMPL +#define IMGUI_IMPL_OPENGL_LOADER_IMGL3W #include "imgui_impl_opengl3_loader.h" #endif @@ -276,6 +278,21 @@ struct ImGui_ImplOpenGL3_VtxAttribState }; #endif +// Not static to allow third-party code to use that if they want to (but undocumented) +bool ImGui_ImplOpenGL3_InitLoader(); +bool ImGui_ImplOpenGL3_InitLoader() +{ + // Initialize our loader +#ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W + if (glGetIntegerv == NULL && imgl3wInit() != 0) + { + fprintf(stderr, "Failed to initialize OpenGL loader!\n"); + return false; + } +#endif + return true; +} + // Functions bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { @@ -283,14 +300,9 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); - // Initialize our loader -#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) - if (imgl3wInit() != 0) - { - fprintf(stderr, "Failed to initialize OpenGL loader!\n"); + // Initialize loader + if (!ImGui_ImplOpenGL3_InitLoader()) return false; - } -#endif // Setup backend capabilities flags ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)(); @@ -406,6 +418,8 @@ void ImGui_ImplOpenGL3_NewFrame() ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL3_Init()?"); + ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries. + if (!bd->ShaderHandle) ImGui_ImplOpenGL3_CreateDeviceObjects(); if (!bd->FontTexture) @@ -497,6 +511,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (fb_width <= 0 || fb_height <= 0) return; + ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries. + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); // Backup GL state diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 19b334ba6..a50bab51e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -87,6 +87,8 @@ Other changes: by showing the filter inside the combo contents. (#718) - Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. (#7660) [@achabense] +- Backends: OpenGL3: Lazily reinitialize embedded GL loader for when calling backend + from e.g. other DLL boundaries. (#8406) - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] - Backends: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. Default to header version if unspecified. (#8326, #8365) [@mklefrancois] From 8a35386ba750fa4c6a77dcbf57211d481528fe43 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Feb 2025 18:40:47 +0100 Subject: [PATCH 0704/2359] Added ImGuiMouseCursor_Wait mouse cursor (busy/wait/hourglass shape) + support in SDL2,SDL3,Win32,Allegro5 backends. --- backends/imgui_impl_allegro5.cpp | 2 ++ backends/imgui_impl_glfw.cpp | 1 + backends/imgui_impl_glfw.h | 1 + backends/imgui_impl_osx.h | 2 ++ backends/imgui_impl_osx.mm | 6 ++++-- backends/imgui_impl_sdl2.cpp | 2 ++ backends/imgui_impl_sdl3.cpp | 2 ++ backends/imgui_impl_win32.cpp | 2 ++ docs/CHANGELOG.txt | 2 ++ imgui.h | 1 + imgui_demo.cpp | 2 +- 11 files changed, 20 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 3718b64ea..7307affde 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-18: Added ImGuiMouseCursor_Wait mouse cursor support. // 2025-01-06: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn @@ -594,6 +595,7 @@ static void ImGui_ImplAllegro5_UpdateMouseCursor() case ImGuiMouseCursor_ResizeEW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break; case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break; case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break; + case ImGuiMouseCursor_Wait: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_BUSY; break; case ImGuiMouseCursor_NotAllowed: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE; break; } al_set_system_mouse_cursor(bd->Display, cursor_id); diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 454a36d36..8bb61d14e 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -11,6 +11,7 @@ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Missing features or Issues: // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. +// [ ] Missing ImGuiMouseCursor_Wait cursor. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index bba6d09ea..260a06b14 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -10,6 +10,7 @@ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Missing features or Issues: // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. +// [ ] Missing ImGuiMouseCursor_Wait cursor. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h index 2e7eabb2b..e4cda54ae 100644 --- a/backends/imgui_impl_osx.h +++ b/backends/imgui_impl_osx.h @@ -10,6 +10,8 @@ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. +// Missing features or Issues: +// [ ] Missing ImGuiMouseCursor_Wait cursor. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 92c26418f..53bdace56 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -10,6 +10,8 @@ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. +// Missing features or Issues: +// [ ] Missing ImGuiMouseCursor_Wait cursor. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -422,12 +424,12 @@ bool ImGui_ImplOSX_Init(NSView* view) bd->MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor]; bd->MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor]; bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor]; - bd->MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor]; - bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor]; bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor]; bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor]; bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor]; bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor]; + bd->MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor]; + bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor]; // Note that imgui.cpp also include default OSX clipboard handlers which can be enabled // by adding '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h and adding '-framework ApplicationServices' to your linker command-line. diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 24585a9d3..d8fd43ae4 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-18: Added ImGuiMouseCursor_Wait mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. // 2025-01-20: Made ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode_Manual) accept an empty array. // 2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f. @@ -499,6 +500,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW); bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND); + bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT); bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO); // Set platform dependent data in viewport diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 16ab5706b..246a91213 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-18: Added ImGuiMouseCursor_Wait mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. // 2025-01-20: Made ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode_Manual) accept an empty array. // 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten. @@ -480,6 +481,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE); bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE); bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER); + bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT); bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED); // Set platform dependent data in viewport diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 03ab53523..cd1cc7ad5 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-18: Added ImGuiMouseCursor_Wait mouse cursor support. // 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. // 2023-09-25: Inputs: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it (same behavior as GLFW/SDL). @@ -256,6 +257,7 @@ static bool ImGui_ImplWin32_UpdateMouseCursor(ImGuiIO& io, ImGuiMouseCursor imgu case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break; case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break; case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break; + case ImGuiMouseCursor_Wait: win32_cursor = IDC_WAIT; break; case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break; } ::SetCursor(::LoadCursor(nullptr, win32_cursor)); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a50bab51e..a72107d12 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,10 +83,12 @@ Other changes: is hovered, merely it's visibility. (#8399, #8387) [@nicovanbentum] - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] +- Misc: Added ImGuiMouseCursor_Wait mouse cursor (busy/wait/hourglass shape). - Demo: Combos: demonstrate a very simple way to add a filter to a combo, by showing the filter inside the combo contents. (#718) - Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. (#7660) [@achabense] +- Backends: SDL2, SDL3, Win32, Allegro5: Added support for ImGuiMouseCursor_Wait. - Backends: OpenGL3: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] diff --git a/imgui.h b/imgui.h index 6174b8a89..5a9b1250c 100644 --- a/imgui.h +++ b/imgui.h @@ -1833,6 +1833,7 @@ enum ImGuiMouseCursor_ ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) + ImGuiMouseCursor_Wait, // When waiting for something to process/load. ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. ImGuiMouseCursor_COUNT }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7671b7764..a2b3de5f9 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7593,7 +7593,7 @@ static void ShowDemoWindowInputs() IMGUI_DEMO_MARKER("Inputs & Focus/Mouse Cursors"); if (ImGui::TreeNode("Mouse Cursors")) { - const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "NotAllowed" }; + const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "Wait", "NotAllowed" }; IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT); ImGuiMouseCursor current = ImGui::GetMouseCursor(); From eec097fe35c0bb2bba60c0a5ce0664cc3507f3bf Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Feb 2025 18:52:08 +0100 Subject: [PATCH 0705/2359] Added ImGuiMouseCursor_Progress mouse cursor 8a35386+ support in SDL2,SDL3,Win32,Allegro5 backends. Amend 8a35386 --- backends/imgui_impl_allegro5.cpp | 3 ++- backends/imgui_impl_glfw.cpp | 2 +- backends/imgui_impl_glfw.h | 2 +- backends/imgui_impl_osx.h | 2 +- backends/imgui_impl_osx.mm | 2 +- backends/imgui_impl_sdl2.cpp | 3 ++- backends/imgui_impl_sdl3.cpp | 3 ++- backends/imgui_impl_win32.cpp | 3 ++- docs/CHANGELOG.txt | 6 ++++-- imgui.h | 1 + imgui_demo.cpp | 2 +- 11 files changed, 18 insertions(+), 11 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 7307affde..9db3e5198 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -20,7 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-02-18: Added ImGuiMouseCursor_Wait mouse cursor support. +// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-01-06: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn @@ -596,6 +596,7 @@ static void ImGui_ImplAllegro5_UpdateMouseCursor() case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break; case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break; case ImGuiMouseCursor_Wait: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_BUSY; break; + case ImGuiMouseCursor_Progress: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_PROGRESS; break; case ImGuiMouseCursor_NotAllowed: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE; break; } al_set_system_mouse_cursor(bd->Display, cursor_id); diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 8bb61d14e..69cde6c08 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -11,7 +11,7 @@ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Missing features or Issues: // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. -// [ ] Missing ImGuiMouseCursor_Wait cursor. +// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index 260a06b14..e203b556f 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -10,7 +10,7 @@ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Missing features or Issues: // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. -// [ ] Missing ImGuiMouseCursor_Wait cursor. +// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h index e4cda54ae..9d0aec07a 100644 --- a/backends/imgui_impl_osx.h +++ b/backends/imgui_impl_osx.h @@ -11,7 +11,7 @@ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. // Missing features or Issues: -// [ ] Missing ImGuiMouseCursor_Wait cursor. +// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 53bdace56..4726462cb 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -11,7 +11,7 @@ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. // Missing features or Issues: -// [ ] Missing ImGuiMouseCursor_Wait cursor. +// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index d8fd43ae4..fbfa2fba8 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,7 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-02-18: Added ImGuiMouseCursor_Wait mouse cursor support. +// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. // 2025-01-20: Made ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode_Manual) accept an empty array. // 2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f. @@ -501,6 +501,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND); bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT); + bd->MouseCursors[ImGuiMouseCursor_Progress] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAITARROW); bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO); // Set platform dependent data in viewport diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 246a91213..006316afb 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,7 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-02-18: Added ImGuiMouseCursor_Wait mouse cursor support. +// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. // 2025-01-20: Made ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode_Manual) accept an empty array. // 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten. @@ -482,6 +482,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE); bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER); bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT); + bd->MouseCursors[ImGuiMouseCursor_Progress] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_PROGRESS); bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED); // Set platform dependent data in viewport diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index cd1cc7ad5..49948c529 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,7 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-02-18: Added ImGuiMouseCursor_Wait mouse cursor support. +// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. // 2023-09-25: Inputs: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it (same behavior as GLFW/SDL). @@ -258,6 +258,7 @@ static bool ImGui_ImplWin32_UpdateMouseCursor(ImGuiIO& io, ImGuiMouseCursor imgu case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break; case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break; case ImGuiMouseCursor_Wait: win32_cursor = IDC_WAIT; break; + case ImGuiMouseCursor_Progress: win32_cursor = IDC_APPSTARTING; break; case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break; } ::SetCursor(::LoadCursor(nullptr, win32_cursor)); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a72107d12..7f2b4554a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,12 +83,14 @@ Other changes: is hovered, merely it's visibility. (#8399, #8387) [@nicovanbentum] - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] -- Misc: Added ImGuiMouseCursor_Wait mouse cursor (busy/wait/hourglass shape). +- Misc: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursors + (busy/wait/hourglass shape, with or without an arrow cursor). - Demo: Combos: demonstrate a very simple way to add a filter to a combo, by showing the filter inside the combo contents. (#718) - Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. (#7660) [@achabense] -- Backends: SDL2, SDL3, Win32, Allegro5: Added support for ImGuiMouseCursor_Wait. +- Backends: SDL2, SDL3, Win32, Allegro5: Added support for ImGuiMouseCursor_Wait + and ImGuiMouseCursor_Progress cursors. - Backends: OpenGL3: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] diff --git a/imgui.h b/imgui.h index 5a9b1250c..16c0b2c22 100644 --- a/imgui.h +++ b/imgui.h @@ -1834,6 +1834,7 @@ enum ImGuiMouseCursor_ ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) ImGuiMouseCursor_Wait, // When waiting for something to process/load. + ImGuiMouseCursor_Progress, // When waiting for something to process/load, but application is still interactive. ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. ImGuiMouseCursor_COUNT }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a2b3de5f9..3be864724 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7593,7 +7593,7 @@ static void ShowDemoWindowInputs() IMGUI_DEMO_MARKER("Inputs & Focus/Mouse Cursors"); if (ImGui::TreeNode("Mouse Cursors")) { - const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "Wait", "NotAllowed" }; + const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "Wait", "Progress", "NotAllowed" }; IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT); ImGuiMouseCursor current = ImGui::GetMouseCursor(); From 8b7b3ce03eef61933727a0823741469e4f6d9b33 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Feb 2025 10:14:38 +0100 Subject: [PATCH 0706/2359] Tables: fixed an issue where Columns Width state wouldn't be correctly restored when hot-reloading .ini state. (#7934) Amend 7cd31c355 column->SortDirection initialized setting was wrong in first block but without side-effect, since sorting always stored explicitly in .ini data. --- docs/CHANGELOG.txt | 4 ++-- imgui_tables.cpp | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7f2b4554a..044be4360 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -65,8 +65,8 @@ Other changes: which amusingly made it disappear when using very big font/frame size. - Tables: fixed calling SetNextWindowScroll() on clipped scrolling table to not leak the value into a subsequent window. (#8196) -- Tables: fixed an issue where Columns Visible/Hidden state wouldn't be correctly - overridden when hot-reloading .ini state. (#7934) +- Tables: fixed an issue where Columns Visible/Width state wouldn't be correctly + restored when hot-reloading .ini state. (#7934) - Tables: tamed some .ini settings optimizations to more accurately allow overwriting/hot-reloading settings in more situations. (#7934) - Tables, Error Handling: Recovery from invalid index in TableSetColumnIndex(). (#1651) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 6486dccd6..3a24ec4c4 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1608,6 +1608,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo flags = column->Flags; // Initialize defaults + // FIXME: Similar to code in TableLoadSettings(), best to see how if we can merge. column->InitStretchWeightOrWidth = init_width_or_weight; if (table->IsInitializing) { @@ -1627,7 +1628,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo // Init default visibility/sort state if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0) column->IsUserEnabled = column->IsUserEnabledNextFrame = false; - if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0) + if ((flags & ImGuiTableColumnFlags_DefaultSort) && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0) { column->SortOrder = 0; // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs. column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); @@ -3724,16 +3725,17 @@ void ImGui::TableLoadSettings(ImGuiTable* table) table->RefScale = settings->RefScale; // Initialize default columns settings + // FIXME: Similar to code in TableSetupColumn(), best to see how if we can merge. for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - column->StretchWeight = -1.0f; - column->WidthRequest = -1.0f; + column->StretchWeight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) && (column->InitStretchWeightOrWidth > 0.0f) ? column->InitStretchWeightOrWidth : -1.0f; + column->WidthRequest = (column->Flags & ImGuiTableColumnFlags_WidthFixed) && (column->InitStretchWeightOrWidth > 0.0f) ? column->InitStretchWeightOrWidth : -1.0f; column->AutoFitQueue = 0x00; column->DisplayOrder = (ImGuiTableColumnIdx)column_n; column->IsUserEnabled = column->IsUserEnabledNextFrame = (column->Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1; column->SortOrder = (column->Flags & ImGuiTableColumnFlags_DefaultSort) ? 0 : -1; - column->SortDirection = (column->Flags & ImGuiTableColumnFlags_DefaultSort) ? (ImS8)ImGuiSortDirection_None : (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); + column->SortDirection = (column->Flags & ImGuiTableColumnFlags_DefaultSort) ? ((column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending)) : (ImS8)ImGuiSortDirection_None; } // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn From 05742f9b6ff06d7ce47669bd5b30fd74390ba11f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Feb 2025 10:55:44 +0100 Subject: [PATCH 0707/2359] Tables: share code between TableSetupColumn() and TableLoadSettings(). (#7934) --- imgui_tables.cpp | 61 ++++++++++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 3a24ec4c4..f6aff8c02 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1565,6 +1565,31 @@ void ImGui::EndTable() NavUpdateCurrentWindowIsScrollPushableX(); } +// Called in TableSetupColumn() when initializing and in TableLoadSettings() for defaults before applying stored settings. +// 'init_mask' specify which fields to initialize. +static void TableInitColumnDefaults(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags init_mask) +{ + ImGuiTableColumnFlags flags = column->Flags; + if (init_mask & ImGuiTableFlags_Resizable) + { + float init_width_or_weight = column->InitStretchWeightOrWidth; + 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; + } + if (init_mask & ImGuiTableFlags_Reorderable) + column->DisplayOrder = (ImGuiTableColumnIdx)table->Columns.index_from_ptr(column); + if (init_mask & ImGuiTableFlags_Hideable) + column->IsUserEnabled = column->IsUserEnabledNextFrame = (flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1; + if (init_mask & ImGuiTableFlags_Sortable) + { + // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs. + column->SortOrder = (flags & ImGuiTableColumnFlags_DefaultSort) ? 0 : -1; + column->SortDirection = (flags & ImGuiTableColumnFlags_DefaultSort) ? ((flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending)) : (ImS8)ImGuiSortDirection_None; + } +} + // See "COLUMNS SIZING POLICIES" comments at the top of this file // If (init_width_or_weight <= 0.0f) it is ignored void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id) @@ -1593,7 +1618,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo IM_ASSERT(init_width_or_weight <= 0.0f && "Can only specify width/weight if sizing policy is set explicitly in either Table or Column."); // When passing a width automatically enforce WidthFixed policy - // (whereas TableSetupColumnFlags would default to WidthAuto if table is not Resizable) + // (whereas TableSetupColumnFlags would default to WidthAuto if table is not resizable) if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0 && init_width_or_weight > 0.0f) if ((table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedFit || (table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame) flags |= ImGuiTableColumnFlags_WidthFixed; @@ -1608,31 +1633,13 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo flags = column->Flags; // Initialize defaults - // FIXME: Similar to code in TableLoadSettings(), best to see how if we can merge. column->InitStretchWeightOrWidth = init_width_or_weight; if (table->IsInitializing) { - // Init width or weight - if (column->WidthRequest < 0.0f && column->StretchWeight < 0.0f) - { - if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) - column->WidthRequest = init_width_or_weight; - if (flags & ImGuiTableColumnFlags_WidthStretch) - column->StretchWeight = (init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f; - - // Disable auto-fit if an explicit width/weight has been specified - if (init_width_or_weight > 0.0f) - column->AutoFitQueue = 0x00; - } - - // Init default visibility/sort state - if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0) - column->IsUserEnabled = column->IsUserEnabledNextFrame = false; - if ((flags & ImGuiTableColumnFlags_DefaultSort) && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0) - { - column->SortOrder = 0; // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs. - column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); - } + ImGuiTableFlags init_flags = ~0; + if (column->WidthRequest >= 0.0f && column->StretchWeight >= 0.0f) + init_flags &= ~ImGuiTableFlags_Resizable; + TableInitColumnDefaults(table, column, init_flags); } // Store name (append with zero-terminator in contiguous buffer) @@ -3725,17 +3732,11 @@ void ImGui::TableLoadSettings(ImGuiTable* table) table->RefScale = settings->RefScale; // Initialize default columns settings - // FIXME: Similar to code in TableSetupColumn(), best to see how if we can merge. for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - column->StretchWeight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) && (column->InitStretchWeightOrWidth > 0.0f) ? column->InitStretchWeightOrWidth : -1.0f; - column->WidthRequest = (column->Flags & ImGuiTableColumnFlags_WidthFixed) && (column->InitStretchWeightOrWidth > 0.0f) ? column->InitStretchWeightOrWidth : -1.0f; + TableInitColumnDefaults(table, column, ~0); column->AutoFitQueue = 0x00; - column->DisplayOrder = (ImGuiTableColumnIdx)column_n; - column->IsUserEnabled = column->IsUserEnabledNextFrame = (column->Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1; - column->SortOrder = (column->Flags & ImGuiTableColumnFlags_DefaultSort) ? 0 : -1; - column->SortDirection = (column->Flags & ImGuiTableColumnFlags_DefaultSort) ? ((column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending)) : (ImS8)ImGuiSortDirection_None; } // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn From 85c488ee121b5f2a3c51141a571dc20f9fd16710 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Feb 2025 11:46:56 +0100 Subject: [PATCH 0708/2359] Hot-fix for broken MouseDrawCursor support for ImGuiMouseCursor_Wait/ImGuiMouseCursor_Progress/ImGuiMouseCursor_NotAllowed. Amend 8a35386, eec097f. --- imgui_draw.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3953212a1..6ff583db6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2466,6 +2466,8 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3 { ImVec2(73,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNESW { ImVec2(55,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNWSE { ImVec2(91,0), ImVec2(17,22), ImVec2( 5, 0) }, // ImGuiMouseCursor_Hand + { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Wait + { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Progress { ImVec2(109,0),ImVec2(13,15), ImVec2( 6, 7) }, // ImGuiMouseCursor_NotAllowed }; From 6dc376f676b3a09375ad53dce652cebac3cb3dc9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Feb 2025 11:54:32 +0100 Subject: [PATCH 0709/2359] ImFontAtlas: added software/drawlist version of ImGuiMouseCursor_Wait/ImGuiMouseCursor_Progress + moved GetMouseCursorTexData() to internals. --- imgui.cpp | 9 ++++++++- imgui.h | 1 - imgui_draw.cpp | 22 +++++++++++----------- imgui_internal.h | 2 ++ 4 files changed, 21 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c27095fd4..e24079487 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3793,7 +3793,7 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso { // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. ImVec2 offset, size, uv[4]; - if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2])) + if (!ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, &offset, &size, &uv[0], &uv[2])) continue; const ImVec2 pos = base_pos - offset; const float scale = base_scale; @@ -3806,6 +3806,13 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border); draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill); + if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress) + { + float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI); + float a_max = a_min + IM_PI * 1.65f; + draw_list->PathArcTo(pos + ImVec2(14, -1) * scale, 6.0f * scale, a_min, a_max); + draw_list->PathStroke(col_fill, ImDrawFlags_None, 3.0f * scale); + } draw_list->PopTextureID(); } } diff --git a/imgui.h b/imgui.h index 16c0b2c22..a607a669e 100644 --- a/imgui.h +++ b/imgui.h @@ -3415,7 +3415,6 @@ struct ImFontAtlas // [Internal] IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; - IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); //------------------------------------------- // Members diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6ff583db6..3fd71cf3c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2402,7 +2402,7 @@ ImFontConfig::ImFontConfig() // - ImFontAtlas::AddCustomRectRegular() // - ImFontAtlas::AddCustomRectFontGlyph() // - ImFontAtlas::CalcCustomRectUV() -// - ImFontAtlas::GetMouseCursorTexData() +// - ImFontAtlasGetMouseCursorTexData() // - ImFontAtlas::Build() // - ImFontAtlasBuildMultiplyCalcLookupTable() // - ImFontAtlasBuildMultiplyRectAlpha8() @@ -2466,8 +2466,8 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3 { ImVec2(73,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNESW { ImVec2(55,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNWSE { ImVec2(91,0), ImVec2(17,22), ImVec2( 5, 0) }, // ImGuiMouseCursor_Hand - { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Wait - { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Progress + { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Wait // Arrow + custom code in ImGui::RenderMouseCursor() + { ImVec2(0,3), ImVec2(12,19), ImVec2(0, 0) }, // ImGuiMouseCursor_Progress // Arrow + custom code in ImGui::RenderMouseCursor() { ImVec2(109,0),ImVec2(13,15), ImVec2( 6, 7) }, // ImGuiMouseCursor_NotAllowed }; @@ -2754,24 +2754,24 @@ void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* ou *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y); } -bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) +bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) { if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT) return false; - if (Flags & ImFontAtlasFlags_NoMouseCursors) + if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) return false; - IM_ASSERT(PackIdMouseCursors != -1); - ImFontAtlasCustomRect* r = GetCustomRectByIndex(PackIdMouseCursors); + IM_ASSERT(atlas->PackIdMouseCursors != -1); + ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->X, (float)r->Y); ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; *out_size = size; *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; - out_uv_border[0] = (pos) * TexUvScale; - out_uv_border[1] = (pos + size) * TexUvScale; + out_uv_border[0] = (pos) * atlas->TexUvScale; + out_uv_border[1] = (pos + size) * atlas->TexUvScale; pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; - out_uv_fill[0] = (pos) * TexUvScale; - out_uv_fill[1] = (pos + size) * TexUvScale; + out_uv_fill[0] = (pos) * atlas->TexUvScale; + out_uv_fill[1] = (pos + size) * atlas->TexUvScale; return true; } diff --git a/imgui_internal.h b/imgui_internal.h index e272d5479..f0cf1c106 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3587,6 +3587,8 @@ IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_ta IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); IMGUI_API void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* cfg, int* out_oversample_h, int* out_oversample_v); +IMGUI_API bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); + //----------------------------------------------------------------------------- // [SECTION] Test Engine specific hooks (imgui_test_engine) //----------------------------------------------------------------------------- From a6bcbb173b36c1c0a12dfa75f996f440d16c1daa Mon Sep 17 00:00:00 2001 From: Tygyh <32486062+tygyh@users.noreply.github.com> Date: Thu, 20 Feb 2025 18:07:25 +0100 Subject: [PATCH 0710/2359] Examples: Android: Update kotlin version (#8409) --- examples/example_android_opengl3/android/app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_android_opengl3/android/app/build.gradle b/examples/example_android_opengl3/android/app/build.gradle index 53181baa2..3a68c8371 100644 --- a/examples/example_android_opengl3/android/app/build.gradle +++ b/examples/example_android_opengl3/android/app/build.gradle @@ -42,5 +42,5 @@ repositories { mavenCentral() } dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" } From 1e18a6cf6018e8de4cb38ebd87d2b9213f09823b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Feb 2025 16:55:35 +0100 Subject: [PATCH 0711/2359] Examples: GLFW+Vulkan: make GLFW_DIR overridable in cmake bit. (#8419) --- examples/example_glfw_vulkan/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/example_glfw_vulkan/CMakeLists.txt b/examples/example_glfw_vulkan/CMakeLists.txt index 443a144ea..75475dbae 100644 --- a/examples/example_glfw_vulkan/CMakeLists.txt +++ b/examples/example_glfw_vulkan/CMakeLists.txt @@ -15,7 +15,9 @@ set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DVK_PROTOTYPES") set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVK_PROTOTYPES") # GLFW -set(GLFW_DIR ../../../glfw) # Set this to point to an up-to-date GLFW repo +if(NOT GLFW_DIR) + set(GLFW_DIR ../../../glfw) # Set this to point to an up-to-date GLFW repo +endif() option(GLFW_BUILD_EXAMPLES "Build the GLFW example programs" OFF) option(GLFW_BUILD_TESTS "Build the GLFW test programs" OFF) option(GLFW_BUILD_DOCS "Build the GLFW documentation" OFF) From 434b7710f3f291cad628b88d4ffb45e0fa3d249e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Feb 2025 16:49:35 +0100 Subject: [PATCH 0712/2359] Internals: packing ImGuiDataVarInfo + misc renaming + value of ImGuiDataType_Pointer doesn't need to be Count+1 --- imgui.cpp | 18 +++++++++--------- imgui_internal.h | 8 ++++---- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e24079487..501a19c66 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3367,7 +3367,7 @@ void ImGui::PopStyleColor(int count) } } -static const ImGuiDataVarInfo GStyleVarInfo[] = +static const ImGuiDataVarInfo GStyleVarsInfo[] = { { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha @@ -3407,15 +3407,15 @@ static const ImGuiDataVarInfo GStyleVarInfo[] = const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx) { IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT); - IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT); - return &GStyleVarInfo[idx]; + IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarsInfo) == ImGuiStyleVar_COUNT); + return &GStyleVarsInfo[idx]; } void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { ImGuiContext& g = *GImGui; const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->Type != ImGuiDataType_Float || var_info->Count != 1) + if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 1) { IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); return; @@ -3429,7 +3429,7 @@ void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x) { ImGuiContext& g = *GImGui; const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2) + if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) { IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); return; @@ -3443,7 +3443,7 @@ void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y) { ImGuiContext& g = *GImGui; const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2) + if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) { IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); return; @@ -3457,7 +3457,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { ImGuiContext& g = *GImGui; const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->Type != ImGuiDataType_Float || var_info->Count != 2) + if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) { IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); return; @@ -3481,8 +3481,8 @@ void ImGui::PopStyleVar(int count) ImGuiStyleMod& backup = g.StyleVarStack.back(); const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx); void* data = info->GetVarPtr(&g.Style); - if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } - else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } + if (info->DataType == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } + else if (info->DataType == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } g.StyleVarStack.pop_back(); count--; } diff --git a/imgui_internal.h b/imgui_internal.h index f0cf1c106..22d035423 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -814,9 +814,9 @@ struct ImDrawDataBuilder struct ImGuiDataVarInfo { - ImGuiDataType Type; - ImU32 Count; // 1+ - ImU32 Offset; // Offset in parent structure + ImGuiDataType DataType : 8; + ImU32 Count : 8; // 1+ + ImU32 Offset : 16; // Offset in parent structure void* GetVarPtr(void* parent) const { return (void*)((unsigned char*)parent + Offset); } }; @@ -837,7 +837,7 @@ struct ImGuiDataTypeInfo // Extend ImGuiDataType_ enum ImGuiDataTypePrivate_ { - ImGuiDataType_Pointer = ImGuiDataType_COUNT + 1, + ImGuiDataType_Pointer = ImGuiDataType_COUNT, ImGuiDataType_ID, }; From edc66d79c7df44899cb1e9be4f839ef4371be91b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Feb 2025 23:09:54 +0100 Subject: [PATCH 0713/2359] Nav: extract code into a NavUpdateWindowingApplyFocus() so it may be reused elsewhere. --- imgui.cpp | 50 +++++++++++++++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 501a19c66..9e2a5e200 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1212,6 +1212,7 @@ static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool j // Navigation static void NavUpdate(); static void NavUpdateWindowing(); +static void NavUpdateWindowingApplyFocus(ImGuiWindow* window); static void NavUpdateWindowingOverlay(); static void NavUpdateCancelRequest(); static void NavUpdateCreateMoveRequest(); @@ -13651,6 +13652,33 @@ static void NavUpdateWindowingTarget(int focus_change_dir) g.NavWindowingToggleLayer = false; } +// Apply focus and close overlay +static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window) +{ + ImGuiContext& g = *GImGui; + if (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow) + { + ClearActiveID(); + SetNavCursorVisibleAfterMove(); + ClosePopupsOverWindow(apply_focus_window, false); + FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild); + apply_focus_window = g.NavWindow; + if (apply_focus_window->NavLastIds[0] == 0) + NavInitWindow(apply_focus_window, false); + + // If the window has ONLY a menu layer (no main layer), select it directly + // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame, + // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since + // the target window as already been previewed once. + // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases, + // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask* + // won't be valid. + if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu)) + g.NavLayer = ImGuiNavLayer_Menu; + } + g.NavWindowingTarget = NULL; +} + // Windowing management mode // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer) // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer) @@ -13802,28 +13830,8 @@ static void ImGui::NavUpdateWindowing() } // Apply final focus - if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)) - { - ClearActiveID(); - SetNavCursorVisibleAfterMove(); - ClosePopupsOverWindow(apply_focus_window, false); - FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild); - apply_focus_window = g.NavWindow; - if (apply_focus_window->NavLastIds[0] == 0) - NavInitWindow(apply_focus_window, false); - - // If the window has ONLY a menu layer (no main layer), select it directly - // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame, - // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since - // the target window as already been previewed once. - // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases, - // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask* - // won't be valid. - if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu)) - g.NavLayer = ImGuiNavLayer_Menu; - } if (apply_focus_window) - g.NavWindowingTarget = NULL; + NavUpdateWindowingApplyFocus(apply_focus_window); // Apply menu/layer toggle if (apply_toggle_layer && g.NavWindow) From 74afea04d6432e3cbcadd43f8eaf771aed48a1c8 Mon Sep 17 00:00:00 2001 From: Tygyh <32486062+tygyh@users.noreply.github.com> Date: Sat, 22 Feb 2025 23:36:40 +0100 Subject: [PATCH 0714/2359] Fix typos in docs (#8427) --- docs/CHANGELOG.txt | 4 ++-- docs/CONTRIBUTING.md | 2 +- docs/TODO.txt | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 044be4360..0d1bbd052 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -346,7 +346,7 @@ Other changes: initial mouse down event. - Note that it may reveal incorrect usage if you were using InputInt/InputFloat without persistent storage by relying solely on e.g. IsItemDeactivatedAfterEdit(): - this was never supported and didn't work consistantly (see #8149). + this was never supported and didn't work consistently (see #8149). - InputText: fixed a bug (regression in 1.91.2) where modifying text buffer within a callback would sometimes prevents further appending to the buffer. - Tabs, Style: made ImGuiCol_TabDimmedSelectedOverline alpha 0 (not visible) in default @@ -450,7 +450,7 @@ Other changes: supported by InputFloat, InputInt, InputScalar etc. widgets. It actually never was. (#8065, #3946) - imgui_freetype: Added support for plutosvg (as an alternative to lunasvg) to render OpenType SVG fonts. Requires defining IMGUI_ENABLE_FREETYPE_PLUTOSVG along with IMGUI_ENABLE_FREETYPE. - Providing headers/librairies for plutosvg + plutovg is up to you (see #7927 for help). + Providing headers/libraries for plutosvg + plutovg is up to you (see #7927 for help). (#7927, #7187, #6591, #6607) [@pthom] - Backends: DX11, DX12, SDLRenderer2/3. Vulkan, WGPU: expose selected state in ImGui_ImplXXXX_RenderState structures during render loop user draw callbacks. diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index f70cf0e23..fb946c4b3 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -77,5 +77,5 @@ If you have been using Dear ImGui for a while or have been using C/C++ for sever Any code you submit will become part of the repository and be distributed under the [Dear ImGui license](https://github.com/ocornut/imgui/blob/master/LICENSE.txt). By submitting code to the project you agree that the code is your work and that you can give it to the project. -You also agree by submitting your code that you grant all transferrable rights to the code to the project maintainer, including for example re-licensing the code, modifying the code, and distributing it in source or binary forms. Specifically, this includes a requirement that you assign copyright to the project maintainer. For this reason, do not modify any copyright statements in files in any PRs. +You also agree by submitting your code that you grant all transferable rights to the code to the project maintainer, including for example re-licensing the code, modifying the code, and distributing it in source or binary forms. Specifically, this includes a requirement that you assign copyright to the project maintainer. For this reason, do not modify any copyright statements in files in any PRs. diff --git a/docs/TODO.txt b/docs/TODO.txt index 31238ff83..14a152a4b 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -22,7 +22,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window: using SetWindowPos() inside Begin() and moving the window with the mouse reacts a very ugly glitch. We should just defer the SetWindowPos() call. - window: GetWindowSize() returns (0,0) when not calculated? (#1045) - window: investigate better auto-positioning for new windows. - - window: top most window flag? more z-order contrl? (#2574) + - window: top most window flag? more z-order control? (#2574) - window/size: manually triggered auto-fit (double-click on grip) shouldn't resize window down to viewport size? - window/size: how to allow to e.g. auto-size vertically to fit contents, but be horizontally resizable? Assuming SetNextWindowSize() is modified to treat -1.0f on each axis as "keep as-is" (would be good but might break erroneous code): Problem is UpdateWindowManualResize() and lots of code treat (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) together. - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. @@ -57,7 +57,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: start exposing PushItemFlag() and ImGuiItemFlags - widgets: alignment options in style (e.g. center Selectable, Right-Align within Button, etc.) #1260 - widgets: activate by identifier (trigger button, focus given id) - - widgets: custom glyph/shapes replacements for stock sapes. (also #6090 #2431 #2235 #6517) + - widgets: custom glyph/shapes replacements for stock shapes. (also #6090 #2431 #2235 #6517) - widgets: coloredit: keep reporting as active when picker is on? - widgets: group/scalarn functions: expose more per-component information. e.g. store NextItemData.ComponentIdx set by scalarn function, groups can expose them back somehow. - selectable: using (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. @@ -137,7 +137,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. + - slider: add dragging-based widgets to edit values with mouse (on 2 axes), saving screen real-estate. - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) - slider: relative dragging? + precision dragging - slider: step option (#1183) @@ -213,7 +213,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. - log: obsolete LogButtons().... (was: LogButtons() options for specifying depth and/or hiding depth slider) - - filters: set a current filter that certains items (e.g. tree node) can automatically query to hide themselves + - filters: set a current filter that certain items (e.g. tree node) can automatically query to hide themselves - filters: handle wild-cards (with implicit leading/trailing *), reg-exprs - filters: fuzzy matches (may use code at blog.forrestthewoods.com/4cffeed33fdb) From 5dce79e9410bfe0fd1709980b637ce38a2313ed0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Feb 2025 10:52:15 +0100 Subject: [PATCH 0715/2359] Backends: DirectX12: Fixed an issue where pre-1.91.5 legacy ImGui_ImplDX12_Init() signature started breaking in 1.91.8 due to missing command queue. (#8429) --- backends/imgui_impl_dx12.cpp | 25 ++++++++++++++++++++++--- backends/imgui_impl_dx12.h | 5 +++-- docs/CHANGELOG.txt | 2 ++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 6f17f587a..8449832c5 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -19,6 +19,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-24: DirectX12: Fixed an issue where ImGui_ImplDX12_Init() signature change from 2024-11-15 combined with change from 2025-01-15 made legacy ImGui_ImplDX12_Init() crash. (#8429) // 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat. // 2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete). @@ -75,6 +76,8 @@ struct ImGui_ImplDX12_Data ID3D12Device* pd3dDevice; ID3D12RootSignature* pRootSignature; ID3D12PipelineState* pPipelineState; + ID3D12CommandQueue* pCommandQueue; + bool commandQueueOwned; DXGI_FORMAT RTVFormat; DXGI_FORMAT DSVFormat; ID3D12DescriptorHeap* pd3dSrvDescHeap; @@ -430,7 +433,7 @@ static void ImGui_ImplDX12_CreateFontsTexture() hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); - ID3D12CommandQueue* cmdQueue = bd->InitInfo.CommandQueue; + ID3D12CommandQueue* cmdQueue = bd->pCommandQueue; cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); hr = cmdQueue->Signal(fence, 1); IM_ASSERT(SUCCEEDED(hr)); @@ -702,6 +705,9 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() if (!bd || !bd->pd3dDevice) return; + if (bd->commandQueueOwned) + SafeRelease(bd->pCommandQueue); + bd->commandQueueOwned = false; SafeRelease(bd->pRootSignature); SafeRelease(bd->pPipelineState); @@ -732,6 +738,8 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) init_info = &bd->InitInfo; bd->pd3dDevice = init_info->Device; + IM_ASSERT(init_info->CommandQueue != NULL); + bd->pCommandQueue = init_info->CommandQueue; bd->RTVFormat = init_info->RTVFormat; bd->DSVFormat = init_info->DSVFormat; bd->numFramesInFlight = init_info->NumFramesInFlight; @@ -793,8 +801,19 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO init_info.RTVFormat = rtv_format; init_info.SrvDescriptorHeap = srv_descriptor_heap; init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle; - init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;; - return ImGui_ImplDX12_Init(&init_info); + init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle; + + D3D12_COMMAND_QUEUE_DESC queueDesc = {}; + queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + queueDesc.NodeMask = 1; + HRESULT hr = device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&init_info.CommandQueue)); + IM_ASSERT(SUCCEEDED(hr)); + + bool ret = ImGui_ImplDX12_Init(&init_info); + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + bd->commandQueueOwned = true; + return ret; } #endif diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index a57c1694d..736e9f5c2 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -27,7 +27,7 @@ struct ImGui_ImplDX12_InitInfo { ID3D12Device* Device; - ID3D12CommandQueue* CommandQueue; + ID3D12CommandQueue* CommandQueue; // Command queue used for queuing texture uploads. int NumFramesInFlight; DXGI_FORMAT RTVFormat; // RenderTarget format. DXGI_FORMAT DSVFormat; // DepthStencilView format. @@ -54,7 +54,8 @@ IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy initialization API Obsoleted in 1.91.5 -// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap' +// - font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap' +// - When we introduced the ImGui_ImplDX12_InitInfo struct we also added a 'ID3D12CommandQueue* CommandQueue' field. IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle); #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0d1bbd052..ae0963703 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -93,6 +93,8 @@ Other changes: and ImGuiMouseCursor_Progress cursors. - Backends: OpenGL3: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) +- Backends: DirectX12: Fixed an issue where pre-1.91.5 legacy ImGui_ImplDX12_Init() + signature started breaking in 1.91.8 due to missing command queue. (#8429) - Backends: Metal: Fixed a crash on application resources. (#8367, #7419) [@anszom] - Backends: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. Default to header version if unspecified. (#8326, #8365) [@mklefrancois] From ef969a53f5fe8b956dc252718f14997393e3344f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Feb 2025 11:44:48 +0100 Subject: [PATCH 0716/2359] Tabs: fixed Unsaved Marker not being visible when Close Button is. (#8430, #8387) --- imgui_widgets.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6e08cec22..f011805f9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10377,9 +10377,15 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, else close_button_visible = (g.Style.TabCloseButtonMinWidthUnselected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthUnselected)); } - bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x); - if (close_button_visible) + // When tabs/document is unsaved, the unsaved marker takes priority over the close button. + const bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x) && (!close_button_visible || !is_hovered); + if (unsaved_marker_visible) + { + const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz)); + RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text)); + } + else if (close_button_visible) { ImGuiLastItemData last_item_backup = g.LastItemData; if (CloseButton(close_button_id, button_pos)) @@ -10390,11 +10396,6 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, if (is_hovered && !(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2)) close_button_pressed = true; } - else if (unsaved_marker_visible) - { - const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz)); - RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text)); - } // This is all rather complicated // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position) From dac40d04872e32399f81b1bf8d0befe87c4cd647 Mon Sep 17 00:00:00 2001 From: TheMode Date: Sat, 22 Feb 2025 11:36:41 +0100 Subject: [PATCH 0717/2359] Backends: SDL2, SDL3: don't call SDL_GetGlobalMouseState() when mouse position is in relative mode. (#8425, #8407) --- backends/imgui_impl_sdl2.cpp | 5 ++++- backends/imgui_impl_sdl3.cpp | 4 +++- docs/CHANGELOG.txt | 4 +++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index fbfa2fba8..361fc3b57 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. // 2025-01-20: Made ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode_Manual) accept an empty array. @@ -622,8 +623,10 @@ static void ImGui_ImplSDL2_UpdateMouseData() SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y); // (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured) - if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0) + const bool is_relative_mouse_mode = SDL_GetRelativeMouseMode() != 0; + if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) { + // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) int window_x, window_y, mouse_x_global, mouse_y_global; SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); SDL_GetWindowPosition(bd->Window, &window_x, &window_y); diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 006316afb..d2433793e 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. // 2025-01-20: Made ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode_Manual) accept an empty array. @@ -588,7 +589,8 @@ static void ImGui_ImplSDL3_UpdateMouseData() SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); // (Optional) Fallback to provide mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) - if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0) + const bool is_relative_mouse_mode = SDL_GetWindowRelativeMouseMode(bd->Window); + if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) { // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) float mouse_x_global, mouse_y_global; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ae0963703..d0acdcb92 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -87,10 +87,12 @@ Other changes: (busy/wait/hourglass shape, with or without an arrow cursor). - Demo: Combos: demonstrate a very simple way to add a filter to a combo, by showing the filter inside the combo contents. (#718) -- Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn +- Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. (#7660) [@achabense] - Backends: SDL2, SDL3, Win32, Allegro5: Added support for ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. +- Backends: SDL2, SDL3: Avoid calling SDL_GetGlobalMouseState() when mouse is in + relative mode. (#8425, #8407) [@TheMode] - Backends: OpenGL3: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) - Backends: DirectX12: Fixed an issue where pre-1.91.5 legacy ImGui_ImplDX12_Init() From 030746faff4a0181ec3149b8457f7bd0a5770819 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Feb 2025 17:45:16 +0100 Subject: [PATCH 0718/2359] Debug Tools: Added io.ConfigDebugHighlightIdConflictsShowItemPicker. (#7961, #7669) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 24 +++++++++++++++++------- imgui.h | 3 ++- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d0acdcb92..d5c4ded32 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,6 +83,8 @@ Other changes: is hovered, merely it's visibility. (#8399, #8387) [@nicovanbentum] - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] +- Debug Tools: Added io.ConfigDebugHighlightIdConflictsShowItemPicker (defaults to true) + to allow disabled Item Picker suggestion in user facing builds. (#7961, #7669) - Misc: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursors (busy/wait/hourglass shape, with or without an arrow cursor). - Demo: Combos: demonstrate a very simple way to add a filter to a combo, diff --git a/imgui.cpp b/imgui.cpp index 9e2a5e200..a5d52d415 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1454,6 +1454,7 @@ ImGuiIO::ImGuiIO() ConfigMemoryCompactTimer = 60.0f; ConfigDebugIsDebuggerPresent = false; ConfigDebugHighlightIdConflicts = true; + ConfigDebugHighlightIdConflictsShowItemPicker = true; ConfigDebugBeginReturnValueOnce = false; ConfigDebugBeginReturnValueLoop = false; @@ -10445,15 +10446,24 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() //BulletText("Code intending to use duplicate ID may use e.g. PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()"); // Not making this too visible for fear of it being abused. BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds."); Separator(); - Text("(Hold CTRL to: use"); - SameLine(); - if (SmallButton("Item Picker")) - DebugStartItemPicker(); - SameLine(); - Text("to break in item call-stack, or"); - SameLine(); + if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker) + { + Text("(Hold CTRL to: use "); + SameLine(0.0f, 0.0f); + if (SmallButton("Item Picker")) + DebugStartItemPicker(); + SameLine(0.0f, 0.0f); + Text(" to break in item call-stack, or "); + } + else + { + Text("(Hold CTRL to "); + } + SameLine(0.0f, 0.0f); if (SmallButton("Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL) g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage"); + SameLine(0.0f, 0.0f); + Text(")"); EndErrorTooltip(); } diff --git a/imgui.h b/imgui.h index a607a669e..5cba09f1c 100644 --- a/imgui.h +++ b/imgui.h @@ -2319,7 +2319,8 @@ struct ImGuiIO // - Code should use PushID()/PopID() in loops, or append "##xx" to same-label identifiers. // - Empty label e.g. Button("") == same ID as parent widget/node. Use Button("##xx") instead! // - See FAQ https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-about-the-id-stack-system - bool ConfigDebugHighlightIdConflicts;// = true // Highlight and show an error message when multiple items have conflicting identifiers. + bool ConfigDebugHighlightIdConflicts;// = true // Highlight and show an error message popup when multiple items have conflicting identifiers. + bool ConfigDebugHighlightIdConflictsShowItemPicker;//=true // Show "Item Picker" button in aforementioned popup. // Tools to test correct Begin/End and BeginChild/EndChild behaviors. // - Presently Begin()/End() and BeginChild()/EndChild() needs to ALWAYS be called in tandem, regardless of return value of BeginXXX() From 6e29450f76db356ebee19a9ac4ee8f4fc129e961 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 25 Feb 2025 16:02:10 +0100 Subject: [PATCH 0719/2359] Internals: added IsItemActiveAsInputText() helper. --- imgui_internal.h | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_internal.h b/imgui_internal.h index 22d035423..c4ec9cc93 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3481,6 +3481,7 @@ namespace ImGui inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == 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); From 4c0604ec2ee9a9121ea4ecb55543ff507ca81bcc Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 18 Jan 2025 16:03:46 +0100 Subject: [PATCH 0720/2359] Font: shallow refactor, rename ConfigData[] fields to Sources[], ConfigDataCount to SourcesCount. In theory this is all internal stuff. --- imgui.cpp | 12 ++-- imgui.h | 10 +-- imgui_draw.cpp | 114 +++++++++++++++---------------- imgui_internal.h | 6 +- misc/freetype/imgui_freetype.cpp | 54 +++++++-------- 5 files changed, 98 insertions(+), 98 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a5d52d415..64514028f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16215,7 +16215,7 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co void ImGui::DebugNodeFont(ImFont* font) { bool opened = TreeNode(font, "Font: \"%s\": %.2f px, %d glyphs, %d sources(s)", - font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); + font->Sources ? font->Sources[0].Name : "", font->FontSize, font->Glyphs.Size, font->SourcesCount); // Display preview text if (!opened) @@ -16248,14 +16248,14 @@ void ImGui::DebugNodeFont(ImFont* font) Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar); const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface); Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt); - for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) - if (font->ConfigData) + for (int config_i = 0; config_i < font->SourcesCount; config_i++) + if (font->Sources) { - const ImFontConfig* cfg = &font->ConfigData[config_i]; + const ImFontConfig* src = &font->Sources[config_i]; int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(cfg, &oversample_h, &oversample_v); + ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", - config_i, cfg->Name, cfg->OversampleH, oversample_h, cfg->OversampleV, oversample_v, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y); + config_i, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); } // Display all glyphs of the fonts in separate pages of 256 characters diff --git a/imgui.h b/imgui.h index 5cba09f1c..1bdc2cb10 100644 --- a/imgui.h +++ b/imgui.h @@ -3441,7 +3441,7 @@ struct ImFontAtlas ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. - ImVector ConfigData; // Configuration data + ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines // [Internal] Font builder @@ -3472,10 +3472,10 @@ struct ImFont ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) // [Internal] Members: Cold ~32/40 bytes - // Conceptually ConfigData[] is the list of font sources merged to create this font. + // Conceptually Sources[] is the list of font sources merged to create this font. ImFontAtlas* ContainerAtlas; // 4-8 // out // What we has been loaded into - const ImFontConfig* ConfigData; // 4-8 // in // Pointer within ContainerAtlas->ConfigData to ConfigDataCount instances - short ConfigDataCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. + ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances + short SourcesCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. short EllipsisCharCount; // 1 // out // 1 or 3 ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') @@ -3494,7 +3494,7 @@ struct ImFont IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); float GetCharAdvance(ImWchar c) { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } bool IsLoaded() const { return ContainerAtlas != NULL; } - const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } + const char* GetDebugName() const { return Sources ? Sources->Name : ""; } // [Internal] Don't use! // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3fd71cf3c..206c29ce5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2408,7 +2408,7 @@ ImFontConfig::ImFontConfig() // - ImFontAtlasBuildMultiplyRectAlpha8() // - ImFontAtlasBuildWithStbTruetype() // - ImFontAtlasGetBuilderForStbTruetype() -// - ImFontAtlasUpdateConfigDataPointers() +// - ImFontAtlasUpdateSourcesPointers() // - ImFontAtlasBuildSetupFont() // - ImFontAtlasBuildPackCustomRects() // - ImFontAtlasBuildRender8bppRectFromString() @@ -2487,7 +2487,7 @@ ImFontAtlas::~ImFontAtlas() void ImFontAtlas::ClearInputData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); - for (ImFontConfig& font_cfg : ConfigData) + for (ImFontConfig& font_cfg : Sources) if (font_cfg.FontData && font_cfg.FontDataOwnedByAtlas) { IM_FREE(font_cfg.FontData); @@ -2496,12 +2496,12 @@ void ImFontAtlas::ClearInputData() // When clearing this we lose access to the font name and other information used to build the font. for (ImFont* font : Fonts) - if (font->ConfigData >= ConfigData.Data && font->ConfigData < ConfigData.Data + ConfigData.Size) + if (font->Sources >= Sources.Data && font->Sources < Sources.Data + Sources.Size) { - font->ConfigData = NULL; - font->ConfigDataCount = 0; + font->Sources = NULL; + font->SourcesCount = 0; } - ConfigData.clear(); + Sources.clear(); CustomRects.clear(); PackIdMouseCursors = PackIdLines = -1; // Important: we leave TexReady untouched @@ -2584,8 +2584,8 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) else IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. - ConfigData.push_back(*font_cfg); - ImFontConfig& new_font_cfg = ConfigData.back(); + Sources.push_back(*font_cfg); + ImFontConfig& new_font_cfg = Sources.back(); if (new_font_cfg.DstFont == NULL) new_font_cfg.DstFont = Fonts.back(); if (!new_font_cfg.FontDataOwnedByAtlas) @@ -2601,8 +2601,8 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) // - We may support it better later and remove this rounding. new_font_cfg.SizePixels = ImTrunc(new_font_cfg.SizePixels); - // Pointers to ConfigData and BuilderData are otherwise dangling - ImFontAtlasUpdateConfigDataPointers(this); + // Pointers to Sources data are otherwise dangling + ImFontAtlasUpdateSourcesPointers(this); // Invalidate texture TexReady = false; @@ -2780,7 +2780,7 @@ bool ImFontAtlas::Build() IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); // Default font is none are specified - if (ConfigData.Size == 0) + if (Sources.Size == 0) AddFontDefault(); // Select builder @@ -2822,11 +2822,11 @@ void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsig *data = table[*data]; } -void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* cfg, int* out_oversample_h, int* out_oversample_v) +void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* src, int* out_oversample_h, int* out_oversample_v) { // Automatically disable horizontal oversampling over size 36 - *out_oversample_h = (cfg->OversampleH != 0) ? cfg->OversampleH : (cfg->SizePixels * cfg->RasterizerDensity > 36.0f || cfg->PixelSnapH) ? 1 : 2; - *out_oversample_v = (cfg->OversampleV != 0) ? cfg->OversampleV : 1; + *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (src->SizePixels * src->RasterizerDensity > 36.0f || src->PixelSnapH) ? 1 : 2; + *out_oversample_v = (src->OversampleV != 0) ? src->OversampleV : 1; } #ifdef IMGUI_ENABLE_STB_TRUETYPE @@ -2869,7 +2869,7 @@ static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector* static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) { - IM_ASSERT(atlas->ConfigData.Size > 0); + IM_ASSERT(atlas->Sources.Size > 0); ImFontAtlasBuildInit(atlas); @@ -2883,32 +2883,32 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) // Temporary storage for building ImVector src_tmp_array; ImVector dst_tmp_array; - src_tmp_array.resize(atlas->ConfigData.Size); + src_tmp_array.resize(atlas->Sources.Size); dst_tmp_array.resize(atlas->Fonts.Size); memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); memset(dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes()); // 1. Initialize font loading structure, check font data validity - for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++) + for (int src_i = 0; src_i < atlas->Sources.Size; src_i++) { ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - ImFontConfig& cfg = atlas->ConfigData[src_i]; - IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas)); + ImFontConfig& src = atlas->Sources[src_i]; + IM_ASSERT(src.DstFont && (!src.DstFont->IsLoaded() || src.DstFont->ContainerAtlas == atlas)); - // Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) + // Find index from src.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) src_tmp.DstIndex = -1; for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++) - if (cfg.DstFont == atlas->Fonts[output_i]) + if (src.DstFont == atlas->Fonts[output_i]) src_tmp.DstIndex = output_i; if (src_tmp.DstIndex == -1) { - IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array? + IM_ASSERT(src_tmp.DstIndex != -1); // src.DstFont not pointing within atlas->Fonts[] array? return false; } // Initialize helper structure for font loading and verify that the TTF/OTF data is correct - const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src.FontData, src.FontNo); IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); - if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) + if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)src.FontData, font_offset)) { IM_ASSERT(0 && "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); return false; @@ -2916,7 +2916,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) // Measure highest codepoints ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault(); + src_tmp.SrcRanges = src.GlyphRanges ? src.GlyphRanges : atlas->GetGlyphRangesDefault(); for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) { // Check for valid range. This may also help detect *some* dangling pointers, because a common @@ -2995,12 +2995,12 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) buf_packedchars_out_n += src_tmp.GlyphsCount; // Automatic selection of oversampling parameters - ImFontConfig& cfg = atlas->ConfigData[src_i]; + ImFontConfig& src = atlas->Sources[src_i]; int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(&cfg, &oversample_h, &oversample_v); + ImFontAtlasBuildGetOversampleFactors(&src, &oversample_h, &oversample_v); // Convert our ranges in the format stb_truetype wants - src_tmp.PackRange.font_size = cfg.SizePixels * cfg.RasterizerDensity; + src_tmp.PackRange.font_size = src.SizePixels * src.RasterizerDensity; src_tmp.PackRange.first_unicode_codepoint_in_range = 0; src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data; src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size; @@ -3009,7 +3009,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) src_tmp.PackRange.v_oversample = (unsigned char)oversample_v; // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects) - const float scale = (cfg.SizePixels > 0.0f) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels * cfg.RasterizerDensity) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels * cfg.RasterizerDensity); + const float scale = (src.SizePixels > 0.0f) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, src.SizePixels * src.RasterizerDensity) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -src.SizePixels * src.RasterizerDensity); for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) { int x0, y0, x1, y1; @@ -3069,7 +3069,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) // 8. Render/rasterize font characters into the texture for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) { - ImFontConfig& cfg = atlas->ConfigData[src_i]; + ImFontConfig& src = atlas->Sources[src_i]; ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; if (src_tmp.GlyphsCount == 0) continue; @@ -3077,10 +3077,10 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) stbtt_PackFontRangesRenderIntoRects(&spc, &src_tmp.FontInfo, &src_tmp.PackRange, 1, src_tmp.Rects); // Apply multiply operator - if (cfg.RasterizerMultiply != 1.0f) + if (src.RasterizerMultiply != 1.0f) { unsigned char multiply_table[256]; - ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply); + ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, src.RasterizerMultiply); stbrp_rect* r = &src_tmp.Rects[0]; for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++, r++) if (r->was_packed) @@ -3098,22 +3098,22 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) { // When merging fonts with MergeMode=true: // - We can have multiple input fonts writing into a same destination font. - // - dst_font->ConfigData is != from cfg which is our source configuration. + // - dst_font->Sources is != from src which is our source configuration. ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - ImFontConfig& cfg = atlas->ConfigData[src_i]; - ImFont* dst_font = cfg.DstFont; + ImFontConfig& src = atlas->Sources[src_i]; + ImFont* dst_font = src.DstFont; - const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels); + const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, src.SizePixels); int unscaled_ascent, unscaled_descent, unscaled_line_gap; stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); const float ascent = ImCeil(unscaled_ascent * font_scale); const float descent = ImFloor(unscaled_descent * font_scale); - ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent); - const float font_off_x = cfg.GlyphOffset.x; - const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent); + ImFontAtlasBuildSetupFont(atlas, dst_font, &src, ascent, descent); + const float font_off_x = src.GlyphOffset.x; + const float font_off_y = src.GlyphOffset.y + IM_ROUND(dst_font->Ascent); - const float inv_rasterization_scale = 1.0f / cfg.RasterizerDensity; + const float inv_rasterization_scale = 1.0f / src.RasterizerDensity; for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) { @@ -3127,7 +3127,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) float y0 = q.y0 * inv_rasterization_scale + font_off_y; float x1 = q.x1 * inv_rasterization_scale + font_off_x; float y1 = q.y1 * inv_rasterization_scale + font_off_y; - dst_font->AddGlyph(&cfg, (ImWchar)codepoint, x0, y0, x1, y1, q.s0, q.t0, q.s1, q.t1, pc.xadvance * inv_rasterization_scale); + dst_font->AddGlyph(&src, (ImWchar)codepoint, x0, y0, x1, y1, q.s0, q.t0, q.s1, q.t1, pc.xadvance * inv_rasterization_scale); } } @@ -3147,17 +3147,17 @@ const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype() #endif // IMGUI_ENABLE_STB_TRUETYPE -void ImFontAtlasUpdateConfigDataPointers(ImFontAtlas* atlas) +void ImFontAtlasUpdateSourcesPointers(ImFontAtlas* atlas) { - for (ImFontConfig& font_cfg : atlas->ConfigData) + for (ImFontConfig& src : atlas->Sources) { - ImFont* font = font_cfg.DstFont; - if (!font_cfg.MergeMode) + ImFont* font = src.DstFont; + if (!src.MergeMode) { - font->ConfigData = &font_cfg; - font->ConfigDataCount = 0; + font->Sources = &src; + font->SourcesCount = 0; } - font->ConfigDataCount++; + font->SourcesCount++; } } @@ -3167,7 +3167,7 @@ void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* f { font->ClearOutputData(); font->FontSize = font_config->SizePixels; - IM_ASSERT(font->ConfigData == font_config); + IM_ASSERT(font->Sources == font_config); font->ContainerAtlas = atlas; font->Ascent = ascent; font->Descent = descent; @@ -3786,7 +3786,7 @@ void ImFont::BuildLookupTable() // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots. - const ImWchar ellipsis_chars[] = { ConfigData->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 }; + const ImWchar ellipsis_chars[] = { Sources->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 }; const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; if (EllipsisChar == 0) EllipsisChar = FindFirstExistingGlyph(this, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars)); @@ -3830,27 +3830,27 @@ void ImFont::GrowIndex(int new_size) // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. // Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). -// 'cfg' is not necessarily == 'this->ConfigData' because multiple source fonts+configs can be used to build one target font. -void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) +// 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. +void ImFont::AddGlyph(const ImFontConfig* src, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) { - if (cfg != NULL) + if (src != NULL) { // Clamp & recenter if needed const float advance_x_original = advance_x; - advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX); + advance_x = ImClamp(advance_x, src->GlyphMinAdvanceX, src->GlyphMaxAdvanceX); if (advance_x != advance_x_original) { - float char_off_x = cfg->PixelSnapH ? ImTrunc((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f; + float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f; x0 += char_off_x; x1 += char_off_x; } // Snap to pixel - if (cfg->PixelSnapH) + if (src->PixelSnapH) advance_x = IM_ROUND(advance_x); // Bake extra spacing - advance_x += cfg->GlyphExtraAdvanceX; + advance_x += src->GlyphExtraAdvanceX; } int glyph_idx = Glyphs.Size; diff --git a/imgui_internal.h b/imgui_internal.h index c4ec9cc93..c70bb999c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3577,16 +3577,16 @@ struct ImFontBuilderIO #ifdef IMGUI_ENABLE_STB_TRUETYPE IMGUI_API const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype(); #endif -IMGUI_API void ImFontAtlasUpdateConfigDataPointers(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasUpdateSourcesPointers(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); +IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value); IMGUI_API void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value); IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); -IMGUI_API void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* cfg, int* out_oversample_h, int* out_oversample_v); +IMGUI_API void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); IMGUI_API bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 875060d7f..73b9862bc 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -166,7 +166,7 @@ namespace // NB: No ctor/dtor, explicitly call Init()/Shutdown() struct FreeTypeFont { - bool InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. + bool InitFont(FT_Library ft_library, const ImFontConfig& src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. void CloseFont(); void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); @@ -185,9 +185,9 @@ namespace float InvRasterizationDensity; }; - bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_font_builder_flags) + bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& src, unsigned int extra_font_builder_flags) { - FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)cfg.FontData, (uint32_t)cfg.FontDataSize, (uint32_t)cfg.FontNo, &Face); + FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src.FontData, (uint32_t)src.FontDataSize, (uint32_t)src.FontNo, &Face); if (error != 0) return false; error = FT_Select_Charmap(Face, FT_ENCODING_UNICODE); @@ -195,7 +195,7 @@ namespace return false; // Convert to FreeType flags (NB: Bold and Oblique are processed separately) - UserFlags = cfg.FontBuilderFlags | extra_font_builder_flags; + UserFlags = src.FontBuilderFlags | extra_font_builder_flags; LoadFlags = 0; if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0) @@ -222,11 +222,11 @@ namespace if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor) LoadFlags |= FT_LOAD_COLOR; - RasterizationDensity = cfg.RasterizerDensity; + RasterizationDensity = src.RasterizerDensity; InvRasterizationDensity = 1.0f / RasterizationDensity; memset(&Info, 0, sizeof(Info)); - SetPixelHeight((uint32_t)cfg.SizePixels); + SetPixelHeight((uint32_t)src.SizePixels); return true; } @@ -443,7 +443,7 @@ struct ImFontBuildDstDataFT bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags) { - IM_ASSERT(atlas->ConfigData.Size > 0); + IM_ASSERT(atlas->Sources.Size > 0); ImFontAtlasBuildInit(atlas); @@ -458,36 +458,36 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u bool src_load_color = false; ImVector src_tmp_array; ImVector dst_tmp_array; - src_tmp_array.resize(atlas->ConfigData.Size); + src_tmp_array.resize(atlas->Sources.Size); dst_tmp_array.resize(atlas->Fonts.Size); memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes()); // 1. Initialize font loading structure, check font data validity - for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++) + for (int src_i = 0; src_i < atlas->Sources.Size; src_i++) { ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - ImFontConfig& cfg = atlas->ConfigData[src_i]; + ImFontConfig& src = atlas->Sources[src_i]; FreeTypeFont& font_face = src_tmp.Font; - IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas)); + IM_ASSERT(src.DstFont && (!src.DstFont->IsLoaded() || src.DstFont->ContainerAtlas == atlas)); - // Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) + // Find index from src.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) src_tmp.DstIndex = -1; for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++) - if (cfg.DstFont == atlas->Fonts[output_i]) + if (src.DstFont == atlas->Fonts[output_i]) src_tmp.DstIndex = output_i; - IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array? + IM_ASSERT(src_tmp.DstIndex != -1); // src.DstFont not pointing within atlas->Fonts[] array? if (src_tmp.DstIndex == -1) return false; // Load font - if (!font_face.InitFont(ft_library, cfg, extra_flags)) + if (!font_face.InitFont(ft_library, src, extra_flags)) return false; // Measure highest codepoints - src_load_color |= (cfg.FontBuilderFlags & ImGuiFreeTypeBuilderFlags_LoadColor) != 0; + src_load_color |= (src.FontBuilderFlags & ImGuiFreeTypeBuilderFlags_LoadColor) != 0; ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault(); + src_tmp.SrcRanges = src.GlyphRanges ? src.GlyphRanges : atlas->GetGlyphRangesDefault(); for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) { // Check for valid range. This may also help detect *some* dangling pointers, because a common @@ -577,7 +577,7 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) { ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - ImFontConfig& cfg = atlas->ConfigData[src_i]; + ImFontConfig& src = atlas->Sources[src_i]; if (src_tmp.GlyphsCount == 0) continue; @@ -585,10 +585,10 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u buf_rects_out_n += src_tmp.GlyphsCount; // Compute multiply table if requested - const bool multiply_enabled = (cfg.RasterizerMultiply != 1.0f); + const bool multiply_enabled = (src.RasterizerMultiply != 1.0f); unsigned char multiply_table[256]; if (multiply_enabled) - ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply); + ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, src.RasterizerMultiply); // Gather the sizes of all rectangles we will need to pack for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) @@ -687,18 +687,18 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u // When merging fonts with MergeMode=true: // - We can have multiple input fonts writing into a same destination font. - // - dst_font->ConfigData is != from cfg which is our source configuration. - ImFontConfig& cfg = atlas->ConfigData[src_i]; - ImFont* dst_font = cfg.DstFont; + // - dst_font->Sources is != from src which is our source configuration. + ImFontConfig& src = atlas->Sources[src_i]; + ImFont* dst_font = src.DstFont; const float ascent = src_tmp.Font.Info.Ascender; const float descent = src_tmp.Font.Info.Descender; - ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent); + ImFontAtlasBuildSetupFont(atlas, dst_font, &src, ascent, descent); if (src_tmp.GlyphsCount == 0) continue; - const float font_off_x = cfg.GlyphOffset.x; - const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent); + const float font_off_x = src.GlyphOffset.x; + const float font_off_y = src.GlyphOffset.y + IM_ROUND(dst_font->Ascent); const int padding = atlas->TexGlyphPadding; for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) @@ -724,7 +724,7 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u float v0 = (ty) / (float)atlas->TexHeight; float u1 = (tx + info.Width) / (float)atlas->TexWidth; float v1 = (ty + info.Height) / (float)atlas->TexHeight; - dst_font->AddGlyph(&cfg, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX * src_tmp.Font.InvRasterizationDensity); + dst_font->AddGlyph(&src, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX * src_tmp.Font.InvRasterizationDensity); ImFontGlyph* dst_glyph = &dst_font->Glyphs.back(); IM_ASSERT(dst_glyph->Codepoint == src_glyph.Codepoint); From a86fcbd9474bb4121f25cbf9196674d79f90f1f1 Mon Sep 17 00:00:00 2001 From: Russ Gibson Date: Wed, 26 Feb 2025 05:38:08 -0800 Subject: [PATCH 0721/2359] Examples: SDL3+SDL_Renderer: removed reference to OpenGL to remove confusion. (#8434) --- examples/example_sdl3_sdlrenderer3/Makefile | 2 +- examples/example_sdl3_sdlrenderer3/main.cpp | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/examples/example_sdl3_sdlrenderer3/Makefile b/examples/example_sdl3_sdlrenderer3/Makefile index 2ca986545..c7ee64fc7 100644 --- a/examples/example_sdl3_sdlrenderer3/Makefile +++ b/examples/example_sdl3_sdlrenderer3/Makefile @@ -44,7 +44,7 @@ endif ifeq ($(OS), Windows_NT) ECHO_MESSAGE = "MinGW" - LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl3` + LIBS += -lgdi32 -limm32 `pkg-config --static --libs sdl3` CXXFLAGS += `pkg-config --cflags sdl3` CFLAGS = $(CXXFLAGS) diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 483350fcb..68078eebd 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -15,11 +15,6 @@ #include "imgui_impl_sdlrenderer3.h" #include #include -#if defined(IMGUI_IMPL_OPENGL_ES2) -#include -#else -#include -#endif #ifdef __EMSCRIPTEN__ #include "../libs/emscripten/emscripten_mainloop_stub.h" @@ -36,7 +31,7 @@ int main(int, char**) } // Create window with SDL_Renderer graphics context - Uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; + Uint32 window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", 1280, 720, window_flags); if (window == nullptr) { From 242d856ede78544a6ed2debea3afecad884630c6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Feb 2025 14:40:41 +0100 Subject: [PATCH 0722/2359] Examples: SDL3+SDL_Renderer: removed reference to OpenGL to remove confusion. (#8434) Amend --- examples/example_sdl3_sdlrenderer3/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_sdl3_sdlrenderer3/Makefile b/examples/example_sdl3_sdlrenderer3/Makefile index c7ee64fc7..1976fa924 100644 --- a/examples/example_sdl3_sdlrenderer3/Makefile +++ b/examples/example_sdl3_sdlrenderer3/Makefile @@ -34,7 +34,7 @@ endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" - LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl3-config --libs` + LIBS += -framework Cocoa -framework IOKit -framework CoreVideo `sdl3-config --libs` LIBS += -L/usr/local/lib -L/opt/local/lib CXXFLAGS += `pkg-config sdl3 --cflags` From 4f4fb1d220d31ca8b04163ed80bed7108e6429bc Mon Sep 17 00:00:00 2001 From: "Jose L. Hidalgo (PpluX)" Date: Sat, 22 Feb 2025 12:47:30 +0100 Subject: [PATCH 0723/2359] Backends: WebGPU: update code for latest webgpu-native changes. (#8426) --- backends/imgui_impl_wgpu.cpp | 22 ++++++++++++---------- docs/CHANGELOG.txt | 3 ++- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index a81662d84..36d053e2b 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-26: Update for latest webgpu-native changes. // 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083) // 2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap. @@ -65,7 +66,7 @@ using WGPUProgrammableStageDescriptor = WGPUComputeState; #endif // Dear ImGui prototypes from imgui_internal.h -extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0); +extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed); #define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro). // WebGPU data @@ -267,7 +268,7 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); -#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) WGPUShaderSourceWGSL wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL; wgsl_desc.code = { wgsl_source, WGPU_STRLEN }; @@ -282,7 +283,8 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c WGPUProgrammableStageDescriptor stage_desc = {}; stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc); -#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN + +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) stage_desc.entryPoint = { "main", WGPU_STRLEN }; #else stage_desc.entryPoint = "main"; @@ -399,7 +401,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder { nullptr, "Dear ImGui Vertex buffer", -#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) WGPU_STRLEN, #endif WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex, @@ -426,7 +428,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder { nullptr, "Dear ImGui Index buffer", -#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) WGPU_STRLEN, #endif WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index, @@ -539,7 +541,7 @@ static void ImGui_ImplWGPU_CreateFontsTexture() // Upload texture to graphics system { WGPUTextureDescriptor tex_desc = {}; -#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) tex_desc.label = { "Dear ImGui Font Texture", WGPU_STRLEN }; #else tex_desc.label = "Dear ImGui Font Texture"; @@ -567,12 +569,12 @@ static void ImGui_ImplWGPU_CreateFontsTexture() // Upload texture data { - WGPUImageCopyTexture dst_view = {}; + WGPUTexelCopyTextureInfo dst_view = {}; dst_view.texture = bd->renderResources.FontTexture; dst_view.mipLevel = 0; dst_view.origin = { 0, 0, 0 }; dst_view.aspect = WGPUTextureAspect_All; - WGPUTextureDataLayout layout = {}; + WGPUTexelCopyBufferLayout layout = {}; layout.offset = 0; layout.bytesPerRow = width * size_pp; layout.rowsPerImage = height; @@ -606,7 +608,7 @@ static void ImGui_ImplWGPU_CreateUniformBuffer() { nullptr, "Dear ImGui Uniform buffer", -#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) WGPU_STRLEN, #endif WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform, @@ -714,7 +716,7 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() // Create depth-stencil State WGPUDepthStencilState depth_stencil_state = {}; depth_stencil_state.format = bd->depthStencilFormat; -#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) depth_stencil_state.depthWriteEnabled = WGPUOptionalBool_False; #else depth_stencil_state.depthWriteEnabled = false; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d5c4ded32..b3af5d94c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -104,8 +104,9 @@ Other changes: Default to header version if unspecified. (#8326, #8365) [@mklefrancois] - Backends: Vulkan: Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" (without -KHR suffix) on API 1.3. (#8326, #8365) [@mklefrancois] -- Backends: WebGPU: Fix for DAWN API rename WGPUProgrammableStageDescriptor -> WGPUComputeState. +- Backends: WebGPU: Fix for DAWN API change WGPUProgrammableStageDescriptor -> WGPUComputeState. [@PhantomCloak] (#8369) +- Backends: WebGPU: Fix for webgpu-native API changes. (#8426) [@pplux] ----------------------------------------------------------------------- From 6aa0810de5dad4add4e73ff6352df63429f921ee Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Feb 2025 15:10:28 +0100 Subject: [PATCH 0724/2359] Backends: WebGPU: update code for latest webgpu-native changes. Amend. (#8426) --- backends/imgui_impl_wgpu.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 36d053e2b..45eaeba64 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -493,7 +493,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder { // Bind custom texture ImTextureID tex_id = pcmd->GetTexID(); - ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id)); + ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id), 0); auto bind_group = bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash); if (bind_group) { @@ -755,7 +755,7 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], bd->renderResources.FontTextureView); bd->renderResources.ImageBindGroup = image_bind_group; bd->renderResources.ImageBindGroupLayout = bg_layouts[1]; - bd->renderResources.ImageBindGroups.SetVoidPtr(ImHashData(&bd->renderResources.FontTextureView, sizeof(ImTextureID)), image_bind_group); + bd->renderResources.ImageBindGroups.SetVoidPtr(ImHashData(&bd->renderResources.FontTextureView, sizeof(ImTextureID), 0), image_bind_group); SafeRelease(vertex_shader_desc.module); SafeRelease(pixel_shader_desc.module); From 9996a2d51b47e8679936f58de31f6df382a83689 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Feb 2025 15:16:38 +0100 Subject: [PATCH 0725/2359] Backends: WebGPU: update code for latest webgpu-native changes. Fix for Emscripten. (#8426) --- backends/imgui_impl_wgpu.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 45eaeba64..4fffa23a5 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -569,12 +569,20 @@ static void ImGui_ImplWGPU_CreateFontsTexture() // Upload texture data { +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) WGPUTexelCopyTextureInfo dst_view = {}; +#else + WGPUImageCopyTexture dst_view = {}; +#endif dst_view.texture = bd->renderResources.FontTexture; dst_view.mipLevel = 0; dst_view.origin = { 0, 0, 0 }; dst_view.aspect = WGPUTextureAspect_All; +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) WGPUTexelCopyBufferLayout layout = {}; +#else + WGPUTextureDataLayout layout = {}; +#endif layout.offset = 0; layout.bytesPerRow = width * size_pp; layout.rowsPerImage = height; From aaacb01b8d4441453928116240b5041625d43fbf Mon Sep 17 00:00:00 2001 From: "Jose L. Hidalgo (PpluX)" Date: Wed, 26 Feb 2025 15:19:56 +0100 Subject: [PATCH 0726/2359] Backends: WebGPU: Recreate image bind groups during render. (#8426, #8046, #7765, #8027) --- backends/imgui_impl_wgpu.cpp | 33 ++++++++++++++++----------------- docs/CHANGELOG.txt | 2 ++ 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 4fffa23a5..b04ac3bb7 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -17,7 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-02-26: Update for latest webgpu-native changes. +// 2025-02-26: Recreate image bind groups during render. (#8426, #8046, #7765, #8027) + Update for latest webgpu-native changes. // 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083) // 2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap. @@ -78,7 +78,6 @@ struct RenderResources WGPUBuffer Uniforms = nullptr; // Shader uniforms WGPUBindGroup CommonBindGroup = nullptr; // Resources bind-group to bind the common resources to pipeline ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map) - WGPUBindGroup ImageBindGroup = nullptr; // Default font-resource of Dear ImGui WGPUBindGroupLayout ImageBindGroupLayout = nullptr; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM }; @@ -252,7 +251,6 @@ static void SafeRelease(RenderResources& res) SafeRelease(res.Sampler); SafeRelease(res.Uniforms); SafeRelease(res.CommonBindGroup); - SafeRelease(res.ImageBindGroup); SafeRelease(res.ImageBindGroupLayout); }; @@ -494,17 +492,13 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder // Bind custom texture ImTextureID tex_id = pcmd->GetTexID(); ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id), 0); - auto bind_group = bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash); - if (bind_group) + WGPUBindGroup bind_group = (WGPUBindGroup)bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash); + if (!bind_group) { - wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr); - } - else - { - WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id); - bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group); - wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, nullptr); + bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id); + bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, bind_group); } + wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr); // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); @@ -526,6 +520,16 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder global_idx_offset += draw_list->IdxBuffer.Size; global_vtx_offset += draw_list->VtxBuffer.Size; } + + // Remove all ImageBindGroups + ImGuiStorage& image_bind_groups = bd->renderResources.ImageBindGroups; + for (int i = 0; i < image_bind_groups.Data.Size; i++) + { + WGPUBindGroup bind_group = (WGPUBindGroup)image_bind_groups.Data[i].val_p; + SafeRelease(bind_group); + } + image_bind_groups.Data.resize(0); + platform_io.Renderer_RenderState = nullptr; } @@ -759,11 +763,7 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry); common_bg_descriptor.entries = common_bg_entries; bd->renderResources.CommonBindGroup = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor); - - WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], bd->renderResources.FontTextureView); - bd->renderResources.ImageBindGroup = image_bind_group; bd->renderResources.ImageBindGroupLayout = bg_layouts[1]; - bd->renderResources.ImageBindGroups.SetVoidPtr(ImHashData(&bd->renderResources.FontTextureView, sizeof(ImTextureID), 0), image_bind_group); SafeRelease(vertex_shader_desc.module); SafeRelease(pixel_shader_desc.module); @@ -823,7 +823,6 @@ bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info) bd->renderResources.Uniforms = nullptr; bd->renderResources.CommonBindGroup = nullptr; bd->renderResources.ImageBindGroups.Data.reserve(100); - bd->renderResources.ImageBindGroup = nullptr; bd->renderResources.ImageBindGroupLayout = nullptr; // Create buffers with a default size (they will later be grown as needed) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b3af5d94c..ff249c140 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -104,6 +104,8 @@ Other changes: Default to header version if unspecified. (#8326, #8365) [@mklefrancois] - Backends: Vulkan: Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" (without -KHR suffix) on API 1.3. (#8326, #8365) [@mklefrancois] +- Backends: WebGPU: Recreate image bind groups during render to allow reuse of + WGPUTextureView pointers. (#8426, #8046, #7765, #8027) [@pplux, @Jairard] - Backends: WebGPU: Fix for DAWN API change WGPUProgrammableStageDescriptor -> WGPUComputeState. [@PhantomCloak] (#8369) - Backends: WebGPU: Fix for webgpu-native API changes. (#8426) [@pplux] From aa83d5d455dcab4b65cca71efd6291f943feea67 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Feb 2025 15:34:31 +0100 Subject: [PATCH 0727/2359] Backends: SDL2, SDL3: Only start SDL_CaptureMouse() when mouse is being dragged. (#6410, #3650) To mitigate issues with e.g. Linux debuggers not claiming capture back. --- backends/imgui_impl_sdl2.cpp | 11 +++++++++-- backends/imgui_impl_sdl3.cpp | 11 +++++++++-- docs/CHANGELOG.txt | 2 ++ 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 361fc3b57..6256b4ddd 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. @@ -609,8 +610,14 @@ static void ImGui_ImplSDL2_UpdateMouseData() // We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below) #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE - // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside - SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE); + // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside. + // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to migitate the issue we wait until mouse has moved to begin capture. + bool want_capture = false; + for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) + if (ImGui::IsMouseDragging(button_n, 1.0f)) + want_capture = true; + SDL_CaptureMouse(want_capture ? SDL_TRUE : SDL_FALSE); + SDL_Window* focused_window = SDL_GetKeyboardFocus(); const bool is_app_focused = (bd->Window == focused_window); #else diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index d2433793e..2d8027184 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. @@ -574,8 +575,14 @@ static void ImGui_ImplSDL3_UpdateMouseData() // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below) #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE - // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside - SDL_CaptureMouse(bd->MouseButtonsDown != 0); + // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside. + // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to migitate the issue we wait until mouse has moved to begin capture. + bool want_capture = false; + for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) + if (ImGui::IsMouseDragging(button_n, 1.0f)) + want_capture = true; + SDL_CaptureMouse(want_capture); + SDL_Window* focused_window = SDL_GetKeyboardFocus(); const bool is_app_focused = (bd->Window == focused_window); #else diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ff249c140..5a1b63ad2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -95,6 +95,8 @@ Other changes: and ImGuiMouseCursor_Progress cursors. - Backends: SDL2, SDL3: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. (#8425, #8407) [@TheMode] +- Backends: SDL2, SDL3: Only start SDL_CaptureMouse() when mouse is being dragged, + to mitigate issues with e.g. Linux debuggers not claiming capture back. (#6410, #3650) - Backends: OpenGL3: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) - Backends: DirectX12: Fixed an issue where pre-1.91.5 legacy ImGui_ImplDX12_Init() From 8bd3e20c86b1541f1da2c1f1d2444220432193fa Mon Sep 17 00:00:00 2001 From: Alan Date: Wed, 26 Feb 2025 18:06:31 -0500 Subject: [PATCH 0728/2359] Backends: WebGPU: include imgui.h before backend check (#8437) --- backends/imgui_impl_wgpu.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index b04ac3bb7..4bf03e8f1 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -41,6 +41,8 @@ // 2021-02-18: Change blending equation to preserve alpha in output buffer. // 2021-01-28: Initial version. +#include "imgui.h" + // When targeting native platforms (i.e. NOT emscripten), one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN // or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details. #ifndef __EMSCRIPTEN__ @@ -53,7 +55,6 @@ #endif #endif -#include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_wgpu.h" #include From cdafefd4be389ef4c6747b102086278b2cc355c3 Mon Sep 17 00:00:00 2001 From: Alan Date: Thu, 27 Feb 2025 07:47:33 -0500 Subject: [PATCH 0729/2359] Backends: WebGPU: Add nextInChain field for VertexAttributes under Dawn (#8438) --- backends/imgui_impl_wgpu.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 4bf03e8f1..3187be29a 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -687,9 +687,15 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() // Vertex input configuration WGPUVertexAttribute attribute_desc[] = { +#ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN + { nullptr, WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 }, + { nullptr, WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 }, + { nullptr, WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 }, +#else { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 }, { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 }, { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 }, +#endif }; WGPUVertexBufferLayout buffer_layouts[1]; From 494ea57b65325f00165da10e6b57b4f295a65bca Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Feb 2025 19:28:01 +0100 Subject: [PATCH 0730/2359] Image: removed 'tint_col', 'border_col' parameters from Image(). Added ImageWithBg(). Added style.ImageBorderSize, ImGuiStyleVar_ImageBorderSize. (#8131, #8238) Displaying a black background behind Font Atlas texture. --- docs/CHANGELOG.txt | 18 ++++++++++++++++++ imgui.cpp | 23 ++++++++++++++++++----- imgui.h | 11 ++++++++--- imgui_demo.cpp | 11 +++++------ imgui_internal.h | 1 - imgui_widgets.cpp | 30 +++++++++++++++++++++++++----- 6 files changed, 74 insertions(+), 20 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5a1b63ad2..9e797e3ec 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,22 @@ HOW TO UPDATE? Breaking changes: +- Image: removed 'tint_col' and 'border_col' parameter from Image() function. (#8131, #8238) + - Old function signature: + void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); + - New function signatures: + void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1)); + void ImageWithBg(ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 bg_col = (0,0,0,0), ImVec4 tint_col = (1,1,1,1)); + - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton(). + - New behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize. + - Old behavior altered border size (and therefore layout) based on border color's + alpha, which caused variety of problems. + - Old behavior used a fixed value of 1.0f for border size which was not tweakable. + - Kept legacy signature (will obsolete), which mimics the old behavior, + but uses Max(1.0f, style.ImageBorderSize) when border_col is specified. + - Added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. + It was impossible to add 'bg_col' to Image() with a parameter order consistent with + other functions, so we decided to remove 'tint_col' and introduce ImageWithBg(). - Renamed ImFontConfig::GlyphExtraSpacing.x option to GlyphExtraAdvanceX. (#242) - Renamed style.TabMinWidthForCloseButton to style.TabCloseButtonMinWidthUnselected. - Backends: Vulkan: Added 'uint32_t api_version' argument to ImGui_ImplVulkan_LoadFunctions(). @@ -70,6 +86,8 @@ Other changes: - Tables: tamed some .ini settings optimizations to more accurately allow overwriting/hot-reloading settings in more situations. (#7934) - Tables, Error Handling: Recovery from invalid index in TableSetColumnIndex(). (#1651) +- Image: Added ImageWithBg() variant with bg color and tint color. (#8131, #8238) +- Image, Style: Added style.ImageBorderSize, ImGuiStyleVar_ImageBorderSize. (#8131, #8238) - Selectable: Fixed horizontal label alignment with SelectableTextAlign.x > 0 and specifying a selectable size. (#8338) - Tabs, Style: made the Close Button of selected tabs always visible by default, diff --git a/imgui.cpp b/imgui.cpp index 64514028f..6e038fad8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -431,6 +431,15 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238) + - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); + - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1)); + - new: void ImageWithBg(ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 bg_col = (0,0,0,0), ImVec4 tint_col = (1,1,1,1)); + - TL;DR: 'border_col' had misleading side-effect on layout, 'bg_col' was missing, parameter order couldn't be consistent with ImageButton(). + - new behavior always use ImGuiCol_Border color + style.ImageBorderSize / ImGuiStyleVar_ImageBorderSize. + - old behavior altered border size (and therefore layout) based on border color's alpha, which caused variety of problems + old behavior a fixed 1.0f for border size which was not tweakable. + - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified. + - added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. It was impossible to add 'bg_col' to Image() with a parameter order consistent with other functions, so we decided to remove 'tint_col' and introduce ImageWithBg(). - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX. - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. @@ -1338,6 +1347,7 @@ ImGuiStyle::ImGuiStyle() GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + ImageBorderSize = 0.0f; // Thickness of border around tabs. TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. @@ -1395,6 +1405,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) GrabMinSize = ImTrunc(GrabMinSize * scale_factor); GrabRounding = ImTrunc(GrabRounding * scale_factor); LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); + ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected; TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; @@ -3393,6 +3404,7 @@ static const ImGuiDataVarInfo GStyleVarsInfo[] = { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding + { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize @@ -15422,11 +15434,12 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) { ImGuiContext& g = *GImGui; - ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; - Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons - ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border); - Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col); + PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); + ImVec2 image_pos = GetCursorScreenPos(); + ImVec2 image_size((float)atlas->TexWidth, (float)atlas->TexHeight); + GetWindowDrawList()->AddRectFilled(image_pos, image_pos + image_size + ImVec2(g.Style.ImageBorderSize, g.Style.ImageBorderSize), IM_COL32(0, 0, 0, 255)); + Image(atlas->TexID, image_size); + PopStyleVar(); TreePop(); } } diff --git a/imgui.h b/imgui.h index 1bdc2cb10..ee9697ea8 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.9 WIP" -#define IMGUI_VERSION_NUM 19184 +#define IMGUI_VERSION_NUM 19185 #define IMGUI_HAS_TABLE /* @@ -566,9 +566,10 @@ namespace ImGui // Widgets: Images // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. - // - Note that Image() may add +2.0f to provided size if a border is visible, ImageButton() adds style.FramePadding*2.0f to provided size. + // - Image() pads adds style.ImageBorderSize on each side, ImageButton() adds style.FramePadding on each side. // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. - IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), const ImVec4& border_col = ImVec4(0, 0, 0, 0)); + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1)); + IMGUI_API void ImageWithBg(ImTextureID user_texture_id, 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, ImTextureID user_texture_id, 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) @@ -1714,6 +1715,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding ImGuiStyleVar_GrabMinSize, // float GrabMinSize ImGuiStyleVar_GrabRounding, // float GrabRounding + ImGuiStyleVar_ImageBorderSize, // float ImageBorderSize ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_TabBorderSize, // float TabBorderSize ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize @@ -2170,6 +2172,7 @@ struct ImGuiStyle float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + float ImageBorderSize; // Thickness of border around Image() calls. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. float TabCloseButtonMinWidthSelected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. @@ -3614,6 +3617,8 @@ struct ImGuiPlatformImeData #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.91.9 (from February 2025) + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- border_col was removed in favor of ImGuiCol_ImageBorder. // OBSOLETED in 1.91.0 (from July 2024) static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } static inline void PopButtonRepeat() { PopItemFlag(); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3be864724..4372dfb45 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1348,15 +1348,12 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) float my_tex_w = (float)io.Fonts->TexWidth; float my_tex_h = (float)io.Fonts->TexHeight; { - static bool use_text_color_for_tint = false; - ImGui::Checkbox("Use Text Color for Tint", &use_text_color_for_tint); ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); ImVec2 pos = ImGui::GetCursorScreenPos(); ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right - ImVec4 tint_col = use_text_color_for_tint ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint - ImVec4 border_col = ImGui::GetStyleColorVec4(ImGuiCol_Border); - ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col); + ImGui::PushStyleVar(ImGuiStyleVar_ImageBorderSize, IM_MAX(1.0f, ImGui::GetStyle().ImageBorderSize)); + ImGui::ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); if (ImGui::BeginItemTooltip()) { float region_sz = 32.0f; @@ -1371,9 +1368,10 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h); ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h); - ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, tint_col, border_col); + ImGui::ImageWithBg(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); ImGui::EndTooltip(); } + ImGui::PopStyleVar(); } IMGUI_DEMO_MARKER("Widgets/Images/Textured buttons"); @@ -8031,6 +8029,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat2("SeparatorTextAlign", (float*)&style.SeparatorTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SeparatorText("Tooltips"); for (int n = 0; n < 2; n++) diff --git a/imgui_internal.h b/imgui_internal.h index c70bb999c..985f8b189 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1998,7 +1998,6 @@ struct ImGuiMetricsConfig bool ShowDrawCmdMesh = true; bool ShowDrawCmdBoundingBoxes = true; bool ShowTextEncodingViewer = false; - bool ShowAtlasTintedWithTextColor = false; int ShowWindowsRectsType = -1; int ShowTablesRectsType = -1; int HighlightMonitorIdx = -1; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f011805f9..8d5aa9581 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1062,25 +1062,45 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. -void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +void ImGui::ImageWithBg(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) { + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - const float border_size = (border_col.w > 0.0f) ? 1.0f : 0.0f; - const ImVec2 padding(border_size, border_size); + const ImVec2 padding(g.Style.ImageBorderSize, g.Style.ImageBorderSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f); ItemSize(bb); if (!ItemAdd(bb, 0)) return; // Render - if (border_size > 0.0f) - window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f, ImDrawFlags_None, border_size); + if (g.Style.ImageBorderSize > 0.0f) + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), 0.0f, ImDrawFlags_None, g.Style.ImageBorderSize); + if (bg_col.w > 0.0f) + window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); } +void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1) +{ + ImageWithBg(user_texture_id, image_size, uv0, uv1); +} + +// 1.91.9 (February 2025) removed 'tint_col' and 'border_col' parameters, made border size not depend on color value. (#8131, #8238) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +{ + ImGuiContext& g = *GImGui; + PushStyleVar(ImGuiStyleVar_ImageBorderSize, (border_col.w > 0.0f) ? ImMax(1.0f, g.Style.ImageBorderSize) : 0.0f); // Preserve legacy behavior where border is always visible when border_col's Alpha is >0.0f + PushStyleColor(ImGuiCol_Border, border_col); + ImageWithBg(user_texture_id, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col); + PopStyleColor(); + PopStyleVar(); +} +#endif + bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; From 482a1f50b61ee71b515a5a4a1c5f6a998214780a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Feb 2025 16:08:51 +0100 Subject: [PATCH 0731/2359] Internals: rename ImGuiDataVarInfo to ImGuiStyleVarInfo. Move ImGuiStyleMod, ImGuiColorMod to own section. # Conflicts: # imgui.cpp --- imgui.cpp | 88 ++++++++++++++++++++++++------------------------ imgui.h | 2 ++ imgui_internal.h | 49 +++++++++++++++------------ 3 files changed, 73 insertions(+), 66 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6e038fad8..30477001f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3380,45 +3380,45 @@ void ImGui::PopStyleColor(int count) } } -static const ImGuiDataVarInfo GStyleVarsInfo[] = +static const ImGuiStyleVarInfo GStyleVarsInfo[] = { - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign - { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign - { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign + { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding }; -const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx) +const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx) { IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT); IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarsInfo) == ImGuiStyleVar_COUNT); @@ -3428,7 +3428,7 @@ const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx) void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { ImGuiContext& g = *GImGui; - const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 1) { IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); @@ -3442,7 +3442,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x) { ImGuiContext& g = *GImGui; - const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) { IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); @@ -3456,7 +3456,7 @@ void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x) void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y) { ImGuiContext& g = *GImGui; - const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) { IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); @@ -3470,7 +3470,7 @@ void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y) void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { ImGuiContext& g = *GImGui; - const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx); + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) { IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); @@ -3493,10 +3493,10 @@ void ImGui::PopStyleVar(int count) { // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it. ImGuiStyleMod& backup = g.StyleVarStack.back(); - const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx); - void* data = info->GetVarPtr(&g.Style); - if (info->DataType == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } - else if (info->DataType == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(backup.VarIdx); + void* data = var_info->GetVarPtr(&g.Style); + if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } + else if (var_info->DataType == ImGuiDataType_Float && var_info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } g.StyleVarStack.pop_back(); count--; } diff --git a/imgui.h b/imgui.h index ee9697ea8..caf8088b2 100644 --- a/imgui.h +++ b/imgui.h @@ -2195,6 +2195,8 @@ struct ImGuiStyle bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + + // Colors ImVec4 Colors[ImGuiCol_COUNT]; // Behaviors diff --git a/imgui_internal.h b/imgui_internal.h index 985f8b189..f896171cd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -14,6 +14,7 @@ Index of this file: // [SECTION] Macros // [SECTION] Generic helpers // [SECTION] ImDrawList support +// [SECTION] Style support // [SECTION] Data types support // [SECTION] Widgets support: flags, enums, data structures // [SECTION] Popup support @@ -145,7 +146,6 @@ struct ImGuiBoxSelectState; // Box-selection state (currently used by mu struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it struct ImGuiContext; // Main Dear ImGui context struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine -struct ImGuiDataVarInfo; // Variable information (e.g. to access style variables from an enum) struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum struct ImGuiDeactivatedItemData; // Data for IsItemDeactivated()/IsItemDeactivatedAfterEdit() function. struct ImGuiErrorRecoveryState; // Storage of stack sizes for error handling and recovery @@ -166,6 +166,7 @@ struct ImGuiOldColumns; // Storage data for a columns set for legacy struct ImGuiPopupData; // Storage for current popup stack struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it +struct ImGuiStyleVarInfo; // Style variable information (e.g. to access style variables from an enum) struct ImGuiTabBar; // Storage for a tab bar struct ImGuiTabItem; // Storage for a tab item (within a tab bar) struct ImGuiTable; // Storage for a table @@ -809,17 +810,38 @@ struct ImDrawDataBuilder }; //----------------------------------------------------------------------------- -// [SECTION] Data types support +// [SECTION] Style support //----------------------------------------------------------------------------- -struct ImGuiDataVarInfo +struct ImGuiStyleVarInfo { - ImGuiDataType DataType : 8; ImU32 Count : 8; // 1+ + ImGuiDataType DataType : 8; ImU32 Offset : 16; // Offset in parent structure void* GetVarPtr(void* parent) const { return (void*)((unsigned char*)parent + Offset); } }; +// Stacked color modifier, backup of modified data so we can restore it +struct ImGuiColorMod +{ + ImGuiCol Col; + ImVec4 BackupValue; +}; + +// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. +struct ImGuiStyleMod +{ + ImGuiStyleVar VarIdx; + union { int BackupInt[2]; float BackupFloat[2]; }; + ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Data types support +//----------------------------------------------------------------------------- + struct ImGuiDataTypeStorage { ImU8 Data[8]; // Opaque storage to fit any data up to ImGuiDataType_COUNT @@ -1038,23 +1060,6 @@ enum ImGuiPlotType ImGuiPlotType_Histogram, }; -// Stacked color modifier, backup of modified data so we can restore it -struct ImGuiColorMod -{ - ImGuiCol Col; - ImVec4 BackupValue; -}; - -// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. -struct ImGuiStyleMod -{ - ImGuiStyleVar VarIdx; - union { int BackupInt[2]; float BackupFloat[2]; }; - ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } - ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } - ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } -}; - // Storage data for BeginComboPreview()/EndComboPreview() struct IMGUI_API ImGuiComboPreviewData { @@ -3114,7 +3119,7 @@ namespace ImGui IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); // Parameter stacks (shared) - IMGUI_API const ImGuiDataVarInfo* GetStyleVarInfo(ImGuiStyleVar idx); + IMGUI_API const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx); IMGUI_API void BeginDisabledOverrideReenable(); IMGUI_API void EndDisabledOverrideReenable(); From 1aab00da8589d06ed861a0b40e9dfaeff791084f Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Feb 2025 21:55:17 +0100 Subject: [PATCH 0732/2359] Misc shallow tweaks/tidying up. (#8446) --- backends/imgui_impl_dx10.cpp | 11 ++++------- backends/imgui_impl_dx11.cpp | 11 ++++------- backends/imgui_impl_dx12.cpp | 27 +++++++++------------------ backends/imgui_impl_metal.h | 1 + backends/imgui_impl_opengl3.cpp | 2 +- backends/imgui_impl_osx.h | 1 + 6 files changed, 20 insertions(+), 33 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 5471eef53..801983211 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -87,8 +87,7 @@ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); // Setup viewport - D3D10_VIEWPORT vp; - memset(&vp, 0, sizeof(D3D10_VIEWPORT)); + D3D10_VIEWPORT vp = {}; vp.Width = (UINT)draw_data->DisplaySize.x; vp.Height = (UINT)draw_data->DisplaySize.y; vp.MinDepth = 0.0f; @@ -152,8 +151,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) { if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; - D3D10_BUFFER_DESC desc; - memset(&desc, 0, sizeof(D3D10_BUFFER_DESC)); + D3D10_BUFFER_DESC desc = {}; desc.Usage = D3D10_USAGE_DYNAMIC; desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert); desc.BindFlags = D3D10_BIND_VERTEX_BUFFER; @@ -167,8 +165,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) { if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; - D3D10_BUFFER_DESC desc; - memset(&desc, 0, sizeof(D3D10_BUFFER_DESC)); + D3D10_BUFFER_DESC desc = {}; desc.Usage = D3D10_USAGE_DYNAMIC; desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D10_BIND_INDEX_BUFFER; @@ -431,7 +428,7 @@ bool ImGui_ImplDX10_CreateDeviceObjects() // Create the constant buffer { - D3D10_BUFFER_DESC desc; + D3D10_BUFFER_DESC desc = {}; desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX10); desc.Usage = D3D10_USAGE_DYNAMIC; desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index b38fece26..9f3958881 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -90,8 +90,7 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); // Setup viewport - D3D11_VIEWPORT vp; - memset(&vp, 0, sizeof(D3D11_VIEWPORT)); + D3D11_VIEWPORT vp = {}; vp.Width = draw_data->DisplaySize.x; vp.Height = draw_data->DisplaySize.y; vp.MinDepth = 0.0f; @@ -158,8 +157,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) { if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; - D3D11_BUFFER_DESC desc; - memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); + D3D11_BUFFER_DESC desc = {}; desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert); desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; @@ -172,8 +170,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) { if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; - D3D11_BUFFER_DESC desc; - memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); + D3D11_BUFFER_DESC desc = {}; desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D11_BIND_INDEX_BUFFER; @@ -447,7 +444,7 @@ bool ImGui_ImplDX11_CreateDeviceObjects() // Create the constant buffer { - D3D11_BUFFER_DESC desc; + D3D11_BUFFER_DESC desc = {}; desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11); desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 8449832c5..e9a2c119c 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -137,8 +137,7 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic } // Setup viewport - D3D12_VIEWPORT vp; - memset(&vp, 0, sizeof(D3D12_VIEWPORT)); + D3D12_VIEWPORT vp = {}; vp.Width = draw_data->DisplaySize.x; vp.Height = draw_data->DisplaySize.y; vp.MinDepth = 0.0f; @@ -149,14 +148,12 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic // Bind shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; - D3D12_VERTEX_BUFFER_VIEW vbv; - memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW)); + D3D12_VERTEX_BUFFER_VIEW vbv = {}; vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset; vbv.SizeInBytes = fr->VertexBufferSize * stride; vbv.StrideInBytes = stride; command_list->IASetVertexBuffers(0, 1, &vbv); - D3D12_INDEX_BUFFER_VIEW ibv; - memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW)); + D3D12_INDEX_BUFFER_VIEW ibv = {}; ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress(); ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx); ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; @@ -196,13 +193,11 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL { SafeRelease(fr->VertexBuffer); fr->VertexBufferSize = draw_data->TotalVtxCount + 5000; - D3D12_HEAP_PROPERTIES props; - memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); + D3D12_HEAP_PROPERTIES props = {}; props.Type = D3D12_HEAP_TYPE_UPLOAD; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - D3D12_RESOURCE_DESC desc; - memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC)); + D3D12_RESOURCE_DESC desc = {}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert); desc.Height = 1; @@ -219,13 +214,11 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL { SafeRelease(fr->IndexBuffer); fr->IndexBufferSize = draw_data->TotalIdxCount + 10000; - D3D12_HEAP_PROPERTIES props; - memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); + D3D12_HEAP_PROPERTIES props = {}; props.Type = D3D12_HEAP_TYPE_UPLOAD; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - D3D12_RESOURCE_DESC desc; - memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC)); + D3D12_RESOURCE_DESC desc = {}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx); desc.Height = 1; @@ -333,8 +326,7 @@ static void ImGui_ImplDX12_CreateFontsTexture() // Upload texture to graphics system ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture; { - D3D12_HEAP_PROPERTIES props; - memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); + D3D12_HEAP_PROPERTIES props = {}; props.Type = D3D12_HEAP_TYPE_DEFAULT; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; @@ -561,8 +553,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. - D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc; - memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC)); + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.NodeMask = 1; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; psoDesc.pRootSignature = bd->pRootSignature; diff --git a/backends/imgui_impl_metal.h b/backends/imgui_impl_metal.h index 351c2eff7..d46998269 100644 --- a/backends/imgui_impl_metal.h +++ b/backends/imgui_impl_metal.h @@ -13,6 +13,7 @@ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp +#pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 14ae90a7e..1311d1bc9 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -284,7 +284,7 @@ bool ImGui_ImplOpenGL3_InitLoader() { // Initialize our loader #ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W - if (glGetIntegerv == NULL && imgl3wInit() != 0) + if (glGetIntegerv == nullptr && imgl3wInit() != 0) { fprintf(stderr, "Failed to initialize OpenGL loader!\n"); return false; diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h index 9d0aec07a..5d4dd8d41 100644 --- a/backends/imgui_impl_osx.h +++ b/backends/imgui_impl_osx.h @@ -21,6 +21,7 @@ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp +#pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE From 9c2876b9f8f3859951390f27186527393001fe20 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Feb 2025 22:04:56 +0100 Subject: [PATCH 0733/2359] ShowFontAtlas() uses ImageWithBg(). (#8131, #8238) Amend 494ea57 --- imgui.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 30477001f..64d447be3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15435,10 +15435,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) { ImGuiContext& g = *GImGui; PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); - ImVec2 image_pos = GetCursorScreenPos(); - ImVec2 image_size((float)atlas->TexWidth, (float)atlas->TexHeight); - GetWindowDrawList()->AddRectFilled(image_pos, image_pos + image_size + ImVec2(g.Style.ImageBorderSize, g.Style.ImageBorderSize), IM_COL32(0, 0, 0, 255)); - Image(atlas->TexID, image_size); + ImageWithBg(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); PopStyleVar(); TreePop(); } From c5ade6591e39216ec950136a6d8e3e3274f2bddf Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 2 Mar 2025 13:39:29 +0100 Subject: [PATCH 0734/2359] TextLink(), TextLinkOpenURL(): fixed honoring text baseline alignment. (#8451, #7660) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9e797e3ec..f7241d7de 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -99,6 +99,8 @@ Other changes: - Default for unselected tabs: TabCloseButtonMinWidthUnselected = 0.0f (visible when hovered) - Tabs: fixed middle-mouse-button to close tab not checking that close button is hovered, merely it's visibility. (#8399, #8387) [@nicovanbentum] +- TextLink(), TextLinkOpenURL(): fixed honoring text baseline alignment. + (#8451, #7660) [@achabense] - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] - Debug Tools: Added io.ConfigDebugHighlightIdConflictsShowItemPicker (defaults to true) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8d5aa9581..76dabb8f9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1444,7 +1444,7 @@ bool ImGui::TextLink(const char* label) const ImGuiID id = window->GetID(label); const char* label_end = FindRenderedTextEnd(label); - ImVec2 pos = window->DC.CursorPos; + ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); ImVec2 size = CalcTextSize(label, label_end, true); ImRect bb(pos, pos + size); ItemSize(size, 0.0f); From 4819eae8674209f7ddf70cd9a8b2e10528405fff Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 2 Mar 2025 14:15:11 +0100 Subject: [PATCH 0735/2359] Clipper: Fixed an issue where passing an out of bound index to IncludeItemByIndex() could incorrectly offset the final cursor. One case where it would manifest was calling Combo() with an out of range index. (#8450) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 8 ++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f7241d7de..0fd46d378 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -103,6 +103,9 @@ Other changes: (#8451, #7660) [@achabense] - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] +- Clipper: Fixed an issue where passing an out of bound index to IncludeItemByIndex() + could incorrectly offset the final cursor, even if that index was not iterated through. + One case where it would manifest was calling Combo() with an out of range index. (#8450) - Debug Tools: Added io.ConfigDebugHighlightIdConflictsShowItemPicker (defaults to true) to allow disabled Item Picker suggestion in user facing builds. (#7961, #7669) - Misc: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursors diff --git a/imgui.cpp b/imgui.cpp index 64d447be3..77e3c1d36 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3258,11 +3258,11 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) { clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted); clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount); - if (clipper->DisplayStart > already_submitted) //-V1051 - clipper->SeekCursorForItem(clipper->DisplayStart); data->StepNo++; - if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size) + if (clipper->DisplayStart >= clipper->DisplayEnd) continue; + if (clipper->DisplayStart > already_submitted) + clipper->SeekCursorForItem(clipper->DisplayStart); return true; } @@ -3279,7 +3279,7 @@ bool ImGuiListClipper::Step() ImGuiContext& g = *Ctx; bool need_items_height = (ItemsHeight <= 0.0f); bool ret = ImGuiListClipper_StepInternal(this); - if (ret && (DisplayStart == DisplayEnd)) + if (ret && (DisplayStart >= DisplayEnd)) ret = false; if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false) IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n"); From ce13f6b73e30307fa150b1e88f6014a454da466c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 13:10:58 +0100 Subject: [PATCH 0736/2359] Backends: GLFW: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. (#8452) Amend 8e4010479 --- backends/imgui_impl_glfw.cpp | 9 ++++++++- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- imgui_internal.h | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 69cde6c08..874a0a440 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -28,7 +28,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// 2025-03-03: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. +// 2024-08-22: Moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn @@ -598,8 +599,14 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw bd->Time = 0.0; ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); +#if GLFW_VERSION_COMBINED < 3300 + platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(ImGui_ImplGlfw_GetBackendData()->Window, text); }; + platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(ImGui_ImplGlfw_GetBackendData()->Window); }; +#else platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(nullptr, text); }; platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(nullptr); }; +#endif + #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; }; #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0fd46d378..bc0f8f17f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -112,6 +112,8 @@ Other changes: (busy/wait/hourglass shape, with or without an arrow cursor). - Demo: Combos: demonstrate a very simple way to add a filter to a combo, by showing the filter inside the combo contents. (#718) +- Backends: GLFW: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled + with asserts enabled. (#8452) - Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. (#7660) [@achabense] - Backends: SDL2, SDL3, Win32, Allegro5: Added support for ImGuiMouseCursor_Wait diff --git a/imgui.h b/imgui.h index caf8088b2..641b1ab92 100644 --- a/imgui.h +++ b/imgui.h @@ -907,7 +907,7 @@ namespace ImGui IMGUI_API void PopClipRect(); // Focus, Activation - IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of of a newly appearing window. + IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a newly appearing window. IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget. // Keyboard/Gamepad Navigation diff --git a/imgui_internal.h b/imgui_internal.h index f896171cd..4bdc6e947 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2940,7 +2940,7 @@ struct IMGUI_API ImGuiTableTempData ImGuiTableTempData() { memset(this, 0, sizeof(*this)); LastTimeActive = -1.0f; } }; -// sizeof() ~ 12 +// sizeof() ~ 16 struct ImGuiTableColumnSettings { float WidthOrWeight; From eefd2da0f68ebec8e93484088f5257612e37281f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 17:38:09 +0100 Subject: [PATCH 0737/2359] Demo: (Refactor) Added new empty sections.. Renamed existing helper functions. --- docs/CHANGELOG.txt | 1 + imgui_demo.cpp | 191 ++++++++++++++++++++++++++++++++++++--------- 2 files changed, 154 insertions(+), 38 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bc0f8f17f..390681161 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -110,6 +110,7 @@ Other changes: to allow disabled Item Picker suggestion in user facing builds. (#7961, #7669) - Misc: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursors (busy/wait/hourglass shape, with or without an arrow cursor). +- Demo: Reorganized "Widgets" section to be alphabetically ordered and split in more functions. - Demo: Combos: demonstrate a very simple way to add a filter to a combo, by showing the filter inside the combo contents. (#718) - Backends: GLFW: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4372dfb45..81d6cfca8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -72,13 +72,36 @@ Index of this file: // [SECTION] Helpers // [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) // [SECTION] Demo Window / ShowDemoWindow() -// [SECTION] ShowDemoWindowMenuBar() -// [SECTION] ShowDemoWindowWidgets() -// [SECTION] ShowDemoWindowMultiSelect() -// [SECTION] ShowDemoWindowLayout() -// [SECTION] ShowDemoWindowPopups() -// [SECTION] ShowDemoWindowTables() -// [SECTION] ShowDemoWindowInputs() +// [SECTION] DemoWindowMenuBar() +// [SECTION] DemoWindowWidgets() +// [SECTION] DemoWindowWidgetsBasic() +// [SECTION] DemoWindowWidgetsBullets() +// [SECTION] DemoWindowWidgetsCollapsingHeaders() +// [SECTION] DemoWindowWidgetsComboBoxes() +// [SECTION] DemoWindowWidgetsColorAndPickers() +// [SECTION] DemoWindowWidgetsDataTypes() +// [SECTION] DemoWindowWidgetsDisableBlocks() +// [SECTION] DemoWindowWidgetsDragAndDrop() +// [SECTION] DemoWindowWidgetsDragsAndSliders() +// [SECTION] DemoWindowWidgetsImages() +// [SECTION] DemoWindowWidgetsListBoxes() +// [SECTION] DemoWindowWidgetsMultiComponents() +// [SECTION] DemoWindowWidgetsPlotting() +// [SECTION] DemoWindowWidgetsProgressBars() +// [SECTION] DemoWindowWidgetsQueryingStatuses() +// [SECTION] DemoWindowWidgetsSelectables() +// [SECTION] DemoWindowWidgetsSelectionAndMultiSelect() +// [SECTION] DemoWindowWidgetsTabs() +// [SECTION] DemoWindowWidgetsText() +// [SECTION] DemoWindowWidgetsTextFilter() +// [SECTION] DemoWindowWidgetsTextInput() +// [SECTION] DemoWindowWidgetsTooltips() +// [SECTION] DemoWindowWidgetsTreeNodes() +// [SECTION] DemoWindowWidgetsVerticalSliders() +// [SECTION] DemoWindowLayout() +// [SECTION] DemoWindowPopups() +// [SECTION] DemoWindowTables() +// [SECTION] DemoWindowInputs() // [SECTION] About Window / ShowAboutWindow() // [SECTION] Style Editor / ShowStyleEditor() // [SECTION] User Guide / ShowUserGuide() @@ -225,14 +248,14 @@ static void ShowExampleMenuFile(); // We split the contents of the big ShowDemoWindow() function into smaller functions // (because the link time of very large functions tends to grow non-linearly) -static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data); -static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data); -static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data); -static void ShowDemoWindowLayout(); -static void ShowDemoWindowPopups(); -static void ShowDemoWindowTables(); -static void ShowDemoWindowColumns(); -static void ShowDemoWindowInputs(); +static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data); +static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data); +static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); +static void DemoWindowLayout(); +static void DemoWindowPopups(); +static void DemoWindowTables(); +static void DemoWindowColumns(); +static void DemoWindowInputs(); //----------------------------------------------------------------------------- // [SECTION] Helpers @@ -475,7 +498,7 @@ void ImGui::ShowDemoWindow(bool* p_open) //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align) // Menu Bar - ShowDemoWindowMenuBar(&demo_data); + DemoWindowMenuBar(&demo_data); ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); ImGui::Spacing(); @@ -683,11 +706,11 @@ void ImGui::ShowDemoWindow(bool* p_open) } // All demo contents - ShowDemoWindowWidgets(&demo_data); - ShowDemoWindowLayout(); - ShowDemoWindowPopups(); - ShowDemoWindowTables(); - ShowDemoWindowInputs(); + DemoWindowWidgets(&demo_data); + DemoWindowLayout(); + DemoWindowPopups(); + DemoWindowTables(); + DemoWindowInputs(); // End of ShowDemoWindow() ImGui::PopItemWidth(); @@ -695,10 +718,10 @@ void ImGui::ShowDemoWindow(bool* p_open) } //----------------------------------------------------------------------------- -// [SECTION] ShowDemoWindowMenuBar() +// [SECTION] DemoWindowMenuBar() //----------------------------------------------------------------------------- -static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data) +static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Menu"); if (ImGui::BeginMenuBar()) @@ -770,10 +793,10 @@ static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data) } //----------------------------------------------------------------------------- -// [SECTION] ShowDemoWindowWidgets() +// [SECTION] DemoWindowWidgets() //----------------------------------------------------------------------------- -static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) +static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Widgets"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); @@ -1680,7 +1703,7 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::TreePop(); } - ShowDemoWindowMultiSelect(demo_data); + DemoWindowWidgetsSelectionAndMultiSelect(demo_data); // To wire InputText() with std::string or any other custom string type, // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. @@ -2986,6 +3009,70 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) } } +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsBasic() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsBullets() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsCollapsingHeaders() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsColorAndPickers() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsComboBoxes() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsDataTypes() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsDisableBlocks() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsDragAndDrop() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsDragsAndSliders() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsImages() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsListBoxes() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsMultiComponents() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsPlotting() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsProgressBars() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsQueryingStatuses() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsSelectables() +//----------------------------------------------------------------------------- + static const char* ExampleNames[] = { "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", @@ -3212,13 +3299,13 @@ struct ExampleDualListBox }; //----------------------------------------------------------------------------- -// [SECTION] ShowDemoWindowMultiSelect() +// [SECTION] DemoWindowWidgetsSelectionAndMultiSelect() //----------------------------------------------------------------------------- // Multi-selection demos // Also read: https://github.com/ocornut/imgui/wiki/Multi-Select //----------------------------------------------------------------------------- -static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) +static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); if (ImGui::TreeNode("Selection State & Multi-Select")) @@ -3954,10 +4041,38 @@ static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) } //----------------------------------------------------------------------------- -// [SECTION] ShowDemoWindowLayout() +// [SECTION] DemoWindowWidgetsTabs() //----------------------------------------------------------------------------- -static void ShowDemoWindowLayout() +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsText() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTextFilter() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTextInput() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTooltips() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsTreeNodes() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsVerticalSliders() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowLayout() +//----------------------------------------------------------------------------- + +static void DemoWindowLayout() { IMGUI_DEMO_MARKER("Layout"); if (!ImGui::CollapsingHeader("Layout & Scrolling")) @@ -4820,10 +4935,10 @@ static void ShowDemoWindowLayout() } //----------------------------------------------------------------------------- -// [SECTION] ShowDemoWindowPopups() +// [SECTION] DemoWindowPopups() //----------------------------------------------------------------------------- -static void ShowDemoWindowPopups() +static void DemoWindowPopups() { IMGUI_DEMO_MARKER("Popups"); if (!ImGui::CollapsingHeader("Popups & Modal windows")) @@ -5284,10 +5399,10 @@ static void ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags) } //----------------------------------------------------------------------------- -// [SECTION] ShowDemoWindowTables() +// [SECTION] DemoWindowTables() //----------------------------------------------------------------------------- -static void ShowDemoWindowTables() +static void DemoWindowTables() { //ImGui::SetNextItemOpen(true, ImGuiCond_Once); IMGUI_DEMO_MARKER("Tables"); @@ -7184,7 +7299,7 @@ static void ShowDemoWindowTables() ImGui::PopID(); - ShowDemoWindowColumns(); + DemoWindowColumns(); if (disable_indent) ImGui::PopStyleVar(); @@ -7192,7 +7307,7 @@ static void ShowDemoWindowTables() // Demonstrate old/legacy Columns API! // [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!] -static void ShowDemoWindowColumns() +static void DemoWindowColumns() { IMGUI_DEMO_MARKER("Columns (legacy API)"); bool open = ImGui::TreeNode("Legacy Columns API"); @@ -7399,10 +7514,10 @@ static void ShowDemoWindowColumns() } //----------------------------------------------------------------------------- -// [SECTION] ShowDemoWindowInputs() +// [SECTION] DemoWindowInputs() //----------------------------------------------------------------------------- -static void ShowDemoWindowInputs() +static void DemoWindowInputs() { IMGUI_DEMO_MARKER("Inputs & Focus"); if (ImGui::CollapsingHeader("Inputs & Focus")) From b2c55c9db56bc7ceb0618c9e247deeff3cb43f47 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 17:50:48 +0100 Subject: [PATCH 0738/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsBasic() section. --- imgui_demo.cpp | 411 +++++++++++++++++++++++++------------------------ 1 file changed, 209 insertions(+), 202 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 81d6cfca8..1e43ea3c4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -250,6 +250,7 @@ static void ShowExampleMenuFile(); // (because the link time of very large functions tends to grow non-linearly) static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data); +static void DemoWindowWidgetsBasic(); static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); static void DemoWindowLayout(); static void DemoWindowPopups(); @@ -807,203 +808,8 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) if (disable_all) ImGui::BeginDisabled(); - IMGUI_DEMO_MARKER("Widgets/Basic"); - if (ImGui::TreeNode("Basic")) - { - ImGui::SeparatorText("General"); + DemoWindowWidgetsBasic(); - IMGUI_DEMO_MARKER("Widgets/Basic/Button"); - static int clicked = 0; - if (ImGui::Button("Button")) - clicked++; - if (clicked & 1) - { - ImGui::SameLine(); - ImGui::Text("Thanks for clicking me!"); - } - - IMGUI_DEMO_MARKER("Widgets/Basic/Checkbox"); - static bool check = true; - ImGui::Checkbox("checkbox", &check); - - IMGUI_DEMO_MARKER("Widgets/Basic/RadioButton"); - static int e = 0; - ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); - ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); - ImGui::RadioButton("radio c", &e, 2); - - // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. - IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Colored)"); - for (int i = 0; i < 7; i++) - { - if (i > 0) - ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f)); - ImGui::Button("Click"); - ImGui::PopStyleColor(3); - ImGui::PopID(); - } - - // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements - // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) - // See 'Demo->Layout->Text Baseline Alignment' for details. - ImGui::AlignTextToFramePadding(); - ImGui::Text("Hold to repeat:"); - ImGui::SameLine(); - - // Arrow buttons with Repeater - IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Repeating)"); - static int counter = 0; - float spacing = ImGui::GetStyle().ItemInnerSpacing.x; - ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); - if (ImGui::ArrowButton("##left", ImGuiDir_Left)) { counter--; } - ImGui::SameLine(0.0f, spacing); - if (ImGui::ArrowButton("##right", ImGuiDir_Right)) { counter++; } - ImGui::PopItemFlag(); - ImGui::SameLine(); - ImGui::Text("%d", counter); - - ImGui::Button("Tooltip"); - ImGui::SetItemTooltip("I am a tooltip"); - - ImGui::LabelText("label", "Value"); - - ImGui::SeparatorText("Inputs"); - - { - // To wire InputText() with std::string or any other custom string type, - // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. - IMGUI_DEMO_MARKER("Widgets/Basic/InputText"); - static char str0[128] = "Hello, world!"; - ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); - ImGui::SameLine(); HelpMarker( - "USER:\n" - "Hold SHIFT or use mouse to select text.\n" - "CTRL+Left/Right to word jump.\n" - "CTRL+A or Double-Click to select all.\n" - "CTRL+X,CTRL+C,CTRL+V for clipboard.\n" - "CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo.\n" - "ESCAPE to revert.\n\n" - "PROGRAMMER:\n" - "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() " - "to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated " - "in imgui_demo.cpp)."); - - static char str1[128] = ""; - ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1)); - - IMGUI_DEMO_MARKER("Widgets/Basic/InputInt, InputFloat"); - static int i0 = 123; - ImGui::InputInt("input int", &i0); - - static float f0 = 0.001f; - ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f"); - - static double d0 = 999999.00000001; - ImGui::InputDouble("input double", &d0, 0.01f, 1.0f, "%.8f"); - - static float f1 = 1.e10f; - ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e"); - ImGui::SameLine(); HelpMarker( - "You can input value using the scientific notation,\n" - " e.g. \"1e+8\" becomes \"100000000\"."); - - static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; - ImGui::InputFloat3("input float3", vec4a); - } - - ImGui::SeparatorText("Drags"); - - { - IMGUI_DEMO_MARKER("Widgets/Basic/DragInt, DragFloat"); - static int i1 = 50, i2 = 42, i3 = 128; - ImGui::DragInt("drag int", &i1, 1); - ImGui::SameLine(); HelpMarker( - "Click and drag to edit value.\n" - "Hold SHIFT/ALT for faster/slower edit.\n" - "Double-click or CTRL+click to input value."); - ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); - ImGui::DragInt("drag int wrap 100..200", &i3, 1, 100, 200, "%d", ImGuiSliderFlags_WrapAround); - - static float f1 = 1.00f, f2 = 0.0067f; - ImGui::DragFloat("drag float", &f1, 0.005f); - ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); - //ImGui::DragFloat("drag wrap -1..1", &f3, 0.005f, -1.0f, 1.0f, NULL, ImGuiSliderFlags_WrapAround); - } - - ImGui::SeparatorText("Sliders"); - - { - IMGUI_DEMO_MARKER("Widgets/Basic/SliderInt, SliderFloat"); - static int i1 = 0; - ImGui::SliderInt("slider int", &i1, -1, 3); - ImGui::SameLine(); HelpMarker("CTRL+click to input value."); - - static float f1 = 0.123f, f2 = 0.0f; - ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); - ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic); - - IMGUI_DEMO_MARKER("Widgets/Basic/SliderAngle"); - static float angle = 0.0f; - ImGui::SliderAngle("slider angle", &angle); - - // Using the format string to display a name instead of an integer. - // Here we completely omit '%d' from the format string, so it'll only display a name. - // This technique can also be used with DragInt(). - IMGUI_DEMO_MARKER("Widgets/Basic/Slider (enum)"); - enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT }; - static int elem = Element_Fire; - const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; - const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown"; - ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); // Use ImGuiSliderFlags_NoInput flag to disable CTRL+Click here. - ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer."); - } - - ImGui::SeparatorText("Selectors/Pickers"); - - { - IMGUI_DEMO_MARKER("Widgets/Basic/ColorEdit3, ColorEdit4"); - static float col1[3] = { 1.0f, 0.0f, 0.2f }; - static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; - ImGui::ColorEdit3("color 1", col1); - ImGui::SameLine(); HelpMarker( - "Click on the color square to open a color picker.\n" - "Click and hold to use drag and drop.\n" - "Right-click on the color square to show options.\n" - "CTRL+click on individual component to input value.\n"); - - ImGui::ColorEdit4("color 2", col2); - } - - { - // Using the _simplified_ one-liner Combo() api here - // See "Combo" section for examples of how to use the more flexible BeginCombo()/EndCombo() api. - IMGUI_DEMO_MARKER("Widgets/Basic/Combo"); - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }; - static int item_current = 0; - ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items)); - ImGui::SameLine(); HelpMarker( - "Using the simplified one-liner Combo API here.\n" - "Refer to the \"Combo\" section below for an explanation of how to use the more flexible and general BeginCombo/EndCombo API."); - } - - { - // Using the _simplified_ one-liner ListBox() api here - // See "List boxes" section for examples of how to use the more flexible BeginListBox()/EndListBox() api. - IMGUI_DEMO_MARKER("Widgets/Basic/ListBox"); - const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; - static int item_current = 1; - ImGui::ListBox("listbox", &item_current, items, IM_ARRAYSIZE(items), 4); - ImGui::SameLine(); HelpMarker( - "Using the simplified one-liner ListBox API here.\n" - "Refer to the \"List boxes\" section below for an explanation of how to use the more flexible and general BeginListBox/EndListBox API."); - } - - ImGui::TreePop(); - } IMGUI_DEMO_MARKER("Widgets/Tooltips"); if (ImGui::TreeNode("Tooltips")) @@ -1097,12 +903,6 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::TreePop(); } - // Testing ImGuiOnceUponAFrame helper. - //static ImGuiOnceUponAFrame once; - //for (int i = 0; i < 5; i++) - // if (once) - // ImGui::Text("This will be displayed only once."); - IMGUI_DEMO_MARKER("Widgets/Tree Nodes"); if (ImGui::TreeNode("Tree Nodes")) { @@ -3013,6 +2813,213 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) // [SECTION] DemoWindowWidgetsBasic() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsBasic() +{ + IMGUI_DEMO_MARKER("Widgets/Basic"); + if (ImGui::TreeNode("Basic")) + { + ImGui::SeparatorText("General"); + + IMGUI_DEMO_MARKER("Widgets/Basic/Button"); + static int clicked = 0; + if (ImGui::Button("Button")) + clicked++; + if (clicked & 1) + { + ImGui::SameLine(); + ImGui::Text("Thanks for clicking me!"); + } + + IMGUI_DEMO_MARKER("Widgets/Basic/Checkbox"); + static bool check = true; + ImGui::Checkbox("checkbox", &check); + + IMGUI_DEMO_MARKER("Widgets/Basic/RadioButton"); + static int e = 0; + ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); + ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); + ImGui::RadioButton("radio c", &e, 2); + + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. + IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Colored)"); + for (int i = 0; i < 7; i++) + { + if (i > 0) + ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f)); + ImGui::Button("Click"); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + + // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements + // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) + // See 'Demo->Layout->Text Baseline Alignment' for details. + ImGui::AlignTextToFramePadding(); + ImGui::Text("Hold to repeat:"); + ImGui::SameLine(); + + // Arrow buttons with Repeater + IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Repeating)"); + static int counter = 0; + float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); + if (ImGui::ArrowButton("##left", ImGuiDir_Left)) { counter--; } + ImGui::SameLine(0.0f, spacing); + if (ImGui::ArrowButton("##right", ImGuiDir_Right)) { counter++; } + ImGui::PopItemFlag(); + ImGui::SameLine(); + ImGui::Text("%d", counter); + + ImGui::Button("Tooltip"); + ImGui::SetItemTooltip("I am a tooltip"); + + ImGui::LabelText("label", "Value"); + + ImGui::SeparatorText("Inputs"); + + { + // To wire InputText() with std::string or any other custom string type, + // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. + IMGUI_DEMO_MARKER("Widgets/Basic/InputText"); + static char str0[128] = "Hello, world!"; + ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); + ImGui::SameLine(); HelpMarker( + "USER:\n" + "Hold SHIFT or use mouse to select text.\n" + "CTRL+Left/Right to word jump.\n" + "CTRL+A or Double-Click to select all.\n" + "CTRL+X,CTRL+C,CTRL+V for clipboard.\n" + "CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo.\n" + "ESCAPE to revert.\n\n" + "PROGRAMMER:\n" + "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() " + "to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated " + "in imgui_demo.cpp)."); + + static char str1[128] = ""; + ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1)); + + IMGUI_DEMO_MARKER("Widgets/Basic/InputInt, InputFloat"); + static int i0 = 123; + ImGui::InputInt("input int", &i0); + + static float f0 = 0.001f; + ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f"); + + static double d0 = 999999.00000001; + ImGui::InputDouble("input double", &d0, 0.01f, 1.0f, "%.8f"); + + static float f1 = 1.e10f; + ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e"); + ImGui::SameLine(); HelpMarker( + "You can input value using the scientific notation,\n" + " e.g. \"1e+8\" becomes \"100000000\"."); + + static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + ImGui::InputFloat3("input float3", vec4a); + } + + ImGui::SeparatorText("Drags"); + + { + IMGUI_DEMO_MARKER("Widgets/Basic/DragInt, DragFloat"); + static int i1 = 50, i2 = 42, i3 = 128; + ImGui::DragInt("drag int", &i1, 1); + ImGui::SameLine(); HelpMarker( + "Click and drag to edit value.\n" + "Hold SHIFT/ALT for faster/slower edit.\n" + "Double-click or CTRL+click to input value."); + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); + ImGui::DragInt("drag int wrap 100..200", &i3, 1, 100, 200, "%d", ImGuiSliderFlags_WrapAround); + + static float f1 = 1.00f, f2 = 0.0067f; + ImGui::DragFloat("drag float", &f1, 0.005f); + ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); + //ImGui::DragFloat("drag wrap -1..1", &f3, 0.005f, -1.0f, 1.0f, NULL, ImGuiSliderFlags_WrapAround); + } + + ImGui::SeparatorText("Sliders"); + + { + IMGUI_DEMO_MARKER("Widgets/Basic/SliderInt, SliderFloat"); + static int i1 = 0; + ImGui::SliderInt("slider int", &i1, -1, 3); + ImGui::SameLine(); HelpMarker("CTRL+click to input value."); + + static float f1 = 0.123f, f2 = 0.0f; + ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); + ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic); + + IMGUI_DEMO_MARKER("Widgets/Basic/SliderAngle"); + static float angle = 0.0f; + ImGui::SliderAngle("slider angle", &angle); + + // Using the format string to display a name instead of an integer. + // Here we completely omit '%d' from the format string, so it'll only display a name. + // This technique can also be used with DragInt(). + IMGUI_DEMO_MARKER("Widgets/Basic/Slider (enum)"); + enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT }; + static int elem = Element_Fire; + const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; + const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown"; + ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); // Use ImGuiSliderFlags_NoInput flag to disable CTRL+Click here. + ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer."); + } + + ImGui::SeparatorText("Selectors/Pickers"); + + { + IMGUI_DEMO_MARKER("Widgets/Basic/ColorEdit3, ColorEdit4"); + static float col1[3] = { 1.0f, 0.0f, 0.2f }; + static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::SameLine(); HelpMarker( + "Click on the color square to open a color picker.\n" + "Click and hold to use drag and drop.\n" + "Right-click on the color square to show options.\n" + "CTRL+click on individual component to input value.\n"); + + ImGui::ColorEdit4("color 2", col2); + } + + { + // Using the _simplified_ one-liner Combo() api here + // See "Combo" section for examples of how to use the more flexible BeginCombo()/EndCombo() api. + IMGUI_DEMO_MARKER("Widgets/Basic/Combo"); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }; + static int item_current = 0; + ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items)); + ImGui::SameLine(); HelpMarker( + "Using the simplified one-liner Combo API here.\n" + "Refer to the \"Combo\" section below for an explanation of how to use the more flexible and general BeginCombo/EndCombo API."); + } + + { + // Using the _simplified_ one-liner ListBox() api here + // See "List boxes" section for examples of how to use the more flexible BeginListBox()/EndListBox() api. + IMGUI_DEMO_MARKER("Widgets/Basic/ListBox"); + const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int item_current = 1; + ImGui::ListBox("listbox", &item_current, items, IM_ARRAYSIZE(items), 4); + ImGui::SameLine(); HelpMarker( + "Using the simplified one-liner ListBox API here.\n" + "Refer to the \"List boxes\" section below for an explanation of how to use the more flexible and general BeginListBox/EndListBox API."); + } + + // Testing ImGuiOnceUponAFrame helper. + //static ImGuiOnceUponAFrame once; + //for (int i = 0; i < 5; i++) + // if (once) + // ImGui::Text("This will be displayed only once."); + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsBullets() //----------------------------------------------------------------------------- From de3f68a233ac35697671c3e0dcbcd333604c3af5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 17:51:34 +0100 Subject: [PATCH 0739/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsTooltips(), DemoWindowWidgetsTreeNodes() sections. --- imgui_demo.cpp | 447 +++++++++++++++++++++++++------------------------ 1 file changed, 228 insertions(+), 219 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1e43ea3c4..479aa53d5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -252,6 +252,8 @@ static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgetsBasic(); static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); +static void DemoWindowWidgetsTooltips(); +static void DemoWindowWidgetsTreeNodes(); static void DemoWindowLayout(); static void DemoWindowPopups(); static void DemoWindowTables(); @@ -809,225 +811,8 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::BeginDisabled(); DemoWindowWidgetsBasic(); - - - IMGUI_DEMO_MARKER("Widgets/Tooltips"); - if (ImGui::TreeNode("Tooltips")) - { - // Tooltips are windows following the mouse. They do not take focus away. - ImGui::SeparatorText("General"); - - // Typical use cases: - // - Short-form (text only): SetItemTooltip("Hello"); - // - Short-form (any contents): if (BeginItemTooltip()) { Text("Hello"); EndTooltip(); } - - // - Full-form (text only): if (IsItemHovered(...)) { SetTooltip("Hello"); } - // - Full-form (any contents): if (IsItemHovered(...) && BeginTooltip()) { Text("Hello"); EndTooltip(); } - - HelpMarker( - "Tooltip are typically created by using a IsItemHovered() + SetTooltip() sequence.\n\n" - "We provide a helper SetItemTooltip() function to perform the two with standards flags."); - - ImVec2 sz = ImVec2(-FLT_MIN, 0.0f); - - ImGui::Button("Basic", sz); - ImGui::SetItemTooltip("I am a tooltip"); - - ImGui::Button("Fancy", sz); - if (ImGui::BeginItemTooltip()) - { - ImGui::Text("I am a fancy tooltip"); - static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); - ImGui::Text("Sin(time) = %f", sinf((float)ImGui::GetTime())); - ImGui::EndTooltip(); - } - - ImGui::SeparatorText("Always On"); - - // Showcase NOT relying on a IsItemHovered() to emit a tooltip. - // Here the tooltip is always emitted when 'always_on == true'. - static int always_on = 0; - ImGui::RadioButton("Off", &always_on, 0); - ImGui::SameLine(); - ImGui::RadioButton("Always On (Simple)", &always_on, 1); - ImGui::SameLine(); - ImGui::RadioButton("Always On (Advanced)", &always_on, 2); - if (always_on == 1) - ImGui::SetTooltip("I am following you around."); - else if (always_on == 2 && ImGui::BeginTooltip()) - { - ImGui::ProgressBar(sinf((float)ImGui::GetTime()) * 0.5f + 0.5f, ImVec2(ImGui::GetFontSize() * 25, 0.0f)); - ImGui::EndTooltip(); - } - - ImGui::SeparatorText("Custom"); - - HelpMarker( - "Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize " - "tooltip activation details across your application. You may however decide to use custom " - "flags for a specific tooltip instance."); - - // The following examples are passed for documentation purpose but may not be useful to most users. - // Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() will pull ImGuiHoveredFlags flags values from - // 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or keyboard/gamepad is being used. - // With default settings, ImGuiHoveredFlags_ForTooltip is equivalent to ImGuiHoveredFlags_DelayShort + ImGuiHoveredFlags_Stationary. - ImGui::Button("Manual", sz); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) - ImGui::SetTooltip("I am a manually emitted tooltip."); - - ImGui::Button("DelayNone", sz); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNone)) - ImGui::SetTooltip("I am a tooltip with no delay."); - - ImGui::Button("DelayShort", sz); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_NoSharedDelay)) - ImGui::SetTooltip("I am a tooltip with a short delay (%0.2f sec).", ImGui::GetStyle().HoverDelayShort); - - ImGui::Button("DelayLong", sz); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay)) - ImGui::SetTooltip("I am a tooltip with a long delay (%0.2f sec).", ImGui::GetStyle().HoverDelayNormal); - - ImGui::Button("Stationary", sz); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary)) - ImGui::SetTooltip("I am a tooltip requiring mouse to be stationary before activating."); - - // Using ImGuiHoveredFlags_ForTooltip will pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav', - // which default value include the ImGuiHoveredFlags_AllowWhenDisabled flag. - ImGui::BeginDisabled(); - ImGui::Button("Disabled item", sz); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) - ImGui::SetTooltip("I am a a tooltip for a disabled item."); - ImGui::EndDisabled(); - - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Tree Nodes"); - if (ImGui::TreeNode("Tree Nodes")) - { - IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Basic trees"); - if (ImGui::TreeNode("Basic trees")) - { - for (int i = 0; i < 5; i++) - { - // Use SetNextItemOpen() so set the default state of a node to be open. We could - // also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing! - if (i == 0) - ImGui::SetNextItemOpen(true, ImGuiCond_Once); - - // Here we use PushID() to generate a unique base ID, and then the "" used as TreeNode id won't conflict. - // An alternative to using 'PushID() + TreeNode("", ...)' to generate a unique ID is to use 'TreeNode((void*)(intptr_t)i, ...)', - // aka generate a dummy pointer-sized value to be hashed. The demo below uses that technique. Both are fine. - ImGui::PushID(i); - if (ImGui::TreeNode("", "Child %d", i)) - { - ImGui::Text("blah blah"); - ImGui::SameLine(); - if (ImGui::SmallButton("button")) {} - ImGui::TreePop(); - } - ImGui::PopID(); - } - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Advanced, with Selectable nodes"); - if (ImGui::TreeNode("Advanced, with Selectable nodes")) - { - HelpMarker( - "This is a more typical looking tree with selectable nodes.\n" - "Click to select, CTRL+Click to toggle, click on arrows or double-click to open."); - static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth; - static bool align_label_with_current_x_position = false; - static bool test_drag_and_drop = false; - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", &base_flags, ImGuiTreeNodeFlags_OpenOnArrow); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &base_flags, ImGuiTreeNodeFlags_SpanFullWidth); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanLabelWidth", &base_flags, ImGuiTreeNodeFlags_SpanLabelWidth); ImGui::SameLine(); HelpMarker("Reduce hit area to the text label and a bit of margin."); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only."); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsBackHere", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsBackHere); - ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); - ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); - ImGui::Text("Hello!"); - if (align_label_with_current_x_position) - ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); - - // 'selection_mask' is dumb representation of what may be user-side selection state. - // You may retain selection state inside or outside your objects in whatever format you see fit. - // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end - /// of the loop. May be a pointer to your own node type, etc. - static int selection_mask = (1 << 2); - int node_clicked = -1; - for (int i = 0; i < 6; i++) - { - // Disable the default "open on single-click behavior" + set Selected flag according to our selection. - // To alter selection we use IsItemClicked() && !IsItemToggledOpen(), so clicking on an arrow doesn't alter selection. - ImGuiTreeNodeFlags node_flags = base_flags; - const bool is_selected = (selection_mask & (1 << i)) != 0; - if (is_selected) - node_flags |= ImGuiTreeNodeFlags_Selected; - if (i < 3) - { - // Items 0..2 are Tree Node - bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); - if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) - node_clicked = i; - if (test_drag_and_drop && ImGui::BeginDragDropSource()) - { - ImGui::SetDragDropPayload("_TREENODE", NULL, 0); - ImGui::Text("This is a drag and drop source"); - ImGui::EndDragDropSource(); - } - if (i == 2 && (base_flags & ImGuiTreeNodeFlags_SpanLabelWidth)) - { - // Item 2 has an additional inline button to help demonstrate SpanLabelWidth. - ImGui::SameLine(); - if (ImGui::SmallButton("button")) {} - } - if (node_open) - { - ImGui::BulletText("Blah blah\nBlah Blah"); - ImGui::SameLine(); - ImGui::SmallButton("Button"); - ImGui::TreePop(); - } - } - else - { - // Items 3..5 are Tree Leaves - // The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can - // use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). - node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet - ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i); - if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) - node_clicked = i; - if (test_drag_and_drop && ImGui::BeginDragDropSource()) - { - ImGui::SetDragDropPayload("_TREENODE", NULL, 0); - ImGui::Text("This is a drag and drop source"); - ImGui::EndDragDropSource(); - } - } - } - if (node_clicked != -1) - { - // Update selection state - // (process outside of tree loop to avoid visual inconsistencies during the clicking frame) - if (ImGui::GetIO().KeyCtrl) - selection_mask ^= (1 << node_clicked); // CTRL+click to toggle - else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection - selection_mask = (1 << node_clicked); // Click to single-select - } - if (align_label_with_current_x_position) - ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); - ImGui::TreePop(); - } - ImGui::TreePop(); - } + DemoWindowWidgetsTooltips(); + DemoWindowWidgetsTreeNodes(); IMGUI_DEMO_MARKER("Widgets/Collapsing Headers"); if (ImGui::TreeNode("Collapsing Headers")) @@ -4067,10 +3852,234 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // [SECTION] DemoWindowWidgetsTooltips() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsTooltips() +{ + IMGUI_DEMO_MARKER("Widgets/Tooltips"); + if (ImGui::TreeNode("Tooltips")) + { + // Tooltips are windows following the mouse. They do not take focus away. + ImGui::SeparatorText("General"); + + // Typical use cases: + // - Short-form (text only): SetItemTooltip("Hello"); + // - Short-form (any contents): if (BeginItemTooltip()) { Text("Hello"); EndTooltip(); } + + // - Full-form (text only): if (IsItemHovered(...)) { SetTooltip("Hello"); } + // - Full-form (any contents): if (IsItemHovered(...) && BeginTooltip()) { Text("Hello"); EndTooltip(); } + + HelpMarker( + "Tooltip are typically created by using a IsItemHovered() + SetTooltip() sequence.\n\n" + "We provide a helper SetItemTooltip() function to perform the two with standards flags."); + + ImVec2 sz = ImVec2(-FLT_MIN, 0.0f); + + ImGui::Button("Basic", sz); + ImGui::SetItemTooltip("I am a tooltip"); + + ImGui::Button("Fancy", sz); + if (ImGui::BeginItemTooltip()) + { + ImGui::Text("I am a fancy tooltip"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); + ImGui::Text("Sin(time) = %f", sinf((float)ImGui::GetTime())); + ImGui::EndTooltip(); + } + + ImGui::SeparatorText("Always On"); + + // Showcase NOT relying on a IsItemHovered() to emit a tooltip. + // Here the tooltip is always emitted when 'always_on == true'. + static int always_on = 0; + ImGui::RadioButton("Off", &always_on, 0); + ImGui::SameLine(); + ImGui::RadioButton("Always On (Simple)", &always_on, 1); + ImGui::SameLine(); + ImGui::RadioButton("Always On (Advanced)", &always_on, 2); + if (always_on == 1) + ImGui::SetTooltip("I am following you around."); + else if (always_on == 2 && ImGui::BeginTooltip()) + { + ImGui::ProgressBar(sinf((float)ImGui::GetTime()) * 0.5f + 0.5f, ImVec2(ImGui::GetFontSize() * 25, 0.0f)); + ImGui::EndTooltip(); + } + + ImGui::SeparatorText("Custom"); + + HelpMarker( + "Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize " + "tooltip activation details across your application. You may however decide to use custom " + "flags for a specific tooltip instance."); + + // The following examples are passed for documentation purpose but may not be useful to most users. + // Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() will pull ImGuiHoveredFlags flags values from + // 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or keyboard/gamepad is being used. + // With default settings, ImGuiHoveredFlags_ForTooltip is equivalent to ImGuiHoveredFlags_DelayShort + ImGuiHoveredFlags_Stationary. + ImGui::Button("Manual", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + ImGui::SetTooltip("I am a manually emitted tooltip."); + + ImGui::Button("DelayNone", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNone)) + ImGui::SetTooltip("I am a tooltip with no delay."); + + ImGui::Button("DelayShort", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_NoSharedDelay)) + ImGui::SetTooltip("I am a tooltip with a short delay (%0.2f sec).", ImGui::GetStyle().HoverDelayShort); + + ImGui::Button("DelayLong", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay)) + ImGui::SetTooltip("I am a tooltip with a long delay (%0.2f sec).", ImGui::GetStyle().HoverDelayNormal); + + ImGui::Button("Stationary", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary)) + ImGui::SetTooltip("I am a tooltip requiring mouse to be stationary before activating."); + + // Using ImGuiHoveredFlags_ForTooltip will pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav', + // which default value include the ImGuiHoveredFlags_AllowWhenDisabled flag. + ImGui::BeginDisabled(); + ImGui::Button("Disabled item", sz); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + ImGui::SetTooltip("I am a a tooltip for a disabled item."); + ImGui::EndDisabled(); + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsTreeNodes() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsTreeNodes() +{ + IMGUI_DEMO_MARKER("Widgets/Tree Nodes"); + if (ImGui::TreeNode("Tree Nodes")) + { + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Basic trees"); + if (ImGui::TreeNode("Basic trees")) + { + for (int i = 0; i < 5; i++) + { + // Use SetNextItemOpen() so set the default state of a node to be open. We could + // also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing! + if (i == 0) + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + + // Here we use PushID() to generate a unique base ID, and then the "" used as TreeNode id won't conflict. + // An alternative to using 'PushID() + TreeNode("", ...)' to generate a unique ID is to use 'TreeNode((void*)(intptr_t)i, ...)', + // aka generate a dummy pointer-sized value to be hashed. The demo below uses that technique. Both are fine. + ImGui::PushID(i); + if (ImGui::TreeNode("", "Child %d", i)) + { + ImGui::Text("blah blah"); + ImGui::SameLine(); + if (ImGui::SmallButton("button")) {} + ImGui::TreePop(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Advanced, with Selectable nodes"); + if (ImGui::TreeNode("Advanced, with Selectable nodes")) + { + HelpMarker( + "This is a more typical looking tree with selectable nodes.\n" + "Click to select, CTRL+Click to toggle, click on arrows or double-click to open."); + static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth; + static bool align_label_with_current_x_position = false; + static bool test_drag_and_drop = false; + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", &base_flags, ImGuiTreeNodeFlags_OpenOnArrow); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &base_flags, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanLabelWidth", &base_flags, ImGuiTreeNodeFlags_SpanLabelWidth); ImGui::SameLine(); HelpMarker("Reduce hit area to the text label and a bit of margin."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsBackHere", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsBackHere); + ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); + ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); + ImGui::Text("Hello!"); + if (align_label_with_current_x_position) + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + + // 'selection_mask' is dumb representation of what may be user-side selection state. + // You may retain selection state inside or outside your objects in whatever format you see fit. + // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end + /// of the loop. May be a pointer to your own node type, etc. + static int selection_mask = (1 << 2); + int node_clicked = -1; + for (int i = 0; i < 6; i++) + { + // Disable the default "open on single-click behavior" + set Selected flag according to our selection. + // To alter selection we use IsItemClicked() && !IsItemToggledOpen(), so clicking on an arrow doesn't alter selection. + ImGuiTreeNodeFlags node_flags = base_flags; + const bool is_selected = (selection_mask & (1 << i)) != 0; + if (is_selected) + node_flags |= ImGuiTreeNodeFlags_Selected; + if (i < 3) + { + // Items 0..2 are Tree Node + bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); + if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) + node_clicked = i; + if (test_drag_and_drop && ImGui::BeginDragDropSource()) + { + ImGui::SetDragDropPayload("_TREENODE", NULL, 0); + ImGui::Text("This is a drag and drop source"); + ImGui::EndDragDropSource(); + } + if (i == 2 && (base_flags & ImGuiTreeNodeFlags_SpanLabelWidth)) + { + // Item 2 has an additional inline button to help demonstrate SpanLabelWidth. + ImGui::SameLine(); + if (ImGui::SmallButton("button")) {} + } + if (node_open) + { + ImGui::BulletText("Blah blah\nBlah Blah"); + ImGui::SameLine(); + ImGui::SmallButton("Button"); + ImGui::TreePop(); + } + } + else + { + // Items 3..5 are Tree Leaves + // The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can + // use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). + node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet + ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i); + if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) + node_clicked = i; + if (test_drag_and_drop && ImGui::BeginDragDropSource()) + { + ImGui::SetDragDropPayload("_TREENODE", NULL, 0); + ImGui::Text("This is a drag and drop source"); + ImGui::EndDragDropSource(); + } + } + } + if (node_clicked != -1) + { + // Update selection state + // (process outside of tree loop to avoid visual inconsistencies during the clicking frame) + if (ImGui::GetIO().KeyCtrl) + selection_mask ^= (1 << node_clicked); // CTRL+click to toggle + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection + selection_mask = (1 << node_clicked); // Click to single-select + } + if (align_label_with_current_x_position) + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsVerticalSliders() //----------------------------------------------------------------------------- From 94877a137d6aac1aba010bcace0f5730c2f153fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 17:56:15 +0100 Subject: [PATCH 0740/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsBullets(), DemoWindowWidgetsCollapsingHeaders(), DemoWindowWidgetsCollapsingText() sections. --- imgui_demo.cpp | 243 ++++++++++++++++++++++++++----------------------- 1 file changed, 129 insertions(+), 114 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 479aa53d5..f40f5ddae 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -251,7 +251,10 @@ static void ShowExampleMenuFile(); static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgetsBasic(); +static void DemoWindowWidgetsBullets(); +static void DemoWindowWidgetsCollapsingHeaders(); static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); +static void DemoWindowWidgetsText(); static void DemoWindowWidgetsTooltips(); static void DemoWindowWidgetsTreeNodes(); static void DemoWindowLayout(); @@ -811,123 +814,12 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::BeginDisabled(); DemoWindowWidgetsBasic(); + DemoWindowWidgetsBullets(); + DemoWindowWidgetsCollapsingHeaders(); + DemoWindowWidgetsText(); DemoWindowWidgetsTooltips(); DemoWindowWidgetsTreeNodes(); - IMGUI_DEMO_MARKER("Widgets/Collapsing Headers"); - if (ImGui::TreeNode("Collapsing Headers")) - { - static bool closable_group = true; - ImGui::Checkbox("Show 2nd header", &closable_group); - if (ImGui::CollapsingHeader("Header", ImGuiTreeNodeFlags_None)) - { - ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); - for (int i = 0; i < 5; i++) - ImGui::Text("Some content %d", i); - } - if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) - { - ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); - for (int i = 0; i < 5; i++) - ImGui::Text("More content %d", i); - } - /* - if (ImGui::CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags_Bullet)) - ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); - */ - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Bullets"); - if (ImGui::TreeNode("Bullets")) - { - ImGui::BulletText("Bullet point 1"); - ImGui::BulletText("Bullet point 2\nOn multiple lines"); - if (ImGui::TreeNode("Tree node")) - { - ImGui::BulletText("Another bullet point"); - ImGui::TreePop(); - } - ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); - ImGui::Bullet(); ImGui::SmallButton("Button"); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text"); - if (ImGui::TreeNode("Text")) - { - IMGUI_DEMO_MARKER("Widgets/Text/Colored Text"); - if (ImGui::TreeNode("Colorful Text")) - { - // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. - ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink"); - ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow"); - ImGui::TextDisabled("Disabled"); - ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle."); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping"); - if (ImGui::TreeNode("Word Wrapping")) - { - // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. - ImGui::TextWrapped( - "This text should automatically wrap on the edge of the window. The current implementation " - "for text wrapping follows simple rules suitable for English and possibly other languages."); - ImGui::Spacing(); - - static float wrap_width = 200.0f; - ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); - - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - for (int n = 0; n < 2; n++) - { - ImGui::Text("Test paragraph %d:", n); - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y); - ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - if (n == 0) - ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); - else - ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); - - // Draw actual text bounding box, following by marker of our expected limit (should not overlap!) - draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255)); - draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)); - ImGui::PopTextWrapPos(); - } - - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text/UTF-8 Text"); - if (ImGui::TreeNode("UTF-8 Text")) - { - // UTF-8 test with Japanese characters - // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) - // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 - // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you - // can save your source files as 'UTF-8 without signature'). - // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 - // CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants. - // Don't do this in your application! Please use u8"text in any language" in your application! - // Note that characters values are preserved even by InputText() if the font cannot be displayed, - // so you can safely copy & paste garbled characters into another application. - ImGui::TextWrapped( - "CJK text will only appear if the font was loaded with the appropriate CJK character ranges. " - "Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. " - "Read docs/FONTS.md for details."); - ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); - ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); - static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; - //static char buf[32] = u8"NIHONGO"; // <- this is how you would write it with C++11, using real kanjis - ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); - ImGui::TreePop(); - } - ImGui::TreePop(); - } - IMGUI_DEMO_MARKER("Widgets/Images"); if (ImGui::TreeNode("Images")) { @@ -2809,10 +2701,55 @@ static void DemoWindowWidgetsBasic() // [SECTION] DemoWindowWidgetsBullets() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsBullets() +{ + IMGUI_DEMO_MARKER("Widgets/Bullets"); + if (ImGui::TreeNode("Bullets")) + { + ImGui::BulletText("Bullet point 1"); + ImGui::BulletText("Bullet point 2\nOn multiple lines"); + if (ImGui::TreeNode("Tree node")) + { + ImGui::BulletText("Another bullet point"); + ImGui::TreePop(); + } + ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); + ImGui::Bullet(); ImGui::SmallButton("Button"); + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsCollapsingHeaders() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsCollapsingHeaders() +{ + IMGUI_DEMO_MARKER("Widgets/Collapsing Headers"); + if (ImGui::TreeNode("Collapsing Headers")) + { + static bool closable_group = true; + ImGui::Checkbox("Show 2nd header", &closable_group); + if (ImGui::CollapsingHeader("Header", ImGuiTreeNodeFlags_None)) + { + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + for (int i = 0; i < 5; i++) + ImGui::Text("Some content %d", i); + } + if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) + { + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + for (int i = 0; i < 5; i++) + ImGui::Text("More content %d", i); + } + /* + if (ImGui::CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags_Bullet)) + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + */ + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsColorAndPickers() //----------------------------------------------------------------------------- @@ -3840,6 +3777,84 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // [SECTION] DemoWindowWidgetsText() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsText() +{ + IMGUI_DEMO_MARKER("Widgets/Text"); + if (ImGui::TreeNode("Text")) + { + IMGUI_DEMO_MARKER("Widgets/Text/Colored Text"); + if (ImGui::TreeNode("Colorful Text")) + { + // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. + ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow"); + ImGui::TextDisabled("Disabled"); + ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle."); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping"); + if (ImGui::TreeNode("Word Wrapping")) + { + // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. + ImGui::TextWrapped( + "This text should automatically wrap on the edge of the window. The current implementation " + "for text wrapping follows simple rules suitable for English and possibly other languages."); + ImGui::Spacing(); + + static float wrap_width = 200.0f; + ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); + + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (int n = 0; n < 2; n++) + { + ImGui::Text("Test paragraph %d:", n); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y); + ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + if (n == 0) + ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); + else + ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + + // Draw actual text bounding box, following by marker of our expected limit (should not overlap!) + draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255)); + draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)); + ImGui::PopTextWrapPos(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text/UTF-8 Text"); + if (ImGui::TreeNode("UTF-8 Text")) + { + // UTF-8 test with Japanese characters + // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) + // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 + // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you + // can save your source files as 'UTF-8 without signature'). + // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 + // CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants. + // Don't do this in your application! Please use u8"text in any language" in your application! + // Note that characters values are preserved even by InputText() if the font cannot be displayed, + // so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped( + "CJK text will only appear if the font was loaded with the appropriate CJK character ranges. " + "Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. " + "Read docs/FONTS.md for details."); + ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); + ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); + static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; + //static char buf[32] = u8"NIHONGO"; // <- this is how you would write it with C++11, using real kanjis + ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsTextFilter() //----------------------------------------------------------------------------- From 22baec494bfec2df120c0acb491eb0a7b643cf40 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 17:57:43 +0100 Subject: [PATCH 0741/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsComboBoxes(), DemoWindowWidgetsImages(), DemoWindowWidgetsListBoxes() sections. --- imgui_demo.cpp | 475 +++++++++++++++++++++++++------------------------ 1 file changed, 245 insertions(+), 230 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f40f5ddae..3b08b152f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -253,6 +253,9 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgetsBasic(); static void DemoWindowWidgetsBullets(); static void DemoWindowWidgetsCollapsingHeaders(); +static void DemoWindowWidgetsComboBoxes(); +static void DemoWindowWidgetsImages(); +static void DemoWindowWidgetsListBoxes(); static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgetsText(); static void DemoWindowWidgetsTooltips(); @@ -816,240 +819,13 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsBasic(); DemoWindowWidgetsBullets(); DemoWindowWidgetsCollapsingHeaders(); + DemoWindowWidgetsComboBoxes(); + DemoWindowWidgetsImages(); + DemoWindowWidgetsListBoxes(); DemoWindowWidgetsText(); DemoWindowWidgetsTooltips(); DemoWindowWidgetsTreeNodes(); - IMGUI_DEMO_MARKER("Widgets/Images"); - if (ImGui::TreeNode("Images")) - { - ImGuiIO& io = ImGui::GetIO(); - ImGui::TextWrapped( - "Below we are displaying the font texture (which is the only texture we have access to in this demo). " - "Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. " - "Hover the texture for a zoomed view!"); - - // Below we are displaying the font texture because it is the only texture we have access to inside the demo! - // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that - // will be passed to the rendering backend via the ImDrawCmd structure. - // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top - // of their respective source file to specify what they expect to be stored in ImTextureID, for example: - // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer - // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. - // More: - // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers - // to ImGui::Image(), and gather width/height through your own functions, etc. - // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, - // it will help you debug issues if you are confused about it. - // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). - // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md - // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - ImTextureID my_tex_id = io.Fonts->TexID; - float my_tex_w = (float)io.Fonts->TexWidth; - float my_tex_h = (float)io.Fonts->TexHeight; - { - ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left - ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right - ImGui::PushStyleVar(ImGuiStyleVar_ImageBorderSize, IM_MAX(1.0f, ImGui::GetStyle().ImageBorderSize)); - ImGui::ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); - if (ImGui::BeginItemTooltip()) - { - float region_sz = 32.0f; - float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; - float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; - float zoom = 4.0f; - if (region_x < 0.0f) { region_x = 0.0f; } - else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; } - if (region_y < 0.0f) { region_y = 0.0f; } - else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; } - ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); - ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); - ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h); - ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h); - ImGui::ImageWithBg(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); - ImGui::EndTooltip(); - } - ImGui::PopStyleVar(); - } - - IMGUI_DEMO_MARKER("Widgets/Images/Textured buttons"); - ImGui::TextWrapped("And now some textured buttons.."); - static int pressed_count = 0; - for (int i = 0; i < 8; i++) - { - // UV coordinates are often (0.0f, 0.0f) and (1.0f, 1.0f) to display an entire textures. - // Here are trying to display only a 32x32 pixels area of the texture, hence the UV computation. - // Read about UV coordinates here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - ImGui::PushID(i); - if (i > 0) - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(i - 1.0f, i - 1.0f)); - ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible - ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left - ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h); // UV coordinates for (32,32) in our texture - ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background - ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint - if (ImGui::ImageButton("", my_tex_id, size, uv0, uv1, bg_col, tint_col)) - pressed_count += 1; - if (i > 0) - ImGui::PopStyleVar(); - ImGui::PopID(); - ImGui::SameLine(); - } - ImGui::NewLine(); - ImGui::Text("Pressed %d times.", pressed_count); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Combo"); - if (ImGui::TreeNode("Combo")) - { - // Combo Boxes are also called "Dropdown" in other systems - // Expose flags as checkbox for the demo - static ImGuiComboFlags flags = 0; - ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", &flags, ImGuiComboFlags_PopupAlignLeft); - ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo"); - if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", &flags, ImGuiComboFlags_NoArrowButton)) - flags &= ~ImGuiComboFlags_NoPreview; // Clear incompatible flags - if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", &flags, ImGuiComboFlags_NoPreview)) - flags &= ~(ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_WidthFitPreview); // Clear incompatible flags - if (ImGui::CheckboxFlags("ImGuiComboFlags_WidthFitPreview", &flags, ImGuiComboFlags_WidthFitPreview)) - flags &= ~ImGuiComboFlags_NoPreview; - - // Override default popup height - if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightSmall", &flags, ImGuiComboFlags_HeightSmall)) - flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightSmall); - if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightRegular", &flags, ImGuiComboFlags_HeightRegular)) - flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightRegular); - if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightLargest", &flags, ImGuiComboFlags_HeightLargest)) - flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightLargest); - - // Using the generic BeginCombo() API, you have full control over how to display the combo contents. - // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively - // stored in the object itself, etc.) - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; - static int item_selected_idx = 0; // Here we store our selection data as an index. - - // Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[]) - const char* combo_preview_value = items[item_selected_idx]; - if (ImGui::BeginCombo("combo 1", combo_preview_value, flags)) - { - for (int n = 0; n < IM_ARRAYSIZE(items); n++) - { - const bool is_selected = (item_selected_idx == n); - if (ImGui::Selectable(items[n], is_selected)) - item_selected_idx = n; - - // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) - if (is_selected) - ImGui::SetItemDefaultFocus(); - } - ImGui::EndCombo(); - } - - // Show case embedding a filter using a simple trick: displaying the filter inside combo contents. - // See https://github.com/ocornut/imgui/issues/718 for advanced/esoteric alternatives. - if (ImGui::BeginCombo("combo 2 (w/ filter)", combo_preview_value, flags)) - { - static ImGuiTextFilter filter; - if (ImGui::IsWindowAppearing()) - { - ImGui::SetKeyboardFocusHere(); - filter.Clear(); - } - ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); - filter.Draw("##Filter", -FLT_MIN); - - for (int n = 0; n < IM_ARRAYSIZE(items); n++) - { - const bool is_selected = (item_selected_idx == n); - if (filter.PassFilter(items[n])) - if (ImGui::Selectable(items[n], is_selected)) - item_selected_idx = n; - } - ImGui::EndCombo(); - } - - ImGui::Spacing(); - ImGui::SeparatorText("One-liner variants"); - HelpMarker("The Combo() function is not greatly useful apart from cases were you want to embed all options in a single strings.\nFlags above don't apply to this section."); - - // Simplified one-liner Combo() API, using values packed in a single constant string - // This is a convenience for when the selection set is small and known at compile-time. - static int item_current_2 = 0; - ImGui::Combo("combo 3 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); - - // Simplified one-liner Combo() using an array of const char* - // This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. - static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview - ImGui::Combo("combo 4 (array)", &item_current_3, items, IM_ARRAYSIZE(items)); - - // 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_ARRAYSIZE(items)); - - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/List Boxes"); - if (ImGui::TreeNode("List boxes")) - { - // BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild() - // using the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. - // You may be tempted to simply use BeginChild() directly. However note that BeginChild() requires EndChild() - // to always be called (inconsistent with BeginListBox()/EndListBox()). - - // Using the generic BeginListBox() API, you have full control over how to display the combo contents. - // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively - // stored in the object itself, etc.) - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; - static int item_selected_idx = 0; // Here we store our selected data as an index. - - static bool item_highlight = false; - int item_highlighted_idx = -1; // Here we store our highlighted data as an index. - ImGui::Checkbox("Highlight hovered item in second listbox", &item_highlight); - - if (ImGui::BeginListBox("listbox 1")) - { - for (int n = 0; n < IM_ARRAYSIZE(items); n++) - { - const bool is_selected = (item_selected_idx == n); - if (ImGui::Selectable(items[n], is_selected)) - item_selected_idx = n; - - if (item_highlight && ImGui::IsItemHovered()) - item_highlighted_idx = n; - - // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) - if (is_selected) - ImGui::SetItemDefaultFocus(); - } - ImGui::EndListBox(); - } - ImGui::SameLine(); HelpMarker("Here we are sharing selection state between both boxes."); - - // Custom size: use all width, 5 items tall - ImGui::Text("Full-width:"); - if (ImGui::BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui::GetTextLineHeightWithSpacing()))) - { - for (int n = 0; n < IM_ARRAYSIZE(items); n++) - { - bool is_selected = (item_selected_idx == n); - ImGuiSelectableFlags flags = (item_highlighted_idx == n) ? ImGuiSelectableFlags_Highlight : 0; - if (ImGui::Selectable(items[n], is_selected, flags)) - item_selected_idx = n; - - // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) - if (is_selected) - ImGui::SetItemDefaultFocus(); - } - ImGui::EndListBox(); - } - - ImGui::TreePop(); - } - IMGUI_DEMO_MARKER("Widgets/Selectables"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Selectables")) @@ -2758,6 +2534,99 @@ static void DemoWindowWidgetsCollapsingHeaders() // [SECTION] DemoWindowWidgetsComboBoxes() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsComboBoxes() +{ + IMGUI_DEMO_MARKER("Widgets/Combo"); + if (ImGui::TreeNode("Combo")) + { + // Combo Boxes are also called "Dropdown" in other systems + // Expose flags as checkbox for the demo + static ImGuiComboFlags flags = 0; + ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", &flags, ImGuiComboFlags_PopupAlignLeft); + ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo"); + if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", &flags, ImGuiComboFlags_NoArrowButton)) + flags &= ~ImGuiComboFlags_NoPreview; // Clear incompatible flags + if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", &flags, ImGuiComboFlags_NoPreview)) + flags &= ~(ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_WidthFitPreview); // Clear incompatible flags + if (ImGui::CheckboxFlags("ImGuiComboFlags_WidthFitPreview", &flags, ImGuiComboFlags_WidthFitPreview)) + flags &= ~ImGuiComboFlags_NoPreview; + + // Override default popup height + if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightSmall", &flags, ImGuiComboFlags_HeightSmall)) + flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightSmall); + if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightRegular", &flags, ImGuiComboFlags_HeightRegular)) + flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightRegular); + if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightLargest", &flags, ImGuiComboFlags_HeightLargest)) + flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightLargest); + + // Using the generic BeginCombo() API, you have full control over how to display the combo contents. + // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + // stored in the object itself, etc.) + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; + static int item_selected_idx = 0; // Here we store our selection data as an index. + + // Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[]) + const char* combo_preview_value = items[item_selected_idx]; + if (ImGui::BeginCombo("combo 1", combo_preview_value, flags)) + { + for (int n = 0; n < IM_ARRAYSIZE(items); n++) + { + const bool is_selected = (item_selected_idx == n); + if (ImGui::Selectable(items[n], is_selected)) + item_selected_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + + // Show case embedding a filter using a simple trick: displaying the filter inside combo contents. + // See https://github.com/ocornut/imgui/issues/718 for advanced/esoteric alternatives. + if (ImGui::BeginCombo("combo 2 (w/ filter)", combo_preview_value, flags)) + { + static ImGuiTextFilter filter; + if (ImGui::IsWindowAppearing()) + { + ImGui::SetKeyboardFocusHere(); + filter.Clear(); + } + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); + filter.Draw("##Filter", -FLT_MIN); + + for (int n = 0; n < IM_ARRAYSIZE(items); n++) + { + const bool is_selected = (item_selected_idx == n); + if (filter.PassFilter(items[n])) + if (ImGui::Selectable(items[n], is_selected)) + item_selected_idx = n; + } + ImGui::EndCombo(); + } + + ImGui::Spacing(); + ImGui::SeparatorText("One-liner variants"); + HelpMarker("The Combo() function is not greatly useful apart from cases were you want to embed all options in a single strings.\nFlags above don't apply to this section."); + + // Simplified one-liner Combo() API, using values packed in a single constant string + // This is a convenience for when the selection set is small and known at compile-time. + static int item_current_2 = 0; + ImGui::Combo("combo 3 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); + + // Simplified one-liner Combo() using an array of const char* + // This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. + static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview + ImGui::Combo("combo 4 (array)", &item_current_3, items, IM_ARRAYSIZE(items)); + + // 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_ARRAYSIZE(items)); + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsDataTypes() //----------------------------------------------------------------------------- @@ -2778,10 +2647,156 @@ static void DemoWindowWidgetsCollapsingHeaders() // [SECTION] DemoWindowWidgetsImages() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsImages() +{ + IMGUI_DEMO_MARKER("Widgets/Images"); + if (ImGui::TreeNode("Images")) + { + ImGuiIO& io = ImGui::GetIO(); + ImGui::TextWrapped( + "Below we are displaying the font texture (which is the only texture we have access to in this demo). " + "Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. " + "Hover the texture for a zoomed view!"); + + // Below we are displaying the font texture because it is the only texture we have access to inside the demo! + // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that + // will be passed to the rendering backend via the ImDrawCmd structure. + // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top + // of their respective source file to specify what they expect to be stored in ImTextureID, for example: + // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer + // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. + // More: + // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers + // to ImGui::Image(), and gather width/height through your own functions, etc. + // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, + // it will help you debug issues if you are confused about it. + // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). + // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md + // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + ImTextureID my_tex_id = io.Fonts->TexID; + float my_tex_w = (float)io.Fonts->TexWidth; + float my_tex_h = (float)io.Fonts->TexHeight; + { + ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left + ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right + ImGui::PushStyleVar(ImGuiStyleVar_ImageBorderSize, IM_MAX(1.0f, ImGui::GetStyle().ImageBorderSize)); + ImGui::ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + if (ImGui::BeginItemTooltip()) + { + float region_sz = 32.0f; + float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; + float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; + float zoom = 4.0f; + if (region_x < 0.0f) { region_x = 0.0f; } + else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; } + if (region_y < 0.0f) { region_y = 0.0f; } + else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; } + ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); + ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); + ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h); + ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h); + ImGui::ImageWithBg(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + ImGui::EndTooltip(); + } + ImGui::PopStyleVar(); + } + + IMGUI_DEMO_MARKER("Widgets/Images/Textured buttons"); + ImGui::TextWrapped("And now some textured buttons.."); + static int pressed_count = 0; + for (int i = 0; i < 8; i++) + { + // UV coordinates are often (0.0f, 0.0f) and (1.0f, 1.0f) to display an entire textures. + // Here are trying to display only a 32x32 pixels area of the texture, hence the UV computation. + // Read about UV coordinates here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + ImGui::PushID(i); + if (i > 0) + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(i - 1.0f, i - 1.0f)); + ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible + ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left + ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h); // UV coordinates for (32,32) in our texture + ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint + if (ImGui::ImageButton("", my_tex_id, size, uv0, uv1, bg_col, tint_col)) + pressed_count += 1; + if (i > 0) + ImGui::PopStyleVar(); + ImGui::PopID(); + ImGui::SameLine(); + } + ImGui::NewLine(); + ImGui::Text("Pressed %d times.", pressed_count); + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsListBoxes() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsListBoxes() +{ + IMGUI_DEMO_MARKER("Widgets/List Boxes"); + if (ImGui::TreeNode("List boxes")) + { + // BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild() + // using the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. + // You may be tempted to simply use BeginChild() directly. However note that BeginChild() requires EndChild() + // to always be called (inconsistent with BeginListBox()/EndListBox()). + + // Using the generic BeginListBox() API, you have full control over how to display the combo contents. + // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + // stored in the object itself, etc.) + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; + static int item_selected_idx = 0; // Here we store our selected data as an index. + + static bool item_highlight = false; + int item_highlighted_idx = -1; // Here we store our highlighted data as an index. + ImGui::Checkbox("Highlight hovered item in second listbox", &item_highlight); + + if (ImGui::BeginListBox("listbox 1")) + { + for (int n = 0; n < IM_ARRAYSIZE(items); n++) + { + const bool is_selected = (item_selected_idx == n); + if (ImGui::Selectable(items[n], is_selected)) + item_selected_idx = n; + + if (item_highlight && ImGui::IsItemHovered()) + item_highlighted_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndListBox(); + } + ImGui::SameLine(); HelpMarker("Here we are sharing selection state between both boxes."); + + // Custom size: use all width, 5 items tall + ImGui::Text("Full-width:"); + if (ImGui::BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui::GetTextLineHeightWithSpacing()))) + { + for (int n = 0; n < IM_ARRAYSIZE(items); n++) + { + bool is_selected = (item_selected_idx == n); + ImGuiSelectableFlags flags = (item_highlighted_idx == n) ? ImGuiSelectableFlags_Highlight : 0; + if (ImGui::Selectable(items[n], is_selected, flags)) + item_selected_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndListBox(); + } + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsMultiComponents() //----------------------------------------------------------------------------- From 4450d61ac25771bd0116754607a33a5eb1da33b3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 18:01:41 +0100 Subject: [PATCH 0742/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsSelectables(), DemoWindowWidgetsTextFilter(), DemoWindowWidgetsTextInputs() sections. --- imgui_demo.cpp | 743 +++++++++++++++++++++++++------------------------ 1 file changed, 379 insertions(+), 364 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3b08b152f..56688d4c4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -256,8 +256,11 @@ static void DemoWindowWidgetsCollapsingHeaders(); static void DemoWindowWidgetsComboBoxes(); static void DemoWindowWidgetsImages(); static void DemoWindowWidgetsListBoxes(); +static void DemoWindowWidgetsSelectables(); static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgetsText(); +static void DemoWindowWidgetsTextFilter(); +static void DemoWindowWidgetsTextInput(); static void DemoWindowWidgetsTooltips(); static void DemoWindowWidgetsTreeNodes(); static void DemoWindowLayout(); @@ -822,347 +825,14 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsComboBoxes(); DemoWindowWidgetsImages(); DemoWindowWidgetsListBoxes(); + DemoWindowWidgetsSelectables(); + DemoWindowWidgetsSelectionAndMultiSelect(demo_data); DemoWindowWidgetsText(); + DemoWindowWidgetsTextFilter(); + DemoWindowWidgetsTextInput(); DemoWindowWidgetsTooltips(); DemoWindowWidgetsTreeNodes(); - IMGUI_DEMO_MARKER("Widgets/Selectables"); - //ImGui::SetNextItemOpen(true, ImGuiCond_Once); - if (ImGui::TreeNode("Selectables")) - { - // Selectable() has 2 overloads: - // - The one taking "bool selected" as a read-only selection information. - // When Selectable() has been clicked it returns true and you can alter selection state accordingly. - // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) - // The earlier is more flexible, as in real application your selection may be stored in many different ways - // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). - IMGUI_DEMO_MARKER("Widgets/Selectables/Basic"); - if (ImGui::TreeNode("Basic")) - { - static bool selection[5] = { false, true, false, false }; - ImGui::Selectable("1. I am selectable", &selection[0]); - ImGui::Selectable("2. I am selectable", &selection[1]); - ImGui::Selectable("3. I am selectable", &selection[2]); - if (ImGui::Selectable("4. I am double clickable", selection[3], ImGuiSelectableFlags_AllowDoubleClick)) - if (ImGui::IsMouseDoubleClicked(0)) - selection[3] = !selection[3]; - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Selectables/Rendering more items on the same line"); - if (ImGui::TreeNode("Rendering more items on the same line")) - { - // (1) Using SetNextItemAllowOverlap() - // (2) Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. - static bool selected[3] = { false, false, false }; - ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(); ImGui::SmallButton("Link 1"); - ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(); ImGui::SmallButton("Link 2"); - ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(); ImGui::SmallButton("Link 3"); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Selectables/In Tables"); - if (ImGui::TreeNode("In Tables")) - { - static bool selected[10] = {}; - - if (ImGui::BeginTable("split1", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) - { - for (int i = 0; i < 10; i++) - { - char label[32]; - sprintf(label, "Item %d", i); - ImGui::TableNextColumn(); - ImGui::Selectable(label, &selected[i]); // FIXME-TABLE: Selection overlap - } - ImGui::EndTable(); - } - ImGui::Spacing(); - if (ImGui::BeginTable("split2", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) - { - for (int i = 0; i < 10; i++) - { - char label[32]; - sprintf(label, "Item %d", i); - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - ImGui::Selectable(label, &selected[i], ImGuiSelectableFlags_SpanAllColumns); - ImGui::TableNextColumn(); - ImGui::Text("Some other contents"); - ImGui::TableNextColumn(); - ImGui::Text("123456"); - } - ImGui::EndTable(); - } - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Selectables/Grid"); - if (ImGui::TreeNode("Grid")) - { - static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; - - // Add in a bit of silly fun... - const float time = (float)ImGui::GetTime(); - const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected... - if (winning_state) - ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f))); - - for (int y = 0; y < 4; y++) - for (int x = 0; x < 4; x++) - { - if (x > 0) - ImGui::SameLine(); - ImGui::PushID(y * 4 + x); - if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(50, 50))) - { - // Toggle clicked cell + toggle neighbors - selected[y][x] ^= 1; - if (x > 0) { selected[y][x - 1] ^= 1; } - if (x < 3) { selected[y][x + 1] ^= 1; } - if (y > 0) { selected[y - 1][x] ^= 1; } - if (y < 3) { selected[y + 1][x] ^= 1; } - } - ImGui::PopID(); - } - - if (winning_state) - ImGui::PopStyleVar(); - ImGui::TreePop(); - } - IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment"); - if (ImGui::TreeNode("Alignment")) - { - HelpMarker( - "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item " - "basis using PushStyleVar(). You'll probably want to always keep your default situation to " - "left-align otherwise it becomes difficult to layout multiple items on a same line"); - static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true }; - for (int y = 0; y < 3; y++) - { - for (int x = 0; x < 3; x++) - { - ImVec2 alignment = ImVec2((float)x / 2.0f, (float)y / 2.0f); - char name[32]; - sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y); - if (x > 0) ImGui::SameLine(); - ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment); - ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80)); - ImGui::PopStyleVar(); - } - } - ImGui::TreePop(); - } - ImGui::TreePop(); - } - - DemoWindowWidgetsSelectionAndMultiSelect(demo_data); - - // To wire InputText() with std::string or any other custom string type, - // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. - IMGUI_DEMO_MARKER("Widgets/Text Input"); - if (ImGui::TreeNode("Text Input")) - { - IMGUI_DEMO_MARKER("Widgets/Text Input/Multi-line Text Input"); - if (ImGui::TreeNode("Multi-line Text Input")) - { - // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize - // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings. - static char text[1024 * 16] = - "/*\n" - " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" - " the hexadecimal encoding of one offending instruction,\n" - " more formally, the invalid operand with locked CMPXCHG8B\n" - " instruction bug, is a design flaw in the majority of\n" - " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" - " processors (all in the P5 microarchitecture).\n" - "*/\n\n" - "label:\n" - "\tlock cmpxchg8b eax\n"; - - static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; - HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include in here)"); - ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); - ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput); - ImGui::SameLine(); HelpMarker("When _AllowTabInput is set, passing through the widget with Tabbing doesn't automatically activate it, in order to also cycling through subsequent widgets."); - ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine); - ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text Input/Filtered Text Input"); - if (ImGui::TreeNode("Filtered Text Input")) - { - struct TextFilters - { - // Modify character input by altering 'data->Eventchar' (ImGuiInputTextFlags_CallbackCharFilter callback) - static int FilterCasingSwap(ImGuiInputTextCallbackData* data) - { - if (data->EventChar >= 'a' && data->EventChar <= 'z') { data->EventChar -= 'a' - 'A'; } // Lowercase becomes uppercase - else if (data->EventChar >= 'A' && data->EventChar <= 'Z') { data->EventChar += 'a' - 'A'; } // Uppercase becomes lowercase - return 0; - } - - // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i', otherwise return 1 (filter out) - static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) - { - if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) - return 0; - return 1; - } - }; - - static char buf1[32] = ""; ImGui::InputText("default", buf1, 32); - static char buf2[32] = ""; ImGui::InputText("decimal", buf2, 32, ImGuiInputTextFlags_CharsDecimal); - static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, 32, ImGuiInputTextFlags_CharsUppercase); - static char buf5[32] = ""; ImGui::InputText("no blank", buf5, 32, ImGuiInputTextFlags_CharsNoBlank); - static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. - static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text Input/Password input"); - if (ImGui::TreeNode("Password Input")) - { - static char password[64] = "password123"; - ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); - ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); - ImGui::InputTextWithHint("password (w/ hint)", "", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); - ImGui::InputText("password (clear)", password, IM_ARRAYSIZE(password)); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text Input/Completion, History, Edit Callbacks"); - if (ImGui::TreeNode("Completion, History, Edit Callbacks")) - { - struct Funcs - { - static int MyCallback(ImGuiInputTextCallbackData* data) - { - if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion) - { - data->InsertChars(data->CursorPos, ".."); - } - else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory) - { - if (data->EventKey == ImGuiKey_UpArrow) - { - data->DeleteChars(0, data->BufTextLen); - data->InsertChars(0, "Pressed Up!"); - data->SelectAll(); - } - else if (data->EventKey == ImGuiKey_DownArrow) - { - data->DeleteChars(0, data->BufTextLen); - data->InsertChars(0, "Pressed Down!"); - data->SelectAll(); - } - } - else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) - { - // Toggle casing of first character - char c = data->Buf[0]; - if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32; - data->BufDirty = true; - - // Increment a counter - int* p_int = (int*)data->UserData; - *p_int = *p_int + 1; - } - return 0; - } - }; - static char buf1[64]; - ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); - ImGui::SameLine(); HelpMarker( - "Here we append \"..\" each time Tab is pressed. " - "See 'Examples>Console' for a more meaningful demonstration of using this callback."); - - static char buf2[64]; - ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); - ImGui::SameLine(); HelpMarker( - "Here we replace and select text each time Up/Down are pressed. " - "See 'Examples>Console' for a more meaningful demonstration of using this callback."); - - static char buf3[64]; - static int edit_count = 0; - ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); - ImGui::SameLine(); HelpMarker( - "Here we toggle the casing of the first character on every edit + count edits."); - ImGui::SameLine(); ImGui::Text("(%d)", edit_count); - - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text Input/Resize Callback"); - if (ImGui::TreeNode("Resize Callback")) - { - // To wire InputText() with std::string or any other custom string type, - // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper - // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. - HelpMarker( - "Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n" - "See misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); - struct Funcs - { - static int MyResizeCallback(ImGuiInputTextCallbackData* data) - { - if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) - { - ImVector* my_str = (ImVector*)data->UserData; - IM_ASSERT(my_str->begin() == data->Buf); - my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1 - data->Buf = my_str->begin(); - } - return 0; - } - - // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace. - // For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)' - static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) - { - IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); - return ImGui::InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str); - } - }; - - // For this demo we are using ImVector as a string container. - // Note that because we need to store a terminating zero character, our size/capacity are 1 more - // than usually reported by a typical string class. - static ImVector my_str; - if (my_str.empty()) - my_str.push_back(0); - Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16)); - ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity()); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text Input/Eliding, Alignment"); - if (ImGui::TreeNode("Eliding, Alignment")) - { - static char buf1[128] = "/path/to/some/folder/with/long/filename.cpp"; - static ImGuiInputTextFlags flags = ImGuiInputTextFlags_ElideLeft; - ImGui::CheckboxFlags("ImGuiInputTextFlags_ElideLeft", &flags, ImGuiInputTextFlags_ElideLeft); - ImGui::InputText("Path", buf1, IM_ARRAYSIZE(buf1), flags); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Text Input/Miscellaneous"); - if (ImGui::TreeNode("Miscellaneous")) - { - static char buf1[16]; - static ImGuiInputTextFlags flags = ImGuiInputTextFlags_EscapeClearsAll; - ImGui::CheckboxFlags("ImGuiInputTextFlags_EscapeClearsAll", &flags, ImGuiInputTextFlags_EscapeClearsAll); - ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); - ImGui::CheckboxFlags("ImGuiInputTextFlags_NoUndoRedo", &flags, ImGuiInputTextFlags_NoUndoRedo); - ImGui::InputText("Hello", buf1, IM_ARRAYSIZE(buf1), flags); - ImGui::TreePop(); - } - - ImGui::TreePop(); - } - // Tabs IMGUI_DEMO_MARKER("Widgets/Tabs"); if (ImGui::TreeNode("Tabs")) @@ -2240,26 +1910,6 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::SameLine(); HelpMarker("Demonstrate using BeginDisabled()/EndDisabled() across this section."); ImGui::TreePop(); } - - IMGUI_DEMO_MARKER("Widgets/Text Filter"); - if (ImGui::TreeNode("Text Filter")) - { - // Helper class to easy setup a text filter. - // You may want to implement a more feature-full filtering scheme in your own application. - HelpMarker("Not a widget per-se, but ImGuiTextFilter is a helper to perform simple filtering on text strings."); - static ImGuiTextFilter filter; - ImGui::Text("Filter usage:\n" - " \"\" display all lines\n" - " \"xxx\" display lines containing \"xxx\"\n" - " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" - " \"-xxx\" hide lines containing \"xxx\""); - filter.Draw(); - const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; - for (int i = 0; i < IM_ARRAYSIZE(lines); i++) - if (filter.PassFilter(lines[i])) - ImGui::BulletText("%s", lines[i]); - ImGui::TreePop(); - } } //----------------------------------------------------------------------------- @@ -2817,6 +2467,146 @@ static void DemoWindowWidgetsListBoxes() // [SECTION] DemoWindowWidgetsSelectables() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsSelectables() +{ + IMGUI_DEMO_MARKER("Widgets/Selectables"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Selectables")) + { + // Selectable() has 2 overloads: + // - The one taking "bool selected" as a read-only selection information. + // When Selectable() has been clicked it returns true and you can alter selection state accordingly. + // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) + // The earlier is more flexible, as in real application your selection may be stored in many different ways + // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). + IMGUI_DEMO_MARKER("Widgets/Selectables/Basic"); + if (ImGui::TreeNode("Basic")) + { + static bool selection[5] = { false, true, false, false }; + ImGui::Selectable("1. I am selectable", &selection[0]); + ImGui::Selectable("2. I am selectable", &selection[1]); + ImGui::Selectable("3. I am selectable", &selection[2]); + if (ImGui::Selectable("4. I am double clickable", selection[3], ImGuiSelectableFlags_AllowDoubleClick)) + if (ImGui::IsMouseDoubleClicked(0)) + selection[3] = !selection[3]; + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selectables/Rendering more items on the same line"); + if (ImGui::TreeNode("Rendering more items on the same line")) + { + // (1) Using SetNextItemAllowOverlap() + // (2) Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. + static bool selected[3] = { false, false, false }; + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(); ImGui::SmallButton("Link 1"); + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(); ImGui::SmallButton("Link 2"); + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(); ImGui::SmallButton("Link 3"); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selectables/In Tables"); + if (ImGui::TreeNode("In Tables")) + { + static bool selected[10] = {}; + + if (ImGui::BeginTable("split1", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) + { + for (int i = 0; i < 10; i++) + { + char label[32]; + sprintf(label, "Item %d", i); + ImGui::TableNextColumn(); + ImGui::Selectable(label, &selected[i]); // FIXME-TABLE: Selection overlap + } + ImGui::EndTable(); + } + ImGui::Spacing(); + if (ImGui::BeginTable("split2", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) + { + for (int i = 0; i < 10; i++) + { + char label[32]; + sprintf(label, "Item %d", i); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Selectable(label, &selected[i], ImGuiSelectableFlags_SpanAllColumns); + ImGui::TableNextColumn(); + ImGui::Text("Some other contents"); + ImGui::TableNextColumn(); + ImGui::Text("123456"); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selectables/Grid"); + if (ImGui::TreeNode("Grid")) + { + static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; + + // Add in a bit of silly fun... + const float time = (float)ImGui::GetTime(); + const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected... + if (winning_state) + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f))); + + for (int y = 0; y < 4; y++) + for (int x = 0; x < 4; x++) + { + if (x > 0) + ImGui::SameLine(); + ImGui::PushID(y * 4 + x); + if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(50, 50))) + { + // Toggle clicked cell + toggle neighbors + selected[y][x] ^= 1; + if (x > 0) { selected[y][x - 1] ^= 1; } + if (x < 3) { selected[y][x + 1] ^= 1; } + if (y > 0) { selected[y - 1][x] ^= 1; } + if (y < 3) { selected[y + 1][x] ^= 1; } + } + ImGui::PopID(); + } + + if (winning_state) + ImGui::PopStyleVar(); + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment"); + if (ImGui::TreeNode("Alignment")) + { + HelpMarker( + "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item " + "basis using PushStyleVar(). You'll probably want to always keep your default situation to " + "left-align otherwise it becomes difficult to layout multiple items on a same line"); + static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true }; + for (int y = 0; y < 3; y++) + { + for (int x = 0; x < 3; x++) + { + ImVec2 alignment = ImVec2((float)x / 2.0f, (float)y / 2.0f); + char name[32]; + sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y); + if (x > 0) ImGui::SameLine(); + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment); + ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80)); + ImGui::PopStyleVar(); + } + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsSelectionAndMultiSelect() +//----------------------------------------------------------------------------- +// Multi-selection demos +// Also read: https://github.com/ocornut/imgui/wiki/Multi-Select +//----------------------------------------------------------------------------- + static const char* ExampleNames[] = { "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper", @@ -3042,13 +2832,6 @@ struct ExampleDualListBox } }; -//----------------------------------------------------------------------------- -// [SECTION] DemoWindowWidgetsSelectionAndMultiSelect() -//----------------------------------------------------------------------------- -// Multi-selection demos -// Also read: https://github.com/ocornut/imgui/wiki/Multi-Select -//----------------------------------------------------------------------------- - static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data) { IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); @@ -3874,10 +3657,242 @@ static void DemoWindowWidgetsText() // [SECTION] DemoWindowWidgetsTextFilter() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsTextFilter() +{ + IMGUI_DEMO_MARKER("Widgets/Text Filter"); + if (ImGui::TreeNode("Text Filter")) + { + // Helper class to easy setup a text filter. + // You may want to implement a more feature-full filtering scheme in your own application. + HelpMarker("Not a widget per-se, but ImGuiTextFilter is a helper to perform simple filtering on text strings."); + static ImGuiTextFilter filter; + ImGui::Text("Filter usage:\n" + " \"\" display all lines\n" + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + filter.Draw(); + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (int i = 0; i < IM_ARRAYSIZE(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsTextInput() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsTextInput() +{ + // To wire InputText() with std::string or any other custom string type, + // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. + IMGUI_DEMO_MARKER("Widgets/Text Input"); + if (ImGui::TreeNode("Text Input")) + { + IMGUI_DEMO_MARKER("Widgets/Text Input/Multi-line Text Input"); + if (ImGui::TreeNode("Multi-line Text Input")) + { + // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize + // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings. + static char text[1024 * 16] = + "/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n"; + + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; + HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include in here)"); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput); + ImGui::SameLine(); HelpMarker("When _AllowTabInput is set, passing through the widget with Tabbing doesn't automatically activate it, in order to also cycling through subsequent widgets."); + ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine); + ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Filtered Text Input"); + if (ImGui::TreeNode("Filtered Text Input")) + { + struct TextFilters + { + // Modify character input by altering 'data->Eventchar' (ImGuiInputTextFlags_CallbackCharFilter callback) + static int FilterCasingSwap(ImGuiInputTextCallbackData* data) + { + if (data->EventChar >= 'a' && data->EventChar <= 'z') { data->EventChar -= 'a' - 'A'; } // Lowercase becomes uppercase + else if (data->EventChar >= 'A' && data->EventChar <= 'Z') { data->EventChar += 'a' - 'A'; } // Uppercase becomes lowercase + return 0; + } + + // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i', otherwise return 1 (filter out) + static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) + { + if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) + return 0; + return 1; + } + }; + + static char buf1[32] = ""; ImGui::InputText("default", buf1, 32); + static char buf2[32] = ""; ImGui::InputText("decimal", buf2, 32, ImGuiInputTextFlags_CharsDecimal); + static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, 32, ImGuiInputTextFlags_CharsUppercase); + static char buf5[32] = ""; ImGui::InputText("no blank", buf5, 32, ImGuiInputTextFlags_CharsNoBlank); + static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. + static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Password input"); + if (ImGui::TreeNode("Password Input")) + { + static char password[64] = "password123"; + ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); + ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputTextWithHint("password (w/ hint)", "", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); + ImGui::InputText("password (clear)", password, IM_ARRAYSIZE(password)); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Completion, History, Edit Callbacks"); + if (ImGui::TreeNode("Completion, History, Edit Callbacks")) + { + struct Funcs + { + static int MyCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion) + { + data->InsertChars(data->CursorPos, ".."); + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory) + { + if (data->EventKey == ImGuiKey_UpArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Up!"); + data->SelectAll(); + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Down!"); + data->SelectAll(); + } + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) + { + // Toggle casing of first character + char c = data->Buf[0]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32; + data->BufDirty = true; + + // Increment a counter + int* p_int = (int*)data->UserData; + *p_int = *p_int + 1; + } + return 0; + } + }; + static char buf1[64]; + ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); + ImGui::SameLine(); HelpMarker( + "Here we append \"..\" each time Tab is pressed. " + "See 'Examples>Console' for a more meaningful demonstration of using this callback."); + + static char buf2[64]; + ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); + ImGui::SameLine(); HelpMarker( + "Here we replace and select text each time Up/Down are pressed. " + "See 'Examples>Console' for a more meaningful demonstration of using this callback."); + + static char buf3[64]; + static int edit_count = 0; + ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); + ImGui::SameLine(); HelpMarker( + "Here we toggle the casing of the first character on every edit + count edits."); + ImGui::SameLine(); ImGui::Text("(%d)", edit_count); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Resize Callback"); + if (ImGui::TreeNode("Resize Callback")) + { + // To wire InputText() with std::string or any other custom string type, + // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper + // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. + HelpMarker( + "Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n" + "See misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); + struct Funcs + { + static int MyResizeCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) + { + ImVector* my_str = (ImVector*)data->UserData; + IM_ASSERT(my_str->begin() == data->Buf); + my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1 + data->Buf = my_str->begin(); + } + return 0; + } + + // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace. + // For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)' + static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) + { + IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); + return ImGui::InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str); + } + }; + + // For this demo we are using ImVector as a string container. + // Note that because we need to store a terminating zero character, our size/capacity are 1 more + // than usually reported by a typical string class. + static ImVector my_str; + if (my_str.empty()) + my_str.push_back(0); + Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16)); + ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity()); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Eliding, Alignment"); + if (ImGui::TreeNode("Eliding, Alignment")) + { + static char buf1[128] = "/path/to/some/folder/with/long/filename.cpp"; + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_ElideLeft; + ImGui::CheckboxFlags("ImGuiInputTextFlags_ElideLeft", &flags, ImGuiInputTextFlags_ElideLeft); + ImGui::InputText("Path", buf1, IM_ARRAYSIZE(buf1), flags); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Miscellaneous"); + if (ImGui::TreeNode("Miscellaneous")) + { + static char buf1[16]; + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_EscapeClearsAll; + ImGui::CheckboxFlags("ImGuiInputTextFlags_EscapeClearsAll", &flags, ImGuiInputTextFlags_EscapeClearsAll); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_NoUndoRedo", &flags, ImGuiInputTextFlags_NoUndoRedo); + ImGui::InputText("Hello", buf1, IM_ARRAYSIZE(buf1), flags); + ImGui::TreePop(); + } + + ImGui::TreePop(); + } + +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsTooltips() //----------------------------------------------------------------------------- From 4d0c776a8089ccaa272f1cf51097e1d606f66d99 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 18:08:22 +0100 Subject: [PATCH 0743/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsPlotting(), DemoWindowWidgetsProgressBars(), DemoWindowWidgetsTabs() sections. --- imgui_demo.cpp | 505 +++++++++++++++++++++++++------------------------ 1 file changed, 259 insertions(+), 246 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 56688d4c4..468e32b59 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -256,8 +256,11 @@ static void DemoWindowWidgetsCollapsingHeaders(); static void DemoWindowWidgetsComboBoxes(); static void DemoWindowWidgetsImages(); static void DemoWindowWidgetsListBoxes(); +static void DemoWindowWidgetsPlotting(); +static void DemoWindowWidgetsProgressBars(); static void DemoWindowWidgetsSelectables(); static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); +static void DemoWindowWidgetsTabs(); static void DemoWindowWidgetsText(); static void DemoWindowWidgetsTextFilter(); static void DemoWindowWidgetsTextInput(); @@ -825,260 +828,17 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsComboBoxes(); DemoWindowWidgetsImages(); DemoWindowWidgetsListBoxes(); + DemoWindowWidgetsPlotting(); + DemoWindowWidgetsProgressBars(); DemoWindowWidgetsSelectables(); DemoWindowWidgetsSelectionAndMultiSelect(demo_data); + DemoWindowWidgetsTabs(); DemoWindowWidgetsText(); DemoWindowWidgetsTextFilter(); DemoWindowWidgetsTextInput(); DemoWindowWidgetsTooltips(); DemoWindowWidgetsTreeNodes(); - // Tabs - IMGUI_DEMO_MARKER("Widgets/Tabs"); - if (ImGui::TreeNode("Tabs")) - { - IMGUI_DEMO_MARKER("Widgets/Tabs/Basic"); - if (ImGui::TreeNode("Basic")) - { - ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None; - if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) - { - if (ImGui::BeginTabItem("Avocado")) - { - ImGui::Text("This is the Avocado tab!\nblah blah blah blah blah"); - ImGui::EndTabItem(); - } - if (ImGui::BeginTabItem("Broccoli")) - { - ImGui::Text("This is the Broccoli tab!\nblah blah blah blah blah"); - ImGui::EndTabItem(); - } - if (ImGui::BeginTabItem("Cucumber")) - { - ImGui::Text("This is the Cucumber tab!\nblah blah blah blah blah"); - ImGui::EndTabItem(); - } - ImGui::EndTabBar(); - } - ImGui::Separator(); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Tabs/Advanced & Close Button"); - if (ImGui::TreeNode("Advanced & Close Button")) - { - // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). - static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable; - ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", &tab_bar_flags, ImGuiTabBarFlags_Reorderable); - ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs); - ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); - ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); - ImGui::CheckboxFlags("ImGuiTabBarFlags_DrawSelectedOverline", &tab_bar_flags, ImGuiTabBarFlags_DrawSelectedOverline); - if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) - tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) - tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) - tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); - - // Tab Bar - ImGui::AlignTextToFramePadding(); - ImGui::Text("Opened:"); - const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" }; - static bool opened[4] = { true, true, true, true }; // Persistent user state - for (int n = 0; n < IM_ARRAYSIZE(opened); n++) - { - ImGui::SameLine(); - ImGui::Checkbox(names[n], &opened[n]); - } - - // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): - // the underlying bool will be set to false when the tab is closed. - if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) - { - for (int n = 0; n < IM_ARRAYSIZE(opened); n++) - if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None)) - { - ImGui::Text("This is the %s tab!", names[n]); - if (n & 1) - ImGui::Text("I am an odd tab."); - ImGui::EndTabItem(); - } - ImGui::EndTabBar(); - } - ImGui::Separator(); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Tabs/TabItemButton & Leading-Trailing flags"); - if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags")) - { - static ImVector active_tabs; - static int next_tab_id = 0; - if (next_tab_id == 0) // Initialize with some default tabs - for (int i = 0; i < 3; i++) - active_tabs.push_back(next_tab_id++); - - // TabItemButton() and Leading/Trailing flags are distinct features which we will demo together. - // (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags... - // but they tend to make more sense together) - static bool show_leading_button = true; - static bool show_trailing_button = true; - ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button); - ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); - - // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs - static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; - ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) - tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) - tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); - - if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) - { - // Demo a Leading TabItemButton(): click the "?" button to open a menu - if (show_leading_button) - if (ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) - ImGui::OpenPopup("MyHelpMenu"); - if (ImGui::BeginPopup("MyHelpMenu")) - { - ImGui::Selectable("Hello!"); - ImGui::EndPopup(); - } - - // Demo Trailing Tabs: click the "+" button to add a new tab. - // (In your app you may want to use a font icon instead of the "+") - // We submit it before the regular tabs, but thanks to the ImGuiTabItemFlags_Trailing flag it will always appear at the end. - if (show_trailing_button) - if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) - active_tabs.push_back(next_tab_id++); // Add new tab - - // Submit our regular tabs - for (int n = 0; n < active_tabs.Size; ) - { - bool open = true; - char name[16]; - snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]); - if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None)) - { - ImGui::Text("This is the %s tab!", name); - ImGui::EndTabItem(); - } - - if (!open) - active_tabs.erase(active_tabs.Data + n); - else - n++; - } - - ImGui::EndTabBar(); - } - ImGui::Separator(); - ImGui::TreePop(); - } - ImGui::TreePop(); - } - - // Plot/Graph widgets are not very good. - // Consider using a third-party library such as ImPlot: https://github.com/epezent/implot - // (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions) - IMGUI_DEMO_MARKER("Widgets/Plotting"); - if (ImGui::TreeNode("Plotting")) - { - static bool animate = true; - ImGui::Checkbox("Animate", &animate); - - // Plot as lines and plot as histogram - static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); - ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); - //ImGui::SameLine(); HelpMarker("Consider using ImPlot instead!"); - - // Fill an array of contiguous float values to plot - // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float - // and the sizeof() of your structure in the "stride" parameter. - static float values[90] = {}; - static int values_offset = 0; - static double refresh_time = 0.0; - if (!animate || refresh_time == 0.0) - refresh_time = ImGui::GetTime(); - while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo - { - static float phase = 0.0f; - values[values_offset] = cosf(phase); - values_offset = (values_offset + 1) % IM_ARRAYSIZE(values); - phase += 0.10f * values_offset; - refresh_time += 1.0f / 60.0f; - } - - // Plots can display overlay texts - // (in this example, we will display an average value) - { - float average = 0.0f; - for (int n = 0; n < IM_ARRAYSIZE(values); n++) - average += values[n]; - average /= (float)IM_ARRAYSIZE(values); - char overlay[32]; - sprintf(overlay, "avg %f", average); - ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); - } - - // Use functions to generate output - // FIXME: This is actually VERY awkward because current plot API only pass in indices. - // We probably want an API passing floats and user provide sample rate/count. - struct Funcs - { - static float Sin(void*, int i) { return sinf(i * 0.1f); } - static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; } - }; - static int func_type = 0, display_count = 70; - ImGui::SeparatorText("Functions"); - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); - ImGui::Combo("func", &func_type, "Sin\0Saw\0"); - ImGui::SameLine(); - ImGui::SliderInt("Sample count", &display_count, 1, 400); - float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; - ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); - ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); - ImGui::Separator(); - - ImGui::Text("Need better plotting and graphing? Consider using ImPlot:"); - ImGui::TextLinkOpenURL("https://github.com/epezent/implot"); - ImGui::Separator(); - - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Progress Bars"); - if (ImGui::TreeNode("Progress Bars")) - { - // Animate a simple progress bar - static float progress = 0.0f, progress_dir = 1.0f; - progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; - if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; } - if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } - - // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width, - // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. - ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f)); - ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); - ImGui::Text("Progress Bar"); - - float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f); - char buf[32]; - sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753); - ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf); - - // Pass an animated negative value, e.g. -1.0f * (float)ImGui::GetTime() is the recommended value. - // Adjust the factor if you want to adjust the animation speed. - ImGui::ProgressBar(-1.0f * (float)ImGui::GetTime(), ImVec2(0.0f, 0.0f), "Searching.."); - ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); - ImGui::Text("Indeterminate"); - - ImGui::TreePop(); - } - IMGUI_DEMO_MARKER("Widgets/Color"); if (ImGui::TreeNode("Color/Picker Widgets")) { @@ -2455,10 +2215,114 @@ static void DemoWindowWidgetsListBoxes() // [SECTION] DemoWindowWidgetsPlotting() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsPlotting() +{ + // Plot/Graph widgets are not very good. +// Consider using a third-party library such as ImPlot: https://github.com/epezent/implot +// (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions) + IMGUI_DEMO_MARKER("Widgets/Plotting"); + if (ImGui::TreeNode("Plotting")) + { + ImGui::Text("Need better plotting and graphing? Consider using ImPlot:"); + ImGui::TextLinkOpenURL("https://github.com/epezent/implot"); + ImGui::Separator(); + + static bool animate = true; + ImGui::Checkbox("Animate", &animate); + + // Plot as lines and plot as histogram + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); + //ImGui::SameLine(); HelpMarker("Consider using ImPlot instead!"); + + // Fill an array of contiguous float values to plot + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float + // and the sizeof() of your structure in the "stride" parameter. + static float values[90] = {}; + static int values_offset = 0; + static double refresh_time = 0.0; + if (!animate || refresh_time == 0.0) + refresh_time = ImGui::GetTime(); + while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo + { + static float phase = 0.0f; + values[values_offset] = cosf(phase); + values_offset = (values_offset + 1) % IM_ARRAYSIZE(values); + phase += 0.10f * values_offset; + refresh_time += 1.0f / 60.0f; + } + + // Plots can display overlay texts + // (in this example, we will display an average value) + { + float average = 0.0f; + for (int n = 0; n < IM_ARRAYSIZE(values); n++) + average += values[n]; + average /= (float)IM_ARRAYSIZE(values); + char overlay[32]; + sprintf(overlay, "avg %f", average); + ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); + } + + // Use functions to generate output + // FIXME: This is actually VERY awkward because current plot API only pass in indices. + // We probably want an API passing floats and user provide sample rate/count. + struct Funcs + { + static float Sin(void*, int i) { return sinf(i * 0.1f); } + static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; } + }; + static int func_type = 0, display_count = 70; + ImGui::SeparatorText("Functions"); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::Combo("func", &func_type, "Sin\0Saw\0"); + ImGui::SameLine(); + ImGui::SliderInt("Sample count", &display_count, 1, 400); + float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; + ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsProgressBars() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsProgressBars() +{ + IMGUI_DEMO_MARKER("Widgets/Progress Bars"); + if (ImGui::TreeNode("Progress Bars")) + { + // Animate a simple progress bar + static float progress = 0.0f, progress_dir = 1.0f; + progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; + if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; } + if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } + + // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width, + // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. + ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f)); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Progress Bar"); + + float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f); + char buf[32]; + sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf); + + // Pass an animated negative value, e.g. -1.0f * (float)ImGui::GetTime() is the recommended value. + // Adjust the factor if you want to adjust the animation speed. + ImGui::ProgressBar(-1.0f * (float)ImGui::GetTime(), ImVec2(0.0f, 0.0f), "Searching.."); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Indeterminate"); + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsQueryingStatuses() //----------------------------------------------------------------------------- @@ -3571,6 +3435,155 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // [SECTION] DemoWindowWidgetsTabs() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsTabs() +{ + IMGUI_DEMO_MARKER("Widgets/Tabs"); + if (ImGui::TreeNode("Tabs")) + { + IMGUI_DEMO_MARKER("Widgets/Tabs/Basic"); + if (ImGui::TreeNode("Basic")) + { + ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None; + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + if (ImGui::BeginTabItem("Avocado")) + { + ImGui::Text("This is the Avocado tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Broccoli")) + { + ImGui::Text("This is the Broccoli tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Cucumber")) + { + ImGui::Text("This is the Cucumber tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tabs/Advanced & Close Button"); + if (ImGui::TreeNode("Advanced & Close Button")) + { + // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable; + ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", &tab_bar_flags, ImGuiTabBarFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs); + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); + ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); + ImGui::CheckboxFlags("ImGuiTabBarFlags_DrawSelectedOverline", &tab_bar_flags, ImGuiTabBarFlags_DrawSelectedOverline); + if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) + tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); + + // Tab Bar + ImGui::AlignTextToFramePadding(); + ImGui::Text("Opened:"); + const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" }; + static bool opened[4] = { true, true, true, true }; // Persistent user state + for (int n = 0; n < IM_ARRAYSIZE(opened); n++) + { + ImGui::SameLine(); + ImGui::Checkbox(names[n], &opened[n]); + } + + // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): + // the underlying bool will be set to false when the tab is closed. + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + for (int n = 0; n < IM_ARRAYSIZE(opened); n++) + if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None)) + { + ImGui::Text("This is the %s tab!", names[n]); + if (n & 1) + ImGui::Text("I am an odd tab."); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tabs/TabItemButton & Leading-Trailing flags"); + if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags")) + { + static ImVector active_tabs; + static int next_tab_id = 0; + if (next_tab_id == 0) // Initialize with some default tabs + for (int i = 0; i < 3; i++) + active_tabs.push_back(next_tab_id++); + + // TabItemButton() and Leading/Trailing flags are distinct features which we will demo together. + // (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags... + // but they tend to make more sense together) + static bool show_leading_button = true; + static bool show_trailing_button = true; + ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button); + ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); + + // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); + + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + // Demo a Leading TabItemButton(): click the "?" button to open a menu + if (show_leading_button) + if (ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) + ImGui::OpenPopup("MyHelpMenu"); + if (ImGui::BeginPopup("MyHelpMenu")) + { + ImGui::Selectable("Hello!"); + ImGui::EndPopup(); + } + + // Demo Trailing Tabs: click the "+" button to add a new tab. + // (In your app you may want to use a font icon instead of the "+") + // We submit it before the regular tabs, but thanks to the ImGuiTabItemFlags_Trailing flag it will always appear at the end. + if (show_trailing_button) + if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) + active_tabs.push_back(next_tab_id++); // Add new tab + + // Submit our regular tabs + for (int n = 0; n < active_tabs.Size; ) + { + bool open = true; + char name[16]; + snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]); + if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None)) + { + ImGui::Text("This is the %s tab!", name); + ImGui::EndTabItem(); + } + + if (!open) + active_tabs.erase(active_tabs.Data + n); + else + n++; + } + + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsText() //----------------------------------------------------------------------------- From 510a9a77d6ad5f2ab017ea7d13979e80a5a53989 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 18:11:16 +0100 Subject: [PATCH 0744/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsDataTypes() section. --- imgui_demo.cpp | 261 +++++++++++++++++++++++++------------------------ 1 file changed, 133 insertions(+), 128 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 468e32b59..692f67af4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -254,6 +254,7 @@ static void DemoWindowWidgetsBasic(); static void DemoWindowWidgetsBullets(); static void DemoWindowWidgetsCollapsingHeaders(); static void DemoWindowWidgetsComboBoxes(); +static void DemoWindowWidgetsDataTypes(); static void DemoWindowWidgetsImages(); static void DemoWindowWidgetsListBoxes(); static void DemoWindowWidgetsPlotting(); @@ -826,6 +827,7 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsBullets(); DemoWindowWidgetsCollapsingHeaders(); DemoWindowWidgetsComboBoxes(); + DemoWindowWidgetsDataTypes(); DemoWindowWidgetsImages(); DemoWindowWidgetsListBoxes(); DemoWindowWidgetsPlotting(); @@ -1087,134 +1089,6 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Data Types"); - if (ImGui::TreeNode("Data Types")) - { - // DragScalar/InputScalar/SliderScalar functions allow various data types - // - signed/unsigned - // - 8/16/32/64-bits - // - integer/float/double - // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum - // to pass the type, and passing all arguments by pointer. - // This is the reason the test code below creates local variables to hold "zero" "one" etc. for each type. - // In practice, if you frequently use a given type that is not covered by the normal API entry points, - // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*, - // and then pass their address to the generic function. For example: - // bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld") - // { - // return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format); - // } - - // Setup limits (as helper variables so we can take their address, as explained above) - // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. - #ifndef LLONG_MIN - ImS64 LLONG_MIN = -9223372036854775807LL - 1; - ImS64 LLONG_MAX = 9223372036854775807LL; - ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1); - #endif - const char s8_zero = 0, s8_one = 1, s8_fifty = 50, s8_min = -128, s8_max = 127; - const ImU8 u8_zero = 0, u8_one = 1, u8_fifty = 50, u8_min = 0, u8_max = 255; - const short s16_zero = 0, s16_one = 1, s16_fifty = 50, s16_min = -32768, s16_max = 32767; - const ImU16 u16_zero = 0, u16_one = 1, u16_fifty = 50, u16_min = 0, u16_max = 65535; - const ImS32 s32_zero = 0, s32_one = 1, s32_fifty = 50, s32_min = INT_MIN/2, s32_max = INT_MAX/2, s32_hi_a = INT_MAX/2 - 100, s32_hi_b = INT_MAX/2; - const ImU32 u32_zero = 0, u32_one = 1, u32_fifty = 50, u32_min = 0, u32_max = UINT_MAX/2, u32_hi_a = UINT_MAX/2 - 100, u32_hi_b = UINT_MAX/2; - const ImS64 s64_zero = 0, s64_one = 1, s64_fifty = 50, s64_min = LLONG_MIN/2, s64_max = LLONG_MAX/2, s64_hi_a = LLONG_MAX/2 - 100, s64_hi_b = LLONG_MAX/2; - const ImU64 u64_zero = 0, u64_one = 1, u64_fifty = 50, u64_min = 0, u64_max = ULLONG_MAX/2, u64_hi_a = ULLONG_MAX/2 - 100, u64_hi_b = ULLONG_MAX/2; - const float f32_zero = 0.f, f32_one = 1.f, f32_lo_a = -10000000000.0f, f32_hi_a = +10000000000.0f; - const double f64_zero = 0., f64_one = 1., f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0; - - // State - static char s8_v = 127; - static ImU8 u8_v = 255; - static short s16_v = 32767; - static ImU16 u16_v = 65535; - static ImS32 s32_v = -1; - static ImU32 u32_v = (ImU32)-1; - static ImS64 s64_v = -1; - static ImU64 u64_v = (ImU64)-1; - static float f32_v = 0.123f; - static double f64_v = 90000.01234567890123456789; - - const float drag_speed = 0.2f; - static bool drag_clamp = false; - IMGUI_DEMO_MARKER("Widgets/Data Types/Drags"); - ImGui::SeparatorText("Drags"); - ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); - ImGui::SameLine(); HelpMarker( - "As with every widget in dear imgui, we never modify values unless there is a user interaction.\n" - "You can override the clamping limits by using CTRL+Click to input a value."); - ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL); - ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms"); - ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL); - ImGui::DragScalar("drag u16", ImGuiDataType_U16, &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, "%u ms"); - ImGui::DragScalar("drag s32", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL); - ImGui::DragScalar("drag s32 hex", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL, "0x%08X"); - ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms"); - ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL); - ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL); - ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f"); - ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic); - ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams"); - ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic); - - IMGUI_DEMO_MARKER("Widgets/Data Types/Sliders"); - ImGui::SeparatorText("Sliders"); - ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); - ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u"); - ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d"); - ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u"); - ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d"); - ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d"); - ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d"); - ImGui::SliderScalar("slider s32 hex", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty, "0x%04X"); - ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u"); - ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u"); - ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u"); - ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%" PRId64); - ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%" PRId64); - ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%" PRId64); - ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%" PRIu64 " ms"); - ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%" PRIu64 " ms"); - ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%" PRIu64 " ms"); - ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); - ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic); - ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); - ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams"); - ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic); - ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); - - ImGui::SeparatorText("Sliders (reverse)"); - ImGui::SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d"); - ImGui::SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u"); - ImGui::SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, &s32_fifty, &s32_zero, "%d"); - ImGui::SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, &u32_fifty, &u32_zero, "%u"); - ImGui::SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, &s64_fifty, &s64_zero, "%" PRId64); - ImGui::SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, &u64_fifty, &u64_zero, "%" PRIu64 " ms"); - - IMGUI_DEMO_MARKER("Widgets/Data Types/Inputs"); - static bool inputs_step = true; - static ImGuiInputTextFlags flags = ImGuiInputTextFlags_None; - ImGui::SeparatorText("Inputs"); - ImGui::Checkbox("Show step buttons", &inputs_step); - ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); - ImGui::CheckboxFlags("ImGuiInputTextFlags_ParseEmptyRefVal", &flags, ImGuiInputTextFlags_ParseEmptyRefVal); - ImGui::CheckboxFlags("ImGuiInputTextFlags_DisplayEmptyRefVal", &flags, ImGuiInputTextFlags_DisplayEmptyRefVal); - ImGui::InputScalar("input s8", ImGuiDataType_S8, &s8_v, inputs_step ? &s8_one : NULL, NULL, "%d", flags); - ImGui::InputScalar("input u8", ImGuiDataType_U8, &u8_v, inputs_step ? &u8_one : NULL, NULL, "%u", flags); - ImGui::InputScalar("input s16", ImGuiDataType_S16, &s16_v, inputs_step ? &s16_one : NULL, NULL, "%d", flags); - ImGui::InputScalar("input u16", ImGuiDataType_U16, &u16_v, inputs_step ? &u16_one : NULL, NULL, "%u", flags); - ImGui::InputScalar("input s32", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%d", flags); - ImGui::InputScalar("input s32 hex", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%04X", flags); - ImGui::InputScalar("input u32", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%u", flags); - ImGui::InputScalar("input u32 hex", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%08X", flags); - ImGui::InputScalar("input s64", ImGuiDataType_S64, &s64_v, inputs_step ? &s64_one : NULL, NULL, NULL, flags); - ImGui::InputScalar("input u64", ImGuiDataType_U64, &u64_v, inputs_step ? &u64_one : NULL, NULL, NULL, flags); - ImGui::InputScalar("input float", ImGuiDataType_Float, &f32_v, inputs_step ? &f32_one : NULL, NULL, NULL, flags); - ImGui::InputScalar("input double", ImGuiDataType_Double, &f64_v, inputs_step ? &f64_one : NULL, NULL, NULL, flags); - - ImGui::TreePop(); - } - IMGUI_DEMO_MARKER("Widgets/Multi-component Widgets"); if (ImGui::TreeNode("Multi-component Widgets")) { @@ -2041,6 +1915,137 @@ static void DemoWindowWidgetsComboBoxes() // [SECTION] DemoWindowWidgetsDataTypes() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsDataTypes() +{ + IMGUI_DEMO_MARKER("Widgets/Data Types"); + if (ImGui::TreeNode("Data Types")) + { + // DragScalar/InputScalar/SliderScalar functions allow various data types + // - signed/unsigned + // - 8/16/32/64-bits + // - integer/float/double + // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum + // to pass the type, and passing all arguments by pointer. + // This is the reason the test code below creates local variables to hold "zero" "one" etc. for each type. + // In practice, if you frequently use a given type that is not covered by the normal API entry points, + // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*, + // and then pass their address to the generic function. For example: + // bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld") + // { + // return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format); + // } + + // Setup limits (as helper variables so we can take their address, as explained above) + // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. + #ifndef LLONG_MIN + ImS64 LLONG_MIN = -9223372036854775807LL - 1; + ImS64 LLONG_MAX = 9223372036854775807LL; + ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1); + #endif + const char s8_zero = 0, s8_one = 1, s8_fifty = 50, s8_min = -128, s8_max = 127; + const ImU8 u8_zero = 0, u8_one = 1, u8_fifty = 50, u8_min = 0, u8_max = 255; + const short s16_zero = 0, s16_one = 1, s16_fifty = 50, s16_min = -32768, s16_max = 32767; + const ImU16 u16_zero = 0, u16_one = 1, u16_fifty = 50, u16_min = 0, u16_max = 65535; + const ImS32 s32_zero = 0, s32_one = 1, s32_fifty = 50, s32_min = INT_MIN/2, s32_max = INT_MAX/2, s32_hi_a = INT_MAX/2 - 100, s32_hi_b = INT_MAX/2; + const ImU32 u32_zero = 0, u32_one = 1, u32_fifty = 50, u32_min = 0, u32_max = UINT_MAX/2, u32_hi_a = UINT_MAX/2 - 100, u32_hi_b = UINT_MAX/2; + const ImS64 s64_zero = 0, s64_one = 1, s64_fifty = 50, s64_min = LLONG_MIN/2, s64_max = LLONG_MAX/2, s64_hi_a = LLONG_MAX/2 - 100, s64_hi_b = LLONG_MAX/2; + const ImU64 u64_zero = 0, u64_one = 1, u64_fifty = 50, u64_min = 0, u64_max = ULLONG_MAX/2, u64_hi_a = ULLONG_MAX/2 - 100, u64_hi_b = ULLONG_MAX/2; + const float f32_zero = 0.f, f32_one = 1.f, f32_lo_a = -10000000000.0f, f32_hi_a = +10000000000.0f; + const double f64_zero = 0., f64_one = 1., f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0; + + // State + static char s8_v = 127; + static ImU8 u8_v = 255; + static short s16_v = 32767; + static ImU16 u16_v = 65535; + static ImS32 s32_v = -1; + static ImU32 u32_v = (ImU32)-1; + static ImS64 s64_v = -1; + static ImU64 u64_v = (ImU64)-1; + static float f32_v = 0.123f; + static double f64_v = 90000.01234567890123456789; + + const float drag_speed = 0.2f; + static bool drag_clamp = false; + IMGUI_DEMO_MARKER("Widgets/Data Types/Drags"); + ImGui::SeparatorText("Drags"); + ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); + ImGui::SameLine(); HelpMarker( + "As with every widget in dear imgui, we never modify values unless there is a user interaction.\n" + "You can override the clamping limits by using CTRL+Click to input a value."); + ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL); + ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL); + ImGui::DragScalar("drag u16", ImGuiDataType_U16, &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s32", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL); + ImGui::DragScalar("drag s32 hex", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL, "0x%08X"); + ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL); + ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL); + ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f"); + ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic); + ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams"); + ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic); + + IMGUI_DEMO_MARKER("Widgets/Data Types/Sliders"); + ImGui::SeparatorText("Sliders"); + ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); + ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u"); + ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d"); + ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u"); + ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d"); + ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d"); + ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d"); + ImGui::SliderScalar("slider s32 hex", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty, "0x%04X"); + ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u"); + ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u"); + ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u"); + ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%" PRId64); + ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%" PRId64); + ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%" PRId64); + ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%" PRIu64 " ms"); + ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%" PRIu64 " ms"); + ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%" PRIu64 " ms"); + ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); + ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic); + ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); + ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams"); + ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic); + ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); + + ImGui::SeparatorText("Sliders (reverse)"); + ImGui::SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d"); + ImGui::SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u"); + ImGui::SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, &s32_fifty, &s32_zero, "%d"); + ImGui::SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, &u32_fifty, &u32_zero, "%u"); + ImGui::SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, &s64_fifty, &s64_zero, "%" PRId64); + ImGui::SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, &u64_fifty, &u64_zero, "%" PRIu64 " ms"); + + IMGUI_DEMO_MARKER("Widgets/Data Types/Inputs"); + static bool inputs_step = true; + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_None; + ImGui::SeparatorText("Inputs"); + ImGui::Checkbox("Show step buttons", &inputs_step); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ParseEmptyRefVal", &flags, ImGuiInputTextFlags_ParseEmptyRefVal); + ImGui::CheckboxFlags("ImGuiInputTextFlags_DisplayEmptyRefVal", &flags, ImGuiInputTextFlags_DisplayEmptyRefVal); + ImGui::InputScalar("input s8", ImGuiDataType_S8, &s8_v, inputs_step ? &s8_one : NULL, NULL, "%d", flags); + ImGui::InputScalar("input u8", ImGuiDataType_U8, &u8_v, inputs_step ? &u8_one : NULL, NULL, "%u", flags); + ImGui::InputScalar("input s16", ImGuiDataType_S16, &s16_v, inputs_step ? &s16_one : NULL, NULL, "%d", flags); + ImGui::InputScalar("input u16", ImGuiDataType_U16, &u16_v, inputs_step ? &u16_one : NULL, NULL, "%u", flags); + ImGui::InputScalar("input s32", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%d", flags); + ImGui::InputScalar("input s32 hex", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%04X", flags); + ImGui::InputScalar("input u32", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%u", flags); + ImGui::InputScalar("input u32 hex", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%08X", flags); + ImGui::InputScalar("input s64", ImGuiDataType_S64, &s64_v, inputs_step ? &s64_one : NULL, NULL, NULL, flags); + ImGui::InputScalar("input u64", ImGuiDataType_U64, &u64_v, inputs_step ? &u64_one : NULL, NULL, NULL, flags); + ImGui::InputScalar("input float", ImGuiDataType_Float, &f32_v, inputs_step ? &f32_one : NULL, NULL, NULL, flags); + ImGui::InputScalar("input double", ImGuiDataType_Double, &f64_v, inputs_step ? &f64_one : NULL, NULL, NULL, flags); + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsDisableBlocks() //----------------------------------------------------------------------------- From caf3faa054d02e0cc569aaa62cf6cec2e30f5e36 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 18:14:23 +0100 Subject: [PATCH 0745/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsColorAndPickers() section. --- imgui_demo.cpp | 391 +++++++++++++++++++++++++------------------------ 1 file changed, 198 insertions(+), 193 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 692f67af4..cc0427231 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -254,6 +254,7 @@ static void DemoWindowWidgetsBasic(); static void DemoWindowWidgetsBullets(); static void DemoWindowWidgetsCollapsingHeaders(); static void DemoWindowWidgetsComboBoxes(); +static void DemoWindowWidgetsColorAndPickers(); static void DemoWindowWidgetsDataTypes(); static void DemoWindowWidgetsImages(); static void DemoWindowWidgetsListBoxes(); @@ -827,6 +828,7 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsBullets(); DemoWindowWidgetsCollapsingHeaders(); DemoWindowWidgetsComboBoxes(); + DemoWindowWidgetsColorAndPickers(); DemoWindowWidgetsDataTypes(); DemoWindowWidgetsImages(); DemoWindowWidgetsListBoxes(); @@ -841,199 +843,6 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsTooltips(); DemoWindowWidgetsTreeNodes(); - IMGUI_DEMO_MARKER("Widgets/Color"); - if (ImGui::TreeNode("Color/Picker Widgets")) - { - static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f); - static ImGuiColorEditFlags base_flags = ImGuiColorEditFlags_None; - - ImGui::SeparatorText("Options"); - ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &base_flags, ImGuiColorEditFlags_NoAlpha); - ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaOpaque", &base_flags, ImGuiColorEditFlags_AlphaOpaque); - ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaNoBg", &base_flags, ImGuiColorEditFlags_AlphaNoBg); - ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaPreviewHalf", &base_flags, ImGuiColorEditFlags_AlphaPreviewHalf); - ImGui::CheckboxFlags("ImGuiColorEditFlags_NoDragDrop", &base_flags, ImGuiColorEditFlags_NoDragDrop); - ImGui::CheckboxFlags("ImGuiColorEditFlags_NoOptions", &base_flags, ImGuiColorEditFlags_NoOptions); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); - ImGui::CheckboxFlags("ImGuiColorEditFlags_HDR", &base_flags, ImGuiColorEditFlags_HDR); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); - - IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit"); - ImGui::SeparatorText("Inline color editor"); - ImGui::Text("Color widget:"); - ImGui::SameLine(); HelpMarker( - "Click on the color square to open a color picker.\n" - "CTRL+click on individual component to input value.\n"); - ImGui::ColorEdit3("MyColor##1", (float*)&color, base_flags); - - IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (HSV, with Alpha)"); - ImGui::Text("Color widget HSV with Alpha:"); - ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | base_flags); - - IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (float display)"); - ImGui::Text("Color widget with Float Display:"); - ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | base_flags); - - IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with Picker)"); - ImGui::Text("Color button with Picker:"); - ImGui::SameLine(); HelpMarker( - "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n" - "With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only " - "be used for the tooltip and picker popup."); - ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | base_flags); - - IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with custom Picker popup)"); - ImGui::Text("Color button with Custom Picker Popup:"); - - // Generate a default palette. The palette will persist and can be edited. - static bool saved_palette_init = true; - static ImVec4 saved_palette[32] = {}; - if (saved_palette_init) - { - for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) - { - ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, - saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); - saved_palette[n].w = 1.0f; // Alpha - } - saved_palette_init = false; - } - - static ImVec4 backup_color; - bool open_popup = ImGui::ColorButton("MyColor##3b", color, base_flags); - ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x); - open_popup |= ImGui::Button("Palette"); - if (open_popup) - { - ImGui::OpenPopup("mypicker"); - backup_color = color; - } - if (ImGui::BeginPopup("mypicker")) - { - ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!"); - ImGui::Separator(); - ImGui::ColorPicker4("##picker", (float*)&color, base_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); - ImGui::SameLine(); - - ImGui::BeginGroup(); // Lock X position - ImGui::Text("Current"); - ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)); - ImGui::Text("Previous"); - if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40))) - color = backup_color; - ImGui::Separator(); - ImGui::Text("Palette"); - for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) - { - ImGui::PushID(n); - if ((n % 8) != 0) - ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); - - ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; - if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20))) - color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! - - // Allow user to drop colors into each palette entry. Note that ColorButton() is already a - // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag. - if (ImGui::BeginDragDropTarget()) - { - if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) - memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3); - if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) - memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4); - ImGui::EndDragDropTarget(); - } - - ImGui::PopID(); - } - ImGui::EndGroup(); - ImGui::EndPopup(); - } - - IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (simple)"); - ImGui::Text("Color button only:"); - static bool no_border = false; - ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); - ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, base_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); - - IMGUI_DEMO_MARKER("Widgets/Color/ColorPicker"); - ImGui::SeparatorText("Color picker"); - - static bool ref_color = false; - static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f); - static int picker_mode = 0; - static int display_mode = 0; - static ImGuiColorEditFlags color_picker_flags = ImGuiColorEditFlags_AlphaBar; - - ImGui::PushID("Color picker"); - ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &color_picker_flags, ImGuiColorEditFlags_NoAlpha); - ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaBar", &color_picker_flags, ImGuiColorEditFlags_AlphaBar); - ImGui::CheckboxFlags("ImGuiColorEditFlags_NoSidePreview", &color_picker_flags, ImGuiColorEditFlags_NoSidePreview); - if (color_picker_flags & ImGuiColorEditFlags_NoSidePreview) - { - ImGui::SameLine(); - ImGui::Checkbox("With Ref Color", &ref_color); - if (ref_color) - { - ImGui::SameLine(); - ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | base_flags); - } - } - - ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0ImGuiColorEditFlags_PickerHueBar\0ImGuiColorEditFlags_PickerHueWheel\0"); - ImGui::SameLine(); HelpMarker("When not specified explicitly, user can right-click the picker to change mode."); - - ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0ImGuiColorEditFlags_NoInputs\0ImGuiColorEditFlags_DisplayRGB\0ImGuiColorEditFlags_DisplayHSV\0ImGuiColorEditFlags_DisplayHex\0"); - ImGui::SameLine(); HelpMarker( - "ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, " - "but the user can change it with a right-click on those inputs.\n\nColorPicker defaults to displaying RGB+HSV+Hex " - "if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); - - ImGuiColorEditFlags flags = base_flags | color_picker_flags; - if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; - if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; - if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; // Disable all RGB/HSV/Hex displays - if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB; // Override display mode - if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV; - if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex; - ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); - - ImGui::Text("Set defaults in code:"); - ImGui::SameLine(); HelpMarker( - "SetColorEditOptions() is designed to allow you to set boot-time default.\n" - "We don't have Push/Pop functions because you can force options on a per-widget basis if needed, " - "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid " - "encouraging you to persistently save values that aren't forward-compatible."); - if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) - ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar); - if (ImGui::Button("Default: Float + HDR + Hue Wheel")) - ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel); - - // Always display a small version of both types of pickers - // (that's in order to make it more visible in the demo to people who are skimming quickly through it) - ImGui::Text("Both types:"); - float w = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.y) * 0.40f; - ImGui::SetNextItemWidth(w); - ImGui::ColorPicker3("##MyColor##5", (float*)&color, ImGuiColorEditFlags_PickerHueBar | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); - ImGui::SameLine(); - ImGui::SetNextItemWidth(w); - ImGui::ColorPicker3("##MyColor##6", (float*)&color, ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); - ImGui::PopID(); - - // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) - static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV! - ImGui::Spacing(); - ImGui::Text("HSV encoded colors"); - ImGui::SameLine(); HelpMarker( - "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV " - "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the " - "added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); - ImGui::Text("Color widget with InputHSV:"); - ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); - ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); - ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f); - - ImGui::TreePop(); - } - IMGUI_DEMO_MARKER("Widgets/Drag and Slider Flags"); if (ImGui::TreeNode("Drag/Slider Flags")) { @@ -1814,6 +1623,202 @@ static void DemoWindowWidgetsCollapsingHeaders() // [SECTION] DemoWindowWidgetsColorAndPickers() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsColorAndPickers() +{ + IMGUI_DEMO_MARKER("Widgets/Color"); + if (ImGui::TreeNode("Color/Picker Widgets")) + { + static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f); + static ImGuiColorEditFlags base_flags = ImGuiColorEditFlags_None; + + ImGui::SeparatorText("Options"); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &base_flags, ImGuiColorEditFlags_NoAlpha); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaOpaque", &base_flags, ImGuiColorEditFlags_AlphaOpaque); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaNoBg", &base_flags, ImGuiColorEditFlags_AlphaNoBg); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaPreviewHalf", &base_flags, ImGuiColorEditFlags_AlphaPreviewHalf); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoDragDrop", &base_flags, ImGuiColorEditFlags_NoDragDrop); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoOptions", &base_flags, ImGuiColorEditFlags_NoOptions); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); + ImGui::CheckboxFlags("ImGuiColorEditFlags_HDR", &base_flags, ImGuiColorEditFlags_HDR); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit"); + ImGui::SeparatorText("Inline color editor"); + ImGui::Text("Color widget:"); + ImGui::SameLine(); HelpMarker( + "Click on the color square to open a color picker.\n" + "CTRL+click on individual component to input value.\n"); + ImGui::ColorEdit3("MyColor##1", (float*)&color, base_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (HSV, with Alpha)"); + ImGui::Text("Color widget HSV with Alpha:"); + ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | base_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (float display)"); + ImGui::Text("Color widget with Float Display:"); + ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | base_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with Picker)"); + ImGui::Text("Color button with Picker:"); + ImGui::SameLine(); HelpMarker( + "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n" + "With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only " + "be used for the tooltip and picker popup."); + ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | base_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with custom Picker popup)"); + ImGui::Text("Color button with Custom Picker Popup:"); + + // Generate a default palette. The palette will persist and can be edited. + static bool saved_palette_init = true; + static ImVec4 saved_palette[32] = {}; + if (saved_palette_init) + { + for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) + { + ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, + saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); + saved_palette[n].w = 1.0f; // Alpha + } + saved_palette_init = false; + } + + static ImVec4 backup_color; + bool open_popup = ImGui::ColorButton("MyColor##3b", color, base_flags); + ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x); + open_popup |= ImGui::Button("Palette"); + if (open_popup) + { + ImGui::OpenPopup("mypicker"); + backup_color = color; + } + if (ImGui::BeginPopup("mypicker")) + { + ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!"); + ImGui::Separator(); + ImGui::ColorPicker4("##picker", (float*)&color, base_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); + ImGui::SameLine(); + + ImGui::BeginGroup(); // Lock X position + ImGui::Text("Current"); + ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)); + ImGui::Text("Previous"); + if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40))) + color = backup_color; + ImGui::Separator(); + ImGui::Text("Palette"); + for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) + { + ImGui::PushID(n); + if ((n % 8) != 0) + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); + + ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20))) + color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! + + // Allow user to drop colors into each palette entry. Note that ColorButton() is already a + // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag. + if (ImGui::BeginDragDropTarget()) + { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) + memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3); + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) + memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4); + ImGui::EndDragDropTarget(); + } + + ImGui::PopID(); + } + ImGui::EndGroup(); + ImGui::EndPopup(); + } + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (simple)"); + ImGui::Text("Color button only:"); + static bool no_border = false; + ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); + ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, base_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorPicker"); + ImGui::SeparatorText("Color picker"); + + static bool ref_color = false; + static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f); + static int picker_mode = 0; + static int display_mode = 0; + static ImGuiColorEditFlags color_picker_flags = ImGuiColorEditFlags_AlphaBar; + + ImGui::PushID("Color picker"); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoAlpha", &color_picker_flags, ImGuiColorEditFlags_NoAlpha); + ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaBar", &color_picker_flags, ImGuiColorEditFlags_AlphaBar); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoSidePreview", &color_picker_flags, ImGuiColorEditFlags_NoSidePreview); + if (color_picker_flags & ImGuiColorEditFlags_NoSidePreview) + { + ImGui::SameLine(); + ImGui::Checkbox("With Ref Color", &ref_color); + if (ref_color) + { + ImGui::SameLine(); + ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | base_flags); + } + } + + ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0ImGuiColorEditFlags_PickerHueBar\0ImGuiColorEditFlags_PickerHueWheel\0"); + ImGui::SameLine(); HelpMarker("When not specified explicitly, user can right-click the picker to change mode."); + + ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0ImGuiColorEditFlags_NoInputs\0ImGuiColorEditFlags_DisplayRGB\0ImGuiColorEditFlags_DisplayHSV\0ImGuiColorEditFlags_DisplayHex\0"); + ImGui::SameLine(); HelpMarker( + "ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, " + "but the user can change it with a right-click on those inputs.\n\nColorPicker defaults to displaying RGB+HSV+Hex " + "if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); + + ImGuiColorEditFlags flags = base_flags | color_picker_flags; + if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; + if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; + if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; // Disable all RGB/HSV/Hex displays + if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB; // Override display mode + if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV; + if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex; + ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); + + ImGui::Text("Set defaults in code:"); + ImGui::SameLine(); HelpMarker( + "SetColorEditOptions() is designed to allow you to set boot-time default.\n" + "We don't have Push/Pop functions because you can force options on a per-widget basis if needed, " + "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid " + "encouraging you to persistently save values that aren't forward-compatible."); + if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) + ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar); + if (ImGui::Button("Default: Float + HDR + Hue Wheel")) + ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel); + + // Always display a small version of both types of pickers + // (that's in order to make it more visible in the demo to people who are skimming quickly through it) + ImGui::Text("Both types:"); + float w = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.y) * 0.40f; + ImGui::SetNextItemWidth(w); + ImGui::ColorPicker3("##MyColor##5", (float*)&color, ImGuiColorEditFlags_PickerHueBar | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); + ImGui::SameLine(); + ImGui::SetNextItemWidth(w); + ImGui::ColorPicker3("##MyColor##6", (float*)&color, ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); + ImGui::PopID(); + + // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) + static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV! + ImGui::Spacing(); + ImGui::Text("HSV encoded colors"); + ImGui::SameLine(); HelpMarker( + "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV " + "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the " + "added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); + ImGui::Text("Color widget with InputHSV:"); + ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f); + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsComboBoxes() //----------------------------------------------------------------------------- From 9b486e47fef41c506941151dc586c4ad75bb784a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 18:40:14 +0100 Subject: [PATCH 0746/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsDragsAndSliders(), DemoWindowWidgetsMultiComponents(), DemoWindowWidgetsVerticalSliders() sections. --- imgui_demo.cpp | 317 +++++++++++++++++++++++++------------------------ 1 file changed, 164 insertions(+), 153 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index cc0427231..9d9cf112b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -256,9 +256,11 @@ static void DemoWindowWidgetsCollapsingHeaders(); static void DemoWindowWidgetsComboBoxes(); static void DemoWindowWidgetsColorAndPickers(); static void DemoWindowWidgetsDataTypes(); +static void DemoWindowWidgetsDragsAndSliders(); static void DemoWindowWidgetsImages(); static void DemoWindowWidgetsListBoxes(); static void DemoWindowWidgetsPlotting(); +static void DemoWindowWidgetsMultiComponents(); static void DemoWindowWidgetsProgressBars(); static void DemoWindowWidgetsSelectables(); static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); @@ -268,6 +270,7 @@ static void DemoWindowWidgetsTextFilter(); static void DemoWindowWidgetsTextInput(); static void DemoWindowWidgetsTooltips(); static void DemoWindowWidgetsTreeNodes(); +static void DemoWindowWidgetsVerticalSliders(); static void DemoWindowLayout(); static void DemoWindowPopups(); static void DemoWindowTables(); @@ -830,8 +833,10 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsComboBoxes(); DemoWindowWidgetsColorAndPickers(); DemoWindowWidgetsDataTypes(); + DemoWindowWidgetsDragsAndSliders(); DemoWindowWidgetsImages(); DemoWindowWidgetsListBoxes(); + DemoWindowWidgetsMultiComponents(); DemoWindowWidgetsPlotting(); DemoWindowWidgetsProgressBars(); DemoWindowWidgetsSelectables(); @@ -842,159 +847,7 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsTextInput(); DemoWindowWidgetsTooltips(); DemoWindowWidgetsTreeNodes(); - - IMGUI_DEMO_MARKER("Widgets/Drag and Slider Flags"); - if (ImGui::TreeNode("Drag/Slider Flags")) - { - // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! - static ImGuiSliderFlags flags = ImGuiSliderFlags_None; - ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp); - ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", &flags, ImGuiSliderFlags_ClampOnInput); - ImGui::SameLine(); HelpMarker("Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds."); - ImGui::CheckboxFlags("ImGuiSliderFlags_ClampZeroRange", &flags, ImGuiSliderFlags_ClampZeroRange); - ImGui::SameLine(); HelpMarker("Clamp even if min==max==0.0f. Otherwise DragXXX functions don't clamp."); - ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic); - ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat); - ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput); - ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoSpeedTweaks", &flags, ImGuiSliderFlags_NoSpeedTweaks); - ImGui::SameLine(); HelpMarker("Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic."); - ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuiSliderFlags_WrapAround); - ImGui::SameLine(); HelpMarker("Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions)"); - - // Drags - static float drag_f = 0.5f; - static int drag_i = 50; - ImGui::Text("Underlying float value: %f", drag_f); - ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags); - ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags); - ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags); - ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags); - //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); - - // Sliders - static float slider_f = 0.5f; - static int slider_i = 50; - const ImGuiSliderFlags flags_for_sliders = flags & ~ImGuiSliderFlags_WrapAround; - 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::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Range Widgets"); - if (ImGui::TreeNode("Range Widgets")) - { - static float begin = 10, end = 90; - static int begin_i = 100, end_i = 1000; - ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp); - ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); - ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Multi-component Widgets"); - if (ImGui::TreeNode("Multi-component Widgets")) - { - static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; - static int vec4i[4] = { 1, 5, 100, 255 }; - - ImGui::SeparatorText("2-wide"); - ImGui::InputFloat2("input float2", vec4f); - ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); - ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); - ImGui::InputInt2("input int2", vec4i); - ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); - ImGui::SliderInt2("slider int2", vec4i, 0, 255); - - ImGui::SeparatorText("3-wide"); - ImGui::InputFloat3("input float3", vec4f); - ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); - ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); - ImGui::InputInt3("input int3", vec4i); - ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); - ImGui::SliderInt3("slider int3", vec4i, 0, 255); - - ImGui::SeparatorText("4-wide"); - ImGui::InputFloat4("input float4", vec4f); - ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); - ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); - ImGui::InputInt4("input int4", vec4i); - ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); - ImGui::SliderInt4("slider int4", vec4i, 0, 255); - - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Vertical Sliders"); - if (ImGui::TreeNode("Vertical Sliders")) - { - const float spacing = 4; - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); - - static int int_value = 0; - ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5); - ImGui::SameLine(); - - static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; - ImGui::PushID("set1"); - for (int i = 0; i < 7; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); - ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, ""); - if (ImGui::IsItemActive() || ImGui::IsItemHovered()) - ImGui::SetTooltip("%.3f", values[i]); - ImGui::PopStyleColor(4); - ImGui::PopID(); - } - ImGui::PopID(); - - ImGui::SameLine(); - ImGui::PushID("set2"); - static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; - const int rows = 3; - const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows)); - for (int nx = 0; nx < 4; nx++) - { - if (nx > 0) ImGui::SameLine(); - ImGui::BeginGroup(); - for (int ny = 0; ny < rows; ny++) - { - ImGui::PushID(nx * rows + ny); - ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); - if (ImGui::IsItemActive() || ImGui::IsItemHovered()) - ImGui::SetTooltip("%.3f", values2[nx]); - ImGui::PopID(); - } - ImGui::EndGroup(); - } - ImGui::PopID(); - - ImGui::SameLine(); - ImGui::PushID("set3"); - for (int i = 0; i < 4; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); - ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); - ImGui::PopStyleVar(); - ImGui::PopID(); - } - ImGui::PopID(); - ImGui::PopStyleVar(); - ImGui::TreePop(); - } + DemoWindowWidgetsVerticalSliders(); IMGUI_DEMO_MARKER("Widgets/Drag and drop"); if (ImGui::TreeNode("Drag and Drop")) @@ -2063,6 +1916,53 @@ static void DemoWindowWidgetsDataTypes() // [SECTION] DemoWindowWidgetsDragsAndSliders() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsDragsAndSliders() +{ + IMGUI_DEMO_MARKER("Widgets/Drag and Slider Flags"); + if (ImGui::TreeNode("Drag/Slider Flags")) + { + // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! + static ImGuiSliderFlags flags = ImGuiSliderFlags_None; + ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp); + ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", &flags, ImGuiSliderFlags_ClampOnInput); + ImGui::SameLine(); HelpMarker("Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds."); + ImGui::CheckboxFlags("ImGuiSliderFlags_ClampZeroRange", &flags, ImGuiSliderFlags_ClampZeroRange); + ImGui::SameLine(); HelpMarker("Clamp even if min==max==0.0f. Otherwise DragXXX functions don't clamp."); + ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic); + ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat); + ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput); + ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoSpeedTweaks", &flags, ImGuiSliderFlags_NoSpeedTweaks); + ImGui::SameLine(); HelpMarker("Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic."); + ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuiSliderFlags_WrapAround); + ImGui::SameLine(); HelpMarker("Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions)"); + + // Drags + static float drag_f = 0.5f; + static int drag_i = 50; + ImGui::Text("Underlying float value: %f", drag_f); + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags); + //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); + + // Sliders + static float slider_f = 0.5f; + static int slider_i = 50; + const ImGuiSliderFlags flags_for_sliders = flags & ~ImGuiSliderFlags_WrapAround; + 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::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsImages() //----------------------------------------------------------------------------- @@ -2221,6 +2121,49 @@ static void DemoWindowWidgetsListBoxes() // [SECTION] DemoWindowWidgetsMultiComponents() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsMultiComponents() +{ + IMGUI_DEMO_MARKER("Widgets/Multi-component Widgets"); + if (ImGui::TreeNode("Multi-component Widgets")) + { + static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + static int vec4i[4] = { 1, 5, 100, 255 }; + + ImGui::SeparatorText("2-wide"); + ImGui::InputFloat2("input float2", vec4f); + ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); + ImGui::InputInt2("input int2", vec4i); + ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); + ImGui::SliderInt2("slider int2", vec4i, 0, 255); + + ImGui::SeparatorText("3-wide"); + ImGui::InputFloat3("input float3", vec4f); + ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); + ImGui::InputInt3("input int3", vec4i); + ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); + ImGui::SliderInt3("slider int3", vec4i, 0, 255); + + ImGui::SeparatorText("4-wide"); + ImGui::InputFloat4("input float4", vec4f); + ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); + ImGui::InputInt4("input int4", vec4i); + ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); + ImGui::SliderInt4("slider int4", vec4i, 0, 255); + + ImGui::SeparatorText("Ranges"); + static float begin = 10, end = 90; + static int begin_i = 100, end_i = 1000; + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp); + ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); + ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsPlotting() //----------------------------------------------------------------------------- @@ -4152,6 +4095,74 @@ static void DemoWindowWidgetsTreeNodes() // [SECTION] DemoWindowWidgetsVerticalSliders() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsVerticalSliders() +{ + IMGUI_DEMO_MARKER("Widgets/Vertical Sliders"); + if (ImGui::TreeNode("Vertical Sliders")) + { + const float spacing = 4; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); + + static int int_value = 0; + ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5); + ImGui::SameLine(); + + static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; + ImGui::PushID("set1"); + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values[i]); + ImGui::PopStyleColor(4); + ImGui::PopID(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set2"); + static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; + const int rows = 3; + const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows)); + for (int nx = 0; nx < 4; nx++) + { + if (nx > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + for (int ny = 0; ny < rows; ny++) + { + ImGui::PushID(nx * rows + ny); + ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values2[nx]); + ImGui::PopID(); + } + ImGui::EndGroup(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set3"); + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); + ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PopStyleVar(); + ImGui::PopID(); + } + ImGui::PopID(); + ImGui::PopStyleVar(); + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowLayout() //----------------------------------------------------------------------------- From 0758594bd2ea56c341005911b74700cea57216a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 18:45:59 +0100 Subject: [PATCH 0747/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsDragAndDrop() section. --- imgui_demo.cpp | 307 +++++++++++++++++++++++++------------------------ 1 file changed, 156 insertions(+), 151 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9d9cf112b..b2a0a5e78 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -256,6 +256,7 @@ static void DemoWindowWidgetsCollapsingHeaders(); static void DemoWindowWidgetsComboBoxes(); static void DemoWindowWidgetsColorAndPickers(); static void DemoWindowWidgetsDataTypes(); +static void DemoWindowWidgetsDragAndDrop(); static void DemoWindowWidgetsDragsAndSliders(); static void DemoWindowWidgetsImages(); static void DemoWindowWidgetsListBoxes(); @@ -833,6 +834,7 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsComboBoxes(); DemoWindowWidgetsColorAndPickers(); DemoWindowWidgetsDataTypes(); + DemoWindowWidgetsDragAndDrop(); DemoWindowWidgetsDragsAndSliders(); DemoWindowWidgetsImages(); DemoWindowWidgetsListBoxes(); @@ -849,157 +851,6 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsTreeNodes(); DemoWindowWidgetsVerticalSliders(); - IMGUI_DEMO_MARKER("Widgets/Drag and drop"); - if (ImGui::TreeNode("Drag and Drop")) - { - IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets"); - if (ImGui::TreeNode("Drag and drop in standard widgets")) - { - // ColorEdit widgets automatically act as drag source and drag target. - // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F - // to allow your own widgets to use colors in their drag and drop interaction. - // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. - HelpMarker("You can drag from the color squares."); - static float col1[3] = { 1.0f, 0.0f, 0.2f }; - static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; - ImGui::ColorEdit3("color 1", col1); - ImGui::ColorEdit4("color 2", col2); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items"); - if (ImGui::TreeNode("Drag and drop to copy/swap items")) - { - enum Mode - { - Mode_Copy, - Mode_Move, - Mode_Swap - }; - static int mode = 0; - if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); - if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); - if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } - static const char* names[9] = - { - "Bobby", "Beatrice", "Betty", - "Brianna", "Barry", "Bernard", - "Bibi", "Blaine", "Bryn" - }; - for (int n = 0; n < IM_ARRAYSIZE(names); n++) - { - ImGui::PushID(n); - if ((n % 3) != 0) - ImGui::SameLine(); - ImGui::Button(names[n], ImVec2(60, 60)); - - // Our buttons are both drag sources and drag targets here! - if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) - { - // Set payload to carry the index of our item (could be anything) - ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); - - // Display preview (could be anything, e.g. when dragging an image we could decide to display - // the filename and a small preview of the image, etc.) - if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } - if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); } - if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); } - ImGui::EndDragDropSource(); - } - if (ImGui::BeginDragDropTarget()) - { - if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_DEMO_CELL")) - { - IM_ASSERT(payload->DataSize == sizeof(int)); - int payload_n = *(const int*)payload->Data; - if (mode == Mode_Copy) - { - names[n] = names[payload_n]; - } - if (mode == Mode_Move) - { - names[n] = names[payload_n]; - names[payload_n] = ""; - } - if (mode == Mode_Swap) - { - const char* tmp = names[n]; - names[n] = names[payload_n]; - names[payload_n] = tmp; - } - } - ImGui::EndDragDropTarget(); - } - ImGui::PopID(); - } - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)"); - if (ImGui::TreeNode("Drag to reorder items (simple)")) - { - // FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice. - // This code was always slightly faulty but in a way which was not easily noticeable. - // Until we fix this, enable ImGuiItemFlags_AllowDuplicateId to disable detecting the issue. - ImGui::PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); - - // Simple reordering - HelpMarker( - "We don't use the drag and drop api at all here! " - "Instead we query when the item is held but not hovered, and order items accordingly."); - static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }; - for (int n = 0; n < IM_ARRAYSIZE(item_names); n++) - { - const char* item = item_names[n]; - ImGui::Selectable(item); - - if (ImGui::IsItemActive() && !ImGui::IsItemHovered()) - { - int n_next = n + (ImGui::GetMouseDragDelta(0).y < 0.f ? -1 : 1); - if (n_next >= 0 && n_next < IM_ARRAYSIZE(item_names)) - { - item_names[n] = item_names[n_next]; - item_names[n_next] = item; - ImGui::ResetMouseDragDelta(); - } - } - } - - ImGui::PopItemFlag(); - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Tooltip at target location"); - if (ImGui::TreeNode("Tooltip at target location")) - { - for (int n = 0; n < 2; n++) - { - // Drop targets - ImGui::Button(n ? "drop here##1" : "drop here##0"); - if (ImGui::BeginDragDropTarget()) - { - ImGuiDragDropFlags drop_target_flags = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoPreviewTooltip; - if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags)) - { - IM_UNUSED(payload); - ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); - ImGui::SetTooltip("Cannot drop here!"); - } - ImGui::EndDragDropTarget(); - } - - // Drop source - static ImVec4 col4 = { 1.0f, 0.0f, 0.2f, 1.0f }; - if (n == 0) - ImGui::ColorButton("drag me", col4); - - } - ImGui::TreePop(); - } - - ImGui::TreePop(); - } - IMGUI_DEMO_MARKER("Widgets/Querying Item Status (Edited,Active,Hovered etc.)"); if (ImGui::TreeNode("Querying Item Status (Edited/Active/Hovered etc.)")) { @@ -1912,6 +1763,160 @@ static void DemoWindowWidgetsDataTypes() // [SECTION] DemoWindowWidgetsDragAndDrop() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsDragAndDrop() +{ + IMGUI_DEMO_MARKER("Widgets/Drag and drop"); + if (ImGui::TreeNode("Drag and Drop")) + { + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets"); + if (ImGui::TreeNode("Drag and drop in standard widgets")) + { + // ColorEdit widgets automatically act as drag source and drag target. + // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F + // to allow your own widgets to use colors in their drag and drop interaction. + // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. + HelpMarker("You can drag from the color squares."); + static float col1[3] = { 1.0f, 0.0f, 0.2f }; + static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::ColorEdit4("color 2", col2); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items"); + if (ImGui::TreeNode("Drag and drop to copy/swap items")) + { + enum Mode + { + Mode_Copy, + Mode_Move, + Mode_Swap + }; + static int mode = 0; + if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); + if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); + if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } + static const char* names[9] = + { + "Bobby", "Beatrice", "Betty", + "Brianna", "Barry", "Bernard", + "Bibi", "Blaine", "Bryn" + }; + for (int n = 0; n < IM_ARRAYSIZE(names); n++) + { + ImGui::PushID(n); + if ((n % 3) != 0) + ImGui::SameLine(); + ImGui::Button(names[n], ImVec2(60, 60)); + + // Our buttons are both drag sources and drag targets here! + if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) + { + // Set payload to carry the index of our item (could be anything) + ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); + + // Display preview (could be anything, e.g. when dragging an image we could decide to display + // the filename and a small preview of the image, etc.) + if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } + if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); } + if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); } + ImGui::EndDragDropSource(); + } + if (ImGui::BeginDragDropTarget()) + { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_DEMO_CELL")) + { + IM_ASSERT(payload->DataSize == sizeof(int)); + int payload_n = *(const int*)payload->Data; + if (mode == Mode_Copy) + { + names[n] = names[payload_n]; + } + if (mode == Mode_Move) + { + names[n] = names[payload_n]; + names[payload_n] = ""; + } + if (mode == Mode_Swap) + { + const char* tmp = names[n]; + names[n] = names[payload_n]; + names[payload_n] = tmp; + } + } + ImGui::EndDragDropTarget(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)"); + if (ImGui::TreeNode("Drag to reorder items (simple)")) + { + // FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice. + // This code was always slightly faulty but in a way which was not easily noticeable. + // Until we fix this, enable ImGuiItemFlags_AllowDuplicateId to disable detecting the issue. + ImGui::PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); + + // Simple reordering + HelpMarker( + "We don't use the drag and drop api at all here! " + "Instead we query when the item is held but not hovered, and order items accordingly."); + static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }; + for (int n = 0; n < IM_ARRAYSIZE(item_names); n++) + { + const char* item = item_names[n]; + ImGui::Selectable(item); + + if (ImGui::IsItemActive() && !ImGui::IsItemHovered()) + { + int n_next = n + (ImGui::GetMouseDragDelta(0).y < 0.f ? -1 : 1); + if (n_next >= 0 && n_next < IM_ARRAYSIZE(item_names)) + { + item_names[n] = item_names[n_next]; + item_names[n_next] = item; + ImGui::ResetMouseDragDelta(); + } + } + } + + ImGui::PopItemFlag(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Tooltip at target location"); + if (ImGui::TreeNode("Tooltip at target location")) + { + for (int n = 0; n < 2; n++) + { + // Drop targets + ImGui::Button(n ? "drop here##1" : "drop here##0"); + if (ImGui::BeginDragDropTarget()) + { + ImGuiDragDropFlags drop_target_flags = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoPreviewTooltip; + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags)) + { + IM_UNUSED(payload); + ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); + ImGui::SetTooltip("Cannot drop here!"); + } + ImGui::EndDragDropTarget(); + } + + // Drop source + static ImVec4 col4 = { 1.0f, 0.0f, 0.2f, 1.0f }; + if (n == 0) + ImGui::ColorButton("drag me", col4); + + } + ImGui::TreePop(); + } + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsDragsAndSliders() //----------------------------------------------------------------------------- From 7a919e80c9dd0a39f5d3a08a19e53504795ba03f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 18:49:02 +0100 Subject: [PATCH 0748/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsQueryingStatuses() section. --- imgui_demo.cpp | 393 +++++++++++++++++++++++++------------------------ 1 file changed, 199 insertions(+), 194 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b2a0a5e78..bb3f6ef7c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -263,6 +263,7 @@ static void DemoWindowWidgetsListBoxes(); static void DemoWindowWidgetsPlotting(); static void DemoWindowWidgetsMultiComponents(); static void DemoWindowWidgetsProgressBars(); +static void DemoWindowWidgetsQueryingStatuses(); static void DemoWindowWidgetsSelectables(); static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgetsTabs(); @@ -841,6 +842,7 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsMultiComponents(); DemoWindowWidgetsPlotting(); DemoWindowWidgetsProgressBars(); + DemoWindowWidgetsQueryingStatuses(); DemoWindowWidgetsSelectables(); DemoWindowWidgetsSelectionAndMultiSelect(demo_data); DemoWindowWidgetsTabs(); @@ -851,200 +853,6 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsTreeNodes(); DemoWindowWidgetsVerticalSliders(); - IMGUI_DEMO_MARKER("Widgets/Querying Item Status (Edited,Active,Hovered etc.)"); - if (ImGui::TreeNode("Querying Item Status (Edited/Active/Hovered etc.)")) - { - // Select an item type - const char* item_names[] = - { - "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputTextMultiline", "InputFloat", - "InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox" - }; - static int item_type = 4; - static bool item_disabled = false; - ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names)); - ImGui::SameLine(); - HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui::IsItemHovered()."); - ImGui::Checkbox("Item Disabled", &item_disabled); - - // Submit selected items so we can query their status in the code following it. - bool ret = false; - static bool b = false; - static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; - static char str[16] = {}; - if (item_disabled) - ImGui::BeginDisabled(true); - if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction - if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button - if (item_type == 2) { ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); ret = ImGui::Button("ITEM: Button"); ImGui::PopItemFlag(); } // Testing button (with repeater) - if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox - if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item - if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) - if (item_type == 6) { ret = ImGui::InputTextMultiline("ITEM: InputTextMultiline", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which uses a child window) - if (item_type == 7) { ret = ImGui::InputFloat("ITEM: InputFloat", col4f, 1.0f); } // Testing +/- buttons on scalar input - if (item_type == 8) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) - if (item_type == 9) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) - if (item_type == 10){ ret = ImGui::Selectable("ITEM: Selectable"); } // Testing selectable item - if (item_type == 11){ ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) - if (item_type == 12){ ret = ImGui::TreeNode("ITEM: TreeNode"); if (ret) ImGui::TreePop(); } // Testing tree node - if (item_type == 13){ ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. - if (item_type == 14){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::Combo("ITEM: Combo", ¤t, items, IM_ARRAYSIZE(items)); } - if (item_type == 15){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } - - bool hovered_delay_none = ImGui::IsItemHovered(); - bool hovered_delay_stationary = ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary); - bool hovered_delay_short = ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort); - bool hovered_delay_normal = ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal); - bool hovered_delay_tooltip = ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip); // = Normal + Stationary - - // Display the values of IsItemHovered() and other common item state functions. - // Note that the ImGuiHoveredFlags_XXX flags can be combined. - // Because BulletText is an item itself and that would affect the output of IsItemXXX functions, - // we query every state in a single call to avoid storing them and to simplify the code. - ImGui::BulletText( - "Return value = %d\n" - "IsItemFocused() = %d\n" - "IsItemHovered() = %d\n" - "IsItemHovered(_AllowWhenBlockedByPopup) = %d\n" - "IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n" - "IsItemHovered(_AllowWhenOverlappedByItem) = %d\n" - "IsItemHovered(_AllowWhenOverlappedByWindow) = %d\n" - "IsItemHovered(_AllowWhenDisabled) = %d\n" - "IsItemHovered(_RectOnly) = %d\n" - "IsItemActive() = %d\n" - "IsItemEdited() = %d\n" - "IsItemActivated() = %d\n" - "IsItemDeactivated() = %d\n" - "IsItemDeactivatedAfterEdit() = %d\n" - "IsItemVisible() = %d\n" - "IsItemClicked() = %d\n" - "IsItemToggledOpen() = %d\n" - "GetItemRectMin() = (%.1f, %.1f)\n" - "GetItemRectMax() = (%.1f, %.1f)\n" - "GetItemRectSize() = (%.1f, %.1f)", - ret, - ImGui::IsItemFocused(), - ImGui::IsItemHovered(), - ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), - ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), - ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByItem), - ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow), - ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled), - ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly), - ImGui::IsItemActive(), - ImGui::IsItemEdited(), - ImGui::IsItemActivated(), - ImGui::IsItemDeactivated(), - ImGui::IsItemDeactivatedAfterEdit(), - ImGui::IsItemVisible(), - ImGui::IsItemClicked(), - ImGui::IsItemToggledOpen(), - ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y, - ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y, - ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y - ); - ImGui::BulletText( - "with Hovering Delay or Stationary test:\n" - "IsItemHovered() = = %d\n" - "IsItemHovered(_Stationary) = %d\n" - "IsItemHovered(_DelayShort) = %d\n" - "IsItemHovered(_DelayNormal) = %d\n" - "IsItemHovered(_Tooltip) = %d", - hovered_delay_none, hovered_delay_stationary, hovered_delay_short, hovered_delay_normal, hovered_delay_tooltip); - - if (item_disabled) - ImGui::EndDisabled(); - - char buf[1] = ""; - ImGui::InputText("unused", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_ReadOnly); - ImGui::SameLine(); - HelpMarker("This widget is only here to be able to tab-out of the widgets above and see e.g. Deactivated() status."); - - ImGui::TreePop(); - } - - IMGUI_DEMO_MARKER("Widgets/Querying Window Status (Focused,Hovered etc.)"); - if (ImGui::TreeNode("Querying Window Status (Focused/Hovered etc.)")) - { - static bool embed_all_inside_a_child_window = false; - ImGui::Checkbox("Embed everything inside a child window for testing _RootWindow flag.", &embed_all_inside_a_child_window); - if (embed_all_inside_a_child_window) - ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), ImGuiChildFlags_Borders); - - // Testing IsWindowFocused() function with its various flags. - ImGui::BulletText( - "IsWindowFocused() = %d\n" - "IsWindowFocused(_ChildWindows) = %d\n" - "IsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n" - "IsWindowFocused(_ChildWindows|_RootWindow) = %d\n" - "IsWindowFocused(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" - "IsWindowFocused(_RootWindow) = %d\n" - "IsWindowFocused(_RootWindow|_NoPopupHierarchy) = %d\n" - "IsWindowFocused(_AnyWindow) = %d\n", - ImGui::IsWindowFocused(), - ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows), - ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_NoPopupHierarchy), - ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow), - ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), - ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow), - ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), - ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)); - - // Testing IsWindowHovered() function with its various flags. - ImGui::BulletText( - "IsWindowHovered() = %d\n" - "IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n" - "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" - "IsWindowHovered(_ChildWindows) = %d\n" - "IsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\n" - "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n" - "IsWindowHovered(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" - "IsWindowHovered(_RootWindow) = %d\n" - "IsWindowHovered(_RootWindow|_NoPopupHierarchy) = %d\n" - "IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n" - "IsWindowHovered(_AnyWindow) = %d\n" - "IsWindowHovered(_Stationary) = %d\n", - ImGui::IsWindowHovered(), - ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), - ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), - ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows), - ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy), - ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow), - ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), - ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow), - ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), - ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup), - ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow), - ImGui::IsWindowHovered(ImGuiHoveredFlags_Stationary)); - - ImGui::BeginChild("child", ImVec2(0, 50), ImGuiChildFlags_Borders); - ImGui::Text("This is another child window for testing the _ChildWindows flag."); - ImGui::EndChild(); - if (embed_all_inside_a_child_window) - ImGui::EndChild(); - - // Calling IsItemHovered() after begin returns the hovered status of the title bar. - // This is useful in particular if you want to create a context menu associated to the title bar of a window. - static bool test_window = false; - ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window); - if (test_window) - { - ImGui::Begin("Title bar Hovered/Active tests", &test_window); - if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered() - { - if (ImGui::MenuItem("Close")) { test_window = false; } - ImGui::EndPopup(); - } - ImGui::Text( - "IsItemHovered() after begin = %d (== is title bar hovered)\n" - "IsItemActive() after begin = %d (== is window being clicked/moved)\n", - ImGui::IsItemHovered(), ImGui::IsItemActive()); - ImGui::End(); - } - - ImGui::TreePop(); - } - // Demonstrate BeginDisabled/EndDisabled using a checkbox located at the bottom of the section (which is a bit odd: // logically we'd have this checkbox at the top of the section, but we don't want this feature to steal that space) if (disable_all) @@ -2285,6 +2093,203 @@ static void DemoWindowWidgetsProgressBars() // [SECTION] DemoWindowWidgetsQueryingStatuses() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsQueryingStatuses() +{ + IMGUI_DEMO_MARKER("Widgets/Querying Item Status (Edited,Active,Hovered etc.)"); + if (ImGui::TreeNode("Querying Item Status (Edited/Active/Hovered etc.)")) + { + // Select an item type + const char* item_names[] = + { + "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputTextMultiline", "InputFloat", + "InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox" + }; + static int item_type = 4; + static bool item_disabled = false; + ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names)); + ImGui::SameLine(); + HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui::IsItemHovered()."); + ImGui::Checkbox("Item Disabled", &item_disabled); + + // Submit selected items so we can query their status in the code following it. + bool ret = false; + static bool b = false; + static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; + static char str[16] = {}; + if (item_disabled) + ImGui::BeginDisabled(true); + if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction + if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button + if (item_type == 2) { ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); ret = ImGui::Button("ITEM: Button"); ImGui::PopItemFlag(); } // Testing button (with repeater) + if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox + if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item + if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) + if (item_type == 6) { ret = ImGui::InputTextMultiline("ITEM: InputTextMultiline", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which uses a child window) + if (item_type == 7) { ret = ImGui::InputFloat("ITEM: InputFloat", col4f, 1.0f); } // Testing +/- buttons on scalar input + if (item_type == 8) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 9) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 10) { ret = ImGui::Selectable("ITEM: Selectable"); } // Testing selectable item + if (item_type == 11) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) + if (item_type == 12) { ret = ImGui::TreeNode("ITEM: TreeNode"); if (ret) ImGui::TreePop(); } // Testing tree node + if (item_type == 13) { ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. + if (item_type == 14) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::Combo("ITEM: Combo", ¤t, items, IM_ARRAYSIZE(items)); } + if (item_type == 15) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } + + bool hovered_delay_none = ImGui::IsItemHovered(); + bool hovered_delay_stationary = ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary); + bool hovered_delay_short = ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort); + bool hovered_delay_normal = ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal); + bool hovered_delay_tooltip = ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip); // = Normal + Stationary + + // Display the values of IsItemHovered() and other common item state functions. + // Note that the ImGuiHoveredFlags_XXX flags can be combined. + // Because BulletText is an item itself and that would affect the output of IsItemXXX functions, + // we query every state in a single call to avoid storing them and to simplify the code. + ImGui::BulletText( + "Return value = %d\n" + "IsItemFocused() = %d\n" + "IsItemHovered() = %d\n" + "IsItemHovered(_AllowWhenBlockedByPopup) = %d\n" + "IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n" + "IsItemHovered(_AllowWhenOverlappedByItem) = %d\n" + "IsItemHovered(_AllowWhenOverlappedByWindow) = %d\n" + "IsItemHovered(_AllowWhenDisabled) = %d\n" + "IsItemHovered(_RectOnly) = %d\n" + "IsItemActive() = %d\n" + "IsItemEdited() = %d\n" + "IsItemActivated() = %d\n" + "IsItemDeactivated() = %d\n" + "IsItemDeactivatedAfterEdit() = %d\n" + "IsItemVisible() = %d\n" + "IsItemClicked() = %d\n" + "IsItemToggledOpen() = %d\n" + "GetItemRectMin() = (%.1f, %.1f)\n" + "GetItemRectMax() = (%.1f, %.1f)\n" + "GetItemRectSize() = (%.1f, %.1f)", + ret, + ImGui::IsItemFocused(), + ImGui::IsItemHovered(), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByItem), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled), + ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly), + ImGui::IsItemActive(), + ImGui::IsItemEdited(), + ImGui::IsItemActivated(), + ImGui::IsItemDeactivated(), + ImGui::IsItemDeactivatedAfterEdit(), + ImGui::IsItemVisible(), + ImGui::IsItemClicked(), + ImGui::IsItemToggledOpen(), + ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y, + ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y, + ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y + ); + ImGui::BulletText( + "with Hovering Delay or Stationary test:\n" + "IsItemHovered() = = %d\n" + "IsItemHovered(_Stationary) = %d\n" + "IsItemHovered(_DelayShort) = %d\n" + "IsItemHovered(_DelayNormal) = %d\n" + "IsItemHovered(_Tooltip) = %d", + hovered_delay_none, hovered_delay_stationary, hovered_delay_short, hovered_delay_normal, hovered_delay_tooltip); + + if (item_disabled) + ImGui::EndDisabled(); + + char buf[1] = ""; + ImGui::InputText("unused", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_ReadOnly); + ImGui::SameLine(); + HelpMarker("This widget is only here to be able to tab-out of the widgets above and see e.g. Deactivated() status."); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Querying Window Status (Focused,Hovered etc.)"); + if (ImGui::TreeNode("Querying Window Status (Focused/Hovered etc.)")) + { + static bool embed_all_inside_a_child_window = false; + ImGui::Checkbox("Embed everything inside a child window for testing _RootWindow flag.", &embed_all_inside_a_child_window); + if (embed_all_inside_a_child_window) + ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), ImGuiChildFlags_Borders); + + // Testing IsWindowFocused() function with its various flags. + ImGui::BulletText( + "IsWindowFocused() = %d\n" + "IsWindowFocused(_ChildWindows) = %d\n" + "IsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_RootWindow) = %d\n" + "IsWindowFocused(_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_AnyWindow) = %d\n", + ImGui::IsWindowFocused(), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)); + + // Testing IsWindowHovered() function with its various flags. + ImGui::BulletText( + "IsWindowHovered() = %d\n" + "IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n" + "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" + "IsWindowHovered(_ChildWindows) = %d\n" + "IsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_RootWindow) = %d\n" + "IsWindowHovered(_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n" + "IsWindowHovered(_AnyWindow) = %d\n" + "IsWindowHovered(_Stationary) = %d\n", + ImGui::IsWindowHovered(), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_Stationary)); + + ImGui::BeginChild("child", ImVec2(0, 50), ImGuiChildFlags_Borders); + ImGui::Text("This is another child window for testing the _ChildWindows flag."); + ImGui::EndChild(); + if (embed_all_inside_a_child_window) + ImGui::EndChild(); + + // Calling IsItemHovered() after begin returns the hovered status of the title bar. + // This is useful in particular if you want to create a context menu associated to the title bar of a window. + static bool test_window = false; + ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window); + if (test_window) + { + ImGui::Begin("Title bar Hovered/Active tests", &test_window); + if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered() + { + if (ImGui::MenuItem("Close")) { test_window = false; } + ImGui::EndPopup(); + } + ImGui::Text( + "IsItemHovered() after begin = %d (== is title bar hovered)\n" + "IsItemActive() after begin = %d (== is window being clicked/moved)\n", + ImGui::IsItemHovered(), ImGui::IsItemActive()); + ImGui::End(); + } + + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsSelectables() //----------------------------------------------------------------------------- From 71b160cdbb15979dd4142719a5c0ed05d10373ea Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 18:53:45 +0100 Subject: [PATCH 0749/2359] Demo: (Refactor) Moved code into DemoWindowWidgetsDisableBlocks() section. --- imgui.h | 2 +- imgui_demo.cpp | 34 ++++++++++++++++++++++------------ 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index 641b1ab92..1cda94914 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.9 WIP" -#define IMGUI_VERSION_NUM 19185 +#define IMGUI_VERSION_NUM 19186 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bb3f6ef7c..31904b1b4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -256,6 +256,7 @@ static void DemoWindowWidgetsCollapsingHeaders(); static void DemoWindowWidgetsComboBoxes(); static void DemoWindowWidgetsColorAndPickers(); static void DemoWindowWidgetsDataTypes(); +static void DemoWindowWidgetsDisableBlocks(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgetsDragAndDrop(); static void DemoWindowWidgetsDragsAndSliders(); static void DemoWindowWidgetsImages(); @@ -427,6 +428,7 @@ struct ImGuiDemoWindowData bool ShowAbout = false; // Other data + bool DisableSections = false; ExampleTreeNode* DemoTree = NULL; ~ImGuiDemoWindowData() { if (DemoTree) ExampleTree_DestroyNode(DemoTree); } @@ -825,7 +827,7 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) if (!ImGui::CollapsingHeader("Widgets")) return; - static bool disable_all = false; // The Checkbox for that is inside the "Disabled" section at the bottom + const bool disable_all = demo_data->DisableSections; // The Checkbox for that is inside the "Disabled" section at the bottom if (disable_all) ImGui::BeginDisabled(); @@ -835,6 +837,13 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsComboBoxes(); DemoWindowWidgetsColorAndPickers(); DemoWindowWidgetsDataTypes(); + + if (disable_all) + ImGui::EndDisabled(); + DemoWindowWidgetsDisableBlocks(demo_data); + if (disable_all) + ImGui::BeginDisabled(); + DemoWindowWidgetsDragAndDrop(); DemoWindowWidgetsDragsAndSliders(); DemoWindowWidgetsImages(); @@ -853,18 +862,8 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsTreeNodes(); DemoWindowWidgetsVerticalSliders(); - // Demonstrate BeginDisabled/EndDisabled using a checkbox located at the bottom of the section (which is a bit odd: - // logically we'd have this checkbox at the top of the section, but we don't want this feature to steal that space) if (disable_all) ImGui::EndDisabled(); - - IMGUI_DEMO_MARKER("Widgets/Disable Block"); - if (ImGui::TreeNode("Disable block")) - { - ImGui::Checkbox("Disable entire section above", &disable_all); - ImGui::SameLine(); HelpMarker("Demonstrate using BeginDisabled()/EndDisabled() across this section."); - ImGui::TreePop(); - } } //----------------------------------------------------------------------------- @@ -1567,6 +1566,17 @@ static void DemoWindowWidgetsDataTypes() // [SECTION] DemoWindowWidgetsDisableBlocks() //----------------------------------------------------------------------------- +static void DemoWindowWidgetsDisableBlocks(ImGuiDemoWindowData* demo_data) +{ + IMGUI_DEMO_MARKER("Widgets/Disable Blocks"); + if (ImGui::TreeNode("Disable Blocks")) + { + ImGui::Checkbox("Disable entire section above", &demo_data->DisableSections); + ImGui::SameLine(); HelpMarker("Demonstrate using BeginDisabled()/EndDisabled() across other sections."); + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsDragAndDrop() //----------------------------------------------------------------------------- @@ -1872,7 +1882,7 @@ static void DemoWindowWidgetsImages() static void DemoWindowWidgetsListBoxes() { IMGUI_DEMO_MARKER("Widgets/List Boxes"); - if (ImGui::TreeNode("List boxes")) + if (ImGui::TreeNode("List Boxes")) { // BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild() // using the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. From df317743272165a8bda2dbe85a0f751495a1e150 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 19:20:10 +0100 Subject: [PATCH 0750/2359] Disabled: Fixed an issue restoring Alpha in EndDisabled() when using nested BeginDisabled() calls with PushStyleVar(ImGuiStyleVar_DisabledAlpha) within. (#8454, #7640) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 4 +++- imgui_internal.h | 1 + 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 390681161..2df26e655 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -103,6 +103,8 @@ Other changes: (#8451, #7660) [@achabense] - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to handle UTF-8 regardless of system regional settings. (#7660) [@achabense] +- Disabled: Fixed an issue restoring Alpha in EndDisabled() when using nested + BeginDisabled() calls with PushStyleVar(ImGuiStyleVar_DisabledAlpha) within. (#8454, #7640) - Clipper: Fixed an issue where passing an out of bound index to IncludeItemByIndex() could incorrectly offset the final cursor, even if that index was not iterated through. One case where it would manifest was calling Combo() with an out of range index. (#8450) diff --git a/imgui.cpp b/imgui.cpp index 77e3c1d36..bae74db5f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7084,6 +7084,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window_stack_data.Window = window; window_stack_data.ParentLastItemDataBackup = g.LastItemData; window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled); + window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0f; ErrorRecoveryStoreState(&window_stack_data.StackSizesInBegin); g.StackSizesInBeginForCurrentWindow = &window_stack_data.StackSizesInBegin; if (flags & ImGuiWindowFlags_ChildMenu) @@ -7950,6 +7951,7 @@ void ImGui::BeginDisabledOverrideReenable() { ImGuiContext& g = *GImGui; IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled); + g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup = g.Style.Alpha; g.Style.Alpha = g.DisabledAlphaBackup; g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled; g.ItemFlagsStack.push_back(g.CurrentItemFlags); @@ -7963,7 +7965,7 @@ void ImGui::EndDisabledOverrideReenable() IM_ASSERT(g.DisabledStackSize > 0); g.ItemFlagsStack.pop_back(); g.CurrentItemFlags = g.ItemFlagsStack.back(); - g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha; + g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup; } void ImGui::PushTextWrapPos(float wrap_pos_x) diff --git a/imgui_internal.h b/imgui_internal.h index 4bdc6e947..40b854559 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1316,6 +1316,7 @@ struct ImGuiWindowStackData ImGuiLastItemData ParentLastItemDataBackup; ImGuiErrorRecoveryState StackSizesInBegin; // Store size of various stacks for asserting bool DisabledOverrideReenable; // Non-child window override disabled flag + float DisabledOverrideReenableAlphaBackup; }; struct ImGuiShrinkWidthItem From a7657f2ed45508bb719a8b9e2d8e7bda57eff4a0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 4 Mar 2025 14:36:00 +0100 Subject: [PATCH 0751/2359] Examples: SDL3: Added comments to clarify setup for users of the unfortunate SDL_MAIN_USE_CALLBACKS feature. (#8455) --- docs/CHANGELOG.txt | 2 ++ examples/example_sdl3_opengl3/main.cpp | 5 +++++ examples/example_sdl3_sdlgpu3/main.cpp | 7 ++++++- examples/example_sdl3_sdlrenderer3/main.cpp | 5 +++++ examples/example_sdl3_vulkan/main.cpp | 7 ++++++- 5 files changed, 24 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2df26e655..78c6f09da 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -115,6 +115,8 @@ Other changes: - Demo: Reorganized "Widgets" section to be alphabetically ordered and split in more functions. - Demo: Combos: demonstrate a very simple way to add a filter to a combo, by showing the filter inside the combo contents. (#718) +- Examples: SDL3: Added comments to clarify setup for users of the unfortunate + SDL_MAIN_USE_CALLBACKS feature. (#8455) - Backends: GLFW: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. (#8452) - Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 8cd54bd4e..d8666061d 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -26,6 +26,7 @@ int main(int, char**) { // Setup SDL + // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function] if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); @@ -139,6 +140,7 @@ int main(int, char**) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function] SDL_Event event; while (SDL_PollEvent(&event)) { @@ -148,6 +150,8 @@ int main(int, char**) if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) done = true; } + + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function] if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) { SDL_Delay(10); @@ -209,6 +213,7 @@ int main(int, char**) #endif // Cleanup + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function] ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplSDL3_Shutdown(); ImGui::DestroyContext(); diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index dbc7759ba..630639f3f 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -26,7 +26,8 @@ int main(int, char**) { // Setup SDL - if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD) != 0) + // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function] + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); return -1; @@ -105,6 +106,7 @@ int main(int, char**) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function] SDL_Event event; while (SDL_PollEvent(&event)) { @@ -114,6 +116,8 @@ int main(int, char**) if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) done = true; } + + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function] if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) { SDL_Delay(10); @@ -199,6 +203,7 @@ int main(int, char**) } // Cleanup + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function] SDL_WaitForGPUIdle(gpu_device); ImGui_ImplSDL3_Shutdown(); ImGui_ImplSDLGPU3_Shutdown(); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 68078eebd..ad05a0f91 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -24,6 +24,7 @@ int main(int, char**) { // Setup SDL + // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function] if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); @@ -101,6 +102,7 @@ int main(int, char**) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function] SDL_Event event; while (SDL_PollEvent(&event)) { @@ -110,6 +112,8 @@ int main(int, char**) if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) done = true; } + + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function] if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) { SDL_Delay(10); @@ -171,6 +175,7 @@ int main(int, char**) #endif // Cleanup + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function] ImGui_ImplSDLRenderer3_Shutdown(); ImGui_ImplSDL3_Shutdown(); ImGui::DestroyContext(); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 99e441d7e..170eae45b 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -345,7 +345,8 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) int main(int, char**) { // Setup SDL - if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD) != 0) + // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function] + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); return -1; @@ -447,6 +448,7 @@ int main(int, char**) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function] SDL_Event event; while (SDL_PollEvent(&event)) { @@ -456,6 +458,8 @@ int main(int, char**) if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) done = true; } + + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function] if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) { SDL_Delay(10); @@ -531,6 +535,7 @@ int main(int, char**) } // Cleanup + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function] err = vkDeviceWaitIdle(g_Device); check_vk_result(err); ImGui_ImplVulkan_Shutdown(); From 324172fb1f096739e81c7f9f1f29939c5781e222 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 13:35:14 +0100 Subject: [PATCH 0752/2359] Demo: (Refactor) Moved DemoWindowWidgets() below the functions it calls, reducing amount of forward declarations. --- imgui_demo.cpp | 126 ++++++++++++++++++++----------------------------- 1 file changed, 51 insertions(+), 75 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 31904b1b4..775e0c731 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -73,7 +73,6 @@ Index of this file: // [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) // [SECTION] Demo Window / ShowDemoWindow() // [SECTION] DemoWindowMenuBar() -// [SECTION] DemoWindowWidgets() // [SECTION] DemoWindowWidgetsBasic() // [SECTION] DemoWindowWidgetsBullets() // [SECTION] DemoWindowWidgetsCollapsingHeaders() @@ -98,6 +97,7 @@ Index of this file: // [SECTION] DemoWindowWidgetsTooltips() // [SECTION] DemoWindowWidgetsTreeNodes() // [SECTION] DemoWindowWidgetsVerticalSliders() +// [SECTION] DemoWindowWidgets() // [SECTION] DemoWindowLayout() // [SECTION] DemoWindowPopups() // [SECTION] DemoWindowTables() @@ -250,30 +250,6 @@ static void ShowExampleMenuFile(); // (because the link time of very large functions tends to grow non-linearly) static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data); static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data); -static void DemoWindowWidgetsBasic(); -static void DemoWindowWidgetsBullets(); -static void DemoWindowWidgetsCollapsingHeaders(); -static void DemoWindowWidgetsComboBoxes(); -static void DemoWindowWidgetsColorAndPickers(); -static void DemoWindowWidgetsDataTypes(); -static void DemoWindowWidgetsDisableBlocks(ImGuiDemoWindowData* demo_data); -static void DemoWindowWidgetsDragAndDrop(); -static void DemoWindowWidgetsDragsAndSliders(); -static void DemoWindowWidgetsImages(); -static void DemoWindowWidgetsListBoxes(); -static void DemoWindowWidgetsPlotting(); -static void DemoWindowWidgetsMultiComponents(); -static void DemoWindowWidgetsProgressBars(); -static void DemoWindowWidgetsQueryingStatuses(); -static void DemoWindowWidgetsSelectables(); -static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data); -static void DemoWindowWidgetsTabs(); -static void DemoWindowWidgetsText(); -static void DemoWindowWidgetsTextFilter(); -static void DemoWindowWidgetsTextInput(); -static void DemoWindowWidgetsTooltips(); -static void DemoWindowWidgetsTreeNodes(); -static void DemoWindowWidgetsVerticalSliders(); static void DemoWindowLayout(); static void DemoWindowPopups(); static void DemoWindowTables(); @@ -816,56 +792,6 @@ static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data) } } -//----------------------------------------------------------------------------- -// [SECTION] DemoWindowWidgets() -//----------------------------------------------------------------------------- - -static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) -{ - IMGUI_DEMO_MARKER("Widgets"); - //ImGui::SetNextItemOpen(true, ImGuiCond_Once); - if (!ImGui::CollapsingHeader("Widgets")) - return; - - const bool disable_all = demo_data->DisableSections; // The Checkbox for that is inside the "Disabled" section at the bottom - if (disable_all) - ImGui::BeginDisabled(); - - DemoWindowWidgetsBasic(); - DemoWindowWidgetsBullets(); - DemoWindowWidgetsCollapsingHeaders(); - DemoWindowWidgetsComboBoxes(); - DemoWindowWidgetsColorAndPickers(); - DemoWindowWidgetsDataTypes(); - - if (disable_all) - ImGui::EndDisabled(); - DemoWindowWidgetsDisableBlocks(demo_data); - if (disable_all) - ImGui::BeginDisabled(); - - DemoWindowWidgetsDragAndDrop(); - DemoWindowWidgetsDragsAndSliders(); - DemoWindowWidgetsImages(); - DemoWindowWidgetsListBoxes(); - DemoWindowWidgetsMultiComponents(); - DemoWindowWidgetsPlotting(); - DemoWindowWidgetsProgressBars(); - DemoWindowWidgetsQueryingStatuses(); - DemoWindowWidgetsSelectables(); - DemoWindowWidgetsSelectionAndMultiSelect(demo_data); - DemoWindowWidgetsTabs(); - DemoWindowWidgetsText(); - DemoWindowWidgetsTextFilter(); - DemoWindowWidgetsTextInput(); - DemoWindowWidgetsTooltips(); - DemoWindowWidgetsTreeNodes(); - DemoWindowWidgetsVerticalSliders(); - - if (disable_all) - ImGui::EndDisabled(); -} - //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsBasic() //----------------------------------------------------------------------------- @@ -4183,6 +4109,56 @@ static void DemoWindowWidgetsVerticalSliders() } } +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgets() +//----------------------------------------------------------------------------- + +static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) +{ + IMGUI_DEMO_MARKER("Widgets"); + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (!ImGui::CollapsingHeader("Widgets")) + return; + + const bool disable_all = demo_data->DisableSections; // The Checkbox for that is inside the "Disabled" section at the bottom + if (disable_all) + ImGui::BeginDisabled(); + + DemoWindowWidgetsBasic(); + DemoWindowWidgetsBullets(); + DemoWindowWidgetsCollapsingHeaders(); + DemoWindowWidgetsComboBoxes(); + DemoWindowWidgetsColorAndPickers(); + DemoWindowWidgetsDataTypes(); + + if (disable_all) + ImGui::EndDisabled(); + DemoWindowWidgetsDisableBlocks(demo_data); + if (disable_all) + ImGui::BeginDisabled(); + + DemoWindowWidgetsDragAndDrop(); + DemoWindowWidgetsDragsAndSliders(); + DemoWindowWidgetsImages(); + DemoWindowWidgetsListBoxes(); + DemoWindowWidgetsMultiComponents(); + DemoWindowWidgetsPlotting(); + DemoWindowWidgetsProgressBars(); + DemoWindowWidgetsQueryingStatuses(); + DemoWindowWidgetsSelectables(); + DemoWindowWidgetsSelectionAndMultiSelect(demo_data); + DemoWindowWidgetsTabs(); + DemoWindowWidgetsText(); + DemoWindowWidgetsTextFilter(); + DemoWindowWidgetsTextInput(); + DemoWindowWidgetsTooltips(); + DemoWindowWidgetsTreeNodes(); + DemoWindowWidgetsVerticalSliders(); + + if (disable_all) + ImGui::EndDisabled(); +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowLayout() //----------------------------------------------------------------------------- From fcec08f7ae32656a00e5dde709ff390870a7a84b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 13:39:48 +0100 Subject: [PATCH 0753/2359] Demo: (Refactor) Moved ExampleTreeNode contents below ShowDemoWindow() so main entry point is more visible to casual reader. --- imgui_demo.cpp | 189 +++++++++++++++++++++++++------------------------ 1 file changed, 97 insertions(+), 92 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 775e0c731..beffe618d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -70,9 +70,9 @@ Index of this file: // [SECTION] Forward Declarations // [SECTION] Helpers -// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) // [SECTION] Demo Window / ShowDemoWindow() // [SECTION] DemoWindowMenuBar() +// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) // [SECTION] DemoWindowWidgetsBasic() // [SECTION] DemoWindowWidgetsBullets() // [SECTION] DemoWindowWidgetsCollapsingHeaders() @@ -256,6 +256,11 @@ static void DemoWindowTables(); static void DemoWindowColumns(); static void DemoWindowInputs(); +// Helper tree functions used by Property Editor & Multi-Select demos +struct ExampleTreeNode; +static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, ExampleTreeNode* parent); +static void ExampleTree_DestroyNode(ExampleTreeNode* node); + //----------------------------------------------------------------------------- // [SECTION] Helpers //----------------------------------------------------------------------------- @@ -282,97 +287,6 @@ ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback = NULL; void* GImGuiDemoMarkerCallbackUserData = NULL; #define IMGUI_DEMO_MARKER(section) do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback(__FILE__, __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0) -//----------------------------------------------------------------------------- -// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor etc.) -//----------------------------------------------------------------------------- - -// Simple representation for a tree -// (this is designed to be simple to understand for our demos, not to be fancy or efficient etc.) -struct ExampleTreeNode -{ - // Tree structure - char Name[28] = ""; - int UID = 0; - ExampleTreeNode* Parent = NULL; - ImVector Childs; - unsigned short IndexInParent = 0; // Maintaining this allows us to implement linear traversal more easily - - // Leaf Data - bool HasData = false; // All leaves have data - bool DataMyBool = true; - int DataMyInt = 128; - ImVec2 DataMyVec2 = ImVec2(0.0f, 3.141592f); -}; - -// Simple representation of struct metadata/serialization data. -// (this is a minimal version of what a typical advanced application may provide) -struct ExampleMemberInfo -{ - const char* Name; // Member name - ImGuiDataType DataType; // Member type - int DataCount; // Member count (1 when scalar) - int Offset; // Offset inside parent structure -}; - -// Metadata description of ExampleTreeNode struct. -static const ExampleMemberInfo ExampleTreeNodeMemberInfos[] -{ - { "MyName", ImGuiDataType_String, 1, offsetof(ExampleTreeNode, Name) }, - { "MyBool", ImGuiDataType_Bool, 1, offsetof(ExampleTreeNode, DataMyBool) }, - { "MyInt", ImGuiDataType_S32, 1, offsetof(ExampleTreeNode, DataMyInt) }, - { "MyVec2", ImGuiDataType_Float, 2, offsetof(ExampleTreeNode, DataMyVec2) }, -}; - -static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, ExampleTreeNode* parent) -{ - ExampleTreeNode* node = IM_NEW(ExampleTreeNode); - snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name); - node->UID = uid; - node->Parent = parent; - node->IndexInParent = parent ? (unsigned short)parent->Childs.Size : 0; - if (parent) - parent->Childs.push_back(node); - return node; -} - -static void ExampleTree_DestroyNode(ExampleTreeNode* node) -{ - for (ExampleTreeNode* child_node : node->Childs) - ExampleTree_DestroyNode(child_node); - IM_DELETE(node); -} - -// Create example tree data -// (this allocates _many_ more times than most other code in either Dear ImGui or others demo) -static ExampleTreeNode* ExampleTree_CreateDemoTree() -{ - static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" }; - const size_t NAME_MAX_LEN = sizeof(ExampleTreeNode::Name); - char name_buf[NAME_MAX_LEN]; - int uid = 0; - ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); - const int root_items_multiplier = 2; - for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * root_items_multiplier; idx_L0++) - { - snprintf(name_buf, IM_ARRAYSIZE(name_buf), "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier); - ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); - const int number_of_childs = (int)strlen(node_L1->Name); - for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) - { - snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Child %d", idx_L1); - ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1); - node_L2->HasData = true; - if (idx_L1 == 0) - { - snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Sub-child %d", 0); - ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2); - node_L3->HasData = true; - } - } - } - return node_L0; -} - //----------------------------------------------------------------------------- // [SECTION] Demo Window / ShowDemoWindow() //----------------------------------------------------------------------------- @@ -792,6 +706,97 @@ static void DemoWindowMenuBar(ImGuiDemoWindowData* demo_data) } } +//----------------------------------------------------------------------------- +// [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) +//----------------------------------------------------------------------------- + +// Simple representation for a tree +// (this is designed to be simple to understand for our demos, not to be fancy or efficient etc.) +struct ExampleTreeNode +{ + // Tree structure + char Name[28] = ""; + int UID = 0; + ExampleTreeNode* Parent = NULL; + ImVector Childs; + unsigned short IndexInParent = 0; // Maintaining this allows us to implement linear traversal more easily + + // Leaf Data + bool HasData = false; // All leaves have data + bool DataMyBool = true; + int DataMyInt = 128; + ImVec2 DataMyVec2 = ImVec2(0.0f, 3.141592f); +}; + +// Simple representation of struct metadata/serialization data. +// (this is a minimal version of what a typical advanced application may provide) +struct ExampleMemberInfo +{ + const char* Name; // Member name + ImGuiDataType DataType; // Member type + int DataCount; // Member count (1 when scalar) + int Offset; // Offset inside parent structure +}; + +// Metadata description of ExampleTreeNode struct. +static const ExampleMemberInfo ExampleTreeNodeMemberInfos[] +{ + { "MyName", ImGuiDataType_String, 1, offsetof(ExampleTreeNode, Name) }, + { "MyBool", ImGuiDataType_Bool, 1, offsetof(ExampleTreeNode, DataMyBool) }, + { "MyInt", ImGuiDataType_S32, 1, offsetof(ExampleTreeNode, DataMyInt) }, + { "MyVec2", ImGuiDataType_Float, 2, offsetof(ExampleTreeNode, DataMyVec2) }, +}; + +static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, ExampleTreeNode* parent) +{ + ExampleTreeNode* node = IM_NEW(ExampleTreeNode); + snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name); + node->UID = uid; + node->Parent = parent; + node->IndexInParent = parent ? (unsigned short)parent->Childs.Size : 0; + if (parent) + parent->Childs.push_back(node); + return node; +} + +static void ExampleTree_DestroyNode(ExampleTreeNode* node) +{ + for (ExampleTreeNode* child_node : node->Childs) + ExampleTree_DestroyNode(child_node); + IM_DELETE(node); +} + +// Create example tree data +// (this allocates _many_ more times than most other code in either Dear ImGui or others demo) +static ExampleTreeNode* ExampleTree_CreateDemoTree() +{ + static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" }; + const size_t NAME_MAX_LEN = sizeof(ExampleTreeNode::Name); + char name_buf[NAME_MAX_LEN]; + int uid = 0; + ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); + const int root_items_multiplier = 2; + for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * root_items_multiplier; idx_L0++) + { + snprintf(name_buf, IM_ARRAYSIZE(name_buf), "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier); + ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); + const int number_of_childs = (int)strlen(node_L1->Name); + for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) + { + snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Child %d", idx_L1); + ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1); + node_L2->HasData = true; + if (idx_L1 == 0) + { + snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Sub-child %d", 0); + ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2); + node_L3->HasData = true; + } + } + } + return node_L0; +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsBasic() //----------------------------------------------------------------------------- From 119dfbc6270cedf29e8655b296f9ca0f31cede32 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 15:04:26 +0100 Subject: [PATCH 0754/2359] Debug Tools: Tweaked layout of ID Stack Tool and always display full path. (#4631) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 50 ++++++++++++++++++++++++---------------------- imgui.h | 3 ++- imgui_internal.h | 1 + 4 files changed, 30 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 78c6f09da..a6110cd55 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -110,6 +110,7 @@ Other changes: One case where it would manifest was calling Combo() with an out of range index. (#8450) - Debug Tools: Added io.ConfigDebugHighlightIdConflictsShowItemPicker (defaults to true) to allow disabled Item Picker suggestion in user facing builds. (#7961, #7669) +- Debug Tools: Tweaked layout of ID Stack Tool and always display full path. (#4631) - Misc: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursors (busy/wait/hourglass shape, with or without an arrow cursor). - Demo: Reorganized "Widgets" section to be alphabetically ordered and split in more functions. diff --git a/imgui.cpp b/imgui.cpp index bae74db5f..896330913 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16924,42 +16924,44 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) // Display hovered/active status ImGuiIDStackTool* tool = &g.DebugIDStackTool; - const ImGuiID hovered_id = g.HoveredIdPreviousFrame; - const ImGuiID active_id = g.ActiveId; -#ifdef IMGUI_ENABLE_TEST_ENGINE - Text("HoveredId: 0x%08X (\"%s\"), ActiveId: 0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : ""); -#else - Text("HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id); -#endif + + // Build and display path + tool->ResultPathBuf.resize(0); + for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++) + { + char level_desc[256]; + StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); + tool->ResultPathBuf.append(stack_n == 0 ? "//" : "/"); + for (int n = 0; level_desc[n]; n++) + { + if (level_desc[n] == '/') + tool->ResultPathBuf.append("\\"); + tool->ResultPathBuf.append(level_desc + n, level_desc + n + 1); + } + } + Text("0x%08X", tool->QueryId); 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."); // CTRL+C to copy path const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime; - Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC); + SameLine(); + PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f); Checkbox("Ctrl+C: copy path", &tool->CopyToClipboardOnCtrlC); PopStyleVar(); SameLine(); TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*"); if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused)) { tool->CopyToClipboardLastTime = (float)g.Time; - char* p = g.TempBuffer.Data; - char* p_end = p + g.TempBuffer.Size; - for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++) - { - *p++ = '/'; - char level_desc[256]; - StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); - for (int n = 0; level_desc[n] && p + 2 < p_end; n++) - { - if (level_desc[n] == '/') - *p++ = '\\'; - *p++ = level_desc[n]; - } - } - *p = '\0'; - SetClipboardText(g.TempBuffer.Data); + SetClipboardText(tool->ResultPathBuf.c_str()); } + Text("- Path \"%s\"", tool->ResultPathBuf.c_str()); +#ifdef IMGUI_ENABLE_TEST_ENGINE + Text("- Label \"%s\"", tool->QueryId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryId) : ""); +#endif + + Separator(); + // Display decorated stack tool->LastActiveFrame = g.FrameCount; if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders)) diff --git a/imgui.h b/imgui.h index 1cda94914..2e6a67b33 100644 --- a/imgui.h +++ b/imgui.h @@ -2600,10 +2600,11 @@ struct ImGuiTextBuffer ImGuiTextBuffer() { } inline char operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } - const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator + const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator int size() const { return Buf.Size ? Buf.Size - 1 : 0; } bool empty() const { return Buf.Size <= 1; } void clear() { Buf.clear(); } + void resize(int size) { IM_ASSERT(size == 0); if (Buf.Size > 0) Buf.Data[0] = 0; Buf.resize(0); } // Similar to resize(0) on ImVector: empty string but don't free buffer. Only resize(0) supported for now. 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); diff --git a/imgui_internal.h b/imgui_internal.h index 40b854559..455a9e066 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2030,6 +2030,7 @@ struct ImGuiIDStackTool ImVector Results; bool CopyToClipboardOnCtrlC; float CopyToClipboardLastTime; + ImGuiTextBuffer ResultPathBuf; ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); CopyToClipboardLastTime = -FLT_MAX; } }; From 9f49292b357bacdf23f7131d0fa735672912f50e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 15:23:49 +0100 Subject: [PATCH 0755/2359] Internals: Menus: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00". --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 30 ++++++++++++++++++++++++------ imgui.h | 2 +- imgui_internal.h | 1 + imgui_widgets.cpp | 4 ++-- 5 files changed, 31 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a6110cd55..39d73571d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,9 @@ Breaking changes: - Backends: Vulkan: Added 'uint32_t api_version' argument to ImGui_ImplVulkan_LoadFunctions(). Note that it was also added to ImGui_ImplVulkan_InitInfo but for the later it is optional. (#8326, #8365, #8400) +- Internals: Menus: reworked mangling of menu windows to use "###Menu_00" etc. instead + of "##Menu_00", allowing them to also store the menu name before it. This shouldn't + affect code unless directly accessing menu window from their mangled name. Other changes: diff --git a/imgui.cpp b/imgui.cpp index 896330913..b2738f170 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -431,6 +431,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238) - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1)); @@ -7202,7 +7203,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. bool window_title_visible_elsewhere = false; - if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB + if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB + window_title_visible_elsewhere = true; + if (flags & ImGuiWindowFlags_ChildMenu) window_title_visible_elsewhere = true; if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0) { @@ -11714,17 +11717,32 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags) } char name[20]; - if (extra_window_flags & ImGuiWindowFlags_ChildMenu) - ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth - else - ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame + IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx() + ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // No recycling, so we can close/open during the same frame 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(); - //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack; + return is_open; +} +bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags) +{ + ImGuiContext& g = *GImGui; + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + return false; + } + + char name[128]; + IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu); + ImFormatString(name, IM_ARRAYSIZE(name), "%s###Menu_%02d", label, 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(); + //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack; return is_open; } diff --git a/imgui.h b/imgui.h index 2e6a67b33..f154efcb9 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.9 WIP" -#define IMGUI_VERSION_NUM 19186 +#define IMGUI_VERSION_NUM 19187 #define IMGUI_HAS_TABLE /* diff --git a/imgui_internal.h b/imgui_internal.h index 455a9e066..a78ae9827 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3136,6 +3136,7 @@ namespace ImGui // 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 void 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 76dabb8f9..b8b872b1a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8867,7 +8867,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) if (g.MenusIdSubmittedThisFrame.contains(id)) { if (menu_is_open) - menu_is_open = BeginPopupEx(id, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + menu_is_open = BeginPopupMenuEx(id, label, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) else g.NextWindowData.ClearFlags(); // we behave like Begin() and need to consume those values return menu_is_open; @@ -9029,7 +9029,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) ImGuiLastItemData last_item_in_parent = g.LastItemData; SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos. PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding - menu_is_open = BeginPopupEx(id, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + menu_is_open = BeginPopupMenuEx(id, label, window_flags); // menu_is_open may be 'false' when the popup is completely clipped (e.g. zero size display) PopStyleVar(); if (menu_is_open) { From 377a387a427f152d63596de66bbaa590234a2b1c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 16:23:31 +0100 Subject: [PATCH 0756/2359] Add proper ImGuiTextBuffer::resize() support other than 0. --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index f154efcb9..2f6a18d2a 100644 --- a/imgui.h +++ b/imgui.h @@ -2604,7 +2604,7 @@ struct ImGuiTextBuffer int size() const { return Buf.Size ? Buf.Size - 1 : 0; } bool empty() const { return Buf.Size <= 1; } void clear() { Buf.clear(); } - void resize(int size) { IM_ASSERT(size == 0); if (Buf.Size > 0) Buf.Data[0] = 0; Buf.resize(0); } // Similar to resize(0) on ImVector: empty string but don't free buffer. Only resize(0) supported for now. + 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); From 1ec99f4fd3a49bcd5479b4ab1a5fd52ce5195c02 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Mar 2025 11:09:02 +0100 Subject: [PATCH 0757/2359] Internals: added ImStrlen/ImMemchr #define to facilitate experimenting with variations. (#8421) --- imgui.cpp | 50 +++++++++++++++++++++++------------------------ imgui_draw.cpp | 13 ++++++------ imgui_internal.h | 2 ++ imgui_tables.cpp | 2 +- imgui_widgets.cpp | 42 +++++++++++++++++++-------------------- 5 files changed, 56 insertions(+), 53 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b2738f170..cac29a932 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1986,15 +1986,15 @@ void ImStrncpy(char* dst, const char* src, size_t count) char* ImStrdup(const char* str) { - size_t len = strlen(str); + size_t len = ImStrlen(str); void* buf = IM_ALLOC(len + 1); return (char*)memcpy(buf, (const void*)str, len + 1); } char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) { - size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1; - size_t src_size = strlen(src) + 1; + size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1; + size_t src_size = ImStrlen(src) + 1; if (dst_buf_size < src_size) { IM_FREE(dst); @@ -2007,7 +2007,7 @@ char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) const char* ImStrchrRange(const char* str, const char* str_end, char c) { - const char* p = (const char*)memchr(str, (int)c, str_end - str); + const char* p = (const char*)ImMemchr(str, (int)c, str_end - str); return p; } @@ -2022,13 +2022,13 @@ int ImStrlenW(const ImWchar* str) // Find end-of-line. Return pointer will point to either first \n, either str_end. const char* ImStreolRange(const char* str, const char* str_end) { - const char* p = (const char*)memchr(str, '\n', str_end - str); + const char* p = (const char*)ImMemchr(str, '\n', str_end - str); return p ? p : str_end; } const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find beginning-of-line { - IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + strlen(buf_begin)); + IM_ASSERT_PARANOID(buf_mid_line >= buf_begin && buf_mid_line <= buf_begin + ImStrlen(buf_begin)); while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') buf_mid_line--; return buf_mid_line; @@ -2037,7 +2037,7 @@ const char* ImStrbol(const char* buf_mid_line, const char* buf_begin) // find be const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) { if (!needle_end) - needle_end = needle + strlen(needle); + needle_end = needle + ImStrlen(needle); const char un0 = (char)ImToUpper(*needle); while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) @@ -2158,7 +2158,7 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, if (buf == NULL) buf = "(null)"; *out_buf = buf; - if (out_buf_end) { *out_buf_end = buf + strlen(buf); } + if (out_buf_end) { *out_buf_end = buf + ImStrlen(buf); } } else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0) { @@ -2567,11 +2567,11 @@ const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const cha int ImTextCountLines(const char* in_text, const char* in_text_end) { if (in_text_end == NULL) - in_text_end = in_text + strlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now. + 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) { - const char* line_end = (const char*)memchr(in_text, '\n', in_text_end - in_text); + 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++; } @@ -2852,7 +2852,7 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector 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() @@ -14378,7 +14378,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* } if (prefix) - LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here. + LogRenderedText(ref_pos, prefix, prefix + ImStrlen(prefix)); // Calculate end ourself to ensure "##" are included here. // Re-adjust padding if we have popped out of our starting depth if (g.LogDepthRef > window->DC.TreeDepth) @@ -14411,7 +14411,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* } if (suffix) - LogRenderedText(ref_pos, suffix, suffix + strlen(suffix)); + LogRenderedText(ref_pos, suffix, suffix + ImStrlen(suffix)); } // Start logging/capturing text output @@ -14677,7 +14677,7 @@ 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 = strlen(ini_data); + ini_size = ImStrlen(ini_data); g.SettingsIniData.Buf.resize((int)ini_size + 1); char* const buf = g.SettingsIniData.Buf.Data; char* const buf_end = buf + ini_size; @@ -14778,7 +14778,7 @@ ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) if (const char* p = strstr(name, "###")) name = p; } - const size_t name_len = strlen(name); + const size_t name_len = ImStrlen(name); // Allocate chunk const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1; @@ -15070,7 +15070,7 @@ static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext*, const char* t if (!main_clipboard) PasteboardCreate(kPasteboardClipboard, &main_clipboard); PasteboardClear(main_clipboard); - CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text)); + CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, ImStrlen(text)); if (cf_data) { PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0); @@ -15124,7 +15124,7 @@ static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const cha { ImGuiContext& g = *ctx; g.ClipboardHandlerData.clear(); - const char* text_end = text + strlen(text); + const char* text_end = text + ImStrlen(text); g.ClipboardHandlerData.resize((int)(text_end - text) + 1); memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text)); g.ClipboardHandlerData[(int)(text_end - text)] = 0; @@ -16894,7 +16894,7 @@ void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* dat ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id); break; case ImGuiDataType_String: - ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id); + ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*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: ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 206c29ce5..efdddc8b1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -143,6 +143,7 @@ namespace IMGUI_STB_NAMESPACE #define STBTT_fabs(x) ImFabs(x) #define STBTT_ifloor(x) ((int)ImFloor(x)) #define STBTT_iceil(x) ((int)ImCeil(x)) +#define STBTT_strlen(x) ImStrlen(x) #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION #else @@ -2672,7 +2673,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, { // Store a short copy of filename into into the font name for convenience const char* p; - for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} + for (p = filename + ImStrlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels); } return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); @@ -2707,7 +2708,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_d ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) { - int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; + int compressed_ttf_size = (((int)ImStrlen(compressed_ttf_data_base85) + 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); ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); @@ -4029,7 +4030,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) { if (!text_end) - text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. + text_end = text_begin + ImStrlen(text_begin); // FIXME-OPT: Need to avoid this. const float line_height = size; const float scale = size / FontSize; @@ -4129,7 +4130,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im return; if (!text_end) - text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. + 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 scale = size / FontSize; const float line_height = FontSize * scale; @@ -4141,7 +4142,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im if (y + line_height < clip_rect.y) while (y + line_height < clip_rect.y && s < text_end) { - const char* line_end = (const char*)memchr(s, '\n', text_end - s); + const char* line_end = (const char*)ImMemchr(s, '\n', text_end - s); if (word_wrap_enabled) { // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPositionA(). @@ -4165,7 +4166,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im float y_end = y; while (y_end < clip_rect.w && s_end < text_end) { - s_end = (const char*)memchr(s_end, '\n', text_end - s_end); + s_end = (const char*)ImMemchr(s_end, '\n', text_end - s_end); s_end = s_end ? s_end + 1 : text_end; y_end += line_height; } diff --git a/imgui_internal.h b/imgui_internal.h index a78ae9827..b7395fcae 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -372,6 +372,8 @@ static inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } // Helpers: String +#define ImStrlen strlen +#define ImMemchr memchr 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). diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f6aff8c02..6c7926236 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1648,7 +1648,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo if (label != NULL && label[0] != 0) { column->NameOffset = (ImS16)table->ColumnsNames.size(); - table->ColumnsNames.append(label, label + strlen(label) + 1); + table->ColumnsNames.append(label, label + ImStrlen(label) + 1); } } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b8b872b1a..01e4e6187 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -169,7 +169,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) // Calculate length const char* text_begin = text; if (text_end == NULL) - text_end = text + strlen(text); // FIXME-OPT + text_end = text + ImStrlen(text); // FIXME-OPT const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); const float wrap_pos_x = window->DC.TextWrapPos; @@ -209,7 +209,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) int lines_skipped = 0; while (line < text_end && lines_skipped < lines_skippable) { - const char* line_end = (const char*)memchr(line, '\n', text_end - line); + const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) @@ -230,7 +230,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) if (IsClippedEx(line_rect, 0)) break; - const char* line_end = (const char*)memchr(line, '\n', text_end - line); + 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); @@ -245,7 +245,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) int lines_skipped = 0; while (line < text_end) { - const char* line_end = (const char*)memchr(line, '\n', text_end - line); + const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) @@ -2064,7 +2064,7 @@ static const char* Items_SingleStringGetter(void* data, int idx) { if (idx == items_count) break; - p += strlen(p) + 1; + p += ImStrlen(p) + 1; items_count++; } return *p ? p : NULL; @@ -2132,7 +2132,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open while (*p) { - p += strlen(p) + 1; + 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); @@ -3899,7 +3899,7 @@ static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** line_count++; if (s_eol == NULL) { - s = s + strlen(s); + s = s + ImStrlen(s); break; } s = s_eol + 1; @@ -4187,7 +4187,7 @@ void ImGuiInputTextState::OnCharPressed(unsigned int c) // The changes we had to make to stb_textedit_key made it very much UTF-8 specific which is not too great. char utf8[5]; ImTextCharToUtf8(utf8, c); - stb_textedit_text(this, Stb, utf8, (int)strlen(utf8)); + stb_textedit_text(this, Stb, utf8, (int)ImStrlen(utf8)); CursorFollow = true; CursorAnimReset(); } @@ -4238,7 +4238,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons // Grow internal buffer if needed const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; - const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); + const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text); if (new_text_len + BufTextLen >= BufSize) { if (!is_resizable) @@ -4560,7 +4560,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const bool init_state = (init_make_active || user_scroll_active); if (init_reload_from_user_buf) { - int new_len = (int)strlen(buf); + int new_len = (int)ImStrlen(buf); IM_ASSERT(new_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?"); state->WantReloadUserBuf = false; InputTextReconcileUndoState(state, state->TextA.Data, state->TextLen, buf, new_len); @@ -4582,7 +4582,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Take a copy of the initial buffer value. // From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode) - const int buf_len = (int)strlen(buf); + const int buf_len = (int)ImStrlen(buf); IM_ASSERT(buf_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?"); state->TextToRevertTo.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. memcpy(state->TextToRevertTo.Data, buf, buf_len + 1); @@ -4667,7 +4667,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Read-only mode always ever read from source buffer. Refresh TextLen when active. if (is_readonly && state != NULL) - state->TextLen = (int)strlen(buf); + state->TextLen = (int)ImStrlen(buf); //if (is_readonly && state != NULL) // state->TextA.clear(); // Uncomment to facilitate debugging, but we otherwise prefer to keep/amortize th allocation. } @@ -4946,7 +4946,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (const char* clipboard = GetClipboardText()) { // Filter pasted buffer - const int clipboard_len = (int)strlen(clipboard); + const int clipboard_len = (int)ImStrlen(clipboard); ImVector clipboard_filtered; clipboard_filtered.reserve(clipboard_len + 1); for (const char* s = clipboard; *s != 0; ) @@ -4958,7 +4958,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ continue; char c_utf8[5]; ImTextCharToUtf8(c_utf8, c); - int out_len = (int)strlen(c_utf8); + int out_len = (int)ImStrlen(c_utf8); clipboard_filtered.resize(clipboard_filtered.Size + out_len); memcpy(clipboard_filtered.Data + clipboard_filtered.Size - out_len, c_utf8, out_len); } @@ -5088,7 +5088,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (buf_dirty) { // Callback may update buffer and thus set buf_dirty even in read-only mode. - IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + IM_ASSERT(callback_data.BufTextLen == (int)ImStrlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! InputTextReconcileUndoState(state, state->CallbackTextBackup.Data, state->CallbackTextBackup.Size - 1, callback_data.Buf, callback_data.BufTextLen); state->TextLen = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() state->CursorAnimReset(); @@ -5187,7 +5187,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_displaying_hint) { buf_display = hint; - buf_display_end = hint + strlen(hint); + buf_display_end = hint + ImStrlen(hint); } // Render text. We currently only render selection when the widget is active or while scrolling. @@ -5220,7 +5220,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ int line_count = 1; if (is_multiline) { - for (const char* s = text_begin; (s = (const char*)memchr(s, '\n', (size_t)(text_end - s))) != NULL; s++) + for (const char* s = text_begin; (s = (const char*)ImMemchr(s, '\n', (size_t)(text_end - s))) != NULL; s++) { if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_no = line_count; } if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_no = line_count; } @@ -5298,7 +5298,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ break; if (rect_pos.y < clip_rect.y) { - p = (const char*)memchr((void*)p, '\n', text_selected_end - p); + p = (const char*)ImMemchr((void*)p, '\n', text_selected_end - p); p = p ? p + 1 : text_selected_end; } else @@ -5350,7 +5350,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else if (!is_displaying_hint && g.ActiveId == id) buf_display_end = buf_display + state->TextLen; else if (!is_displaying_hint) - buf_display_end = buf_display + strlen(buf_display); + buf_display_end = buf_display + ImStrlen(buf_display); if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) { @@ -7184,7 +7184,7 @@ ImGuiTypingSelectRequest* ImGui::GetTypingSelectRequest(ImGuiTypingSelectFlags f // Append to buffer const int buffer_max_len = IM_ARRAYSIZE(data->SearchBuffer) - 1; - int buffer_len = (int)strlen(data->SearchBuffer); + int buffer_len = (int)ImStrlen(data->SearchBuffer); bool select_request = false; for (ImWchar w : g.IO.InputQueueCharacters) { @@ -10111,7 +10111,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, else { tab->NameOffset = (ImS32)tab_bar->TabsNames.size(); - tab_bar->TabsNames.append(label, label + strlen(label) + 1); + tab_bar->TabsNames.append(label, label + ImStrlen(label) + 1); } // Update selected tab From 806731e37a27dab2abae14cc26a970d37ef9cd7d Mon Sep 17 00:00:00 2001 From: TheMode Date: Sun, 9 Mar 2025 06:28:36 +0100 Subject: [PATCH 0758/2359] Set IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS on 3DS sdk (#8477, #8476) --- imgui.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cac29a932..73bd2581e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15138,11 +15138,13 @@ static void Platform_SetClipboardTextFn_DefaultImpl(ImGuiContext* ctx, const cha #if defined(__APPLE__) && TARGET_OS_IPHONE #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS #endif - +#if defined(__3DS__) +#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS +#endif #if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS) #define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS #endif -#endif +#endif // #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS #ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS #ifdef _WIN32 From 3c3d943fb13c7ae2ddecbfe5f73252c4820f3a9f Mon Sep 17 00:00:00 2001 From: fdsa <14tanks999@gmail.com> Date: Sat, 8 Mar 2025 01:28:48 -0800 Subject: [PATCH 0759/2359] Docs: Fix some typos (#8473) --- backends/imgui_impl_opengl3.cpp | 2 +- backends/imgui_impl_osx.mm | 2 +- backends/imgui_impl_vulkan.cpp | 2 +- docs/CHANGELOG.txt | 138 ++++++++++++++++---------------- docs/FAQ.md | 4 +- docs/TODO.txt | 4 +- imgui.cpp | 10 +-- imgui.h | 2 +- imgui_demo.cpp | 6 +- imgui_internal.h | 6 +- imgui_tables.cpp | 4 +- imgui_widgets.cpp | 2 +- 12 files changed, 91 insertions(+), 91 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 1311d1bc9..7d0b53621 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -54,7 +54,7 @@ // 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state. // 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state. // 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x) -// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader. +// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre-3.3 context which have the defines set by a loader. // 2020-07-10: OpenGL: Added support for glad2 OpenGL loader. // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 4726462cb..2d72d413e 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -39,7 +39,7 @@ // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen. // 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen. -// 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mices). +// 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mice). // 2022-11-02: Fixed mouse coordinates before clicking the host window. // 2022-10-06: Fixed mouse inputs on flipped views. // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 7379e000b..e67b74c01 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -53,7 +53,7 @@ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-10-04: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symmetry. (#914, #5738). // 2022-01-20: Vulkan: Added support for ImTextureID as VkDescriptorSet. User need to call ImGui_ImplVulkan_AddTexture(). Building for 32-bit targets requires '#define ImTextureID ImU64'. (#914). -// 2021-10-15: Vulkan: Call vkCmdSetScissor() at the end of render a full-viewport to reduce likehood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame. +// 2021-10-15: Vulkan: Call vkCmdSetScissor() at the end of render a full-viewport to reduce likelihood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-03-22: Vulkan: Fix mapped memory validation error when buffer sizes are not multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize. // 2021-02-18: Vulkan: Change blending equation to preserve alpha in output buffer. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 39d73571d..ca5ab47e3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -101,7 +101,7 @@ Other changes: - Default for selected tabs: TabCloseButtonMinWidthSelected = -1.0f (always visible) - Default for unselected tabs: TabCloseButtonMinWidthUnselected = 0.0f (visible when hovered) - Tabs: fixed middle-mouse-button to close tab not checking that close button - is hovered, merely it's visibility. (#8399, #8387) [@nicovanbentum] + is hovered, merely its visibility. (#8399, #8387) [@nicovanbentum] - TextLink(), TextLinkOpenURL(): fixed honoring text baseline alignment. (#8451, #7660) [@achabense] - TextLinkOpenURL(): fixed default Win32 io.PlatformOpenInShellFn handler to @@ -678,7 +678,7 @@ Other changes: by an extra pixel + rework the change so that contents doesn't overlap the bottom and right border in a scrolling table. (#6765, #3752, #7428) - Tables: fixed an issue resizing columns or querying hovered column/row when using multiple - synched instances that are layed out at different X positions. (#7933) + synced instances that are laid out at different X positions. (#7933) - Tabs: avoid queuing a refocus when tab is already focused, which would have the side-effect of e.g. closing popup on a mouse release. (#7914) - InputText: allow callback to update buffer while in read-only mode. (imgui_club/#46) @@ -911,7 +911,7 @@ Other changes: - Windows: BeginChild(): fixed a glitch when during a resize of a child window which is tightly close to the boundaries of its parent (e.g. with zero WindowPadding), the child position could have temporarily be moved around by erroneous padding application. (#7706) -- TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline option to draw an horizontal +- TabBar, Style: added ImGuiTabBarFlags_DrawSelectedOverline option to draw a horizontal line over selected tabs to increase visibility. This is used by docking. Added corresponding ImGuiCol_TabSelectedOverline and ImGuiCol_TabDimmedSelectedOverline colors. - Tables: added TableGetHoveredColumn() to public API, as an alternative to testing for @@ -974,7 +974,7 @@ Other changes: - Scrollbar: made scrolling logic more standard: clicking above or below the grab scrolls by one page, holding mouse button repeats scrolling. (#7328, #150) - Scrollbar: fixed miscalculation of vertical scrollbar visibility when required - solely by the presence of an horizontal scrollbar. (#1574) + solely by the presence of a horizontal scrollbar. (#1574) - InputScalar, InputInt, InputFloat: added ImGuiInputTextFlags_ParseEmptyRefVal to parse an empty field as zero-value. (#7305) [@supermerill, @ocornut] - InputScalar, InputInt, InputFloat: added ImGuiInputTextFlags_DisplayEmptyRefVal @@ -1108,7 +1108,7 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v Breaking changes: -- TreeNode: Fixed a layout inconsistency when using a empty/hidden label followed +- TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282) Before: TreeNode("##Hidden"); SameLine(); Text("Hello"); // This was actually incorrect! BUT appeared to look ok with the default style @@ -1207,7 +1207,7 @@ Other changes: Note that only simple polygons (no self-intersections, no holes) are supported. - DrawList: Allow AddText() to accept null ranges. (#3615, 7391) - Docs: added more wiki links to headers of imgui.h/imgui.cpp to facilitate discovery - of interesting resources, because github doesn't allow Wiki to be crawled by search engines. + of interesting resources, because GitHub doesn't allow Wiki to be crawled by search engines. - This is the main wiki: https://github.com/ocornut/imgui/wiki - This is the crawlable version: https://github-wiki-see.page/m/ocornut/imgui/wiki Adding a link to the crawlable version, even though it is not intended for humans, @@ -1359,7 +1359,7 @@ Other changes: - BeginChild(): Resize borders rendered even when ImGuiWindowFlags_NoBackground is specified. (#1710, #7194) - Fixed some auto-resizing path using style.WindowMinSize.x (instead of x/y) - for both axises since 1.90. (#7106) [@n0bodysec] + for both axes since 1.90. (#7106) [@n0bodysec] - Scrolling: internal scrolling value is rounded instead of truncated, as a way to reduce speed asymmetry when (incorrectly) attempting to scroll by non-integer amount. (#6677) - Navigation (Keyboard/gamepad): @@ -1517,7 +1517,7 @@ Other changes: - Combining this with also specifying ImGuiChildFlags_AlwaysAutoResize disables this optimization, meaning child contents will never be clipped (not recommended). - Please be considerate that child are full windows and carry significant overhead: - combining auto-resizing for both axises to create a non-scrolling child to merely draw + combining auto-resizing for both axes to create a non-scrolling child to merely draw a border would be better more optimally using BeginGroup(). (see #1496) (until we come up with new helpers for framed groups and work-rect adjustments). - BeginChild(): made it possible to use SetNextWindowSizeConstraints() rectangle, often @@ -1579,7 +1579,7 @@ Other changes: parent-menu would erroneously close the child-menu. (Regression from 1.88). (#6869) - MenuBar: Fixed an issue where layouting an item in the menu-bar would erroneously register contents size in a way that would affect the scrolling layer. - Was most often noticeable when using an horizontal scrollbar. (#6789) + Was most often noticeable when using a horizontal scrollbar. (#6789) - InputText: - InputTextMultiline: Fixed a crash pressing Down on last empty line of a multi-line buffer. (regression from 1.89.2, only happened in some states). (#6783, #6000) @@ -1785,7 +1785,7 @@ Breaking changes: - Moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only - tweaked once during app initialisation, we are exceptionally accepting the breakage. + tweaked once during app initialization, we are exceptionally accepting the breakage. Majority of users should not even notice. - Overlapping items: (#6512, #3909, #517) - Added 'SetNextItemAllowOverlap()' (called before an item) as a replacement for using @@ -1885,7 +1885,7 @@ Breaking changes: - Commented out obsolete/redirecting functions that were marked obsolete more than two years ago: - ListBoxHeader() -> use BeginListBox() - ListBoxFooter() -> use EndListBox() - - Note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for refeence. + - Note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference. - Backends: SDL_Renderer: Renamed 'imgui_impl_sdlrenderer.h/cpp' to 'imgui_impl_sdlrenderer2.h/cpp', in order to accommodate for upcoming SDL3 and change in its SDL_Renderer API. (#6286) - Backends: GLUT: Removed call to ImGui::NewFrame() from ImGui_ImplGLUT_NewFrame(). @@ -2112,20 +2112,20 @@ Other changes: due to how unique table instance id was generated. (#6140) [@ocornut, @rodrigorc] - Inputs, Scrolling: Made horizontal scroll wheel and horizontal scroll direction consistent across backends/os. (#4019, #6096, #1463) [@PathogenDavid, @ocornut, @rokups] - - Clarified that 'wheel_y > 0.0f' scrolls Up, 'wheel_y > 0.0f' scrolls Down. - Clarified that 'wheel_x > 0.0f' scrolls Left, 'wheel_x > 0.0f' scrolls Right. + - Clarified that 'wheel_y > 0.0f' scrolls Up, 'wheel_y < 0.0f' scrolls Down. + Clarified that 'wheel_x > 0.0f' scrolls Left, 'wheel_x < 0.0f' scrolls Right. - Backends: Fixed horizontal scroll direction for Win32 and SDL backends. (#4019) - Shift+WheelY support on non-OSX machines was already correct. (#2424, #1463) (whereas on OSX machines Shift+WheelY turns into WheelX at the OS level). - If you use a custom backend, you should verify horizontal wheel direction. - - Axises are flipped by OSX for mouse & touch-pad when 'Natural Scrolling' is on. - - Axises are flipped by Windows for touch-pad when 'Settings->Touchpad->Down motion scrolls up' is on. + - Axes are flipped by OSX for mouse & touch-pad when 'Natural Scrolling' is on. + - Axes are flipped by Windows for touch-pad when 'Settings->Touchpad->Down motion scrolls up' is on. - You can use 'Demo->Tools->Debug Log->IO" to visualize values submitted to Dear ImGui. - Known issues remaining with Emscripten: - The magnitude of wheeling values on Emscripten was improved but isn't perfect. (#6096) - When running the Emscripten app on a Mac with a mouse, SHIFT+WheelY doesn't turn into WheelX. This is because we don't know that we are running on Mac and apply our own Shift+swapping - on top of OSX' own swapping, so wheel axises are swapped twice. Emscripten apps may need + on top of OSX's own swapping, so wheel axes are swapped twice. Emscripten apps may need to find a way to detect this and set io.ConfigMacOSXBehaviors manually (if you know a way let us know!), or offer the "OSX-style behavior" option to their user. - Window: Avoid rendering shapes for hidden resize grips. @@ -2151,7 +2151,7 @@ Other changes: values for io.DeltaTime, and browser features such as "privacy.resistFingerprinting=true" can exacerbate that. (#6114, #3644) - Backends: OSX: Fixed scroll/wheel scaling for devices emitting events with - hasPreciseScrollingDeltas==false (e.g. non-Apple mices). + hasPreciseScrollingDeltas==false (e.g. non-Apple mice). - Backends: Win32: flipping WM_MOUSEHWHEEL horizontal value to match other backends and offer consistent horizontal scrolling direction. (#4019) - Backends: SDL2: flipping SDL_MOUSEWHEEL horizontal value to match other backends and @@ -2355,7 +2355,7 @@ Other Changes: - Scrolling: Mitigated issue where multi-axis mouse-wheel inputs (usually from touch pad events) are incorrectly locking scrolling in a parent window. (#4559, #3795, #2604) - Scrolling: Exposed SetNextWindowScroll() in public API. Useful to remove a scrolling - delay in some situations where e.g. windows need to be synched. (#1526) + delay in some situations where e.g. windows need to be synced. (#1526) - InputText: added experimental io.ConfigInputTextEnterKeepActive feature to make pressing Enter keep the input active and select all text. - InputText: numerical fields automatically accept full-width characters (U+FF01..U+FF5E) @@ -2399,7 +2399,7 @@ Other Changes: - Menus: Fixed using IsItemHovered()/IsItemClicked() on BeginMenu(). (#5775) - Menus, Popups: Experimental fix for issue where clicking on an open BeginMenu() item called from a window which is neither a popup neither a menu used to incorrectly close and reopen the menu - (the fix may have side-effect and is labelld as experimental as we may need to revert). (#5775) + (the fix may have side-effect and is labelled as experimental as we may need to revert). (#5775) - Menus, Nav: Fixed keyboard/gamepad navigation occasionally erroneously landing on menu-item in parent window when the parent is not a popup. (#5730) - Menus, Nav: Fixed not being able to close a menu with Left arrow when parent is not a popup. (#5730) @@ -2537,7 +2537,7 @@ Other Changes: always lead to menu closure. Fixes using items that are not MenuItem() or BeginItem() at the root level of a popup with a child menu opened. - Menus: Menus emitted from the main/scrolling layer are not part of the same menu-set as menus emitted - from the menu-bar, avoiding accidental hovering from one to the other. (#3496, #4797) [@rokups] + from the menu-bar, avoiding accidental hovering from one to the other. (#3496, #4797) [@rokups] - Style: Adjust default value of GrabMinSize from 10.0f to 12.0f. - Stack Tool: Added option to copy item path to clipboard. (#4631) - Settings: Fixed out-of-bounds read when .ini file on disk is empty. (#5351) [@quantum5] @@ -2639,7 +2639,7 @@ Breaking Changes: io.AddKeyEvent(), io.AddKeyAnalogEvent(). - Added io.AddKeyAnalogEvent() function, obsoleting writing directly to io.NavInputs[] arrays. - Renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum. (#2625) -- Removed support for legacy arithmetic operators (+,+-,*,/) when inputing text into a slider/drag. (#4917, #3184) +- Removed support for legacy arithmetic operators (+,+-,*,/) when inputting text into a slider/drag. (#4917, #3184) This doesn't break any api/code but a feature that was accessible by end-users (which seemingly no one used). (Instead you may implement custom expression evaluators to provide a better version of this). - Backends: GLFW: backend now uses glfwSetCursorPosCallback(). @@ -2695,7 +2695,7 @@ Other Changes: - Backends: GLFW: Retrieve mouse position using glfwSetCursorPosCallback() + fallback when focused but not hovered/captured. - Backends: GLFW: Submit gamepad data using io.AddKeyEvent/AddKeyAnalogEvent() functions, stopped writing to io.NavInputs[]. (#4921) - Backends: GLFW: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing - callbacks after iniitializing backend. (#4981) + callbacks after initializing backend. (#4981) - Backends: Win32: Submit keys and key mods using io.AddKeyEvent(). (#2625, #4921) - Backends: Win32: Retrieve mouse position using WM_MOUSEMOVE/WM_MOUSELEAVE + fallback when focused but not hovered/captured. - Backends: Win32: Submit mouse data using io.AddMousePosEvent(), AddMouseButtonEvent(), AddMouseWheelEvent() functions. (#4921) @@ -2777,7 +2777,7 @@ Other Changes: - Menus: fixed sub-menu items inside a popups from closing the popup. - Menus: fixed top-level menu from not consistently using style.PopupRounding. (#4788) - InputText, Nav: fixed repeated calls to SetKeyboardFocusHere() preventing to use InputText(). (#4682) -- Inputtext, Nav: fixed using SetKeyboardFocusHere() on InputTextMultiline(). (#4761) +- InputText, Nav: fixed using SetKeyboardFocusHere() on InputTextMultiline(). (#4761) - InputText: made double-click select word, triple-line select line. Word delimitation logic differs slightly from the one used by CTRL+arrows. (#2244) - InputText: fixed ReadOnly flag preventing callbacks from receiving the text buffer. (#4762) [@actondev] @@ -2808,7 +2808,7 @@ Other Changes: - Misc: Fix MinGW DLL build issue (when IMGUI_API is defined). [@rokups] - CI: Add MinGW DLL build to test suite. [@rokups] - Backends: Vulkan: Call vkCmdSetScissor() at the end of render with a full-viewport to reduce - likehood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling + likelihood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame. (#4644) - Backends: OpenGL3: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers, and perhaps improve performances. (#4468, #4504, #2981, #3381) [@parbo] @@ -2884,7 +2884,7 @@ Other Changes: - Nav: Fixed vertical scoring offset when wrapping on Y in a decorated window. - Nav: Improve scrolling behavior when navigating to an item larger than view. - TreePush(): removed unnecessary/inconsistent legacy behavior where passing a NULL value to - the TreePush(const char*) and TreePush(const void*) functions would use an hard-coded replacement. + the TreePush(const char*) and TreePush(const void*) functions would use a hard-coded replacement. The only situation where that change would make a meaningful difference is TreePush((const char*)NULL) (_explicitly_ casting a null pointer to const char*), which is unlikely and will now crash. You may replace it with anything else. @@ -3007,9 +3007,9 @@ Other Changes: - Fonts: Functions with a 'float size_pixels' parameter can accept zero if it is set in ImFontSize::SizePixels. - Fonts: Prefer using U+FFFD character for fallback instead of '?', if available. (#4269) - Fonts: Use U+FF0E dot character to construct an ellipsis if U+002E '.' is not available. (#4269) -- Fonts: Added U+FFFD ("replacement character") to default asian glyphs ranges. (#4269) +- Fonts: Added U+FFFD ("replacement character") to default Asian glyphs ranges. (#4269) - Fonts: Fixed calling ClearTexData() (clearing CPU side font data) triggering an assert in NewFrame(). (#3487) -- DrawList: Fixed AddCircle/AddCircleFilled() with auto-tesselation not using accelerated paths for small circles. +- DrawList: Fixed AddCircle/AddCircleFilled() with auto-tessellation not using accelerated paths for small circles. Fixed AddCircle/AddCircleFilled() with 12 segments which had a broken edge. (#4419, #4421) [@thedmd] - Demo: Fixed requirement in 1.83 to link with imgui_demo.cpp if IMGUI_DISABLE_METRICS_WINDOW is not set. (#4171) Normally the right way to disable compiling the demo is to set IMGUI_DISABLE_DEMO_WINDOWS, but we want to avoid @@ -3053,7 +3053,7 @@ Other Changes: - Examples: OSX+OpenGL2: Fix event forwarding (fix key remaining stuck when using shortcuts with Cmd/Super key). Other OSX examples were not affected. (#4253, #1873) [@rokups] - Examples: Updated all .vcxproj to VS2015 (toolset v140) to facilitate usage with vcpkg. -- Examples: SDL2: Accommodate for vcpkg install having headers in SDL2/SDL.h vs SDL.h. +- Examples: SDL2: Accommodate for vcpkg install having headers in SDL2/SDL.h vs SDL.h. ----------------------------------------------------------------------- @@ -3175,7 +3175,7 @@ Breaking Changes: - ImDrawList: clarified that PathArcTo()/PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would lead to counter-clockwise paths which and have an effect on anti-aliasing. - InputText: renamed ImGuiInputTextFlags_AlwaysInsertMode to ImGuiInputTextFlags_AlwaysOverwrite, old name was an - incorrect description of behavior. Was ostly used by memory editor. Kept inline redirection function. (#2863) + incorrect description of behavior. Was mostly used by memory editor. Kept inline redirection function. (#2863) - Moved 'misc/natvis/imgui.natvis' to 'misc/debuggers/imgui.natvis' as we will provide scripts for other debuggers. - Style: renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as its meaning changed. (#3808) [@thedmd] @@ -3273,7 +3273,7 @@ Other Changes: - For a Platform Monitor, the work area is generally the full area minus space used by task-bars. - All of this has been the case in 'docking' branch for a long time. What we've done is merely merging a small chunk of the multi-viewport logic into 'master' to standardize some concepts ahead of time. -- Tables: Fixed PopItemWidth() or multi-components items not restoring per-colum ItemWidth correctly. (#3760) +- Tables: Fixed PopItemWidth() or multi-components items not restoring per-column ItemWidth correctly. (#3760) - Window: Fixed minor title bar text clipping issue when FramePadding is small/zero and there are no close button in the window. (#3731) - SliderInt: Fixed click/drag when v_min==v_max from setting the value to zero. (#3774) [@erwincoumans] @@ -3310,7 +3310,7 @@ Other Changes: User needs to call ImGui_ImplVulkan_LoadFunctions() with their custom loader prior to other functions. - Backends: Metal: Fixed texture storage mode when building on Mac Catalyst. (#3748) [@Belinsky-L-V] - Backends: OSX: Fixed mouse position not being reported when mouse buttons other than left one are down. (#3762) [@rokups] -- Backends: WebGPU: Added enderer backend for WebGPU support (imgui_impl_wgpu.cpp) (#3632) [@bfierz] +- Backends: WebGPU: Added renderer backend for WebGPU support (imgui_impl_wgpu.cpp) (#3632) [@bfierz] Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break. - Examples: WebGPU: Added Emscripten+WebGPU example. (#3632) [@bfierz] - Backends: GLFW: Added ImGui_ImplGlfw_InitForOther() initialization call to use with non OpenGL API. (#3632) @@ -3509,12 +3509,12 @@ Other Changes: - Columns: Fix inverted ClipRect being passed to renderer when using certain primitives inside of a fully clipped column. (#3475) [@szreder] - Popups, Tooltips: Fix edge cases issues with positioning popups and tooltips when they are larger than - viewport on either or both axises. [@Rokups] + viewport on either or both axes. [@Rokups] - Fonts: AddFontDefault() adjust its vertical offset based on floor(size/13) instead of always +1. Was previously done by altering DisplayOffset.y but wouldn't work for DPI scaled font. - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). -- Backends: OpenGL3: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 contexts which have +- Backends: OpenGL3: Fix to avoid compiling/calling glBindSampler() on ES or pre-3.3 contexts which have the defines set by a loader. (#3467, #1985) [@jjwebb] - Backends: Vulkan: Some internal refactor aimed at allowing multi-viewport feature to create their own render pass. (#3455, #3459) [@FunMiles] @@ -3603,7 +3603,7 @@ Other Changes: and allowed to pass them to InvisibleButton(): ImGuiButtonFlags_MouseButtonLeft/Right/Middle. This is a small but rather important change because lots of multi-button behaviors could previously only be achieved using lower-level/internal API. Now also available via high-level InvisibleButton() - with is a de-facto versatile building block to creating custom widgets with the public API. + with is a de facto versatile building block to creating custom widgets with the public API. - Fonts: Fixed ImFontConfig::GlyphExtraSpacing and ImFontConfig::PixelSnapH settings being pulled from the merged/target font settings when merging fonts, instead of being pulled from the source font settings. @@ -3750,7 +3750,7 @@ Other Changes: ImGuiListClipper as the first thing after Begin() could largely break size calculations. (#3073) - Added optional support for Unicode plane 1-16 (#2538, #2541, #2815) [@cloudwu, @samhocevar] - Compile-time enable with '#define IMGUI_USE_WCHAR32' in imconfig.h. - - More onsistent handling of unsupported code points (0xFFFD). + - More consistent handling of unsupported code points (0xFFFD). - Surrogate pairs are supported when submitting UTF-16 data via io.AddInputCharacterUTF16(), allowing for more complete CJK input. - sizeof(ImWchar) goes from 2 to 4. IM_UNICODE_CODEPOINT_MAX goes from 0xFFFF to 0x10FFFF. @@ -3834,7 +3834,7 @@ Other Changes: - Inputs: Added ImGuiMouseButton enum for convenience (e.g. ImGuiMouseButton_Right=1). We forever guarantee that the existing value will not changes so existing code is free to use 0/1/2. -- Nav: Fixed a bug where the initial CTRL-Tab press while in a child window sometimes selected +- Nav: Fixed a bug where the initial CTRL+Tab press while in a child window sometimes selected the current root window instead of always selecting the previous root window. (#787) - ColorEdit: Fix label alignment when using ImGuiColorEditFlags_NoInputs. (#2955) [@rokups] - ColorEdit: In HSV display of a RGB stored value, attempt to locally preserve Saturation @@ -4007,7 +4007,7 @@ Other Changes: mostly for consistency. (#2159, #2160) [@goran-w] - Selectable: Added ImGuiSelectableFlags_AllowItemOverlap flag in public api (was previously internal only). - Style: Allow style.WindowMenuButtonPosition to be set to ImGuiDir_None to hide the collapse button. (#2634, #2639) -- Font: Better ellipsis ("...") drawing implementation. Instead of drawing three pixel-ey dots (which was glaringly +- Font: Better ellipsis ("...") drawing implementation. Instead of drawing three pixely dots (which was glaringly unfitting with many types of fonts) we first attempt to find a standard ellipsis glyphs within the loaded set. Otherwise we render ellipsis using '.' from the font from where we trim excessive spacing to make it as narrow as possible. (#2775) [@rokups] @@ -4343,7 +4343,7 @@ Other Changes: - InputText: Fixed an edge case crash that would happen if another widget sharing the same ID is being swapped with an InputText that has yet to be activated. - InputText: Fixed various display corruption related to swapping the underlying buffer while - a input widget is active (both for writable and read-only paths). Often they would manifest + an input widget is active (both for writable and read-only paths). Often they would manifest when manipulating the scrollbar of a multi-line input text. - ColorEdit, ColorPicker, ColorButton: Added ImGuiColorEditFlags_InputHSV to manipulate color values encoded as HSV (in order to avoid HSV<>RGB round trips and associated singularities). @@ -4354,7 +4354,7 @@ Other Changes: reading the 4th float in the array (value was read and discarded). (#2384) [@haldean] - MenuItem, Selectable: Fixed disabled widget interfering with navigation (fix c2db7f63 in 1.67). - Tabs: Fixed a crash when using many BeginTabBar() recursively (didn't affect docking). (#2371) -- Tabs: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to +- Tabs: Added extra misusage error recovery. Past the assert, common misusage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) - Tabs: Fixed ImGuiTabItemFlags_SetSelected being ignored if the tab is not visible (with scrolling policy enabled) or if is currently appearing. @@ -4397,7 +4397,7 @@ Breaking Changes: - Removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - Made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). - If for some reason your time step calculation gives you a zero value, replace it with a arbitrarily small value! + If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value! Other Changes: @@ -4495,7 +4495,7 @@ Other Changes: in the parent window, so there is no mismatch between the layout in parent and the position of the child window. - InputFloat: When using ImGuiInputTextFlags_ReadOnly the step buttons are disabled. (#2257) - DragFloat: Fixed broken mouse direction change with power!=1.0. (#2174, #2206) [@Joshhua5] -- Nav: Fixed an keyboard issue where holding Activate/Space for longer than two frames on a button would unnecessary +- Nav: Fixed a keyboard issue where holding Activate/Space for longer than two frames on a button would unnecessary keep the focus on the parent window, which could steal it from newly appearing windows. (#787) - Nav: Fixed animated window titles from being updated when displayed in the CTRL+Tab list. (#787) - Error recovery: Extraneous/undesired calls to End() are now being caught by an assert in the End() function closer @@ -4647,7 +4647,7 @@ Changes: then separate your changes into several patches that can more easily be applied to 1.64 on a per-file basis. What I found worked nicely for me, was to open the diff of the old patches in an interactive merge/diff tool, search for the corresponding function in the new code and apply the chunks manually. -- As a reminder, if you have any change to imgui.cpp it is a good habit to discuss them on the github, +- As a reminder, if you have any change to imgui.cpp it is a good habit to discuss them on the GitHub, so a solution applicable on the Master branch can be found. If your company has changes that you cannot disclose you may also contact me privately. @@ -4682,7 +4682,7 @@ Other Changes: - Nav: Added a CTRL+TAB window list and changed the highlight system accordingly. The change is motivated by upcoming Docking features. (#787) - Nav: Made CTRL+TAB skip menus + skip the current navigation window if is has the ImGuiWindow_NoNavFocus set. (#787) - While it was previously possible, you won't be able to CTRL-TAB out and immediately back in a window with the + While it was previously possible, you won't be able to CTRL+TAB out and immediately back in a window with the ImGuiWindow_NoNavFocus flag. - Window: Allow menu and popups windows from ignoring the style.WindowMinSize values so short menus/popups are not padded. (#1909) - Window: Added global io.ConfigResizeWindowsFromEdges option to enable resizing windows from their edges and from @@ -4717,7 +4717,7 @@ Other Changes: - Fixed assertion when transitioning from an active ID to another within a group, affecting ColorPicker (broken in 1.62). (#2023, #820, #956, #1875). - Fixed PushID() from keeping alive the new ID Stack top value (if a previously active widget shared the ID it would be erroneously kept alive). - Fixed horizontal mouse wheel not forwarding the request to the parent window if ImGuiWindowFlags_NoScrollWithMouse is set. (#1463, #1380, #1502) -- Fixed a include build issue for Cygwin in non-POSIX (Win32) mode. (#1917, #1319, #276) +- Fixed an include build issue for Cygwin in non-POSIX (Win32) mode. (#1917, #1319, #276) - ImDrawList: Improved handling for worst-case vertices reservation policy when large amount of text (e.g. 1+ million character strings) are being submitted in a single call. It would typically have crashed InputTextMultiline(). (#200) - OS/Windows: Fixed missing ImmReleaseContext() call in the default Win32 IME handler. (#1932) [@vby] @@ -4952,7 +4952,7 @@ Other Changes: - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays. - Basic controls: arrows to navigate, Alt to enter menus, Space to activate item, Enter to edit text, - Escape to cancel/close, Ctrl-Tab to focus windows, etc. + Escape to cancel/close, Ctrl+Tab to focus windows, etc. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag will be set. - For more advanced uses, you may want to read from io.NavActive or io.NavVisible. Read imgui.cpp for more details. @@ -5002,7 +5002,7 @@ Other Changes: - Style: Exposed ImGuiStyleVar_WindowTitleAlign, ImGuiStyleVar_ScrollbarSize, ImGuiStyleVar_ScrollbarRounding, ImGuiStyleVar_GrabRounding + added an assert to reduce accidental breakage. (#1181) - Style: Added style.MouseCursorScale help when using the software mouse cursor facility. (#939). -- Style: Close button nows display a cross before hovering. Fixed cross positioning being a little off. Uses button colors for highlight when hovering. (#707) +- Style: Close buttons now display a cross before hovering. Fixed cross positioning being a little off. Uses button colors for highlight when hovering. (#707) - Popup: OpenPopup() Always reopen existing pop-ups. (Removed imgui_internal.h's OpenPopupEx() which was used for this.) (#1497, #1533). - Popup: BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick() all react on mouse release instead of mouse press. (~#439) - Popup: Better handling of user mistakenly calling OpenPopup() every frame (with the 'reopen_existing' option). @@ -5025,7 +5025,7 @@ Other Changes: - Drag and Drop: Increased payload type string to 32 characters instead of 8. (#143) - Drag and Drop: TreeNode as drop target displays rectangle over full frame. (#1597, #143) - DragFloat: Fix/workaround for backends which do not preserve a valid mouse position when dragged out of bounds. (#1559) -- InputFloat: Allow inputing value using scientific notation e.g. "1e+10". +- InputFloat: Allow inputting value using scientific notation e.g. "1e+10". - InputDouble: Added InputDouble() function. We use a format string instead of a 'decimal_precision' parameter to also for "%e" and variants. (#1011) - Slider, Combo: Use ImGuiCol_FrameBgHovered color when hovered. (#1456) [@stfx] @@ -5070,7 +5070,7 @@ Other Changes: - Demo: Improved Selectable() examples. (#1528) - Demo: Tweaked the Child demos, added a menu bar to the second child to test some navigation functions. - Demo: Console: Using ImGuiCol_Text to be more friendly to color changes. -- Demo: Using IM_COL32() instead of ImColor() in ImDrawList centric contexts. Trying to phase out use of the ImColor helper whenever possible. +- Demo: Using IM_COL32() instead of ImColor() in ImDrawList-centric contexts. Trying to phase out use of the ImColor helper whenever possible. - Examples: Files in examples/ now include their own changelog so it is easier to occasionally update your backends if needed. - Examples: Using Dark theme by default. (#707). Tweaked demo code. - Examples: Added support for horizontal mouse wheel for API that allows it. (#1463) [@tseeker] @@ -5188,7 +5188,7 @@ Other Changes: - Window: Added ImGuiWindowFlags_ResizeFromAnySide flag to resize from any borders or from the lower-left corner of a window. This requires your backend to honor GetMouseCursor() requests for full usability. (#822) -- Window: Sizing fixes when using SetNextWindowSize() on individual axises. +- Window: Sizing fixes when using SetNextWindowSize() on individual axes. - Window: Hide new window for one frame until they calculate their size. Also fixes SetNextWindowPos() given a non-zero pivot. (#1694) - Window: Made mouse wheel scrolling accommodate better to windows that are smaller than the scroll step. @@ -5490,7 +5490,7 @@ Other Changes: check the Demo window and comment for `ImGuiColorEditFlags_`. Some of the options it supports are: two color picker types (hue bar + sat/val rectangle, hue wheel + rotating sat/val triangle), display as u8 or float, lifting 0.0..1.0 constraints - (currently rgba only), context menus, alpha bar, background checkerboard options, preview tooltip, + (currently rgba only), context menus, alpha bar, background checkerboard options, preview tooltip, basic revert. For simple use, calling the existing `ColorEdit4()` function as you did before will be enough, as you can now open the color picker from there. - Added `SetColorEditOptions()` to set default color options (e.g. if you want HSV over RGBA, @@ -5592,7 +5592,7 @@ Other Changes: certain style settings and zero WindowMinSize). - EndGroup(): Made IsItemHovered() work when an item was activated within the group. (#849) - BulletText(): Fixed stopping to display formatted string after the '##' mark. -- Closing the focused window restore focus to the first active root window in descending z-order .(part of #727) +- Closing the focused window restore focus to the first active root window in descending z-order. (part of #727) - Word-wrapping: Fixed a bug where we never wrapped after a 1 character word. [@sronsse] - Word-wrapping: Fixed TextWrapped() overriding wrap position if one is already set. (#690) - Word-wrapping: Fixed incorrect testing for negative wrap coordinates, they are perfectly legal. (#706) @@ -5629,7 +5629,7 @@ Other Changes: - Demo: ShowStyleEditor: show font character map / grid in more details. - Demo: Console: Fixed a completion bug when multiple candidates are equals and match until the end. - Demo: Fixed 1-byte off overflow in the ShowStyleEditor() combo usage. (#783) [@bear24rw] -- Examples: Accessing ImVector fields directly, feel less stl-ey. (#810) +- Examples: Accessing ImVector fields directly, feel less stl-y. (#810) - Examples: OpenGL*: Saving/restoring existing scissor rectangle for completeness. (#807) - Examples: OpenGL*: Saving/restoring active texture number (the value modified by glActiveTexture). (#1087, #1088, #1116) - Examples: OpenGL*: Saving/restoring separate color/alpha blend functions correctly. (#1120) [@greggman] @@ -5793,7 +5793,7 @@ Other Changes: after a text input modification (e.g. "0.0" --> "0.000" would keep returning true). (#564) - DragFloat(): Always apply value when mouse is held/widget active, so that an always-resetting variable (e.g. non saved local) can be passed. -- InputText(): OS X friendly behaviors: (@zhiayang), (#473) +- InputText(): OS X friendly behaviors: (@zhiayang), (#473) - Word movement uses ALT key; - Shortcuts uses CMD key; - Double-clicking text select a single word; @@ -5918,7 +5918,7 @@ Changes: - PlotHistogram(): improved rendering of histogram with a lot of values. - Dummy(): creates an item so functions such as IsItemHovered() can be used. - BeginChildFrame() helper: added the extra_flags parameter. -- Scrollbar: fixed rounding of background + child window consistenly have ChildWindowBg color under ScrollbarBg fill. (#355). +- Scrollbar: fixed rounding of background + child window consistently have ChildWindowBg color under ScrollbarBg fill. (#355). - Scrollbar: background color less translucent in default style so it works better when changing background color. - Scrollbar: fixed minor rendering offset when borders are enabled. (#365) - ImDrawList: fixed 1 leak per ImDrawList using the ChannelsSplit() API (via Columns). (#318) @@ -5934,7 +5934,7 @@ Changes: - Internal: Extracted a EndFrame() function out of Render() but kept it internal/private + clarified some asserts. (#335) - Internal: Added missing IMGUI_API definitions in imgui_internal.h (#326) - Internal: ImLoadFileToMemory() return void\* instead of taking void*\* + allow optional int\* file_size. -- Demo: Horizontal scrollbar demo allows to enable simultanaeous scrollbars on both axises. +- Demo: Horizontal scrollbar demo allows to enable simultaneous scrollbars on both axes. - Tools: binary_to_compressed_c.cpp: added -nocompress option. - Examples: Added example for the Marmalade platform. - Examples: Added batch files to build Windows examples with VS. @@ -5979,7 +5979,7 @@ Other Changes: - ImDrawList: Added an assert on overflowing index value (#292). - ImDrawList: Fixed issues with channels split/merge. Now functional without manually adding a draw cmd. Added comments. - ImDrawData: Added ScaleClipRects() helper useful when rendering scaled. (#287). -- Fixed Bullet() inconsistent layout behaviour when clipped. +- Fixed Bullet() inconsistent layout behavior when clipped. - Fixed IsWindowHovered() not taking account of window hoverability (may be disabled because of a popup). - Fixed InvisibleButton() not honoring negative size consistently with other widgets that do so. - Fixed OpenPopup() accessing current window, effectively opening "Debug" when called from an empty window stack. @@ -5991,7 +5991,7 @@ Other Changes: the first place so it's not really a useful default. - Begin(): Minor fixes with windows main clipping rectangle (e.g. child window with border). - Begin(): Window flags are only read on the first call of the frame. Subsequent calls ignore flags, which allows - appending to a window without worryin about flags. + appending to a window without worrying about flags. - InputText(): ignore character input when ctrl/alt are held. (Normally those text input are ignored by most wrappers.) (#279). - Demo: Fixed incorrectly formed string passed to Combo (#298). - Demo: Added simple Log demo. @@ -6025,7 +6025,7 @@ Other Changes: and more natural to extend ImGui. However please note that none of the content in imgui_internal.h is guaranteed for forward-compatibility and code using those types/functions may occasionally break. (#219) - All sample code is in imgui_demo.cpp. Please keep this file in your project and consider allowing your code to call - the ShowTestWindow() function as de-facto guide to ImGui features. It will be stripped out by the linker when unused. + the ShowTestWindow() function as de facto guide to ImGui features. It will be stripped out by the linker when unused. - Added GetContentRegionAvail() helper (basically GetContentRegionMax() - GetCursorPos()). - Added ImGuiWindowFlags_NoInputs for totally input-passthru window. - Button(): honor negative size consistently with other widgets that do so (width -100 to align the button 100 pixels @@ -6390,7 +6390,7 @@ Other Changes: - IsItemHovered() return false if another widget is active, aka we can't use what we are hovering now. - Added IsItemHoveredRect() if old behavior of IsItemHovered() is needed (e.g. for implementing the drop side of a drag'n drop operation). -- IsItemhovered() include space taken by label and behave consistently for all widgets (#145) +- IsItemHovered() include space taken by label and behave consistently for all widgets (#145) - Auto-filling child window feed their content size to parent (#170) - InputText() removed the odd ~ characters when clipping. - InputText() update its width in case of resize initiated programmatically while the widget is active. @@ -6454,7 +6454,7 @@ Other Changes: - Sliders: Fixed parsing of decimal precision back from format string when using %%. - Sliders: Fixed hovering bounding test excluding padding between outer frame and grab (there was a few pixels dead-zone). - Separator() logs itself as text when passing through text log. -- Optimisation: TreeNodeV() early out if SkipItems is set without formatting. +- Optimization: TreeNodeV() early out if SkipItems is set without formatting. - Moved various static buffers into state. Increase the formatted string buffer from 1K to 3K. - Examples: Example console keeps focus on input box at all times. - Examples: Updated to GLFW 3.1. Moved to examples/libs/ folder. @@ -6583,8 +6583,8 @@ Other Changes: Callback now passed an "EventFlag" parameter. - InputText: Added ImGuiInputTextFlags_CharsUppercase and ImGuiInputTextFlags_CharsNoBlank stock filters. - PushItemWidth() can take negative value to right-align items. -- Optimisation: Columns offsets cached to avoid unnecessary binary search. -- Optimisation: Optimized CalcTextSize() function by about 25% (they are often the bottleneck when +- Optimization: Columns offsets cached to avoid unnecessary binary search. +- Optimization: Optimized CalcTextSize() function by about 25% (they are often the bottleneck when submitting thousands of clipped items). - Added ImGuiCol_ChildWindowBg, ImGuiStyleVar_ChildWindowRounding for completeness and flexibility. - Added BeginChild() variant that takes an ImGuiID. @@ -6627,7 +6627,7 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v Breaking Changes: -- Big update! Initialisation had to be changed. You don't need to load PNG data anymore. Th +- Big update! Initialization had to be changed. You don't need to load PNG data anymore. The new system gives you uncompressed texture data. - This sequence: const void* png_data; @@ -6637,7 +6637,7 @@ Breaking Changes: - Became: unsigned char* pixels; int width, height; - // io.Fonts->AddFontFromFileTTF("myfontfile.ttf", 24.0f); // Optionally load another font + // io.Fonts->AddFontFromFileTTF("myfontfile.ttf", 24.0f); // Optionally load another font io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // io.Fonts->TexID = (your_texture_identifier); @@ -6659,7 +6659,7 @@ Other Changes: - Added IsItemActive() to tell if last widget is being held / modified (as opposed to just being hovered). Useful for custom dragging behaviors. - Style: Added FrameRounding setting for a more rounded look (default to 0 for now). -- Window: Fixed using multiple Begin/End pair on the same wnidow. +- Window: Fixed using multiple Begin/End pair on the same window. - Window: Fixed style.WindowMinSize not being honored properly. - Window: Added SetCursorScreenPos() helper (WindowPos+CursorPos = ScreenPos). - ColorEdit3: clicking on color square change the edition. The toggle button is hidden by default. @@ -6690,10 +6690,10 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v - Dragging outside area of a widget while it is active doesn't trigger hover on other widgets. - Activating widget bring parent window to front if not already. - Checkbox and Radio buttons activate on click-release to be consistent with other widgets and most UI. -- InputText() nows consume input characters immediately so they cannot be reused if +- InputText() now consumes input characters immediately so they cannot be reused if ImGui::Update is called again with a call to ImGui::Render(). (fixes #105) - Examples: Console: added support for History callbacks + some cleanup. -- Various small optimisations. +- Various small optimizations. - Cleanup and other fixes. @@ -6896,7 +6896,7 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v Breaking Changes: -- The behaviour of PixelCenterOffset changed! You may need to change your value if you had set +- The behavior of PixelCenterOffset changed! You may need to change your value if you had set it to non-default in your code and/or offset your projection matrix by 0.5 pixels. It is likely that the default PixelCenterOffset value of 0.0 is now suitable unless your rendering uses some form of multisampling. @@ -6990,7 +6990,7 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v - OpenGL example now use the fixed function-pipeline + cleanups, down by 150 lines. - Added quick & dirty Makefiles for MacOSX and Linux. -- Simplified the DrawList system, ImDrawCmd include the clipping rectangle + some optimisations. +- Simplified the DrawList system, ImDrawCmd include the clipping rectangle + some optimizations. - Fixed warnings for more stringent compilation settings. diff --git a/docs/FAQ.md b/docs/FAQ.md index 6e8d6c26f..5af2e9035 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -543,7 +543,7 @@ The short answer is: obtain the desired DPI scale, load your fonts resized with Your application may want to detect DPI change and reload the fonts and reset style between frames. -Your ui code should avoid using hardcoded constants for size and positioning. Prefer to express values as multiple of reference values such as `ImGui::GetFontSize()` or `ImGui::GetFrameHeight()`. So e.g. instead of seeing a hardcoded height of 500 for a given item/window, you may want to use `30*ImGui::GetFontSize()` instead. +Your UI code should avoid using hardcoded constants for size and positioning. Prefer to express values as multiple of reference values such as `ImGui::GetFontSize()` or `ImGui::GetFrameHeight()`. So e.g. instead of seeing a hardcoded height of 500 for a given item/window, you may want to use `30*ImGui::GetFontSize()` instead. Down the line Dear ImGui will provide a variety of standardized reference values to facilitate using this. @@ -666,7 +666,7 @@ You may take a look at: Yes. People have written game editors, data browsers, debuggers, profilers, and all sorts of non-trivial tools with the library. In my experience, the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools). The list of sponsors below is also an indicator that serious game teams have been using the library. -Dear ImGui is very programmer centric and the immediate-mode GUI paradigm might require you to readjust some habits before you can realize its full potential. Dear ImGui is about making things that are simple, efficient, and powerful. +Dear ImGui is very programmer-centric and the immediate-mode GUI paradigm might require you to readjust some habits before you can realize its full potential. Dear ImGui is about making things that are simple, efficient, and powerful. Dear ImGui is built to be efficient and scalable toward the needs for AAA-quality applications running all day. The IMGUI paradigm offers different opportunities for optimization than the more typical RMGUI paradigm. diff --git a/docs/TODO.txt b/docs/TODO.txt index 14a152a4b..aeef17592 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -279,7 +279,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - nav: expose wrap around flags/logic to allow e.g. grid based layout (pressing NavRight on the right-most element would go to the next row, etc.). see internal's NavMoveRequestTryWrapping(). - nav: patterns to make it possible for arrows key to update selection (see JustMovedTo in range_select branch) - nav: restore/find nearest NavId when current one disappear (e.g. pressed a button that disappear, or perhaps auto restoring when current button change name) - - nav: SetItemDefaultFocus() level of priority, so widget like Selectable when inside a popup could claim a low-priority default focus on the first selected iem + - nav: SetItemDefaultFocus() level of priority, so widgets like Selectable when inside a popup could claim a low-priority default focus on the first selected item - nav: holding space to repeat a button doesn't show button activated during hold. - nav: NavFlattened: init requests don't work properly on flattened siblings. - nav: NavFlattened: pageup/pagedown/home/end don't work properly on flattened siblings. @@ -329,7 +329,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - backends: opengl: explicitly disable GL_STENCIL_TEST in bindings. - backends: vulkan: viewport: support for synchronized swapping of multiple swap chains. - backends: bgfx: https://gist.github.com/RichardGale/6e2b74bc42b3005e08397236e4be0fd0 - - backends: emscriptem: with refactored examples, we could provide a direct imgui_impl_emscripten platform layer (see eg. https://github.com/floooh/sokol-samples/blob/master/html5/imgui-emsc.cc#L42) + - backends: emscripten: with refactored examples, we could provide a direct imgui_impl_emscripten platform layer (see eg. https://github.com/floooh/sokol-samples/blob/master/html5/imgui-emsc.cc#L42) - bindings: ways to use clang ast dump to generate bindings or helpers for bindings? (e.g. clang++ -Xclang -ast-dump=json imgui.h) (--> use https://github.com/dearimgui/dear_bindings) diff --git a/imgui.cpp b/imgui.cpp index 73bd2581e..86b0d5d46 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -655,7 +655,7 @@ CODE - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO. - 2022/01/20 (1.87) - inputs: reworded gamepad IO. - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values. - - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used). + - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputting text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used). - 2022/01/17 (1.87) - inputs: reworked mouse IO. - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent() - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent() @@ -4954,7 +4954,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) // Handle mouse moving window // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() -// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId. +// FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId. // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs, // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other. void ImGui::UpdateMouseMovingWindowNewFrame() @@ -6563,7 +6563,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si { // Auto-fit when double-clicking size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit); - ret_auto_fit_mask = 0x03; // Both axises + ret_auto_fit_mask = 0x03; // Both axes ClearActiveID(); } else if (held) @@ -9701,7 +9701,7 @@ void ImGui::UpdateMouseWheel() if (g.IO.MouseWheelRequestAxisSwap) wheel = ImVec2(wheel.y, 0.0f); - // Maintain a rough average of moving magnitude on both axises + // Maintain a rough average of moving magnitude on both axes // FIXME: should by based on wall clock time rather than frame-counter g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30); g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30); @@ -9714,7 +9714,7 @@ void ImGui::UpdateMouseWheel() // Mouse wheel scrolling: find target and apply // - don't renew lock if axis doesn't apply on the window. - // - select a main axis when both axises are being moved. + // - select a main axis when both axes are being moved. if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel))) if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) { diff --git a/imgui.h b/imgui.h index 2f6a18d2a..4a14c82c2 100644 --- a/imgui.h +++ b/imgui.h @@ -544,7 +544,7 @@ namespace ImGui IMGUI_API void LabelTextV(const char* 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 an horizontal line + IMGUI_API void SeparatorText(const char* label); // currently: formatted text with a horizontal line // Widgets: Main // - Most widgets return true when the value has been changed or when pressed/selected diff --git a/imgui_demo.cpp b/imgui_demo.cpp index beffe618d..50eeed107 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8415,7 +8415,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::EndTooltip(); } ImGui::SameLine(); - HelpMarker("When drawing circle primitives with \"num_segments == 0\" tesselation will be calculated automatically."); + HelpMarker("When drawing circle primitives with \"num_segments == 0\" tessellation will be calculated automatically."); ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. ImGui::DragFloat("Disabled Alpha", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha)."); @@ -8446,7 +8446,7 @@ void ImGui::ShowUserGuide() ImGui::BulletText("CTRL+Tab to select a window."); if (io.FontAllowUserScaling) ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); - ImGui::BulletText("While inputing text:\n"); + ImGui::BulletText("While inputting text:\n"); ImGui::Indent(); ImGui::BulletText("CTRL+Left/Right to word jump."); ImGui::BulletText("CTRL+A or double-click to select all."); @@ -8877,7 +8877,7 @@ struct ExampleAppConsole else { // Multiple matches. Complete as much as we can.. - // So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. + // So inputting "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. int match_len = (int)(word_end - word_start); for (;;) { diff --git a/imgui_internal.h b/imgui_internal.h index b7395fcae..aaa2027df 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2801,7 +2801,7 @@ struct IMGUI_API ImGuiTable { ImGuiID ID; ImGuiTableFlags Flags; - void* RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[] and RowCellData[] + void* RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[], and RowCellData[] ImGuiTableTempData* TempData; // Transient data while table is active. Point within g.CurrentTableStack[] ImSpan Columns; // Point within RawData[] ImSpan DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) @@ -2815,7 +2815,7 @@ struct IMGUI_API ImGuiTable int ColumnsCount; // Number of columns declared in BeginTable() int CurrentRow; int CurrentColumn; - ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple table with same ID look are multiple tables, they are just synched. + ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple tables with the same ID are multiple tables, they are just synced. ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with float RowPosY1; float RowPosY2; @@ -2847,7 +2847,7 @@ struct IMGUI_API ImGuiTable float AngledHeadersHeight; // Set by TableAngledHeadersRow(), used in TableUpdateLayout() float AngledHeadersSlope; // Set by TableAngledHeadersRow(), used in TableUpdateLayout() ImRect OuterRect; // Note: for non-scrolling table, OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). - ImRect InnerRect; // InnerRect but without decoration. As with OuterRect, for non-scrolling tables, InnerRect.Max.y is + ImRect InnerRect; // InnerRect but without decoration. As with OuterRect, for non-scrolling tables, InnerRect.Max.y is " ImRect WorkRect; ImRect InnerClipRect; ImRect BgClipRect; // We use this to cpu-clip cell background color fill, evolve during the frame as we cross frozen rows boundaries diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 6c7926236..bc5862ee3 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -977,7 +977,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // [Part 4] Apply final widths based on requested widths const ImRect work_rect = table->WorkRect; const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1); - const float width_removed = (table->HasScrollbarYPrev && !table->InnerWindow->ScrollbarY) ? g.Style.ScrollbarSize : 0.0f; // To synchronize decoration width of synched tables with mismatching scrollbar state (#5920) + const float width_removed = (table->HasScrollbarYPrev && !table->InnerWindow->ScrollbarY) ? g.Style.ScrollbarSize : 0.0f; // To synchronize decoration width of synced tables with mismatching scrollbar state (#5920) const float width_avail = ImMax(1.0f, (((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth()) - width_removed); const float width_avail_for_stretched_columns = width_avail - width_spacings - sum_width_requests; float width_remaining_for_stretched_columns = width_avail_for_stretched_columns; @@ -1390,7 +1390,7 @@ void ImGui::EndTable() // Setup inner scrolling range // FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y, - // but since the later is likely to be impossible to do we'd rather update both axises together. + // 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 outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 01e4e6187..9ecdbae8e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8898,7 +8898,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_NoAutoClosePopups; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { - // Menu inside an horizontal menu bar + // Menu inside a horizontal menu bar // Selectable extend their highlight by half ItemSpacing in each direction. // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin() popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight); From 88d4827b64f0453284252b2af344d770fb52da36 Mon Sep 17 00:00:00 2001 From: Zijie Wu Date: Sun, 9 Mar 2025 13:44:26 -0700 Subject: [PATCH 0760/2359] Update FAQ.md for SDL3 (#8480) --- docs/FAQ.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 5af2e9035..8c08b4dd7 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -562,7 +562,8 @@ Please note that if you are not using multi-viewports with multi-monitors using On Windows, in addition to scaling the font size (make sure to round to an integer) and using `style.ScaleAllSizes()`, you will need to inform Windows that your application is DPI aware. If this is not done, Windows will scale the application window and the UI text will be blurry. Potential solutions to indicate DPI awareness on Windows are: -- For SDL: the flag `SDL_WINDOW_ALLOW_HIGHDPI` needs to be passed to `SDL_CreateWindow()``. +- For SDL2: the flag `SDL_WINDOW_ALLOW_HIGHDPI` needs to be passed to `SDL_CreateWindow()`. +- For SDL3: the flag `SDL_WINDOW_HIGH_PIXEL_DENSITY` needs to be passed to `SDL_CreateWindow()`. - For GLFW: this is done automatically. - For other Windows projects with other backends, or wrapper projects: - We provide a `ImGui_ImplWin32_EnableDpiAwareness()` helper method in the Win32 backend. From a9e53829d2753b6eb3ef763e091f430ab507c722 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Mar 2025 16:29:59 +0100 Subject: [PATCH 0761/2359] Backends: Win32, SDL2, SDL3, GLFW: prioritize scancodes instead of translated keycodes when dealing with OEM keys + Added ImGuiKey_Oem102. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) --- backends/imgui_impl_glfw.cpp | 3 +++ backends/imgui_impl_sdl2.cpp | 34 ++++++++++++++++++++------- backends/imgui_impl_sdl3.cpp | 34 ++++++++++++++++++++------- backends/imgui_impl_win32.cpp | 43 +++++++++++++++++++++++++++-------- docs/CHANGELOG.txt | 12 ++++++++++ imgui.cpp | 4 ++-- imgui.h | 5 ++-- 7 files changed, 105 insertions(+), 30 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 874a0a440..baa8541b0 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -28,6 +28,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-03-10: Map GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 into ImGuiKey_Oem102. // 2025-03-03: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. // 2024-08-22: Moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn @@ -221,6 +222,8 @@ ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode) case GLFW_KEY_EQUAL: return ImGuiKey_Equal; case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket; case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash; + case GLFW_KEY_WORLD_1: return ImGuiKey_Oem102; + case GLFW_KEY_WORLD_2: return ImGuiKey_Oem102; case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket; case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent; case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock; diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 6256b4ddd..33f7fed06 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. @@ -209,17 +210,17 @@ ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode sca case SDLK_SPACE: return ImGuiKey_Space; case SDLK_RETURN: return ImGuiKey_Enter; case SDLK_ESCAPE: return ImGuiKey_Escape; - case SDLK_QUOTE: return ImGuiKey_Apostrophe; + //case SDLK_QUOTE: return ImGuiKey_Apostrophe; case SDLK_COMMA: return ImGuiKey_Comma; - case SDLK_MINUS: return ImGuiKey_Minus; + //case SDLK_MINUS: return ImGuiKey_Minus; case SDLK_PERIOD: return ImGuiKey_Period; - case SDLK_SLASH: return ImGuiKey_Slash; + //case SDLK_SLASH: return ImGuiKey_Slash; case SDLK_SEMICOLON: return ImGuiKey_Semicolon; - case SDLK_EQUALS: return ImGuiKey_Equal; - case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; - case SDLK_BACKSLASH: return ImGuiKey_Backslash; - case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; - case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent; + //case SDLK_EQUALS: return ImGuiKey_Equal; + //case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; + //case SDLK_BACKSLASH: return ImGuiKey_Backslash; + //case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; + //case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent; case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; @@ -315,6 +316,23 @@ ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode sca case SDLK_AC_FORWARD: return ImGuiKey_AppForward; default: break; } + + // Fallback to scancode + switch (scancode) + { + case SDL_SCANCODE_GRAVE: return ImGuiKey_GraveAccent; + case SDL_SCANCODE_MINUS: return ImGuiKey_Minus; + case SDL_SCANCODE_EQUALS: return ImGuiKey_Equal; + case SDL_SCANCODE_LEFTBRACKET: return ImGuiKey_LeftBracket; + case SDL_SCANCODE_RIGHTBRACKET: return ImGuiKey_RightBracket; + case SDL_SCANCODE_NONUSBACKSLASH: return ImGuiKey_Oem102; + case SDL_SCANCODE_BACKSLASH: return ImGuiKey_Backslash; + case SDL_SCANCODE_SEMICOLON: return ImGuiKey_Semicolon; + case SDL_SCANCODE_APOSTROPHE: return ImGuiKey_Apostrophe; + case SDL_SCANCODE_COMMA: return ImGuiKey_Comma; + case SDL_SCANCODE_PERIOD: return ImGuiKey_Period; + case SDL_SCANCODE_SLASH: return ImGuiKey_Slash; + } return ImGuiKey_None; } diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 2d8027184..6720899ef 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. @@ -207,17 +208,17 @@ ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode sca case SDLK_SPACE: return ImGuiKey_Space; case SDLK_RETURN: return ImGuiKey_Enter; case SDLK_ESCAPE: return ImGuiKey_Escape; - case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe; + //case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe; case SDLK_COMMA: return ImGuiKey_Comma; - case SDLK_MINUS: return ImGuiKey_Minus; + //case SDLK_MINUS: return ImGuiKey_Minus; case SDLK_PERIOD: return ImGuiKey_Period; - case SDLK_SLASH: return ImGuiKey_Slash; + //case SDLK_SLASH: return ImGuiKey_Slash; case SDLK_SEMICOLON: return ImGuiKey_Semicolon; - case SDLK_EQUALS: return ImGuiKey_Equal; - case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; - case SDLK_BACKSLASH: return ImGuiKey_Backslash; - case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; - case SDLK_GRAVE: return ImGuiKey_GraveAccent; + //case SDLK_EQUALS: return ImGuiKey_Equal; + //case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; + //case SDLK_BACKSLASH: return ImGuiKey_Backslash; + //case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; + //case SDLK_GRAVE: return ImGuiKey_GraveAccent; case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; @@ -296,6 +297,23 @@ ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode sca case SDLK_AC_FORWARD: return ImGuiKey_AppForward; default: break; } + + // Fallback to scancode + switch (scancode) + { + case SDL_SCANCODE_GRAVE: return ImGuiKey_GraveAccent; + case SDL_SCANCODE_MINUS: return ImGuiKey_Minus; + case SDL_SCANCODE_EQUALS: return ImGuiKey_Equal; + case SDL_SCANCODE_LEFTBRACKET: return ImGuiKey_LeftBracket; + case SDL_SCANCODE_RIGHTBRACKET: return ImGuiKey_RightBracket; + case SDL_SCANCODE_NONUSBACKSLASH: return ImGuiKey_Oem102; + case SDL_SCANCODE_BACKSLASH: return ImGuiKey_Backslash; + case SDL_SCANCODE_SEMICOLON: return ImGuiKey_Semicolon; + case SDL_SCANCODE_APOSTROPHE: return ImGuiKey_Apostrophe; + case SDL_SCANCODE_COMMA: return ImGuiKey_Comma; + case SDL_SCANCODE_PERIOD: return ImGuiKey_Period; + case SDL_SCANCODE_SLASH: return ImGuiKey_Slash; + } return ImGuiKey_None; } diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 49948c529..2c749515d 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. @@ -431,6 +432,8 @@ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam) if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED)) return ImGuiKey_KeypadEnter; + const int scancode = (int)LOBYTE(HIWORD(lParam)); + //IMGUI_DEBUG_LOG("scancode %3d, keycode = 0x%02X\n", scancode, wParam); switch (wParam) { case VK_TAB: return ImGuiKey_Tab; @@ -448,17 +451,17 @@ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam) case VK_SPACE: return ImGuiKey_Space; case VK_RETURN: return ImGuiKey_Enter; case VK_ESCAPE: return ImGuiKey_Escape; - case VK_OEM_7: return ImGuiKey_Apostrophe; + //case VK_OEM_7: return ImGuiKey_Apostrophe; case VK_OEM_COMMA: return ImGuiKey_Comma; - case VK_OEM_MINUS: return ImGuiKey_Minus; + //case VK_OEM_MINUS: return ImGuiKey_Minus; case VK_OEM_PERIOD: return ImGuiKey_Period; - case VK_OEM_2: return ImGuiKey_Slash; - case VK_OEM_1: return ImGuiKey_Semicolon; - case VK_OEM_PLUS: return ImGuiKey_Equal; - case VK_OEM_4: return ImGuiKey_LeftBracket; - case VK_OEM_5: return ImGuiKey_Backslash; - case VK_OEM_6: return ImGuiKey_RightBracket; - case VK_OEM_3: return ImGuiKey_GraveAccent; + //case VK_OEM_2: return ImGuiKey_Slash; + //case VK_OEM_1: return ImGuiKey_Semicolon; + //case VK_OEM_PLUS: return ImGuiKey_Equal; + //case VK_OEM_4: return ImGuiKey_LeftBracket; + //case VK_OEM_5: return ImGuiKey_Backslash; + //case VK_OEM_6: return ImGuiKey_RightBracket; + //case VK_OEM_3: return ImGuiKey_GraveAccent; case VK_CAPITAL: return ImGuiKey_CapsLock; case VK_SCROLL: return ImGuiKey_ScrollLock; case VK_NUMLOCK: return ImGuiKey_NumLock; @@ -550,8 +553,28 @@ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam) case VK_F24: return ImGuiKey_F24; case VK_BROWSER_BACK: return ImGuiKey_AppBack; case VK_BROWSER_FORWARD: return ImGuiKey_AppForward; - default: return ImGuiKey_None; + default: break; } + + // Fallback to scancode + // https://handmade.network/forums/t/2011-keyboard_inputs_-_scancodes,_raw_input,_text_input,_key_names + switch (scancode) + { + case 41: return ImGuiKey_GraveAccent; // VK_OEM_8 in EN-UK, VK_OEM_3 in EN-US, VK_OEM_7 in FR, VK_OEM_5 in DE, etc. + case 12: return ImGuiKey_Minus; + case 13: return ImGuiKey_Equal; + case 26: return ImGuiKey_LeftBracket; + case 27: return ImGuiKey_RightBracket; + case 86: return ImGuiKey_Oem102; + case 43: return ImGuiKey_Backslash; + case 39: return ImGuiKey_Semicolon; + case 40: return ImGuiKey_Apostrophe; + case 51: return ImGuiKey_Comma; + case 52: return ImGuiKey_Period; + case 53: return ImGuiKey_Slash; + } + + return ImGuiKey_None; } // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ca5ab47e3..07a9801bc 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -121,6 +121,18 @@ Other changes: by showing the filter inside the combo contents. (#718) - Examples: SDL3: Added comments to clarify setup for users of the unfortunate SDL_MAIN_USE_CALLBACKS feature. (#8455) +- IO: Added ImGuiKey_Oem102 to ImGuiKey enum. (#7136, #7201, #7206, #7306, #8468) +- Backends: reworked key handlers to use/prioritize untranslated scancodes instead of + translated keycodes when dealing with OEM keys. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) + Not that only ImGuiKey value (NOT the characters used for text input) are affected. + - Win32, SDL2, SDL3: Use scancodes for OEM keys. + - GLFW: GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 are emitting ImGuiKey_Oem102. + - Fixes many cases of keys not emitting a ImGuiKey value with certain keyboad layouts. + - Makes emitted ImGuiKey values more consistent regardless of keyboard mapping. + - OEM keys are: ImGuiKey_Apostrophe, ImGuiKey_Comma, ImGuiKey_Minus, ImGuiKey_Period, + ImGuiKey_Slash, ImGuiKey_Semicolon, ImGuiKey_Equal, ImGuiKey_LeftBracket, + ImGuiKey_RightBracket, ImGuiKey_Backslash, ImGuiKey_GraveAccent, which are difficult + to find a reliable translated mapping on all keyboard layouts. - Backends: GLFW: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. (#8452) - Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn diff --git a/imgui.cpp b/imgui.cpp index 86b0d5d46..26d055dd2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8772,7 +8772,7 @@ ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key) return &g.IO.KeysData[key - ImGuiKey_NamedKey_BEGIN]; } -// Those names a provided for debugging purpose and are not meant to be saved persistently not compared. +// Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. static const char* const GKeyNames[] = { "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown", @@ -8787,7 +8787,7 @@ static const char* const GKeyNames[] = "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6", "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply", "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual", - "AppBack", "AppForward", + "AppBack", "AppForward", "Oem102", "GamepadStart", "GamepadBack", "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown", "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown", diff --git a/imgui.h b/imgui.h index 4a14c82c2..7cecf064a 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.9 WIP" -#define IMGUI_VERSION_NUM 19187 +#define IMGUI_VERSION_NUM 19188 #define IMGUI_HAS_TABLE /* @@ -975,7 +975,7 @@ namespace ImGui IMGUI_API bool IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)? IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord); // was key chord (mods + key) pressed, e.g. you can pass 'ImGuiMod_Ctrl | ImGuiKey_S' as a key-chord. This doesn't do any routing or focus check, please consider using Shortcut() function instead. IMGUI_API int GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate - IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names a provided for debugging purpose and are not meant to be saved persistently not compared. + IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. IMGUI_API void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call. // Inputs Utilities: Shortcut Testing & Routing [BETA] @@ -1493,6 +1493,7 @@ enum ImGuiKey : int ImGuiKey_KeypadEqual, ImGuiKey_AppBack, // Available on some keyboard/mouses. Often referred as "Browser Back" ImGuiKey_AppForward, + ImGuiKey_Oem102, // Non-US backslash. // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) From 39585aa90d43c26a12a0d754d16b407f0c1ca62d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Mar 2025 18:13:45 +0100 Subject: [PATCH 0762/2359] Amend Changelog to talk about OEM keys. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) + more consistently use Ctrl+XXX instead of Ctrl-XXX. --- docs/CHANGELOG.txt | 20 +++++++++++--------- imgui.h | 2 +- imgui_widgets.cpp | 6 +++--- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 07a9801bc..5975e9155 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -123,16 +123,18 @@ Other changes: SDL_MAIN_USE_CALLBACKS feature. (#8455) - IO: Added ImGuiKey_Oem102 to ImGuiKey enum. (#7136, #7201, #7206, #7306, #8468) - Backends: reworked key handlers to use/prioritize untranslated scancodes instead of - translated keycodes when dealing with OEM keys. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) - Not that only ImGuiKey value (NOT the characters used for text input) are affected. + translated keycodes when dealing with OEM keys which are too difficult to find a reliable + translated mapping on all systems, backends and keyboard layout. + (#7136, #7201, #7206, #7306, #7670, #7672, #8468) + - The affected keys are: ImGuiKey_Apostrophe, ImGuiKey_Comma, ImGuiKey_Minus, ImGuiKey_Period, + ImGuiKey_Slash, ImGuiKey_Semicolon, ImGuiKey_Equal, ImGuiKey_LeftBracket, ImGuiKey_RightBracket, + ImGuiKey_Backslash, ImGuiKey_GraveAccent, and newly introduced ImGuiKey_Oem102. + - This is NOT affecting characters used the text inputs. + - Fixes many cases of keys not emitting a ImGuiKey value with certain keyboad layouts. + - Makes emitted ImGuiKey values more consistent regardless of keyboard mapping, + but you may be getting different values as before. - Win32, SDL2, SDL3: Use scancodes for OEM keys. - GLFW: GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 are emitting ImGuiKey_Oem102. - - Fixes many cases of keys not emitting a ImGuiKey value with certain keyboad layouts. - - Makes emitted ImGuiKey values more consistent regardless of keyboard mapping. - - OEM keys are: ImGuiKey_Apostrophe, ImGuiKey_Comma, ImGuiKey_Minus, ImGuiKey_Period, - ImGuiKey_Slash, ImGuiKey_Semicolon, ImGuiKey_Equal, ImGuiKey_LeftBracket, - ImGuiKey_RightBracket, ImGuiKey_Backslash, ImGuiKey_GraveAccent, which are difficult - to find a reliable translated mapping on all keyboard layouts. - Backends: GLFW: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. (#8452) - Backends: SDL2, SDL3: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn @@ -2061,7 +2063,7 @@ Other changes: - Public API: PushTabStop(false) / PopTabStop() - Internal: PushItemFlag(ImGuiItemFlags_NoTabStop, true); - Internal: Directly pass ImGuiItemFlags_NoTabStop to ItemAdd() for custom widgets. -- Nav: Tabbing/Shift-Tabbing can more reliably be used to step out of an item that is not +- Nav: Tabbing/Shift+Tabbing can more reliably be used to step out of an item that is not tab-stoppable. (#3092, #5759, #787) - Nav: Made Enter key submit the same type of Activation event as Space key, allowing to press buttons with Enter. (#5606) diff --git a/imgui.h b/imgui.h index 7cecf064a..429bb7480 100644 --- a/imgui.h +++ b/imgui.h @@ -2436,7 +2436,7 @@ struct ImGuiIO bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding SHIFT requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system. - bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a ctrl-click that spawned a simulated right click + bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a Ctrl+click that spawned a simulated right click float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) float MouseDownDurationPrev[5]; // Previous time the mouse button has been down float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9ecdbae8e..fef30d273 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2642,7 +2642,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { - // Tabbing or CTRL-clicking on Drag turns it into an InputText + // Tabbing or CTRL+click on Drag turns it into an InputText const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id); const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2 && TestKeyOwner(ImGuiKey_MouseLeft, id)); const bool make_active = (clicked || double_clicked || g.NavActivateId == id); @@ -3246,7 +3246,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { - // Tabbing or CTRL-clicking on Slider turns it into an input box + // Tabbing or CTRL+click on Slider turns it into an input box const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id); const bool make_active = (clicked || g.NavActivateId == id); if (make_active && clicked) @@ -5495,7 +5495,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. +// 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) { ImGuiWindow* window = GetCurrentWindow(); From 51e4cba909e7a442eed3fcb1080c7d757ea031de Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Mar 2025 12:05:23 +0100 Subject: [PATCH 0763/2359] Backends: Fixed zealous warnings. --- backends/imgui_impl_sdl2.cpp | 2 +- backends/imgui_impl_sdl3.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 33f7fed06..0be2f2c6e 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -192,7 +192,6 @@ static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImG ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode); ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode) { - IM_UNUSED(scancode); switch (keycode) { case SDLK_TAB: return ImGuiKey_Tab; @@ -332,6 +331,7 @@ ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode sca case SDL_SCANCODE_COMMA: return ImGuiKey_Comma; case SDL_SCANCODE_PERIOD: return ImGuiKey_Period; case SDL_SCANCODE_SLASH: return ImGuiKey_Slash; + default: break; } return ImGuiKey_None; } diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 6720899ef..cfe8bbd4e 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -313,6 +313,7 @@ ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode sca case SDL_SCANCODE_COMMA: return ImGuiKey_Comma; case SDL_SCANCODE_PERIOD: return ImGuiKey_Period; case SDL_SCANCODE_SLASH: return ImGuiKey_Slash; + default: break; } return ImGuiKey_None; } From 6da230636b4cb64aa8a30c9110c5a52862a5c2c0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Mar 2025 12:20:33 +0100 Subject: [PATCH 0764/2359] Examples: Updated all .vcxproj from VS2015 to VS2019 (toolset v140 to v142), Windows SDK 8.1 to 10. --- docs/CHANGELOG.txt | 6 ++++++ examples/example_allegro5/example_allegro5.vcxproj | 10 +++++----- .../example_glfw_opengl2.vcxproj | 10 +++++----- .../example_glfw_opengl3.vcxproj | 10 +++++----- .../example_glfw_vulkan/example_glfw_vulkan.vcxproj | 10 +++++----- .../example_glut_opengl2.vcxproj | 10 +++++----- .../example_sdl2_directx11.vcxproj | 10 +++++----- .../example_sdl2_opengl2.vcxproj | 10 +++++----- .../example_sdl2_opengl3.vcxproj | 10 +++++----- .../example_sdl2_sdlrenderer2.vcxproj | 12 ++++++------ .../example_sdl2_vulkan/example_sdl2_vulkan.vcxproj | 12 ++++++------ .../example_sdl3_opengl3.vcxproj | 10 +++++----- .../example_sdl3_sdlgpu3.vcxproj | 12 ++++++------ .../example_sdl3_sdlrenderer3.vcxproj | 10 +++++----- .../example_sdl3_vulkan/example_sdl3_vulkan.vcxproj | 10 +++++----- .../example_win32_directx10.vcxproj | 10 +++++----- .../example_win32_directx11.vcxproj | 9 +++++---- .../example_win32_directx12.vcxproj | 10 +++++----- .../example_win32_directx9.vcxproj | 10 +++++----- .../example_win32_opengl3.vcxproj | 10 +++++----- .../example_win32_vulkan.vcxproj | 9 +++++---- 21 files changed, 109 insertions(+), 101 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5975e9155..2a55e2413 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,10 @@ Breaking changes: Other changes: +- This is the last release we are thoroughly testing with VS2015 + Windows SDK 8.1. + Example projects have been transitioned to VS2019 + Windows SDK 10. The library + as of today still compiles and works fine with VS2015, but onward we may break + support more often. - Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), RadioButton(), Selectable(). Regression from 2025/01/13. (#8370) - Windows: Fixed an issue where BeginChild() inside a collapsed Begin() @@ -121,6 +125,8 @@ Other changes: by showing the filter inside the combo contents. (#718) - Examples: SDL3: Added comments to clarify setup for users of the unfortunate SDL_MAIN_USE_CALLBACKS feature. (#8455) +- Examples: Updated all .vcxproj from VS2015 to VS2019 (toolset v140 to v142), + and from Windows SDK 8.1 to Windows SDK 10 ("latest" setting). - IO: Added ImGuiKey_Oem102 to ImGuiKey enum. (#7136, #7201, #7206, #7306, #8468) - Backends: reworked key handlers to use/prioritize untranslated scancodes instead of translated keycodes when dealing with OEM keys which are too difficult to find a reliable diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index 02f6a4741..220095e78 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -21,34 +21,34 @@ {73F235B5-7D31-4FC6-8682-DDC5A097B9C1} example_allegro5 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index 2aa25506e..6d373337c 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -21,34 +21,34 @@ {9CDA7840-B7A5-496D-A527-E95571496D18} example_glfw_opengl2 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 4bd503afe..400007757 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -21,34 +21,34 @@ {4a1fb5ea-22f5-42a8-ab92-1d2df5d47fb9} example_glfw_opengl3 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index a81d328df..d2ff07e9b 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -21,34 +21,34 @@ {57E2DF5A-6FC8-45BB-99DD-91A18C646E80} example_glfw_vulkan - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index c56452b26..5c773c818 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -21,34 +21,34 @@ {F90D0333-5FB1-440D-918D-DD39A1B5187E} example_glut_opengl2 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj b/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj index c23800c9e..5a8daf1bd 100644 --- a/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj +++ b/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj @@ -21,7 +21,7 @@ {9E1987E3-1F19-45CA-B9C9-D31E791836D8} example_sdl2_directx11 - 8.1 + 10.0 example_sdl2_directx11 @@ -29,27 +29,27 @@ Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj b/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj index 036463f96..b033c322f 100644 --- a/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj +++ b/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj @@ -21,34 +21,34 @@ {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} example_sdl2_opengl2 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj b/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj index 6a81c6770..faf5874b3 100644 --- a/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj +++ b/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj @@ -21,34 +21,34 @@ {BBAEB705-1669-40F3-8567-04CF6A991F4C} example_sdl2_opengl3 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj b/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj index cf2c890bb..7d3cd4eb5 100644 --- a/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj +++ b/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj @@ -21,7 +21,7 @@ {0C0B2BEA-311F-473C-9652-87923EF639E3} example_sdl2_sdlrenderer2 - 8.1 + 10.0 example_sdl2_sdlrenderer2 @@ -29,27 +29,27 @@ Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 @@ -184,4 +184,4 @@ - + \ No newline at end of file diff --git a/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj b/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj index bcf99a46c..07a60ac72 100644 --- a/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj +++ b/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj @@ -21,34 +21,34 @@ {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3} example_sdl2_vulkan - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 @@ -187,4 +187,4 @@ - + \ No newline at end of file diff --git a/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj b/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj index 051f87d76..2f14fdf80 100644 --- a/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj +++ b/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj @@ -21,34 +21,34 @@ {84AAA301-84FE-428B-9E3E-817BC8123C0C} example_sdl3_opengl3 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj b/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj index 3d034f52c..01a38f336 100644 --- a/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj +++ b/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj @@ -21,34 +21,34 @@ {c22cb6f8-39a5-4dda-90ed-4aca4e81e1e5} example_sdl3_sdlgpu3 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 @@ -186,4 +186,4 @@ - + \ No newline at end of file diff --git a/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj b/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj index 8b71324cc..4793e537c 100644 --- a/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj +++ b/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj @@ -21,34 +21,34 @@ {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA} example_sdl3_opengl3 - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj b/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj index d48e4aff3..294377784 100644 --- a/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj +++ b/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj @@ -21,34 +21,34 @@ {663A7E89-1E42-4222-921C-177F5B5910DF} example_sdl3_vulkan - 8.1 + 10.0 Application true MultiByte - v140 + v142 Application true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 Application false true MultiByte - v140 + v142 diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index d11aed883..8fe6d10b5 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -21,34 +21,34 @@ {345A953E-A004-4648-B442-DC5F9F11068C} example_win32_directx10 - 8.1 + 10.0 Application true Unicode - v140 + v142 Application true Unicode - v140 + v142 Application false true Unicode - v140 + v142 Application false true Unicode - v140 + v142 diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index bace6a2c8..79cdbaea7 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -21,33 +21,34 @@ {9F316E83-5AE5-4939-A723-305A94F48005} example_win32_directx11 + 10.0 Application true Unicode - v140 + v142 Application true Unicode - v140 + v142 Application false true Unicode - v140 + v142 Application false true Unicode - v140 + v142 diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj b/examples/example_win32_directx12/example_win32_directx12.vcxproj index bb98c4141..c4b81e76f 100644 --- a/examples/example_win32_directx12/example_win32_directx12.vcxproj +++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj @@ -21,34 +21,34 @@ {b4cf9797-519d-4afe-a8f4-5141a6b521d3} example_win32_directx12 - 10.0.20348.0 + 10.0 Application true Unicode - v140 + v142 Application true Unicode - v140 + v142 Application false true Unicode - v140 + v142 Application false true Unicode - v140 + v142 diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index 8c3f99589..346ec1efc 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -21,34 +21,34 @@ {4165A294-21F2-44CA-9B38-E3F935ABADF5} example_win32_directx9 - 8.1 + 10.0 Application true Unicode - v140 + v142 Application true Unicode - v140 + v142 Application false true Unicode - v140 + v142 Application false true Unicode - v140 + v142 diff --git a/examples/example_win32_opengl3/example_win32_opengl3.vcxproj b/examples/example_win32_opengl3/example_win32_opengl3.vcxproj index 98fc38fd3..9848d62c6 100644 --- a/examples/example_win32_opengl3/example_win32_opengl3.vcxproj +++ b/examples/example_win32_opengl3/example_win32_opengl3.vcxproj @@ -21,34 +21,34 @@ {C624E5FF-D4FE-4D35-9164-B8A91864F98E} example_win32_opengl2 - 8.1 + 10.0 Application true Unicode - v140 + v142 Application true Unicode - v140 + v142 Application false true Unicode - v140 + v142 Application false true Unicode - v140 + v142 diff --git a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj index dab8afd4e..604f8a817 100644 --- a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj +++ b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj @@ -21,33 +21,34 @@ {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88} example_win32_directx11 + 10.0 Application true Unicode - v140 + v142 Application true Unicode - v140 + v142 Application false true Unicode - v140 + v142 Application false true Unicode - v140 + v142 From 557c77e4556a776058c099881f4b32d5416b27c6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Mar 2025 18:38:45 +0100 Subject: [PATCH 0765/2359] Added ImGuiKey_AbntC1, ImGuiKey_AbntC2 + Backends: GLFW, Win32: added support. (#8468) --- backends/imgui_impl_glfw.cpp | 12 +++++++++--- backends/imgui_impl_win32.cpp | 6 ++++-- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 2 +- imgui.h | 2 ++ 5 files changed, 19 insertions(+), 7 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index baa8541b0..d46294932 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -28,7 +28,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-03-10: Map GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 into ImGuiKey_Oem102. +// 2025-03-11: Added support for ImGuiKey_Oem102, ImGuiKey_AbntC1, ImGuiKey_AbntC2. // 2025-03-03: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. // 2024-08-22: Moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn @@ -195,7 +195,6 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode); ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode) { - IM_UNUSED(scancode); switch (keycode) { case GLFW_KEY_TAB: return ImGuiKey_Tab; @@ -317,8 +316,15 @@ ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode) case GLFW_KEY_F22: return ImGuiKey_F22; case GLFW_KEY_F23: return ImGuiKey_F23; case GLFW_KEY_F24: return ImGuiKey_F24; - default: return ImGuiKey_None; + default: break; } + switch (scancode) + { + case 115: return ImGuiKey_AbntC1; + case 126: return ImGuiKey_AbntC2; + default: break; + } + return ImGuiKey_None; } // X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 2c749515d..da007c1d8 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,7 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) +// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) + Added support for ImGuiKey_Oem102, ImGuiKey_AbntC1, ImGuiKey_AbntC2. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. @@ -565,13 +565,15 @@ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam) case 13: return ImGuiKey_Equal; case 26: return ImGuiKey_LeftBracket; case 27: return ImGuiKey_RightBracket; - case 86: return ImGuiKey_Oem102; case 43: return ImGuiKey_Backslash; case 39: return ImGuiKey_Semicolon; case 40: return ImGuiKey_Apostrophe; case 51: return ImGuiKey_Comma; case 52: return ImGuiKey_Period; case 53: return ImGuiKey_Slash; + case 86: return ImGuiKey_Oem102; + case 115: return ImGuiKey_AbntC1; + case 126: return ImGuiKey_AbntC2; } return ImGuiKey_None; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2a55e2413..f5ce04a88 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -128,6 +128,7 @@ Other changes: - Examples: Updated all .vcxproj from VS2015 to VS2019 (toolset v140 to v142), and from Windows SDK 8.1 to Windows SDK 10 ("latest" setting). - IO: Added ImGuiKey_Oem102 to ImGuiKey enum. (#7136, #7201, #7206, #7306, #8468) +- IO: Added ImGuiKey_AbntC1, ImGuiKey_AbntC2 to ImGuiKey enum. (#8468) - Backends: reworked key handlers to use/prioritize untranslated scancodes instead of translated keycodes when dealing with OEM keys which are too difficult to find a reliable translated mapping on all systems, backends and keyboard layout. @@ -139,7 +140,8 @@ Other changes: - Fixes many cases of keys not emitting a ImGuiKey value with certain keyboad layouts. - Makes emitted ImGuiKey values more consistent regardless of keyboard mapping, but you may be getting different values as before. - - Win32, SDL2, SDL3: Use scancodes for OEM keys. + - Win32: Use scancodes for OEM keys. Added support for the 3 new keys. + - SDL2, SDL3: Use scancodes for OEM keys. Added support for the Oem102 new key. - GLFW: GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 are emitting ImGuiKey_Oem102. - Backends: GLFW: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. (#8452) diff --git a/imgui.cpp b/imgui.cpp index 26d055dd2..ae81cc64a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8787,7 +8787,7 @@ static const char* const GKeyNames[] = "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6", "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply", "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual", - "AppBack", "AppForward", "Oem102", + "AppBack", "AppForward", "Oem102", "AbntC1", "AbntC2", "GamepadStart", "GamepadBack", "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown", "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown", diff --git a/imgui.h b/imgui.h index 429bb7480..512e9a6c7 100644 --- a/imgui.h +++ b/imgui.h @@ -1494,6 +1494,8 @@ enum ImGuiKey : int ImGuiKey_AppBack, // Available on some keyboard/mouses. Often referred as "Browser Back" ImGuiKey_AppForward, ImGuiKey_Oem102, // Non-US backslash. + ImGuiKey_AbntC1, // Brazil ABNT extra keys + ImGuiKey_AbntC2, // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) From 09654f4e8caae1ae2c25f246e007ec0fd97eb6b8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Mar 2025 18:42:12 +0100 Subject: [PATCH 0766/2359] Revert "Examples: Updated all .vcxproj from VS2015 to VS2019 (toolset v140 to v142), Windows SDK 8.1 to 10." This reverts commit 6da230636b4cb64aa8a30c9110c5a52862a5c2c0. --- docs/CHANGELOG.txt | 6 ------ examples/example_allegro5/example_allegro5.vcxproj | 10 +++++----- .../example_glfw_opengl2.vcxproj | 10 +++++----- .../example_glfw_opengl3.vcxproj | 10 +++++----- .../example_glfw_vulkan/example_glfw_vulkan.vcxproj | 10 +++++----- .../example_glut_opengl2.vcxproj | 10 +++++----- .../example_sdl2_directx11.vcxproj | 10 +++++----- .../example_sdl2_opengl2.vcxproj | 10 +++++----- .../example_sdl2_opengl3.vcxproj | 10 +++++----- .../example_sdl2_sdlrenderer2.vcxproj | 12 ++++++------ .../example_sdl2_vulkan/example_sdl2_vulkan.vcxproj | 12 ++++++------ .../example_sdl3_opengl3.vcxproj | 10 +++++----- .../example_sdl3_sdlgpu3.vcxproj | 12 ++++++------ .../example_sdl3_sdlrenderer3.vcxproj | 10 +++++----- .../example_sdl3_vulkan/example_sdl3_vulkan.vcxproj | 10 +++++----- .../example_win32_directx10.vcxproj | 10 +++++----- .../example_win32_directx11.vcxproj | 9 ++++----- .../example_win32_directx12.vcxproj | 10 +++++----- .../example_win32_directx9.vcxproj | 10 +++++----- .../example_win32_opengl3.vcxproj | 10 +++++----- .../example_win32_vulkan.vcxproj | 9 ++++----- 21 files changed, 101 insertions(+), 109 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f5ce04a88..cc5964f07 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,10 +68,6 @@ Breaking changes: Other changes: -- This is the last release we are thoroughly testing with VS2015 + Windows SDK 8.1. - Example projects have been transitioned to VS2019 + Windows SDK 10. The library - as of today still compiles and works fine with VS2015, but onward we may break - support more often. - Fixed IsItemDeactivatedAfterEdit() signal being broken for Checkbox(), RadioButton(), Selectable(). Regression from 2025/01/13. (#8370) - Windows: Fixed an issue where BeginChild() inside a collapsed Begin() @@ -125,8 +121,6 @@ Other changes: by showing the filter inside the combo contents. (#718) - Examples: SDL3: Added comments to clarify setup for users of the unfortunate SDL_MAIN_USE_CALLBACKS feature. (#8455) -- Examples: Updated all .vcxproj from VS2015 to VS2019 (toolset v140 to v142), - and from Windows SDK 8.1 to Windows SDK 10 ("latest" setting). - IO: Added ImGuiKey_Oem102 to ImGuiKey enum. (#7136, #7201, #7206, #7306, #8468) - IO: Added ImGuiKey_AbntC1, ImGuiKey_AbntC2 to ImGuiKey enum. (#8468) - Backends: reworked key handlers to use/prioritize untranslated scancodes instead of diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index 220095e78..02f6a4741 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -21,34 +21,34 @@ {73F235B5-7D31-4FC6-8682-DDC5A097B9C1} example_allegro5 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index 6d373337c..2aa25506e 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -21,34 +21,34 @@ {9CDA7840-B7A5-496D-A527-E95571496D18} example_glfw_opengl2 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 400007757..4bd503afe 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -21,34 +21,34 @@ {4a1fb5ea-22f5-42a8-ab92-1d2df5d47fb9} example_glfw_opengl3 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index d2ff07e9b..a81d328df 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -21,34 +21,34 @@ {57E2DF5A-6FC8-45BB-99DD-91A18C646E80} example_glfw_vulkan - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index 5c773c818..c56452b26 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -21,34 +21,34 @@ {F90D0333-5FB1-440D-918D-DD39A1B5187E} example_glut_opengl2 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj b/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj index 5a8daf1bd..c23800c9e 100644 --- a/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj +++ b/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj @@ -21,7 +21,7 @@ {9E1987E3-1F19-45CA-B9C9-D31E791836D8} example_sdl2_directx11 - 10.0 + 8.1 example_sdl2_directx11 @@ -29,27 +29,27 @@ Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj b/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj index b033c322f..036463f96 100644 --- a/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj +++ b/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj @@ -21,34 +21,34 @@ {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} example_sdl2_opengl2 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj b/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj index faf5874b3..6a81c6770 100644 --- a/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj +++ b/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj @@ -21,34 +21,34 @@ {BBAEB705-1669-40F3-8567-04CF6A991F4C} example_sdl2_opengl3 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj b/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj index 7d3cd4eb5..cf2c890bb 100644 --- a/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj +++ b/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj @@ -21,7 +21,7 @@ {0C0B2BEA-311F-473C-9652-87923EF639E3} example_sdl2_sdlrenderer2 - 10.0 + 8.1 example_sdl2_sdlrenderer2 @@ -29,27 +29,27 @@ Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 @@ -184,4 +184,4 @@ - \ No newline at end of file + diff --git a/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj b/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj index 07a60ac72..bcf99a46c 100644 --- a/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj +++ b/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj @@ -21,34 +21,34 @@ {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3} example_sdl2_vulkan - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 @@ -187,4 +187,4 @@ - \ No newline at end of file + diff --git a/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj b/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj index 2f14fdf80..051f87d76 100644 --- a/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj +++ b/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj @@ -21,34 +21,34 @@ {84AAA301-84FE-428B-9E3E-817BC8123C0C} example_sdl3_opengl3 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj b/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj index 01a38f336..3d034f52c 100644 --- a/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj +++ b/examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj @@ -21,34 +21,34 @@ {c22cb6f8-39a5-4dda-90ed-4aca4e81e1e5} example_sdl3_sdlgpu3 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 @@ -186,4 +186,4 @@ - \ No newline at end of file + diff --git a/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj b/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj index 4793e537c..8b71324cc 100644 --- a/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj +++ b/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj @@ -21,34 +21,34 @@ {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA} example_sdl3_opengl3 - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj b/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj index 294377784..d48e4aff3 100644 --- a/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj +++ b/examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj @@ -21,34 +21,34 @@ {663A7E89-1E42-4222-921C-177F5B5910DF} example_sdl3_vulkan - 10.0 + 8.1 Application true MultiByte - v142 + v140 Application true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 Application false true MultiByte - v142 + v140 diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index 8fe6d10b5..d11aed883 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -21,34 +21,34 @@ {345A953E-A004-4648-B442-DC5F9F11068C} example_win32_directx10 - 10.0 + 8.1 Application true Unicode - v142 + v140 Application true Unicode - v142 + v140 Application false true Unicode - v142 + v140 Application false true Unicode - v142 + v140 diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index 79cdbaea7..bace6a2c8 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -21,34 +21,33 @@ {9F316E83-5AE5-4939-A723-305A94F48005} example_win32_directx11 - 10.0 Application true Unicode - v142 + v140 Application true Unicode - v142 + v140 Application false true Unicode - v142 + v140 Application false true Unicode - v142 + v140 diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj b/examples/example_win32_directx12/example_win32_directx12.vcxproj index c4b81e76f..bb98c4141 100644 --- a/examples/example_win32_directx12/example_win32_directx12.vcxproj +++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj @@ -21,34 +21,34 @@ {b4cf9797-519d-4afe-a8f4-5141a6b521d3} example_win32_directx12 - 10.0 + 10.0.20348.0 Application true Unicode - v142 + v140 Application true Unicode - v142 + v140 Application false true Unicode - v142 + v140 Application false true Unicode - v142 + v140 diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index 346ec1efc..8c3f99589 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -21,34 +21,34 @@ {4165A294-21F2-44CA-9B38-E3F935ABADF5} example_win32_directx9 - 10.0 + 8.1 Application true Unicode - v142 + v140 Application true Unicode - v142 + v140 Application false true Unicode - v142 + v140 Application false true Unicode - v142 + v140 diff --git a/examples/example_win32_opengl3/example_win32_opengl3.vcxproj b/examples/example_win32_opengl3/example_win32_opengl3.vcxproj index 9848d62c6..98fc38fd3 100644 --- a/examples/example_win32_opengl3/example_win32_opengl3.vcxproj +++ b/examples/example_win32_opengl3/example_win32_opengl3.vcxproj @@ -21,34 +21,34 @@ {C624E5FF-D4FE-4D35-9164-B8A91864F98E} example_win32_opengl2 - 10.0 + 8.1 Application true Unicode - v142 + v140 Application true Unicode - v142 + v140 Application false true Unicode - v142 + v140 Application false true Unicode - v142 + v140 diff --git a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj index 604f8a817..dab8afd4e 100644 --- a/examples/example_win32_vulkan/example_win32_vulkan.vcxproj +++ b/examples/example_win32_vulkan/example_win32_vulkan.vcxproj @@ -21,34 +21,33 @@ {0A1E32DF-E0F4-4CCE-B3DC-9644C503BD88} example_win32_directx11 - 10.0 Application true Unicode - v142 + v140 Application true Unicode - v142 + v140 Application false true Unicode - v142 + v140 Application false true Unicode - v142 + v140 From de4f77b0ac9a41fa4a77ffc5d3a2c4a106880068 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Mar 2025 15:47:37 +0100 Subject: [PATCH 0767/2359] Backends: DX12: comment about using SrvDescriptorAllocFn/SrvDescriptorFreeFn. Amend 40b2286d16e92ea017347a62cb91e63f378ff455 --- backends/imgui_impl_dx12.cpp | 2 +- backends/imgui_impl_dx12.h | 2 +- examples/example_win32_directx12/main.cpp | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index e9a2c119c..202bac3b0 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -748,7 +748,7 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle) { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - IM_ASSERT(bd->LegacySingleDescriptorUsed == false); + IM_ASSERT(bd->LegacySingleDescriptorUsed == false && "Only 1 simultaneous texture allowed with legacy ImGui_ImplDX12_Init() signature!"); *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor; *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor; bd->LegacySingleDescriptorUsed = true; diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 736e9f5c2..a79de7b13 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -34,7 +34,7 @@ struct ImGui_ImplDX12_InitInfo void* UserData; // Allocating SRV descriptors for textures is up to the application, so we provide callbacks. - // (current version of the backend will only allocate one descriptor, future versions will need to allocate more) + // (current version of the backend will only allocate one descriptor, from 1.92 the backend will need to allocate more) ID3D12DescriptorHeap* SrvDescriptorHeap; void (*SrvDescriptorAllocFn)(ImGui_ImplDX12_InitInfo* info, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_desc_handle); void (*SrvDescriptorFreeFn)(ImGui_ImplDX12_InitInfo* info, D3D12_CPU_DESCRIPTOR_HANDLE cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE gpu_desc_handle); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index e83ce7dcb..5f6cd51dd 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -154,6 +154,9 @@ int main(int, char**) init_info.SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle) { return g_pd3dSrvDescHeapAlloc.Free(cpu_handle, gpu_handle); }; ImGui_ImplDX12_Init(&init_info); + // Before 1.91.6: our signature was using a single descriptor. From 1.92, specifying SrvDescriptorAllocFn/SrvDescriptorFreeFn will be required to benefit from new features. + //ImGui_ImplDX12_Init(g_pd3dDevice, APP_NUM_FRAMES_IN_FLIGHT, DXGI_FORMAT_R8G8B8A8_UNORM, g_pd3dSrvDescHeap, g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(), g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart()); + // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. From 6e30c4210181aebb6137f6c10fdfc572ea1202f2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Mar 2025 19:29:41 +0100 Subject: [PATCH 0768/2359] Tables: fixed an issue with TableSetupColumn() overriding ini data. (#7934) Amend 05742f9b6f --- imgui_tables.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index bc5862ee3..5464ba688 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1637,7 +1637,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo if (table->IsInitializing) { ImGuiTableFlags init_flags = ~0; - if (column->WidthRequest >= 0.0f && column->StretchWeight >= 0.0f) + if (column->WidthRequest >= 0.0f || column->StretchWeight >= 0.0f) init_flags &= ~ImGuiTableFlags_Resizable; TableInitColumnDefaults(table, column, init_flags); } From d9dad2f4a15aa49c7464b9b3eef2588f14437e22 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 12 Mar 2025 14:15:51 +0100 Subject: [PATCH 0769/2359] Scrollbar: stabilize visibility of ScrollbarX when detecting a feedback loop. (#8488, #3285, #4539) --- docs/CHANGELOG.txt | 8 ++++++++ imgui.cpp | 14 ++++++++++++++ imgui_internal.h | 9 ++++++--- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cc5964f07..bbf9255c3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -82,6 +82,14 @@ Other changes: visibility of the preview/hint buffer. (#8368) [@m9710797, @ocornut] - Scrollbar: Rework logic that fades-out scrollbar when it becomes too small, which amusingly made it disappear when using very big font/frame size. +- Scrollbar: Automatically stabilize ScrollbarX visibility when detecting a + feedback loop manifesting with ScrollbarX visibility toggling on and off + repeatedly. (#8488, #3285, #4539) + (feedback loops of this sort can manifest in various situations, but combining + horizontal + vertical scrollbar + using a clipper with varying width items is + one frequent cause. The better solution is to, either: (1) enforce visibility + by using ImGuiWindowFlags_AlwaysHorizontalScrollbar or (2) declare stable + contents width with SetNextWindowContentSize(), if you can compute it.) - Tables: fixed calling SetNextWindowScroll() on clipped scrolling table to not leak the value into a subsequent window. (#8196) - Tables: fixed an issue where Columns Visible/Width state wouldn't be correctly diff --git a/imgui.cpp b/imgui.cpp index ae81cc64a..093ba6375 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7456,9 +7456,23 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f; float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; + bool scrollbar_x_prev = window->ScrollbarX; //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons? window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + + // Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488) + // (Feedback loops of this sort can manifest in various situations, but combining horizontal + vertical scrollbar + using a clipper with varying width items is one frequent cause. + // The better solution is to, either (1) enforce visibility by using ImGuiWindowFlags_AlwaysHorizontalScrollbar or (2) declare stable contents width with SetNextWindowContentSize(), if you can compute it) + window->ScrollbarXStabilizeToggledHistory <<= 1; + window->ScrollbarXStabilizeToggledHistory |= (scrollbar_x_prev != window->ScrollbarX) ? 0x01 : 0x00; + const bool scrollbar_x_stabilize = (window->ScrollbarXStabilizeToggledHistory != 0) && ImCountSetBits(window->ScrollbarXStabilizeToggledHistory) >= 4; // 4 == half of bits in our U8 history. + if (scrollbar_x_stabilize) + window->ScrollbarX = true; + //if (scrollbar_x_stabilize && !window->ScrollbarXStabilizeEnabled) + // IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window->Name); + window->ScrollbarXStabilizeEnabled = scrollbar_x_stabilize; + if (window->ScrollbarX && !window->ScrollbarY) window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index aaa2027df..6d9120a9e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -367,9 +367,10 @@ static inline void ImQsort(void* base, size_t count, size_t size_of_element IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); // Helpers: Bit manipulation -static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } -static inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } -static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } +static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } +static inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } +static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } +static inline unsigned int ImCountSetBits(unsigned int v) { unsigned int count = 0; while (v > 0) { v = v & (v - 1); count++; } return count; } // Helpers: String #define ImStrlen strlen @@ -2514,6 +2515,8 @@ struct IMGUI_API ImGuiWindow ImVec2 ScrollTargetEdgeSnapDist; // 0.0f = no snapping, >0.0f snapping threshold ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar. bool ScrollbarX, ScrollbarY; // Are scrollbars visible? + bool ScrollbarXStabilizeEnabled; // Was ScrollbarX previously auto-stabilized? + ImU8 ScrollbarXStabilizeToggledHistory; // Used to stabilize scrollbar visibility in case of feedback loops bool Active; // Set to true on Begin(), unless Collapsed bool WasActive; bool WriteAccessed; // Set to true when any widget access the current window From 79bba34c5f453640bf6f4a17741ad2e3e7b5abfe Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Mar 2025 16:32:50 +0100 Subject: [PATCH 0770/2359] Revert "Added ImGuiKey_AbntC1, ImGuiKey_AbntC2 + Backends: GLFW, Win32: added support. (#8468)" This reverts commit 557c77e4556a776058c099881f4b32d5416b27c6. --- backends/imgui_impl_glfw.cpp | 12 +++--------- backends/imgui_impl_win32.cpp | 6 ++---- docs/CHANGELOG.txt | 4 +--- imgui.cpp | 2 +- imgui.h | 2 -- 5 files changed, 7 insertions(+), 19 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index d46294932..baa8541b0 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -28,7 +28,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-03-11: Added support for ImGuiKey_Oem102, ImGuiKey_AbntC1, ImGuiKey_AbntC2. +// 2025-03-10: Map GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 into ImGuiKey_Oem102. // 2025-03-03: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. // 2024-08-22: Moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn @@ -195,6 +195,7 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode); ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode) { + IM_UNUSED(scancode); switch (keycode) { case GLFW_KEY_TAB: return ImGuiKey_Tab; @@ -316,15 +317,8 @@ ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode) case GLFW_KEY_F22: return ImGuiKey_F22; case GLFW_KEY_F23: return ImGuiKey_F23; case GLFW_KEY_F24: return ImGuiKey_F24; - default: break; + default: return ImGuiKey_None; } - switch (scancode) - { - case 115: return ImGuiKey_AbntC1; - case 126: return ImGuiKey_AbntC2; - default: break; - } - return ImGuiKey_None; } // X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index da007c1d8..2c749515d 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,7 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) + Added support for ImGuiKey_Oem102, ImGuiKey_AbntC1, ImGuiKey_AbntC2. +// 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. @@ -565,15 +565,13 @@ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam) case 13: return ImGuiKey_Equal; case 26: return ImGuiKey_LeftBracket; case 27: return ImGuiKey_RightBracket; + case 86: return ImGuiKey_Oem102; case 43: return ImGuiKey_Backslash; case 39: return ImGuiKey_Semicolon; case 40: return ImGuiKey_Apostrophe; case 51: return ImGuiKey_Comma; case 52: return ImGuiKey_Period; case 53: return ImGuiKey_Slash; - case 86: return ImGuiKey_Oem102; - case 115: return ImGuiKey_AbntC1; - case 126: return ImGuiKey_AbntC2; } return ImGuiKey_None; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bbf9255c3..f184ddc8f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -130,7 +130,6 @@ Other changes: - Examples: SDL3: Added comments to clarify setup for users of the unfortunate SDL_MAIN_USE_CALLBACKS feature. (#8455) - IO: Added ImGuiKey_Oem102 to ImGuiKey enum. (#7136, #7201, #7206, #7306, #8468) -- IO: Added ImGuiKey_AbntC1, ImGuiKey_AbntC2 to ImGuiKey enum. (#8468) - Backends: reworked key handlers to use/prioritize untranslated scancodes instead of translated keycodes when dealing with OEM keys which are too difficult to find a reliable translated mapping on all systems, backends and keyboard layout. @@ -142,8 +141,7 @@ Other changes: - Fixes many cases of keys not emitting a ImGuiKey value with certain keyboad layouts. - Makes emitted ImGuiKey values more consistent regardless of keyboard mapping, but you may be getting different values as before. - - Win32: Use scancodes for OEM keys. Added support for the 3 new keys. - - SDL2, SDL3: Use scancodes for OEM keys. Added support for the Oem102 new key. + - Win32, SDL2, SDL3: Use scancodes for OEM keys. - GLFW: GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 are emitting ImGuiKey_Oem102. - Backends: GLFW: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. (#8452) diff --git a/imgui.cpp b/imgui.cpp index 093ba6375..a2d90caed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8801,7 +8801,7 @@ static const char* const GKeyNames[] = "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6", "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply", "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual", - "AppBack", "AppForward", "Oem102", "AbntC1", "AbntC2", + "AppBack", "AppForward", "Oem102", "GamepadStart", "GamepadBack", "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown", "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown", diff --git a/imgui.h b/imgui.h index 512e9a6c7..429bb7480 100644 --- a/imgui.h +++ b/imgui.h @@ -1494,8 +1494,6 @@ enum ImGuiKey : int ImGuiKey_AppBack, // Available on some keyboard/mouses. Often referred as "Browser Back" ImGuiKey_AppForward, ImGuiKey_Oem102, // Non-US backslash. - ImGuiKey_AbntC1, // Brazil ABNT extra keys - ImGuiKey_AbntC2, // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) From b758b8223fc789c8f1962be08ce234aaa4ccd4f4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Mar 2025 19:30:42 +0100 Subject: [PATCH 0771/2359] InputText: Pasting a multi-line buffer into a single-line edit replaces carriage return by spaces. (#8459) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f184ddc8f..8d4f0bec7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,8 @@ Other changes: inner/outer padding applied to hit-testing of windows borders and detection of hovered window. - InputText: Allow CTRL+Shift+Z to redo even outside of OSX. (#8389) [@tanksdude] +- InputText: Pasting a multi-line buffer into a single-line edit replaces + carriage return by spaces. (#8459) - InputTextWithHint(): Fixed buffer-overflow (luckily often with no visible effect) when a user callback modified the buffer contents in a way that altered the visibility of the preview/hint buffer. (#8368) [@m9710797, @ocornut] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fef30d273..602bdb9e1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4294,7 +4294,13 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im if (c < 0x20) { bool pass = false; - pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0; // Note that an Enter KEY will emit \r and be ignored (we poll for KEY in InputText() code) + pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0; // Note that an Enter KEY will emit \r and be ignored (we poll for KEY in InputText() code) + if (c == '\n' && input_source_is_clipboard && (flags & ImGuiInputTextFlags_Multiline) == 0) // In single line mode, replace \n with a space + { + c = *p_char = ' '; + pass = true; + } + pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0; pass |= (c == '\t') && (flags & ImGuiInputTextFlags_AllowTabInput) != 0; if (!pass) return false; From ea2a12112df50975f3582b121c63d65fcdebd330 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 14 Mar 2025 17:13:04 +0100 Subject: [PATCH 0772/2359] Misc: Various zealous warning fixes for newer version of Clang. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 4 +++- imgui_demo.cpp | 2 ++ imgui_draw.cpp | 1 + imgui_tables.cpp | 2 ++ imgui_widgets.cpp | 2 ++ 6 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8d4f0bec7..3c6c4f234 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -124,6 +124,7 @@ Other changes: - Debug Tools: Added io.ConfigDebugHighlightIdConflictsShowItemPicker (defaults to true) to allow disabled Item Picker suggestion in user facing builds. (#7961, #7669) - Debug Tools: Tweaked layout of ID Stack Tool and always display full path. (#4631) +- Misc: Various zealous warning fixes for newer version of Clang. - Misc: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursors (busy/wait/hourglass shape, with or without an arrow cursor). - Demo: Reorganized "Widgets" section to be alphabetically ordered and split in more functions. diff --git a/imgui.cpp b/imgui.cpp index a2d90caed..60340c022 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1145,17 +1145,19 @@ CODE #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#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 "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #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 "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int' #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. #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label #elif defined(__GNUC__) // We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 50eeed107..0423c49f2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -159,6 +159,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code) #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type +#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int' #pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #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. @@ -167,6 +168,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access +#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 "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe diff --git a/imgui_draw.cpp b/imgui_draw.cpp index efdddc8b1..a1111b08f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -68,6 +68,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type #pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier +#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 diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 5464ba688..5cdee0433 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -221,6 +221,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 // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#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 "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 @@ -230,6 +231,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#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 "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 602bdb9e1..880232965 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -70,6 +70,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 // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#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-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. @@ -80,6 +81,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type +#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 "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe From 97428e8ac99e339ce05eee531cf55b77b29ea709 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 14 Mar 2025 16:30:39 +0100 Subject: [PATCH 0773/2359] Version 1.91.9 --- docs/CHANGELOG.txt | 11 +++++++---- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 16 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3c6c4f234..c9a68c7b2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.91.9 WIP (In Progress) + VERSION 1.91.9 (Released 2025-03-14) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.9 + Breaking changes: - Image: removed 'tint_col' and 'border_col' parameter from Image() function. (#8131, #8238) @@ -72,7 +74,7 @@ Other changes: RadioButton(), Selectable(). Regression from 2025/01/13. (#8370) - Windows: Fixed an issue where BeginChild() inside a collapsed Begin() wouldn't inherit the SkipItems flag, resulting in missing coarse clipping - opportunity for code not checking the BeginChild() return value. + opportunities for code not checking the BeginChild() return value. - Windows, Style: Added style.WindowBorderHoverPadding setting to configure inner/outer padding applied to hit-testing of windows borders and detection of hovered window. @@ -141,7 +143,7 @@ Other changes: ImGuiKey_Slash, ImGuiKey_Semicolon, ImGuiKey_Equal, ImGuiKey_LeftBracket, ImGuiKey_RightBracket, ImGuiKey_Backslash, ImGuiKey_GraveAccent, and newly introduced ImGuiKey_Oem102. - This is NOT affecting characters used the text inputs. - - Fixes many cases of keys not emitting a ImGuiKey value with certain keyboad layouts. + - Fixes many cases of keys not emitting a ImGuiKey value with certain keyboard layouts. - Makes emitted ImGuiKey values more consistent regardless of keyboard mapping, but you may be getting different values as before. - Win32, SDL2, SDL3: Use scancodes for OEM keys. @@ -155,7 +157,8 @@ Other changes: - Backends: SDL2, SDL3: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. (#8425, #8407) [@TheMode] - Backends: SDL2, SDL3: Only start SDL_CaptureMouse() when mouse is being dragged, - to mitigate issues with e.g. Linux debuggers not claiming capture back. (#6410, #3650) + to mitigate issues with e.g. Linux debuggers not claiming capture back on debug + break. (#6410, #3650) - Backends: OpenGL3: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) - Backends: DirectX12: Fixed an issue where pre-1.91.5 legacy ImGui_ImplDX12_Init() diff --git a/imgui.cpp b/imgui.cpp index 60340c022..8ec001178 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 WIP +// dear imgui, v1.91.9 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 429bb7480..4ca9c8372 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 WIP +// dear imgui, v1.91.9 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.9 WIP" -#define IMGUI_VERSION_NUM 19188 +#define IMGUI_VERSION "1.91.9" +#define IMGUI_VERSION_NUM 19190 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0423c49f2..ead800f4b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 WIP +// dear imgui, v1.91.9 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a1111b08f..aa0a7feec 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 WIP +// dear imgui, v1.91.9 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 6d9120a9e..6cb9be406 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 WIP +// dear imgui, v1.91.9 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 5cdee0433..e67a83649 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 WIP +// dear imgui, v1.91.9 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 880232965..fc358534e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 WIP +// dear imgui, v1.91.9 // (widgets code) /* From d6493aab028139538c9bcf2141ae02574b12aa75 Mon Sep 17 00:00:00 2001 From: Wizard <74285801+wizard00000@users.noreply.github.com> Date: Sun, 16 Mar 2025 18:56:59 -0400 Subject: [PATCH 0774/2359] Fix typo in comment (#8494) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fc358534e..d671cbbda 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6207,7 +6207,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if (g.Style.FrameBorderSize > 0.0f) RenderFrameBorder(bb.Min, bb.Max, rounding); else - window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border } // Drag and Drop Source From 4d4f1fd364ebb770766a6fd4dd0d17c39865e7b2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 11:50:32 +0100 Subject: [PATCH 0775/2359] Docs: retroactively document ConfigData->Sources renaming. (#8495) Amend 4c0604e --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + 2 files changed, 3 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c9a68c7b2..36ceb7cdb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,8 @@ Breaking changes: - Backends: Vulkan: Added 'uint32_t api_version' argument to ImGui_ImplVulkan_LoadFunctions(). Note that it was also added to ImGui_ImplVulkan_InitInfo but for the later it is optional. (#8326, #8365, #8400) +- Internals: Fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[], +- Internals: Fonts: ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. - Internals: Menus: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. diff --git a/imgui.cpp b/imgui.cpp index 8ec001178..af7ce4ce7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -441,6 +441,7 @@ CODE - old behavior altered border size (and therefore layout) based on border color's alpha, which caused variety of problems + old behavior a fixed 1.0f for border size which was not tweakable. - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified. - added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. It was impossible to add 'bg_col' to Image() with a parameter order consistent with other functions, so we decided to remove 'tint_col' and introduce ImageWithBg(). + - 2025/02/25 (1.91.9) - internals: fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX. - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. From 2737dbb1e1cd206fc874a5ca17ee672a68523182 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 11:51:57 +0100 Subject: [PATCH 0776/2359] Docs: Fixed typo. Very oops. (#8495) --- docs/CHANGELOG.txt | 2 +- imgui.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 36ceb7cdb..e369f1957 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -65,7 +65,7 @@ Breaking changes: Note that it was also added to ImGui_ImplVulkan_InitInfo but for the later it is optional. (#8326, #8365, #8400) - Internals: Fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[], -- Internals: Fonts: ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. +- Internals: Fonts: ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourcesCount. - Internals: Menus: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. diff --git a/imgui.cpp b/imgui.cpp index af7ce4ce7..78774c2b4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -441,7 +441,7 @@ CODE - old behavior altered border size (and therefore layout) based on border color's alpha, which caused variety of problems + old behavior a fixed 1.0f for border size which was not tweakable. - kept legacy signature (will obsolete), which mimics the old behavior, but uses Max(1.0f, style.ImageBorderSize) when border_col is specified. - added ImageWithBg() function which has both 'bg_col' (which was missing) and 'tint_col'. It was impossible to add 'bg_col' to Image() with a parameter order consistent with other functions, so we decided to remove 'tint_col' and introduce ImageWithBg(). - - 2025/02/25 (1.91.9) - internals: fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. + - 2025/02/25 (1.91.9) - internals: fonts: ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourcesCount. - 2025/02/06 (1.91.9) - renamed ImFontConfig::GlyphExtraSpacing.x to ImFontConfig::GlyphExtraAdvanceX. - 2025/01/22 (1.91.8) - removed ImGuiColorEditFlags_AlphaPreview (made value 0): it is now the default behavior. prior to 1.91.8: alpha was made opaque in the preview by default _unless_ using ImGuiColorEditFlags_AlphaPreview. We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. From bfaef8ca1783a26aa7eba766dacf87a85ed13ede Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 19:08:58 +0100 Subject: [PATCH 0777/2359] Version 1.92.0 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e369f1957..62c7c548a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.0 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking changes: + +Other changes: + + ----------------------------------------------------------------------- VERSION 1.91.9 (Released 2025-03-14) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 78774c2b4..932f433fd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 +// dear imgui, v1.92.0 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 4ca9c8372..7bbdf8225 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 +// dear imgui, v1.92.0 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.9" -#define IMGUI_VERSION_NUM 19190 +#define IMGUI_VERSION "1.92.0 WIP" +#define IMGUI_VERSION_NUM 19191 #define IMGUI_HAS_TABLE /* diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ead800f4b..996694268 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 +// dear imgui, v1.92.0 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index aa0a7feec..1404b8d61 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 +// dear imgui, v1.92.0 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 6cb9be406..870360264 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 +// dear imgui, v1.92.0 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e67a83649..0ac6ec896 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 +// dear imgui, v1.92.0 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d671cbbda..0aa121e77 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9 +// dear imgui, v1.92.0 WIP // (widgets code) /* From a7dc1847728171e8940671d8e34a8ecb050f00fa Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 19:07:24 +0100 Subject: [PATCH 0778/2359] Moved ImDrawIdx definition lower in imgui.h. Moved ImTextureID slightly below in its own section. --- imgui.h | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/imgui.h b/imgui.h index 7bbdf8225..0db50aec1 100644 --- a/imgui.h +++ b/imgui.h @@ -37,6 +37,7 @@ Index of this file: // [SECTION] Header mess // [SECTION] Forward declarations and basic types +// [SECTION] Texture identifier (ImTextureID) // [SECTION] Dear ImGui end-user API functions // [SECTION] Flags & Enumerations // [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) @@ -250,22 +251,6 @@ typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: f typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() -// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type] -// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. -// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. -// - You can make this a structure with various constructors if you need. You will have to implement ==/!= operators. -// - (note: before v1.91.4 (2024/10/08) the default type for ImTextureID was void*. Use intermediary intptr_t cast and read FAQ if you have casting warnings) -#ifndef ImTextureID -typedef ImU64 ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) -#endif - -// ImDrawIdx: vertex index. [Compile-time configurable type] -// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). -// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. -#ifndef ImDrawIdx -typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends) -#endif - // Character types // (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display) typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings. @@ -315,6 +300,19 @@ struct ImVec4 }; IM_MSVC_RUNTIME_CHECKS_RESTORE +//----------------------------------------------------------------------------- +// [SECTION] Texture identifier (ImTextureID) +//----------------------------------------------------------------------------- + +// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type] +// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. +// - You can make this a structure with various constructors if you need. You will have to implement ==/!= operators. +// - (note: before v1.91.4 (2024/10/08) the default type for ImTextureID was void*. Use intermediary intptr_t cast and read FAQ if you have casting warnings) +#ifndef ImTextureID +typedef ImU64 ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) +#endif + //----------------------------------------------------------------------------- // [SECTION] Dear ImGui end-user API functions // (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) @@ -2957,6 +2955,13 @@ struct ImGuiSelectionExternalStorage #define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) #endif +// ImDrawIdx: vertex index. [Compile-time configurable type] +// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). +// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends) +#endif + // ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] // NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, // you can poke into the draw list for that! Draw callback may be useful for example to: From 93b446a96281ceec9b226ef624cdc428efd44c60 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 19:39:52 +0100 Subject: [PATCH 0779/2359] Backtrack of version tagging 1.92.0 > 1.91.9b for publishing a hotfix (#8496) --- docs/CHANGELOG.txt | 2 +- imgui.cpp | 2 +- imgui.h | 4 ++-- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 62c7c548a..a2a55e1f2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,7 +36,7 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.0 WIP (In Progress) + VERSION 1.91.9b WIP (In Progress) ----------------------------------------------------------------------- Breaking changes: diff --git a/imgui.cpp b/imgui.cpp index 932f433fd..7ec192278 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.91.9b // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 0db50aec1..75750ae10 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.91.9b // (headers) // Help: @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.0 WIP" +#define IMGUI_VERSION "1.91.9b" #define IMGUI_VERSION_NUM 19191 #define IMGUI_HAS_TABLE diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 996694268..10fa434dc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.91.9b // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1404b8d61..273101529 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.91.9b // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 870360264..ddf9ea3e9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.91.9b // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0ac6ec896..74eec5797 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.91b // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0aa121e77..c997e17b6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.91b // (widgets code) /* From cfed7a3a5446cd6b36a161d02e89fc816deab69b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 19:51:46 +0100 Subject: [PATCH 0780/2359] Tables: fixed assert/issues loading settings. (#8496, #7934) Not sure what I did with 05742f9b6ff but I missed on the primary filter. --- docs/CHANGELOG.txt | 4 ++++ imgui_tables.cpp | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a2a55e1f2..d32fa1c43 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,10 @@ Breaking changes: Other changes: +- Tables: Fixed assert when loading .ini settings of reordered columns. (#8496, #7934) +- Tables: Fixed issues when loading .ini settings for a table with columns using + ImGuiTableColumnFlags_DefaultHide or ImGuiTableColumnFlags_DefaultSort. (#8496, #7934) + ----------------------------------------------------------------------- VERSION 1.91.9 (Released 2025-03-14) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 74eec5797..c98aea2d1 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1638,9 +1638,9 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo column->InitStretchWeightOrWidth = init_width_or_weight; if (table->IsInitializing) { - ImGuiTableFlags init_flags = ~0; - if (column->WidthRequest >= 0.0f || column->StretchWeight >= 0.0f) - init_flags &= ~ImGuiTableFlags_Resizable; + ImGuiTableFlags init_flags = ~table->SettingsLoadedFlags; + if (column->WidthRequest < 0.0f && column->StretchWeight < 0.0f) + init_flags |= ImGuiTableFlags_Resizable; TableInitColumnDefaults(table, column, init_flags); } From f5befd2d29e66809cd1110a152e375a7f1981f06 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 20:17:26 +0100 Subject: [PATCH 0781/2359] Version 1.91.9b --- docs/CHANGELOG.txt | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d32fa1c43..db1fb0cea 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,14 +36,12 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.91.9b WIP (In Progress) + VERSION 1.91.9b (Released 2025-03-17) ----------------------------------------------------------------------- -Breaking changes: +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.91.9b -Other changes: - -- Tables: Fixed assert when loading .ini settings of reordered columns. (#8496, #7934) +- Tables: Fixed assert when loading .ini settings with reordered columns. (#8496, #7934) - Tables: Fixed issues when loading .ini settings for a table with columns using ImGuiTableColumnFlags_DefaultHide or ImGuiTableColumnFlags_DefaultSort. (#8496, #7934) From 5679de60c567fc62c091004ee80a738757e6d3b6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Mar 2025 17:35:43 +0100 Subject: [PATCH 0782/2359] Error Handling: added better report and recovery for extraneous EndPopup() call. (#1651, #8499) --- docs/CHANGELOG.txt | 12 ++++++++++++ imgui.cpp | 7 +++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index db1fb0cea..17327ee24 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,18 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.0 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking changes: + +Other changes: + +- Error Handling: added better error report and recovery for extraneous + EndPopup() call. (#1651, #8499) + + ----------------------------------------------------------------------- VERSION 1.91.9b (Released 2025-03-17) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 7ec192278..3b9d25e54 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11818,8 +11818,11 @@ void ImGui::EndPopup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls - IM_ASSERT(g.BeginPopupStack.Size > 0); + if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0) + { + IM_ASSERT_USER_ERROR(0, "Calling EndPopup() too many times or in wrong window!"); + return; + } // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests) if (g.NavWindow == window) From ee48ffe0215fa639254372f303d4539ef047f7c8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Mar 2025 17:42:19 +0100 Subject: [PATCH 0783/2359] Added comments about line/rect thickness needing scaling. (#7031) --- imgui.cpp | 4 ++-- imgui_widgets.cpp | 19 ++++++++++--------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3b9d25e54..b8ffe463f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5617,7 +5617,7 @@ static void ImGui::RenderDimmedBackgrounds() if (window->DrawList->CmdBuffer.Size == 0) window->DrawList->AddDrawCmd(); window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size); - window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); // FIXME-DPI window->DrawList->PopClipRect(); } } @@ -14307,7 +14307,7 @@ void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_r bool push_clip_rect = !window->ClipRect.Contains(bb_display); if (push_clip_rect) window->DrawList->PushClipRectFullScreen(); - window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); + window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); // FIXME-DPI if (push_clip_rect) window->DrawList->PopClipRect(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c997e17b6..1eea8cb50 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -867,11 +867,12 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) if (hovered) window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact); - ImU32 cross_col = GetColorU32(ImGuiCol_Text); - ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f); - float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; - window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); - window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); + const ImU32 cross_col = GetColorU32(ImGuiCol_Text); + const ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f); + const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; + const float cross_thickness = 1.0f; // FIXME-DPI + window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness); + window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, cross_thickness); return pressed; } @@ -1478,7 +1479,7 @@ bool ImGui::TextLink(const char* label) } float line_y = bb.Max.y + ImFloor(g.Font->Descent * g.FontScale * 0.20f); - window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode. + window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode // FIXME-DPI PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); RenderText(bb.Min, label, label_end); @@ -5339,7 +5340,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) - draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text), 1.0f); // FIXME-DPI: Cursor thickness (#7031) + Color // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) if (!is_readonly) @@ -6207,7 +6208,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if (g.Style.FrameBorderSize > 0.0f) RenderFrameBorder(bb.Min, bb.Max, rounding); else - window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border // FIXME-DPI } // Drag and Drop Source @@ -7486,7 +7487,7 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flag ImRect box_select_r = bs->BoxSelectRectCurr; box_select_r.ClipWith(scope_rect); window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling - window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT: Styling + window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT FIXME-DPI: Styling // Scroll const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0; From 0ecb2bbe74b8e86e9f1acf4a0a7a508d0b8b9b52 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Mar 2025 17:45:20 +0100 Subject: [PATCH 0784/2359] Version 1.92.0 WIP --- docs/CHANGELOG.txt | 2 +- imgui.cpp | 2 +- imgui.h | 4 ++-- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 17327ee24..5ebedf819 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,7 +43,7 @@ Breaking changes: Other changes: -- Error Handling: added better error report and recovery for extraneous +- Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) diff --git a/imgui.cpp b/imgui.cpp index b8ffe463f..3918f6433 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.0 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 75750ae10..0db50aec1 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.0 WIP // (headers) // Help: @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.9b" +#define IMGUI_VERSION "1.92.0 WIP" #define IMGUI_VERSION_NUM 19191 #define IMGUI_HAS_TABLE diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 10fa434dc..996694268 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.0 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 273101529..1404b8d61 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.0 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index ddf9ea3e9..870360264 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.0 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index c98aea2d1..0954784bb 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91b +// dear imgui, v1.92.0 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1eea8cb50..eb805640a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91b +// dear imgui, v1.92.0 WIP // (widgets code) /* From d467950a5e167e06abc278803fa230e3461fce09 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Mar 2025 17:50:40 +0100 Subject: [PATCH 0785/2359] Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui.h | 1 + imgui_draw.cpp | 3 +++ imgui_widgets.cpp | 2 +- 5 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5ebedf819..1a668bf73 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,8 @@ Other changes: - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) +- Style, InputText: added ImGuiCol_InputTextCursor to configure color of + the InputText cursor/caret. (#7031) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 3918f6433..b0e197590 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3544,6 +3544,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; + case ImGuiCol_InputTextCursor: return "InputTextCursor"; case ImGuiCol_TabHovered: return "TabHovered"; case ImGuiCol_Tab: return "Tab"; case ImGuiCol_TabSelected: return "TabSelected"; diff --git a/imgui.h b/imgui.h index 0db50aec1..a45348ad3 100644 --- a/imgui.h +++ b/imgui.h @@ -1648,6 +1648,7 @@ enum ImGuiCol_ ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows. ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, + ImGuiCol_InputTextCursor, // InputText cursor/caret ImGuiCol_TabHovered, // Tab background, when hovered ImGuiCol_Tab, // Tab background, when tab-bar is focused & tab is unselected ImGuiCol_TabSelected, // Tab background, when tab-bar is focused & tab is selected diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1404b8d61..67dfbdecc 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -217,6 +217,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); @@ -280,6 +281,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); @@ -344,6 +346,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(0.35f, 0.35f, 0.35f, 0.17f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index eb805640a..df12c0066 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5340,7 +5340,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) - draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text), 1.0f); // FIXME-DPI: Cursor thickness (#7031) + Color + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031) // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) if (!is_readonly) From 979c7d76abdddc086cb1a21e4d36fff6bebd5a17 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Mar 2025 15:42:47 +0100 Subject: [PATCH 0786/2359] Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) --- backends/imgui_impl_android.cpp | 2 +- backends/imgui_impl_android.h | 2 +- backends/imgui_impl_glfw.cpp | 2 +- backends/imgui_impl_osx.h | 2 +- backends/imgui_impl_osx.mm | 5 ++--- backends/imgui_impl_sdl2.cpp | 6 ++---- backends/imgui_impl_sdl2.h | 2 +- backends/imgui_impl_sdl3.cpp | 6 ++---- backends/imgui_impl_sdl3.h | 2 +- backends/imgui_impl_win32.cpp | 4 +--- backends/imgui_impl_win32.h | 2 +- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- 13 files changed, 17 insertions(+), 22 deletions(-) diff --git a/backends/imgui_impl_android.cpp b/backends/imgui_impl_android.cpp index 1c2d62476..a76de1c26 100644 --- a/backends/imgui_impl_android.cpp +++ b/backends/imgui_impl_android.cpp @@ -6,7 +6,7 @@ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // Missing features or Issues: // [ ] Platform: Clipboard support. -// [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [ ] Platform: Gamepad support. // [ ] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. // Important: // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. diff --git a/backends/imgui_impl_android.h b/backends/imgui_impl_android.h index 3eaeca725..f6e41039a 100644 --- a/backends/imgui_impl_android.h +++ b/backends/imgui_impl_android.h @@ -6,7 +6,7 @@ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // Missing features or Issues: // [ ] Platform: Clipboard support. -// [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [ ] Platform: Gamepad support. // [ ] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. // Important: // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index baa8541b0..6beb97f6c 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -789,7 +789,7 @@ static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0 static void ImGui_ImplGlfw_UpdateGamepads() { ImGuiIO& io = ImGui::GetIO(); - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs, but see #8075 return; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h index 5d4dd8d41..b4d7bf8d7 100644 --- a/backends/imgui_impl_osx.h +++ b/backends/imgui_impl_osx.h @@ -7,7 +7,7 @@ // [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend). // [X] Platform: Mouse support. Can discriminate Mouse/Pen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. // Missing features or Issues: diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 2d72d413e..86e8b17a6 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -7,7 +7,7 @@ // [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend). // [X] Platform: Mouse support. Can discriminate Mouse/Pen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. // Missing features or Issues: @@ -31,6 +31,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-01-20: Removed notification observer when shutting down. (#8331) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn @@ -552,8 +553,6 @@ static void ImGui_ImplOSX_UpdateMouseCursor() static void ImGui_ImplOSX_UpdateGamepads() { ImGuiIO& io = ImGui::GetIO(); - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. - return; #if APPLE_HAS_CONTROLLER GCController* controller = GCController.current; diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 0be2f2c6e..54f9599cc 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -7,7 +7,7 @@ // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. @@ -755,9 +756,6 @@ static void ImGui_ImplSDL2_UpdateGamepads() bd->WantUpdateGamepadsList = false; } - // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) - return; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; if (bd->Gamepads.Size == 0) return; diff --git a/backends/imgui_impl_sdl2.h b/backends/imgui_impl_sdl2.h index 3c4775697..9f7b551fc 100644 --- a/backends/imgui_impl_sdl2.h +++ b/backends/imgui_impl_sdl2.h @@ -6,7 +6,7 @@ // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index cfe8bbd4e..d2be43620 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -6,7 +6,7 @@ // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. @@ -724,9 +725,6 @@ static void ImGui_ImplSDL3_UpdateGamepads() SDL_free(sdl_gamepads); } - // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) - return; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; if (bd->Gamepads.Size == 0) return; diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h index 5b8973738..a822a259b 100644 --- a/backends/imgui_impl_sdl3.h +++ b/backends/imgui_impl_sdl3.h @@ -6,7 +6,7 @@ // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 2c749515d..ab7c8ab9f 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -5,7 +5,7 @@ // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values are obsolete since 1.87 and not supported since 1.91.5] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -335,8 +335,6 @@ static void ImGui_ImplWin32_UpdateGamepads(ImGuiIO& io) { #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io); - //if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. - // return; // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow. // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE. diff --git a/backends/imgui_impl_win32.h b/backends/imgui_impl_win32.h index 083fe385f..5ae399e0e 100644 --- a/backends/imgui_impl_win32.h +++ b/backends/imgui_impl_win32.h @@ -5,7 +5,7 @@ // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values are obsolete since 1.87 and not supported since 1.91.5] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1a668bf73..c7be9a949 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Other changes: EndPopup() call. (#1651, #8499) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) +- Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad + regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) ----------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index a45348ad3..ddd6645c4 100644 --- a/imgui.h +++ b/imgui.h @@ -3288,7 +3288,7 @@ struct ImFontConfig float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. - float RasterizerDensity; // 1.0f // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display. IMPORTANT: If you increase this it is expected that you increase font scale accordingly, otherwise quality may look lowered. + float RasterizerDensity; // 1.0f // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. // [Internal] From 102f3f3a0de607ba444b4a0932f23a9de84de139 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Mar 2025 16:18:36 +0100 Subject: [PATCH 0787/2359] IO: variations in analog-only components of gamepad events do not interfere with trickling of mouse position events (#4921, #8508) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 12 ++++++++---- imgui.h | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c7be9a949..cf423eeb1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking changes: Other changes: +- IO: variations in analog-only components of gamepad events do not interfere + with trickling of mouse position events (#4921, #8508) - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of diff --git a/imgui.cpp b/imgui.cpp index b0e197590..833969724 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9868,12 +9868,16 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input)) break; + if (key_data->Down != e->Key.Down) // Analog change only do not trigger this, so it won't block e.g. further mouse pos events testing key_changed. + { + key_changed = true; + key_changed_mask.SetBit(key_data_index); + if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input) + key_changed_nonchar = true; + } + key_data->Down = e->Key.Down; key_data->AnalogValue = e->Key.AnalogValue; - key_changed = true; - key_changed_mask.SetBit(key_data_index); - if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input) - key_changed_nonchar = true; } else if (e->Type == ImGuiInputEventType_Text) { diff --git a/imgui.h b/imgui.h index ddd6645c4..8e456e130 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19191 +#define IMGUI_VERSION_NUM 19192 #define IMGUI_HAS_TABLE /* From f5003aff69ed8ee6c8b3ec07206ae266eb948b17 Mon Sep 17 00:00:00 2001 From: tanksdude <58898485+tanksdude@users.noreply.github.com> Date: Fri, 21 Mar 2025 08:23:09 -0700 Subject: [PATCH 0788/2359] Docs: Fix some typos (#8505) --- backends/imgui_impl_osx.mm | 2 +- backends/imgui_impl_sdlgpu3.h | 2 +- docs/CHANGELOG.txt | 2 +- examples/libs/usynergy/uSynergy.h | 2 +- imgui.cpp | 18 +++++++++--------- imgui.h | 4 ++-- imgui_demo.cpp | 10 +++++----- imgui_draw.cpp | 4 ++-- imgui_widgets.cpp | 8 ++++---- misc/fonts/binary_to_compressed_c.cpp | 4 ++-- misc/freetype/imgui_freetype.h | 2 +- 11 files changed, 29 insertions(+), 29 deletions(-) diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 86e8b17a6..e681d176b 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -537,7 +537,7 @@ static void ImGui_ImplOSX_UpdateMouseCursor() else { NSCursor* desired = bd->MouseCursors[imgui_cursor] ?: bd->MouseCursors[ImGuiMouseCursor_Arrow]; - // -[NSCursor set] generates measureable overhead if called unconditionally. + // -[NSCursor set] generates measurable overhead if called unconditionally. if (desired != NSCursor.currentCursor) { [desired set]; diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index 865139e26..7d28f7a36 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -17,7 +17,7 @@ // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. -// - Unline other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. +// - Unlike other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. #pragma once diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cf423eeb1..2e57ee005 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -633,7 +633,7 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v Breaking changes: - - Internals: using multiple overlayed ButtonBehavior() with same ID will now have the + - Internals: using multiple overlaid ButtonBehavior() with same ID will now have the io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030) It was one of the rare case where using same ID is legal. Workarounds: - use single ButtonBehavior() call with multiple _MouseButton flags diff --git a/examples/libs/usynergy/uSynergy.h b/examples/libs/usynergy/uSynergy.h index 2d7f9fa15..2b4d779b6 100644 --- a/examples/libs/usynergy/uSynergy.h +++ b/examples/libs/usynergy/uSynergy.h @@ -336,7 +336,7 @@ typedef struct uSynergyJoystickCallback m_joystickCallback; /* Callback for joystick events */ uSynergyClipboardCallback m_clipboardCallback; /* Callback for clipboard events */ - /* State data, used internall by client, initialized by uSynergyInit() */ + /* State data, used internally by client, initialized by uSynergyInit() */ uSynergyBool m_connected; /* Is our socket connected? */ uSynergyBool m_hasReceivedHello; /* Have we received a 'Hello' from the server? */ uSynergyBool m_isCaptured; /* Is Synergy active (i.e. this client is receiving input messages?) */ diff --git a/imgui.cpp b/imgui.cpp index 833969724..d9a6c2b0f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -477,7 +477,7 @@ CODE - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76) - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed). although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76) - - 2024/09/10 (1.91.2) - internals: using multiple overlayed ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030) + - 2024/09/10 (1.91.2) - internals: using multiple overlaid ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030) it was one of the rare case where using same ID is legal. workarounds: (1) use single ButtonBehavior() call with multiple _MouseButton flags, or (2) surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag() - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag. - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure: @@ -667,7 +667,7 @@ CODE - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(), ImGui::IsKeyDown(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details. - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX) - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX) - - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes). + - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to still function with legacy key codes). - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.* - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert. - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper. @@ -876,7 +876,7 @@ CODE - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. - - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix. + - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicitly to fix. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete). @@ -1748,7 +1748,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button. if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick) { - // Order of both statements matterns: this event will still release mouse button 1 + // Order of both statements matters: this event will still release mouse button 1 mouse_button = 1; if (!down) MouseCtrlLeftAsRightClick = false; @@ -3637,7 +3637,7 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end // Default clip_rect uses (pos_min,pos_max) // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) -// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList. +// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList. // 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. void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) @@ -5525,7 +5525,7 @@ static void InitViewportDrawData(ImGuiViewportP* viewport) // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): // some frequently called functions which to modify both channels and clipping simultaneously tend to use the // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds. -// - This is analoguous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack, +// - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack, // which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { @@ -5717,7 +5717,7 @@ void ImGui::EndFrame() } // Prepare the data for rendering so you can call GetDrawData() -// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all: +// (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all: // it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend) void ImGui::Render() { @@ -7870,7 +7870,7 @@ void ImGui::SetCurrentFont(ImFont* font) g.DrawListSharedData.FontScale = g.FontScale; } -// Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authorative against window-local ImDrawList. +// Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authoritative against window-local ImDrawList. // - Whereas ImDrawList::PushTextureID()/PopTextureID() is not to be used across Begin() calls. // - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... // - Some code paths never really fully worked with multiple atlas textures. @@ -11360,7 +11360,7 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext // - offset visibility to increase visibility around mouse. // - never clamp within outer viewport boundary. // We call SetNextWindowPos() to enforce position and disable clamping. - // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones). + // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones). //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen); if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0) diff --git a/imgui.h b/imgui.h index 8e456e130..2b6dd083d 100644 --- a/imgui.h +++ b/imgui.h @@ -696,7 +696,7 @@ namespace ImGui // - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. // - If you don't need a label you can probably simply use BeginChild() with the ImGuiChildFlags_FrameStyle flag for the same result. // - You can submit contents and manage your selection state however you want it, by creating e.g. Selectable() or any other items. - // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created. + // - 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 @@ -1022,7 +1022,7 @@ namespace ImGui IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); // IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired mouse cursor shape. Important: reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired mouse cursor shape - IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instucts your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. + IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instructs your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. // Clipboard Utilities // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 996694268..7bf2879d7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2388,7 +2388,7 @@ static const char* ExampleNames[] = struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage { // Find which item should be Focused after deletion. - // Call _before_ item submission. Retunr an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it. + // Call _before_ item submission. Return an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it. // The subsequent ApplyDeletionPostLoop() code will use it to apply Selection. // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. // - We don't actually manipulate the ImVector<> here, only in ApplyDeletionPostLoop(), but using similar API for consistency and flexibility. @@ -5399,7 +5399,7 @@ struct MyItem return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; } - // qsort() is instable so always return a way to differenciate items. + // qsort() is instable so always return a way to differentiate items. // Your own compare function may want to avoid fallback on implicit sort specs. // e.g. a Name compare if it wasn't already part of the sort specs. return (a->ID - b->ID); @@ -7762,7 +7762,7 @@ static void DemoWindowInputs() ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); // 2: InputText also polling for CTRL+A: it always uses _RouteFocused internally (gets priority when active) - // (Commmented because the owner-aware version of Shortcut() is still in imgui_internal.h) + // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) //char str[16] = "Press CTRL+A"; //ImGui::Spacing(); //ImGui::InputText("InputTextB", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly); @@ -7789,7 +7789,7 @@ static void DemoWindowInputs() { ImGui::Text("(in PopupF)"); ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); - // (Commmented because the owner-aware version of Shortcut() is still in imgui_internal.h) + // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) //ImGui::InputText("InputTextG", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly); //ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags, ImGui::GetItemID()) ? "PRESSED" : "..."); ImGui::EndPopup(); @@ -10368,7 +10368,7 @@ struct ExampleAssetsBrowser Selection.Clear(); } - // Logic would be written in the main code BeginChild() and outputing to local variables. + // Logic would be written in the main code BeginChild() and outputting to local variables. // We extracted it into a function so we can call it easily from multiple places. void UpdateLayoutSizes(float avail_width) { diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 67dfbdecc..95d5eaba1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -856,7 +856,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area dm_y *= half_draw_size; - // Add temporary vertexes for the outer edges + // Add temporary vertices for the outer edges ImVec2* out_vtx = &temp_points[i2 * 2]; out_vtx[0].x = points[i2].x + dm_x; out_vtx[0].y = points[i2].y + dm_y; @@ -883,7 +883,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 idx1 = idx2; } - // Add vertexes for each point on the line + // Add vertices for each point on the line if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index df12c0066..883a2648d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -494,7 +494,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);' // For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading. // - Since v1.91.2 (Sept 2024) we included io.ConfigDebugHighlightIdConflicts feature. -// One idiom which was previously valid which will now emit a warning is when using multiple overlayed ButtonBehavior() +// One idiom which was previously valid which will now emit a warning is when using multiple overlaid ButtonBehavior() // with same ID and different MouseButton (see #8030). You can fix it by: // (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags. // or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag() @@ -3891,7 +3891,7 @@ bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, si return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); } -// This is only used in the path where the multiline widget is inactivate. +// This is only used in the path where the multiline widget is inactive. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) { int line_count = 0; @@ -4648,7 +4648,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (g.ActiveId == id) { // Declare some inputs, the other are registered and polled via Shortcut() routing system. - // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combinaison into individual shortcuts. + // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combination into individual shortcuts. const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Enter, ImGuiKey_KeypadEnter, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End }; for (ImGuiKey key : always_owned_keys) SetKeyOwner(key, id); @@ -7691,7 +7691,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->IsFocused) { // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here. - if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at begining of the scope (see tests for easy failure) + if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at beginning of the scope (see tests for easy failure) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; diff --git a/misc/fonts/binary_to_compressed_c.cpp b/misc/fonts/binary_to_compressed_c.cpp index b0a243a71..da9883191 100644 --- a/misc/fonts/binary_to_compressed_c.cpp +++ b/misc/fonts/binary_to_compressed_c.cpp @@ -5,8 +5,8 @@ // The data is first compressed with stb_compress() to reduce source code size. // Then stored in a C array: // - Base85: ~5 bytes of source code for 4 bytes of input data. 5 bytes stored in binary (suggested by @mmalex). -// - As int: ~11 bytes of source code for 4 bytes of input data. 4 bytes stored in binary. Endianness dependant, need swapping on big-endian CPU. -// - As char: ~12 bytes of source code for 4 bytes of input data. 4 bytes stored in binary. Not endianness dependant. +// - As int: ~11 bytes of source code for 4 bytes of input data. 4 bytes stored in binary. Endianness dependent, need swapping on big-endian CPU. +// - As char: ~12 bytes of source code for 4 bytes of input data. 4 bytes stored in binary. Not endianness dependent. // Load compressed TTF fonts with ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF() // Build with, e.g: diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index 6572b1547..9d367074e 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -21,7 +21,7 @@ struct ImFontBuilderIO; // - When disabled, FreeType generates blurrier glyphs, more or less matches the stb_truetype.h // - The Default hinting mode usually looks good, but may distort glyphs in an unusual way. // - The Light hinting mode generates fuzzier glyphs but better matches Microsoft's rasterizer. -// You can set those flags globaly in ImFontAtlas::FontBuilderFlags +// You can set those flags globally in ImFontAtlas::FontBuilderFlags // You can set those flags on a per font basis in ImFontConfig::FontBuilderFlags enum ImGuiFreeTypeBuilderFlags { From ca3ba287683a1c60339e54edfe58da1175c9f79c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Mar 2025 17:21:22 +0100 Subject: [PATCH 0789/2359] Internals: made MousePos an argument of UpdateHoveredWindowAndCaptureFlags(). (#8431, #1152) --- imgui.cpp | 6 +++--- imgui_internal.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d9a6c2b0f..ea813cd92 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5058,7 +5058,7 @@ static bool IsWindowActiveAndVisible(ImGuiWindow* window) } // The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app) -void ImGui::UpdateHoveredWindowAndCaptureFlags() +void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) { ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; @@ -5072,7 +5072,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame. // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. bool clear_hovered_windows = false; - FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow); + FindHoveredWindowEx(mouse_pos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow); g.HoveredWindowBeforeClear = g.HoveredWindow; // Modal windows prevents mouse from hovering behind them. @@ -5343,7 +5343,7 @@ void ImGui::NewFrame() // Find hovered window // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame) // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active) - UpdateHoveredWindowAndCaptureFlags(); + UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos); // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) UpdateMouseMovingWindowNewFrame(); diff --git a/imgui_internal.h b/imgui_internal.h index 870360264..d2abe4588 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3049,7 +3049,7 @@ namespace ImGui // NewFrame IMGUI_API void UpdateInputEvents(bool trickle_fast_inputs); - IMGUI_API void UpdateHoveredWindowAndCaptureFlags(); + IMGUI_API void UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos); IMGUI_API void FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window); IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); IMGUI_API void UpdateMouseMovingWindowNewFrame(); From a806d2f9b8f18209e436ffb33815b2d0a8d7ad4f Mon Sep 17 00:00:00 2001 From: puugz Date: Fri, 21 Mar 2025 20:05:32 +0100 Subject: [PATCH 0790/2359] Backends: SDLGPU: Fixed typo in function name Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData(). (#8509, 8163, #7998, #7988) --- backends/imgui_impl_sdlgpu3.cpp | 9 +++++---- backends/imgui_impl_sdlgpu3.h | 4 ++-- docs/CHANGELOG.txt | 2 ++ examples/example_sdl3_sdlgpu3/main.cpp | 6 +++--- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 74b966227..94d81551c 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -17,10 +17,11 @@ // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. -// - Unlike other backends, the user must call the function Imgui_ImplSDLGPU3_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU3_RenderDrawData. +// - Unlike other backends, the user must call the function ImGui_ImplSDLGPU3_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU3_RenderDrawData. // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-03-21: Fixed typo in function name Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData(). // 2025-01-16: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device. // 2025-01-09: SDL_GPU: Added the SDL_GPU3 backend. @@ -134,7 +135,7 @@ static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer, uint32_t* old_size, uin // SDL_GPU doesn't allow copy passes to occur while a render or compute pass is bound! // The only way to allow a user to supply their own RenderPass (to render to a texture instead of the window for example), // is to split the upload part of ImGui_ImplSDLGPU3_RenderDrawData() to another function that needs to be called by the user before rendering. -void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer) +void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer) { // 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); @@ -366,7 +367,7 @@ void ImGui_ImplSDLGPU3_DestroyFontsTexture() io.Fonts->SetTexID(0); } -static void Imgui_ImplSDLGPU3_CreateShaders() +static void ImGui_ImplSDLGPU3_CreateShaders() { // Create the shader modules ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); @@ -431,7 +432,7 @@ static void ImGui_ImplSDLGPU3_CreateGraphicsPipeline() { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - Imgui_ImplSDLGPU3_CreateShaders(); + ImGui_ImplSDLGPU3_CreateShaders(); SDL_GPUVertexBufferDescription vertex_buffer_desc[1]; vertex_buffer_desc[0].slot = 0; diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index 7d28f7a36..c6d5a8e5d 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -17,7 +17,7 @@ // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. -// - Unlike other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. +// - Unlike other backends, the user must call the function ImGui_ImplSDLGPU_PrepareDrawData BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. #pragma once @@ -38,7 +38,7 @@ struct ImGui_ImplSDLGPU3_InitInfo IMGUI_IMPL_API bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info); IMGUI_IMPL_API void ImGui_ImplSDLGPU3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDLGPU3_NewFrame(); -IMGUI_IMPL_API void Imgui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer); +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer); IMGUI_IMPL_API void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline = nullptr); IMGUI_IMPL_API void ImGui_ImplSDLGPU3_CreateDeviceObjects(); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2e57ee005..6052c4300 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other changes: EndPopup() call. (#1651, #8499) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) +- Backends: SDL3: Fixed casing typo in function name: (#8509, #8163, #7998, #7988) [@puugz] + - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 630639f3f..3deeeafd5 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -7,7 +7,7 @@ // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app. -// - Unlike other backends, the user must call the function Imgui_ImplSDLGPU_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. +// - Unlike other backends, the user must call the function ImGui_ImplSDLGPU_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU_RenderDrawData. // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. #include "imgui.h" @@ -178,8 +178,8 @@ int main(int, char**) if (swapchain_texture != nullptr && !is_minimized) { - // This is mandatory: call Imgui_ImplSDLGPU3_PrepareDrawData() to upload the vertex/index buffer! - Imgui_ImplSDLGPU3_PrepareDrawData(draw_data, command_buffer); + // This is mandatory: call ImGui_ImplSDLGPU3_PrepareDrawData() to upload the vertex/index buffer! + ImGui_ImplSDLGPU3_PrepareDrawData(draw_data, command_buffer); // Setup and start a render pass SDL_GPUColorTargetInfo target_info = {}; From 702a67807bbba83986a955376995cd277984ff57 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Mar 2025 20:17:49 +0100 Subject: [PATCH 0791/2359] Move Changelog entry. (#8509) --- docs/CHANGELOG.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6052c4300..4d35191a5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ HOW TO UPDATE? Breaking changes: +- Backends: SDL3: Fixed casing typo in function name: (#8509, #8163, #7998, #7988) [@puugz] + - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() + Other changes: - IO: variations in analog-only components of gamepad events do not interfere @@ -49,8 +52,6 @@ Other changes: EndPopup() call. (#1651, #8499) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) -- Backends: SDL3: Fixed casing typo in function name: (#8509, #8163, #7998, #7988) [@puugz] - - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) From dbd9ae287a40e773a6fff364bdd8816ddae9b92b Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 23 Mar 2025 12:55:59 +0100 Subject: [PATCH 0792/2359] Windows: fixed SetNextWindowCollapsed()/SetWindowCollapsed() breaking codepath that preserve last contents size when collapsed. (#7691) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4d35191a5..0574bfe36 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,10 @@ Other changes: - IO: variations in analog-only components of gamepad events do not interfere with trickling of mouse position events (#4921, #8508) +- Windows: fixed SetNextWindowCollapsed()/SetWindowCollapsed() breaking + codepath that preserve last contents size when collapsed, resulting in + programmatically uncollapsing auto-sizing windows having them flicker size + for a frame. (#7691) [@achabense] - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of diff --git a/imgui.cpp b/imgui.cpp index ea813cd92..ba3271c54 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8228,8 +8228,10 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co return; window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); - // Set - window->Collapsed = collapsed; + // Queue applying in Begin() + if (window->WantCollapseToggle) + window->Collapsed ^= 1; + window->WantCollapseToggle = (window->Collapsed != collapsed); } void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) From 7674cbc9b25668dcbcc0ffd35b126b094c978e89 Mon Sep 17 00:00:00 2001 From: gan74 Date: Fri, 21 Mar 2025 20:40:38 +0100 Subject: [PATCH 0793/2359] Added extra operators to ImVec4. (#8510) --- docs/CHANGELOG.txt | 1 + imgui.h | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0574bfe36..469483be3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,7 @@ Other changes: EndPopup() call. (#1651, #8499) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) +- Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) diff --git a/imgui.h b/imgui.h index 2b6dd083d..fec015c77 100644 --- a/imgui.h +++ b/imgui.h @@ -2731,6 +2731,7 @@ struct ImGuiListClipper #ifdef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED IM_MSVC_RUNTIME_CHECKS_OFF +// ImVec2 operators static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } @@ -2746,9 +2747,14 @@ static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } static inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } static inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } +// ImVec4 operators +static inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } +static inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } +static inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } +static inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } static inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } IM_MSVC_RUNTIME_CHECKS_RESTORE From 5c9fb8f0648ed8b7be9c8f571157eefbf7ba1c88 Mon Sep 17 00:00:00 2001 From: Green Sky Date: Sat, 29 Mar 2025 21:04:17 +0100 Subject: [PATCH 0794/2359] Backends: SDL3: Update for API changes: Revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) see https://github.com/libsdl-org/SDL/pull/10390 --- backends/imgui_impl_sdl3.cpp | 4 ++-- docs/CHANGELOG.txt | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index d2be43620..ac2e841e6 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-03-30: Update for SDL3 api changes: Revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) @@ -133,8 +134,7 @@ static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*) ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); - const char* sdl_clipboard_text = SDL_GetClipboardText(); - bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : nullptr; + bd->ClipboardTextData = SDL_GetClipboardText(); return bd->ClipboardTextData; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 469483be3..4a691a20a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,8 @@ Other changes: - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) +- Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() + memory ownership change. (#8530, #7801) [@Green-Sky] ----------------------------------------------------------------------- From 187acb86093503bdf0af6aff069495671d8b607e Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 30 Mar 2025 14:46:07 +0200 Subject: [PATCH 0795/2359] Nav: polling gamepad for ImGuiKey_NavGamepadMenu use routing-friendly Shortcut() so Ctrl+Tab equivalent may be hijacked. (#8525, #4828, #3255, #5641) --- imgui.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ba3271c54..d8cbbf9f1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13779,7 +13779,7 @@ static void ImGui::NavUpdateWindowing() const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); - const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None); + const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id); const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard! bool just_started_windowing_from_null_focus = false; if (start_windowing_with_gamepad || start_windowing_with_keyboard) @@ -13802,7 +13802,8 @@ static void ImGui::NavUpdateWindowing() g.NavWindowingTimer += io.DeltaTime; if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad) { - // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise + // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise + // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast. g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // Select window to focus From 8bbdfefe056bfb2d778b144fbfdfc49642c367a1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 30 Mar 2025 15:05:27 +0200 Subject: [PATCH 0796/2359] Nav: added bool ConfigNavWindowingWithGamepad to disable windowing with gamepad. (#8525, #4828, #3255, #5641) --- imgui.cpp | 27 ++++++++++++++++----------- imgui_internal.h | 1 + 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d8cbbf9f1..53537baa0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4016,6 +4016,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac... // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this.. + ConfigNavWindowingWithGamepad = true; ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab); ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab); NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; @@ -13799,19 +13800,22 @@ static void ImGui::NavUpdateWindowing() } // Gamepad update - g.NavWindowingTimer += io.DeltaTime; if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad) { - // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise - // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast. - g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); - - // Select window to focus - const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1); - if (focus_change_dir != 0 && !just_started_windowing_from_null_focus) + if (g.ConfigNavWindowingWithGamepad) { - NavUpdateWindowingTarget(focus_change_dir); - g.NavWindowingHighlightAlpha = 1.0f; + // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise + // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast. + g.NavWindowingTimer += io.DeltaTime; + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); + + // Select window to focus + const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1); + if (focus_change_dir != 0 && !just_started_windowing_from_null_focus) + { + NavUpdateWindowingTarget(focus_change_dir); + g.NavWindowingHighlightAlpha = 1.0f; + } } // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) @@ -13820,7 +13824,7 @@ static void ImGui::NavUpdateWindowing() g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. if (g.NavWindowingToggleLayer && g.NavWindow) apply_toggle_layer = true; - else if (!g.NavWindowingToggleLayer) + else if (!g.NavWindowingToggleLayer && g.ConfigNavWindowingWithGamepad) apply_focus_window = g.NavWindowingTarget; g.NavWindowingTarget = NULL; } @@ -13832,6 +13836,7 @@ static void ImGui::NavUpdateWindowing() // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_; IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows. + g.NavWindowingTimer += io.DeltaTime; g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus) NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1); diff --git a/imgui_internal.h b/imgui_internal.h index d2abe4588..ec9c6047c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2240,6 +2240,7 @@ struct ImGuiContext bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) + bool ConfigNavWindowingWithGamepad; // = true. Enable CTRL+TAB by holding ImGuiKey_GamepadFaceLeft (== ImGuiKey_NavGamepadMenu). When false, the button may still be used to toggle Menu layer. ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828) ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X) ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! From a26fcf58cc2d0cfeee8b98ad8517af998f75c27e Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 30 Mar 2025 16:40:36 +0200 Subject: [PATCH 0797/2359] Nav: fixed assertion when holding gamepad FaceLeft/West button + pressing a keyboard key. (#8525) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 19 +++++++++++-------- imgui_internal.h | 1 + 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4a691a20a..b333f109e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,8 @@ Other changes: codepath that preserve last contents size when collapsed, resulting in programmatically uncollapsing auto-sizing windows having them flicker size for a frame. (#7691) [@achabense] +- Nav: fixed assertion when holding gamepad FaceLeft/West button to open + CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of diff --git a/imgui.cpp b/imgui.cpp index 53537baa0..b9088378a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4020,6 +4020,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab); ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab); NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; + NavWindowingInputSource = ImGuiInputSource_None; NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; NavWindowingToggleLayer = false; NavWindowingToggleKey = ImGuiKey_None; @@ -13786,11 +13787,12 @@ static void ImGui::NavUpdateWindowing() if (start_windowing_with_gamepad || start_windowing_with_keyboard) if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) { - g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location + if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad) + g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f); g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer - g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad; + g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad; if (g.NavWindow == NULL) just_started_windowing_from_null_focus = true; @@ -13800,9 +13802,9 @@ static void ImGui::NavUpdateWindowing() } // Gamepad update - if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad) + if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad) { - if (g.ConfigNavWindowingWithGamepad) + if (g.NavWindowingTarget != NULL) { // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast. @@ -13824,14 +13826,15 @@ static void ImGui::NavUpdateWindowing() g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. if (g.NavWindowingToggleLayer && g.NavWindow) apply_toggle_layer = true; - else if (!g.NavWindowingToggleLayer && g.ConfigNavWindowingWithGamepad) + else if (!g.NavWindowingToggleLayer) apply_focus_window = g.NavWindowingTarget; g.NavWindowingTarget = NULL; + g.NavWindowingToggleLayer = false; } } // Keyboard: Focus - if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard) + if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard) { // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_; @@ -13854,10 +13857,10 @@ static void ImGui::NavUpdateWindowing() windowing_toggle_layer_start = true; g.NavWindowingToggleLayer = true; g.NavWindowingToggleKey = windowing_toggle_key; - g.NavInputSource = ImGuiInputSource_Keyboard; + g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Keyboard; break; } - if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard) + if (g.NavWindowingToggleLayer && g.NavWindowingInputSource == ImGuiInputSource_Keyboard) { // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370) // We cancel toggling nav layer when other modifiers are pressed. (See #4439) diff --git a/imgui_internal.h b/imgui_internal.h index ec9c6047c..ff1a8d8ac 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2248,6 +2248,7 @@ struct ImGuiContext ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents float NavWindowingTimer; float NavWindowingHighlightAlpha; + ImGuiInputSource NavWindowingInputSource; bool NavWindowingToggleLayer; ImGuiKey NavWindowingToggleKey; ImVec2 NavWindowingAccumDeltaPos; From b6786595a43651a6214f036a5ce999138c37cd3b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 14:43:17 +0200 Subject: [PATCH 0798/2359] Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. (#8534) --- backends/imgui_impl_sdlgpu3.cpp | 67 ++++++++++++++++----------------- docs/CHANGELOG.txt | 2 + 2 files changed, 34 insertions(+), 35 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 94d81551c..f3a7adc85 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -21,6 +21,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-03-30: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. // 2025-03-21: Fixed typo in function name Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData(). // 2025-01-16: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device. // 2025-01-09: SDL_GPU: Added the SDL_GPU3 backend. @@ -35,10 +36,12 @@ // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData() struct ImGui_ImplSDLGPU3_FrameData { - SDL_GPUBuffer* VertexBuffer = nullptr; - SDL_GPUBuffer* IndexBuffer = nullptr; - uint32_t VertexBufferSize = 0; - uint32_t IndexBufferSize = 0; + SDL_GPUBuffer* VertexBuffer = nullptr; + SDL_GPUTransferBuffer* VertexTransferBuffer = nullptr; + uint32_t VertexBufferSize = 0; + SDL_GPUBuffer* IndexBuffer = nullptr; + SDL_GPUTransferBuffer* IndexTransferBuffer = nullptr; + uint32_t IndexBufferSize = 0; }; struct ImGui_ImplSDLGPU3_Data @@ -114,14 +117,15 @@ static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGra SDL_PushGPUVertexUniformData(command_buffer, 0, &ubo, sizeof(UBO)); } -static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer, uint32_t* old_size, uint32_t new_size, SDL_GPUBufferUsageFlags usage) +static void CreateOrResizeBuffers(SDL_GPUBuffer** buffer, SDL_GPUTransferBuffer** transferbuffer, uint32_t* old_size, uint32_t new_size, SDL_GPUBufferUsageFlags usage) { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - // Even though this is fairly rarely called. + // FIXME-OPT: Not optimal, but this is fairly rarely called. SDL_WaitForGPUIdle(v->Device); SDL_ReleaseGPUBuffer(v->Device, *buffer); + SDL_ReleaseGPUTransferBuffer(v->Device, *transferbuffer); SDL_GPUBufferCreateInfo buffer_info = {}; buffer_info.usage = usage; @@ -130,6 +134,12 @@ static void CreateOrResizeBuffer(SDL_GPUBuffer** buffer, uint32_t* old_size, uin *buffer = SDL_CreateGPUBuffer(v->Device, &buffer_info); *old_size = new_size; IM_ASSERT(*buffer != nullptr && "Failed to create GPU Buffer, call SDL_GetError() for more information"); + + SDL_GPUTransferBufferCreateInfo transferbuffer_info = {}; + transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; + transferbuffer_info.size = new_size; + *transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info); + IM_ASSERT(*transferbuffer != nullptr && "Failed to create GPU Transfer Buffer, call SDL_GetError() for more information"); } // SDL_GPU doesn't allow copy passes to occur while a render or compute pass is bound! @@ -150,25 +160,12 @@ void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff uint32_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); uint32_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); if (fd->VertexBuffer == nullptr || fd->VertexBufferSize < vertex_size) - CreateOrResizeBuffer(&fd->VertexBuffer, &fd->VertexBufferSize, vertex_size, SDL_GPU_BUFFERUSAGE_VERTEX); + CreateOrResizeBuffers(&fd->VertexBuffer, &fd->VertexTransferBuffer, &fd->VertexBufferSize, vertex_size, SDL_GPU_BUFFERUSAGE_VERTEX); if (fd->IndexBuffer == nullptr || fd->IndexBufferSize < index_size) - CreateOrResizeBuffer(&fd->IndexBuffer, &fd->IndexBufferSize, index_size, SDL_GPU_BUFFERUSAGE_INDEX); + CreateOrResizeBuffers(&fd->IndexBuffer, &fd->IndexTransferBuffer, &fd->IndexBufferSize, index_size, SDL_GPU_BUFFERUSAGE_INDEX); - // FIXME: It feels like more code could be shared there. - SDL_GPUTransferBufferCreateInfo vertex_transferbuffer_info = {}; - vertex_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; - vertex_transferbuffer_info.size = vertex_size; - SDL_GPUTransferBufferCreateInfo index_transferbuffer_info = {}; - index_transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; - index_transferbuffer_info.size = index_size; - - SDL_GPUTransferBuffer* vertex_transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &vertex_transferbuffer_info); - IM_ASSERT(vertex_transferbuffer != nullptr && "Failed to create the vertex transfer buffer, call SDL_GetError() for more information"); - SDL_GPUTransferBuffer* index_transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &index_transferbuffer_info); - IM_ASSERT(index_transferbuffer != nullptr && "Failed to create the index transfer buffer, call SDL_GetError() for more information"); - - ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->Device, vertex_transferbuffer, true); - ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->Device, index_transferbuffer, true); + ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->Device, fd->VertexTransferBuffer, true); + ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->Device, fd->IndexTransferBuffer, true); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* draw_list = draw_data->CmdLists[n]; @@ -177,15 +174,15 @@ void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff vtx_dst += draw_list->VtxBuffer.Size; idx_dst += draw_list->IdxBuffer.Size; } - SDL_UnmapGPUTransferBuffer(v->Device, vertex_transferbuffer); - SDL_UnmapGPUTransferBuffer(v->Device, index_transferbuffer); + SDL_UnmapGPUTransferBuffer(v->Device, fd->VertexTransferBuffer); + SDL_UnmapGPUTransferBuffer(v->Device, fd->IndexTransferBuffer); SDL_GPUTransferBufferLocation vertex_buffer_location = {}; vertex_buffer_location.offset = 0; - vertex_buffer_location.transfer_buffer = vertex_transferbuffer; + vertex_buffer_location.transfer_buffer = fd->VertexTransferBuffer; SDL_GPUTransferBufferLocation index_buffer_location = {}; index_buffer_location.offset = 0; - index_buffer_location.transfer_buffer = index_transferbuffer; + index_buffer_location.transfer_buffer = fd->IndexTransferBuffer; SDL_GPUBufferRegion vertex_buffer_region = {}; vertex_buffer_region.buffer = fd->VertexBuffer; @@ -201,8 +198,6 @@ void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff SDL_UploadToGPUBuffer(copy_pass, &vertex_buffer_location, &vertex_buffer_region, true); SDL_UploadToGPUBuffer(copy_pass, &index_buffer_location, &index_buffer_region, true); SDL_EndGPUCopyPass(copy_pass); - SDL_ReleaseGPUTransferBuffer(v->Device, index_transferbuffer); - SDL_ReleaseGPUTransferBuffer(v->Device, vertex_transferbuffer); } void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline) @@ -547,12 +542,14 @@ void ImGui_ImplSDLGPU3_DestroyFrameData() ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - SDL_ReleaseGPUBuffer(v->Device, bd->MainWindowFrameData.VertexBuffer); - SDL_ReleaseGPUBuffer(v->Device, bd->MainWindowFrameData.IndexBuffer); - bd->MainWindowFrameData.VertexBuffer = nullptr; - bd->MainWindowFrameData.IndexBuffer = nullptr; - bd->MainWindowFrameData.VertexBufferSize = 0; - bd->MainWindowFrameData.IndexBufferSize = 0; + ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData; + SDL_ReleaseGPUBuffer(v->Device, fd->VertexBuffer); + SDL_ReleaseGPUBuffer(v->Device, fd->IndexBuffer); + SDL_ReleaseGPUTransferBuffer(v->Device, fd->VertexTransferBuffer); + SDL_ReleaseGPUTransferBuffer(v->Device, fd->IndexTransferBuffer); + fd->VertexBuffer = fd->IndexBuffer = nullptr; + fd->VertexTransferBuffer = fd->IndexTransferBuffer = nullptr; + fd->VertexBufferSize = fd->IndexBufferSize = 0; } void ImGui_ImplSDLGPU3_DestroyDeviceObjects() diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b333f109e..216a1c4a6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,6 +63,8 @@ Other changes: regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) [@Green-Sky] +- Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers + which were unusually slow to recreate every frame. Much faster now. (#8534) ----------------------------------------------------------------------- From 4bdb0ac68539f3812dd1abb4b080624d22b46fe6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 15:12:28 +0200 Subject: [PATCH 0799/2359] Comments --- docs/CHANGELOG.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 216a1c4a6..2ad53ed61 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,8 +63,8 @@ Other changes: regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) [@Green-Sky] -- Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers - which were unusually slow to recreate every frame. Much faster now. (#8534) +- Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which + were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] ----------------------------------------------------------------------- @@ -530,7 +530,7 @@ Other changes: - Set io.ConfigNavCursorVisibleAuto = true (default) to enable automatic toggling of cursor visibility (mouse click hide the cursor, arrow keys makes it visible). - Set io.ConfigNavCursorVisibleAlways to keep cursor always visible. - - Nav: added NavSetCursorVisible(bool visible) function to manipulate visibility of + - Nav: added SetNavCursorVisible(bool visible) function to manipulate visibility of navigation cursor (e.g. set default state, or after some actions). (#1074, #2048, #7237, #8059) - Nav: added io.ConfigNavEscapeClearFocusItem and io.ConfigNavEscapeClearFocusWindow to change how pressing Escape affects navigation. (#8059, #2048, #1074, #3200) From 8098d79ca2e7787b082189623c5ffbba2cca6d4d Mon Sep 17 00:00:00 2001 From: Shixian Sheng Date: Tue, 1 Apr 2025 03:10:30 -0400 Subject: [PATCH 0800/2359] Docs: fixed link typo (#8538) --- docs/EXAMPLES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index 0df73059b..2826a5ad7 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -58,7 +58,7 @@ Allegro 5 example.
Android + OpenGL3 (ES) example.
= main.cpp + imgui_impl_android.cpp + imgui_impl_opengl3.cpp -[example_apple_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_metal/)
+[example_apple_metal/](https://github.com/ocornut/imgui/tree/master/examples/example_apple_metal/)
OSX & iOS + Metal example.
= main.m + imgui_impl_osx.mm + imgui_impl_metal.mm
It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. From fcab22f80f48495e70a24430f3a03a495e807fca Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 1 Apr 2025 22:53:00 +0200 Subject: [PATCH 0801/2359] Fonts: fixed CalcWordWrapPositionA() fallback when width is too small to wrap with multibyte codepoints.. (#8540) --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2ad53ed61..3872fe507 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,8 @@ Other changes: CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) +- Fonts: fixed CalcWordWrapPositionA() fallback when width is too small to wrap: + would use a +1 offset instead of advancing to the next UTF-8 codepoint. (#8540) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 95d5eaba1..df044e9b6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4027,7 +4027,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c // 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) - return s + 1; + return s + ImTextCountUtf8BytesFromChar(s, text_end); return s; } From b4bd596a393f09eb39c8fa9cf1b4430dbe6272b0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 1 Apr 2025 22:56:59 +0200 Subject: [PATCH 0802/2359] Fonts: word-wrapping code handle ideographic comma & full stop (U+3001, U+3002). (#8540) --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3872fe507..6a6c08bdd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,7 @@ Other changes: CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) +- Fonts: word-wrapping code handle ideographic comma & full stop (U+3001, U+3002). (#8540) - Fonts: fixed CalcWordWrapPositionA() fallback when width is too small to wrap: would use a +1 offset instead of advancing to the next UTF-8 codepoint. (#8540) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of diff --git a/imgui_draw.cpp b/imgui_draw.cpp index df044e9b6..06da4ef2d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4009,7 +4009,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c } // Allow wrapping after punctuation. - inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"'); + inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"' && c != 0x3001 && c != 0x3002); } // We ignore blank width at the end of the line (they can be skipped) From 9701810bc36577d443422b2894ba1a580faef13b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Apr 2025 11:41:21 +0200 Subject: [PATCH 0803/2359] TreeNode: adding ImGuiTreeNodeFlags_NoNavFocus in imgui_internal.h (#8551) --- imgui_internal.h | 1 + imgui_widgets.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/imgui_internal.h b/imgui_internal.h index ff1a8d8ac..a5bb47e03 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -994,6 +994,7 @@ enum ImGuiSelectableFlagsPrivate_ // Extend ImGuiTreeNodeFlags_ enum ImGuiTreeNodeFlagsPrivate_ { + ImGuiTreeNodeFlags_NoNavFocus = 1 << 27,// Don't claim nav focus when interacting with this item (#8551) ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader() ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517) ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 883a2648d..e882d85ee 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6691,6 +6691,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; else button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + if (flags & ImGuiTreeNodeFlags_NoNavFocus) + button_flags |= ImGuiButtonFlags_NoNavFocus; bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; const bool was_selected = selected; From 91652c317e8b231318afed60b4b506a8888837fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Apr 2025 16:38:05 +0200 Subject: [PATCH 0804/2359] Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) # Conflicts: # backends/imgui_impl_vulkan.cpp # docs/CHANGELOG.txt --- backends/imgui_impl_vulkan.cpp | 13 +++++++++++++ docs/CHANGELOG.txt | 3 +++ 2 files changed, 16 insertions(+) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index e67b74c01..b44513a2b 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -26,6 +26,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-04-07: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) // 2025-02-14: *BREAKING CHANGE*: Added uint32_t api_version to ImGui_ImplVulkan_LoadFunctions(). // 2025-02-13: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. Default to header version if unspecified. Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" (without -KHR suffix) on API 1.3. (#8326) // 2025-01-09: Vulkan: Added IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE to clarify how many image sampler descriptors are expected to be available in descriptor pool. (#6642) @@ -1174,6 +1175,16 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); bd->VulkanInitInfo = *info; + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + if (bd->VulkanInitInfo.PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) + { + // Deep copy buffer to reduce error-rate for end user (#8282) + VkFormat* formats_copy = (VkFormat*)IM_ALLOC(sizeof(VkFormat) * v->PipelineRenderingCreateInfo.colorAttachmentCount); + memcpy(formats_copy, v->PipelineRenderingCreateInfo.pColorAttachmentFormats, sizeof(VkFormat) * v->PipelineRenderingCreateInfo.colorAttachmentCount); + v->PipelineRenderingCreateInfo.pColorAttachmentFormats = formats_copy; + } +#endif ImGui_ImplVulkan_CreateDeviceObjects(); @@ -1187,6 +1198,8 @@ void ImGui_ImplVulkan_Shutdown() ImGuiIO& io = ImGui::GetIO(); ImGui_ImplVulkan_DestroyDeviceObjects(); + IM_FREE((void*)bd->VulkanInitInfo.PipelineRenderingCreateInfo.pColorAttachmentFormats); + io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6a6c08bdd..c6cb31221 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,9 @@ Other changes: memory ownership change. (#8530, #7801) [@Green-Sky] - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] +- Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's + pColorAttachmentFormats buffer when set, in order to reduce common user-error of + specifying a pointer to data that gets out of scope. (#8282) ----------------------------------------------------------------------- From 974bf58a215cbc71af2f16432fc65a3f50e0d6d1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Apr 2025 17:38:28 +0200 Subject: [PATCH 0805/2359] Backends: Vulkan: Build and warning fixes. (#8282) --- backends/imgui_impl_vulkan.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index b44513a2b..398b81f20 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1175,9 +1175,9 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); bd->VulkanInitInfo = *info; - ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - if (bd->VulkanInitInfo.PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + if (v->PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) { // Deep copy buffer to reduce error-rate for end user (#8282) VkFormat* formats_copy = (VkFormat*)IM_ALLOC(sizeof(VkFormat) * v->PipelineRenderingCreateInfo.colorAttachmentCount); @@ -1198,7 +1198,9 @@ void ImGui_ImplVulkan_Shutdown() ImGuiIO& io = ImGui::GetIO(); ImGui_ImplVulkan_DestroyDeviceObjects(); +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING IM_FREE((void*)bd->VulkanInitInfo.PipelineRenderingCreateInfo.pColorAttachmentFormats); +#endif io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; From faa03031b4cdf34fe9174c4e73dd769a5b41fda5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Apr 2025 18:16:23 +0200 Subject: [PATCH 0806/2359] Windows: loosened code to handle ImGuiButtonFlags_FlattenChildren so that master matches docking. (#8554) This essentially merges 059560d2 back into master. --- docs/CHANGELOG.txt | 3 +++ imgui_widgets.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c6cb31221..17f856c3a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,9 @@ Other changes: codepath that preserve last contents size when collapsed, resulting in programmatically uncollapsing auto-sizing windows having them flicker size for a frame. (#7691) [@achabense] +- Windows: loosened code to allow hovering of resize grips, borders, and table + borders while hovering a sibling child window, so that the code in master matches + one in docking (they accidentally diverged). (#8554) - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e882d85ee..0067bae01 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -518,7 +518,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool flags |= (item_flags & ImGuiItemFlags_ButtonRepeat) ? ImGuiButtonFlags_PressedOnClick : ImGuiButtonFlags_PressedOnDefault_; ImGuiWindow* backup_hovered_window = g.HoveredWindow; - const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindow == window; + const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindow == window->RootWindow; if (flatten_hovered_children) g.HoveredWindow = window; From e5b218e6d1e1943ca211522be322cbcf57db4477 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Jul 2024 19:03:25 +0200 Subject: [PATCH 0807/2359] TreeNode: added ImGuiTreeNodeFlags_DrawTreeXXX flags. (#2920) # Conflicts: # docs/CHANGELOG.txt --- docs/CHANGELOG.txt | 12 +++++++++ imgui.cpp | 7 ++++- imgui.h | 12 ++++++++- imgui_demo.cpp | 64 +++++++++++++++++++++++++++++++++++++++++++--- imgui_draw.cpp | 3 +++ imgui_internal.h | 10 +++++--- imgui_tables.cpp | 2 ++ imgui_widgets.cpp | 61 +++++++++++++++++++++++++++++++++++++------ 8 files changed, 154 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 17f856c3a..42721adac 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,18 @@ Other changes: - Windows: loosened code to allow hovering of resize grips, borders, and table borders while hovering a sibling child window, so that the code in master matches one in docking (they accidentally diverged). (#8554) +- TreeNode: added flags to draw tree hierarchy outlines linking parent + and tree nodes: (#2920) + - ImGuiTreeNodeFlags_DrawLinesNone: No lines drawn. + - ImGuiTreeNodeFlags_DrawLinesFull: Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. + - ImGuiTreeNodeFlags_DrawLinesToNodes: Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. + - Added style.TreeLinesFlags which stores the default setting, + which may be overriden in individual TreeNode() calls. + - Added style.TreeLinesSize (default to 1.0f). + - Added ImGuiCol_TreeLines (in default style this is the same as ImGuiCol_Border). + The color for a given hierarchy level is latched in TreeNode(), + allowing advanced tree drawing code to potentially alter it. + - The feature adds a little cost as extra data needs to be stored. - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui.cpp b/imgui.cpp index b9088378a..f0b633cf2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1360,6 +1360,8 @@ ImGuiStyle::ImGuiStyle() TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar. TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees). TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell + TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone; + TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. @@ -3415,6 +3417,7 @@ static const ImGuiStyleVarInfo GStyleVarsInfo[] = { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize @@ -3563,6 +3566,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt"; case ImGuiCol_TextLink: return "TextLink"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; + case ImGuiCol_TreeLines: return "TreeLines"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; case ImGuiCol_NavCursor: return "NavCursor"; case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; @@ -10243,6 +10247,7 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders. IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right); + IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes); // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way. if (g.IO.ConfigErrorRecovery) @@ -12794,7 +12799,7 @@ void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result) } // Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere -void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data) +void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data) { ImGuiContext& g = *GImGui; g.NavMoveScoringItems = false; diff --git a/imgui.h b/imgui.h index fec015c77..a3efff402 100644 --- a/imgui.h +++ b/imgui.h @@ -1214,6 +1214,12 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 17, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, + // [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. + // Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls. + ImGuiTreeNodeFlags_DrawLinesNone = 1 << 18, // No lines drawn + ImGuiTreeNodeFlags_DrawLinesFull = 1 << 19, // Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. + ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, // Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. A little bit slower. + #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth,// Renamed in 1.90.7 @@ -1666,7 +1672,8 @@ enum ImGuiCol_ ImGuiCol_TableRowBg, // Table row background (even rows) ImGuiCol_TableRowBgAlt, // Table row background (odd rows) ImGuiCol_TextLink, // Hyperlink color - ImGuiCol_TextSelectedBg, + ImGuiCol_TextSelectedBg, // Selected text inside an InputText + ImGuiCol_TreeLines, // Tree node hierarchy outlines when using ImGuiTreeNodeFlags_DrawLines ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target ImGuiCol_NavCursor, // Color of keyboard/gamepad navigation cursor/rectangle, when visible ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB @@ -1722,6 +1729,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign + ImGuiStyleVar_TreeLinesSize, // float TreeLinesSize ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize @@ -2181,6 +2189,8 @@ struct ImGuiStyle float TabBarOverlineSize; // Thickness of tab-bar overline, which highlights the selected tab-bar. float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees). ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell + ImGuiTreeNodeFlags TreeLinesFlags; // Default way to draw lines connecting TreeNode hierarchy. ImGuiTreeNodeFlags_DrawLinesNone or ImGuiTreeNodeFlags_DrawLinesFull or ImGuiTreeNodeFlags_DrawLinesToNodes. + float TreeLinesSize; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7bf2879d7..205551fbf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3920,6 +3920,7 @@ static void DemoWindowWidgetsTreeNodes() IMGUI_DEMO_MARKER("Widgets/Tree Nodes"); if (ImGui::TreeNode("Tree Nodes")) { + // See see "Examples -> Property Editor" (ShowExampleAppPropertyEditor() function) for a fancier, data-driven tree. IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Basic trees"); if (ImGui::TreeNode("Basic trees")) { @@ -3946,6 +3947,35 @@ static void DemoWindowWidgetsTreeNodes() ImGui::TreePop(); } + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Hierarchy lines"); + if (ImGui::TreeNode("Hierarchy lines")) + { + static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DefaultOpen; + HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesFull", &base_flags, ImGuiTreeNodeFlags_DrawLinesFull); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesToNodes", &base_flags, ImGuiTreeNodeFlags_DrawLinesToNodes); + + if (ImGui::TreeNodeEx("Parent", base_flags)) + { + if (ImGui::TreeNodeEx("Child 1", base_flags)) + { + ImGui::Button("Button for Child 1"); + ImGui::TreePop(); + } + if (ImGui::TreeNodeEx("Child 2", base_flags)) + { + ImGui::Button("Button for Child 2"); + ImGui::TreePop(); + } + ImGui::Text("Remaining contents"); + ImGui::Text("Remaining contents"); + ImGui::TreePop(); + } + + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Advanced, with Selectable nodes"); if (ImGui::TreeNode("Advanced, with Selectable nodes")) { @@ -3964,6 +3994,12 @@ static void DemoWindowWidgetsTreeNodes() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsBackHere", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsBackHere); + + HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesFull", &base_flags, ImGuiTreeNodeFlags_DrawLinesFull); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesToNodes", &base_flags, ImGuiTreeNodeFlags_DrawLinesToNodes); + ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); ImGui::Text("Hello!"); @@ -4607,10 +4643,11 @@ static void DemoWindowLayout() ImGui::SmallButton("SmallButton()"); // Tree + // (here the node appears after a button and has odd intent, so we use ImGuiTreeNodeFlags_DrawLinesNone to disable hierarchy outline) const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; ImGui::Button("Button##1"); ImGui::SameLine(0.0f, spacing); - if (ImGui::TreeNode("Node##1")) + if (ImGui::TreeNodeEx("Node##1", ImGuiTreeNodeFlags_DrawLinesNone)) { // Placeholder tree data for (int i = 0; i < 6; i++) @@ -6592,7 +6629,7 @@ static void DemoWindowTables() { static ImGuiTableFlags table_flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; - static ImGuiTreeNodeFlags tree_node_flags_base = ImGuiTreeNodeFlags_SpanAllColumns; + static ImGuiTreeNodeFlags tree_node_flags_base = ImGuiTreeNodeFlags_SpanAllColumns | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_DrawLinesFull; ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanFullWidth); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanLabelWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanLabelWidth); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanAllColumns); @@ -8139,6 +8176,14 @@ bool ImGui::ShowStyleSelector(const char* label) return false; } +static const char* GetTreeLinesFlagsName(ImGuiTreeNodeFlags flags) +{ + if (flags == ImGuiTreeNodeFlags_DrawLinesNone) return "DrawLinesNone"; + if (flags == ImGuiTreeNodeFlags_DrawLinesFull) return "DrawLinesFull"; + if (flags == ImGuiTreeNodeFlags_DrawLinesToNodes) return "DrawLinesToNodes"; + return ""; +} + void ImGui::ShowStyleEditor(ImGuiStyle* ref) { IMGUI_DEMO_MARKER("Tools/Style Editor"); @@ -8233,6 +8278,15 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1); ImGui::SeparatorText("Widgets"); + if (ImGui::BeginCombo("TreeLinesFlags", GetTreeLinesFlagsName(style.TreeLinesFlags))) + { + const ImGuiTreeNodeFlags options[] = { ImGuiTreeNodeFlags_DrawLinesNone, ImGuiTreeNodeFlags_DrawLinesFull, ImGuiTreeNodeFlags_DrawLinesToNodes }; + for (ImGuiTreeNodeFlags option : options) + if (ImGui::Selectable(GetTreeLinesFlagsName(option), style.TreeLinesFlags == option)) + style.TreeLinesFlags = option; + ImGui::EndCombo(); + } + ImGui::SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 1.0f, "%.0f"); ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); @@ -9285,8 +9339,10 @@ struct ExampleAppPropertyEditor ImGui::TableNextColumn(); ImGui::PushID(node->UID); ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None; - tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; // Standard opening mode as we are likely to want to add selection afterwards - tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support + tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;// Standard opening mode as we are likely to want to add selection afterwards + tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support + tree_flags |= ImGuiTreeNodeFlags_SpanFullWidth; // Span full width for easier mouse reach + tree_flags |= ImGuiTreeNodeFlags_DrawLinesToNodes; // Always draw hierarchy outlines if (node == VisibleNode) tree_flags |= ImGuiTreeNodeFlags_Selected; if (node->Childs.Size == 0) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 06da4ef2d..07145751a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -236,6 +236,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavCursor] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); @@ -300,6 +301,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); @@ -365,6 +367,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.09f); colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); diff --git a/imgui_internal.h b/imgui_internal.h index a5bb47e03..5703cd0e3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -998,6 +998,7 @@ enum ImGuiTreeNodeFlagsPrivate_ ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader() ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517) ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, + ImGuiTreeNodeFlags_DrawLinesMask_ = ImGuiTreeNodeFlags_DrawLinesNone | ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes, }; enum ImGuiSeparatorFlags_ @@ -1291,8 +1292,11 @@ struct ImGuiTreeNodeStackData { ImGuiID ID; ImGuiTreeNodeFlags TreeFlags; - ImGuiItemFlags ItemFlags; // Used for nav landing - ImRect NavRect; // Used for nav landing + ImGuiItemFlags ItemFlags; // Used for nav landing + ImRect NavRect; // Used for nav landing + ImU32 DrawLinesCol; + float DrawLinesX1; + float DrawLinesY2; }; // sizeof() = 20 @@ -3178,7 +3182,7 @@ namespace ImGui IMGUI_API void NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); IMGUI_API void NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result); - IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data); + IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data); IMGUI_API void NavMoveRequestCancel(); IMGUI_API void NavMoveRequestApplyResult(); IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0954784bb..a3d4a886b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -451,6 +451,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable(). table->WorkRect = table->OuterRect = table->InnerRect = outer_rect; table->HasScrollbarYPrev = table->HasScrollbarYCurr = false; + table->InnerWindow->DC.TreeDepth++; // This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking accross a table } // Push a standardized ID for both child-using and not-child-using tables @@ -1510,6 +1511,7 @@ void ImGui::EndTable() } else { + table->InnerWindow->DC.TreeDepth--; ItemSize(table->OuterRect.GetSize()); ItemAdd(table->OuterRect, 0); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0067bae01..3491ce8aa 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6390,6 +6390,7 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl // - TreeNodeV() // - TreeNodeEx() // - TreeNodeExV() +// - TreeNodeStoreStackData() [Internal] // - TreeNodeBehavior() [Internal] // - TreePush() // - TreePop() @@ -6548,17 +6549,27 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) // Store ImGuiTreeNodeStackData for just submitted node. // Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase. -static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags) +static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; g.TreeNodeStack.resize(g.TreeNodeStack.Size + 1); - ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.back(); + ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; tree_node_data->ID = g.LastItemData.ID; tree_node_data->TreeFlags = flags; tree_node_data->ItemFlags = g.LastItemData.ItemFlags; tree_node_data->NavRect = g.LastItemData.NavRect; + if (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) + { + tree_node_data->DrawLinesCol = ImGui::GetColorU32(ImGuiCol_TreeLines); + tree_node_data->DrawLinesX1 = x1; + tree_node_data->DrawLinesY2 = -FLT_MAX; + } + else + { + tree_node_data->DrawLinesCol = 0; + } window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); } @@ -6634,18 +6645,28 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default or move it to ImGuiStyle. bool store_tree_node_stack_data = false; - if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0) + flags |= g.Style.TreeLinesFlags; + const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y);// && (g.Style.TreeLinesSize > 0.0f); + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) { - if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && is_open && !g.NavIdIsAlive) + if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !g.NavIdIsAlive) if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) store_tree_node_stack_data = true; + if (draw_tree_lines) + store_tree_node_stack_data = true; } const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; if (!is_visible) { - if (store_tree_node_stack_data && is_open) - TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() + if (draw_tree_lines && (flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeHasStackDataDepthMask & (1 << window->DC.TreeDepth))) + { + ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, window->DC.CursorPos.y); // Don't need to aim to mid Y position as we are clipped anyway. + } + if (is_open && store_tree_node_stack_data) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushOverrideID(id); IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); @@ -6807,6 +6828,18 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l LogSetNextTextDecoration(">", NULL); } + if (draw_tree_lines && (window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1)))) + { + // Draw horizontal line from our parent node + ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + float x1 = parent_data->DrawLinesX1 + ImTrunc(g.FontSize * 0.5f + g.Style.FramePadding.x); // GetTreeNodeToLabelSpacing() * 0.5f + float x2 = text_pos.x - text_offset_x; + float y = text_pos.y + ImTrunc(g.FontSize * 0.5f); + parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, y); + if (x1 < x2) + window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), parent_data->DrawLinesCol, g.Style.TreeLinesSize); + } + if (span_all_columns && !span_all_columns_label) TablePopBackgroundChannel(); @@ -6821,7 +6854,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l } if (store_tree_node_stack_data && is_open) - TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice @@ -6865,7 +6898,7 @@ void ImGui::TreePop() if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) // Only set during request { - ImGuiTreeNodeStackData* data = &g.TreeNodeStack.back(); + const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; IM_ASSERT(data->ID == window->IDStack.back()); if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) { @@ -6873,6 +6906,18 @@ void ImGui::TreePop() if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data); } + if (data->DrawLinesCol != 0 && window->DC.CursorPos.y >= window->ClipRect.Min.y) + { + // Draw vertical line of the hierarchy + float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y); + float y2 = (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesToNodes) ? data->DrawLinesY2 : ImTrunc(window->DC.CursorPos.y - g.Style.ItemSpacing.y - g.FontSize * 0.5f); + y2 = ImMin(y2, window->ClipRect.Max.y); + if (y1 < y2) + { + float x = data->DrawLinesX1 + ImTrunc(g.FontSize * 0.5f + g.Style.FramePadding.x); // GetTreeNodeToLabelSpacing() * 0.5f + window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), data->DrawLinesCol, g.Style.TreeLinesSize); + } + } g.TreeNodeStack.pop_back(); window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask; } From 39f34e1e5846f064f5457645d205b4d69d598b2f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 8 Apr 2025 19:56:14 +0200 Subject: [PATCH 0808/2359] TreeNode: Don't latch GetColorU32(ImGuiCol_TreeLines). (#2920) Trade off doesn't seem worth it for large trees. User who really needs to alter colors can do it by adjusting Push/Pop locations. --- docs/CHANGELOG.txt | 2 -- imgui_internal.h | 1 - imgui_widgets.cpp | 20 +++++++------------- 3 files changed, 7 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 42721adac..5fe43da86 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,8 +64,6 @@ Other changes: which may be overriden in individual TreeNode() calls. - Added style.TreeLinesSize (default to 1.0f). - Added ImGuiCol_TreeLines (in default style this is the same as ImGuiCol_Border). - The color for a given hierarchy level is latched in TreeNode(), - allowing advanced tree drawing code to potentially alter it. - The feature adds a little cost as extra data needs to be stored. - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) diff --git a/imgui_internal.h b/imgui_internal.h index 5703cd0e3..0b2b0e6a0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1294,7 +1294,6 @@ struct ImGuiTreeNodeStackData ImGuiTreeNodeFlags TreeFlags; ImGuiItemFlags ItemFlags; // Used for nav landing ImRect NavRect; // Used for nav landing - ImU32 DrawLinesCol; float DrawLinesX1; float DrawLinesY2; }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3491ce8aa..6323e2271 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6560,16 +6560,10 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) tree_node_data->TreeFlags = flags; tree_node_data->ItemFlags = g.LastItemData.ItemFlags; tree_node_data->NavRect = g.LastItemData.NavRect; - if (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) - { - tree_node_data->DrawLinesCol = ImGui::GetColorU32(ImGuiCol_TreeLines); - tree_node_data->DrawLinesX1 = x1; - tree_node_data->DrawLinesY2 = -FLT_MAX; - } - else - { - tree_node_data->DrawLinesCol = 0; - } + + // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees. + tree_node_data->DrawLinesX1 = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) ? x1 : +FLT_MAX; + tree_node_data->DrawLinesY2 = -FLT_MAX; window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); } @@ -6837,7 +6831,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l float y = text_pos.y + ImTrunc(g.FontSize * 0.5f); parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, y); if (x1 < x2) - window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), parent_data->DrawLinesCol, g.Style.TreeLinesSize); + window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } if (span_all_columns && !span_all_columns_label) @@ -6906,7 +6900,7 @@ void ImGui::TreePop() if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data); } - if (data->DrawLinesCol != 0 && window->DC.CursorPos.y >= window->ClipRect.Min.y) + if (data->DrawLinesX1 != +FLT_MAX && window->DC.CursorPos.y >= window->ClipRect.Min.y) { // Draw vertical line of the hierarchy float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y); @@ -6915,7 +6909,7 @@ void ImGui::TreePop() if (y1 < y2) { float x = data->DrawLinesX1 + ImTrunc(g.FontSize * 0.5f + g.Style.FramePadding.x); // GetTreeNodeToLabelSpacing() * 0.5f - window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), data->DrawLinesCol, g.Style.TreeLinesSize); + window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } } g.TreeNodeStack.pop_back(); From 789de09dda710a8826cf3bdfba29a4c1f72c6097 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Apr 2025 12:04:09 +0200 Subject: [PATCH 0809/2359] TreeNode: extracted TreeNodeDrawLineToChildNode() for usage by custom widgets (#2920) --- docs/CHANGELOG.txt | 8 ++++++-- imgui.cpp | 4 ++-- imgui.h | 2 +- imgui_internal.h | 1 + imgui_widgets.cpp | 30 +++++++++++++++++++----------- 5 files changed, 29 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5fe43da86..312b6de3e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,14 +57,18 @@ Other changes: one in docking (they accidentally diverged). (#8554) - TreeNode: added flags to draw tree hierarchy outlines linking parent and tree nodes: (#2920) - - ImGuiTreeNodeFlags_DrawLinesNone: No lines drawn. + - ImGuiTreeNodeFlags_DrawLinesNone: No lines drawn (default value in style.TreeLinesFlags). - ImGuiTreeNodeFlags_DrawLinesFull: Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. - ImGuiTreeNodeFlags_DrawLinesToNodes: Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. - Added style.TreeLinesFlags which stores the default setting, which may be overriden in individual TreeNode() calls. - Added style.TreeLinesSize (default to 1.0f). - Added ImGuiCol_TreeLines (in default style this is the same as ImGuiCol_Border). - - The feature adds a little cost as extra data needs to be stored. + - Caveats: + - Tree nodes may be used in many creative ways (manually positioning openable + nodes in unusual ways, using indent to create tree-looking structures, etc.) + and the feature may not accurately represent them in every cases. + - The feature adds a little cost as extra data needs to be stored. - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui.cpp b/imgui.cpp index f0b633cf2..b32874ec5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16578,9 +16578,9 @@ void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int wi ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext); //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name); DebugNodeWindow(window, buf); - Indent(); + TreePush(buf); DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window); - Unindent(); + TreePop(); } } diff --git a/imgui.h b/imgui.h index a3efff402..d5e24f09e 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19192 +#define IMGUI_VERSION_NUM 19193 #define IMGUI_HAS_TABLE /* diff --git a/imgui_internal.h b/imgui_internal.h index 0b2b0e6a0..b4c2a429e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3467,6 +3467,7 @@ namespace ImGui // Widgets: Tree Nodes IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API void TreeNodeDrawLineToChildNode(const ImVec2& target_pos); IMGUI_API void TreePushOverrideID(ImGuiID id); IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6323e2271..56134d641 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6822,17 +6822,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l LogSetNextTextDecoration(">", NULL); } - if (draw_tree_lines && (window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1)))) - { - // Draw horizontal line from our parent node - ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; - float x1 = parent_data->DrawLinesX1 + ImTrunc(g.FontSize * 0.5f + g.Style.FramePadding.x); // GetTreeNodeToLabelSpacing() * 0.5f - float x2 = text_pos.x - text_offset_x; - float y = text_pos.y + ImTrunc(g.FontSize * 0.5f); - parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, y); - if (x1 < x2) - window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); - } + if (draw_tree_lines) + TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x, text_pos.y + g.FontSize * 0.5f)); if (span_all_columns && !span_all_columns_label) TablePopBackgroundChannel(); @@ -6856,6 +6847,23 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l return is_open; } +// Draw horizontal line from our parent node +// This is only called for visible child nodes so we are not too fussy anymore about performances +void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if ((window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1))) == 0) + return; + + ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + float x1 = parent_data->DrawLinesX1 + ImTrunc(g.FontSize * 0.5f + g.Style.FramePadding.x); // GetTreeNodeToLabelSpacing() * 0.5f + float y = ImTrunc(target_pos.y); + parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, y); + if (x1 < target_pos.x) + window->DrawList->AddLine(ImVec2(x1, y), ImVec2(target_pos.x, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); +} + void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); From 74e453cf15c08cd1c34128a2cb020fe732efe61c Mon Sep 17 00:00:00 2001 From: Zane van Iperen Date: Wed, 9 Apr 2025 14:56:54 +0200 Subject: [PATCH 0810/2359] Backends: SDL2, SDL3: don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) --- backends/imgui_impl_sdl2.cpp | 41 ++++++++++++++++++++---------------- backends/imgui_impl_sdl3.cpp | 41 ++++++++++++++++++++---------------- docs/CHANGELOG.txt | 3 +++ 3 files changed, 49 insertions(+), 36 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 54f9599cc..b2dacc48e 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) @@ -142,6 +143,7 @@ struct ImGui_ImplSDL2_Data SDL_Cursor* MouseLastCursor; int MouseLastLeaveFrame; bool MouseCanUseGlobalState; + bool MouseCanUseCapture; // Gamepad handling ImVector Gamepads; @@ -474,17 +476,6 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); - // Check and store if we are on a SDL backend that supports global mouse position - // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) - bool mouse_can_use_global_state = false; -#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE - const char* sdl_backend = SDL_GetCurrentVideoDriver(); - const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; - for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++) - if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0) - mouse_can_use_global_state = true; -#endif - // Setup backend capabilities flags ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)(); io.BackendPlatformUserData = (void*)bd; @@ -495,7 +486,18 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->Window = window; bd->WindowID = SDL_GetWindowID(window); bd->Renderer = renderer; - bd->MouseCanUseGlobalState = mouse_can_use_global_state; + + // Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse() + // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) + bd->MouseCanUseGlobalState = false; + bd->MouseCanUseCapture = false; +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + const char* sdl_backend = SDL_GetCurrentVideoDriver(); + const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; + for (const char* item : capture_and_global_state_whitelist) + if (strncmp(sdl_backend, item, strlen(item)) == 0) + bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true; +#endif ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; @@ -630,12 +632,15 @@ static void ImGui_ImplSDL2_UpdateMouseData() // We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below) #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside. - // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to migitate the issue we wait until mouse has moved to begin capture. - bool want_capture = false; - for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) - if (ImGui::IsMouseDragging(button_n, 1.0f)) - want_capture = true; - SDL_CaptureMouse(want_capture ? SDL_TRUE : SDL_FALSE); + // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture. + if (bd->MouseCanUseCapture) + { + bool want_capture = false; + for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) + if (ImGui::IsMouseDragging(button_n, 1.0f)) + want_capture = true; + SDL_CaptureMouse(want_capture ? SDL_TRUE : SDL_FALSE); + } SDL_Window* focused_window = SDL_GetKeyboardFocus(); const bool is_app_focused = (bd->Window == focused_window); diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index ac2e841e6..c2dd81085 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) // 2025-03-30: Update for SDL3 api changes: Revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) @@ -110,6 +111,7 @@ struct ImGui_ImplSDL3_Data SDL_Cursor* MouseLastCursor; int MousePendingLeaveFrame; bool MouseCanUseGlobalState; + bool MouseCanUseCapture; // Gamepad handling ImVector Gamepads; @@ -461,17 +463,6 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_UNUSED(sdl_gl_context); // Unused in this branch - // Check and store if we are on a SDL backend that supports global mouse position - // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) - bool mouse_can_use_global_state = false; -#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE - const char* sdl_backend = SDL_GetCurrentVideoDriver(); - const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; - for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++) - if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0) - mouse_can_use_global_state = true; -#endif - // Setup backend capabilities flags ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)(); io.BackendPlatformUserData = (void*)bd; @@ -482,7 +473,18 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void bd->Window = window; bd->WindowID = SDL_GetWindowID(window); bd->Renderer = renderer; - bd->MouseCanUseGlobalState = mouse_can_use_global_state; + + // Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse() + // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) + bd->MouseCanUseGlobalState = false; + bd->MouseCanUseCapture = false; +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + const char* sdl_backend = SDL_GetCurrentVideoDriver(); + const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; + for (const char* item : capture_and_global_state_whitelist) + if (strncmp(sdl_backend, item, strlen(item)) == 0) + bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true; +#endif ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; @@ -596,12 +598,15 @@ static void ImGui_ImplSDL3_UpdateMouseData() // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below) #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside. - // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to migitate the issue we wait until mouse has moved to begin capture. - bool want_capture = false; - for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) - if (ImGui::IsMouseDragging(button_n, 1.0f)) - want_capture = true; - SDL_CaptureMouse(want_capture); + // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture. + if (bd->MouseCanUseCapture) + { + bool want_capture = false; + for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) + if (ImGui::IsMouseDragging(button_n, 1.0f)) + want_capture = true; + SDL_CaptureMouse(want_capture); + } SDL_Window* focused_window = SDL_GetKeyboardFocus(); const bool is_app_focused = (bd->Window == focused_window); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 312b6de3e..b45cc1e3a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,9 @@ Other changes: - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) +- Backends: SDL2, SDL3: don't attempt to call SDL_CaptureMouse() on drivers where we don't + call SDL_GetGlobalMouseState(). This is specifically for Wayland but we currently use + the same white-list as SDL_GetGlobalMouseState(). (#8561) [@vs49688] - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) [@Green-Sky] - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which From 5e7174dec6d7d708dbfd857c32c15671619babc2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Apr 2025 17:39:22 +0200 Subject: [PATCH 0811/2359] TreeNode: removed TreeLinesSize > 0.0f optimization check. (#2920) This is desirable but we'd need to avoid exposing 0.0f in style editor + assert on it. --- imgui_demo.cpp | 2 +- imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 205551fbf..ac51635cf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8286,7 +8286,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) style.TreeLinesFlags = option; ImGui::EndCombo(); } - ImGui::SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 1.0f, "%.0f"); + ImGui::SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 2.0f, "%.0f"); ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 56134d641..5122fef7d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6641,7 +6641,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l bool store_tree_node_stack_data = false; if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0) flags |= g.Style.TreeLinesFlags; - const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y);// && (g.Style.TreeLinesSize > 0.0f); + const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f); if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) { if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !g.NavIdIsAlive) From bcbbfdaad4b98249cedcfd4914c70b01c4cb3243 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Apr 2025 17:43:48 +0200 Subject: [PATCH 0812/2359] TreeNode: DrawLines: latch X1 offset during TreePush(). (#2920) --- imgui_widgets.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5122fef7d..b61817b9c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6562,7 +6562,7 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) tree_node_data->NavRect = g.LastItemData.NavRect; // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees. - tree_node_data->DrawLinesX1 = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) ? x1 : +FLT_MAX; + tree_node_data->DrawLinesX1 = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX; tree_node_data->DrawLinesY2 = -FLT_MAX; window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); } @@ -6857,11 +6857,12 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) return; ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; - float x1 = parent_data->DrawLinesX1 + ImTrunc(g.FontSize * 0.5f + g.Style.FramePadding.x); // GetTreeNodeToLabelSpacing() * 0.5f + float x1 = ImTrunc(parent_data->DrawLinesX1); + float x2 = ImTrunc(target_pos.x); float y = ImTrunc(target_pos.y); parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, y); - if (x1 < target_pos.x) - window->DrawList->AddLine(ImVec2(x1, y), ImVec2(target_pos.x, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + if (x1 < x2) + window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } void ImGui::TreePush(const char* str_id) @@ -6916,7 +6917,7 @@ void ImGui::TreePop() y2 = ImMin(y2, window->ClipRect.Max.y); if (y1 < y2) { - float x = data->DrawLinesX1 + ImTrunc(g.FontSize * 0.5f + g.Style.FramePadding.x); // GetTreeNodeToLabelSpacing() * 0.5f + float x = ImTrunc(data->DrawLinesX1); window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } } From 43caca05c27aebaa8f8fc3064d47042dce6c7f8b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Apr 2025 17:58:23 +0200 Subject: [PATCH 0813/2359] TreeNode: DrawLines: tweak X2 offset to avoid losing line when ItemSpacing is large. (#2920) --- imgui_widgets.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b61817b9c..c1d1f54ba 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6823,7 +6823,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l } if (draw_tree_lines) - TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x, text_pos.y + g.FontSize * 0.5f)); + TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5f)); if (span_all_columns && !span_all_columns_label) TablePopBackgroundChannel(); @@ -6858,7 +6858,7 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; float x1 = ImTrunc(parent_data->DrawLinesX1); - float x2 = ImTrunc(target_pos.x); + float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); float y = ImTrunc(target_pos.y); parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, y); if (x1 < x2) From bbb0f0ade4d716be73c5c4b2552e124e54c63681 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Apr 2025 14:08:10 +0200 Subject: [PATCH 0814/2359] TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b45cc1e3a..5ab36ed18 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,7 @@ Other changes: nodes in unusual ways, using indent to create tree-looking structures, etc.) and the feature may not accurately represent them in every cases. - The feature adds a little cost as extra data needs to be stored. +- TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c1d1f54ba..bd56f509b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6794,6 +6794,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding); RenderNavCursor(frame_bb, id, nav_render_cursor_flags); + if (span_all_columns && !span_all_columns_label) + TablePopBackgroundChannel(); if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col); else if (!is_leaf) @@ -6814,6 +6816,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false); } RenderNavCursor(frame_bb, id, nav_render_cursor_flags); + if (span_all_columns && !span_all_columns_label) + TablePopBackgroundChannel(); 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) @@ -6825,9 +6829,6 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (draw_tree_lines) TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5f)); - if (span_all_columns && !span_all_columns_label) - TablePopBackgroundChannel(); - // Label if (display_frame) RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); From ed50bb167671f716358c8bd7bb5a6fadde39fae3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Apr 2025 14:47:08 +0200 Subject: [PATCH 0815/2359] TreeNode, Tables: fixed ImGuiTreeNodeFlags_DrawLinesXXX feature when TreePop() is called from a different column. (#2920) --- imgui_internal.h | 13 ++++++++----- imgui_tables.cpp | 31 ++++++++++++++++++++++++++++++- imgui_widgets.cpp | 8 +++++++- 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index b4c2a429e..070a75e6f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -206,6 +206,10 @@ typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // F typedef int ImGuiTypingSelectFlags; // -> enum ImGuiTypingSelectFlags_ // Flags: for GetTypingSelectRequest() typedef int ImGuiWindowRefreshFlags; // -> enum ImGuiWindowRefreshFlags_ // Flags: for SetNextWindowRefreshPolicy() +// Table column indexing +typedef ImS16 ImGuiTableColumnIdx; +typedef ImU16 ImGuiTableDrawChannelIdx; + //----------------------------------------------------------------------------- // [SECTION] Context pointer // See implementation of this variable in imgui.cpp for comments and details. @@ -1296,6 +1300,7 @@ struct ImGuiTreeNodeStackData ImRect NavRect; // Used for nav landing float DrawLinesX1; float DrawLinesY2; + ImGuiTableColumnIdx DrawLinesTableColumn; }; // sizeof() = 20 @@ -2704,11 +2709,7 @@ struct IMGUI_API ImGuiTabBar //----------------------------------------------------------------------------- #define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code which cannot be used as a regular color. -#define IMGUI_TABLE_MAX_COLUMNS 512 // May be further lifted - -// Our current column maximum is 64 but we may raise that in the future. -typedef ImS16 ImGuiTableColumnIdx; -typedef ImU16 ImGuiTableDrawChannelIdx; +#define IMGUI_TABLE_MAX_COLUMNS 512 // Arbitrary "safety" maximum, may be lifted in the future if needed. Must fit in ImGuiTableColumnIdx/ImGuiTableDrawChannelIdx. // [Internal] sizeof() ~ 112 // We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. @@ -3344,6 +3345,8 @@ namespace ImGui IMGUI_API float TableGetHeaderAngledMaxLabelWidth(); IMGUI_API void TablePushBackgroundChannel(); IMGUI_API void TablePopBackgroundChannel(); + IMGUI_API void TablePushColumnChannel(int column_n); + IMGUI_API void TablePopColumnChannel(); IMGUI_API void TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label_width, const ImGuiTableHeaderData* data, int data_count); // Tables: Internals diff --git a/imgui_tables.cpp b/imgui_tables.cpp index a3d4a886b..6d4d673a1 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2193,6 +2193,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_n) g.LastItemData.StatusFlags = 0; } + // Also see TablePushColumnChannel() if (table->Flags & ImGuiTableFlags_NoClip) { // FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed. @@ -2466,10 +2467,38 @@ void ImGui::TablePopBackgroundChannel() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiTable* table = g.CurrentTable; - ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; // Optimization: avoid PopClipRect() + SetCurrentChannel() SetWindowClipRectBeforeSetChannel(window, table->HostBackupInnerClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[table->CurrentColumn].DrawChannelCurrent); +} + +// Also see TableBeginCell() +void ImGui::TablePushColumnChannel(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + if (table->Flags & ImGuiTableFlags_NoClip) + return; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiTableColumn* column = &table->Columns[column_n]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); +} + +void ImGui::TablePopColumnChannel() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + if (table->Flags & ImGuiTableFlags_NoClip) + return; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bd56f509b..8d98dab6e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6562,7 +6562,9 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) tree_node_data->NavRect = g.LastItemData.NavRect; // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees. - tree_node_data->DrawLinesX1 = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX; + const bool draw_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) != 0; + tree_node_data->DrawLinesX1 = draw_lines ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX; + tree_node_data->DrawLinesTableColumn = draw_lines && g.CurrentTable ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1; tree_node_data->DrawLinesY2 = -FLT_MAX; window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); } @@ -6919,7 +6921,11 @@ void ImGui::TreePop() if (y1 < y2) { float x = ImTrunc(data->DrawLinesX1); + if (data->DrawLinesTableColumn != -1) + TablePushColumnChannel(data->DrawLinesTableColumn); window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + if (data->DrawLinesTableColumn != -1) + TablePopColumnChannel(); } } g.TreeNodeStack.pop_back(); From 531125346847d26f87e5a0dde9fa74b50d5725f9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Apr 2025 16:03:39 +0200 Subject: [PATCH 0816/2359] TreeNode: ImGuiTreeNodeFlags_DrawLinesFull uses ToNodes Y2 when they are close (using a threshold). (#2920) --- imgui.h | 4 ++-- imgui_internal.h | 2 +- imgui_widgets.cpp | 14 ++++++++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index d5e24f09e..98761113f 100644 --- a/imgui.h +++ b/imgui.h @@ -1217,8 +1217,8 @@ enum ImGuiTreeNodeFlags_ // [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. // Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls. ImGuiTreeNodeFlags_DrawLinesNone = 1 << 18, // No lines drawn - ImGuiTreeNodeFlags_DrawLinesFull = 1 << 19, // Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. - ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, // Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. A little bit slower. + ImGuiTreeNodeFlags_DrawLinesFull = 1 << 19, // Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). + ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, // Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 diff --git a/imgui_internal.h b/imgui_internal.h index 070a75e6f..3100bd4ac 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1299,7 +1299,7 @@ struct ImGuiTreeNodeStackData ImGuiItemFlags ItemFlags; // Used for nav landing ImRect NavRect; // Used for nav landing float DrawLinesX1; - float DrawLinesY2; + float DrawLinesToNodesY2; ImGuiTableColumnIdx DrawLinesTableColumn; }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8d98dab6e..42741b227 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6565,7 +6565,7 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) const bool draw_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) != 0; tree_node_data->DrawLinesX1 = draw_lines ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX; tree_node_data->DrawLinesTableColumn = draw_lines && g.CurrentTable ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1; - tree_node_data->DrawLinesY2 = -FLT_MAX; + tree_node_data->DrawLinesToNodesY2 = -FLT_MAX; window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); } @@ -6659,7 +6659,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (draw_tree_lines && (flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeHasStackDataDepthMask & (1 << window->DC.TreeDepth))) { ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; - parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, window->DC.CursorPos.y); // Don't need to aim to mid Y position as we are clipped anyway. + parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, window->DC.CursorPos.y); // Don't need to aim to mid Y position as we are clipped anyway. } if (is_open && store_tree_node_stack_data) TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() @@ -6863,7 +6863,7 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) float x1 = ImTrunc(parent_data->DrawLinesX1); float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); float y = ImTrunc(target_pos.y); - parent_data->DrawLinesY2 = ImMax(parent_data->DrawLinesY2, y); + parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y); if (x1 < x2) window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } @@ -6916,7 +6916,13 @@ void ImGui::TreePop() { // Draw vertical line of the hierarchy float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y); - float y2 = (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesToNodes) ? data->DrawLinesY2 : ImTrunc(window->DC.CursorPos.y - g.Style.ItemSpacing.y - g.FontSize * 0.5f); + float y2 = data->DrawLinesToNodesY2; + if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull) + { + float y2_full = ImTrunc(window->DC.CursorPos.y - g.Style.ItemSpacing.y - g.FontSize * 0.5f); + if (y2 + g.Style.ItemSpacing.y < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y + y2 = y2_full; + } y2 = ImMin(y2, window->ClipRect.Max.y); if (y1 < y2) { From 8c977bf7b3a74ac3a9bea4ad003676ffd2a3d940 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Apr 2025 16:26:38 +0200 Subject: [PATCH 0817/2359] TreeNode, Tables: fixed ImGuiTreeNodeFlags_DrawLinesXXX feature when TreePop() is called in table: in no column or at top of row. (#2920) --- docs/CHANGELOG.txt | 9 +++++++-- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 5 ++++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5ab36ed18..1e6766842 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,8 +55,8 @@ Other changes: - Windows: loosened code to allow hovering of resize grips, borders, and table borders while hovering a sibling child window, so that the code in master matches one in docking (they accidentally diverged). (#8554) -- TreeNode: added flags to draw tree hierarchy outlines linking parent - and tree nodes: (#2920) +- TreeNode: added experimental flags to draw tree hierarchy outlines linking + parent and tree nodes: (#2920) - ImGuiTreeNodeFlags_DrawLinesNone: No lines drawn (default value in style.TreeLinesFlags). - ImGuiTreeNodeFlags_DrawLinesFull: Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. - ImGuiTreeNodeFlags_DrawLinesToNodes: Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. @@ -69,6 +69,11 @@ Other changes: nodes in unusual ways, using indent to create tree-looking structures, etc.) and the feature may not accurately represent them in every cases. - The feature adds a little cost as extra data needs to be stored. + (ImGuiTreeNodeFlags_DrawLinesToNodes is slower than ImGuiTreeNodeFlags_DrawLinesFull + which may be meaningful on very large trees, as it needs to record bottom-most + Y position even for clipped nodes). + - The feature is unlikely to ever work properly when using a coarse clipper + such as ImGuiListClipper. - TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 6d4d673a1..b8b869301 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2494,7 +2494,7 @@ void ImGui::TablePopColumnChannel() ImGuiTable* table = g.CurrentTable; // Optimization: avoid PopClipRect() + SetCurrentChannel() - if (table->Flags & ImGuiTableFlags_NoClip) + if ((table->Flags & ImGuiTableFlags_NoClip) || (table->CurrentColumn == -1)) // Calling TreePop() after TableNextRow() is supported. return; ImGuiWindow* window = g.CurrentWindow; const ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 42741b227..6933fdcb6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6919,7 +6919,10 @@ void ImGui::TreePop() float y2 = data->DrawLinesToNodesY2; if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull) { - float y2_full = ImTrunc(window->DC.CursorPos.y - g.Style.ItemSpacing.y - g.FontSize * 0.5f); + float y2_full = window->DC.CursorPos.y; + if (g.CurrentTable) + y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full); + y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f); if (y2 + g.Style.ItemSpacing.y < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y y2 = y2_full; } From ee0d96ac0d7c0a2d79ad1650eb4c12f9c7cd739a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Apr 2025 17:00:17 +0200 Subject: [PATCH 0818/2359] TreeNode: extract code out of TreePop() into TreeNodeDrawLineToTreePop(). (#2920) --- imgui_internal.h | 1 + imgui_widgets.cpp | 60 ++++++++++++++++++++++++++--------------------- 2 files changed, 34 insertions(+), 27 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 3100bd4ac..d5155e425 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3471,6 +3471,7 @@ namespace ImGui // Widgets: Tree Nodes IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API void TreeNodeDrawLineToChildNode(const ImVec2& target_pos); + IMGUI_API void TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data); IMGUI_API void TreePushOverrideID(ImGuiID id); IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6933fdcb6..13c1362b1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6868,6 +6868,33 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } +// Draw vertical line of the hierarchy +void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y); + float y2 = data->DrawLinesToNodesY2; + if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull) + { + float y2_full = window->DC.CursorPos.y; + if (g.CurrentTable) + y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full); + y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f); + if (y2 + g.Style.ItemSpacing.y < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y + y2 = y2_full; + } + y2 = ImMin(y2, window->ClipRect.Max.y); + if (y2 <= y1) + return; + float x = ImTrunc(data->DrawLinesX1); + if (data->DrawLinesTableColumn != -1) + TablePushColumnChannel(data->DrawLinesTableColumn); + window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + if (data->DrawLinesTableColumn != -1) + TablePopColumnChannel(); +} + void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); @@ -6906,37 +6933,16 @@ void ImGui::TreePop() { const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; IM_ASSERT(data->ID == window->IDStack.back()); + + // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled) if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) - { - // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled) if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data); - } + + // Draw hierarchy lines if (data->DrawLinesX1 != +FLT_MAX && window->DC.CursorPos.y >= window->ClipRect.Min.y) - { - // Draw vertical line of the hierarchy - float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y); - float y2 = data->DrawLinesToNodesY2; - if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull) - { - float y2_full = window->DC.CursorPos.y; - if (g.CurrentTable) - y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full); - y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f); - if (y2 + g.Style.ItemSpacing.y < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y - y2 = y2_full; - } - y2 = ImMin(y2, window->ClipRect.Max.y); - if (y1 < y2) - { - float x = ImTrunc(data->DrawLinesX1); - if (data->DrawLinesTableColumn != -1) - TablePushColumnChannel(data->DrawLinesTableColumn); - window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); - if (data->DrawLinesTableColumn != -1) - TablePopColumnChannel(); - } - } + TreeNodeDrawLineToTreePop(data); + g.TreeNodeStack.pop_back(); window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask; } From 9943137d1e926d4e4901c5721fea249c8ee4355f Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Apr 2025 17:25:06 +0200 Subject: [PATCH 0819/2359] TreeNode: fixed non-opened clipped child node not moving Y2 marker. (#2920) --- imgui.cpp | 2 +- imgui_internal.h | 3 ++- imgui_widgets.cpp | 8 ++++++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b32874ec5..c7566494b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7649,7 +7649,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.MenuBarAppending = false; window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user); window->DC.TreeDepth = 0; - window->DC.TreeHasStackDataDepthMask = 0x00; + window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 0x00; window->DC.ChildWindows.resize(0); window->DC.StateStorage = &window->StateStorage; window->DC.CurrentColumns = NULL; diff --git a/imgui_internal.h b/imgui_internal.h index d5155e425..65de255f5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2474,7 +2474,8 @@ struct IMGUI_API ImGuiWindowTempData ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs. ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement int TreeDepth; // Current tree depth. - ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. + ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. + ImU32 TreeRecordsClippedNodesY2Mask; // Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. ImVector ChildWindows; ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) ImGuiOldColumns* CurrentColumns; // Current columns set diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 13c1362b1..140ceb9e1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6564,9 +6564,11 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees. const bool draw_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) != 0; tree_node_data->DrawLinesX1 = draw_lines ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX; - tree_node_data->DrawLinesTableColumn = draw_lines && g.CurrentTable ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1; + tree_node_data->DrawLinesTableColumn = (draw_lines && g.CurrentTable) ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1; tree_node_data->DrawLinesToNodesY2 = -FLT_MAX; window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); + if (flags & ImGuiTreeNodeFlags_DrawLinesToNodes) + window->DC.TreeRecordsClippedNodesY2Mask |= (1 << window->DC.TreeDepth); } // When using public API, currently 'id == storage_id' is always true, but we separate the values to facilitate advanced user code doing storage queries outside of UI loop. @@ -6656,10 +6658,12 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; if (!is_visible) { - if (draw_tree_lines && (flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeHasStackDataDepthMask & (1 << window->DC.TreeDepth))) + if ((flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeRecordsClippedNodesY2Mask & (1 << (window->DC.TreeDepth - 1)))) { ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, window->DC.CursorPos.y); // Don't need to aim to mid Y position as we are clipped anyway. + if (frame_bb.Min.y >= window->ClipRect.Max.y) + window->DC.TreeRecordsClippedNodesY2Mask &= ~(1 << (window->DC.TreeDepth - 1)); // Done } if (is_open && store_tree_node_stack_data) TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() From 3ab50c334a0b89480c00cca3bca414cea9d02d05 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Apr 2025 19:26:29 +0200 Subject: [PATCH 0820/2359] TreeNode, Style: added style.TreeLinesRounding support. (#2920) --- docs/CHANGELOG.txt | 3 ++- imgui.cpp | 3 +++ imgui.h | 4 +++- imgui_demo.cpp | 24 +++++++++++++++--------- imgui_widgets.cpp | 19 ++++++++++++++++--- 5 files changed, 39 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1e6766842..e4e8dc0db 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,9 +60,10 @@ Other changes: - ImGuiTreeNodeFlags_DrawLinesNone: No lines drawn (default value in style.TreeLinesFlags). - ImGuiTreeNodeFlags_DrawLinesFull: Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. - ImGuiTreeNodeFlags_DrawLinesToNodes: Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. - - Added style.TreeLinesFlags which stores the default setting, + - Added style.TreeLinesFlags which stores the default setting, which may be overriden in individual TreeNode() calls. - Added style.TreeLinesSize (default to 1.0f). + - Added style.TreeLinesRadius (default to 0.0f). - Added ImGuiCol_TreeLines (in default style this is the same as ImGuiCol_Border). - Caveats: - Tree nodes may be used in many creative ways (manually positioning openable diff --git a/imgui.cpp b/imgui.cpp index c7566494b..a8d67f9bf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1362,6 +1362,7 @@ ImGuiStyle::ImGuiStyle() TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone; TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. + TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. @@ -1416,6 +1417,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected; TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); + TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); @@ -3418,6 +3420,7 @@ static const ImGuiStyleVarInfo GStyleVarsInfo[] = { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize diff --git a/imgui.h b/imgui.h index 98761113f..0ddef9510 100644 --- a/imgui.h +++ b/imgui.h @@ -1730,6 +1730,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign ImGuiStyleVar_TreeLinesSize, // float TreeLinesSize + ImGuiStyleVar_TreeLinesRounding, // float TreeLinesRounding ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize @@ -2190,7 +2191,8 @@ struct ImGuiStyle float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees). ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell ImGuiTreeNodeFlags TreeLinesFlags; // Default way to draw lines connecting TreeNode hierarchy. ImGuiTreeNodeFlags_DrawLinesNone or ImGuiTreeNodeFlags_DrawLinesFull or ImGuiTreeNodeFlags_DrawLinesToNodes. - float TreeLinesSize; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. + float TreeLinesSize; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. + float TreeLinesRounding; // Radius of lines connecting child nodes to the vertical line. ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ac51635cf..fbf65aa1d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8270,15 +8270,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderAngle("TableAngledHeadersAngle", &style.TableAngledHeadersAngle, -50.0f, +50.0f); ImGui::SliderFloat2("TableAngledHeadersTextAlign", (float*)&style.TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SeparatorText("Windows"); - ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SliderFloat("WindowBorderHoverPadding", &style.WindowBorderHoverPadding, 1.0f, 20.0f, "%.0f"); - int window_menu_button_position = style.WindowMenuButtonPosition + 1; - if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) - style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1); - - ImGui::SeparatorText("Widgets"); - if (ImGui::BeginCombo("TreeLinesFlags", GetTreeLinesFlagsName(style.TreeLinesFlags))) + ImGui::SeparatorText("Trees"); + bool combo_open = ImGui::BeginCombo("TreeLinesFlags", GetTreeLinesFlagsName(style.TreeLinesFlags)); + ImGui::SameLine(); + HelpMarker("[Experimental] Tree lines may not work in all situations (e.g. using a clipper) and may incurs slight traversal overhead.\n\nImGuiTreeNodeFlags_DrawLinesFull is faster than ImGuiTreeNodeFlags_DrawLinesToNode."); + if (combo_open) { const ImGuiTreeNodeFlags options[] = { ImGuiTreeNodeFlags_DrawLinesNone, ImGuiTreeNodeFlags_DrawLinesFull, ImGuiTreeNodeFlags_DrawLinesToNodes }; for (ImGuiTreeNodeFlags option : options) @@ -8287,6 +8283,16 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::EndCombo(); } ImGui::SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 2.0f, "%.0f"); + ImGui::SliderFloat("TreeLinesRounding", &style.TreeLinesRounding, 0.0f, 12.0f, "%.0f"); + + ImGui::SeparatorText("Windows"); + ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + ImGui::SliderFloat("WindowBorderHoverPadding", &style.WindowBorderHoverPadding, 1.0f, 20.0f, "%.0f"); + int window_menu_button_position = style.WindowMenuButtonPosition + 1; + if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) + style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1); + + ImGui::SeparatorText("Widgets"); ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 140ceb9e1..64f07a41b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6867,9 +6867,22 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) float x1 = ImTrunc(parent_data->DrawLinesX1); float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); float y = ImTrunc(target_pos.y); - parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y); - if (x1 < x2) + float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f; + parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding); + if (x1 >= x2) + return; + if (rounding > 0.0f) + { + x1 += 0.5f + rounding; + window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3); + if (x1 < x2) + window->DrawList->PathLineTo(ImVec2(x2, y)); + window->DrawList->PathStroke(GetColorU32(ImGuiCol_TreeLines), ImDrawFlags_None, g.Style.TreeLinesSize); + } + else + { window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + } } // Draw vertical line of the hierarchy @@ -6885,7 +6898,7 @@ void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) if (g.CurrentTable) y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full); y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f); - if (y2 + g.Style.ItemSpacing.y < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y + if (y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y y2 = y2_full; } y2 = ImMin(y2, window->ClipRect.Max.y); From d3bb3336f5359dd3bf4af9bb32c2164b31414eac Mon Sep 17 00:00:00 2001 From: 519q Date: Sat, 12 Apr 2025 17:54:10 +0300 Subject: [PATCH 0821/2359] Backends: OSX: remove duplicate variable. (#8565) --- backends/imgui_impl_osx.mm | 2 -- 1 file changed, 2 deletions(-) diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index e681d176b..558ed9f2a 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -788,8 +788,6 @@ static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) default: return io.WantCaptureKeyboard; } - - NSEventModifierFlags modifier_flags = [event modifierFlags]; io.AddKeyEvent(key, (modifier_flags & mask) != 0); io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code) } From b23a216ecddedcc1bf3c1241b5428d39399b622a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 16 Apr 2025 13:28:57 +0200 Subject: [PATCH 0822/2359] Examples: added SDL2+Vulkan, SDL3+Vulkan, GLFW+Vulkan makefiles. Amend ignore list. (#2480) --- .gitignore | 8 +- examples/example_glfw_vulkan/Makefile | 83 +++++++++++++++++++++ examples/example_glfw_vulkan/main.cpp | 2 +- examples/example_sdl2_vulkan/Makefile | 80 ++++++++++++++++++++ examples/example_sdl2_vulkan/main.cpp | 2 +- examples/example_sdl3_opengl3/Makefile | 5 +- examples/example_sdl3_sdlrenderer3/Makefile | 7 +- examples/example_sdl3_vulkan/Makefile | 77 +++++++++++++++++++ examples/example_sdl3_vulkan/main.cpp | 2 +- 9 files changed, 257 insertions(+), 9 deletions(-) create mode 100644 examples/example_glfw_vulkan/Makefile create mode 100644 examples/example_sdl2_vulkan/Makefile create mode 100644 examples/example_sdl3_vulkan/Makefile diff --git a/.gitignore b/.gitignore index 15a908273..c920ba649 100644 --- a/.gitignore +++ b/.gitignore @@ -56,9 +56,15 @@ cmake-build-* examples/example_glfw_metal/example_glfw_metal examples/example_glfw_opengl2/example_glfw_opengl2 examples/example_glfw_opengl3/example_glfw_opengl3 +examples/example_glfw_vulkan/example_glfw_vulkan examples/example_glut_opengl2/example_glut_opengl2 examples/example_null/example_null examples/example_sdl2_metal/example_sdl2_metal examples/example_sdl2_opengl2/example_sdl2_opengl2 examples/example_sdl2_opengl3/example_sdl2_opengl3 -examples/example_sdl2_sdlrenderer/example_sdl2_sdlrenderer +examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2 +examples/example_sdl2_vulkan/example_sdl2_vulkan +examples/example_sdl3_opengl3/example_sdl3_opengl3 +examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3 +examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3 +examples/example_sdl3_vulkan/example_sdl3_vulkan diff --git a/examples/example_glfw_vulkan/Makefile b/examples/example_glfw_vulkan/Makefile new file mode 100644 index 000000000..1a84082d1 --- /dev/null +++ b/examples/example_glfw_vulkan/Makefile @@ -0,0 +1,83 @@ +# +# Cross Platform Makefile +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X +# +# You will need GLFW (http://www.glfw.org): +# Linux: +# apt-get install libglfw-dev +# Mac OS X: +# brew install glfw +# MSYS2: +# pacman -S --noconfirm --needed mingw-w64-x86_64-toolchain mingw-w64-x86_64-glfw +# + +#CXX = g++ +#CXX = clang++ + +EXE = example_glfw_vulkan +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_vulkan.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) +LINUX_GL_LIBS = -lGL + +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS += -g -Wall -Wformat +LIBS = + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- + +ifeq ($(UNAME_S), Linux) #LINUX + ECHO_MESSAGE = "Linux" + LIBS += $(LINUX_GL_LIBS) `pkg-config --static --libs glfw3 vulkan` + + CXXFLAGS += `pkg-config --cflags glfw3 vulkan` + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(UNAME_S), Darwin) #APPLE + ECHO_MESSAGE = "Mac OS X" + LIBS += -framework Cocoa -framework IOKit -framework CoreVideo + LIBS += `pkg-config --libs glfw3 vulkan` + LIBS += -L/usr/local/lib -L/opt/local/lib -L/opt/homebrew/lib + #LIBS += -lglfw3 + + LIBS += `pkg-config --cflags glfw3 vulkan` + CXXFLAGS += -I/usr/local/include -I/opt/local/include -I/opt/homebrew/include + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(OS), Windows_NT) + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -limm32 + LIBS += `pkg-config --libs glfw3 vulkan` + + CXXFLAGS += `pkg-config --cflags glfw3 vulkan` + CFLAGS = $(CXXFLAGS) +endif + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(ECHO_MESSAGE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index ce7fcde5e..3d2181e89 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -38,6 +38,7 @@ //#define APP_USE_UNLIMITED_FRAME_RATE #ifdef _DEBUG #define APP_USE_VULKAN_DEBUG_REPORT +static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; #endif // Data @@ -47,7 +48,6 @@ static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; static VkDevice g_Device = VK_NULL_HANDLE; static uint32_t g_QueueFamily = (uint32_t)-1; static VkQueue g_Queue = VK_NULL_HANDLE; -static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; diff --git a/examples/example_sdl2_vulkan/Makefile b/examples/example_sdl2_vulkan/Makefile new file mode 100644 index 000000000..e722ab035 --- /dev/null +++ b/examples/example_sdl2_vulkan/Makefile @@ -0,0 +1,80 @@ +# +# Cross Platform Makefile +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X +# +# You will need SDL2 (http://www.libsdl.org): +# Linux: +# apt-get install libsdl2-dev +# Mac OS X: +# brew install sdl2 +# MSYS2: +# pacman -S mingw-w64-i686-SDL2 +# + +#CXX = g++ +#CXX = clang++ + +EXE = example_sdl2_vulkan +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl2.cpp $(IMGUI_DIR)/backends/imgui_impl_vulkan.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) + +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS += -g -Wall -Wformat +LIBS = + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- + +ifeq ($(UNAME_S), Linux) #LINUX + ECHO_MESSAGE = "Linux" + LIBS += -lGL -ldl + LIBS += `pkg-config --libs sdl2 vulkan` + CXXFLAGS += `pkg-config --cflags sdl2 vulkan` + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(UNAME_S), Darwin) #APPLE + ECHO_MESSAGE = "Mac OS X" + LIBS += -framework Cocoa -framework IOKit -framework CoreVideo + LIBS += `pkg-config --libs sdl2 vulkan` + LIBS += -L/usr/local/lib -L/opt/local/lib + + CXXFLAGS += `pkg-config --cflags sdl2 vulkan` + CXXFLAGS += -I/usr/local/include -I/opt/local/include + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(OS), Windows_NT) + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl2 vulkan` + + CXXFLAGS += `pkg-config --cflags sdl2 vulkan` + CFLAGS = $(CXXFLAGS) +endif + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(ECHO_MESSAGE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 0c29154bc..c62222577 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -30,6 +30,7 @@ //#define APP_USE_UNLIMITED_FRAME_RATE #ifdef _DEBUG #define APP_USE_VULKAN_DEBUG_REPORT +static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; #endif // Data @@ -39,7 +40,6 @@ static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; static VkDevice g_Device = VK_NULL_HANDLE; static uint32_t g_QueueFamily = (uint32_t)-1; static VkQueue g_Queue = VK_NULL_HANDLE; -static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; diff --git a/examples/example_sdl3_opengl3/Makefile b/examples/example_sdl3_opengl3/Makefile index c2ef3ba55..d9c6eac9e 100644 --- a/examples/example_sdl3_opengl3/Makefile +++ b/examples/example_sdl3_opengl3/Makefile @@ -45,10 +45,11 @@ endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" - LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl3-config --libs` + LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo + LIBS += `pkg-config --libs sdl3` LIBS += -L/usr/local/lib -L/opt/local/lib - CXXFLAGS += `pkg-config sdl3 --cflags` + CXXFLAGS += `pkg-config --cflags sdl3` CXXFLAGS += -I/usr/local/include -I/opt/local/include CFLAGS = $(CXXFLAGS) endif diff --git a/examples/example_sdl3_sdlrenderer3/Makefile b/examples/example_sdl3_sdlrenderer3/Makefile index 1976fa924..c278f7830 100644 --- a/examples/example_sdl3_sdlrenderer3/Makefile +++ b/examples/example_sdl3_sdlrenderer3/Makefile @@ -26,7 +26,7 @@ LIBS = ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" - LIBS += -ldl `pkg-config sdl3 --libs` + LIBS += -ldl `pkg-config sdl3 --libs` CXXFLAGS += `pkg-config sdl3 --cflags` CFLAGS = $(CXXFLAGS) @@ -34,10 +34,11 @@ endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" - LIBS += -framework Cocoa -framework IOKit -framework CoreVideo `sdl3-config --libs` + LIBS += -framework Cocoa -framework IOKit -framework CoreVideo + LIBS += `pkg-config --libs sdl3` LIBS += -L/usr/local/lib -L/opt/local/lib - CXXFLAGS += `pkg-config sdl3 --cflags` + CXXFLAGS += `pkg-config --cflags sdl3` CXXFLAGS += -I/usr/local/include -I/opt/local/include CFLAGS = $(CXXFLAGS) endif diff --git a/examples/example_sdl3_vulkan/Makefile b/examples/example_sdl3_vulkan/Makefile new file mode 100644 index 000000000..e1956ff67 --- /dev/null +++ b/examples/example_sdl3_vulkan/Makefile @@ -0,0 +1,77 @@ +# +# Cross Platform Makefile +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X +# +# You will need SDL3 (http://www.libsdl.org) which is still unreleased/unpackaged. +# Mac OS X: +# brew install sdl3 + +#CXX = g++ +#CXX = clang++ + +EXE = example_sdl3_vulkan +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl3.cpp $(IMGUI_DIR)/backends/imgui_impl_vulkan.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) + +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS += -g -Wall -Wformat +LIBS = + + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- + +ifeq ($(UNAME_S), Linux) #LINUX + ECHO_MESSAGE = "Linux" + LIBS += -ldl + LIBS += `pkg-config --libs sdl3 vulkan` + + CXXFLAGS += `pkg-config --cflags sdl3 vulkan` + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(UNAME_S), Darwin) #APPLE + ECHO_MESSAGE = "Mac OS X" + LIBS += -framework Cocoa -framework IOKit -framework CoreVideo + LIBS += `pkg-config --libs sdl3 vulkan` + LIBS += -L/usr/local/lib -L/opt/local/lib + + CXXFLAGS += `pkg-config --cflags sdl3 vulkan` + CXXFLAGS += -I/usr/local/include -I/opt/local/include + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(OS), Windows_NT) + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -limm32 `pkg-config --static --libs sdl3 vulkan` + + CXXFLAGS += `pkg-config --cflags sdl3 vulkan` + CFLAGS = $(CXXFLAGS) +endif + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(ECHO_MESSAGE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 170eae45b..618fd34a8 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -35,6 +35,7 @@ //#define APP_USE_UNLIMITED_FRAME_RATE #ifdef _DEBUG #define APP_USE_VULKAN_DEBUG_REPORT +static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; #endif // Data @@ -44,7 +45,6 @@ static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; static VkDevice g_Device = VK_NULL_HANDLE; static uint32_t g_QueueFamily = (uint32_t)-1; static VkQueue g_Queue = VK_NULL_HANDLE; -static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; From 7ab4728a36cfa99c9a5cffde758f86248accb5b3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 16 Apr 2025 18:12:53 +0200 Subject: [PATCH 0823/2359] Error Handling: added better error report and recovery when calling EndFrame() or Render() without NewFrame(). --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e4e8dc0db..51229ac83 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,6 +80,8 @@ Other changes: CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) +- Error Handling: added better error report and recovery when calling EndFrame() + or Render() without NewFrame(). Was previously only an assert. - Fonts: word-wrapping code handle ideographic comma & full stop (U+3001, U+3002). (#8540) - Fonts: fixed CalcWordWrapPositionA() fallback when width is too small to wrap: would use a +1 offset instead of advancing to the next UTF-8 codepoint. (#8540) diff --git a/imgui.cpp b/imgui.cpp index a8d67f9bf..0d882da04 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5641,7 +5641,11 @@ void ImGui::EndFrame() // Don't process EndFrame() multiple times. if (g.FrameCountEnded == g.FrameCount) return; - IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?"); + if (!g.WithinFrameScope) + { + IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?"); + return; + } CallContextHooks(&g, ImGuiContextHookType_EndFramePre); From faea1938001d9667e0e98bedef4104cd73325236 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 16 Apr 2025 19:18:10 +0200 Subject: [PATCH 0824/2359] Internals: minor refactor of TabItemLabelAndCloseButton(), should be no-op. (minor thing toward #7024) --- imgui_widgets.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 64f07a41b..52e6236b5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10466,13 +10466,13 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, #endif // Render text label (with clipping + alpha gradient) + unsaved marker - ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); - ImRect text_ellipsis_clip_bb = text_pixel_clip_bb; + ImRect text_ellipsis_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); + float text_pixel_clip_bb_max_x = text_ellipsis_clip_bb.Max.x; // Return clipped state ignoring the close button if (out_text_clipped) { - *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_pixel_clip_bb.Max.x; + *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_pixel_clip_bb_max_x; //draw_list->AddCircle(text_ellipsis_clip_bb.Min, 3.0f, *out_text_clipped ? IM_COL32(255, 0, 0, 255) : IM_COL32(0, 255, 0, 255)); } @@ -10518,15 +10518,15 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // This is all rather complicated // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position) // FIXME: if FramePadding is noticeably large, ellipsis_max_x will be wrong here (e.g. #3497), maybe for consistency that parameter of RenderTextEllipsis() shouldn't exist.. - float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f; + float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb_max_x : bb.Max.x - 1.0f; if (close_button_visible || unsaved_marker_visible) { - text_pixel_clip_bb.Max.x -= close_button_visible ? (button_sz) : (button_sz * 0.80f); + text_pixel_clip_bb_max_x -= close_button_visible ? (button_sz) : (button_sz * 0.80f); text_ellipsis_clip_bb.Max.x -= unsaved_marker_visible ? (button_sz * 0.80f) : 0.0f; - ellipsis_max_x = text_pixel_clip_bb.Max.x; + ellipsis_max_x = text_pixel_clip_bb_max_x; } LogSetNextTextDecoration("/", "\\"); - RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size); + RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb_max_x, ellipsis_max_x, label, NULL, &label_size); #if 0 if (!is_contents_visible) From e4a865177ee7276d63e2d33789010722232b73fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 16 Apr 2025 20:21:23 +0200 Subject: [PATCH 0825/2359] ImFont: added cpu clip fine option for ImFont::RenderChar() (which is technically internal). (toward #7024) --- imgui.h | 2 +- imgui_draw.cpp | 27 +++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 0ddef9510..989ae5ebc 100644 --- a/imgui.h +++ b/imgui.h @@ -3532,7 +3532,7 @@ struct ImFont // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL); // utf8 IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width); - IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c); + 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, bool cpu_fine_clip = false); // [Internal] Don't use! diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 07145751a..13130a242 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4113,7 +4113,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons } // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. -void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) +void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip) { const ImFontGlyph* glyph = FindGlyph(c); if (!glyph || !glyph->Visible) @@ -4123,8 +4123,31 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, Im float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; float x = IM_TRUNC(pos.x); float y = IM_TRUNC(pos.y); + + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + if (cpu_fine_clip && (x1 > cpu_fine_clip->z || x2 < cpu_fine_clip->x)) + return; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // Always CPU fine clip. Code extracted from RenderText(). + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip != NULL) + { + if (x1 < cpu_fine_clip->x) { u1 = u1 + (1.0f - (x2 - cpu_fine_clip->x) / (x2 - x1)) * (u2 - u1); x1 = cpu_fine_clip->x; } + if (y1 < cpu_fine_clip->y) { v1 = v1 + (1.0f - (y2 - cpu_fine_clip->y) / (y2 - y1)) * (v2 - v1); y1 = cpu_fine_clip->y; } + if (x2 > cpu_fine_clip->z) { u2 = u1 + ((cpu_fine_clip->z - x1) / (x2 - x1)) * (u2 - u1); x2 = cpu_fine_clip->z; } + if (y2 > cpu_fine_clip->w) { v2 = v1 + ((cpu_fine_clip->w - y1) / (y2 - y1)) * (v2 - v1); y2 = cpu_fine_clip->w; } + if (y1 >= y2) + return; + } draw_list->PrimReserve(6, 4); - draw_list->PrimRectUV(ImVec2(x + glyph->X0 * scale, y + glyph->Y0 * scale), ImVec2(x + glyph->X1 * scale, y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); + draw_list->PrimRectUV(ImVec2(x1, y1), ImVec2(x2, y2), ImVec2(u1, v1), ImVec2(u2, v2), col); } // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. From 97d85338e8cb3c865649aead7842ec32367281aa Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 16 Apr 2025 20:27:23 +0200 Subject: [PATCH 0826/2359] Tabs: adjust handling of ellipsis now that Close Button visibility changed. (#8387) Internals: remove extra parameter to RenderTextEllipsis(). This requires RenderTextEllipsis() to use fine CPU-side clippoing. Users of RenderTextEllipsis(): #7024, #6236, #5267, #5745, #4269, #2775 --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 20 ++++++++++---------- imgui_internal.h | 2 +- imgui_tables.cpp | 4 ++-- imgui_widgets.cpp | 22 ++++++++++++++-------- 5 files changed, 29 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 51229ac83..23093c963 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,8 @@ Other changes: - The feature is unlikely to ever work properly when using a coarse clipper such as ImGuiListClipper. - TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. +- Tabs: fixes small issues with how "..." ellipsis moved depending on visibility + of Close Button or Unsaved Document marker. (#8387) - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui.cpp b/imgui.cpp index 0d882da04..0f7618edc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3691,18 +3691,18 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons } // 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) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display. +// 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. -void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, 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, const char* text, const char* text_end_full, 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); - //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255)); - //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255)); - //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255)); + //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 6), IM_COL32(0, 0, 255, 255)); + //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y - 2), ImVec2(ellipsis_max_x, pos_max.y + 3), IM_COL32(0, 255, 0, 255)); + // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels. if (text_size.x > pos_max.x - pos_min.x) { @@ -3734,15 +3734,15 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con } // Render text, render ellipsis - RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); + RenderTextClippedEx(draw_list, pos_min, pos_max, text, 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)); - if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x) - for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale) - font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar); + for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale) + font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect); } else { - RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); + RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); } if (g.LogEnabled) diff --git a/imgui_internal.h b/imgui_internal.h index 65de255f5..1d217553b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3424,7 +3424,7 @@ namespace ImGui 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 clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); + 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 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 RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b8b869301..077d54b14 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3275,7 +3275,7 @@ 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, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, label, label_end, &label_size); const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x); if (text_clipped && hovered && g.ActiveId == 0) @@ -3427,7 +3427,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label 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, clip_r.Max.x, label_name, label_name_eol, &label_size); + RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, label_name, label_name_eol, &label_size); PopStyleColor(); int vtx_idx_end = draw_list->_VtxCurrentIdx; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 52e6236b5..984bf5f06 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1690,7 +1690,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end window->DrawList->AddLine(ImVec2(sep2_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness); if (g.LogEnabled) LogSetNextTextDecoration("---", NULL); - RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, 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_end, &label_size); } else { @@ -10467,12 +10467,11 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // Render text label (with clipping + alpha gradient) + unsaved marker ImRect text_ellipsis_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); - float text_pixel_clip_bb_max_x = text_ellipsis_clip_bb.Max.x; // Return clipped state ignoring the close button if (out_text_clipped) { - *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_pixel_clip_bb_max_x; + *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_ellipsis_clip_bb.Max.x; //draw_list->AddCircle(text_ellipsis_clip_bb.Min, 3.0f, *out_text_clipped ? IM_COL32(255, 0, 0, 255) : IM_COL32(0, 255, 0, 255)); } @@ -10518,15 +10517,22 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // This is all rather complicated // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position) // FIXME: if FramePadding is noticeably large, ellipsis_max_x will be wrong here (e.g. #3497), maybe for consistency that parameter of RenderTextEllipsis() shouldn't exist.. - float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb_max_x : bb.Max.x - 1.0f; + float ellipsis_max_x = text_ellipsis_clip_bb.Max.x; if (close_button_visible || unsaved_marker_visible) { - text_pixel_clip_bb_max_x -= close_button_visible ? (button_sz) : (button_sz * 0.80f); - text_ellipsis_clip_bb.Max.x -= unsaved_marker_visible ? (button_sz * 0.80f) : 0.0f; - ellipsis_max_x = text_pixel_clip_bb_max_x; + const bool visible_without_hover = unsaved_marker_visible || (is_contents_visible ? g.Style.TabCloseButtonMinWidthSelected : g.Style.TabCloseButtonMinWidthUnselected) < 0.0f; + if (visible_without_hover) + { + text_ellipsis_clip_bb.Max.x -= button_sz * 0.90f; + ellipsis_max_x -= button_sz * 0.90f; + } + else + { + text_ellipsis_clip_bb.Max.x -= button_sz * 1.00f; + } } LogSetNextTextDecoration("/", "\\"); - RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb_max_x, ellipsis_max_x, label, NULL, &label_size); + RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, ellipsis_max_x, label, NULL, &label_size); #if 0 if (!is_contents_visible) From 69d572bb107c2e2dde3b0ce9d4bb583ac628be6b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 16 Apr 2025 20:30:00 +0200 Subject: [PATCH 0827/2359] Fonts: reworked text ellipsis logic to ensure a "..." is always displayed instead of a single character. (#7024) Requires 97d85338e8 and e4a865177e --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 6 ------ 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 23093c963..197fe9bb0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -84,6 +84,8 @@ Other changes: EndPopup() call. (#1651, #8499) - Error Handling: added better error report and recovery when calling EndFrame() or Render() without NewFrame(). Was previously only an assert. +- Fonts: reworked text ellipsis logic to ensure a "..." is always displayed instead + of a single character. (#7024) - Fonts: word-wrapping code handle ideographic comma & full stop (U+3001, U+3002). (#8540) - Fonts: fixed CalcWordWrapPositionA() fallback when width is too small to wrap: would use a +1 offset instead of advancing to the next UTF-8 codepoint. (#8540) diff --git a/imgui.cpp b/imgui.cpp index 0f7618edc..90d4bbfa9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3720,12 +3720,6 @@ 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); float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x; - if (text == text_end_ellipsis && text_end_ellipsis < text_end_full) - { - // Always display at least 1 character if there's no room for character + ellipsis - text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full); - text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x; - } while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) { // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text) From af987eb1176fb4c11a6f0a4f2550d9907d113df5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 20 Apr 2025 11:24:30 +0200 Subject: [PATCH 0828/2359] Backends: DX12: build fix for Clang. (#8582) --- backends/imgui_impl_dx12.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 202bac3b0..b6425cf52 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -535,7 +535,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return false; } - PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature"); + PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)(void*)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature"); if (D3D12SerializeRootSignatureFn == nullptr) return false; From bf0f586b69ec9f082164c8fe39068952beadf304 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Apr 2025 11:21:02 +0200 Subject: [PATCH 0829/2359] Platform IME: added ImGuiPlatformImeData::WantTextInput, ViewportId. Backends: SDL3: honor WantTextInput. (#8584, #7492, #6341) --- backends/imgui_impl_sdl3.cpp | 6 ++++-- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 4 +++- imgui.h | 12 +++++++----- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 8 +++++--- 6 files changed, 27 insertions(+), 13 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index c2dd81085..e4e64721a 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-04-22: IME: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. // 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) // 2025-03-30: Update for SDL3 api changes: Revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. @@ -150,7 +151,7 @@ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle; SDL_Window* window = SDL_GetWindowFromID(window_id); - if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != nullptr) + if ((!(data->WantVisible || data->WantTextInput) || bd->ImeWindow != window) && bd->ImeWindow != nullptr) { SDL_StopTextInput(bd->ImeWindow); bd->ImeWindow = nullptr; @@ -163,9 +164,10 @@ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view r.w = 1; r.h = (int)data->InputLineHeight; SDL_SetTextInputArea(window, &r, 0); - SDL_StartTextInput(window); bd->ImeWindow = window; } + if (data->WantVisible || data->WantTextInput) + SDL_StartTextInput(window); } // Not static to allow third-party code to use that if they want to (but undocumented) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 197fe9bb0..d78e8104f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -91,6 +91,10 @@ Other changes: would use a +1 offset instead of advancing to the next UTF-8 codepoint. (#8540) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) +- Platform IME: added ImGuiPlatformImeData::ViewportId info (backported from Docking branch). +- Platform IME: added ImGuiPlatformImeData::WantTextInput which might set independently + of WantVisible. This is set in the same structure because activating text input generally + requires providing a window to the backend. (#8584, #6341) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) @@ -99,6 +103,8 @@ Other changes: the same white-list as SDL_GetGlobalMouseState(). (#8561) [@vs49688] - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) [@Green-Sky] +- Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative + way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] - Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's diff --git a/imgui.cpp b/imgui.cpp index 90d4bbfa9..ad9132f23 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5362,7 +5362,7 @@ void ImGui::NewFrame() // Platform IME data: reset for the frame g.PlatformImeDataPrev = g.PlatformImeData; - g.PlatformImeData.WantVisible = false; + g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false; // Mouse wheel scrolling, scale UpdateMouseWheel(); @@ -5654,9 +5654,11 @@ void ImGui::EndFrame() if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) { IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y); + IM_ASSERT(ime_data->ViewportId == IMGUI_VIEWPORT_DEFAULT_ID); // master branch ImGuiViewport* viewport = GetMainViewport(); g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data); } + g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0; // Hide implicit/fallback "Debug" window if it hasn't been used g.WithinFrameScopeWithImplicitWindow = false; diff --git a/imgui.h b/imgui.h index 989ae5ebc..af72083e3 100644 --- a/imgui.h +++ b/imgui.h @@ -3626,14 +3626,16 @@ struct ImGuiPlatformIO void* Renderer_RenderState; }; -// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. +// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). struct ImGuiPlatformImeData { - bool WantVisible; // A widget wants the IME to be visible - ImVec2 InputPos; // Position of the input cursor - float InputLineHeight; // Line height + bool WantVisible; // A widget wants the IME to be visible. + bool WantTextInput; // A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. + ImVec2 InputPos; // Position of input cursor (for IME). + float InputLineHeight; // Line height (for IME). + ImGuiID ViewportId; // ID of platform window/viewport. - ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } + ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index 1d217553b..2c147e397 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2360,7 +2360,7 @@ struct ImGuiContext ImGuiTypingSelectState TypingSelectState; // State for GetTypingSelectRequest() // Platform support - ImGuiPlatformImeData PlatformImeData; // Data updated by current frame + ImGuiPlatformImeData PlatformImeData; // Data updated by current frame. Will be applied at end of the frame. For some backends, this is required to have WantVisible=true in order to receive text message. ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. // Settings @@ -2428,7 +2428,7 @@ struct ImGuiContext float FramerateSecPerFrameAccum; int WantCaptureMouseNextFrame; // Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. int WantCaptureKeyboardNextFrame; // " - int WantTextInputNextFrame; + int WantTextInputNextFrame; // Copied in EndFrame() from g.PlatformImeData.WanttextInput. Needs to be set for some backends (SDL3) to emit character inputs. ImVector TempBuffer; // Temporary text buffer char TempKeychordName[64]; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 984bf5f06..c0a34db34 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5161,8 +5161,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Otherwise request text input ahead for next frame. if (g.ActiveId == id && clear_active_id) ClearActiveID(); - else if (g.ActiveId == id) - g.WantTextInputNextFrame = 1; // Render frame if (!is_multiline) @@ -5343,11 +5341,15 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031) // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) - if (!is_readonly) + // This is required for some backends (SDL3) to start emitting character/text inputs. + // As per #6341, make sure we don't set that on the deactivating frame. + if (!is_readonly && g.ActiveId == id) { g.PlatformImeData.WantVisible = true; + g.PlatformImeData.WantTextInput = true; g.PlatformImeData.InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); g.PlatformImeData.InputLineHeight = g.FontSize; + g.PlatformImeData.ViewportId = window->Viewport->ID; } } } From 7c6ce12fa487c7684ac56be8e40c2a1c57c39602 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Apr 2025 11:24:02 +0200 Subject: [PATCH 0830/2359] Platform IME: minor amend to bf0f586 (#8584) --- imgui_widgets.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c0a34db34..6a6d1e6ad 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5345,11 +5345,12 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // As per #6341, make sure we don't set that on the deactivating frame. if (!is_readonly && g.ActiveId == id) { - g.PlatformImeData.WantVisible = true; - g.PlatformImeData.WantTextInput = true; - g.PlatformImeData.InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); - g.PlatformImeData.InputLineHeight = g.FontSize; - g.PlatformImeData.ViewportId = window->Viewport->ID; + ImGuiPlatformImeData* ime_data = &g.PlatformImeData; // (this is a public struct, passed to io.Platform_SetImeDataFn() handler) + ime_data->WantVisible = true; + ime_data->WantTextInput = true; + ime_data->InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); + ime_data->InputLineHeight = g.FontSize; + ime_data->ViewportId = window->Viewport->ID; } } } From dcf0d8cab68bcf90156077211740836d95d683ad Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Apr 2025 18:34:56 +0200 Subject: [PATCH 0831/2359] Tables: fixed TableHeader() eager vertical clipping of text. (#6236) --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d78e8104f..a3892a06b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,8 @@ Other changes: - The feature is unlikely to ever work properly when using a coarse clipper such as ImGuiListClipper. - TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. +- Tables: fixed TableHeader() eager vertical clipping of text which may be noticeable + with FramePadding.y was too small. (#6236) - Tabs: fixes small issues with how "..." ellipsis moved depending on visibility of Close Button or Unsaved Document marker. (#8387) - Nav: fixed assertion when holding gamepad FaceLeft/West button to open diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 077d54b14..6a84dba36 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3275,7 +3275,7 @@ 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, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, label, label_end, &label_size); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, &label_size); const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x); if (text_clipped && hovered && g.ActiveId == 0) From 6a42d6b339e0c86cdf0bce866bf390496155df69 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Apr 2025 14:39:59 +0200 Subject: [PATCH 0832/2359] Added wp TextAligned() TextAlignedV(), TextAlignedExV() to internal API. (#7024) --- imgui.h | 2 +- imgui_internal.h | 7 ++++++- imgui_widgets.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index af72083e3..64049bed6 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19193 +#define IMGUI_VERSION_NUM 19194 #define IMGUI_HAS_TABLE /* diff --git a/imgui_internal.h b/imgui_internal.h index 2c147e397..cc5c488ba 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3443,8 +3443,13 @@ namespace ImGui IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); - // Widgets + // Widgets: Text IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); + IMGUI_API void TextAligned(float align_x, const char* fmt, ...); // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) + IMGUI_API void TextAlignedV(float align_x, const char* fmt, va_list args); + IMGUI_API void TextAlignedExV(float align_x, float avail_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 ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6a6d1e6ad..6e19c22ed 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -339,6 +339,52 @@ void ImGui::TextWrappedV(const char* fmt, va_list args) PopTextWrapPos(); } +void ImGui::TextAligned(float align_x, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextAlignedV(align_x, fmt, args); + va_end(args); +} + +// align_x: 0.0f = left, 0.5f = center, 1.0f = right. +// FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) +void ImGui::TextAlignedV(float align_x, const char* fmt, va_list args) +{ + TextAlignedExV(align_x, GetContentRegionAvail().x, fmt, args); +} + +void ImGui::TextAlignedExV(float align_x, float avail_x, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const char* text, *text_end; + ImFormatStringToTempBufferV(&text, &text_end, fmt, args); + const ImVec2 text_size = CalcTextSize(text, text_end); + + ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + ImVec2 pos_max(pos.x + avail_x, window->ClipRect.Max.y); + ImVec2 size(ImMin(avail_x, text_size.x), text_size.y); + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, pos.x + text_size.x); + window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, pos.x + text_size.x); + if (align_x > 0.0f && text_size.x < avail_x) + { + pos.x += ImTrunc((avail_x - text_size.x) * align_x); + window->DC.CursorPos = pos; + } + RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size); + + const ImVec2 backup_max_pos = window->DC.CursorMaxPos; + ItemSize(size); + ItemAdd(ImRect(pos, pos + size), 0); + window->DC.CursorMaxPos.x = backup_max_pos.x; // Cancel out extending content size because right-aligned text would otherwise mess it up. + + if (avail_x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip)) + SetTooltip("%.*s", (int)(text_end - text), text); +} + void ImGui::LabelText(const char* label, const char* fmt, ...) { va_list args; From aed1bcc12c3260b0e4e202cfbb6625d2127fa6c0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Apr 2025 14:52:29 +0200 Subject: [PATCH 0833/2359] Rework TextAligned() api to take size input. (#7024) --- imgui_internal.h | 5 ++--- imgui_widgets.cpp | 26 +++++++++++++------------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index cc5c488ba..1c60ddf18 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3445,9 +3445,8 @@ namespace ImGui // Widgets: Text IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); - IMGUI_API void TextAligned(float align_x, const char* fmt, ...); // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) - IMGUI_API void TextAlignedV(float align_x, const char* fmt, va_list args); - IMGUI_API void TextAlignedExV(float align_x, float avail_x, const char* fmt, va_list args); + IMGUI_API void TextAligned(float align_x, float size_x, const char* fmt, ...); // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) + 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6e19c22ed..435a89b64 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -339,39 +339,39 @@ void ImGui::TextWrappedV(const char* fmt, va_list args) PopTextWrapPos(); } -void ImGui::TextAligned(float align_x, const char* fmt, ...) +void ImGui::TextAligned(float align_x, float size_x, const char* fmt, ...) { va_list args; va_start(args, fmt); - TextAlignedV(align_x, fmt, args); + TextAlignedV(align_x, size_x, fmt, args); va_end(args); } // align_x: 0.0f = left, 0.5f = center, 1.0f = right. +// size_x : 0.0f = shortcut for GetContentRegionAvail().x // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) -void ImGui::TextAlignedV(float align_x, const char* fmt, va_list args) -{ - TextAlignedExV(align_x, GetContentRegionAvail().x, fmt, args); -} - -void ImGui::TextAlignedExV(float align_x, float avail_x, const char* fmt, va_list args) +void ImGui::TextAlignedV(float align_x, float size_x, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + // ~CalcItemSize() + if (size_x <= 0.0f) + size_x = GetContentRegionAvail().x + size_x; // <-- Remember that size_x is negative here + const char* text, *text_end; ImFormatStringToTempBufferV(&text, &text_end, fmt, args); const ImVec2 text_size = CalcTextSize(text, text_end); ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); - ImVec2 pos_max(pos.x + avail_x, window->ClipRect.Max.y); - ImVec2 size(ImMin(avail_x, text_size.x), text_size.y); + ImVec2 pos_max(pos.x + size_x, window->ClipRect.Max.y); + ImVec2 size(ImMin(size_x, text_size.x), text_size.y); window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, pos.x + text_size.x); window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, pos.x + text_size.x); - if (align_x > 0.0f && text_size.x < avail_x) + if (align_x > 0.0f && text_size.x < size_x) { - pos.x += ImTrunc((avail_x - text_size.x) * align_x); + pos.x += ImTrunc((size_x - text_size.x) * align_x); window->DC.CursorPos = pos; } RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size); @@ -381,7 +381,7 @@ void ImGui::TextAlignedExV(float align_x, float avail_x, const char* fmt, va_lis ItemAdd(ImRect(pos, pos + size), 0); window->DC.CursorMaxPos.x = backup_max_pos.x; // Cancel out extending content size because right-aligned text would otherwise mess it up. - if (avail_x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip)) + if (size_x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip)) SetTooltip("%.*s", (int)(text_end - text), text); } From 0fc4967ebc6a2d40b7b048296ff5e0cc24f91f26 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Apr 2025 15:08:57 +0200 Subject: [PATCH 0834/2359] Rework TextAligned() api to fix issues with baseline alignment + use standard CalcItemSize(). (#7024) --- imgui_widgets.cpp | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 435a89b64..1204a4599 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -356,13 +356,10 @@ void ImGui::TextAlignedV(float align_x, float size_x, const char* fmt, va_list a if (window->SkipItems) return; - // ~CalcItemSize() - if (size_x <= 0.0f) - size_x = GetContentRegionAvail().x + size_x; // <-- Remember that size_x is negative here - const char* text, *text_end; ImFormatStringToTempBufferV(&text, &text_end, fmt, args); const ImVec2 text_size = CalcTextSize(text, text_end); + size_x = CalcItemSize(ImVec2(size_x, 0.0f), 0.0f, text_size.y).x; ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); ImVec2 pos_max(pos.x + size_x, window->ClipRect.Max.y); @@ -370,10 +367,7 @@ void ImGui::TextAlignedV(float align_x, float size_x, const char* fmt, va_list a window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, pos.x + text_size.x); window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, pos.x + text_size.x); if (align_x > 0.0f && text_size.x < size_x) - { pos.x += ImTrunc((size_x - text_size.x) * align_x); - window->DC.CursorPos = pos; - } RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size); const ImVec2 backup_max_pos = window->DC.CursorMaxPos; From 75964a9860d497ce3a4b0c482a093e664971466c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 24 Apr 2025 14:39:17 +0200 Subject: [PATCH 0835/2359] CI: run on ubuntu-latest. --- .github/workflows/build.yml | 6 +++--- .github/workflows/static-analysis.yml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f95ff43c8..86872d21c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -218,7 +218,7 @@ jobs: run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' Linux: - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -516,7 +516,7 @@ jobs: xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_ios CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO Emscripten: - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -557,7 +557,7 @@ jobs: cmake --build build Android: - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 69df5cdf8..53db04764 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -10,7 +10,7 @@ on: jobs: PVS-Studio: - runs-on: ubuntu-22.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: From cbb8edb0b775f0abba3ea16d73eaabcbac10fc33 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 26 Apr 2025 15:41:08 +0200 Subject: [PATCH 0836/2359] Tables: fixed an assert when combining Tables, Frozen Rows, Clipper and BeginMultiSelect() in a certain order. (#8595, #8250) The table->CurrentColumn != -1 test in BeginMultiSelect() was affected. It would have been possible to amend the test with table->IsInsideRow but this seems generally saner. Docs: fixed typo. (#8592) --- docs/CHANGELOG.txt | 2 ++ docs/README.md | 2 +- imgui_tables.cpp | 3 +++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a3892a06b..0f4418fd6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -78,6 +78,8 @@ Other changes: - TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. - Tables: fixed TableHeader() eager vertical clipping of text which may be noticeable with FramePadding.y was too small. (#6236) +- Tables: fixed an assert when combining Tables, Frozen Rows, Clipper and BeginMultiSelect() + in a certain order. (#8595, #8250) - Tabs: fixes small issues with how "..." ellipsis moved depending on visibility of Close Button or Unsaved Document marker. (#8387) - Nav: fixed assertion when holding gamepad FaceLeft/West button to open diff --git a/docs/README.md b/docs/README.md index 9b437311a..701016a6a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -120,7 +120,7 @@ See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/backends) backends without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more imgui_impl_xxxx files instead of rewriting them: this will be less work for you, and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so. -Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading a texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles, which is essentially what Backends are doing. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that: setting up a window and using backends. If you follow the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide it should in theory takes you less than an hour to integrate Dear ImGui. **Make sure to spend time reading the [FAQ](https://www.dearimgui.com/faq), comments, and the examples applications!** +Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading a texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles, which is essentially what Backends are doing. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that: setting up a window and using backends. If you follow the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide it should in theory take you less than an hour to integrate Dear ImGui. **Make sure to spend time reading the [FAQ](https://www.dearimgui.com/faq), comments, and the examples applications!** Officially maintained backends/bindings (in repository): - Renderers: DirectX9, DirectX10, DirectX11, DirectX12, Metal, OpenGL/ES/ES2, SDL_GPU, SDL_Renderer2/3, Vulkan, WebGPU. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 6a84dba36..e1813110d 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1953,7 +1953,10 @@ void ImGui::TableEndRow(ImGuiTable* table) IM_ASSERT(table->IsInsideRow); if (table->CurrentColumn != -1) + { TableEndCell(table); + table->CurrentColumn = -1; + } // Logging if (g.LogEnabled) From b3c96bde8c4e2ce0465d4c02d80f3d8173f2164c Mon Sep 17 00:00:00 2001 From: Ryan Jensen Date: Sat, 26 Apr 2025 09:10:00 -0500 Subject: [PATCH 0837/2359] Demo: use IM_ARRAYSIZE more consistently InputText calls in demo window (#8596) --- imgui_demo.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index fbf65aa1d..c7d3a31bc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3659,13 +3659,13 @@ static void DemoWindowWidgetsTextInput() } }; - static char buf1[32] = ""; ImGui::InputText("default", buf1, 32); - static char buf2[32] = ""; ImGui::InputText("decimal", buf2, 32, ImGuiInputTextFlags_CharsDecimal); - static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, 32, ImGuiInputTextFlags_CharsUppercase); - static char buf5[32] = ""; ImGui::InputText("no blank", buf5, 32, ImGuiInputTextFlags_CharsNoBlank); - static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. - static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. + static char buf1[32] = ""; ImGui::InputText("default", buf1, IM_ARRAYSIZE(buf1)); + static char buf2[32] = ""; ImGui::InputText("decimal", buf2, IM_ARRAYSIZE(buf2), ImGuiInputTextFlags_CharsDecimal); + static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, IM_ARRAYSIZE(buf3), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, IM_ARRAYSIZE(buf4), ImGuiInputTextFlags_CharsUppercase); + static char buf5[32] = ""; ImGui::InputText("no blank", buf5, IM_ARRAYSIZE(buf5), ImGuiInputTextFlags_CharsNoBlank); + static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, IM_ARRAYSIZE(buf6), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. + static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, IM_ARRAYSIZE(buf7), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. ImGui::TreePop(); } @@ -3721,20 +3721,20 @@ static void DemoWindowWidgetsTextInput() } }; static char buf1[64]; - ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); + ImGui::InputText("Completion", buf1, IM_ARRAYSIZE(buf1), ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); ImGui::SameLine(); HelpMarker( "Here we append \"..\" each time Tab is pressed. " "See 'Examples>Console' for a more meaningful demonstration of using this callback."); static char buf2[64]; - ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); + ImGui::InputText("History", buf2, IM_ARRAYSIZE(buf2), ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); ImGui::SameLine(); HelpMarker( "Here we replace and select text each time Up/Down are pressed. " "See 'Examples>Console' for a more meaningful demonstration of using this callback."); static char buf3[64]; static int edit_count = 0; - ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); + ImGui::InputText("Edit", buf3, IM_ARRAYSIZE(buf3), ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); ImGui::SameLine(); HelpMarker( "Here we toggle the casing of the first character on every edit + count edits."); ImGui::SameLine(); ImGui::Text("(%d)", edit_count); From 75ddd9a6cd85db455ed2ee5ea8f4dfe1a9f96c7a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 28 Apr 2025 23:10:29 +0200 Subject: [PATCH 0838/2359] Backends: SDLGPU3: added support for ImDrawCallback_ResetRenderState. (#8599) --- backends/imgui_impl_sdlgpu3.cpp | 8 +++++++- docs/CHANGELOG.txt | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index f3a7adc85..b277512cc 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -21,6 +21,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-04-28: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2025-03-30: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. // 2025-03-21: Fixed typo in function name Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData(). // 2025-01-16: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device. @@ -232,7 +233,12 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback != nullptr) { - pcmd->UserCallback(draw_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplSDLGPU3_SetupRenderState(draw_data, pipeline, command_buffer, render_pass, fd, fb_width, fb_height); + else + pcmd->UserCallback(draw_list, pcmd); } else { diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0f4418fd6..e52537692 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -111,6 +111,7 @@ Other changes: way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] +- Backends: SDLGPU3: added support for ImDrawCallback_ResetRenderState. (#8599) - Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) From 3f8033324fbe5dbd3a47e91b02556c91b7d6ce1f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Apr 2025 11:10:54 +0200 Subject: [PATCH 0839/2359] Demo: Dual List Box: fix sorting function, in theory should return 0 when equal. (#8601) --- imgui_demo.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c7d3a31bc..24ea67fa2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2491,7 +2491,7 @@ struct ExampleDualListBox { const int* a = (const int*)lhs; const int* b = (const int*)rhs; - return (*a - *b) > 0 ? +1 : -1; + return (*a - *b); } void SortItems(int n) { @@ -2499,7 +2499,7 @@ struct ExampleDualListBox } void Show() { - //ImGui::Checkbox("Sorted", &OptKeepSorted); + //if (ImGui::Checkbox("Sorted", &OptKeepSorted) && OptKeepSorted) { SortItems(0); SortItems(1); } if (ImGui::BeginTable("split", 3, ImGuiTableFlags_None)) { ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Left side From 20066a8964a069b51de24eb0fe412d8539448266 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Apr 2025 11:30:06 +0200 Subject: [PATCH 0840/2359] Examples: DirectX12+Win32: also test for IsIconic() for sleeping since we don't seem to get a DXGI_STATUS_OCCLUDED signal when minimized. (#8603) Amend ec1d2be96f. (#2496, #3907, #6308, #7615) This technically prevents multi-viewports from working with io.ConfigViewportsNoDefaultParent=true but this is a more fringe case to handle for our example app, better tradeoff imho to use IsIconic(). --- docs/CHANGELOG.txt | 2 ++ examples/example_win32_directx12/main.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e52537692..852380a8c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -115,6 +115,8 @@ Other changes: - Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) +- Examples: DirectX12+Win32: also test for IsIconic() for sleeping since we don't seem to + get a DXGI_STATUS_OCCLUDED signal when minimized. (#8603) [@dooann] ----------------------------------------------------------------------- diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 5f6cd51dd..2df2751c5 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -196,7 +196,7 @@ int main(int, char**) break; // Handle window screen locked - if (g_SwapChainOccluded && g_pSwapChain->Present(0, DXGI_PRESENT_TEST) == DXGI_STATUS_OCCLUDED) + if ((g_SwapChainOccluded && g_pSwapChain->Present(0, DXGI_PRESENT_TEST) == DXGI_STATUS_OCCLUDED) || ::IsIconic(hwnd)) { ::Sleep(10); continue; From c0dfd65d6790b9b96872b64fa232f1fa80fcd3b3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Apr 2025 16:23:58 +0200 Subject: [PATCH 0841/2359] Backends: Win32: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) would fail to claim it again the next subsequent click. (#8594) --- backends/imgui_impl_win32.cpp | 6 +++++- docs/CHANGELOG.txt | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index ab7c8ab9f..cd5e2dbf2 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-04-30: Inputs: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) would fail to claim it again the next subsequent click. (#8594) // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) @@ -682,7 +683,10 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPA if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; } if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; } if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } - if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr) + HWND hwnd_with_capture = ::GetCapture(); + if (bd->MouseButtonsDown != 0 && hwnd_with_capture != hwnd) // Did we externally lost capture? + bd->MouseButtonsDown = 0; + if (bd->MouseButtonsDown == 0 && hwnd_with_capture == nullptr) ::SetCapture(hwnd); // Allow us to read mouse coordinates when dragging mouse outside of our window bounds. bd->MouseButtonsDown |= 1 << button; io.AddMouseSourceEvent(mouse_source); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 852380a8c..9a221b949 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -100,6 +100,8 @@ Other changes: of WantVisible. This is set in the same structure because activating text input generally requires providing a window to the backend. (#8584, #6341) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] +- Backends: Win32: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) + would fail to claim it again the next subsequent click. (#8594) - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) - Backends: SDL2, SDL3: don't attempt to call SDL_CaptureMouse() on drivers where we don't From e3bfaab3f70755af84f47300dbe448d5a52dcd7a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 May 2025 17:12:06 +0200 Subject: [PATCH 0842/2359] Examples: update xcode projects. --- .gitignore | 1 + .../project.pbxproj | 39 ++++++++++++++----- .../project.pbxproj | 4 +- 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index c920ba649..5a5c8cda3 100644 --- a/.gitignore +++ b/.gitignore @@ -53,6 +53,7 @@ cmake-build-* .vscode ## Unix executables from our example Makefiles +examples/example_apple_metal/example_apple_metal examples/example_glfw_metal/example_glfw_metal examples/example_glfw_opengl2/example_glfw_opengl2 examples/example_glfw_opengl3/example_glfw_opengl3 diff --git a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj index 5f657eab9..bf3c80d6e 100644 --- a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj +++ b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 48; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -209,7 +209,8 @@ 8307E7B620E9F9C700473790 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 1200; + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1530; ORGANIZATIONNAME = "Warren Moore"; TargetAttributes = { 8307E7C320E9F9C900473790 = { @@ -327,9 +328,11 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -383,9 +386,11 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -405,8 +410,11 @@ CODE_SIGN_STYLE = Automatic; DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = "$(SRCROOT)/iOS/Info-iOS.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "org.imgui.example.apple-metal-ios"; PRODUCT_NAME = example_apple_metal; SDKROOT = iphoneos; @@ -422,8 +430,11 @@ CODE_SIGN_STYLE = Automatic; DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = "$(SRCROOT)/iOS/Info-iOS.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = "org.imgui.example.apple-metal-ios"; PRODUCT_NAME = example_apple_metal; SDKROOT = iphoneos; @@ -439,10 +450,14 @@ CODE_SIGN_IDENTITY = "-"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = "$(SRCROOT)/macOS/Info-macOS.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.12; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; PRODUCT_BUNDLE_IDENTIFIER = "org.imgui.example.apple-metal-macos"; PRODUCT_NAME = example_apple_metal; SDKROOT = macosx; @@ -456,10 +471,14 @@ CODE_SIGN_IDENTITY = "-"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = "$(SRCROOT)/macOS/Info-macOS.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.12; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; PRODUCT_BUNDLE_IDENTIFIER = "org.imgui.example.apple-metal-macos"; PRODUCT_NAME = example_apple_metal; SDKROOT = macosx; diff --git a/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj b/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj index a168373d4..9770e4396 100644 --- a/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj +++ b/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj @@ -289,7 +289,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - MACOSX_DEPLOYMENT_TARGET = 10.12; + MACOSX_DEPLOYMENT_TARGET = 10.13; PRODUCT_NAME = "$(TARGET_NAME)"; USER_HEADER_SEARCH_PATHS = ../..; }; @@ -299,7 +299,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - MACOSX_DEPLOYMENT_TARGET = 10.12; + MACOSX_DEPLOYMENT_TARGET = 10.13; PRODUCT_NAME = "$(TARGET_NAME)"; USER_HEADER_SEARCH_PATHS = ../..; }; From c5e2bb7cd1c577f701cb67a2e04d319b5ecacc9d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 May 2025 19:19:33 +0200 Subject: [PATCH 0843/2359] Backends: SDLGPU3: Fixed creating atlas texture earlier than other backends. # Conflicts: # backends/imgui_impl_sdlgpu3.cpp --- backends/imgui_impl_sdlgpu3.cpp | 4 ++-- docs/CHANGELOG.txt | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index b277512cc..4bcc5bdfc 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -589,8 +589,6 @@ bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info) bd->InitInfo = *info; - ImGui_ImplSDLGPU3_CreateDeviceObjects(); - return true; } @@ -612,6 +610,8 @@ void ImGui_ImplSDLGPU3_NewFrame() ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLGPU3_Init()?"); + if (!bd->FontSampler) + ImGui_ImplSDLGPU3_CreateDeviceObjects(); if (!bd->FontTexture) ImGui_ImplSDLGPU3_CreateFontsTexture(); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9a221b949..ceb7bfcf7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -111,6 +111,8 @@ Other changes: memory ownership change. (#8530, #7801) [@Green-Sky] - Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) +- Backends: SDLGPU3: Fixed creating atlas texture earlier than other backends, preventing + to load fonts between the Init and NewFrames calls. - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] - Backends: SDLGPU3: added support for ImDrawCallback_ResetRenderState. (#8599) From afd3a36f6989d09fa785bb27ffb9537c23333ea9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 May 2025 19:39:56 +0200 Subject: [PATCH 0844/2359] Demo: added basic Fonts section under main demo (same as Metrics one) for visibility. --- imgui.cpp | 24 ++++++++++++++++++++---- imgui_demo.cpp | 20 ++++++++++++++++++++ imgui_internal.h | 1 + 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ad9132f23..cb36ac536 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15491,6 +15491,18 @@ static void MetricsHelpMarker(const char* desc) // [DEBUG] List fonts in a font atlas and display its texture void ImGui::ShowFontAtlas(ImFontAtlas* atlas) { + ImGuiContext& g = *GImGui; + + Text("Read "); + SameLine(0, 0); + TextLinkOpenURL("https://www.dearimgui.com/faq/"); + SameLine(0, 0); + Text(" for details on font loading."); + + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + Checkbox("Show font preview", &cfg->ShowFontPreview); + + // Font list for (ImFont* font : atlas->Fonts) { PushID(font); @@ -15499,7 +15511,6 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) } if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) { - ImGuiContext& g = *GImGui; PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); ImageWithBg(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); PopStyleVar(); @@ -16290,6 +16301,8 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co // [DEBUG] Display details for a single font, called by ShowStyleEditor(). void ImGui::DebugNodeFont(ImFont* font) { + ImGuiContext& g = *GImGui; + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; bool opened = TreeNode(font, "Font: \"%s\": %.2f px, %d glyphs, %d sources(s)", font->Sources ? font->Sources[0].Name : "", font->FontSize, font->Glyphs.Size, font->SourcesCount); @@ -16297,9 +16310,12 @@ void ImGui::DebugNodeFont(ImFont* font) if (!opened) Indent(); Indent(); - PushFont(font); - Text("The quick brown fox jumps over the lazy dog"); - PopFont(); + if (cfg->ShowFontPreview) + { + PushFont(font); + Text("The quick brown fox jumps over the lazy dog"); + PopFont(); + } if (!opened) { Unindent(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 24ea67fa2..091a52569 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -82,6 +82,7 @@ Index of this file: // [SECTION] DemoWindowWidgetsDisableBlocks() // [SECTION] DemoWindowWidgetsDragAndDrop() // [SECTION] DemoWindowWidgetsDragsAndSliders() +// [SECTION] DemoWindowWidgetsFonts() // [SECTION] DemoWindowWidgetsImages() // [SECTION] DemoWindowWidgetsListBoxes() // [SECTION] DemoWindowWidgetsMultiComponents() @@ -1719,6 +1720,24 @@ static void DemoWindowWidgetsDragsAndSliders() } } +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsFonts() +//----------------------------------------------------------------------------- + +// Forward declare ShowFontAtlas() which isn't worth putting in public API yet +namespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); } + +static void DemoWindowWidgetsFonts() +{ + IMGUI_DEMO_MARKER("Widgets/Fonts"); + if (ImGui::TreeNode("Fonts")) + { + ImFontAtlas* atlas = ImGui::GetIO().Fonts; + ImGui::ShowFontAtlas(atlas); + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsImages() //----------------------------------------------------------------------------- @@ -4182,6 +4201,7 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsDragAndDrop(); DemoWindowWidgetsDragsAndSliders(); + DemoWindowWidgetsFonts(); DemoWindowWidgetsImages(); DemoWindowWidgetsListBoxes(); DemoWindowWidgetsMultiComponents(); diff --git a/imgui_internal.h b/imgui_internal.h index 1c60ddf18..996eb82a2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2020,6 +2020,7 @@ struct ImGuiMetricsConfig int ShowTablesRectsType = -1; int HighlightMonitorIdx = -1; ImGuiID HighlightViewportID = 0; + bool ShowFontPreview = true; }; struct ImGuiStackLevelInfo From 46235e91f602b663f9b0f1f1a300177b61b193f5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 May 2025 20:04:12 +0200 Subject: [PATCH 0845/2359] Examples: SDL3: specify SDL_WINDOW_HIGH_PIXEL_DENSITY and make centering consistent + call SDL_RenderScale(). --- examples/example_sdl3_opengl3/main.cpp | 4 ++-- examples/example_sdl3_sdlgpu3/main.cpp | 5 ++++- examples/example_sdl3_sdlrenderer3/main.cpp | 4 ++-- examples/example_sdl3_vulkan/main.cpp | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index d8666061d..46eeb59b5 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -68,14 +68,13 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); - Uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; + SDL_WindowFlags window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", 1280, 720, window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); return -1; } - SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_GLContext gl_context = SDL_GL_CreateContext(window); if (gl_context == nullptr) { @@ -85,6 +84,7 @@ int main(int, char**) SDL_GL_MakeCurrent(window, gl_context); SDL_GL_SetSwapInterval(1); // Enable vsync + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_ShowWindow(window); // Setup Dear ImGui context diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 3deeeafd5..4178f94b5 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -34,12 +34,15 @@ int main(int, char**) } // Create SDL window graphics context - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", 1280, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY); + SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", 1280, 720, window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); return -1; } + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + SDL_ShowWindow(window); // Create GPU Device SDL_GPUDevice* gpu_device = SDL_CreateGPUDevice(SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_DXIL | SDL_GPU_SHADERFORMAT_METALLIB,true,nullptr); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index ad05a0f91..9a2732b45 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -32,7 +32,7 @@ int main(int, char**) } // Create window with SDL_Renderer graphics context - Uint32 window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; + SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", 1280, 720, window_flags); if (window == nullptr) { @@ -164,7 +164,7 @@ int main(int, char**) // Rendering ImGui::Render(); - //SDL_RenderSetScale(renderer, io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); + SDL_SetRenderScale(renderer, io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); SDL_SetRenderDrawColorFloat(renderer, clear_color.x, clear_color.y, clear_color.z, clear_color.w); SDL_RenderClear(renderer); ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData(), renderer); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 618fd34a8..183965a84 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -353,7 +353,7 @@ int main(int, char**) } // Create window with Vulkan graphics context - SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_HIDDEN); + SDL_WindowFlags window_flags = SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Vulkan example", 1280, 720, window_flags); if (window == nullptr) { From d1dc2a329893cdfe9bf9b7c20602b0a77d42c9ad Mon Sep 17 00:00:00 2001 From: ChrisTom-94 Date: Wed, 7 May 2025 11:47:58 +0200 Subject: [PATCH 0846/2359] Backends: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + try both non-KHR and KHR versions. (#8600, #8326, #8365) # Conflicts: # backends/imgui_impl_vulkan.cpp # docs/CHANGELOG.txt --- backends/imgui_impl_vulkan.cpp | 17 +++++++++++++---- docs/CHANGELOG.txt | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 398b81f20..2cebb6c25 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -26,6 +26,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-05-07: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + try both non-KHR and KHR versions. (#8600, #8326, #8365) // 2025-04-07: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) // 2025-02-14: *BREAKING CHANGE*: Added uint32_t api_version to ImGui_ImplVulkan_LoadFunctions(). // 2025-02-13: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. Default to header version if unspecified. Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" (without -KHR suffix) on API 1.3. (#8326) @@ -1085,9 +1086,17 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING static void ImGui_ImplVulkan_LoadDynamicRenderingFunctions(uint32_t api_version, PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) { - // Manually load those two (see #5446, #8326, #8365) - ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func(api_version < VK_API_VERSION_1_3 ? "vkCmdBeginRenderingKHR" : "vkCmdBeginRendering", user_data)); - ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func(api_version < VK_API_VERSION_1_3 ? "vkCmdEndRenderingKHR" : "vkCmdEndRendering", user_data)); + // Manually load those two (see #5446, #8326, #8365, #8600) + // - Try loading core (non-KHR) versions first (this will work for Vulkan 1.3+ and the device supports dynamic rendering) + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func("vkCmdBeginRendering", user_data)); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func("vkCmdEndRendering", user_data)); + + // - Fallback to KHR versions if core not available (this will work if KHR extension is available and enabled and also the device supports dynamic rendering) + if (ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR == nullptr || ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR == nullptr) + { + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func("vkCmdBeginRenderingKHR", user_data)); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func("vkCmdEndRenderingKHR", user_data)); + } } #endif @@ -1142,7 +1151,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) { #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #ifndef IMGUI_IMPL_VULKAN_USE_LOADER - ImGui_ImplVulkan_LoadDynamicRenderingFunctions(info->ApiVersion, [](const char* function_name, void* user_data) { return vkGetInstanceProcAddr((VkInstance)user_data, function_name); }, (void*)info->Instance); + ImGui_ImplVulkan_LoadDynamicRenderingFunctions(info->ApiVersion, [](const char* function_name, void* user_data) { return vkGetDeviceProcAddr((VkDevice)user_data, function_name); }, (void*)info->Device); #endif IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR != nullptr); IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR != nullptr); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ceb7bfcf7..2ec521434 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -119,9 +119,28 @@ Other changes: - Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) +- Backends: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + + try both non-KHR and KHR versions. (#8600, #8326, #8365) [@ChrisTom-94] - Examples: DirectX12+Win32: also test for IsIconic() for sleeping since we don't seem to get a DXGI_STATUS_OCCLUDED signal when minimized. (#8603) [@dooann] +Docking+Viewports Branch: + +- Backends: Win32: Viewports: fixed an issue when closing a window from + the OS close button (with io.ConfigViewportsNoDecoration=false) while + user code is discarding the 'bool *p_open=false output' from Begin(). + Because we allowed the Win32 window to close early, Windows destroyed + it and our imgui window became not visible even though user code was + still submitting it. +- Backends: SDLGPU3 for SDL3: added multi-viewport support. (#8573) [@Lekoopapaul] +- Backends: SDL2, SDL3: revert updating monitors and work areas info every + frame. Only do it on Windows to detect task-bar resize until we get an + adequate event for it. (#8415, #8558) +- Backends: SDL3: macOS: Fixed secondary-viewports not appearing on a different + monitor than the main viewport. Because SDL_SetWindowParent() seems to restrict it. +- Backends: GLFW: Disable multi-viewports under Wayland (require GLFW 3.4). (#8587) +>>>>>>> 6f2d429592 (Backends: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + try both non-KHR and KHR versions. (#8600, #8326, #8365)) + ----------------------------------------------------------------------- VERSION 1.91.9b (Released 2025-03-17) From 64a5e274860ccf3771d35df1487812cdd790f0d0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 May 2025 14:22:19 +0200 Subject: [PATCH 0847/2359] Docs: bad merge error. --- docs/CHANGELOG.txt | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2ec521434..ff5a8b90a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -124,23 +124,6 @@ Other changes: - Examples: DirectX12+Win32: also test for IsIconic() for sleeping since we don't seem to get a DXGI_STATUS_OCCLUDED signal when minimized. (#8603) [@dooann] -Docking+Viewports Branch: - -- Backends: Win32: Viewports: fixed an issue when closing a window from - the OS close button (with io.ConfigViewportsNoDecoration=false) while - user code is discarding the 'bool *p_open=false output' from Begin(). - Because we allowed the Win32 window to close early, Windows destroyed - it and our imgui window became not visible even though user code was - still submitting it. -- Backends: SDLGPU3 for SDL3: added multi-viewport support. (#8573) [@Lekoopapaul] -- Backends: SDL2, SDL3: revert updating monitors and work areas info every - frame. Only do it on Windows to detect task-bar resize until we get an - adequate event for it. (#8415, #8558) -- Backends: SDL3: macOS: Fixed secondary-viewports not appearing on a different - monitor than the main viewport. Because SDL_SetWindowParent() seems to restrict it. -- Backends: GLFW: Disable multi-viewports under Wayland (require GLFW 3.4). (#8587) ->>>>>>> 6f2d429592 (Backends: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + try both non-KHR and KHR versions. (#8600, #8326, #8365)) - ----------------------------------------------------------------------- VERSION 1.91.9b (Released 2025-03-17) From bbc89b6391a0f89dc48c8c223b221820a3feceec Mon Sep 17 00:00:00 2001 From: ChrisTom-94 Date: Wed, 7 May 2025 15:19:45 +0200 Subject: [PATCH 0848/2359] Backends: Vulkan: fixed validation errors during window detach in multi-viewport mode. (#8600, #8176) --- backends/imgui_impl_vulkan.cpp | 79 ++++++++++++++++++++++++++++++++++ docs/CHANGELOG.txt | 3 ++ 2 files changed, 82 insertions(+) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 2cebb6c25..78d092217 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -26,6 +26,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-05-07- Vulkan: Fixed validation errors during window detach in multi-viewport mode. (#8600, #8176) // 2025-05-07: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + try both non-KHR and KHR versions. (#8600, #8326, #8365) // 2025-04-07: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) // 2025-02-14: *BREAKING CHANGE*: Added uint32_t api_version to ImGui_ImplVulkan_LoadFunctions(). @@ -1086,6 +1087,8 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING static void ImGui_ImplVulkan_LoadDynamicRenderingFunctions(uint32_t api_version, PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) { + IM_UNUSED(api_version); + // Manually load those two (see #5446, #8326, #8365, #8600) // - Try loading core (non-KHR) versions first (this will work for Vulkan 1.3+ and the device supports dynamic rendering) ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func("vkCmdBeginRendering", user_data)); @@ -1667,6 +1670,82 @@ void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevic (void)instance; ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); 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; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + 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 ff5a8b90a..9074f906c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -121,6 +121,9 @@ Other changes: specifying a pointer to data that gets out of scope. (#8282) - Backends: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + try both non-KHR and KHR versions. (#8600, #8326, #8365) [@ChrisTom-94] +- Backends: Vulkan: fixed validation errors in window create/resize helpers used by examples + and by multi-viewports implementation, which would typically trigger errors while detaching + secondary viewports. (#8600, #8176) [@ChrisTom-94] - Examples: DirectX12+Win32: also test for IsIconic() for sleeping since we don't seem to get a DXGI_STATUS_OCCLUDED signal when minimized. (#8603) [@dooann] From bf68040dc592f9eaf9abc2c268db5d97493325b0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 May 2025 15:42:23 +0200 Subject: [PATCH 0849/2359] Backends: Vulkan: fixed build with VK_NO_PROTOTYPES. Amend bbc89b6 (#8600) --- backends/imgui_impl_vulkan.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 78d092217..10648c3a4 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -177,6 +177,7 @@ static bool g_FunctionsLoaded = true; IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetBufferMemoryRequirements) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetDeviceQueue) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetImageMemoryRequirements) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceProperties) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceMemoryProperties) \ @@ -189,8 +190,10 @@ static bool g_FunctionsLoaded = true; IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueSubmit) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueWaitIdle) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkResetCommandPool) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkResetFences) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkUnmapMemory) \ - IMGUI_VULKAN_FUNC_MAP_MACRO(vkUpdateDescriptorSets) + IMGUI_VULKAN_FUNC_MAP_MACRO(vkUpdateDescriptorSets) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkWaitForFences) // Define function pointers #define IMGUI_VULKAN_FUNC_DEF(func) static PFN_##func func; From ba513ba804c87635f7bcb3a054a463598a0a332d Mon Sep 17 00:00:00 2001 From: WSSDude <41929176+WSSDude@users.noreply.github.com> Date: Wed, 19 Feb 2025 14:00:06 +0100 Subject: [PATCH 0850/2359] Backends: DX10, DX11, DX12: honor FramebufferScale. (#8412) # Conflicts: # backends/imgui_impl_dx11.cpp # backends/imgui_impl_dx12.cpp --- backends/imgui_impl_dx10.cpp | 10 ++++++---- backends/imgui_impl_dx11.cpp | 10 ++++++---- backends/imgui_impl_dx12.cpp | 10 ++++++---- docs/CHANGELOG.txt | 3 +++ 4 files changed, 21 insertions(+), 12 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 801983211..dd06e0e7f 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-05-07: DirectX10: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-01-06: DirectX10: Expose selected render state in ImGui_ImplDX10_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. @@ -88,8 +89,8 @@ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* // Setup viewport D3D10_VIEWPORT vp = {}; - vp.Width = (UINT)draw_data->DisplaySize.x; - vp.Height = (UINT)draw_data->DisplaySize.y; + vp.Width = (UINT)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + vp.Height = (UINT)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0; @@ -246,6 +247,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) int global_vtx_offset = 0; int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; + ImVec2 clip_scale = draw_data->FramebufferScale; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* draw_list = draw_data->CmdLists[n]; @@ -264,8 +266,8 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) else { // Project scissor/clipping rectangles into framebuffer space - ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); - ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index 9f3958881..f6a7f35f6 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -16,6 +16,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-05-07: DirectX11: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-01-06: DirectX11: Expose VertexConstantBuffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handler. // 2024-10-07: DirectX11: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-10-07: DirectX11: Expose selected render state in ImGui_ImplDX11_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. @@ -91,8 +92,8 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC // Setup viewport D3D11_VIEWPORT vp = {}; - vp.Width = draw_data->DisplaySize.x; - vp.Height = draw_data->DisplaySize.y; + vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x; + vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0; @@ -260,6 +261,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) int global_idx_offset = 0; int global_vtx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; + ImVec2 clip_scale = draw_data->FramebufferScale; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* draw_list = draw_data->CmdLists[n]; @@ -278,8 +280,8 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) else { // Project scissor/clipping rectangles into framebuffer space - ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); - ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index b6425cf52..84ec37f49 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -19,6 +19,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-05-07: DirectX12: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-02-24: DirectX12: Fixed an issue where ImGui_ImplDX12_Init() signature change from 2024-11-15 combined with change from 2025-01-15 made legacy ImGui_ImplDX12_Init() crash. (#8429) // 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat. @@ -138,8 +139,8 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic // Setup viewport D3D12_VIEWPORT vp = {}; - vp.Width = draw_data->DisplaySize.x; - vp.Height = draw_data->DisplaySize.y; + vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x; + vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0.0f; @@ -274,6 +275,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL int global_vtx_offset = 0; int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; + ImVec2 clip_scale = draw_data->FramebufferScale; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* draw_list = draw_data->CmdLists[n]; @@ -292,8 +294,8 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL else { // Project scissor/clipping rectangles into framebuffer space - ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); - ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9074f906c..4c6dfe706 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -116,6 +116,9 @@ Other changes: - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] - Backends: SDLGPU3: added support for ImDrawCallback_ResetRenderState. (#8599) +- Backends: DirectX10, DirectX11, DirectX12: Honor FramebufferScale to allow for custom + platform backends and experiments using it (consistently with other renderer backends, + even though in normal condition it is not set under Windows). (#8412) [@WSSDude] - Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) From f484af34c2014e98a64410e6cd81e1a5ab434bfd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 May 2025 18:05:05 +0200 Subject: [PATCH 0851/2359] Font: rename ImFont::AddRemapChar() parameters for clarity. (#609) --- imgui.h | 2 +- imgui_draw.cpp | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 64049bed6..b9b8bf6ad 100644 --- a/imgui.h +++ b/imgui.h @@ -3540,7 +3540,7 @@ struct ImFont IMGUI_API void ClearOutputData(); IMGUI_API void GrowIndex(int new_size); IMGUI_API void AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); - IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. + IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst);// , bool overwrite_dst = true); // Makes 'from_codepoint' character points to 'to_codepoint' character. Currently needs to be called AFTER fonts have been built. IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 13130a242..dbc659d25 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3885,19 +3885,19 @@ void ImFont::AddGlyph(const ImFontConfig* src, ImWchar codepoint, float x0, floa MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad); } -void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) +void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst) { IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. unsigned int index_size = (unsigned int)IndexLookup.Size; - if (dst < index_size && IndexLookup.Data[dst] == (ImU16)-1 && !overwrite_dst) // 'dst' already exists + if (from_codepoint < index_size && IndexLookup.Data[from_codepoint] == (ImU16)-1 && !overwrite_dst) // 'from_codepoint' already exists return; - if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op + if (to_codepoint >= index_size && from_codepoint >= index_size) // both 'from_codepoint' and 'to_codepoint' don't exist -> no-op return; - GrowIndex(dst + 1); - IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImU16)-1; - IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f; + GrowIndex(from_codepoint + 1); + IndexLookup[from_codepoint] = (to_codepoint < index_size) ? IndexLookup.Data[to_codepoint] : (ImU16)-1; + IndexAdvanceX[from_codepoint] = (to_codepoint < index_size) ? IndexAdvanceX.Data[to_codepoint] : 1.0f; } // Find glyph, return fallback if missing From b9ac32a0d5011db31f40f639f99b8db30a4848b6 Mon Sep 17 00:00:00 2001 From: tamas-rabel Date: Sun, 11 May 2025 23:04:44 +0100 Subject: [PATCH 0852/2359] Backends: DirectX12: Make sure texture sampling in the dx12 backend is not limited to the highest mip. (#8631) --- backends/imgui_impl_dx12.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 84ec37f49..a373e8eec 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -499,7 +499,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; staticSampler.MinLOD = 0.f; - staticSampler.MaxLOD = 0.f; + staticSampler.MaxLOD = D3D12_FLOAT32_MAX; staticSampler.ShaderRegister = 0; staticSampler.RegisterSpace = 0; staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; From 4a6ba9539216c5cd78696e4b90a665709aa275b9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 May 2025 19:19:23 +0200 Subject: [PATCH 0853/2359] Backends: SDL3: Comments (#6146) --- backends/imgui_impl_sdl3.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index e4e64721a..cacce7e10 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -782,7 +782,7 @@ void ImGui_ImplSDL3_NewFrame() if (w > 0 && h > 0) io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); - // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) + // Setup time step (we could also use SDL_GetTicksNS() available since SDL3) // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); From 08689c51a9c9ff9eea44b5bf0b0ae11242487d1d Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 13 May 2025 15:48:00 +0200 Subject: [PATCH 0854/2359] Backends: GLFW, SDL2, SDL3: include GLFW/SDL version number in io.BackendPlatformName. # Conflicts: # backends/imgui_impl_sdl2.cpp # backends/imgui_impl_sdl3.cpp --- backends/imgui_impl_glfw.cpp | 5 ++++- backends/imgui_impl_sdl2.cpp | 16 +++++++++++++--- backends/imgui_impl_sdl3.cpp | 8 +++++++- docs/CHANGELOG.txt | 1 + 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 6beb97f6c..ba7569970 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -117,6 +117,7 @@ #ifndef _WIN32 #include // for usleep() #endif +#include // for snprintf() #ifdef __EMSCRIPTEN__ #include @@ -157,6 +158,7 @@ struct ImGui_ImplGlfw_Data ImVec2 LastValidMousePos; bool InstalledCallbacks; bool CallbacksChainForAllWindows; + char BackendPlatformName[32]; #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 const char* CanvasSelector; #endif @@ -593,8 +595,9 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Setup backend capabilities flags ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)(); + snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_glfw (%d)", GLFW_VERSION_COMBINED); io.BackendPlatformUserData = (void*)bd; - io.BackendPlatformName = "imgui_impl_glfw"; + io.BackendPlatformName = bd->BackendPlatformName; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index b2dacc48e..3d82bc348 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -109,6 +109,7 @@ // SDL #include #include +#include // for snprintf() #ifdef __APPLE__ #include #endif @@ -135,6 +136,7 @@ struct ImGui_ImplSDL2_Data SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; + char BackendPlatformName[40]; // Mouse handling Uint32 MouseWindowID; @@ -476,12 +478,20 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); + // Obtain compiled and runtime versions + SDL_version ver_compiled; + SDL_version ver_runtime; + SDL_VERSION(&ver_compiled); + SDL_GetVersion(&ver_runtime); + // Setup backend capabilities flags ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)(); + snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl2 (%u.%u.%u, %u.%u.%u)", + ver_compiled.major, ver_compiled.minor, ver_compiled.patch, ver_runtime.major, ver_runtime.minor, ver_runtime.patch); io.BackendPlatformUserData = (void*)bd; - io.BackendPlatformName = "imgui_impl_sdl2"; - io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) - io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + io.BackendPlatformName = bd->BackendPlatformName; + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Window = window; bd->WindowID = SDL_GetWindowID(window); diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index cacce7e10..41511140c 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -69,6 +69,7 @@ // SDL #include +#include // for snprintf() #if defined(__APPLE__) #include #endif @@ -101,6 +102,7 @@ struct ImGui_ImplSDL3_Data SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; + char BackendPlatformName[40]; // IME handling SDL_Window* ImeWindow; @@ -465,10 +467,14 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_UNUSED(sdl_gl_context); // Unused in this branch + const int ver_linked = SDL_GetVersion(); + // Setup backend capabilities flags ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)(); + snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl3 (%u.%u.%u; %u.%u.%u)", + SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_MICRO_VERSION, SDL_VERSIONNUM_MAJOR(ver_linked), SDL_VERSIONNUM_MINOR(ver_linked), SDL_VERSIONNUM_MICRO(ver_linked)); io.BackendPlatformUserData = (void*)bd; - io.BackendPlatformName = "imgui_impl_sdl3"; + io.BackendPlatformName = bd->BackendPlatformName; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4c6dfe706..197a97da4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -107,6 +107,7 @@ Other changes: - Backends: SDL2, SDL3: don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). This is specifically for Wayland but we currently use the same white-list as SDL_GetGlobalMouseState(). (#8561) [@vs49688] +- Backends: GLFW, SDL2, SDL3: include GLFW/SDL version number in io.BackendPlatformName. - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) [@Green-Sky] - Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative From 61242e2e6a9c58337faff50afe8298e113901720 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 May 2025 11:35:38 +0200 Subject: [PATCH 0855/2359] InputText: fixed cursor positioning issue using up/down keys on non-ASCII text. (#8635, #7925) Bug introduced in abd07f6d30736c00fba899d41043a78a5de0f765. Ref https://github.com/nothings/stb/issues/188 --- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- imstb_textedit.h | 12 ++++++++---- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 197a97da4..1d37496b5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,8 @@ Other changes: - The feature is unlikely to ever work properly when using a coarse clipper such as ImGuiListClipper. - TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. +- InputText: fixed cursor positioning issue using up/down keys near end of lines while + editing non-ASCII text. (Regression from 1.91.2) (#8635, #7925) - Tables: fixed TableHeader() eager vertical clipping of text which may be noticeable with FramePadding.y was too small. (#6236) - Tables: fixed an assert when combining Tables, Frozen Rows, Clipper and BeginMultiSelect() diff --git a/imgui.h b/imgui.h index b9b8bf6ad..633f9f6dc 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19194 +#define IMGUI_VERSION_NUM 19195 #define IMGUI_HAS_TABLE /* diff --git a/imstb_textedit.h b/imstb_textedit.h index b7a761c85..ecdc7d39d 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -918,7 +918,7 @@ retry: state->cursor = start; STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); x = row.x0; - for (i=0; i < row.num_chars; ++i) { + for (i=0; i < row.num_chars; ) { float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) @@ -927,7 +927,9 @@ retry: x += dx; if (x > goal_x) break; - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + int next_cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + i += next_cursor - state->cursor; + state->cursor = next_cursor; } stb_textedit_clamp(str, state); @@ -980,7 +982,7 @@ retry: state->cursor = find.prev_first; STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); x = row.x0; - for (i=0; i < row.num_chars; ++i) { + for (i=0; i < row.num_chars; ) { float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) @@ -989,7 +991,9 @@ retry: x += dx; if (x > goal_x) break; - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + int next_cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + i += next_cursor - state->cursor; + state->cursor = next_cursor; } stb_textedit_clamp(str, state); From 5c3ac9333596374d08eddef1292a196948ecb223 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 May 2025 13:14:31 +0200 Subject: [PATCH 0856/2359] stb_textedit: minor edits to match PR submitted upstream. --- imstb_textedit.h | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/imstb_textedit.h b/imstb_textedit.h index ecdc7d39d..f97a20747 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -400,6 +400,16 @@ typedef struct #define IMSTB_TEXTEDIT_memmove memmove #endif +// [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) +#endif ///////////////////////////////////////////////////////////////////////////// // @@ -648,17 +658,6 @@ static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditSt } } -// [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) -#endif - #ifdef STB_TEXTEDIT_IS_SPACE static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx ) { @@ -920,6 +919,7 @@ retry: x = row.x0; for (i=0; i < row.num_chars; ) { float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); + int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) break; @@ -927,9 +927,8 @@ retry: x += dx; if (x > goal_x) break; - int next_cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); - i += next_cursor - state->cursor; - state->cursor = next_cursor; + i += next - state->cursor; + state->cursor = next; } stb_textedit_clamp(str, state); @@ -984,6 +983,7 @@ retry: x = row.x0; for (i=0; i < row.num_chars; ) { float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); + int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) break; @@ -991,9 +991,8 @@ retry: x += dx; if (x > goal_x) break; - int next_cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); - i += next_cursor - state->cursor; - state->cursor = next_cursor; + i += next - state->cursor; + state->cursor = next; } stb_textedit_clamp(str, state); From 1387d356aab85d8104fbb2837037fe5cd7783bf5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 May 2025 13:37:30 +0200 Subject: [PATCH 0857/2359] stb_textedit: subsequent fixes for next/prev word impl (not used by imgui) + PageUp/Home/End (no side effect but more correct) (#8635, #7925) --- imstb_textedit.h | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/imstb_textedit.h b/imstb_textedit.h index f97a20747..56d9d1151 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -667,9 +667,9 @@ static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx ) #ifndef STB_TEXTEDIT_MOVEWORDLEFT static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c ) { - --c; // always move at least one character - while( c >= 0 && !is_word_boundary( str, c ) ) - --c; + c = IMSTB_TEXTEDIT_GETPREVCHARINDEX( str, c ); // always move at least one character + while (c >= 0 && !is_word_boundary(str, c)) + c = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, c); if( c < 0 ) c = 0; @@ -683,9 +683,9 @@ static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c static int stb_textedit_move_to_word_next( IMSTB_TEXTEDIT_STRING *str, int c ) { const int len = STB_TEXTEDIT_STRINGLEN(str); - ++c; // always move at least one character + c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); // always move at least one character while( c < len && !is_word_boundary( str, c ) ) - ++c; + c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); if( c > len ) c = len; @@ -1005,8 +1005,13 @@ retry: // go to previous line // (we need to scan previous line the hard way. maybe we could expose this as a new API function?) prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0; - while (prev_scan > 0 && STB_TEXTEDIT_GETCHAR(str, prev_scan - 1) != STB_TEXTEDIT_NEWLINE) - --prev_scan; + while (prev_scan > 0) + { + int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, prev_scan); + if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) + break; + prev_scan = prev; + } find.first_char = find.prev_first; find.prev_first = prev_scan; } @@ -1085,7 +1090,7 @@ retry: if (state->single_line) state->cursor = 0; else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) - --state->cursor; + state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); state->has_preferred_x = 0; break; @@ -1097,9 +1102,9 @@ retry: stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); if (state->single_line) - state->cursor = n; + state->cursor = n; else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) - ++state->cursor; + state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); state->has_preferred_x = 0; break; } @@ -1113,7 +1118,7 @@ retry: if (state->single_line) state->cursor = 0; else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) - --state->cursor; + state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); state->select_end = state->cursor; state->has_preferred_x = 0; break; @@ -1128,7 +1133,7 @@ retry: if (state->single_line) state->cursor = n; else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) - ++state->cursor; + state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); state->select_end = state->cursor; state->has_preferred_x = 0; break; From 4e487cfa9985b8db8430096d283cf2763b0507d2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 May 2025 14:05:19 +0200 Subject: [PATCH 0858/2359] stb_textedit: subsequent comments to match ocornut/stb branch. (#8635, #7925) --- imstb_textedit.h | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/imstb_textedit.h b/imstb_textedit.h index 56d9d1151..33eef7095 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -141,6 +141,7 @@ // with previous char) // STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character // (return type is int, -1 means not valid to insert) +// (not supported if you want to use UTF-8, see below) // STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based // STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize // as manually wordwrapping for end-of-line positioning @@ -178,6 +179,13 @@ // 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: +// +// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character +// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character +// 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 // be a bitflag, so we can test the shifted state of cursor movements to allow selection, @@ -250,8 +258,10 @@ // if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are // transformed into text and stb_textedit_text() is automatically called. // -// text: [DEAR IMGUI] added 2024-09 -// call this to text inputs sent to the textfield. +// 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 @@ -738,6 +748,7 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS #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) { @@ -752,8 +763,7 @@ static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* sta state->cursor += text_len; state->has_preferred_x = 0; } - } - else { + } else { stb_textedit_delete_selection(str, state); // implicitly clamps if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) { stb_text_makeundo_insert(state, state->cursor, text_len); @@ -770,6 +780,7 @@ retry: switch (key) { default: { #ifdef STB_TEXTEDIT_KEYTOTEXT + // 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; From 2fd474132d4af57c61b3474af0fc9fd7bbe12f93 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 14 May 2025 16:53:36 +0200 Subject: [PATCH 0859/2359] Update pull_request_template.md --- .github/pull_request_template.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 638545bd6..796ec0b9e 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -2,5 +2,7 @@ 1. PLEASE CAREFULLY READ: [Contributing Guidelines](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md) -2. Clear this template before submitting your PR. +2. Make sure you're using a special branch just for this pull request. (Sometimes people unknowingly use a default branch, then later update that branch, which updates the pull request with the other changes if it hasn't been merged yet.) + +3. Clear this template before submitting your PR. From 2df9e9b103d2d2c5d14bddf5ecc8099c248b2f03 Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Wed, 14 May 2025 17:27:26 +0200 Subject: [PATCH 0860/2359] Examples: Apple: add Makefile for example_apple_metal, example_apple_opengl2. (#8637) - Works only for macOS: use XCode for iOS - It will produce a raw exe. It will not a produce an macOS application bundle (i.e a folder that includes exe and resources). To get app bundles, use the XCode project. - An adjustment was required in main.mm (for macOS only), to ensure that the exe can run without any plist or storyboard under macOS --- examples/example_apple_metal/Makefile | 25 +++++++++++++++++++++++++ examples/example_apple_metal/main.mm | 15 +++++++++++++-- examples/example_apple_opengl2/Makefile | 25 +++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 examples/example_apple_metal/Makefile create mode 100644 examples/example_apple_opengl2/Makefile diff --git a/examples/example_apple_metal/Makefile b/examples/example_apple_metal/Makefile new file mode 100644 index 000000000..a15fc431c --- /dev/null +++ b/examples/example_apple_metal/Makefile @@ -0,0 +1,25 @@ +# Makefile for example_apple_metal, for macOS only (**not iOS**) +TARGET := example_apple_metal +CXX := clang++ +CXXFLAGS := -std=c++17 -ObjC++ -fobjc-arc -Wall -Wextra \ + -I../../ \ + -I../../backends +FRAMEWORKS := -framework AppKit -framework Metal -framework MetalKit -framework QuartzCore -framework GameController +IMGUI_SRC := ../../imgui.cpp ../../imgui_draw.cpp ../../imgui_demo.cpp \ + ../../imgui_tables.cpp ../../imgui_widgets.cpp +BACKENDS := ../../backends/imgui_impl_metal.mm ../../backends/imgui_impl_osx.mm +SRC := main.mm $(IMGUI_SRC) $(BACKENDS) + +.PHONY: all run clean + + +all: $(TARGET) + +$(TARGET): $(SRC) + $(CXX) $(CXXFLAGS) $^ $(FRAMEWORKS) -o $@ + +run: all + ./$(TARGET) + +clean: + rm -f $(TARGET) *.o diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 830f1aed3..3ad7cff46 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -319,9 +319,20 @@ #if TARGET_OS_OSX -int main(int argc, const char * argv[]) +int main(int, const char**) { - return NSApplicationMain(argc, argv); + @autoreleasepool + { + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + + AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window + [NSApp setDelegate:appDelegate]; + + [NSApp activateIgnoringOtherApps:YES]; + [NSApp run]; + } + return 0; } #else diff --git a/examples/example_apple_opengl2/Makefile b/examples/example_apple_opengl2/Makefile new file mode 100644 index 000000000..02b4fba58 --- /dev/null +++ b/examples/example_apple_opengl2/Makefile @@ -0,0 +1,25 @@ +IMGUI_DIR = ../../ +CXX = clang++ +CXXFLAGS = -std=c++17 -ObjC++ -Wall -Wextra -g -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +FRAMEWORKS = -framework Cocoa -framework OpenGL -framework GameController + +SOURCES = \ + main.mm \ + $(IMGUI_DIR)/backends/imgui_impl_osx.mm \ + $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp \ + $(IMGUI_DIR)/imgui.cpp \ + $(IMGUI_DIR)/imgui_draw.cpp \ + $(IMGUI_DIR)/imgui_demo.cpp \ + $(IMGUI_DIR)/imgui_tables.cpp \ + $(IMGUI_DIR)/imgui_widgets.cpp + +TARGET = imgui_example_apple_opengl2 + +all: $(TARGET) + +$(TARGET): $(SOURCES) + $(CXX) $(CXXFLAGS) $(SOURCES) -o imgui_example_apple_opengl2 $(FRAMEWORKS) + +clean: + rm -f $(TARGET) + rm -rf $(TARGET).dSYM From b5a73033ab54009186bb8e4c711e03e6b939cb91 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 May 2025 18:05:23 +0200 Subject: [PATCH 0861/2359] Examples: Apple: Amend build scripts and gitignore, fix misc OSX warnings. (#8637) # Conflicts: # backends/imgui_impl_metal.mm --- .gitignore | 4 +++- backends/imgui_impl_osx.mm | 2 +- docs/CHANGELOG.txt | 1 + examples/example_apple_metal/Makefile | 28 ++++++++++------------ examples/example_apple_opengl2/Makefile | 32 +++++++++++-------------- 5 files changed, 31 insertions(+), 36 deletions(-) diff --git a/.gitignore b/.gitignore index 5a5c8cda3..6cadd63b4 100644 --- a/.gitignore +++ b/.gitignore @@ -32,9 +32,10 @@ JSON/ ## Commonly used CMake directories build*/ -## Xcode artifacts +## Xcode & macOS artifacts project.xcworkspace xcuserdata +examples/*/*.dSYM ## Emscripten artifacts examples/*.o.tmp @@ -54,6 +55,7 @@ cmake-build-* ## Unix executables from our example Makefiles examples/example_apple_metal/example_apple_metal +examples/example_apple_opengl2/example_apple_opengl2 examples/example_glfw_metal/example_glfw_metal examples/example_glfw_opengl2/example_glfw_opengl2 examples/example_glfw_opengl3/example_glfw_opengl3 diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 558ed9f2a..32e562472 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -477,7 +477,7 @@ bool ImGui_ImplOSX_Init(NSView* view) [view addSubview:bd->KeyEventResponder]; ImGui_ImplOSX_AddTrackingArea(view); - platform_io.Platform_SetImeDataFn = [](ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void + platform_io.Platform_SetImeDataFn = [](ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData* data) -> void { ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); if (data->WantVisible) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1d37496b5..5f957e7f0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -130,6 +130,7 @@ Other changes: - Backends: Vulkan: fixed validation errors in window create/resize helpers used by examples and by multi-viewports implementation, which would typically trigger errors while detaching secondary viewports. (#8600, #8176) [@ChrisTom-94] +- Examples: Apple+Metal, Apple+OpenGL: add Makefile (CLion opens them nicely). (#8637) [@pthom] - Examples: DirectX12+Win32: also test for IsIconic() for sleeping since we don't seem to get a DXGI_STATUS_OCCLUDED signal when minimized. (#8603) [@dooann] diff --git a/examples/example_apple_metal/Makefile b/examples/example_apple_metal/Makefile index a15fc431c..9412c9b53 100644 --- a/examples/example_apple_metal/Makefile +++ b/examples/example_apple_metal/Makefile @@ -1,25 +1,21 @@ # Makefile for example_apple_metal, for macOS only (**not iOS**) -TARGET := example_apple_metal -CXX := clang++ -CXXFLAGS := -std=c++17 -ObjC++ -fobjc-arc -Wall -Wextra \ - -I../../ \ - -I../../backends -FRAMEWORKS := -framework AppKit -framework Metal -framework MetalKit -framework QuartzCore -framework GameController -IMGUI_SRC := ../../imgui.cpp ../../imgui_draw.cpp ../../imgui_demo.cpp \ - ../../imgui_tables.cpp ../../imgui_widgets.cpp -BACKENDS := ../../backends/imgui_impl_metal.mm ../../backends/imgui_impl_osx.mm -SRC := main.mm $(IMGUI_SRC) $(BACKENDS) +CXX = clang++ +EXE = example_apple_metal +IMGUI_DIR = ../../ +SOURCES = main.mm +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_osx.mm $(IMGUI_DIR)/backends/imgui_impl_metal.mm -.PHONY: all run clean +CXXFLAGS = -std=c++11 -ObjC++ -fobjc-arc -Wall -Wextra -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +FRAMEWORKS = -framework AppKit -framework Metal -framework MetalKit -framework QuartzCore -framework GameController +all: $(EXE) -all: $(TARGET) - -$(TARGET): $(SRC) +$(EXE): $(SOURCES) $(CXX) $(CXXFLAGS) $^ $(FRAMEWORKS) -o $@ run: all - ./$(TARGET) + ./$(EXE) clean: - rm -f $(TARGET) *.o + rm -f $(EXE) *.o diff --git a/examples/example_apple_opengl2/Makefile b/examples/example_apple_opengl2/Makefile index 02b4fba58..4ad5fa692 100644 --- a/examples/example_apple_opengl2/Makefile +++ b/examples/example_apple_opengl2/Makefile @@ -1,25 +1,21 @@ -IMGUI_DIR = ../../ +# Makefile for example_apple_metal, for macOS only (**not iOS**) CXX = clang++ -CXXFLAGS = -std=c++17 -ObjC++ -Wall -Wextra -g -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +EXE = example_apple_opengl2 +IMGUI_DIR = ../../ +SOURCES = main.mm +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_osx.mm $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp + +CXXFLAGS = -std=c++11 -ObjC++ -fobjc-arc -Wall -Wextra -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends FRAMEWORKS = -framework Cocoa -framework OpenGL -framework GameController -SOURCES = \ - main.mm \ - $(IMGUI_DIR)/backends/imgui_impl_osx.mm \ - $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp \ - $(IMGUI_DIR)/imgui.cpp \ - $(IMGUI_DIR)/imgui_draw.cpp \ - $(IMGUI_DIR)/imgui_demo.cpp \ - $(IMGUI_DIR)/imgui_tables.cpp \ - $(IMGUI_DIR)/imgui_widgets.cpp +all: $(EXE) -TARGET = imgui_example_apple_opengl2 +$(EXE): $(SOURCES) + $(CXX) $(CXXFLAGS) $(SOURCES) -o $(EXE) $(FRAMEWORKS) -all: $(TARGET) - -$(TARGET): $(SOURCES) - $(CXX) $(CXXFLAGS) $(SOURCES) -o imgui_example_apple_opengl2 $(FRAMEWORKS) +run: all + ./$(EXE) clean: - rm -f $(TARGET) - rm -rf $(TARGET).dSYM + rm -f $(EXE) *.o From 9361c35176e770dd3098039a9a8cbc900e7e68e8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 May 2025 15:36:42 +0200 Subject: [PATCH 0862/2359] Backends: SDL2, SDL3: maximum room for sanitizer to not be zealous. --- backends/imgui_impl_sdl2.cpp | 2 +- backends/imgui_impl_sdl3.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 3d82bc348..fa2714bb9 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -136,7 +136,7 @@ struct ImGui_ImplSDL2_Data SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; - char BackendPlatformName[40]; + char BackendPlatformName[48]; // Mouse handling Uint32 MouseWindowID; diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 41511140c..58cc11c44 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -102,7 +102,7 @@ struct ImGui_ImplSDL3_Data SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; - char BackendPlatformName[40]; + char BackendPlatformName[48]; // IME handling SDL_Window* ImeWindow; From 6d939fcedc1f15313a3be782040b260c5fc29b4d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 May 2025 17:35:29 +0200 Subject: [PATCH 0863/2359] (Breaking) TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. (#1079, #8639) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 3 ++- imgui.h | 9 +++++---- imgui_demo.cpp | 6 +++--- imgui_internal.h | 2 +- imgui_widgets.cpp | 10 +++++----- 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5f957e7f0..628ccfce4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ HOW TO UPDATE? Breaking changes: +- TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent + for clarity. Kept inline redirection enum (will obsolete). (#1079, #8639) - Backends: SDL3: Fixed casing typo in function name: (#8509, #8163, #7998, #7988) [@puugz] - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() diff --git a/imgui.cpp b/imgui.cpp index cb36ac536..9a39394ca 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -431,6 +431,7 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238) - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); @@ -12801,7 +12802,7 @@ void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result) NavUpdateAnyRequestFlag(); } -// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere +// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data) { ImGuiContext& g = *GImGui; diff --git a/imgui.h b/imgui.h index 633f9f6dc..10198bb31 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19195 +#define IMGUI_VERSION_NUM 19196 #define IMGUI_HAS_TABLE /* @@ -1211,7 +1211,7 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (label will still fit in current column) ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, // Label will span all columns of its container table //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible - ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 17, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) + ImGuiTreeNodeFlags_NavLeftJumpsToParent = 1 << 17, // Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfullfilled Left nav request remaining. ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, // [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. @@ -1221,8 +1221,9 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, // Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 - ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth,// Renamed in 1.90.7 + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = ImGuiTreeNodeFlags_NavLeftJumpsToParent, // Renamed in 1.92.0 + ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth, // Renamed in 1.90.7 + ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 #endif }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 091a52569..69018315c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2990,7 +2990,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d static void DrawNode(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection) { ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; - tree_node_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Enable pressing left to jump to parent + tree_node_flags |= ImGuiTreeNodeFlags_NavLeftJumpsToParent; // Enable pressing left to jump to parent if (node->Childs.Size == 0) tree_node_flags |= ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_Leaf; if (selection->Contains((ImGuiID)node->UID)) @@ -4012,7 +4012,7 @@ static void DemoWindowWidgetsTreeNodes() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsBackHere", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsBackHere); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsToParent", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsToParent); HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); @@ -9366,7 +9366,7 @@ struct ExampleAppPropertyEditor ImGui::PushID(node->UID); ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None; tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;// Standard opening mode as we are likely to want to add selection afterwards - tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support + tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsToParent; // Left arrow support tree_flags |= ImGuiTreeNodeFlags_SpanFullWidth; // Span full width for easier mouse reach tree_flags |= ImGuiTreeNodeFlags_DrawLinesToNodes; // Always draw hierarchy outlines if (node == VisibleNode) diff --git a/imgui_internal.h b/imgui_internal.h index 996eb82a2..fb23c6cfb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1289,7 +1289,7 @@ struct ImGuiLastItemData }; // Store data emitted by TreeNode() for usage by TreePop() -// - To implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere: store the minimum amount of data +// - To implement ImGuiTreeNodeFlags_NavLeftJumpsToParent: store the minimum amount of data // which we can't infer in TreePop(), to perform the equivalent of NavApplyItemToResult(). // Only stored when the node is a potential candidate for landing on a Left arrow jump. struct ImGuiTreeNodeStackData diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1204a4599..f0108d12b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6681,17 +6681,17 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; g.LastItemData.DisplayRect = frame_bb; - // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsBackHere enabled: + // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsToParent enabled: // Store data for the current depth to allow returning to this node from any child item. // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). - // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default or move it to ImGuiStyle. + // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsToParent by default or move it to ImGuiStyle. bool store_tree_node_stack_data = false; if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0) flags |= g.Style.TreeLinesFlags; const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f); if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) { - if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !g.NavIdIsAlive) + if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) && !g.NavIdIsAlive) if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) store_tree_node_stack_data = true; if (draw_tree_lines) @@ -6994,8 +6994,8 @@ void ImGui::TreePop() const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; IM_ASSERT(data->ID == window->IDStack.back()); - // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled) - if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) + // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsToParent is enabled) + if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data); From d93d918eca6eaa361fd058218bea1498fca4e160 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 May 2025 17:38:45 +0200 Subject: [PATCH 0864/2359] (Breaking) Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. (#3092) Amend e83fb46. --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 1 + imgui.h | 6 +++--- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 628ccfce4..1bdce0ce5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,10 @@ Breaking changes: - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). (#1079, #8639) +- Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted + in 1.89.4 (March 2023). (#3092) + - PushAllowKeyboardFocus(bool tab_stop) --> PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); + - PopAllowKeyboardFocus() --> PopItemFlag(). - Backends: SDL3: Fixed casing typo in function name: (#8509, #8163, #7998, #7988) [@puugz] - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() diff --git a/imgui.cpp b/imgui.cpp index 9a39394ca..7f4c18c4c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -432,6 +432,7 @@ CODE You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). + - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092) - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238) - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); diff --git a/imgui.h b/imgui.h index 10198bb31..688f9c5e9 100644 --- a/imgui.h +++ b/imgui.h @@ -3668,11 +3668,11 @@ namespace ImGui 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); // OBSOLETED in 1.89.7 (from June 2023) IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() before item. - // OBSOLETED in 1.89.4 (from March 2023) - static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } - static inline void PopAllowKeyboardFocus() { PopItemFlag(); } // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + //-- OBSOLETED in 1.89.4 (from March 2023) + //static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + //static inline void PopAllowKeyboardFocus() { PopItemFlag(); } //-- OBSOLETED in 1.89 (from August 2022) //IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // --> Use new ImageButton() signature (explicit item id, regular FramePadding). Refer to code in 1.91 if you want to grab a copy of this version. //-- OBSOLETED in 1.88 (from May 2022) From cdb5cbe6f8786ced227624a71bc8a677618e5327 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 May 2025 17:44:10 +0200 Subject: [PATCH 0865/2359] (Breaking) Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Amend ecb0aaa. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 1 + imgui.h | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1bdce0ce5..384d0b26d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,9 @@ Breaking changes: in 1.89.4 (March 2023). (#3092) - PushAllowKeyboardFocus(bool tab_stop) --> PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); - PopAllowKeyboardFocus() --> PopItemFlag(). +- Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted + in 1.89.6 (June 2023). + - ForceDisplayRangeByIndices() --> IncludeItemsByIndex() - Backends: SDL3: Fixed casing typo in function name: (#8509, #8163, #7998, #7988) [@puugz] - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() diff --git a/imgui.cpp b/imgui.cpp index 7f4c18c4c..6150475b0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -433,6 +433,7 @@ CODE - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092) + - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead. - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238) - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); diff --git a/imgui.h b/imgui.h index 688f9c5e9..6794abede 100644 --- a/imgui.h +++ b/imgui.h @@ -2731,7 +2731,7 @@ struct ImGuiListClipper #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9] - inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] + //inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] //inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] #endif }; From 10a0eb3e1c31b8b6b6595ce75e8d65ec984b2ff9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 May 2025 18:40:45 +0200 Subject: [PATCH 0866/2359] Alter windows min/max size logic to prioritize enforcing size_max bounds rather than size_min. Docking branch until now used the opposite, aka ImClamp(size_desired, size_min, ImMax(size_min, size_max));, will be standardized across branches. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 6150475b0..b5d6b802d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6408,7 +6408,7 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont // Maximum window size is determined by the viewport size or monitor size ImVec2 size_min = CalcWindowMinSize(window); ImVec2 size_max = ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; - ImVec2 size_auto_fit = ImClamp(size_desired, size_min, size_max); + ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max); // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars, // we may need to compute/store three variants of size_auto_fit, for x/y/xy. From 415dddf0fac942647fc29ce3b9a02cfda89383e0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 May 2025 18:26:15 +0200 Subject: [PATCH 0867/2359] Tooltips: tooltips have a maximum size corresponding to host display/monitor size. --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 11 +++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 384d0b26d..48201acdf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -93,6 +93,10 @@ Other changes: in a certain order. (#8595, #8250) - Tabs: fixes small issues with how "..." ellipsis moved depending on visibility of Close Button or Unsaved Document marker. (#8387) +- Tooltips: tooltips have a maximum size corresponding to host display/monitor size, + which mitigates edge case issues in multi-viewport scenarios where abnormally large + windows (e.g. determined programmatically) can lead to renderer backend trying to + create abnormally large framebuffers. - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui.cpp b/imgui.cpp index b5d6b802d..6a4c37f41 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6398,16 +6398,19 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y; ImVec2 size_pad = window->WindowPadding * 2.0f; ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars); + + // Determine maximum window size + // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction + ImVec2 size_max = ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; + if (window->Flags & ImGuiWindowFlags_Tooltip) { - // Tooltip always resize - return size_desired; + // Tooltip always resize (up to maximum size) + return ImMin(size_desired, size_max); } else { - // Maximum window size is determined by the viewport size or monitor size ImVec2 size_min = CalcWindowMinSize(window); - ImVec2 size_max = ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max); // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars, From 1ffa7a40ac02a9edbc04c31db574304dbc017dac Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 20 May 2025 17:31:58 +0200 Subject: [PATCH 0868/2359] TextLinkOpenURL(): added bool return value on click. (#8645, #8451, #7660) --- docs/CHANGELOG.txt | 1 + imgui.h | 2 +- imgui_widgets.cpp | 9 +++++---- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 48201acdf..4fbbeea92 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -97,6 +97,7 @@ Other changes: which mitigates edge case issues in multi-viewport scenarios where abnormally large windows (e.g. determined programmatically) can lead to renderer backend trying to create abnormally large framebuffers. +- TextLinkOpenURL(): added bool return value on click. (#8645, #8451, #7660) - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui.h b/imgui.h index 6794abede..f90e4dfc0 100644 --- a/imgui.h +++ b/imgui.h @@ -559,7 +559,7 @@ namespace ImGui IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL); 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 void TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked + IMGUI_API bool TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked // Widgets: Images // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f0108d12b..b99e6e5c0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1529,14 +1529,14 @@ bool ImGui::TextLink(const char* label) return pressed; } -void ImGui::TextLinkOpenURL(const char* label, const char* url) +bool ImGui::TextLinkOpenURL(const char* label, const char* url) { ImGuiContext& g = *GImGui; if (url == NULL) url = label; - if (TextLink(label)) - if (g.PlatformIO.Platform_OpenInShellFn != NULL) - g.PlatformIO.Platform_OpenInShellFn(&g, url); + bool pressed = TextLink(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 we same as label if (BeginPopupContextItem()) { @@ -1544,6 +1544,7 @@ void ImGui::TextLinkOpenURL(const char* label, const char* url) SetClipboardText(url); EndPopup(); } + return pressed; } //------------------------------------------------------------------------- From 143924bbf3eb5aa548711dd2e5fbaf5822772cf0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 20 May 2025 17:53:17 +0200 Subject: [PATCH 0869/2359] Image(), ImageWithBg(): added extra comments. (#8131, #8238) --- imgui.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index f90e4dfc0..f4b692ab2 100644 --- a/imgui.h +++ b/imgui.h @@ -566,6 +566,7 @@ namespace ImGui // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. // - Image() pads adds style.ImageBorderSize on each side, ImageButton() adds style.FramePadding on each side. // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. + // - 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(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1)); IMGUI_API void ImageWithBg(ImTextureID user_texture_id, 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, ImTextureID user_texture_id, 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)); @@ -3649,7 +3650,7 @@ struct ImGuiPlatformImeData namespace ImGui { // OBSOLETED in 1.91.9 (from February 2025) - IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- border_col was removed in favor of ImGuiCol_ImageBorder. + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } static inline void PopButtonRepeat() { PopItemFlag(); } From 5f0acadf7db1b6d469f0771284e2e3f7818443ce Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 20 May 2025 18:06:12 +0200 Subject: [PATCH 0870/2359] RenderTextEllipsis() added breaking comments. --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4fbbeea92..f6207965e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,7 +51,9 @@ Breaking changes: in 1.89.6 (June 2023). - ForceDisplayRangeByIndices() --> IncludeItemsByIndex() - Backends: SDL3: Fixed casing typo in function name: (#8509, #8163, #7998, #7988) [@puugz] - - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() + - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() +- Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly + preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387) Other changes: diff --git a/imgui.cpp b/imgui.cpp index 6a4c37f41..16632d8da 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -435,6 +435,7 @@ CODE - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092) - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead. - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. + - 2025/04/16 (1.91.9) - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387) - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238) - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1)); @@ -3696,6 +3697,7 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons // 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 preceeding '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) { ImGuiContext& g = *GImGui; From 407a0b972eac6166095d2b5b5b0896bad6e9687a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 18:10:42 +0100 Subject: [PATCH 0871/2359] (Breaking) Fonts: CalcWordWrapPositionA() -> CalcWordWrapPosition(), takes size instead of scale. This will be needed for upcoming changes. --- docs/CHANGELOG.txt | 10 ++++++++-- imgui.cpp | 4 ++++ imgui.h | 8 ++++++-- imgui_draw.cpp | 13 +++++++------ 4 files changed, 25 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f6207965e..f45fa178c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,12 @@ Breaking changes: - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). (#1079, #8639) +- Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition(): + - old: const char* CalcWordWrapPositionA(float scale, const char* text, ....); + - new: const char* CalcWordWrapPosition (float size, const char* text, ....); + The leading 'float scale' parameters was changed to 'float size'. + This was necessary as 'scale' is assuming standard font size which is a concept we aim to + eliminate in an upcoming update. Kept inline redirection function. - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4 (March 2023). (#3092) - PushAllowKeyboardFocus(bool tab_stop) --> PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); @@ -51,7 +57,7 @@ Breaking changes: in 1.89.6 (June 2023). - ForceDisplayRangeByIndices() --> IncludeItemsByIndex() - Backends: SDL3: Fixed casing typo in function name: (#8509, #8163, #7998, #7988) [@puugz] - - Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData() + - Imgui_ImplSDLGPU3_PrepareDrawData() --> ImGui_ImplSDLGPU3_PrepareDrawData() - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387) @@ -109,7 +115,7 @@ Other changes: - Fonts: reworked text ellipsis logic to ensure a "..." is always displayed instead of a single character. (#7024) - Fonts: word-wrapping code handle ideographic comma & full stop (U+3001, U+3002). (#8540) -- Fonts: fixed CalcWordWrapPositionA() fallback when width is too small to wrap: +- Fonts: fixed CalcWordWrapPosition() fallback when width is too small to wrap: would use a +1 offset instead of advancing to the next UTF-8 codepoint. (#8540) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) diff --git a/imgui.cpp b/imgui.cpp index 16632d8da..30263bac6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -431,6 +431,10 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition() + - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....); + - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....); + The leading 'float scale' parameters was changed to 'float size'. This was necessary as 'scale' is assuming standard font size which is a concept we aim to eliminate in an upcoming update. Kept inline redirection function. - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092) - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead. diff --git a/imgui.h b/imgui.h index f4b692ab2..8e0e09b25 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19196 +#define IMGUI_VERSION_NUM 19197 #define IMGUI_HAS_TABLE /* @@ -3533,10 +3533,14 @@ 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 ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL); // utf8 - IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width); + IMGUI_API const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, 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, bool cpu_fine_clip = false); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(FontSize * scale, text, text_end, wrap_width); } +#endif + // [Internal] Don't use! IMGUI_API void BuildLookupTable(); IMGUI_API void ClearOutputData(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dbc659d25..78b0e152e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3936,7 +3936,7 @@ static inline const char* CalcWordWrapNextLineStartA(const char* text, const cha // 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. // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) -const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) +const char* ImFont::CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width) { // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" @@ -3952,6 +3952,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c float line_width = 0.0f; float word_width = 0.0f; float blank_width = 0.0f; + const float scale = size / FontSize; wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters const char* word_end = text; @@ -4055,7 +4056,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + word_wrap_eol = CalcWordWrapPosition(size, s, text_end, wrap_width - line_width); if (s >= word_wrap_eol) { @@ -4175,10 +4176,10 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im const char* line_end = (const char*)ImMemchr(s, '\n', text_end - s); if (word_wrap_enabled) { - // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPositionA(). - // If the specs for CalcWordWrapPositionA() were reworked to optionally return on \n we could combine both. + // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPosition(). + // If the specs for CalcWordWrapPosition() were reworked to optionally return on \n we could combine both. // However it is still better than nothing performing the fast-forward! - s = CalcWordWrapPositionA(scale, s, line_end ? line_end : text_end, wrap_width); + s = CalcWordWrapPosition(size, s, line_end ? line_end : text_end, wrap_width); s = CalcWordWrapNextLineStartA(s, text_end); } else @@ -4223,7 +4224,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - origin_x)); + word_wrap_eol = CalcWordWrapPosition(size, s, text_end, wrap_width - (x - origin_x)); if (s >= word_wrap_eol) { From 77f1d3b317c400c34ee02fe9a5354d0d757b55ca Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 May 2025 19:32:28 +0200 Subject: [PATCH 0872/2359] Refactor: move SetCurrentFont(), PushFont(), PopFont() to a section. --- imgui.cpp | 121 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 68 insertions(+), 53 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 30263bac6..2332073a2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -77,6 +77,7 @@ CODE // [SECTION] RENDER HELPERS // [SECTION] INITIALIZATION, SHUTDOWN // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) +// [SECTION] FONTS // [SECTION] ID STACK // [SECTION] INPUTS // [SECTION] ERROR CHECKING, STATE RECOVERY @@ -1268,6 +1269,7 @@ static void UpdateMouseWheel(); static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt); // Misc +static void UpdateFontsNewFrame(); static void UpdateSettings(); static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowOuterBorders(ImGuiWindow* window); @@ -5218,10 +5220,8 @@ void ImGui::NewFrame() UpdateViewportsNewFrame(); // Setup current font and draw list shared data - g.IO.Fonts->Locked = true; SetupDrawListSharedData(); - SetCurrentFont(GetDefaultFont()); - IM_ASSERT(g.Font->IsLoaded()); + UpdateFontsNewFrame(); // Mark rendering data as invalid to prevent user who may have a handle on it to use it. for (ImGuiViewportP* viewport : g.Viewports) @@ -7872,56 +7872,6 @@ void ImGui::End() SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window); } -// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only. -void ImGui::SetCurrentFont(ImFont* font) -{ - ImGuiContext& g = *GImGui; - IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? - IM_ASSERT(font->Scale > 0.0f); - g.Font = font; - g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); - g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; - g.FontScale = g.FontSize / g.Font->FontSize; - - ImFontAtlas* atlas = g.Font->ContainerAtlas; - g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; - g.DrawListSharedData.TexUvLines = atlas->TexUvLines; - g.DrawListSharedData.Font = g.Font; - g.DrawListSharedData.FontSize = g.FontSize; - g.DrawListSharedData.FontScale = g.FontScale; -} - -// Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authoritative against window-local ImDrawList. -// - Whereas ImDrawList::PushTextureID()/PopTextureID() is not to be used across Begin() calls. -// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... -// - Some code paths never really fully worked with multiple atlas textures. -// - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID() -// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem -// because we have a concrete need and a test bed for multiple atlas textures. -void ImGui::PushFont(ImFont* font) -{ - ImGuiContext& g = *GImGui; - if (font == NULL) - font = GetDefaultFont(); - g.FontStack.push_back(font); - SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); -} - -void ImGui::PopFont() -{ - ImGuiContext& g = *GImGui; - if (g.FontStack.Size <= 0) - { - IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!"); - return; - } - g.FontStack.pop_back(); - ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); - SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); -} - void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) { ImGuiContext& g = *GImGui; @@ -8546,6 +8496,71 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } +//----------------------------------------------------------------------------- +// [SECTION] FONTS +//----------------------------------------------------------------------------- +// Most of the relevant font logic is in imgui_draw.cpp. +// Those are high-level support functions. +//----------------------------------------------------------------------------- + +void ImGui::UpdateFontsNewFrame() +{ + ImGuiContext& g = *GImGui; + g.IO.Fonts->Locked = true; + SetCurrentFont(GetDefaultFont()); + IM_ASSERT(g.Font->IsLoaded()); +} + +// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only. +void ImGui::SetCurrentFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(font->Scale > 0.0f); + g.Font = font; + g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); + g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + g.FontScale = g.FontSize / g.Font->FontSize; + + ImFontAtlas* atlas = g.Font->ContainerAtlas; + g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; + g.DrawListSharedData.TexUvLines = atlas->TexUvLines; + g.DrawListSharedData.Font = g.Font; + g.DrawListSharedData.FontSize = g.FontSize; + g.DrawListSharedData.FontScale = g.FontScale; +} + +// Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authoritative against window-local ImDrawList. +// - Whereas ImDrawList::PushTextureID()/PopTextureID() is not to be used across Begin() calls. +// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... +// - Some code paths never really fully worked with multiple atlas textures. +// - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID() +// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem +// because we have a concrete need and a test bed for multiple atlas textures. +void ImGui::PushFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + if (font == NULL) + font = GetDefaultFont(); + g.FontStack.push_back(font); + SetCurrentFont(font); + g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); +} + +void ImGui::PopFont() +{ + ImGuiContext& g = *GImGui; + if (g.FontStack.Size <= 0) + { + IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!"); + return; + } + g.FontStack.pop_back(); + ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); + SetCurrentFont(font); + g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); +} + //----------------------------------------------------------------------------- // [SECTION] ID STACK //----------------------------------------------------------------------------- From 87a6443c5bc6297f18cbbb2712db2dc28983d23f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 May 2025 20:47:50 +0200 Subject: [PATCH 0873/2359] Scroll: fixed contents size, scrollbar visibility and scrolling reet issue with abnormally large contents ranges. (#3609, #8215) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 10 +++++----- imgui_internal.h | 2 ++ 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f45fa178c..4b123e59a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -106,6 +106,8 @@ Other changes: windows (e.g. determined programmatically) can lead to renderer backend trying to create abnormally large framebuffers. - TextLinkOpenURL(): added bool return value on click. (#8645, #8451, #7660) +- Scroll: fixed contents size, scrollbar visibility and scrolling resetting issues + with abnormally large contents ranges. (#3609, #8215) - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui.cpp b/imgui.cpp index 2332073a2..4e85502be 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6390,10 +6390,10 @@ static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_cur return; } - content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); - content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); - content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x); - content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y); + content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); + content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); + content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x); + content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y); } static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents) @@ -11166,7 +11166,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) } scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]); } - scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f)); + scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f)); if (!window->Collapsed && !window->SkipItems) scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]); } diff --git a/imgui_internal.h b/imgui_internal.h index fb23c6cfb..ca250e0b7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -496,6 +496,8 @@ static inline float ImTrunc(float f) static inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } static inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } +static inline float ImTrunc64(float f) { return (float)(ImS64)(f); } +static inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } static inline int ImModPositive(int a, int b) { return (a + b) % b; } static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } From c53c9a8644e05a9e4a0573896eb79d5aeaa354c8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 May 2025 21:11:23 +0200 Subject: [PATCH 0874/2359] Clipper: further mitigation/improvements for abnormally large contents ranges (larger than e.g. 2^31). (#3609, #8215) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 11 +++++++++-- imgui.h | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4b123e59a..8fd49b525 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -108,6 +108,7 @@ Other changes: - TextLinkOpenURL(): added bool return value on click. (#8645, #8451, #7660) - Scroll: fixed contents size, scrollbar visibility and scrolling resetting issues with abnormally large contents ranges. (#3609, #8215) +- Clipper: some mitigation/improvements for abnormally large contents ranges. (#3609, #8215) - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) - Error Handling: added better error report and recovery for extraneous diff --git a/imgui.cpp b/imgui.cpp index 4e85502be..fb4966292 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3195,10 +3195,17 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) if (table) IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y); - clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart); - bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y); + bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision((float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y); if (affected_by_floating_point_precision) + { + // Mitigation/hack for very large range: assume last time height constitute line height. clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries. + window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight); + } + else + { + clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart); + } if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode. return false; IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!"); diff --git a/imgui.h b/imgui.h index 8e0e09b25..6d062c190 100644 --- a/imgui.h +++ b/imgui.h @@ -2708,7 +2708,7 @@ struct ImGuiListClipper int DisplayEnd; // End of items to display (exclusive) int ItemsCount; // [Internal] Number of items float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it - float StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed + double StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed double StartSeekOffsetY; // [Internal] Account for frozen rows in a table and initial loss of precision in very large windows. void* TempData; // [Internal] Internal data From 19289d587a3a7a13c4ca799dbf2108c2a5bb4935 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 May 2025 21:33:09 +0200 Subject: [PATCH 0875/2359] Nav: fixed scroll fallback (when there are no interactive widgets to jump to) not being enabled on windows with menu or title bar. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8fd49b525..92df7b4f6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -111,6 +111,8 @@ Other changes: - Clipper: some mitigation/improvements for abnormally large contents ranges. (#3609, #8215) - Nav: fixed assertion when holding gamepad FaceLeft/West button to open CTRL+Tab windowing + pressing a keyboard key. (#8525) +- Nav: fixed scroll fallback (when there are no interactive widgets to jump to) not + being enabled on windows with menu or title bar. - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) - Error Handling: added better error report and recovery when calling EndFrame() diff --git a/imgui.cpp b/imgui.cpp index fb4966292..36d2e976e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13598,7 +13598,7 @@ static float ImGui::NavUpdatePageUpPageDown() if (g.NavLayer != ImGuiNavLayer_Main) NavRestoreLayer(ImGuiNavLayer_Main); - if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY) + if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY) { // Fallback manual-scroll when window has no navigable item if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner)) From c3a3a39e92adaf64272c5c3542844852a52d0ec6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 May 2025 21:46:33 +0200 Subject: [PATCH 0876/2359] Nav: fixed abnormal clipping disable over large ranges, could lead to stall. (#3841, #1725) Amend 93cccd27f --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 92df7b4f6..1f03f7936 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -113,6 +113,8 @@ Other changes: CTRL+Tab windowing + pressing a keyboard key. (#8525) - Nav: fixed scroll fallback (when there are no interactive widgets to jump to) not being enabled on windows with menu or title bar. +- Nav: fixed an issue handling PageUp/PageDown on windows with abnormally large contents + range which could lead to clipper requesting very large ranges. - Error Handling: added better error report and recovery for extraneous EndPopup() call. (#1651, #8499) - Error Handling: added better error report and recovery when calling EndFrame() diff --git a/imgui.cpp b/imgui.cpp index 36d2e976e..419098b80 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3229,7 +3229,10 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) // Add range selected to be included for navigation const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); if (is_nav_request) + { + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, 0, 0)); data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0)); + } if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1) data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount)); @@ -13379,7 +13382,7 @@ void ImGui::NavUpdateCreateMoveRequest() //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG] } g.NavScoringRect = scoring_rect; - g.NavScoringNoClipRect.Add(scoring_rect); + //g.NavScoringNoClipRect.Add(scoring_rect); } void ImGui::NavUpdateCreateTabbingRequest() From e6913f58b90f9eaf034fab5b576ca8ef6bd80aa7 Mon Sep 17 00:00:00 2001 From: Romain Moret Date: Mon, 26 May 2025 19:02:18 +0200 Subject: [PATCH 0877/2359] imgui_freetype: Update lunasvg API to support v3.0+ (#8656, #6842, #6591) --- docs/CHANGELOG.txt | 1 + misc/freetype/imgui_freetype.cpp | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1f03f7936..aaf219a6e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -268,6 +268,7 @@ Other changes: - Debug Tools: Added io.ConfigDebugHighlightIdConflictsShowItemPicker (defaults to true) to allow disabled Item Picker suggestion in user facing builds. (#7961, #7669) - Debug Tools: Tweaked layout of ID Stack Tool and always display full path. (#4631) +- imgui_freetype: update lunasvg API to support v3.0+. (#8656, #6842, #6591) - Misc: Various zealous warning fixes for newer version of Clang. - Misc: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursors (busy/wait/hourglass shape, with or without an arrow cursor). diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 73b9862bc..39a997e67 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -880,8 +880,12 @@ static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state) // rows is height, pitch (or stride) equals to width * sizeof(int32) lunasvg::Bitmap bitmap((uint8_t*)slot->bitmap.buffer, slot->bitmap.width, slot->bitmap.rows, slot->bitmap.pitch); +#if LUNASVG_VERSION_MAJOR >= 3 + state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated +#else state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated +#endif state->err = FT_Err_Ok; return state->err; } @@ -904,7 +908,11 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ return state->err; } +#if LUNASVG_VERSION_MAJOR >= 3 + lunasvg::Box box = state->svg->boundingBox(); +#else lunasvg::Box box = state->svg->box(); +#endif double scale = std::min(metrics.x_ppem / box.w, metrics.y_ppem / box.h); double xx = (double)document->transform.xx / (1 << 16); double xy = -(double)document->transform.xy / (1 << 16); @@ -913,6 +921,15 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ double x0 = (double)document->delta.x / 64 * box.w / metrics.x_ppem; double y0 = -(double)document->delta.y / 64 * box.h / metrics.y_ppem; +#if LUNASVG_VERSION_MAJOR >= 3 + // Scale, transform and pre-translate the matrix for the rendering step + state->matrix = lunasvg::Matrix::translated(-box.x, -box.y); + state->matrix.multiply(lunasvg::Matrix(xx, xy, yx, yy, x0, y0)); + state->matrix.scale(scale, scale); + + // Apply updated transformation to the bounding box + box.transform(state->matrix); +#else // Scale and transform, we don't translate the svg yet state->matrix.identity(); state->matrix.scale(scale, scale); @@ -924,6 +941,7 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ // Get the box again after the transformation box = state->svg->box(); +#endif // Calculate the bitmap size slot->bitmap_left = FT_Int(box.x); From 69e1fb50cacbde1c2c585ae59898e68c1818d9b7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 May 2025 21:59:13 +0200 Subject: [PATCH 0878/2359] Docs: fixed missing commit credit. (#8656) --- docs/CHANGELOG.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index aaf219a6e..956c04120 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -268,7 +268,7 @@ Other changes: - Debug Tools: Added io.ConfigDebugHighlightIdConflictsShowItemPicker (defaults to true) to allow disabled Item Picker suggestion in user facing builds. (#7961, #7669) - Debug Tools: Tweaked layout of ID Stack Tool and always display full path. (#4631) -- imgui_freetype: update lunasvg API to support v3.0+. (#8656, #6842, #6591) +- imgui_freetype: update lunasvg API to support v3.0+. (#8656, #6842, #6591) [@moretromain] - Misc: Various zealous warning fixes for newer version of Clang. - Misc: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursors (busy/wait/hourglass shape, with or without an arrow cursor). From b7ab2b7523748401ed9fc7b82a40d20e3b8b36cc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Jun 2025 20:41:01 +0200 Subject: [PATCH 0879/2359] TreeNode: fixed an issue where tree lines are not drawn on node opening frame. (#2920) --- imgui_widgets.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b99e6e5c0..cc3b5201e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6690,7 +6690,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0) flags |= g.Style.TreeLinesFlags; const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f); - if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) { if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) && !g.NavIdIsAlive) if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) @@ -6889,7 +6889,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l TablePopBackgroundChannel(); } - if (store_tree_node_stack_data && is_open) + if (is_open && store_tree_node_stack_data) TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice From ef503ab0c881934fb971c3e73745ba44bd355434 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Jun 2025 20:50:12 +0200 Subject: [PATCH 0880/2359] TreeNode: fixed out of bound access in ImGuiTreeNodeFlags_DrawLinesXXX feature. (#2920) TreeNode behavior would read TreeRecordsClippedNodesY2Mask from an older node at same lebel, and write to g.TreeNodeStack.Data[-1]. --- imgui_widgets.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index cc3b5201e..6b80d19d1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6990,7 +6990,7 @@ void ImGui::TreePop() window->DC.TreeDepth--; ImU32 tree_depth_mask = (1 << window->DC.TreeDepth); - if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) // Only set during request + if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) { const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; IM_ASSERT(data->ID == window->IDStack.back()); @@ -7006,6 +7006,7 @@ void ImGui::TreePop() g.TreeNodeStack.pop_back(); window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask; + window->DC.TreeRecordsClippedNodesY2Mask &= ~tree_depth_mask; } IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much. From e877f78b0e9938ae6e8806ffa3c97392882c6501 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Jun 2025 20:57:21 +0200 Subject: [PATCH 0881/2359] TreeNode: minor amend to b7ab2b7. (#2920) --- imgui_widgets.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6b80d19d1..341bf2712 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6692,11 +6692,10 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f); if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) { + store_tree_node_stack_data = draw_tree_lines; if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) && !g.NavIdIsAlive) if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) store_tree_node_stack_data = true; - if (draw_tree_lines) - store_tree_node_stack_data = true; } const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; From 9485aeb5c8cf11277ac6f30cac477ba1050d2c07 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Jun 2025 17:30:17 +0200 Subject: [PATCH 0882/2359] Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). --- docs/CHANGELOG.txt | 1 + imgui.cpp | 11 +++++------ imgui_demo.cpp | 27 ++++++++++++++++++++++++--- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 956c04120..e490133ca 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -131,6 +131,7 @@ Other changes: of WantVisible. This is set in the same structure because activating text input generally requires providing a window to the backend. (#8584, #6341) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] +- Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). - Backends: Win32: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) would fail to claim it again the next subsequent click. (#8594) - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad diff --git a/imgui.cpp b/imgui.cpp index 419098b80..df41d9713 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7563,12 +7563,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f); window->InnerClipRect.ClipWithFull(host_rect); - // Default item width. Make it proportional to window size if window manually resizes - if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) - window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f); - else - window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f); - // SCROLLING // Lock down maximum scrolling @@ -7681,6 +7675,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; + // Default item width. Make it proportional to window size if window manually resizes + if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) + window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f); + else + window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f); window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled window->DC.ItemWidthStack.resize(0); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 69018315c..82e7d4801 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -410,9 +410,19 @@ void ImGui::ShowDemoWindow(bool* p_open) return; } - // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details. - ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. - //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align) + // Most framed widgets share a common width settings. Remaining width is used for the label. + // The width of the frame may be changed with PushItemWidth() or SetNextItemWidth(). + // - Positive value for absolute size, negative value for right-alignment. + // - The default value is about GetWindowWidth() * 0.65f. + // - See 'Demo->Layout->Widgets Width' for details. + // Here we change the frame width based on how much width we want to give to the label. + const float label_width_base = ImGui::GetFontSize() * 12; // Some amount of width for label, based on font size. + const float label_width_max = ImGui::GetContentRegionAvail().x * 0.40f; // ...but always leave some room for framed widgets. + const float label_width = IM_MIN(label_width_base, label_width_max); + ImGui::PushItemWidth(-label_width); // Right-align: framed items will leave 'label_width' available for the label. + //ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.40f); // e.g. Use 40% width for framed widgets, leaving 60% width for labels. + //ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.40f); // e.g. Use 40% width for labels, leaving 60% width for framed widgets. + //ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // e.g. Use XXX width for labels, leaving the rest for framed widgets. // Menu Bar DemoWindowMenuBar(&demo_data); @@ -4426,6 +4436,17 @@ static void DemoWindowLayout() } ImGui::PopItemWidth(); + ImGui::Text("SetNextItemWidth/PushItemWidth(-Min(GetContentRegionAvail().x * 0.40f, GetFontSize() * 12))"); + ImGui::PushItemWidth(-IM_MIN(ImGui::GetFontSize() * 12, ImGui::GetContentRegionAvail().x * 0.40f)); + ImGui::DragFloat("float##4a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##4b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + // Demonstrate using PushItemWidth to surround three items. // Calling SetNextItemWidth() before each of them would have the same effect. ImGui::Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)"); From 91f72bbe1c286645108cff4fa89d4031139241f8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Jun 2025 21:29:12 +0200 Subject: [PATCH 0883/2359] Demo: omit ImGui:: prefix from ShowStyleEditor(), ShowUserGuide() code. --- imgui_demo.cpp | 367 +++++++++++++++++++++++++------------------------ 1 file changed, 184 insertions(+), 183 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 82e7d4801..14dcc3204 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8225,12 +8225,13 @@ static const char* GetTreeLinesFlagsName(ImGuiTreeNodeFlags flags) return ""; } +// We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. void ImGui::ShowStyleEditor(ImGuiStyle* ref) { IMGUI_DEMO_MARKER("Tools/Style Editor"); // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to // (without a reference style pointer, we will use one compared locally as a reference) - ImGuiStyle& style = ImGui::GetStyle(); + ImGuiStyle& style = GetStyle(); static ImGuiStyle ref_saved_style; // Default to using internal storage as reference @@ -8241,206 +8242,206 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ref == NULL) ref = &ref_saved_style; - ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f); + PushItemWidth(GetWindowWidth() * 0.50f); - if (ImGui::ShowStyleSelector("Colors##Selector")) + if (ShowStyleSelector("Colors##Selector")) ref_saved_style = style; - ImGui::ShowFontSelector("Fonts##Selector"); + ShowFontSelector("Fonts##Selector"); // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) - if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) + if (SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding - { bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } - ImGui::SameLine(); - { bool border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } - ImGui::SameLine(); - { bool border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } + { bool border = (style.WindowBorderSize > 0.0f); if (Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } + SameLine(); + { bool border = (style.FrameBorderSize > 0.0f); if (Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } + SameLine(); + { bool border = (style.PopupBorderSize > 0.0f); if (Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } // Save/Revert button - if (ImGui::Button("Save Ref")) + if (Button("Save Ref")) *ref = ref_saved_style = style; - ImGui::SameLine(); - if (ImGui::Button("Revert Ref")) + SameLine(); + if (Button("Revert Ref")) style = *ref; - ImGui::SameLine(); + SameLine(); HelpMarker( "Save/Revert in local non-persistent storage. Default Colors definition are not affected. " "Use \"Export\" below to save them somewhere."); - ImGui::Separator(); + Separator(); - if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_None)) + if (BeginTabBar("##tabs", ImGuiTabBarFlags_None)) { - if (ImGui::BeginTabItem("Sizes")) + if (BeginTabItem("Sizes")) { - ImGui::SeparatorText("Main"); - ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); - ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); - ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); + SeparatorText("Main"); + SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); + SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); + SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); - ImGui::SeparatorText("Borders"); - ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); + SeparatorText("Borders"); + SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SeparatorText("Rounding"); - ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); + SeparatorText("Rounding"); + SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SeparatorText("Tabs"); - ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); - ImGui::SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); - ImGui::SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); - ImGui::DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); - ImGui::DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); - ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); + SeparatorText("Tabs"); + SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); + SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); + SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); + DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); + DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); + SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SeparatorText("Tables"); - ImGui::SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderAngle("TableAngledHeadersAngle", &style.TableAngledHeadersAngle, -50.0f, +50.0f); - ImGui::SliderFloat2("TableAngledHeadersTextAlign", (float*)&style.TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f"); + SeparatorText("Tables"); + SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0f, 20.0f, "%.0f"); + SliderAngle("TableAngledHeadersAngle", &style.TableAngledHeadersAngle, -50.0f, +50.0f); + SliderFloat2("TableAngledHeadersTextAlign", (float*)&style.TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SeparatorText("Trees"); - bool combo_open = ImGui::BeginCombo("TreeLinesFlags", GetTreeLinesFlagsName(style.TreeLinesFlags)); - ImGui::SameLine(); + SeparatorText("Trees"); + bool combo_open = BeginCombo("TreeLinesFlags", GetTreeLinesFlagsName(style.TreeLinesFlags)); + SameLine(); HelpMarker("[Experimental] Tree lines may not work in all situations (e.g. using a clipper) and may incurs slight traversal overhead.\n\nImGuiTreeNodeFlags_DrawLinesFull is faster than ImGuiTreeNodeFlags_DrawLinesToNode."); if (combo_open) { const ImGuiTreeNodeFlags options[] = { ImGuiTreeNodeFlags_DrawLinesNone, ImGuiTreeNodeFlags_DrawLinesFull, ImGuiTreeNodeFlags_DrawLinesToNodes }; for (ImGuiTreeNodeFlags option : options) - if (ImGui::Selectable(GetTreeLinesFlagsName(option), style.TreeLinesFlags == option)) + if (Selectable(GetTreeLinesFlagsName(option), style.TreeLinesFlags == option)) style.TreeLinesFlags = option; - ImGui::EndCombo(); + EndCombo(); } - ImGui::SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 2.0f, "%.0f"); - ImGui::SliderFloat("TreeLinesRounding", &style.TreeLinesRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 2.0f, "%.0f"); + SliderFloat("TreeLinesRounding", &style.TreeLinesRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SeparatorText("Windows"); - ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SliderFloat("WindowBorderHoverPadding", &style.WindowBorderHoverPadding, 1.0f, 20.0f, "%.0f"); + SeparatorText("Windows"); + SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + SliderFloat("WindowBorderHoverPadding", &style.WindowBorderHoverPadding, 1.0f, 20.0f, "%.0f"); int window_menu_button_position = style.WindowMenuButtonPosition + 1; - if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) + if (Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1); - ImGui::SeparatorText("Widgets"); - ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); - ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); - ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); - ImGui::SliderFloat("SeparatorTextBorderSize", &style.SeparatorTextBorderSize, 0.0f, 10.0f, "%.0f"); - ImGui::SliderFloat2("SeparatorTextAlign", (float*)&style.SeparatorTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); - ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, 1.0f, "%.0f"); + SeparatorText("Widgets"); + Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); + SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); + SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); + SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); + SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); + SliderFloat("SeparatorTextBorderSize", &style.SeparatorTextBorderSize, 0.0f, 10.0f, "%.0f"); + SliderFloat2("SeparatorTextAlign", (float*)&style.SeparatorTextAlign, 0.0f, 1.0f, "%.2f"); + SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); + SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); + SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SeparatorText("Tooltips"); + SeparatorText("Tooltips"); for (int n = 0; n < 2; n++) - if (ImGui::TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) + if (TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) { ImGuiHoveredFlags* p = (n == 0) ? &style.HoverFlagsForTooltipMouse : &style.HoverFlagsForTooltipNav; - ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayNone", p, ImGuiHoveredFlags_DelayNone); - ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayShort", p, ImGuiHoveredFlags_DelayShort); - ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayNormal", p, ImGuiHoveredFlags_DelayNormal); - ImGui::CheckboxFlags("ImGuiHoveredFlags_Stationary", p, ImGuiHoveredFlags_Stationary); - ImGui::CheckboxFlags("ImGuiHoveredFlags_NoSharedDelay", p, ImGuiHoveredFlags_NoSharedDelay); - ImGui::TreePop(); + CheckboxFlags("ImGuiHoveredFlags_DelayNone", p, ImGuiHoveredFlags_DelayNone); + CheckboxFlags("ImGuiHoveredFlags_DelayShort", p, ImGuiHoveredFlags_DelayShort); + CheckboxFlags("ImGuiHoveredFlags_DelayNormal", p, ImGuiHoveredFlags_DelayNormal); + CheckboxFlags("ImGuiHoveredFlags_Stationary", p, ImGuiHoveredFlags_Stationary); + CheckboxFlags("ImGuiHoveredFlags_NoSharedDelay", p, ImGuiHoveredFlags_NoSharedDelay); + TreePop(); } - ImGui::SeparatorText("Misc"); - ImGui::SliderFloat2("DisplayWindowPadding", (float*)&style.DisplayWindowPadding, 0.0f, 30.0f, "%.0f"); ImGui::SameLine(); HelpMarker("Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen."); - ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); ImGui::SameLine(); HelpMarker("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)."); + SeparatorText("Misc"); + SliderFloat2("DisplayWindowPadding", (float*)&style.DisplayWindowPadding, 0.0f, 30.0f, "%.0f"); SameLine(); HelpMarker("Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen."); + SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); SameLine(); HelpMarker("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)."); - ImGui::EndTabItem(); + EndTabItem(); } - if (ImGui::BeginTabItem("Colors")) + if (BeginTabItem("Colors")) { static int output_dest = 0; static bool output_only_modified = true; - if (ImGui::Button("Export")) + if (Button("Export")) { if (output_dest == 0) - ImGui::LogToClipboard(); + LogToClipboard(); else - ImGui::LogToTTY(); - ImGui::LogText("ImVec4* colors = ImGui::GetStyle().Colors;" IM_NEWLINE); + LogToTTY(); + LogText("ImVec4* colors = GetStyle().Colors;" IM_NEWLINE); for (int i = 0; i < ImGuiCol_COUNT; i++) { const ImVec4& col = style.Colors[i]; - const char* name = ImGui::GetStyleColorName(i); + const char* name = GetStyleColorName(i); if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) - ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, + LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w); } - ImGui::LogFinish(); + LogFinish(); } - ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); - ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified); + SameLine(); SetNextItemWidth(120); Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + SameLine(); Checkbox("Only Modified Colors", &output_only_modified); static ImGuiTextFilter filter; - filter.Draw("Filter colors", ImGui::GetFontSize() * 16); + filter.Draw("Filter colors", GetFontSize() * 16); static ImGuiColorEditFlags alpha_flags = 0; - if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) { alpha_flags = ImGuiColorEditFlags_AlphaOpaque; } ImGui::SameLine(); - if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine(); - if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); + if (RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) { alpha_flags = ImGuiColorEditFlags_AlphaOpaque; } SameLine(); + if (RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } SameLine(); + if (RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } SameLine(); HelpMarker( "In the color list:\n" "Left-click on color square to open color picker,\n" "Right-click to open edit options menu."); - ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); - ImGui::BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); - ImGui::PushItemWidth(ImGui::GetFontSize() * -12); + SetNextWindowSizeConstraints(ImVec2(0.0f, GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); + BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); + PushItemWidth(GetFontSize() * -12); for (int i = 0; i < ImGuiCol_COUNT; i++) { - const char* name = ImGui::GetStyleColorName(i); + const char* name = GetStyleColorName(i); if (!filter.PassFilter(name)) continue; - ImGui::PushID(i); + PushID(i); #ifndef IMGUI_DISABLE_DEBUG_TOOLS - if (ImGui::Button("?")) - ImGui::DebugFlashStyleColor((ImGuiCol)i); - ImGui::SetItemTooltip("Flash given color to identify places where it is used."); - ImGui::SameLine(); + if (Button("?")) + DebugFlashStyleColor((ImGuiCol)i); + SetItemTooltip("Flash given color to identify places where it is used."); + SameLine(); #endif - ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); + ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) { // Tips: in a real user application, you may want to merge and use an icon font into the main font, // so instead of "Save"/"Revert" you'd use icons! // Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient! - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; } - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) { style.Colors[i] = ref->Colors[i]; } + SameLine(0.0f, style.ItemInnerSpacing.x); if (Button("Save")) { ref->Colors[i] = style.Colors[i]; } + SameLine(0.0f, style.ItemInnerSpacing.x); if (Button("Revert")) { style.Colors[i] = ref->Colors[i]; } } - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); - ImGui::TextUnformatted(name); - ImGui::PopID(); + SameLine(0.0f, style.ItemInnerSpacing.x); + TextUnformatted(name); + PopID(); } - ImGui::PopItemWidth(); - ImGui::EndChild(); + PopItemWidth(); + EndChild(); - ImGui::EndTabItem(); + EndTabItem(); } - if (ImGui::BeginTabItem("Fonts")) + if (BeginTabItem("Fonts")) { - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = GetIO(); ImFontAtlas* atlas = io.Fonts; HelpMarker("Read FAQ and docs/FONTS.md for details on font loading."); - ImGui::ShowFontAtlas(atlas); + ShowFontAtlas(atlas); // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). @@ -8452,119 +8453,119 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" "Using those settings here will give you poor quality results."); static float window_scale = 1.0f; - ImGui::PushItemWidth(ImGui::GetFontSize() * 8); - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window - ImGui::SetWindowFontScale(window_scale); - ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything - ImGui::PopItemWidth(); + PushItemWidth(GetFontSize() * 8); + if (DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window + SetWindowFontScale(window_scale); + DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything + PopItemWidth(); - ImGui::EndTabItem(); + EndTabItem(); } - if (ImGui::BeginTabItem("Rendering")) + if (BeginTabItem("Rendering")) { - ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); - ImGui::SameLine(); + Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); - ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); - ImGui::SameLine(); + Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); + SameLine(); HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering)."); - ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); - ImGui::PushItemWidth(ImGui::GetFontSize() * 8); - ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); + Checkbox("Anti-aliased fill", &style.AntiAliasedFill); + PushItemWidth(GetFontSize() * 8); + DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f; // When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. - ImGui::DragFloat("Circle Tessellation Max Error", &style.CircleTessellationMaxError , 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp); - const bool show_samples = ImGui::IsItemActive(); + DragFloat("Circle Tessellation Max Error", &style.CircleTessellationMaxError , 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp); + const bool show_samples = IsItemActive(); if (show_samples) - ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); - if (show_samples && ImGui::BeginTooltip()) + SetNextWindowPos(GetCursorScreenPos()); + if (show_samples && BeginTooltip()) { - ImGui::TextUnformatted("(R = radius, N = approx number of segments)"); - ImGui::Spacing(); - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - const float min_widget_width = ImGui::CalcTextSize("R: MMM\nN: MMM").x; + TextUnformatted("(R = radius, N = approx number of segments)"); + Spacing(); + ImDrawList* draw_list = GetWindowDrawList(); + const float min_widget_width = CalcTextSize("R: MMM\nN: MMM").x; for (int n = 0; n < 8; n++) { const float RAD_MIN = 5.0f; const float RAD_MAX = 70.0f; const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (8.0f - 1.0f); - ImGui::BeginGroup(); + BeginGroup(); // N is not always exact here due to how PathArcTo() function work internally - ImGui::Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad)); + Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad)); const float canvas_width = IM_MAX(min_widget_width, rad * 2.0f); const float offset_x = floorf(canvas_width * 0.5f); const float offset_y = floorf(RAD_MAX); - const ImVec2 p1 = ImGui::GetCursorScreenPos(); - draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text)); - ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2)); + const ImVec2 p1 = GetCursorScreenPos(); + draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, GetColorU32(ImGuiCol_Text)); + Dummy(ImVec2(canvas_width, RAD_MAX * 2)); /* - const ImVec2 p2 = ImGui::GetCursorScreenPos(); - draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text)); - ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2)); + const ImVec2 p2 = GetCursorScreenPos(); + draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, GetColorU32(ImGuiCol_Text)); + Dummy(ImVec2(canvas_width, RAD_MAX * 2)); */ - ImGui::EndGroup(); - ImGui::SameLine(); + EndGroup(); + SameLine(); } - ImGui::EndTooltip(); + EndTooltip(); } - ImGui::SameLine(); + SameLine(); HelpMarker("When drawing circle primitives with \"num_segments == 0\" tessellation will be calculated automatically."); - ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. - ImGui::DragFloat("Disabled Alpha", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha)."); - ImGui::PopItemWidth(); + DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. + DragFloat("Disabled Alpha", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, "%.2f"); SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha)."); + PopItemWidth(); - ImGui::EndTabItem(); + EndTabItem(); } - ImGui::EndTabBar(); + EndTabBar(); } - - ImGui::PopItemWidth(); + PopItemWidth(); } //----------------------------------------------------------------------------- // [SECTION] User Guide / ShowUserGuide() //----------------------------------------------------------------------------- +// We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. void ImGui::ShowUserGuide() { - ImGuiIO& io = ImGui::GetIO(); - ImGui::BulletText("Double-click on title bar to collapse window."); - ImGui::BulletText( + ImGuiIO& io = GetIO(); + BulletText("Double-click on title bar to collapse window."); + BulletText( "Click and drag on lower corner to resize window\n" "(double-click to auto fit window to its contents)."); - ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text."); - ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); - ImGui::BulletText("CTRL+Tab to select a window."); + BulletText("CTRL+Click on a slider or drag box to input value as text."); + BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); + BulletText("CTRL+Tab to select a window."); if (io.FontAllowUserScaling) - ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); - ImGui::BulletText("While inputting text:\n"); - ImGui::Indent(); - ImGui::BulletText("CTRL+Left/Right to word jump."); - ImGui::BulletText("CTRL+A or double-click to select all."); - ImGui::BulletText("CTRL+X/C/V to use clipboard cut/copy/paste."); - ImGui::BulletText("CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo."); - ImGui::BulletText("ESCAPE to revert."); - ImGui::Unindent(); - ImGui::BulletText("With keyboard navigation enabled:"); - ImGui::Indent(); - ImGui::BulletText("Arrow keys to navigate."); - ImGui::BulletText("Space to activate a widget."); - ImGui::BulletText("Return to input text into a widget."); - ImGui::BulletText("Escape to deactivate a widget, close popup, exit child window."); - ImGui::BulletText("Alt to jump to the menu layer of a window."); - ImGui::Unindent(); + BulletText("CTRL+Mouse Wheel to zoom window contents."); + BulletText("While inputting text:\n"); + Indent(); + BulletText("CTRL+Left/Right to word jump."); + BulletText("CTRL+A or double-click to select all."); + BulletText("CTRL+X/C/V to use clipboard cut/copy/paste."); + BulletText("CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo."); + BulletText("ESCAPE to revert."); + Unindent(); + BulletText("With keyboard navigation enabled:"); + Indent(); + BulletText("Arrow keys to navigate."); + BulletText("Space to activate a widget."); + BulletText("Return to input text into a widget."); + BulletText("Escape to deactivate a widget, close popup, exit child window."); + BulletText("Alt to jump to the menu layer of a window."); + Unindent(); } //----------------------------------------------------------------------------- From c3d7ada9dfa8dc8ba80fb72d824ca70e2688a48b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Jun 2025 22:27:34 +0200 Subject: [PATCH 0884/2359] Demo: add indentation to simplify upcoming merges. --- imgui_demo.cpp | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 14dcc3204..3a6f3a501 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8244,18 +8244,21 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) PushItemWidth(GetWindowWidth() * 0.50f); - if (ShowStyleSelector("Colors##Selector")) - ref_saved_style = style; - ShowFontSelector("Fonts##Selector"); + { + // General + if (ShowStyleSelector("Colors##Selector")) + ref_saved_style = style; + ShowFontSelector("Fonts##Selector"); - // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) - if (SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) - style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding - { bool border = (style.WindowBorderSize > 0.0f); if (Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } - SameLine(); - { bool border = (style.FrameBorderSize > 0.0f); if (Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } - SameLine(); - { bool border = (style.PopupBorderSize > 0.0f); if (Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } + // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) + if (SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) + style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding + { bool border = (style.WindowBorderSize > 0.0f); if (Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } + SameLine(); + { bool border = (style.FrameBorderSize > 0.0f); if (Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } + SameLine(); + { bool border = (style.PopupBorderSize > 0.0f); if (Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } + } // Save/Revert button if (Button("Save Ref")) From 201899b611c34d35e6e38778abab91d76b0451c0 Mon Sep 17 00:00:00 2001 From: Dylam De La Torre Date: Wed, 4 Jun 2025 23:08:19 +0200 Subject: [PATCH 0885/2359] Backends: OpenGL3: Fixed using non-existing features on GLES 3.20 which would push a GL error. (#8664) * GL_PRIMITIVE_RESTART is not a valid enum for glEnable&co on GLES 3.20 * GL_CONTEXT_PROFILE_MASK is not a valid enum for glGetIntegerv on GLES 3.20 --- backends/imgui_impl_opengl3.cpp | 18 ++++++++++-------- docs/CHANGELOG.txt | 2 ++ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 7d0b53621..8b7a2ecb5 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-04: OpenGL: Made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664) // 2025-02-18: OpenGL: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) @@ -325,11 +326,6 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) if (major == 0 && minor == 0) sscanf(gl_version_str, "%d.%d", &major, &minor); // Query GL_VERSION in desktop GL 2.x, the string will start with "." bd->GlVersion = (GLuint)(major * 100 + minor * 10); -#if defined(GL_CONTEXT_PROFILE_MASK) - if (bd->GlVersion >= 320) - glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask); - bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0; -#endif #if defined(IMGUI_IMPL_OPENGL_ES3) bd->GlProfileIsES3 = true; @@ -338,6 +334,12 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) bd->GlProfileIsES3 = true; #endif +#if defined(GL_CONTEXT_PROFILE_MASK) + if (!bd->GlProfileIsES3 && bd->GlVersion >= 320) + glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask); + bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0; +#endif + bd->UseBufferSubData = false; /* // Query vendor to enable glBufferSubData kludge @@ -439,7 +441,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glDisable(GL_STENCIL_TEST); glEnable(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART - if (bd->GlVersion >= 310) + if (!bd->GlProfileIsES3 && bd->GlVersion >= 310) glDisable(GL_PRIMITIVE_RESTART); #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE @@ -551,7 +553,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART - GLboolean last_enable_primitive_restart = (bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; + GLboolean last_enable_primitive_restart = (!bd->GlProfileIsES3 && bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; #endif // Setup desired GL state @@ -670,7 +672,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART - if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } + if (!bd->GlProfileIsES3 && bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e490133ca..059daf5b5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -149,6 +149,8 @@ Other changes: - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] - Backends: SDLGPU3: added support for ImDrawCallback_ResetRenderState. (#8599) +- Backends: OpenGL3: made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor + GL_PRIMITIVE_RESTART. (#8664) [@DyXel] - Backends: DirectX10, DirectX11, DirectX12: Honor FramebufferScale to allow for custom platform backends and experiments using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). (#8412) [@WSSDude] From b2f39318cb10eb51f37f393bd5c6bbe07dd0edcd Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 13:41:06 +0200 Subject: [PATCH 0886/2359] Adding .cache to ignore list. (#8674) --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6cadd63b4..6f6c50cb4 100644 --- a/.gitignore +++ b/.gitignore @@ -29,8 +29,9 @@ ipch ## Getting files created in JSON/Schemas/Catalog/ from a VS2022 update JSON/ -## Commonly used CMake directories +## Commonly used CMake directories & CMake CPM cache build*/ +.cache ## Xcode & macOS artifacts project.xcworkspace From 191a728ecca454f11ff473e285804d1f7362a83d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 19:13:17 +0100 Subject: [PATCH 0887/2359] (Breaking) added ImTextureRef struct. Changed ImDrawCmd::TextureId to TexRef. Softly breaking. May require support from language binding generator. Rebased and reworked completely on 2025/03/19. --- imgui.cpp | 30 +++++------ imgui.h | 75 +++++++++++++++++++--------- imgui_demo.cpp | 2 +- imgui_draw.cpp | 85 +++++++++++++++++--------------- imgui_internal.h | 2 +- imgui_widgets.cpp | 22 ++++----- misc/freetype/imgui_freetype.cpp | 2 +- 7 files changed, 126 insertions(+), 92 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index df41d9713..bb5819a37 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3841,12 +3841,12 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale))) continue; ImDrawList* draw_list = GetForegroundDrawList(viewport); - ImTextureID tex_id = font_atlas->TexID; - draw_list->PushTextureID(tex_id); - draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow); - draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); - draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border); - draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill); + ImTextureRef tex_ref = font_atlas->TexID; + draw_list->PushTexture(tex_ref); + draw_list->AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[2], uv[3], col_border); + draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[0], uv[1], col_fill); if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress) { float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI); @@ -3854,7 +3854,7 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso draw_list->PathArcTo(pos + ImVec2(14, -1) * scale, 6.0f * scale, a_min, a_max); draw_list->PathStroke(col_fill, ImDrawFlags_None, 3.0f * scale); } - draw_list->PopTextureID(); + draw_list->PopTexture(); } } @@ -4925,7 +4925,7 @@ static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t draw if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount) { draw_list->_ResetForNewFrame(); - draw_list->PushTextureID(g.IO.Fonts->TexID); + draw_list->PushTexture(g.IO.Fonts->TexID); draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false); viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount; } @@ -7580,7 +7580,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Setup draw list and outer clipping rectangle IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); - window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); + window->DrawList->PushTexture(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71) @@ -8553,7 +8553,7 @@ void ImGui::PushFont(ImFont* font) font = GetDefaultFont(); g.FontStack.push_back(font); SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); + g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexID); } void ImGui::PopFont() @@ -8567,7 +8567,7 @@ void ImGui::PopFont() g.FontStack.pop_back(); ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); + g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexID); } //----------------------------------------------------------------------------- @@ -15500,11 +15500,11 @@ void ImGui::UpdateDebugToolFlashStyleColor() DebugFlashStyleColorStop(); } -static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id) +static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureRef tex_ref) { union { void* ptr; int integer; } tex_id_opaque; - memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id))); - if (sizeof(tex_id) >= sizeof(void*)) + memcpy(&tex_id_opaque, &tex_ref._TexID, ImMin(sizeof(void*), sizeof(tex_ref._TexID))); + if (sizeof(tex_ref._TexID) >= sizeof(void*)) ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr); else ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer); @@ -16245,7 +16245,7 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con } char texid_desc[20]; - FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId); + FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TexRef); char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); diff --git a/imgui.h b/imgui.h index 6d062c190..0e8f9c1ae 100644 --- a/imgui.h +++ b/imgui.h @@ -37,7 +37,7 @@ Index of this file: // [SECTION] Header mess // [SECTION] Forward declarations and basic types -// [SECTION] Texture identifier (ImTextureID) +// [SECTION] Texture identifiers (ImTextureID, ImTextureRef) // [SECTION] Dear ImGui end-user API functions // [SECTION] Flags & Enumerations // [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) @@ -301,18 +301,38 @@ struct ImVec4 IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- -// [SECTION] Texture identifier (ImTextureID) +// [SECTION] Texture identifiers (ImTextureID, ImTextureRef) //----------------------------------------------------------------------------- -// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type] +// ImTextureID: user data for renderer backend to identify a texture [Compile-time configurable type] // - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. // - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. // - You can make this a structure with various constructors if you need. You will have to implement ==/!= operators. // - (note: before v1.91.4 (2024/10/08) the default type for ImTextureID was void*. Use intermediary intptr_t cast and read FAQ if you have casting warnings) #ifndef ImTextureID -typedef ImU64 ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) +typedef ImU64 ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) #endif +// ImTextureRef contains: +// - a texture/atlas pointer, typically when created by Dear ImGui itself. +// - OR a raw ImTextureID value (user/backend identifier), typically when created by user code to load images. +// There is no constructor to create a ImTextureID from a ImTextureData* as we don't expect this to be useful to the end-user. +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImTextureRef +{ + ImTextureRef() { memset(this, 0, sizeof(*this)); } + ImTextureRef(ImTextureID tex_id) { memset(this, 0, sizeof(*this)); _TexID = tex_id; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImTextureRef(void* tex_id) { memset(this, 0, sizeof(*this)); _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID + //inline operator intptr_t() const { return (intptr_t)_TexID; } // For legacy backends casting to ImTextureID +#endif + + // Members + ImFontAtlas* _Atlas; // Texture/Atlas pointer + ImTextureID _TexID; // _OR_ Underlying user/backend texture identifier, or zero if not yet uploaded. +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + //----------------------------------------------------------------------------- // [SECTION] Dear ImGui end-user API functions // (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) @@ -567,9 +587,9 @@ namespace ImGui // - Image() pads adds style.ImageBorderSize on each side, ImageButton() adds style.FramePadding on each side. // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. // - 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(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1)); - IMGUI_API void ImageWithBg(ImTextureID user_texture_id, 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, ImTextureID user_texture_id, 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 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)); // 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. @@ -3004,11 +3024,11 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c // - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, // this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. // Backends made for <1.71. will typically ignore the VtxOffset fields. -// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). +// - The ClipRect/TexRef/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). struct ImDrawCmd { ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates - ImTextureID TextureId; // 4-8 // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + ImTextureRef TexRef; // 16 // User-provided texture ID. Set by user in ImFontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. unsigned int IdxOffset; // 4 // Start offset in index buffer. unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. @@ -3020,7 +3040,8 @@ struct ImDrawCmd ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) - inline ImTextureID GetTexID() const { return TextureId; } + // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! + inline ImTextureID GetTexID() const { return TexRef._TexID; } }; // Vertex layout @@ -3043,7 +3064,7 @@ IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; struct ImDrawCmdHeader { ImVec4 ClipRect; - ImTextureID TextureId; + ImTextureRef TexRef; unsigned int VtxOffset; }; @@ -3128,7 +3149,7 @@ struct ImDrawList ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back(). ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) ImVector _ClipRectStack; // [Internal] - ImVector _TextureIdStack; // [Internal] + ImVector _TextureStack; // [Internal] ImVector _CallbacksDataBuf; // [Internal] float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content const char* _OwnerName; // Pointer to owner window's name for debugging @@ -3141,8 +3162,8 @@ struct ImDrawList IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); IMGUI_API void PopClipRect(); - IMGUI_API void PushTextureID(ImTextureID texture_id); - IMGUI_API void PopTextureID(); + IMGUI_API void PushTexture(ImTextureRef tex_ref); + IMGUI_API void PopTexture(); inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } @@ -3180,12 +3201,12 @@ struct ImDrawList IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); // Image primitives - // - Read FAQ to understand what ImTextureID is. + // - Read FAQ to understand what ImTextureID/ImTextureRef are. // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. - IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); + IMGUI_API void AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); // Stateful path API, add points then finish with PathFillConvex() or PathStroke() // - Important: filled shapes must always use clockwise winding order! The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. @@ -3241,6 +3262,10 @@ struct ImDrawList inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //IMGUI_API void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x + //IMGUI_API void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x +#endif //inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void PathEllipticalArcTo(const ImVec2& center, float radius_x, float radius_y, float rot, float a_min, float a_max, int num_segments = 0) { PathEllipticalArcTo(center, ImVec2(radius_x, radius_y), rot, a_min, a_max, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) @@ -3253,9 +3278,9 @@ struct ImDrawList IMGUI_API void _PopUnusedDrawCmd(); IMGUI_API void _TryMergeDrawCmds(); IMGUI_API void _OnChangedClipRect(); - IMGUI_API void _OnChangedTextureID(); + IMGUI_API void _OnChangedTexture(); IMGUI_API void _OnChangedVtxOffset(); - IMGUI_API void _SetTextureID(ImTextureID texture_id); + IMGUI_API void _SetTexture(ImTextureRef tex_ref); IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); @@ -3412,7 +3437,11 @@ struct ImFontAtlas IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel bool IsBuilt() const { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... - void SetTexID(ImTextureID id) { TexID = id; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + void SetTexID(ImTextureID id){ TexID._Atlas = this; TexID._TexID = id; } // FIXME-NEWATLAS: Called by legacy backends. + void SetTexID(ImTextureRef id) { TexID = id; } // FIXME-NEWATLAS: Called by legacy backends. +#endif + //------------------------------------------- // Glyph Ranges @@ -3456,7 +3485,7 @@ struct ImFontAtlas // Input ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) - ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. + ImTextureRef TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). @@ -3654,7 +3683,7 @@ struct ImGuiPlatformImeData namespace ImGui { // OBSOLETED in 1.91.9 (from February 2025) - IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. + IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } static inline void PopButtonRepeat() { PopItemFlag(); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3a6f3a501..790f37611 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1778,7 +1778,7 @@ static void DemoWindowWidgetsImages() // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - ImTextureID my_tex_id = io.Fonts->TexID; + ImTextureRef my_tex_id = io.Fonts->TexID; float my_tex_w = (float)io.Fonts->TexWidth; float my_tex_h = (float)io.Fonts->TexHeight; { diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 78b0e152e..8a31b79f7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -423,8 +423,8 @@ void ImDrawList::_ResetForNewFrame() { // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. IM_STATIC_ASSERT(offsetof(ImDrawCmd, ClipRect) == 0); - IM_STATIC_ASSERT(offsetof(ImDrawCmd, TextureId) == sizeof(ImVec4)); - IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, TexRef) == sizeof(ImVec4)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureRef)); if (_Splitter._Count > 1) _Splitter.Merge(this); @@ -437,7 +437,7 @@ void ImDrawList::_ResetForNewFrame() _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.resize(0); - _TextureIdStack.resize(0); + _TextureStack.resize(0); _CallbacksDataBuf.resize(0); _Path.resize(0); _Splitter.Clear(); @@ -455,7 +455,7 @@ void ImDrawList::_ClearFreeMemory() _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.clear(); - _TextureIdStack.clear(); + _TextureStack.clear(); _CallbacksDataBuf.clear(); _Path.clear(); _Splitter.ClearFreeMemory(); @@ -475,7 +475,7 @@ void ImDrawList::AddDrawCmd() { ImDrawCmd draw_cmd; draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy() - draw_cmd.TextureId = _CmdHeader.TextureId; + draw_cmd.TexRef = _CmdHeader.TexRef; draw_cmd.VtxOffset = _CmdHeader.VtxOffset; draw_cmd.IdxOffset = IdxBuffer.Size; @@ -530,10 +530,10 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* userdata, size_t use AddDrawCmd(); // Force a new command after us (see comment below) } -// Compare ClipRect, TextureId and VtxOffset with a single memcmp() +// Compare ClipRect, TexRef and VtxOffset with a single memcmp() #define ImDrawCmd_HeaderSize (offsetof(ImDrawCmd, VtxOffset) + sizeof(unsigned int)) -#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TextureId, VtxOffset -#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TextureId, VtxOffset +#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TexRef, VtxOffset +#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TexRef, VtxOffset #define ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) (CMD_0->IdxOffset + CMD_0->ElemCount == CMD_1->IdxOffset) // Try to merge two last draw commands @@ -573,12 +573,16 @@ void ImDrawList::_OnChangedClipRect() curr_cmd->ClipRect = _CmdHeader.ClipRect; } -void ImDrawList::_OnChangedTextureID() +// Operators for easy compare +static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._Atlas == rhs._Atlas; } +static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._Atlas != rhs._Atlas; } + +void ImDrawList::_OnChangedTexture() { // If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(CmdBuffer.Size > 0); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) + if (curr_cmd->ElemCount != 0 && curr_cmd->TexRef != _CmdHeader.TexRef) { AddDrawCmd(); return; @@ -592,7 +596,7 @@ void ImDrawList::_OnChangedTextureID() CmdBuffer.pop_back(); return; } - curr_cmd->TextureId = _CmdHeader.TextureId; + curr_cmd->TexRef = _CmdHeader.TexRef; } void ImDrawList::_OnChangedVtxOffset() @@ -653,27 +657,27 @@ void ImDrawList::PopClipRect() _OnChangedClipRect(); } -void ImDrawList::PushTextureID(ImTextureID texture_id) +void ImDrawList::PushTexture(ImTextureRef tex_ref) { - _TextureIdStack.push_back(texture_id); - _CmdHeader.TextureId = texture_id; - _OnChangedTextureID(); + _TextureStack.push_back(tex_ref); + _CmdHeader.TexRef = tex_ref; + _OnChangedTexture(); } -void ImDrawList::PopTextureID() +void ImDrawList::PopTexture() { - _TextureIdStack.pop_back(); - _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1]; - _OnChangedTextureID(); + _TextureStack.pop_back(); + _CmdHeader.TexRef = (_TextureStack.Size == 0) ? ImTextureRef() : _TextureStack.Data[_TextureStack.Size - 1]; + _OnChangedTexture(); } // This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTextureID()/PopTextureID(). -void ImDrawList::_SetTextureID(ImTextureID texture_id) +void ImDrawList::_SetTexture(ImTextureRef tex_ref) { - if (_CmdHeader.TextureId == texture_id) + if (_CmdHeader.TexRef == tex_ref) return; - _CmdHeader.TextureId = texture_id; - _OnChangedTextureID(); + _CmdHeader.TexRef = tex_ref; + _OnChangedTexture(); } // Reserve space for a number of vertices and indices. @@ -1686,7 +1690,7 @@ void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 if (font_size == 0.0f) font_size = _Data->FontSize; - IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TextureId); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TexRef); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. ImVec4 clip_rect = _CmdHeader.ClipRect; if (cpu_fine_clip_rect) @@ -1704,39 +1708,39 @@ void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, c AddText(_Data->Font, _Data->FontSize, pos, col, text_begin, text_end); } -void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) +void ImDrawList::AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; - const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; if (push_texture_id) - PushTextureID(user_texture_id); + PushTexture(tex_ref); PrimReserve(6, 4); PrimRectUV(p_min, p_max, uv_min, uv_max, col); if (push_texture_id) - PopTextureID(); + PopTexture(); } -void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col) +void ImDrawList::AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; - const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; if (push_texture_id) - PushTextureID(user_texture_id); + PushTexture(tex_ref); PrimReserve(6, 4); PrimQuadUV(p1, p2, p3, p4, uv1, uv2, uv3, uv4, col); if (push_texture_id) - PopTextureID(); + PopTexture(); } -void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags) +void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; @@ -1744,13 +1748,13 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi flags = FixRectCornerFlags(flags); if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { - AddImage(user_texture_id, p_min, p_max, uv_min, uv_max, col); + AddImage(tex_ref, p_min, p_max, uv_min, uv_max, col); return; } - const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; if (push_texture_id) - PushTextureID(user_texture_id); + PushTexture(tex_ref); int vert_start_idx = VtxBuffer.Size; PathRect(p_min, p_max, rounding, flags); @@ -1759,7 +1763,7 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); if (push_texture_id) - PopTextureID(); + PopTexture(); } //----------------------------------------------------------------------------- @@ -2187,7 +2191,7 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; if (curr_cmd->ElemCount == 0) - ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TexRef, VtxOffset else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) draw_list->AddDrawCmd(); @@ -2213,7 +2217,7 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) if (curr_cmd == NULL) draw_list->AddDrawCmd(); else if (curr_cmd->ElemCount == 0) - ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TexRef, VtxOffset else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) draw_list->AddDrawCmd(); } @@ -2483,6 +2487,7 @@ ImFontAtlas::ImFontAtlas() { memset(this, 0, sizeof(*this)); TexGlyphPadding = 1; + TexID._Atlas = this; PackIdMouseCursors = PackIdLines = -1; } @@ -2882,7 +2887,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) ImFontAtlasBuildInit(atlas); // Clear atlas - atlas->TexID = (ImTextureID)NULL; + atlas->TexID._TexID = 0; atlas->TexWidth = atlas->TexHeight = 0; atlas->TexUvScale = ImVec2(0.0f, 0.0f); atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index ca250e0b7..91ac0bc83 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3454,7 +3454,7 @@ namespace ImGui // 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 ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 341bf2712..1c22bd4c6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1103,9 +1103,9 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 return held; } -// - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples +// - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. -void ImGui::ImageWithBg(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) +void ImGui::ImageWithBg(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 = GetCurrentWindow(); @@ -1123,28 +1123,28 @@ void ImGui::ImageWithBg(ImTextureID user_texture_id, const ImVec2& image_size, c window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), 0.0f, ImDrawFlags_None, g.Style.ImageBorderSize); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); - window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); } -void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1) +void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1) { - ImageWithBg(user_texture_id, image_size, uv0, uv1); + ImageWithBg(tex_ref, image_size, uv0, uv1); } // 1.91.9 (February 2025) removed 'tint_col' and 'border_col' parameters, made border size not depend on color value. (#8131, #8238) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { ImGuiContext& g = *GImGui; PushStyleVar(ImGuiStyleVar_ImageBorderSize, (border_col.w > 0.0f) ? ImMax(1.0f, g.Style.ImageBorderSize) : 0.0f); // Preserve legacy behavior where border is always visible when border_col's Alpha is >0.0f PushStyleColor(ImGuiCol_Border, border_col); - ImageWithBg(user_texture_id, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col); + ImageWithBg(tex_ref, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col); PopStyleColor(); PopStyleVar(); } #endif -bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags) +bool ImGui::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) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -1166,21 +1166,21 @@ bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding)); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); - window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); return pressed; } // - 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, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) +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) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return false; - return ImageButtonEx(window->GetID(str_id), user_texture_id, image_size, uv0, uv1, bg_col, tint_col); + return ImageButtonEx(window->GetID(str_id), tex_ref, image_size, uv0, uv1, bg_col, tint_col); } #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 39a997e67..6521f83b9 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -448,7 +448,7 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u ImFontAtlasBuildInit(atlas); // Clear atlas - atlas->TexID = 0; + atlas->TexID._TexID = 0; atlas->TexWidth = atlas->TexHeight = 0; atlas->TexUvScale = ImVec2(0.0f, 0.0f); atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); From 0f0473bf1c9d6e4cd74dde883f37f87f57165096 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Nov 2024 13:42:35 +0100 Subject: [PATCH 0888/2359] Fonts, Textures: main code for ImGuiBackendFlags_RendererHasTextures feature. # Conflicts: # imgui.h # imgui_demo.cpp --- examples/example_null/main.cpp | 7 +- imgui.cpp | 180 ++- imgui.h | 212 +++- imgui_demo.cpp | 13 +- imgui_draw.cpp | 2004 ++++++++++++++++++++---------- imgui_internal.h | 127 +- imgui_widgets.cpp | 5 +- misc/freetype/imgui_freetype.cpp | 4 +- 8 files changed, 1750 insertions(+), 802 deletions(-) diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index f7153cc48..460f33cab 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -11,9 +11,10 @@ int main(int, char**) ImGuiIO& io = ImGui::GetIO(); // Build atlas - unsigned char* tex_pixels = nullptr; - int tex_w, tex_h; - io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_w, &tex_h); + //unsigned char* tex_pixels = nullptr; + //int tex_w, tex_h; + //io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_w, &tex_h); + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; for (int n = 0; n < 20; n++) { diff --git a/imgui.cpp b/imgui.cpp index bb5819a37..5acd91c0c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1270,6 +1270,7 @@ static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt); // Misc static void UpdateFontsNewFrame(); +static void UpdateTexturesNewFrame(); static void UpdateSettings(); static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowOuterBorders(ImGuiWindow* window); @@ -3841,7 +3842,7 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale))) continue; ImDrawList* draw_list = GetForegroundDrawList(viewport); - ImTextureRef tex_ref = font_atlas->TexID; + ImTextureRef tex_ref = font_atlas->TexRef; draw_list->PushTexture(tex_ref); draw_list->AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow); draw_list->AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); @@ -4194,6 +4195,11 @@ void ImGui::Initialize() #ifdef IMGUI_HAS_DOCK #endif + // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context. + // But this link allows us to facilitate/handle a few edge cases better. + g.DrawListSharedData.Context = &g; + ImFontAtlasAddDrawListSharedData(g.IO.Fonts, &g.DrawListSharedData); + g.Initialized = true; } @@ -4205,6 +4211,8 @@ void ImGui::Shutdown() IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?"); // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) + if (g.IO.Fonts) + ImFontAtlasRemoveDrawListSharedData(g.IO.Fonts, &g.DrawListSharedData); if (g.IO.Fonts && g.FontAtlasOwnedByContext) { g.IO.Fonts->Locked = false; @@ -4339,7 +4347,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL SettingsOffset = -1; DrawList = &DrawListInst; DrawList->_OwnerName = Name; - DrawList->_Data = &Ctx->DrawListSharedData; + DrawList->_SetDrawListSharedData(&Ctx->DrawListSharedData); NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX); } @@ -4925,7 +4933,7 @@ static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t draw if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount) { draw_list->_ResetForNewFrame(); - draw_list->PushTexture(g.IO.Fonts->TexID); + draw_list->PushTexture(g.IO.Fonts->TexRef); draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false); viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount; } @@ -5166,6 +5174,14 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; } +static void ImGui::UpdateTexturesNewFrame() +{ + // FIXME-NEWATLAS: How to reach/target all atlas? + ImGuiContext& g = *GImGui; + ImFontAtlas* atlas = g.IO.Fonts; + ImFontAtlasUpdateNewFrame(atlas); +} + // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! static void SetupDrawListSharedData() @@ -5202,6 +5218,13 @@ void ImGui::NewFrame() CallContextHooks(&g, ImGuiContextHookType_NewFramePre); + // Check that font atlas was built or backend support texture reload in which case we can build now + ImFontAtlas* atlas = g.IO.Fonts; + if (!atlas->TexIsBuilt && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) + atlas->Build(); + else // Legacy backend + IM_ASSERT(atlas->TexIsBuilt && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()"); + // Check and assert for various common IO and Configuration mistakes ErrorCheckNewFrameSanityChecks(); @@ -5209,7 +5232,6 @@ void ImGui::NewFrame() UpdateSettings(); g.Time += g.IO.DeltaTime; - g.WithinFrameScope = true; g.FrameCount += 1; g.TooltipOverrideCount = 0; g.WindowsActiveCount = 0; @@ -5229,10 +5251,15 @@ void ImGui::NewFrame() // Update viewports (after processing input queue, so io.MouseHoveredViewport is set) UpdateViewportsNewFrame(); + // Update texture list (collect destroyed textures, etc.) + UpdateTexturesNewFrame(); + // Setup current font and draw list shared data SetupDrawListSharedData(); UpdateFontsNewFrame(); + g.WithinFrameScope = true; + // Mark rendering data as invalid to prevent user who may have a handle on it to use it. for (ImGuiViewportP* viewport : g.Viewports) viewport->DrawDataP.Valid = false; @@ -5810,6 +5837,11 @@ void ImGui::Render() g.IO.MetricsRenderIndices += draw_data->TotalIdxCount; } +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + ImFontAtlasDebugLogTextureRequests(g.IO.Fonts); +#endif + CallContextHooks(&g, ImGuiContextHookType_RenderPost); } @@ -7580,7 +7612,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Setup draw list and outer clipping rectangle IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); - window->DrawList->PushTexture(g.Font->ContainerAtlas->TexID); + window->DrawList->PushTexture(g.Font->ContainerAtlas->TexRef); PushClipRect(host_rect.Min, host_rect.Max, false); // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71) @@ -8515,7 +8547,12 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) void ImGui::UpdateFontsNewFrame() { ImGuiContext& g = *GImGui; - g.IO.Fonts->Locked = true; + if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + { + g.IO.Fonts->Locked = true; + for (ImFont* font : g.IO.Fonts->Fonts) + font->LockDisableLoading = true; + } SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); } @@ -8530,13 +8567,12 @@ void ImGui::SetCurrentFont(ImFont* font) g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; g.FontScale = g.FontSize / g.Font->FontSize; - - ImFontAtlas* atlas = g.Font->ContainerAtlas; - g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; - g.DrawListSharedData.TexUvLines = atlas->TexUvLines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; g.DrawListSharedData.FontScale = g.FontScale; + ImFontAtlasUpdateDrawListsSharedData(g.Font->ContainerAtlas); + if (g.CurrentWindow) + g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexRef); } // Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authoritative against window-local ImDrawList. @@ -8546,6 +8582,7 @@ void ImGui::SetCurrentFont(ImFont* font) // - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID() // the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem // because we have a concrete need and a test bed for multiple atlas textures. +// FIXME-NEWATLAS: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ? void ImGui::PushFont(ImFont* font) { ImGuiContext& g = *GImGui; @@ -8553,7 +8590,6 @@ void ImGui::PushFont(ImFont* font) font = GetDefaultFont(); g.FontStack.push_back(font); SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexID); } void ImGui::PopFont() @@ -8567,7 +8603,6 @@ void ImGui::PopFont() g.FontStack.pop_back(); ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexID); } //----------------------------------------------------------------------------- @@ -10278,7 +10313,6 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!"); IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!"); - IM_ASSERT(g.IO.Fonts->IsBuilt() && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()"); IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations @@ -15460,10 +15494,12 @@ void ImGui::DebugTextEncoding(const char* str) Text("0x%02X", (int)(unsigned char)p[byte_index]); } TableNextColumn(); - if (GetFont()->FindGlyphNoFallback((ImWchar)c)) - TextUnformatted(p, p + c_utf8_len); - else - TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]"); + TextUnformatted(p, p + c_utf8_len); + if (GetFont()->FindGlyphNoFallback((ImWchar)c) == NULL) + { + SameLine(); + TextUnformatted("[missing]"); + } TableNextColumn(); Text("U+%04X", (int)c); p += c_utf8_len; @@ -15500,17 +15536,25 @@ void ImGui::UpdateDebugToolFlashStyleColor() DebugFlashStyleColorStop(); } -static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureRef tex_ref) +static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id) { union { void* ptr; int integer; } tex_id_opaque; - memcpy(&tex_id_opaque, &tex_ref._TexID, ImMin(sizeof(void*), sizeof(tex_ref._TexID))); - if (sizeof(tex_ref._TexID) >= sizeof(void*)) + memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id))); + if (sizeof(tex_id) >= sizeof(void*)) ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr); else ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer); return buf; } +static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, const ImDrawCmd* cmd) +{ + char* buf_end = buf + buf_size; + if (cmd->TexRef._TexData != NULL) + buf += ImFormatString(buf, buf_end - buf, "#%03d: ", cmd->TexRef._TexData->UniqueID); + return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), cmd->GetTexID()); +} + // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. static void MetricsHelpMarker(const char* desc) { @@ -15524,6 +15568,10 @@ static void MetricsHelpMarker(const char* desc) } } +#ifdef IMGUI_ENABLE_FREETYPE +namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetBackendIOForFreeType(); } +#endif + // [DEBUG] List fonts in a font atlas and display its texture void ImGui::ShowFontAtlas(ImFontAtlas* atlas) { @@ -15538,6 +15586,36 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; Checkbox("Show font preview", &cfg->ShowFontPreview); + // Font loaders + if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL")) + { + const ImFontLoader* loader_current = atlas->FontLoader; + BeginDisabled(!atlas->DrawListSharedData || !atlas->DrawListSharedData->RendererHasTextures); +#ifdef IMGUI_ENABLE_STB_TRUETYPE + const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype(); + if (RadioButton("stb_truetype", loader_current == loader_stbtruetype)) + ImFontAtlasBuildSetupFontLoader(atlas, loader_stbtruetype); +#else + BeginDisabled(); + RadioButton("stb_truetype", false); + SetItemTooltip("Requires IMGUI_ENABLE_STB_TRUETYPE"); + EndDisabled(); +#endif + SameLine(); +#ifdef IMGUI_ENABLE_FREETYPE + const ImFontLoader* loader_freetype = ImGuiFreeType::GetBackendIOForFreeType(); + if (RadioButton("FreeType", loader_current == loader_freetype)) + ImFontAtlasBuildSetupFontLoader(atlas, loader_freetype); +#else + BeginDisabled(); + RadioButton("FreeType", false); + SetItemTooltip("Requires IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp."); + EndDisabled(); +#endif + EndDisabled(); + TreePop(); + } + // Font list for (ImFont* font : atlas->Fonts) { @@ -15545,11 +15623,32 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) DebugNodeFont(font); PopID(); } - if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) + + // Texture list + for (ImTextureData* tex : atlas->TexList) + { + PushID(tex); + DebugNodeTexture(tex); + PopID(); + } +} + +void ImGui::DebugNodeTexture(ImTextureData* tex) +{ + ImGuiContext& g = *GImGui; + if (TreeNode(tex, "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height)) { PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); - ImageWithBg(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + ImTextureRef tex_id; + tex_id._TexData = tex; // Don't use tex->TexID directly so first frame works. + ImageWithBg(tex_id, ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); PopStyleVar(); + + char texid_desc[20]; + Text("Format = %d", tex->Format); + Text("TexID = %s", FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->TexID)); + Text("BackendUserData = %p", tex->BackendUserData); + Text("UseColors = %d", tex->UseColors); TreePop(); } } @@ -15793,6 +15892,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) TreePop(); } + // Details for Fonts + ImFontAtlas* atlas = g.IO.Fonts; + if (TreeNode("Fonts", "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size)) + { + ShowFontAtlas(atlas); + TreePop(); + } + // Details for Popups if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) { @@ -15829,14 +15936,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) TreePop(); } - // Details for Fonts - ImFontAtlas* atlas = g.IO.Fonts; - if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size)) - { - ShowFontAtlas(atlas); - TreePop(); - } - // Details for InputText if (TreeNode("InputText")) { @@ -16245,7 +16344,7 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con } char texid_desc[20]; - FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TexRef); + FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd); char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); @@ -16379,7 +16478,7 @@ void ImGui::DebugNodeFont(ImFont* font) for (int config_i = 0; config_i < font->SourcesCount; config_i++) if (font->Sources) { - const ImFontConfig* src = &font->Sources[config_i]; + ImFontConfig* src = &font->Sources[config_i]; int oversample_h, oversample_v; ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", @@ -16390,6 +16489,10 @@ void ImGui::DebugNodeFont(ImFont* font) { if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) { + if (SmallButton("Load all")) + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++) + font->FindGlyph((ImWchar)base); + ImDrawList* draw_list = GetWindowDrawList(); const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); const float cell_size = font->FontSize * 1; @@ -16407,7 +16510,7 @@ void ImGui::DebugNodeFont(ImFont* font) int count = 0; for (unsigned int n = 0; n < 256; n++) - if (font->FindGlyphNoFallback((ImWchar)(base + n))) + if (font->IsGlyphLoaded((ImWchar)(base + n))) count++; if (count <= 0) continue; @@ -16422,7 +16525,7 @@ void ImGui::DebugNodeFont(ImFont* font) // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); - const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); + const ImFontGlyph* glyph = font->IsGlyphLoaded((ImWchar)(base + n)) ? font->FindGlyph((ImWchar)(base + n)) : NULL; draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); if (!glyph) continue; @@ -16443,7 +16546,7 @@ void ImGui::DebugNodeFont(ImFont* font) Unindent(); } -void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph) +void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) { Text("Codepoint: U+%04X", glyph->Codepoint); Separator(); @@ -16451,6 +16554,11 @@ void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph) Text("AdvanceX: %.1f", glyph->AdvanceX); Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + if (glyph->PackId >= 0) + { + ImFontAtlasRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId); + Text("PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y);; + } } // [DEBUG] Display contents of ImGuiStorage @@ -16727,7 +16835,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open) ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper); ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus); ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO); - //ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont); + ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont); ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav); ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup); ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection); diff --git a/imgui.h b/imgui.h index 0e8f9c1ae..0420b4358 100644 --- a/imgui.h +++ b/imgui.h @@ -31,6 +31,7 @@ #define IMGUI_VERSION "1.92.0 WIP" #define IMGUI_VERSION_NUM 19197 #define IMGUI_HAS_TABLE +#define IMGUI_HAS_TEXTURES // 1.92+ WIP branch with ImGuiBackendFlags_RendererHasTextures /* @@ -48,6 +49,7 @@ Index of this file: // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) +// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) // [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformImeData) @@ -169,10 +171,13 @@ struct ImDrawListSplitter; // Helper to split a draw list into differen struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader -struct ImFontBuilderIO; // Opaque interface to a font builder (stb_truetype or FreeType). +struct ImFontAtlasBuilder; // Opaque storage for building a ImFontAtlas struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data +struct ImFontLoader; // Opaque interface to a font loading backend (stb_truetype, FreeType etc.). +struct ImTextureData; // Specs and pixel storage for a texture used by Dear ImGui. +struct ImTextureRect; // Coordinates of a rectangle within a texture. struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) // Forward declarations: ImGui layer @@ -328,8 +333,8 @@ struct ImTextureRef #endif // Members - ImFontAtlas* _Atlas; // Texture/Atlas pointer - ImTextureID _TexID; // _OR_ Underlying user/backend texture identifier, or zero if not yet uploaded. + ImTextureData* _TexData; // Texture, generally owned by a ImFontAtlas + ImTextureID _TexID; // _OR_ Underlying texture identifier for backend, if already uploaded (otherwise pulled from _TexData) }; IM_MSVC_RUNTIME_CHECKS_RESTORE @@ -1638,6 +1643,7 @@ enum ImGuiBackendFlags_ ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + ImGuiBackendFlags_RendererHasTextures = 1 << 4, // Backend Renderer supports ImTextureData requests to create/update/destroy textures. This enables incremental texture updates and texture reloads. }; // Enumeration for PushStyleColor() / PopStyleColor() @@ -2794,6 +2800,14 @@ static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return IM_MSVC_RUNTIME_CHECKS_RESTORE #endif +// Helpers: ImTexture ==/!= operators provided as convenience (not strictly necessary) +static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } +static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } +//#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // For legacy backends +//static inline bool operator==(ImTextureID lhs, const ImTextureRef& rhs) { return lhs == rhs._TexID && rhs._TexData == NULL; } +//static inline bool operator==(const ImTextureRef& lhs, ImTextureID rhs) { return lhs._TexID == rhs && lhs._TexData == NULL; } +//#endif + // Helpers macros to generate 32-bit encoded colors // - User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file. // - Any setting other than the default will need custom backend support. The only standard backend that supports anything else than the default is DirectX9. @@ -3041,7 +3055,8 @@ struct ImDrawCmd // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! - inline ImTextureID GetTexID() const { return TexRef._TexID; } + // If for some reason you non C++ tech stack makes it difficult to call it, we may decide to separate the fields in ImDrawCmd. + inline ImTextureID GetTexID() const; }; // Vertex layout @@ -3273,6 +3288,7 @@ struct ImDrawList //inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021) // [Internal helpers] + IMGUI_API void _SetDrawListSharedData(ImDrawListSharedData* data); IMGUI_API void _ResetForNewFrame(); IMGUI_API void _ClearFreeMemory(); IMGUI_API void _PopUnusedDrawCmd(); @@ -3309,6 +3325,73 @@ struct ImDrawData IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. }; +//----------------------------------------------------------------------------- +// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureDataUpdate, ImTextureData +//----------------------------------------------------------------------------- + +// We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension. +enum ImTextureFormat +{ + ImTextureFormat_RGBA32, // 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + ImTextureFormat_Alpha8, // 1 component per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight +}; + +// Status of a texture +enum ImTextureStatus +{ + ImTextureStatus_OK, + ImTextureStatus_Destroyed, // Backend destroyed the texture. + ImTextureStatus_WantCreate, // Requesting backend to create the texture. Set status OK when done. + ImTextureStatus_WantUpdates, // Requesting backend to update specific blocks of pixels (write to texture portions which have never been used before). Set status OK when done. + ImTextureStatus_WantDestroy, // Requesting backend to destroy the texture. Set status to Destroyed when done. +}; + +// Coordinates of a rectangle within a texture. +// When a texture is in ImTextureStatus_WantUpdates state, we provide a list of individual rectangles to copy to GPU texture. +// You may use ImTextureData::Updates[] for the list, or ImTextureData::UpdateBox for a single bounding box. +struct ImTextureRect +{ + unsigned short x, y; // Upper-left coordinates of rectangle to update + unsigned short w, h; // Size of rectangle to update (in pixels) +}; + +// Specs and pixel storage for a texture used by Dear ImGui. +// The renderer backend will generally create a GPU-side version of this. +// Why does we store two identifiers: TexID and BackendUserData? +// - ImTextureID TexID = lower-level identifier stored in ImDrawCmd. ImDrawCmd can refer to textures not created by the backend, and for which there's no ImTextureData. +// - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both. +struct IMGUI_API ImTextureData +{ + ImTextureStatus Status; // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy + ImTextureFormat Format; // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8 + int Width; // Texture width + int Height; // Texture height + int BytesPerPixel; // 4 or 1 + int UniqueID; // Sequential index to facilitate identifying a texture when debugging/printing. Only unique per atlas. + unsigned char* Pixels; // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. + ImTextureID TexID; // Identifier stored in ImDrawCmd::GetTexID() and passed to backend RenderDrawData loop. + void* BackendUserData; // Convenience storage for backend. Some backends may have enough with TexID. + ImTextureRect UpdateRect; // Bounding box encompassing all individual updates. + ImVector Updates; // Array of individual updates. + int UnusedFrames; // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. + + // [Internal] + bool UseColors; // [Internal] Tell whether our texture data is known to use colors (rather than just white + alpha). + bool WantDestroyNextFrame; // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. + + // Functions + ImTextureData() { memset(this, 0, sizeof(*this)); } + ~ImTextureData() { DestroyPixels(); } + void Create(ImTextureFormat format, int w, int h); + void DestroyPixels(); + unsigned char* GetPixels() { IM_ASSERT(Pixels != NULL); return Pixels; } + unsigned char* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } + int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } + int GetPitch() const { return Width * BytesPerPixel; } + ImTextureRef GetTexRef() const { ImTextureRef tex_ref; tex_ref._TexData = (ImTextureData*)(void*)this; tex_ref._TexID = TexID; return tex_ref; } + ImTextureID GetTexID() const { return TexID; } +}; + //----------------------------------------------------------------------------- // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) //----------------------------------------------------------------------------- @@ -3338,7 +3421,8 @@ struct ImFontConfig // [Internal] char Name[40]; // Name (strictly to ease debugging) - ImFont* DstFont; + ImFont* DstFont; // Target font (as we merging fonts, multiple ImFontConfig may target the same font) + void* FontLoaderData; // Font loader opaque storage (per font config) IMGUI_API ImFontConfig(); }; @@ -3353,6 +3437,9 @@ struct ImFontGlyph float AdvanceX; // Horizontal distance to advance layout with float X0, Y0, X1, Y1; // Glyph corners float U0, V0, U1, V1; // Texture coordinates + int PackId; // [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) + + ImFontGlyph() { memset(this, 0, sizeof(*this)); PackId = -1; } }; // Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). @@ -3400,12 +3487,14 @@ enum ImFontAtlasFlags_ // - One or more fonts. // - Custom graphics data needed to render the shapes needed by Dear ImGui. // - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). -// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api. -// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you. -// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. -// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples) +// - If you don't call any AddFont*** functions, the default font embedded in the code will be loaded for you. +// It is the rendering backend responsibility to upload texture into your graphics API: +// - ImGui_ImplXXXX_RenderDrawData() functions generally iterate atlas->TexList[] to create/update/destroy each ImTextureData instance. +// - Backend then set ImTextureData's TexID and BackendUserData. +// - Texture id are passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. +// Legacy path: +// - Call Build() + GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. // - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. -// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. // Common pitfalls: // - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the // atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. @@ -3423,25 +3512,30 @@ struct ImFontAtlas 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(const char* 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. + + // FIXME-NEWATLAS: Clarify meaning/purpose IMGUI_API void ClearInputData(); // 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 ClearFonts(); // Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. IMGUI_API void Clear(); // Clear all input and output. + IMGUI_API void ClearCache(); // Clear cached glyphs + // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). // The pitch is always = Width * BytesPerPixels (1 or 4) // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. - IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel - IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel - bool IsBuilt() const { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... + IMGUI_API void BuildGrowTexture(); + IMGUI_API void BuildCompactTexture(); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - void SetTexID(ImTextureID id){ TexID._Atlas = this; TexID._TexID = id; } // FIXME-NEWATLAS: Called by legacy backends. - void SetTexID(ImTextureRef id) { TexID = id; } // FIXME-NEWATLAS: Called by legacy backends. + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + void SetTexID(ImTextureID id) { TexRef._TexData = NULL; TexRef._TexID = id; } // Called by legacy backends. + void SetTexID(ImTextureRef id) { TexRef = id; } // Called by legacy backends. #endif - + bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... //------------------------------------------- // Glyph Ranges @@ -3466,10 +3560,15 @@ struct ImFontAtlas //------------------------------------------- // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. - // - After calling Build(), you can query the rectangle position and render your pixels. - // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. - // - You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), - // so you can render e.g. custom colorful icons and use them as regular glyphs. + // You can request your rectangles to be mapped as font glyph (given a font + Unicode point), + // so you can render e.g. custom colorful icons and use them as regular glyphs. + // - If your backend supports ImGuiBackendFlags_RendererHasTextures (since 1.92.X): + // - Packing is done immediately. Returns >= on success. Return <0 on error. + // - You can render your pixels into the texture right after calling the AddCustomRectXXX functions. + // - Texture may be resized, so you cannot cache UV coordinates. // FIXME-NEWATLAS-V1: How to handle that smoothly? + // - If your backend does NOT supports ImGuiBackendFlags_RendererHasTextures (older than 1.92.X): + // - After calling Build(), you can query the rectangle position and render your pixels. + // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. // - Read docs/FONTS.md for more details about using colorful icons. // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. IMGUI_API int AddCustomRectRegular(int width, int height); @@ -3485,34 +3584,38 @@ struct ImFontAtlas // Input ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) - ImTextureRef TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. + ImTextureRef TexRef; // User data to refer to the latest texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8). int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). + // Output + ImTextureData* TexData; // Current texture + ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). + // [Internal] - // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. - bool TexReady; // Set when texture was built matching current font input - bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format. - unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight - unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 - int TexWidth; // Texture width calculated during Build(). - int TexHeight; // Texture height calculated during Build(). - ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) + bool TexIsBuilt; // Set when texture was built matching current font input + bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. + ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight) ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + int TexNextUniqueID; // Next value to be stored in TexData->UniqueID + ImDrawListSharedData* DrawListSharedData; // In principle this could become an array (e.g. multiple contexts using same atlas) // [Internal] Font builder - const ImFontBuilderIO* FontBuilderIO; // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). - unsigned int FontBuilderFlags; // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in ImFontConfig. - - // [Internal] Packing data - int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines + ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public + const ImFontLoader* FontLoader; // Font loader opaque interface (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). Don't set directly! + const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name + void* FontLoaderData; // Font backend opaque storage + unsigned int FontBuilderFlags; // [FIXME: Should be called FontLoaderFlags] Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. . Per-font override is also available in ImFontConfig. + int _PackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. + int _PackedRects; // Number of packed rectangles. + float _PackNodesFactor = 1.0f; // [Obsolete] //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ @@ -3525,13 +3628,13 @@ struct ImFont { // [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) ImVector IndexAdvanceX; // 12-16 // out // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). - float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX + float FallbackAdvanceX; // 4 // out // FindGlyph(FallbackChar)->AdvanceX float FontSize; // 4 // in // Height of characters/line, set during loading (don't change after loading) // [Internal] Members: Hot ~28/40 bytes (for RenderText loop) ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. ImVector Glyphs; // 12-16 // out // All glyphs. - ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) + int FallbackGlyphIndex; // 4 // out // Index of FontFallbackChar // [Internal] Members: Cold ~32/40 bytes // Conceptually Sources[] is the list of font sources merged to create this font. @@ -3543,18 +3646,21 @@ struct ImFont ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') float EllipsisWidth; // 4 // out // Total ellipsis Width float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 - float Scale; // 4 // in // Base font scale (1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() + float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) - bool DirtyLookupTables; // 1 // out // ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + bool LockDisableLoading; + ImFontConfig* LockSingleSrcConfig; // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); - IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); - IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); - float GetCharAdvance(ImWchar c) { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } + IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); // Return fallback glyph if requested glyph doesn't exists. + IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); // Return NULL if glyph doesn't exist + IMGUI_API float GetCharAdvance(ImWchar c); + IMGUI_API bool IsGlyphLoaded(ImWchar c); + IMGUI_API bool IsGlyphInFont(ImWchar c); bool IsLoaded() const { return ContainerAtlas != NULL; } const char* GetDebugName() const { return Sources ? Sources->Name : ""; } @@ -3571,14 +3677,24 @@ struct ImFont #endif // [Internal] Don't use! - IMGUI_API void BuildLookupTable(); IMGUI_API void ClearOutputData(); - IMGUI_API void GrowIndex(int new_size); - IMGUI_API void AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); - IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst);// , bool overwrite_dst = true); // Makes 'from_codepoint' character points to 'to_codepoint' character. Currently needs to be called AFTER fonts have been built. + IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst);// , bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); + IMGUI_API ImFontGlyph* BuildLoadGlyph(ImWchar c); + IMGUI_API void BuildRegisterGlyph(ImFontConfig* src, const ImFontGlyph* glyph); + IMGUI_API void BuildGrowIndex(int new_size); + IMGUI_API void BuildClearGlyphs(); }; +// FIXME-NEWATLAS: Added indirection to avoid patching ImDrawCmd after texture updates. +inline ImTextureID ImDrawCmd::GetTexID() const +{ + ImTextureID tex_id = TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID; + if (TexRef._TexData != NULL) + IM_ASSERT(tex_id && "ImDrawCmd is referring to Atlas texture that wasn't uploaded to graphics system."); + return tex_id; +} + //----------------------------------------------------------------------------- // [SECTION] Viewports //----------------------------------------------------------------------------- @@ -3657,6 +3773,10 @@ struct ImGuiPlatformIO // Input - Interface with Renderer Backend //------------------------------------------------------------------ + // Optional: Maximum texture size supported by renderer (used to adjust how we size textures). 0 if not known. + int Renderer_TextureMaxWidth; + int Renderer_TextureMaxHeight; + // Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. void* Renderer_RenderState; }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 790f37611..5d5075e81 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -576,6 +576,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &io.BackendFlags, ImGuiBackendFlags_HasMouseCursors); ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", &io.BackendFlags, ImGuiBackendFlags_HasSetMousePos); ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &io.BackendFlags, ImGuiBackendFlags_RendererHasVtxOffset); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures); ImGui::EndDisabled(); ImGui::TreePop(); @@ -1778,9 +1779,9 @@ static void DemoWindowWidgetsImages() // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - ImTextureRef my_tex_id = io.Fonts->TexID; - float my_tex_w = (float)io.Fonts->TexWidth; - float my_tex_h = (float)io.Fonts->TexHeight; + ImTextureRef my_tex_id = io.Fonts->TexRef; + float my_tex_w = (float)io.Fonts->TexData->Width; + float my_tex_h = (float)io.Fonts->TexData->Height; { ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); ImVec2 pos = ImGui::GetCursorScreenPos(); @@ -8041,7 +8042,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (copy_to_clipboard) { ImGui::LogToClipboard(); - ImGui::LogText("```\n"); // Back quotes will make text appears without formatting when pasting on GitHub + ImGui::LogText("```cpp\n"); // Back quotes will make text appears without formatting when pasting on GitHub } ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); @@ -8137,8 +8138,10 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos"); if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) ImGui::Text(" RendererHasTextures"); ImGui::Separator(); - ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); + ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexData->Width, io.Fonts->TexData->Height); + ImGui::Text("io.Fonts->FontLoaderName: \"%s\"", io.Fonts->FontLoaderName ? io.Fonts->FontLoaderName : "NULL"); ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); ImGui::Separator(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8a31b79f7..b1cf15ff4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -13,7 +13,8 @@ Index of this file: // [SECTION] ImDrawData // [SECTION] Helpers ShadeVertsXXX functions // [SECTION] ImFontConfig -// [SECTION] ImFontAtlas +// [SECTION] ImFontAtlas, ImFontAtlasBuilder +// [SECTION] ImFontAtlas: backend for stb_truetype // [SECTION] ImFontAtlas: glyph ranges helpers // [SECTION] ImFontGlyphRangesBuilder // [SECTION] ImFont @@ -389,6 +390,12 @@ ImDrawListSharedData::ImDrawListSharedData() ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); } ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError); + RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. +} + +ImDrawListSharedData::~ImDrawListSharedData() +{ + IM_ASSERT(DrawLists.Size == 0); } void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error) @@ -409,12 +416,22 @@ void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error) ImDrawList::ImDrawList(ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); - _Data = shared_data; + _SetDrawListSharedData(shared_data); } ImDrawList::~ImDrawList() { _ClearFreeMemory(); + _SetDrawListSharedData(NULL); +} + +void ImDrawList::_SetDrawListSharedData(ImDrawListSharedData* data) +{ + if (_Data != NULL) + _Data->DrawLists.find_erase_unsorted(this); + _Data = data; + if (_Data != NULL) + _Data->DrawLists.push_back(this); } // Initialize before use in a new frame. We always have a command ready in the buffer. @@ -573,10 +590,6 @@ void ImDrawList::_OnChangedClipRect() curr_cmd->ClipRect = _CmdHeader.ClipRect; } -// Operators for easy compare -static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._Atlas == rhs._Atlas; } -static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._Atlas != rhs._Atlas; } - void ImDrawList::_OnChangedTexture() { // If current command is used with different settings we need to add a new command @@ -1690,8 +1703,6 @@ void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 if (font_size == 0.0f) font_size = _Data->FontSize; - IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TexRef); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. - ImVec4 clip_rect = _CmdHeader.ClipRect; if (cpu_fine_clip_rect) { @@ -2396,39 +2407,113 @@ ImFontConfig::ImFontConfig() } //----------------------------------------------------------------------------- -// [SECTION] ImFontAtlas +// [SECTION] ImTextureData +//----------------------------------------------------------------------------- +// - ImTextureData::Create() +// - ImTextureData::DestroyPixels() +//----------------------------------------------------------------------------- + +static int GetTextureFormatBytesPerPixel(ImTextureFormat format) +{ + switch (format) + { + case ImTextureFormat_Alpha8: return 1; + case ImTextureFormat_RGBA32: return 4; + } + IM_ASSERT(0); + return 0; +} + +void ImTextureData::Create(ImTextureFormat format, int w, int h) +{ + DestroyPixels(); + Format = format; + Width = w; + Height = h; + BytesPerPixel = GetTextureFormatBytesPerPixel(format); + UseColors = false; + Pixels = (unsigned char*)IM_ALLOC(Width * Height * BytesPerPixel); + IM_ASSERT(Pixels != NULL); + memset(Pixels, 0, Width * Height * BytesPerPixel); +} + +void ImTextureData::DestroyPixels() +{ + if (Pixels) + IM_FREE(Pixels); + Pixels = NULL; + UseColors = false; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlas, ImFontAtlasBuilder //----------------------------------------------------------------------------- // - Default texture data encoded in ASCII +// - ImFontAtlasBuilder // - ImFontAtlas::ClearInputData() // - ImFontAtlas::ClearTexData() // - ImFontAtlas::ClearFonts() // - ImFontAtlas::Clear() -// - ImFontAtlas::GetTexDataAsAlpha8() -// - ImFontAtlas::GetTexDataAsRGBA32() +// - ImFontAtlas::ClearCache() +// - ImFontAtlas::BuildGrowTexture() +// - ImFontAtlas::BuildCompactTexture() +// - ImFontAtlasUpdateTextures() +//----------------------------------------------------------------------------- +// - ImFontAtlasTextureBlockConvertAndPostProcess() +// - ImFontAtlasTextureBlockConvert() +// - ImFontAtlasTextureBlockPostProcessMultiply() +// - ImFontAtlasTextureBlockCopy() +// - ImFontAtlasTextureBlockQueueUpload() +//----------------------------------------------------------------------------- +// - ImFontAtlas::GetTexDataAsAlpha8() [legacy] +// - ImFontAtlas::GetTexDataAsRGBA32() [legacy] +// - ImFontAtlas::Build() +//----------------------------------------------------------------------------- // - ImFontAtlas::AddFont() // - ImFontAtlas::AddFontDefault() // - ImFontAtlas::AddFontFromFileTTF() // - ImFontAtlas::AddFontFromMemoryTTF() // - ImFontAtlas::AddFontFromMemoryCompressedTTF() // - ImFontAtlas::AddFontFromMemoryCompressedBase85TTF() +//----------------------------------------------------------------------------- // - ImFontAtlas::AddCustomRectRegular() // - ImFontAtlas::AddCustomRectFontGlyph() // - ImFontAtlas::CalcCustomRectUV() // - ImFontAtlasGetMouseCursorTexData() -// - ImFontAtlas::Build() -// - ImFontAtlasBuildMultiplyCalcLookupTable() -// - ImFontAtlasBuildMultiplyRectAlpha8() -// - ImFontAtlasBuildWithStbTruetype() -// - ImFontAtlasGetBuilderForStbTruetype() -// - ImFontAtlasUpdateSourcesPointers() -// - ImFontAtlasBuildSetupFont() -// - ImFontAtlasBuildPackCustomRects() -// - ImFontAtlasBuildRender8bppRectFromString() -// - ImFontAtlasBuildRender32bppRectFromString() -// - ImFontAtlasBuildRenderDefaultTexData() -// - ImFontAtlasBuildRenderLinesTexData() +//----------------------------------------------------------------------------- +// - ImFontAtlasBuildSetupFontLoader() +// - ImFontAtlasBuildPreloadAllGlyphRanges() +// - ImFontAtlasBuildUpdatePointers() +// - ImFontAtlasBuildRenderBitmapFromString() +// - ImFontAtlasBuildUpdateBasicTexData() +// - ImFontAtlasBuildUpdateLinesTexData() +// - ImFontAtlasBuildAddFont() +// - ImFontAtlasBuildSetupFontSpecialGlyphs() +// - ImFontAtlasBuildReloadFont() +//----------------------------------------------------------------------------- +// - ImFontAtlasAddDrawListSharedData() +// - ImFontAtlasRemoveDrawListSharedData() +// - ImFontAtlasUpdateDrawListsTextures() +// - ImFontAtlasUpdateDrawListsSharedData() +//----------------------------------------------------------------------------- +// - ImFontAtlasBuildSetTexture() +// - ImFontAtlasBuildAddTexture() +// - ImFontAtlasBuildRepackTexture() +// - ImFontAtlasBuildGrowTexture() +// - ImFontAtlasBuildCompactTexture() // - ImFontAtlasBuildInit() -// - ImFontAtlasBuildFinish() +// - ImFontAtlasBuildDestroy() +//----------------------------------------------------------------------------- +// - ImFontAtlasPackInit() +// - ImFontAtlasPackAddRect() +// - ImFontAtlasPackGetRect() +//----------------------------------------------------------------------------- +// - ImFont::BuildLoadGlyph() +// - ImFont::BuildClearGlyphs() +//----------------------------------------------------------------------------- +// - ImFontAtlasDebugLogTextureRequests() +//----------------------------------------------------------------------------- +// - ImFontAtlasGetFontLoaderForStbTruetype() //----------------------------------------------------------------------------- // A work of art lies ahead! (. = white layer, X = black layer, others are blank) @@ -2483,23 +2568,29 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3 { ImVec2(109,0),ImVec2(13,15), ImVec2( 6, 7) }, // ImGuiMouseCursor_NotAllowed }; +#define IM_FONTGLYPH_INDEX_UNUSED ((ImU16)-1) // 0xFFFF +#define IM_FONTGLYPH_INDEX_NOT_FOUND ((ImU16)-2) // 0xFFFE + ImFontAtlas::ImFontAtlas() { memset(this, 0, sizeof(*this)); + TexDesiredFormat = ImTextureFormat_RGBA32; TexGlyphPadding = 1; - TexID._Atlas = this; - PackIdMouseCursors = PackIdLines = -1; + TexRef._TexData = NULL;// this; + TexNextUniqueID = 1; + _PackNodesFactor = 1.0f; + Builder = NULL; } ImFontAtlas::~ImFontAtlas() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); Clear(); } -void ImFontAtlas::ClearInputData() +void ImFontAtlas::ClearInputData() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); for (ImFontConfig& font_cfg : Sources) if (font_cfg.FontData && font_cfg.FontDataOwnedByAtlas) { @@ -2516,77 +2607,281 @@ void ImFontAtlas::ClearInputData() } Sources.clear(); CustomRects.clear(); - PackIdMouseCursors = PackIdLines = -1; // Important: we leave TexReady untouched } -void ImFontAtlas::ClearTexData() +void ImFontAtlas::ClearTexData() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); - if (TexPixelsAlpha8) - IM_FREE(TexPixelsAlpha8); - if (TexPixelsRGBA32) - IM_FREE(TexPixelsRGBA32); - TexPixelsAlpha8 = NULL; - TexPixelsRGBA32 = NULL; - TexPixelsUseColors = false; - // Important: we leave TexReady untouched + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + TexList.clear(); + IM_DELETE(TexData); + TexData = NULL; + // TexData.Destroy(); + //IM_ASSERT(0); + // Important: we leave TexReady untouched } -void ImFontAtlas::ClearFonts() +void ImFontAtlas::ClearFonts() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + // FIXME-NEWATLAS: Illegal to remove currently bound font. + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); ClearInputData(); Fonts.clear_delete(); - TexReady = false; + TexIsBuilt = false; + DrawListSharedData->Font = NULL; + DrawListSharedData->FontScale = DrawListSharedData->FontSize = 0.0f; } -void ImFontAtlas::Clear() +void ImFontAtlas::Clear() { + //IM_DELETE(Builder); // FIXME-NEW-ATLAS: ClearXXX functions + const ImFontLoader* font_loader = FontLoader; + ImFontAtlasBuildSetupFontLoader(this, NULL); ClearInputData(); ClearTexData(); ClearFonts(); + ImFontAtlasBuildSetupFontLoader(this, font_loader); } -void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +void ImFontAtlas::ClearCache() { - // Build atlas on demand - if (TexPixelsAlpha8 == NULL) - Build(); - - *out_pixels = TexPixelsAlpha8; - if (out_width) *out_width = TexWidth; - if (out_height) *out_height = TexHeight; - if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; + int tex_w = (TexData && TexData->Status != ImTextureStatus_WantDestroy) ? TexData->Width : 0; + int tex_h = (TexData && TexData->Status != ImTextureStatus_WantDestroy) ? TexData->Height : 0; + ImFontAtlasBuildDestroy(this); + if (tex_w != 0 && tex_h != 0) + ImFontAtlasBuildAddTexture(this, tex_w, tex_h); + ImFontAtlasBuildInit(this); } -void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +void ImFontAtlas::BuildGrowTexture() { - // Convert to RGBA32 format on demand - // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp - if (!TexPixelsRGBA32) + ImFontAtlasBuildGrowTexture(this, TexData->Width, TexData->Height); +} + +void ImFontAtlas::BuildCompactTexture() +{ + ImFontAtlasBuildCompactTexture(this); +} + +static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* atlas) +{ + // [LEGACY] Copy back the ImGuiBackendFlags_RendererHasTextures flag from ImGui context. + // - This is the 1% exceptional case where that dependency if useful, to bypass an issue where otherwise at the + // time of an early call to Build(), it would be impossible for us to tell if the backend supports texture update. + // - Without this hack, we would have quite a pitfall as many legacy codebases have an early call to Build(). + // Whereas conversely, the portion of people using ImDrawList without ImGui is expected to be pathologically rare. + if (atlas->DrawListSharedData) + if (ImGuiContext* imgui_ctx = atlas->DrawListSharedData->Context) + atlas->DrawListSharedData->RendererHasTextures = (imgui_ctx->IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; +} + +// Called by NewFrame() +void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) +{ + if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges) { - unsigned char* pixels = NULL; - GetTexDataAsAlpha8(&pixels, NULL, NULL); - if (pixels) - { - TexPixelsRGBA32 = (unsigned int*)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4); - const unsigned char* src = pixels; - unsigned int* dst = TexPixelsRGBA32; - for (int n = TexWidth * TexHeight; n > 0; n--) - *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++)); - } + ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + IM_ASSERT_USER_ERROR(atlas->DrawListSharedData->RendererHasTextures == false, + "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build()."); } - *out_pixels = (unsigned char*)TexPixelsRGBA32; - if (out_width) *out_width = TexWidth; - if (out_height) *out_height = TexHeight; - if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) + { + ImTextureData* tex = atlas->TexList[tex_n]; + bool remove_from_list = false; + tex->Updates.resize(0); + tex->UpdateRect.x = tex->UpdateRect.y = (unsigned short)~0; + tex->UpdateRect.w = tex->UpdateRect.h = 0; + + if (tex->Status == ImTextureStatus_Destroyed) + { + IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == NULL); + if (tex->WantDestroyNextFrame) + remove_from_list = true; // Destroy was scheduled by us + else + tex->Status = ImTextureStatus_WantCreate; // Destroy was done was backend (e.g. freed resources mid-run) + } + else if (tex->WantDestroyNextFrame && tex->Status != ImTextureStatus_WantDestroy) + { + // Request destroy. Keep bool as it allows us to keep track of things. + IM_ASSERT(tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates); + tex->Status = ImTextureStatus_WantDestroy; + tex->DestroyPixels(); + } + + // The backend may need defer destroying by a few frames, to handle texture used by previous in-flight rendering. + // We allow the texture staying in _WantDestroy state and increment a counter which the backend can use to take its decision. + if (tex->Status == ImTextureStatus_WantDestroy) + tex->UnusedFrames++; + + // If a texture has never reached the backend, they don't need to know about it. + if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == 0 && tex->BackendUserData == NULL) + remove_from_list = true; + + // Remove + if (remove_from_list) + { + IM_DELETE(tex); + atlas->TexList.erase(atlas->TexList.begin() + tex_n); + tex_n--; + } + } } +// Source buffer may be written to (used for in-place mods). +// Post-process hooks may eventually be added here. +void ImFontAtlasTextureBlockConvertAndPostProcess(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, ImFontGlyph* glyph, unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst, ImTextureFormat dst_fmt, int dst_pitch, int w, int h) +{ + IM_UNUSED(atlas); + IM_UNUSED(font); + IM_UNUSED(glyph); + + // Multiply operator (legacy) + if (src->RasterizerMultiply != 1.0f) + ImFontAtlasTextureBlockPostProcessMultiply(atlas, font, src, glyph, src_pixels, src_fmt, w, h, src_pitch, src->RasterizerMultiply); + + ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst, dst_fmt, dst_pitch, w, h); +} + +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) +{ + IM_ASSERT(src_pixels != NULL && dst_pixels != NULL); + if (src_fmt == dst_fmt) + { + int line_sz = w * GetTextureFormatBytesPerPixel(src_fmt); + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + memcpy(dst_pixels, src_pixels, line_sz); + } + else if (src_fmt == ImTextureFormat_Alpha8 && dst_fmt == ImTextureFormat_RGBA32) + { + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + { + const ImU8* src_p = (const ImU8*)src_pixels; + ImU32* dst_p = (ImU32*)(void*)dst_pixels; + for (int nx = w; nx > 0; nx--) + *dst_p++ = IM_COL32(255, 255, 255, (unsigned int)(*src_p++)); + } + } + else if (src_fmt == ImTextureFormat_RGBA32 && dst_fmt == ImTextureFormat_Alpha8) + { + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + { + const ImU32* src_p = (const ImU32*)(void*)src_pixels; + ImU8* dst_p = (ImU8*)dst_pixels; + for (int nx = w; nx > 0; nx--) + *dst_p++ = ((*src_p++) >> IM_COL32_A_SHIFT) & 0xFF; + } + } + else + { + IM_ASSERT(0); + } +} + +void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, ImFontGlyph* glyph, unsigned char* pixels, ImTextureFormat format, int w, int h, int pitch, float in_multiply_factor) +{ + IM_UNUSED(atlas); + IM_UNUSED(font); + IM_UNUSED(src); + IM_UNUSED(glyph); + IM_ASSERT(in_multiply_factor >= 0.0f); + IM_ASSERT_PARANOID(w <= pitch); + if (format == ImTextureFormat_Alpha8) + { + for (int ny = h; ny > 0; ny--, pixels += pitch) + { + ImU8* p = (ImU8*)pixels; + for (int nx = w; nx > 0; nx--, p++) + { + unsigned int v = ImMin((unsigned int)(*p * in_multiply_factor), (unsigned int)255); + *p = (unsigned char)v; + } + } + } + else if (format == ImTextureFormat_RGBA32) + { + for (int ny = h; ny > 0; ny--, pixels += pitch) + { + ImU32* p = (ImU32*)(void*)pixels; + for (int nx = w; nx > 0; nx--, p++) + { + unsigned int a = ImMin((unsigned int)(((*p >> IM_COL32_A_SHIFT) & 0xFF) * in_multiply_factor), (unsigned int)255); + *p = IM_COL32((*p >> IM_COL32_R_SHIFT) & 0xFF, (*p >> IM_COL32_G_SHIFT) & 0xFF, (*p >> IM_COL32_B_SHIFT) & 0xFF, a); + } + } + } + else + { + IM_ASSERT(0); + } +} + +// Convert block from one texture to another +void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h) +{ + IM_ASSERT(src_tex != dst_tex); + IM_ASSERT(src_tex->Pixels != NULL && dst_tex->Pixels != NULL); + IM_ASSERT(src_tex->Format == dst_tex->Format); + IM_ASSERT(src_x >= 0 && src_x + w <= src_tex->Width); + IM_ASSERT(src_y >= 0 && src_y + h <= src_tex->Height); + IM_ASSERT(dst_x >= 0 && dst_x + w <= dst_tex->Width); + IM_ASSERT(dst_y >= 0 && dst_y + h <= dst_tex->Height); + for (int y = 0; y < h; y++) + memcpy(dst_tex->GetPixelsAt(dst_x, dst_y + y), src_tex->GetPixelsAt(src_x, src_y + y), w * dst_tex->BytesPerPixel); +} + +// Queue texture block update for renderer backend +void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h) +{ + // Queue texture update (no need to queue if status is _WantCreate) + IM_ASSERT(atlas); + if (tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantUpdates) + { + IM_ASSERT(x >= 0 && x <= 0xFFFF && y >= 0 && y <= 0xFFFF && w >= 0 && x + w <= 0x10000 && h >= 0 && y + h <= 0x10000); + ImTextureRect req = { (unsigned short)x, (unsigned short)y, (unsigned short)w, (unsigned short)h }; + tex->Status = ImTextureStatus_WantUpdates; + tex->Updates.push_back(req); + int new_x1 = ImMax(tex->UpdateRect.w == 0 ? 0 : tex->UpdateRect.x + tex->UpdateRect.w, req.x + req.w); + int new_y1 = ImMax(tex->UpdateRect.h == 0 ? 0 : tex->UpdateRect.y + tex->UpdateRect.h, req.y + req.h); + IM_ASSERT(new_x1 < 0x8000); + IM_ASSERT(new_y1 < 0x8000); + tex->UpdateRect.x = ImMin(tex->UpdateRect.x, req.x); + tex->UpdateRect.y = ImMin(tex->UpdateRect.y, req.y); + tex->UpdateRect.w = (unsigned short)(new_x1 - tex->UpdateRect.x); + tex->UpdateRect.h = (unsigned short)(new_y1 - tex->UpdateRect.y); + } +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +static void GetTexDataAsFormat(ImFontAtlas* atlas, ImTextureFormat format, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + ImTextureData* tex = atlas->TexData; + if (!atlas->TexIsBuilt || tex == NULL || tex->Pixels == NULL || atlas->TexDesiredFormat != format) + { + atlas->TexDesiredFormat = format; + atlas->Build(); + tex = atlas->TexData; + } + if (out_pixels) { *out_pixels = (unsigned char*)tex->Pixels; }; + if (out_width) { *out_width = tex->Width; }; + if (out_height) { *out_height = tex->Height; }; + if (out_bytes_per_pixel) { *out_bytes_per_pixel = tex->BytesPerPixel; } +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + GetTexDataAsFormat(this, ImTextureFormat_Alpha8, out_pixels, out_width, out_height, out_bytes_per_pixel); +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + GetTexDataAsFormat(this, ImTextureFormat_RGBA32, out_pixels, out_width, out_height, out_bytes_per_pixel); +} +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); IM_ASSERT(font_cfg->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); @@ -2614,12 +2909,15 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) // - We may support it better later and remove this rounding. new_font_cfg.SizePixels = ImTrunc(new_font_cfg.SizePixels); - // Pointers to Sources data are otherwise dangling - ImFontAtlasUpdateSourcesPointers(this); + // Pointers to Sources are otherwise dangling + ImFontAtlasBuildUpdatePointers(this); + + if (Builder != NULL) + ImFontAtlasBuildAddFont(this, &new_font_cfg); // Invalidate texture - TexReady = false; - ClearTexData(); + //TexReady = false; + //ClearTexData(); return new_font_cfg.DstFont; } @@ -2672,7 +2970,7 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); size_t data_size = 0; void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0); if (!data) @@ -2694,7 +2992,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, // NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); IM_ASSERT(font_cfg.FontData == NULL); IM_ASSERT(font_data_size > 100 && "Incorrect value for font_data_size!"); // Heuristic to prevent accidentally passing a wrong value to font_data_size. @@ -2728,6 +3026,25 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed return font; } +// FIXME-NEWATLAS-V1: Feature is broken for now. +/* + // Register custom rectangle glyphs + for (int i = 0; i < atlas->CustomRects.Size; i++) + { + const ImFontAtlasCustomRect* r = &atlas->CustomRects[i]; + if (r->Font == NULL || r->GlyphID == 0) + continue; + + // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, PixelSnapH + IM_ASSERT(r->Font->ContainerAtlas == atlas); + ImVec2 uv0, uv1; + atlas->CalcCustomRectUV(r, &uv0, &uv1); + r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX); + if (r->GlyphColored) + r->Font->Glyphs.back().Colored = 1; + } +*/ + int ImFontAtlas::AddCustomRectRegular(int width, int height) { IM_ASSERT(width > 0 && width <= 0xFFFF); @@ -2761,7 +3078,7 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const { - IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates + IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y); *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y); @@ -2774,9 +3091,8 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) return false; - IM_ASSERT(atlas->PackIdMouseCursors != -1); - ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); - ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->X, (float)r->Y); + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, atlas->Builder->PackIdMouseCursors); + ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->x, (float)r->y); ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; *out_size = size; *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; @@ -2788,407 +3104,104 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso return true; } -bool ImFontAtlas::Build() +bool ImFontAtlas::Build() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); // Default font is none are specified if (Sources.Size == 0) AddFontDefault(); // Select builder - // - Note that we do not reassign to atlas->FontBuilderIO, since it is likely to point to static data which + // - Note that we do not reassign to atlas->FontLoader, since it is likely to point to static data which // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are - // using a hot-reloading scheme that messes up static data, store your own instance of ImFontBuilderIO somewhere - // and point to it instead of pointing directly to return value of the GetBuilderXXX functions. - const ImFontBuilderIO* builder_io = FontBuilderIO; - if (builder_io == NULL) + // using a hot-reloading scheme that messes up static data, store your own instance of ImFontLoader somewhere + // and point to it instead of pointing directly to return value of the GetBackendIOXXX functions. + if (FontLoader == NULL) { #ifdef IMGUI_ENABLE_FREETYPE - builder_io = ImGuiFreeType::GetBuilderForFreeType(); + ImFontAtlasBuildSetupFontLoader(this, ImGuiFreeType::GetBackendIOForFreeType()); #elif defined(IMGUI_ENABLE_STB_TRUETYPE) - builder_io = ImFontAtlasGetBuilderForStbTruetype(); + ImFontAtlasBuildSetupFontLoader(this, ImFontAtlasGetFontLoaderForStbTruetype()); #else IM_ASSERT(0); // Invalid Build function #endif } - // Build - return builder_io->FontBuilder_Build(this); + // Create initial texture size + ImFontAtlasBuildAddTexture(this, 512, 128); + ImFontAtlasBuildInit(this); + + // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs + ImFontAtlasBuildUpdateRendererHasTexturesFromContext(this); + if (DrawListSharedData->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures + ImFontAtlasBuildPreloadAllGlyphRanges(this); + TexIsBuilt = true; + + return true; } -void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor) -{ - for (unsigned int i = 0; i < 256; i++) - { - unsigned int value = (unsigned int)(i * in_brighten_factor); - out_table[i] = value > 255 ? 255 : (value & 0xFF); - } -} - -void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride) -{ - IM_ASSERT_PARANOID(w <= stride); - unsigned char* data = pixels + x + y * stride; - for (int j = h; j > 0; j--, data += stride - w) - for (int i = w; i > 0; i--, data++) - *data = table[*data]; -} - -void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* src, int* out_oversample_h, int* out_oversample_v) +void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v) { // Automatically disable horizontal oversampling over size 36 *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (src->SizePixels * src->RasterizerDensity > 36.0f || src->PixelSnapH) ? 1 : 2; *out_oversample_v = (src->OversampleV != 0) ? src->OversampleV : 1; } -#ifdef IMGUI_ENABLE_STB_TRUETYPE -// Temporary data for one source font (multiple source fonts can be merged into one destination ImFont) -// (C++03 doesn't allow instancing ImVector<> with function-local types so we declare the type here.) -struct ImFontBuildSrcData +void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader) { - stbtt_fontinfo FontInfo; - stbtt_pack_range PackRange; // Hold the list of codepoints to pack (essentially points to Codepoints.Data) - stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position. - stbtt_packedchar* PackedChars; // Output glyphs - const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF) - int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[] - int GlyphsHighest; // Highest requested codepoint - int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font) - ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB) - ImVector GlyphsList; // Glyph codepoints list (flattened version of GlyphsSet) -}; + if (atlas->FontLoader == font_loader) + return; + IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); -// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont) -struct ImFontBuildDstData -{ - int SrcCount; // Number of source fonts targeting this destination font. - int GlyphsHighest; - int GlyphsCount; - ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font. -}; - -static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector* out) -{ - IM_ASSERT(sizeof(in->Storage.Data[0]) == sizeof(int)); - const ImU32* it_begin = in->Storage.begin(); - const ImU32* it_end = in->Storage.end(); - for (const ImU32* it = it_begin; it < it_end; it++) - if (ImU32 entries_32 = *it) - for (ImU32 bit_n = 0; bit_n < 32; bit_n++) - if (entries_32 & ((ImU32)1 << bit_n)) - out->push_back((int)(((it - it_begin) << 5) + bit_n)); + ImFontAtlasBuildDestroy(atlas); + if (atlas->FontLoader && atlas->FontLoader->LoaderShutdown) + { + atlas->FontLoader->LoaderShutdown(atlas); + IM_ASSERT(atlas->FontLoaderData == NULL); + } + atlas->FontLoader = font_loader; + atlas->FontLoaderName = font_loader ? font_loader->Name : "NULL"; + if (atlas->FontLoader && atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); + if (atlas->Builder && font_loader != NULL) + atlas->ClearCache(); } -static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) +// Preload all glyph ranges for legacy backends. +// This may lead to multiple texture creation which might be a little slower than before. +void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas) { - IM_ASSERT(atlas->Sources.Size > 0); - - ImFontAtlasBuildInit(atlas); - - // Clear atlas - atlas->TexID._TexID = 0; - atlas->TexWidth = atlas->TexHeight = 0; - atlas->TexUvScale = ImVec2(0.0f, 0.0f); - atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); - atlas->ClearTexData(); - - // Temporary storage for building - ImVector src_tmp_array; - ImVector dst_tmp_array; - src_tmp_array.resize(atlas->Sources.Size); - dst_tmp_array.resize(atlas->Fonts.Size); - memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); - memset(dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes()); - - // 1. Initialize font loading structure, check font data validity - for (int src_i = 0; src_i < atlas->Sources.Size; src_i++) + atlas->Builder->PreloadedAllGlyphsRanges = true; + for (int src_n = 0; src_n < atlas->Sources.Size; src_n++) { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - ImFontConfig& src = atlas->Sources[src_i]; - IM_ASSERT(src.DstFont && (!src.DstFont->IsLoaded() || src.DstFont->ContainerAtlas == atlas)); - - // Find index from src.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) - src_tmp.DstIndex = -1; - for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++) - if (src.DstFont == atlas->Fonts[output_i]) - src_tmp.DstIndex = output_i; - if (src_tmp.DstIndex == -1) - { - IM_ASSERT(src_tmp.DstIndex != -1); // src.DstFont not pointing within atlas->Fonts[] array? - return false; - } - // Initialize helper structure for font loading and verify that the TTF/OTF data is correct - const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src.FontData, src.FontNo); - IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); - if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)src.FontData, font_offset)) - { - IM_ASSERT(0 && "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); - return false; - } - - // Measure highest codepoints - ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.SrcRanges = src.GlyphRanges ? src.GlyphRanges : atlas->GetGlyphRangesDefault(); - for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) - { - // Check for valid range. This may also help detect *some* dangling pointers, because a common - // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent, - // or to forget to zero-terminate the glyph range array. - IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?"); - src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]); - } - dst_tmp.SrcCount++; - dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest); + ImFontConfig* src = &atlas->Sources[src_n]; + const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault(); + IM_ASSERT(ranges != NULL); + for (; ranges[0]; ranges += 2) + for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 + src->DstFont->FindGlyphNoFallback((ImWchar)c); } - - // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs. - int total_glyphs_count = 0; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1); - if (dst_tmp.GlyphsSet.Storage.empty()) - dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1); - - for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) - for (unsigned int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++) - { - if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true) - continue; - if (!stbtt_FindGlyphIndex(&src_tmp.FontInfo, codepoint)) // It is actually in the font? - continue; - - // Add to avail set/counters - src_tmp.GlyphsCount++; - dst_tmp.GlyphsCount++; - src_tmp.GlyphsSet.SetBit(codepoint); - dst_tmp.GlyphsSet.SetBit(codepoint); - total_glyphs_count++; - } - } - - // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another) - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount); - UnpackBitVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList); - src_tmp.GlyphsSet.Clear(); - IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount); - } - for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++) - dst_tmp_array[dst_i].GlyphsSet.Clear(); - dst_tmp_array.clear(); - - // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) - // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity) - ImVector buf_rects; - ImVector buf_packedchars; - buf_rects.resize(total_glyphs_count); - buf_packedchars.resize(total_glyphs_count); - memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes()); - memset(buf_packedchars.Data, 0, (size_t)buf_packedchars.size_in_bytes()); - - // 4. Gather glyphs sizes so we can pack them in our virtual canvas. - int total_surface = 0; - int buf_rects_out_n = 0; - int buf_packedchars_out_n = 0; - const int pack_padding = atlas->TexGlyphPadding; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - src_tmp.Rects = &buf_rects[buf_rects_out_n]; - src_tmp.PackedChars = &buf_packedchars[buf_packedchars_out_n]; - buf_rects_out_n += src_tmp.GlyphsCount; - buf_packedchars_out_n += src_tmp.GlyphsCount; - - // Automatic selection of oversampling parameters - ImFontConfig& src = atlas->Sources[src_i]; - int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(&src, &oversample_h, &oversample_v); - - // Convert our ranges in the format stb_truetype wants - src_tmp.PackRange.font_size = src.SizePixels * src.RasterizerDensity; - src_tmp.PackRange.first_unicode_codepoint_in_range = 0; - src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data; - src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size; - src_tmp.PackRange.chardata_for_range = src_tmp.PackedChars; - src_tmp.PackRange.h_oversample = (unsigned char)oversample_h; - src_tmp.PackRange.v_oversample = (unsigned char)oversample_v; - - // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects) - const float scale = (src.SizePixels > 0.0f) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, src.SizePixels * src.RasterizerDensity) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -src.SizePixels * src.RasterizerDensity); - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) - { - int x0, y0, x1, y1; - const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]); - IM_ASSERT(glyph_index_in_font != 0); - stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * oversample_h, scale * oversample_v, 0, 0, &x0, &y0, &x1, &y1); - src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + pack_padding + oversample_h - 1); - src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + pack_padding + oversample_v - 1); - total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h; - } - } - for (int i = 0; i < atlas->CustomRects.Size; i++) - total_surface += (atlas->CustomRects[i].Width + pack_padding) * (atlas->CustomRects[i].Height + pack_padding); - - // We need a width for the skyline algorithm, any width! - // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height. - // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface. - const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1; - atlas->TexHeight = 0; - if (atlas->TexDesiredWidth > 0) - atlas->TexWidth = atlas->TexDesiredWidth; - else - atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512; - - // 5. Start packing - // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). - const int TEX_HEIGHT_MAX = 1024 * 32; - stbtt_pack_context spc = {}; - stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, 0, NULL); - spc.padding = atlas->TexGlyphPadding; // Because we mixup stbtt_PackXXX and stbrp_PackXXX there's a bit of a hack here, not passing the value to stbtt_PackBegin() allows us to still pack a TexWidth-1 wide item. (#8107) - ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info); - - // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point. - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - stbrp_pack_rects((stbrp_context*)spc.pack_info, src_tmp.Rects, src_tmp.GlyphsCount); - - // Extend texture height and mark missing glyphs as non-packed so we won't render them. - // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?) - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) - if (src_tmp.Rects[glyph_i].was_packed) - atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h); - } - - // 7. Allocate texture - atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); - atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); - atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight); - memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); - spc.pixels = atlas->TexPixelsAlpha8; - spc.height = atlas->TexHeight; - - // 8. Render/rasterize font characters into the texture - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontConfig& src = atlas->Sources[src_i]; - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - stbtt_PackFontRangesRenderIntoRects(&spc, &src_tmp.FontInfo, &src_tmp.PackRange, 1, src_tmp.Rects); - - // Apply multiply operator - if (src.RasterizerMultiply != 1.0f) - { - unsigned char multiply_table[256]; - ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, src.RasterizerMultiply); - stbrp_rect* r = &src_tmp.Rects[0]; - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++, r++) - if (r->was_packed) - ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, atlas->TexPixelsAlpha8, r->x, r->y, r->w, r->h, atlas->TexWidth * 1); - } - src_tmp.Rects = NULL; - } - - // End packing - stbtt_PackEnd(&spc); - buf_rects.clear(); - - // 9. Setup ImFont and glyphs for runtime - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - // When merging fonts with MergeMode=true: - // - We can have multiple input fonts writing into a same destination font. - // - dst_font->Sources is != from src which is our source configuration. - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - ImFontConfig& src = atlas->Sources[src_i]; - ImFont* dst_font = src.DstFont; - - const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, src.SizePixels); - int unscaled_ascent, unscaled_descent, unscaled_line_gap; - stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); - - const float ascent = ImCeil(unscaled_ascent * font_scale); - const float descent = ImFloor(unscaled_descent * font_scale); - ImFontAtlasBuildSetupFont(atlas, dst_font, &src, ascent, descent); - const float font_off_x = src.GlyphOffset.x; - const float font_off_y = src.GlyphOffset.y + IM_ROUND(dst_font->Ascent); - - const float inv_rasterization_scale = 1.0f / src.RasterizerDensity; - - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) - { - // Register glyph - const int codepoint = src_tmp.GlyphsList[glyph_i]; - const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i]; - stbtt_aligned_quad q; - float unused_x = 0.0f, unused_y = 0.0f; - stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0); - float x0 = q.x0 * inv_rasterization_scale + font_off_x; - float y0 = q.y0 * inv_rasterization_scale + font_off_y; - float x1 = q.x1 * inv_rasterization_scale + font_off_x; - float y1 = q.y1 * inv_rasterization_scale + font_off_y; - dst_font->AddGlyph(&src, (ImWchar)codepoint, x0, y0, x1, y1, q.s0, q.t0, q.s1, q.t1, pc.xadvance * inv_rasterization_scale); - } - } - - // Cleanup - src_tmp_array.clear_destruct(); - - ImFontAtlasBuildFinish(atlas); - return true; } -const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype() +void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) { - static ImFontBuilderIO io; - io.FontBuilder_Build = ImFontAtlasBuildWithStbTruetype; - return &io; -} - -#endif // IMGUI_ENABLE_STB_TRUETYPE - -void ImFontAtlasUpdateSourcesPointers(ImFontAtlas* atlas) -{ - for (ImFontConfig& src : atlas->Sources) + for (int src_n = 0; src_n < atlas->Sources.Size; src_n++) { - ImFont* font = src.DstFont; - if (!src.MergeMode) + ImFontConfig* src = &atlas->Sources[src_n]; + ImFont* font = src->DstFont; + if (!src->MergeMode) { - font->Sources = &src; + font->Sources = src; font->SourcesCount = 0; } font->SourcesCount++; } } -void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) -{ - if (!font_config->MergeMode) - { - font->ClearOutputData(); - font->FontSize = font_config->SizePixels; - IM_ASSERT(font->Sources == font_config); - font->ContainerAtlas = atlas; - font->Ascent = ascent; - font->Descent = descent; - } -} - void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque) { + ImTextureData* tex = atlas->TexData; stbrp_context* pack_context = (stbrp_context*)stbrp_context_opaque; IM_ASSERT(pack_context != NULL); @@ -3213,175 +3226,828 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa { user_rects[i].X = (unsigned short)pack_rects[i].x; user_rects[i].Y = (unsigned short)pack_rects[i].y; - IM_ASSERT(pack_rects[i].w == user_rects[i].Width + pack_padding && pack_rects[i].h == user_rects[i].Height + pack_padding); - atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h); + IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height); + tex->Height = ImMax(tex->Height, pack_rects[i].y + pack_rects[i].h); } } -void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value) +// Render a white-colored bitmap encoded in a string +void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char) { - IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth); - IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight); - unsigned char* out_pixel = atlas->TexPixelsAlpha8 + x + (y * atlas->TexWidth); - for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w) - for (int off_x = 0; off_x < w; off_x++) - out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : 0x00; -} + ImTextureData* tex = atlas->TexData; + IM_ASSERT(x >= 0 && x + w <= tex->Width); + IM_ASSERT(y >= 0 && y + h <= tex->Height); -void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value) -{ - IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth); - IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight); - unsigned int* out_pixel = atlas->TexPixelsRGBA32 + x + (y * atlas->TexWidth); - for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w) - for (int off_x = 0; off_x < w; off_x++) - out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : IM_COL32_BLACK_TRANS; -} - -static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) -{ - ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); - IM_ASSERT(r->IsPacked()); - - const int w = atlas->TexWidth; - if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) + switch (tex->Format) { - // White pixels only - IM_ASSERT(r->Width == 2 && r->Height == 2); - const int offset = (int)r->X + (int)r->Y * w; - if (atlas->TexPixelsAlpha8 != NULL) + case ImTextureFormat_Alpha8: + { + ImU8* out_p = tex->GetPixelsAt(x, y); + for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_p[off_x] = (in_str[off_x] == in_marker_char) ? 0xFF : 0x00; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)(void*)tex->GetPixelsAt(x, y); + for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_p[off_x] = (in_str[off_x] == in_marker_char) ? IM_COL32_WHITE : IM_COL32_BLACK_TRANS; + break; + } + } +} + +static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_draw) +{ + ImVec2i pack_size = (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) ? ImVec2i(2, 2) : ImVec2i(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + + // Pack and store identifier so we can refresh UV coordinates on texture resize. + // FIXME-NEWATLAS: User/custom rects where user code wants to store UV coordinates will need to do the same thing. + ImFontAtlasBuilder* builder = atlas->Builder; + + if (add_and_draw) + builder->PackIdMouseCursors = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdMouseCursors); + + // Draw to texture + if (add_and_draw) + { + if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) { - atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF; + // 2x2 white pixels + ImFontAtlasBuildRenderBitmapFromString(atlas, r->x, r->y, 2, 2, "XX" "XX", 'X'); } else { - atlas->TexPixelsRGBA32[offset] = atlas->TexPixelsRGBA32[offset + 1] = atlas->TexPixelsRGBA32[offset + w] = atlas->TexPixelsRGBA32[offset + w + 1] = IM_COL32_WHITE; + // 2x2 white pixels + mouse cursors + const int x_for_white = r->x; + const int x_for_black = r->x + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; + ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r->y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.'); + ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r->y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X'); } } - else - { - // White pixels and mouse cursor - IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); - const int x_for_white = r->X; - const int x_for_black = r->X + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; - if (atlas->TexPixelsAlpha8 != NULL) - { - ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', 0xFF); - ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', 0xFF); - } - else - { - ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', IM_COL32_WHITE); - ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', IM_COL32_WHITE); - } - } - atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); + atlas->TexUvWhitePixel = ImVec2((r->x + 0.5f) * atlas->TexUvScale.x, (r->y + 0.5f) * atlas->TexUvScale.y); } -static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas) +static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_draw) { if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) return; + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + + // Pack and store identifier so we can refresh UV coordinates on texture resize. + ImFontAtlasBuilder* builder = atlas->Builder; + if (add_and_draw) + builder->PackIdLinesTexData = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdLinesTexData); + + // Register texture region for thick lines + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them - ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines); - IM_ASSERT(r->IsPacked()); + ImTextureData* tex = atlas->TexData; for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle int y = n; int line_width = n; - int pad_left = (r->Width - line_width) / 2; - int pad_right = r->Width - (pad_left + line_width); + int pad_left = (r->w - line_width) / 2; + int pad_right = r->w - (pad_left + line_width); // Write each slice - IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels - if (atlas->TexPixelsAlpha8 != NULL) + IM_ASSERT(pad_left + line_width + pad_right == r->w && y < r->h); // Make sure we're inside the texture bounds before we start writing pixels + if (add_and_draw) { - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)]; - for (int i = 0; i < pad_left; i++) - *(write_ptr + i) = 0x00; + switch (tex->Format) + { + case ImTextureFormat_Alpha8: + { + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r->x, r->y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = 0x00; - for (int i = 0; i < line_width; i++) - *(write_ptr + pad_left + i) = 0xFF; + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = 0xFF; - for (int i = 0; i < pad_right; i++) - *(write_ptr + pad_left + line_width + i) = 0x00; - } - else - { - unsigned int* write_ptr = &atlas->TexPixelsRGBA32[r->X + ((r->Y + y) * atlas->TexWidth)]; - for (int i = 0; i < pad_left; i++) - *(write_ptr + i) = IM_COL32(255, 255, 255, 0); + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = 0x00; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r->x, r->y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = IM_COL32(255, 255, 255, 0); - for (int i = 0; i < line_width; i++) - *(write_ptr + pad_left + i) = IM_COL32_WHITE; + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = IM_COL32_WHITE; - for (int i = 0; i < pad_right; i++) - *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); + break; + } + } } // Calculate UVs for this line - ImVec2 uv0 = ImVec2((float)(r->X + pad_left - 1), (float)(r->Y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r->X + pad_left + line_width + 1), (float)(r->Y + y + 1)) * atlas->TexUvScale; + ImVec2 uv0 = ImVec2((float)(r->x + pad_left - 1), (float)(r->y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r->x + pad_left + line_width + 1), (float)(r->y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } -// Note: this is called / shared by both the stb_truetype and the FreeType builder +//----------------------------------------------------------------------------------------------------------------------------- + +static const ImFontGlyph* LoadFirstExistingGlyph(ImFont* font, const ImWchar* candidate_chars, int candidate_chars_count) +{ + for (int n = 0; n < candidate_chars_count; n++) + if (candidate_chars[n] != 0) + if (const ImFontGlyph* glyph = font->FindGlyphNoFallback(candidate_chars[n])) + return glyph; + return NULL; +} + +bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) +{ + ImFont* font = src->DstFont; + if (src->MergeMode == false) + { + font->ClearOutputData(); + font->FontSize = src->SizePixels; + font->ContainerAtlas = atlas; + IM_ASSERT(font->Sources == src); + } + + const ImFontLoader* font_loader = atlas->FontLoader; + if (!font_loader->FontSrcInit(atlas, src)) + return false; // FIXME-NEWATLAS: error handling + + ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, src); + return true; +} + +// Load/identify special glyphs +// (note that this is called again for fonts with MergeMode) +void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src) +{ + ImFont* font = src->DstFont; + IM_UNUSED(atlas); + + // While manipulating glyphs during init we want to restrict all searches for one source font. + font->LockSingleSrcConfig = src; + + // Setup Fallback character + // FIXME-NEWATLAS: could we use a scheme where this is lazily loaded? + const ImWchar fallback_chars[] = { font->FallbackChar, (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; + if (font->FallbackGlyphIndex == -1) + if (const ImFontGlyph* glyph = LoadFirstExistingGlyph(font, fallback_chars, IM_ARRAYSIZE(fallback_chars))) + { + font->FallbackChar = (ImWchar)glyph->Codepoint; + font->FallbackGlyphIndex = font->Glyphs.index_from_ptr(glyph); // Storing index avoid need to update pointer on growth. + font->FallbackAdvanceX = glyph->AdvanceX; + } + + // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews) + ImFontGlyph* space_glyph = (ImFontGlyph*)(void*)font->FindGlyph((ImWchar)' '); + if (space_glyph != NULL) + space_glyph->Visible = false; + + // Setup Tab character. + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (font->FindGlyphNoFallback('\t') == NULL && space_glyph != NULL) + { + ImFontGlyph tab_glyph; + tab_glyph.Codepoint = '\t'; + tab_glyph.AdvanceX = space_glyph->AdvanceX * IM_TABSIZE; + font->BuildRegisterGlyph(font->Sources, &tab_glyph); + } + + // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). + // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. + // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots. + const ImWchar ellipsis_chars[] = { src->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 }; + if (font->EllipsisChar == 0) + if (const ImFontGlyph* glyph = LoadFirstExistingGlyph(font, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars))) + { + font->EllipsisChar = (ImWchar)glyph->Codepoint; + font->EllipsisCharCount = 1; + font->EllipsisWidth = font->EllipsisCharStep = glyph->X1; + } + if (font->EllipsisChar == 0) + { + // FIXME-NEWATLAS-V2: We can now rasterize this into a regular character and register it! + const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; + if (const ImFontGlyph* dot_glyph = LoadFirstExistingGlyph(font, dots_chars, IM_ARRAYSIZE(dots_chars))) + { + font->EllipsisChar = (ImWchar)dot_glyph->Codepoint; + font->EllipsisCharCount = 3; + font->EllipsisCharStep = (float)(int)(dot_glyph->X1 - dot_glyph->X0) + 1.0f; + font->EllipsisWidth = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + font->EllipsisCharStep * 3.0f - 1.0f); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. + } + } + + font->LockSingleSrcConfig = NULL; +} + +// Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* +void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) +{ + IM_ASSERT(atlas->DrawListSharedData == NULL && data->FontAtlas == NULL); + atlas->DrawListSharedData = data; + data->FontAtlas = atlas; +} + +void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) +{ + IM_ASSERT(atlas->DrawListSharedData == data && data->FontAtlas == atlas); + atlas->DrawListSharedData = data; + data->FontAtlas = NULL; +} + +// Update texture identifier in all active draw lists +void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex) +{ + ImDrawListSharedData* shared_data = atlas->DrawListSharedData; + for (ImDrawList* draw_list : shared_data->DrawLists) + { + // Replace in command-buffer + // (there is not need to replace in ImDrawListSplitter: current channel is in ImDrawList's CmdBuffer[], + // other channels will be on SetCurrentChannel() which already needs to compare CmdHeader anyhow) + if (draw_list->CmdBuffer.Size > 0 && draw_list->_CmdHeader.TexRef == old_tex) + draw_list->_SetTexture(new_tex); + + // Replace in stack + for (ImTextureRef& stacked_tex : draw_list->_TextureStack) + if (stacked_tex == old_tex) + stacked_tex = new_tex; + } +} + +// Update texture coordinates in all draw list shared context +void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) +{ + ImDrawListSharedData* shared_data = atlas->DrawListSharedData; + shared_data->FontAtlas = atlas; + shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; + shared_data->TexUvLines = atlas->TexUvLines; +} + +// Set current texture. This is mostly called from AddTexture() + to handle a failed resize. +static void ImFontAtlasBuildSetTexture(ImFontAtlas* atlas, ImTextureData* tex) +{ + ImTextureRef old_tex_ref = atlas->TexRef; + atlas->TexData = tex; + atlas->TexUvScale = ImVec2(1.0f / tex->Width, 1.0f / tex->Height); + atlas->TexRef._TexData = tex; + //atlas->TexID._TexID = tex->TexID; // <-- We intentionally don't do that and leave it 0, to allow late upload. + ImTextureRef new_tex_ref = atlas->TexRef; + ImFontAtlasUpdateDrawListsTextures(atlas, old_tex_ref, new_tex_ref); +} + +// Create a new texture, discard previous one +ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h) +{ + ImTextureData* old_tex = atlas->TexData; + ImTextureData* new_tex; + + // FIXME: Cannot reuse texture because old UV may have been used already (unless we remap UV). + /*if (old_tex != NULL && old_tex->Status == ImTextureStatus_WantCreate) + { + // Reuse texture not yet used by backend. + IM_ASSERT(old_tex->TexID == 0 && old_tex->BackendUserData == NULL); + old_tex->DestroyPixels(); + old_tex->Updates.clear(); + new_tex = old_tex; + old_tex = NULL; + } + else*/ + { + // Add new + new_tex = IM_NEW(ImTextureData)(); + new_tex->UniqueID = atlas->TexNextUniqueID++; + atlas->TexList.push_back(new_tex); + } + if (old_tex != NULL) + { + // Queue old as to destroy next frame + old_tex->WantDestroyNextFrame = true; + IM_ASSERT(old_tex->Status == ImTextureStatus_OK || old_tex->Status == ImTextureStatus_WantCreate || old_tex->Status == ImTextureStatus_WantUpdates); + } + + new_tex->Create(atlas->TexDesiredFormat, w, h); + new_tex->Status = ImTextureStatus_WantCreate; + + ImFontAtlasBuildSetTexture(atlas, new_tex); + + return new_tex; +} + +void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) +{ + ImGuiContext& g = *GImGui; + IM_UNUSED(g); // for IMGUI_DEBUG_LOG_FONT() + + ImFontAtlasBuilder* builder = atlas->Builder; + builder->LockDisableResize = true; + + ImTextureData* old_tex = atlas->TexData; + ImTextureData* new_tex = ImFontAtlasBuildAddTexture(atlas, w, h); + new_tex->UseColors = old_tex->UseColors; + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d\n", old_tex->UniqueID, old_tex->Width, old_tex->Height, new_tex->UniqueID, new_tex->Width, new_tex->Height); + + // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. + +#if 1 + // Repack + copy pixels + // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic. + ImFontAtlasPackInit(atlas); + ImVector old_rects; + old_rects.swap(builder->Rects); + for (ImFontAtlasRect& old_r : old_rects) + { + ImFontAtlasRectId new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h); + if (new_r_id == -1) + { + // Undo, grow texture and try repacking again. + // FIXME-NEWATLAS-TESTS: This is a very rarely exercised path! It needs to be automatically tested properly. + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize failed. Will grow.\n", new_tex->UniqueID); + new_tex->WantDestroyNextFrame = true; + old_rects.swap(builder->Rects); + ImFontAtlasBuildSetTexture(atlas, old_tex); + ImFontAtlasBuildGrowTexture(atlas, w, h); + return; + } + ImFontAtlasRect* new_r = ImFontAtlasPackGetRect(atlas, new_r_id); + ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r->x, new_r->y, new_r->w, new_r->h); + } + IM_ASSERT(old_rects.Size == builder->Rects.Size); + + // Patch glyphs UV + for (ImFont* font : atlas->Fonts) + for (ImFontGlyph& glyph : font->Glyphs) + if (glyph.PackId != -1) + { + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); + glyph.U0 = (r->x) * atlas->TexUvScale.x; + glyph.V0 = (r->y) * atlas->TexUvScale.y; + glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + } + + // Update other cached UV + ImFontAtlasBuildUpdateLinesTexData(atlas, false); + ImFontAtlasBuildUpdateBasicTexData(atlas, false); + +#else + // Copy previous pixels + ImFontAtlasTextureCopyBlock(atlas, old_tex, 0, 0, new_tex, 0, 0, ImMin(old_tex->Width, new_tex->Width), ImMin(old_tex->Height, new_tex->Height)); + + // Scale UV coordinates + // FIXME-NEWATLAS: Probably lossy? + ImVec2 uv_scale((float)old_tex->Width / new_tex->Width, (float)old_tex->Height / new_tex->Height); + for (ImFont* font : atlas->Fonts) + for (ImFontGlyph& glyph : font->Glyphs) + { + glyph.U0 *= uv_scale.x; + glyph.U1 *= uv_scale.x; + glyph.V0 *= uv_scale.y; + glyph.V1 *= uv_scale.y; + } + ImVec4 uv_scale4(uv_scale.x, uv_scale.y, uv_scale.x, uv_scale.y); + atlas->TexUvWhitePixel *= uv_scale; + for (ImVec4& uv : atlas->TexUvLines) + uv = uv * uv_scale4; +#endif + + builder->LockDisableResize = false; + ImFontAtlasUpdateDrawListsSharedData(atlas); +} + +void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_h) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + if (old_tex_w == -1) + old_tex_w = atlas->TexData->Width; + if (old_tex_h == -1) + old_tex_h = atlas->TexData->Height; + + // FIXME-NEWATLAS-V1: Handle atlas->TexDesiredWidth from user? + // FIXME-NEWATLAS-V1: What to do when reaching limits exposed by backend? + // FIXME-NEWATLAS-V1: does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? + IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h)); + + // Grow texture so it follows roughly a square. + int new_tex_w = (old_tex_h < old_tex_w) ? old_tex_w : old_tex_w * 2; + int new_tex_h = (old_tex_h < old_tex_w) ? old_tex_h * 2 : old_tex_h; + + // Handle minimum size first (for pathologically large packed rects) + new_tex_w = ImMax(new_tex_w, ImUpperPowerOfTwo(builder->MaxRectSize.x + builder->PackPadding)); + new_tex_h = ImMax(new_tex_h, ImUpperPowerOfTwo(builder->MaxRectSize.y + builder->PackPadding)); + + ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); +} + +// You should not need to call this manually! +// If you think you do, let us know and we can advise about policies auto-compact. +void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + + ImTextureData* old_tex = atlas->TexData; + int old_tex_w = old_tex->Width; + int old_tex_h = old_tex->Height; + + // FIXME-NEWATLAS: Expose atlas->TexMinWidth etc. + const int min_w = ImMax(builder->MaxRectSize.x, 512); + const int min_h = builder->MaxRectSize.y; + const int surface_sqrt = (int)sqrtf((float)atlas->_PackedSurface); + + int new_tex_w; + int new_tex_h; + if (min_w >= min_h) + { + new_tex_w = ImMax(min_w, ImUpperPowerOfTwo(surface_sqrt)); + new_tex_h = ImMax(min_h, (int)(atlas->_PackedSurface / new_tex_w)); + if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0) + new_tex_h = ImUpperPowerOfTwo(new_tex_h); + } + else + { + new_tex_h = ImMax(min_h, ImUpperPowerOfTwo(surface_sqrt)); + if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0) + new_tex_h = ImUpperPowerOfTwo(new_tex_h); + new_tex_w = ImMax(min_w, (int)(atlas->_PackedSurface / new_tex_h)); + } + + if (new_tex_w == old_tex_w && new_tex_h == old_tex_h) + return; + + ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); +} + +// Start packing over current empty texture void ImFontAtlasBuildInit(ImFontAtlas* atlas) { - // Register texture region for mouse cursors or standard white pixels - if (atlas->PackIdMouseCursors < 0) + ImFontAtlasBuilder* builder = atlas->Builder; + + const bool builder_is_new = (builder == NULL); + if (builder_is_new) { - if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); - else - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); + builder = atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); + builder->PackPadding = 1; } - // Register texture region for thick lines - // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row - if (atlas->PackIdLines < 0) + ImFontAtlasPackInit(atlas); + + // Add required texture data + ImFontAtlasBuildUpdateLinesTexData(atlas, true); + ImFontAtlasBuildUpdateBasicTexData(atlas, true); + + // Register fonts + if (builder_is_new) { - if (!(atlas->Flags & ImFontAtlasFlags_NoBakedLines)) - atlas->PackIdLines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + ImFontAtlasBuildUpdatePointers(atlas); + for (ImFontConfig& cfg : atlas->Sources) + ImFontAtlasBuildAddFont(atlas, &cfg); } + + // Update UV coordinates etc. stored in bound ImDrawListSharedData instance + ImFontAtlasUpdateDrawListsSharedData(atlas); + + //atlas->TexIsBuilt = true; } -// This is called/shared by both the stb_truetype and the FreeType builder. -void ImFontAtlasBuildFinish(ImFontAtlas* atlas) +// Destroy builder and all cached glyphs. Do not destroy actual fonts. +void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) { - // Render into our custom data blocks - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL || atlas->TexPixelsRGBA32 != NULL); - ImFontAtlasBuildRenderDefaultTexData(atlas); - ImFontAtlasBuildRenderLinesTexData(atlas); + for (ImFont* font : atlas->Fonts) + font->BuildClearGlyphs(); + if (atlas->FontLoader && atlas->FontLoader->FontSrcDestroy != NULL) + for (ImFontConfig& font_cfg : atlas->Sources) + atlas->FontLoader->FontSrcDestroy(atlas, &font_cfg); - // Register custom rectangle glyphs - for (int i = 0; i < atlas->CustomRects.Size; i++) + IM_DELETE(atlas->Builder); + atlas->Builder = NULL; +} + +void ImFontAtlasPackInit(ImFontAtlas* atlas) +{ + ImTextureData* tex = atlas->TexData; + ImFontAtlasBuilder* builder = atlas->Builder; + + // FIXME-NEWATLAS-V2: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 + // FIXME-NEWATLAS-V2: Experiment with number of nodes. 2024-11-05: Seems to be quite fine to reduce this. + int pack_node_count = tex->Width - builder->PackPadding; + //pack_node_count *= atlas->_PackNodesFactor; + builder->PackNodes.resize(pack_node_count); + IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque)); + stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width - builder->PackPadding, tex->Height - builder->PackPadding, builder->PackNodes.Data, builder->PackNodes.Size); + atlas->_PackedSurface = atlas->_PackedRects = 0; + builder->MaxRectSize = ImVec2i(0, 0); + builder->MaxRectBounds = ImVec2i(0, 0); +} + +// Important: Calling this may recreate a new texture and therefore change atlas->TexData +ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h) +{ + IM_ASSERT(w > 0 && w <= 0xFFFF); + IM_ASSERT(h > 0 && h <= 0xFFFF); + + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + builder->MaxRectSize.x = ImMax(builder->MaxRectSize.x, w); + builder->MaxRectSize.y = ImMax(builder->MaxRectSize.y, h); + + // Pack + ImFontAtlasRect r = { 0, 0, (unsigned short)w, (unsigned short)h }; + for (int attempts_remaining = 3; attempts_remaining >= 0; attempts_remaining--) { - const ImFontAtlasCustomRect* r = &atlas->CustomRects[i]; - if (r->Font == NULL || r->GlyphID == 0) - continue; + // Try packing + stbrp_rect pack_r = {}; + pack_r.w = r.w + builder->PackPadding; + pack_r.h = r.h + builder->PackPadding; + stbrp_pack_rects((stbrp_context*)(void*)&builder->PackContext, &pack_r, 1); + r.x = (unsigned short)(pack_r.x + builder->PackPadding); + r.y = (unsigned short)(pack_r.y + builder->PackPadding); + if (pack_r.was_packed) + break; - // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, PixelSnapH - IM_ASSERT(r->Font->ContainerAtlas == atlas); - ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(r, &uv0, &uv1); - r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX); - if (r->GlyphColored) - r->Font->Glyphs.back().Colored = 1; + // If we ran out of attempts, return fallback + if (attempts_remaining == 0 || builder->LockDisableResize) + { + ImGuiContext& g = *GImGui; + IM_UNUSED(g); + IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.\n", w, h); + return -1; + } + + // Resize atlas! (this should be a rare event) + ImFontAtlasBuildGrowTexture(atlas); } - // Build all fonts lookup tables - for (ImFont* font : atlas->Fonts) - if (font->DirtyLookupTables) - font->BuildLookupTable(); + builder->MaxRectBounds.x = ImMax(builder->MaxRectBounds.x, r.x + r.w); + builder->MaxRectBounds.y = ImMax(builder->MaxRectBounds.y, r.y + r.h); + atlas->_PackedSurface += w * h; + atlas->_PackedRects++; - atlas->TexReady = true; + builder->Rects.push_back(r); + return builder->Rects.Size - 1; } +ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + return &builder->Rects[id]; +} + +ImFontGlyph* ImFont::BuildLoadGlyph(ImWchar codepoint) +{ + if (LockDisableLoading) + return NULL; + + //char utf8_buf[5]; + //IMGUI_DEBUG_LOG("[font] BuildAddGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); + + ImFontAtlas* atlas = ContainerAtlas; + const ImFontLoader* font_loader = atlas->FontLoader; + if (!font_loader->FontAddGlyph(atlas, this, codepoint)) + { + // Mark index as not found, so we don't attempt the search twice + BuildGrowIndex(codepoint + 1); + IndexAdvanceX[codepoint] = (float)IM_FONTGLYPH_INDEX_NOT_FOUND; + IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; + return NULL; + } + + // FIXME: Add hooks for e.g. #7962 + ImFontGlyph* glyph = &Glyphs.back(); + return glyph; +} + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) +{ + // [DEBUG] Log texture update requests + ImGuiContext& g = *GImGui; + IM_UNUSED(g); + for (ImTextureData* tex : atlas->TexList) + { + if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + IM_ASSERT(tex->Updates.Size == 0); + if (tex->Status == ImTextureStatus_WantCreate) + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: create %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + else if (tex->Status == ImTextureStatus_WantDestroy) + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: destroy %dx%d, texid=0x%" IM_PRIX64 ", backend_data=%p\n", tex->UniqueID, tex->Width, tex->Height, tex->TexID, tex->BackendUserData); + else if (tex->Status == ImTextureStatus_WantUpdates) + { + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); + for (const ImTextureRect& r : tex->Updates) + { + IM_ASSERT(r.x >= 0 && r.y >= 0); + IM_ASSERT(r.x + r.w < tex->Width && r.y + r.h < tex->Height); + //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); + } + } + } +} +#endif + +//------------------------------------------------------------------------- +// [SECTION] ImFontAtlas: backend for stb_truetype +//------------------------------------------------------------------------- +// (imstb_truetype.h in included near the top of this file, when IMGUI_ENABLE_STB_TRUETYPE is set) +//------------------------------------------------------------------------- + +#ifdef IMGUI_ENABLE_STB_TRUETYPE + +// One for each ConfigData +struct ImGui_ImplStbTrueType_FontSrcData +{ + stbtt_fontinfo FontInfo; + float ScaleForRasterX; // Factor in RasterizationDensity * OversampleH + float ScaleForRasterY; // Factor in RasterizationDensity * OversampleV + float ScaleForLayout; +}; + +static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplStbTrueType_FontSrcData); + IM_ASSERT(src->FontLoaderData == NULL); + + // Initialize helper structure for font loading and verify that the TTF/OTF data is correct + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src->FontData, src->FontNo); + IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); // FIXME-NEWATLAS: error handling + if (!stbtt_InitFont(&bd_font_data->FontInfo, (unsigned char*)src->FontData, font_offset)) + { + IM_ASSERT(0 && "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); + return false; + } + src->FontLoaderData = bd_font_data; + + // FIXME-NEWATLAS-V2: reevaluate sizing metrics + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); + if (src->SizePixels > 0.0f) + { + bd_font_data->ScaleForRasterX = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, src->SizePixels * src->RasterizerDensity) * oversample_h; + bd_font_data->ScaleForRasterY = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, src->SizePixels * src->RasterizerDensity) * oversample_v; + bd_font_data->ScaleForLayout = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, src->SizePixels); + } + else + { + bd_font_data->ScaleForRasterX = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, -src->SizePixels * src->RasterizerDensity) * oversample_h; + bd_font_data->ScaleForRasterY = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, -src->SizePixels * src->RasterizerDensity) * oversample_v; + bd_font_data->ScaleForLayout = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, -src->SizePixels); + } + + // FIXME-NEWATLAS-V2: make use of line gap value + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + + if (src->MergeMode == false) + { + ImFont* font = src->DstFont; + font->Ascent = ImCeil(unscaled_ascent * bd_font_data->ScaleForLayout); + font->Descent = ImFloor(unscaled_descent * bd_font_data->ScaleForLayout); + } + + return true; +} + +static void ImGui_ImplStbTrueType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_DELETE(bd_font_data); + src->FontLoaderData = NULL; +} + +static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) +{ + IM_UNUSED(atlas); + + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_ASSERT(bd_font_data != NULL); + + int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + return glyph_index != 0; +} + +static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImWchar codepoint) +{ + // Search for first font which has the glyph + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = NULL; + ImFontConfig* src = NULL; + int glyph_index = 0; + int scan_count = (font->LockSingleSrcConfig != NULL) ? 1 : font->SourcesCount; + for (int src_n = 0; src_n < scan_count; src_n++, bd_font_data++) + { + src = font->LockSingleSrcConfig ? font->LockSingleSrcConfig : &font->Sources[src_n]; + bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + if (glyph_index != 0) + break; + } + if (glyph_index == 0) + return false; // Not found + + // FIXME-NEWATLAS: Handling of atlas->TexGlyphPadding? + const float scale_for_layout = bd_font_data->ScaleForLayout; // ~ (font units to pixels) + const float scale_for_raster_x = bd_font_data->ScaleForRasterX; // ~ (font units to pixels) * RasterizationDensity * OversampleH + const float scale_for_raster_y = bd_font_data->ScaleForRasterY; // ~ (font units to pixels) * RasterizationDensity * OversampleV + + // Obtain size and advance + int x0, y0, x1, y1; + int advance, lsb; + stbtt_GetGlyphBitmapBoxSubpixel(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0, &x0, &y0, &x1, &y1); + stbtt_GetGlyphHMetrics(&bd_font_data->FontInfo, glyph_index, &advance, &lsb); + const bool is_visible = (x0 != x1 && y0 != y1); + + // Prepare glyph + ImFontGlyph glyph; + glyph.Codepoint = codepoint; + glyph.AdvanceX = advance * scale_for_layout; + + // Pack and retrieve position inside texture atlas + // (generally based on stbtt_PackFontRangesRenderIntoRects) + if (is_visible) + { + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); + const int w = (x1 - x0 + oversample_h - 1); + const int h = (y1 - y0 + oversample_v - 1); + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + font->MetricsTotalSurface += w * h; + + // Render + stbtt_GetGlyphBitmapBox(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, &x0, &y0, &x1, &y1); + ImFontAtlasBuilder* builder = atlas->Builder; + builder->TempBuffer.resize(w * h * 1); + unsigned char* bitmap_pixels = builder->TempBuffer.Data; + memset(bitmap_pixels, 0, w * h * 1); + stbtt_MakeGlyphBitmapSubpixel(&bd_font_data->FontInfo, bitmap_pixels, r->w - oversample_h + 1, r->h - oversample_v + 1, w, + scale_for_raster_x, scale_for_raster_y, 0, 0, glyph_index); + + // Oversampling + // (those functions conveniently assert if pixels are not cleared, which is another safety layer) + if (oversample_h > 1) + stbtt__h_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_h); + if (oversample_v > 1) + stbtt__v_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_v); + + float font_off_x = src->GlyphOffset.x + stbtt__oversample_shift(oversample_h); + float font_off_y = src->GlyphOffset.y + stbtt__oversample_shift(oversample_v) + IM_ROUND(font->Ascent); + float recip_h = 1.0f / (oversample_h * src->RasterizerDensity); + float recip_v = 1.0f / (oversample_v * src->RasterizerDensity); + + // Register glyph + // r->x r->y are coordinates inside texture (in pixels) + // glyph.X0, glyph.Y0 are drawing coordinates from base text position, and accounting for oversampling. + glyph.X0 = x0 * recip_h + font_off_x; + glyph.Y0 = y0 * recip_v + font_off_y; + glyph.X1 = (x0 + (int)r->w) * recip_h + font_off_x; + glyph.Y1 = (y0 + (int)r->h) * recip_v + font_off_y; + glyph.U0 = (r->x) * atlas->TexUvScale.x; + glyph.V0 = (r->y) * atlas->TexUvScale.y; + glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + glyph.Visible = true; + glyph.PackId = pack_id; + font->BuildRegisterGlyph(src, &glyph); + + // Copy to texture, post-process and queue update for backend + ImTextureData* tex = atlas->TexData; + IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); + ImFontAtlasTextureBlockConvertAndPostProcess(atlas, font, src, &font->Glyphs.back(), + bitmap_pixels, ImTextureFormat_Alpha8, w, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); + } + else + { + font->BuildRegisterGlyph(src, &glyph); + } + + return true; +} + +const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() +{ + static ImFontLoader loader; + loader.Name = "stb_truetype"; + loader.FontSrcInit = ImGui_ImplStbTrueType_FontSrcInit; + loader.FontSrcDestroy = ImGui_ImplStbTrueType_FontSrcDestroy; + loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph; + loader.FontAddGlyph = ImGui_ImplStbTrueType_FontAddGlyph; + return &loader; +} + +#endif // IMGUI_ENABLE_STB_TRUETYPE + //------------------------------------------------------------------------- // [SECTION] ImFontAtlas: glyph ranges helpers //------------------------------------------------------------------------- @@ -3710,113 +4376,30 @@ ImFont::~ImFont() ClearOutputData(); } -void ImFont::ClearOutputData() +void ImFont::ClearOutputData() { FontSize = 0.0f; FallbackAdvanceX = 0.0f; Glyphs.clear(); IndexAdvanceX.clear(); IndexLookup.clear(); - FallbackGlyph = NULL; + FallbackGlyphIndex = -1; ContainerAtlas = NULL; - DirtyLookupTables = true; Ascent = Descent = 0.0f; MetricsTotalSurface = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); } -static ImWchar FindFirstExistingGlyph(ImFont* font, const ImWchar* candidate_chars, int candidate_chars_count) +void ImFont::BuildClearGlyphs() { - for (int n = 0; n < candidate_chars_count; n++) - if (font->FindGlyphNoFallback(candidate_chars[n]) != NULL) - return candidate_chars[n]; - return 0; -} - -void ImFont::BuildLookupTable() -{ - int max_codepoint = 0; - for (int i = 0; i != Glyphs.Size; i++) - max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); - - // Build lookup table - IM_ASSERT(Glyphs.Size > 0 && "Font has not loaded glyph!"); - IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved + FallbackAdvanceX = 0.0f; + Glyphs.clear(); IndexAdvanceX.clear(); IndexLookup.clear(); - DirtyLookupTables = false; + FallbackGlyphIndex = 0; + MetricsTotalSurface = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); - GrowIndex(max_codepoint + 1); - for (int i = 0; i < Glyphs.Size; i++) - { - int codepoint = (int)Glyphs[i].Codepoint; - IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX; - IndexLookup[codepoint] = (ImU16)i; - - // Mark 4K page as used - const int page_n = codepoint / 8192; - Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); - } - - // Create a glyph to handle TAB - // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) - if (FindGlyph((ImWchar)' ')) - { - if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times (FIXME: Flaky) - Glyphs.resize(Glyphs.Size + 1); - ImFontGlyph& tab_glyph = Glyphs.back(); - tab_glyph = *FindGlyph((ImWchar)' '); - tab_glyph.Codepoint = '\t'; - tab_glyph.AdvanceX *= IM_TABSIZE; - IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; - IndexLookup[(int)tab_glyph.Codepoint] = (ImU16)(Glyphs.Size - 1); - } - - // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons) - if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)' ')) - glyph->Visible = false; - if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)'\t')) - glyph->Visible = false; - - // Setup Fallback character - const ImWchar fallback_chars[] = { (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; - FallbackGlyph = FindGlyphNoFallback(FallbackChar); - if (FallbackGlyph == NULL) - { - FallbackChar = FindFirstExistingGlyph(this, fallback_chars, IM_ARRAYSIZE(fallback_chars)); - FallbackGlyph = FindGlyphNoFallback(FallbackChar); - if (FallbackGlyph == NULL) - { - FallbackGlyph = &Glyphs.back(); - FallbackChar = (ImWchar)FallbackGlyph->Codepoint; - } - } - FallbackAdvanceX = FallbackGlyph->AdvanceX; - for (int i = 0; i < max_codepoint + 1; i++) - if (IndexAdvanceX[i] < 0.0f) - IndexAdvanceX[i] = FallbackAdvanceX; - - // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). - // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. - // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots. - const ImWchar ellipsis_chars[] = { Sources->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 }; - const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; - if (EllipsisChar == 0) - EllipsisChar = FindFirstExistingGlyph(this, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars)); - const ImWchar dot_char = FindFirstExistingGlyph(this, dots_chars, IM_ARRAYSIZE(dots_chars)); - if (EllipsisChar != 0) - { - EllipsisCharCount = 1; - EllipsisWidth = EllipsisCharStep = FindGlyph(EllipsisChar)->X1; - } - else if (dot_char != 0) - { - const ImFontGlyph* dot_glyph = FindGlyph(dot_char); - EllipsisChar = dot_char; - EllipsisCharCount = 3; - EllipsisCharStep = (float)(int)(dot_glyph->X1 - dot_glyph->X0) + 1.0f; - EllipsisWidth = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + EllipsisCharStep * 3.0f - 1.0f); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. - } + // Don't clear BuilderData } // API is designed this way to avoid exposing the 8K page size @@ -3832,7 +4415,7 @@ bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) return true; } -void ImFont::GrowIndex(int new_size) +void ImFont::BuildGrowIndex(int new_size) { IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); if (new_size <= IndexLookup.Size) @@ -3844,50 +4427,43 @@ void ImFont::GrowIndex(int new_size) // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. // Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). // 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. -void ImFont::AddGlyph(const ImFontConfig* src, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) +void ImFont::BuildRegisterGlyph(ImFontConfig* src, const ImFontGlyph* in_glyph) { + int glyph_idx = Glyphs.Size; + Glyphs.push_back(*in_glyph); + ImFontGlyph& glyph = Glyphs[glyph_idx]; + IM_ASSERT(Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. + if (src != NULL) { // Clamp & recenter if needed - const float advance_x_original = advance_x; - advance_x = ImClamp(advance_x, src->GlyphMinAdvanceX, src->GlyphMaxAdvanceX); - if (advance_x != advance_x_original) + float advance_x = ImClamp(glyph.AdvanceX, src->GlyphMinAdvanceX, src->GlyphMaxAdvanceX); + if (advance_x != glyph.AdvanceX) { - float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f; - x0 += char_off_x; - x1 += char_off_x; + float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - glyph.AdvanceX) * 0.5f) : (advance_x - glyph.AdvanceX) * 0.5f; + glyph.X0 += char_off_x; + glyph.X1 += char_off_x; } // Snap to pixel if (src->PixelSnapH) advance_x = IM_ROUND(advance_x); - // Bake extra spacing - advance_x += src->GlyphExtraAdvanceX; + // Bake spacing + glyph.AdvanceX = advance_x + src->GlyphExtraAdvanceX; } + if (glyph.Colored) + ContainerAtlas->TexPixelsUseColors = ContainerAtlas->TexData->UseColors = true; - int glyph_idx = Glyphs.Size; - Glyphs.resize(Glyphs.Size + 1); - ImFontGlyph& glyph = Glyphs[glyph_idx]; - glyph.Codepoint = (unsigned int)codepoint; - glyph.Visible = (x0 != x1) && (y0 != y1); - glyph.Colored = false; - glyph.X0 = x0; - glyph.Y0 = y0; - glyph.X1 = x1; - glyph.Y1 = y1; - glyph.U0 = u0; - glyph.V0 = v0; - glyph.U1 = u1; - glyph.V1 = v1; - glyph.AdvanceX = advance_x; - IM_ASSERT(Glyphs.Size < 0xFFFF); // IndexLookup[] hold 16-bit values and -1 is reserved. + // Update lookup tables + int codepoint = glyph.Codepoint; + BuildGrowIndex(codepoint + 1); + IndexAdvanceX[codepoint] = glyph.AdvanceX; + IndexLookup[codepoint] = (ImU16)glyph_idx; - // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round) - // We use (U1-U0)*TexWidth instead of X1-X0 to account for oversampling. - float pad = ContainerAtlas->TexGlyphPadding + 0.99f; - DirtyLookupTables = true; - MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad); + // Mark 4K page as used + const int page_n = codepoint / 8192; + Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); } void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst) @@ -3900,30 +4476,76 @@ void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool ove if (to_codepoint >= index_size && from_codepoint >= index_size) // both 'from_codepoint' and 'to_codepoint' don't exist -> no-op return; - GrowIndex(from_codepoint + 1); + BuildGrowIndex(from_codepoint + 1); IndexLookup[from_codepoint] = (to_codepoint < index_size) ? IndexLookup.Data[to_codepoint] : (ImU16)-1; IndexAdvanceX[from_codepoint] = (to_codepoint < index_size) ? IndexAdvanceX.Data[to_codepoint] : 1.0f; } -// Find glyph, return fallback if missing +// Find glyph, load if necessary, return fallback if missing ImFontGlyph* ImFont::FindGlyph(ImWchar c) { - if (c >= (size_t)IndexLookup.Size) - return FallbackGlyph; - const ImU16 i = IndexLookup.Data[c]; - if (i == (ImU16)-1) - return FallbackGlyph; - return &Glyphs.Data[i]; + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return &Glyphs.Data[FallbackGlyphIndex]; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return &Glyphs.Data[i]; + } + ImFontGlyph* glyph = BuildLoadGlyph(c); + return glyph ? glyph : &Glyphs.Data[FallbackGlyphIndex]; } +// Attempt to load but when missing, return NULL instead of FallbackGlyph ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) { - if (c >= (size_t)IndexLookup.Size) - return NULL; - const ImU16 i = IndexLookup.Data[c]; - if (i == (ImU16)-1) - return NULL; - return &Glyphs.Data[i]; + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return NULL; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return &Glyphs.Data[i]; + } + ImFontGlyph* glyph = BuildLoadGlyph(c); + return glyph; +} + +bool ImFont::IsGlyphLoaded(ImWchar c) +{ + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return false; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return true; + } + return false; +} + +// This is not fast query +bool ImFont::IsGlyphInFont(ImWchar c) +{ + ImFontAtlas* atlas = ContainerAtlas; + for (int src_n = 0; src_n < SourcesCount; src_n++) + if (atlas->FontLoader->FontSrcContainsGlyph(atlas, &Sources[src_n], c)) + return true; + return false; +} + +float ImFont::GetCharAdvance(ImWchar c) +{ + if (c < (size_t)IndexAdvanceX.Size) + { + const float x = IndexAdvanceX.Data[c]; + if (x >= 0.0f) + return x; + if (x == (float)IM_FONTGLYPH_INDEX_NOT_FOUND) // FIXME-NEWATLAS: could bake in index + return FallbackAdvanceX; + } + const ImFontGlyph* glyph = BuildLoadGlyph(c); + return glyph ? glyph->AdvanceX : FallbackAdvanceX; } // Trim trailing space and find beginning of next line @@ -3991,7 +4613,9 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha } } - const float char_width = ImFontGetCharAdvanceX(this, c); + // FIXME-NEWATLAS-V1: Measure perf, inline etc. + //const float char_width = ImFontGetCharAdvanceX(this, c); + const float char_width = GetCharAdvance((ImWchar)c); // ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX); if (ImCharIsBlankW(c)) { if (inside_word) @@ -4096,7 +4720,9 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons continue; } - const float char_width = ImFontGetCharAdvanceX(this, c) * scale; + // FIXME-NEWATLAS-V1: Measure perf, inline etc. + //const float char_width = ImFontGetCharAdvanceX(this, c) * scale; + const float char_width = GetCharAdvance((ImWchar)c) /* (int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX)*/ * scale; if (line_width + char_width >= max_width) { s = prev_s; diff --git a/imgui_internal.h b/imgui_internal.h index 91ac0bc83..3b650c9d5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -37,6 +37,7 @@ Index of this file: // [SECTION] Tab bar, Tab item support // [SECTION] Table support // [SECTION] ImGui internal API +// [SECTION] ImFontLoader // [SECTION] ImFontAtlas internal API // [SECTION] Test Engine specific hooks (imgui_test_engine) @@ -140,6 +141,8 @@ struct ImGuiTextIndex; // Maintain a line index for a text buffer. // ImDrawList/ImFontAtlas struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances +struct ImFontAtlasRect; // Packed rectangle (same as ImTextureRect) +struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas // ImGui struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) @@ -530,6 +533,14 @@ struct ImVec1 constexpr ImVec1(float _x) : x(_x) { } }; +// Helper: ImVec2i (2D vector, integer) +struct ImVec2i +{ + int x, y; + constexpr ImVec2i() : x(0), y(0) {} + constexpr ImVec2i(int _x, int _y) : x(_x), y(_y) {} +}; + // Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage) struct ImVec2ih { @@ -789,8 +800,9 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag // You may want to create your own instance of you try to ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. struct IMGUI_API ImDrawListSharedData { - ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas - const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas + ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) + const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) + ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current/default font (optional, for simplified AddText overload) float FontSize; // Current/default font size (optional, for simplified AddText overload) float FontScale; // Current/default font scale (== FontSize / Font->FontSize) @@ -800,13 +812,17 @@ struct IMGUI_API ImDrawListSharedData ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() ImVector TempBuffer; // Temporary write buffer + ImVector DrawLists; // All draw lists associated to this ImDrawListSharedData + ImGuiContext* Context; // [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. // Lookup tables ImVec2 ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle. float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo() ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) + bool RendererHasTextures; // Copy of (GetIO().BackendFlags & ImGuiBackendFlags_RendererHasTextures). ImDrawListSharedData(); + ~ImDrawListSharedData(); void SetCircleTessellationMaxError(float max_error); }; @@ -2085,6 +2101,7 @@ struct ImGuiContext float FontScale; // == FontSize / Font->FontSize float CurrentDpiScale; // Current window/viewport DpiScale ImDrawListSharedData DrawListSharedData; + ImVectorTextures; double Time; int FrameCount; int FrameCountEnded; @@ -3561,6 +3578,7 @@ namespace ImGui IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); IMGUI_API void DebugNodeFont(ImFont* font); IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph); + IMGUI_API void DebugNodeTexture(ImTextureData* tex); IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label); IMGUI_API void DebugNodeTable(ImGuiTable* table); @@ -3593,31 +3611,102 @@ namespace ImGui } // namespace ImGui +//----------------------------------------------------------------------------- +// [SECTION] ImFontLoader +//----------------------------------------------------------------------------- + +// Hooks and storage for a given font backend. +// This structure is likely to evolve as we add support for incremental atlas updates. +// Conceptually this could be in ImGuiPlatformIO, but we are far from ready to make this public. +struct ImFontLoader +{ + const char* Name; + bool (*LoaderInit)(ImFontAtlas* atlas); + void (*LoaderShutdown)(ImFontAtlas* atlas); + bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); + void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); + bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); + bool (*FontAddGlyph)(ImFontAtlas* atlas, ImFont* font, ImWchar codepoint); + + ImFontLoader() { memset(this, 0, sizeof(*this)); } +}; + +#ifdef IMGUI_ENABLE_STB_TRUETYPE +IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); +#endif + //----------------------------------------------------------------------------- // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- -// This structure is likely to evolve as we add support for incremental atlas updates. -// Conceptually this could be in ImGuiPlatformIO, but we are far from ready to make this public. -struct ImFontBuilderIO +// Packed rectangle (same as ImTextureRect) +struct ImFontAtlasRect { - bool (*FontBuilder_Build)(ImFontAtlas* atlas); + unsigned short x, y; + unsigned short w, h; +}; +typedef int ImFontAtlasRectId; // <0 when invalid + +// Internal storage for incrementally packing and building a ImFontAtlas +struct stbrp_context_opaque { char data[80]; }; +struct stbrp_node; +struct ImFontAtlasBuilder +{ + stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file. + ImVector PackNodes; + int PackPadding; // Generally 1 to avoid bilinear filtering issues. + ImVector Rects; + ImVector TempBuffer; // Misc scratch buffer + ImVec2i MaxRectSize; // Largest rectangle to pack (defacto 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. + + // Custom rectangle identifiers + ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. + ImFontAtlasRectId PackIdLinesTexData; + + ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); } }; -// Helper for font builder -#ifdef IMGUI_ENABLE_STB_TRUETYPE -IMGUI_API const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype(); +// FIXME-NEWATLAS: Cleanup +IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader); +IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); + +IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); + +IMGUI_API ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); +IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); + +IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy +IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); + +IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); +IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h); +IMGUI_API ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); + +IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); +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 void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas); + +IMGUI_API void ImFontAtlasTextureBlockConvertAndPostProcess(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, ImFontGlyph* glyph, unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst, ImTextureFormat dst_fmt, int dst_pitch, int w, int h); +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 ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, ImFontGlyph* glyph, unsigned char* pixels, ImTextureFormat format, int w, int h, int pitch, float in_multiply_factor); +IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h); +IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h); + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +IMGUI_API void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas); #endif -IMGUI_API void ImFontAtlasUpdateSourcesPointers(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, float ascent, float descent); -IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); -IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value); -IMGUI_API void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value); -IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); -IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); -IMGUI_API void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); IMGUI_API bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1c22bd4c6..186b639b5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3984,7 +3984,8 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c if (c == '\r') continue; - const float char_width = ((int)c < font->IndexAdvanceX.Size ? font->IndexAdvanceX.Data[c] : font->FallbackAdvanceX) * scale; + // FIXME-NEWATLAS-V1: Measure perf, inline etc. + const float char_width = font->GetCharAdvance((ImWchar)c) * scale;// ((int)c < font->IndexAdvanceX.Size ? font->IndexAdvanceX.Data[c] : font->FallbackAdvanceX)* scale; line_width += char_width; } @@ -4322,7 +4323,7 @@ void ImGui::PushPasswordFont() out_font->Ascent = in_font->Ascent; out_font->Descent = in_font->Descent; out_font->ContainerAtlas = in_font->ContainerAtlas; - out_font->FallbackGlyph = glyph; + out_font->FallbackGlyphIndex = in_font->Glyphs.index_from_ptr(glyph); // FIXME: broken out_font->FallbackAdvanceX = glyph->AdvanceX; IM_ASSERT(out_font->Glyphs.Size == 0 && out_font->IndexAdvanceX.Size == 0 && out_font->IndexLookup.Size == 0); PushFont(out_font); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 6521f83b9..1a268365b 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -166,7 +166,7 @@ namespace // NB: No ctor/dtor, explicitly call Init()/Shutdown() struct FreeTypeFont { - bool InitFont(FT_Library ft_library, const ImFontConfig& src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. + bool InitFont(FT_Library ft_library, ImFontConfig& src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. void CloseFont(); void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); @@ -185,7 +185,7 @@ namespace float InvRasterizationDensity; }; - bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& src, unsigned int extra_font_builder_flags) + bool FreeTypeFont::InitFont(FT_Library ft_library, ImFontConfig& src, unsigned int extra_font_builder_flags) { FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src.FontData, (uint32_t)src.FontDataSize, (uint32_t)src.FontNo, &Face); if (error != 0) From 2cde9125d6286c878c5e00d4a9ff9c85e108aa8d Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 17 Jan 2025 18:06:25 +0100 Subject: [PATCH 0889/2359] Fonts: Selecting font config source list done by shared code. --- imgui.h | 10 +++++----- imgui_draw.cpp | 24 +++++++++++++++--------- imgui_internal.h | 2 +- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/imgui.h b/imgui.h index 0420b4358..753fffe92 100644 --- a/imgui.h +++ b/imgui.h @@ -3631,19 +3631,19 @@ struct ImFont float FallbackAdvanceX; // 4 // out // FindGlyph(FallbackChar)->AdvanceX float FontSize; // 4 // in // Height of characters/line, set during loading (don't change after loading) - // [Internal] Members: Hot ~28/40 bytes (for RenderText loop) + // [Internal] Members: Hot ~28/36 bytes (for RenderText loop) ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. ImVector Glyphs; // 12-16 // out // All glyphs. int FallbackGlyphIndex; // 4 // out // Index of FontFallbackChar - // [Internal] Members: Cold ~32/40 bytes + // [Internal] Members: Cold ~32/40/60 bytes // Conceptually Sources[] is the list of font sources merged to create this font. - ImFontAtlas* ContainerAtlas; // 4-8 // out // What we has been loaded into - ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances short SourcesCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. short EllipsisCharCount; // 1 // out // 1 or 3 ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') + ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances + ImFontAtlas* ContainerAtlas; // 4-8 // out // What we has been loaded into float EllipsisWidth; // 4 // out // Total ellipsis Width float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() @@ -3651,7 +3651,7 @@ struct ImFont int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool LockDisableLoading; - ImFontConfig* LockSingleSrcConfig; + short LockSingleSrcConfigIdx; // Methods IMGUI_API ImFont(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b1cf15ff4..a497663b9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3394,10 +3394,12 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src) { ImFont* font = src->DstFont; + const int cfg_idx_in_font = (int)(src - font->Sources); + IM_ASSERT(cfg_idx_in_font >= 0 && cfg_idx_in_font < font->SourcesCount); IM_UNUSED(atlas); // While manipulating glyphs during init we want to restrict all searches for one source font. - font->LockSingleSrcConfig = src; + font->LockSingleSrcConfigIdx = (short)cfg_idx_in_font; // Setup Fallback character // FIXME-NEWATLAS: could we use a scheme where this is lazily loaded? @@ -3448,8 +3450,7 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* sr font->EllipsisWidth = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + font->EllipsisCharStep * 3.0f - 1.0f); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. } } - - font->LockSingleSrcConfig = NULL; + font->LockSingleSrcConfigIdx = -1; } // Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* @@ -3809,10 +3810,15 @@ ImFontGlyph* ImFont::BuildLoadGlyph(ImWchar codepoint) //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildAddGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); - ImFontAtlas* atlas = ContainerAtlas; + + // Load from single source or all sources? + int srcs_count = (LockSingleSrcConfigIdx != -1) ? 1 : SourcesCount; + ImFontConfig* srcs = (LockSingleSrcConfigIdx != -1) ? &Sources[LockSingleSrcConfigIdx] : Sources; + + // Call backend const ImFontLoader* font_loader = atlas->FontLoader; - if (!font_loader->FontAddGlyph(atlas, this, codepoint)) + if (!font_loader->FontAddGlyph(atlas, this, srcs, srcs_count, codepoint)) { // Mark index as not found, so we don't attempt the search twice BuildGrowIndex(codepoint + 1); @@ -3937,16 +3943,15 @@ static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFon return glyph_index != 0; } -static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImWchar codepoint) +static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) { // Search for first font which has the glyph ImGui_ImplStbTrueType_FontSrcData* bd_font_data = NULL; ImFontConfig* src = NULL; int glyph_index = 0; - int scan_count = (font->LockSingleSrcConfig != NULL) ? 1 : font->SourcesCount; - for (int src_n = 0; src_n < scan_count; src_n++, bd_font_data++) + for (int src_n = 0; src_n < srcs_count; src_n++) { - src = font->LockSingleSrcConfig ? font->LockSingleSrcConfig : &font->Sources[src_n]; + src = &srcs[src_n]; bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); if (glyph_index != 0) @@ -4369,6 +4374,7 @@ ImFont::ImFont() { memset(this, 0, sizeof(*this)); Scale = 1.0f; + LockSingleSrcConfigIdx = -1; } ImFont::~ImFont() diff --git a/imgui_internal.h b/imgui_internal.h index 3b650c9d5..27d1ca8e1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3626,7 +3626,7 @@ struct ImFontLoader bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); - bool (*FontAddGlyph)(ImFontAtlas* atlas, ImFont* font, ImWchar codepoint); + bool (*FontAddGlyph)(ImFontAtlas* atlas, ImFont* font, ImFontConfig* srcs, int srcs_count, ImWchar codepoint); ImFontLoader() { memset(this, 0, sizeof(*this)); } }; From ee357aaddf438e93127eed68e9be6456ca5130a3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jan 2025 15:35:32 +0100 Subject: [PATCH 0890/2359] Textures: Add ImTextureUserID_Invalid + introducing SetTexID(). Which gives us room for potentially updating ImDrawData during render. --- imgui.h | 21 +++++++++++++++------ imgui_draw.cpp | 6 +++--- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index 753fffe92..e51280e44 100644 --- a/imgui.h +++ b/imgui.h @@ -318,6 +318,11 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE typedef ImU64 ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) #endif +// Define this to another value if you need value of 0 to be valid. +#ifndef ImTextureID_Invalid +#define ImTextureID_Invalid ((ImTextureID)0) +#endif + // ImTextureRef contains: // - a texture/atlas pointer, typically when created by Dear ImGui itself. // - OR a raw ImTextureID value (user/backend identifier), typically when created by user code to load images. @@ -3362,21 +3367,19 @@ struct ImTextureRect // - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both. struct IMGUI_API ImTextureData { - ImTextureStatus Status; // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy + ImTextureStatus Status; // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! ImTextureFormat Format; // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8 int Width; // Texture width int Height; // Texture height int BytesPerPixel; // 4 or 1 int UniqueID; // Sequential index to facilitate identifying a texture when debugging/printing. Only unique per atlas. unsigned char* Pixels; // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. - ImTextureID TexID; // Identifier stored in ImDrawCmd::GetTexID() and passed to backend RenderDrawData loop. + ImTextureID TexID; // Always use SetTexID() to modify! Identifier stored in ImDrawCmd::GetTexID() and passed to backend RenderDrawData loop. void* BackendUserData; // Convenience storage for backend. Some backends may have enough with TexID. ImTextureRect UpdateRect; // Bounding box encompassing all individual updates. ImVector Updates; // Array of individual updates. int UnusedFrames; // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. - - // [Internal] - bool UseColors; // [Internal] Tell whether our texture data is known to use colors (rather than just white + alpha). + bool UseColors; // Tell whether our texture data is known to use colors (rather than just white + alpha). bool WantDestroyNextFrame; // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. // Functions @@ -3390,6 +3393,10 @@ struct IMGUI_API ImTextureData int GetPitch() const { return Width * BytesPerPixel; } ImTextureRef GetTexRef() const { ImTextureRef tex_ref; tex_ref._TexData = (ImTextureData*)(void*)this; tex_ref._TexID = TexID; return tex_ref; } ImTextureID GetTexID() const { return TexID; } + + // Called by Renderer backend + void SetTexID(ImTextureID tex_id) { TexID = tex_id; } // Call after creating or destroying the texture. Never modify TexID directly! + void SetStatus(ImTextureStatus status) { Status = status; } // Call after honoring a request. Never modify Status directly! }; //----------------------------------------------------------------------------- @@ -3689,9 +3696,11 @@ struct ImFont // FIXME-NEWATLAS: Added indirection to avoid patching ImDrawCmd after texture updates. inline ImTextureID ImDrawCmd::GetTexID() const { + // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92) + // must iterate and handle ImTextureData requests stored in ImDrawData::Textures[]. ImTextureID tex_id = TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID; if (TexRef._TexData != NULL) - IM_ASSERT(tex_id && "ImDrawCmd is referring to Atlas texture that wasn't uploaded to graphics system."); + IM_ASSERT(tex_id != ImTextureID_Invalid && "ImDrawCmd is referring to ImTextureData that wasn't uploaded to graphics system. Backend must call ImTextureData::SetTexID() after handling ImTextureStatus_WantCreate request!"); return tex_id; } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a497663b9..1e66a3b9c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2695,7 +2695,7 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) if (tex->Status == ImTextureStatus_Destroyed) { - IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == NULL); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL); if (tex->WantDestroyNextFrame) remove_from_list = true; // Destroy was scheduled by us else @@ -2715,7 +2715,7 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) tex->UnusedFrames++; // If a texture has never reached the backend, they don't need to know about it. - if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == 0 && tex->BackendUserData == NULL) + if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL) remove_from_list = true; // Remove @@ -3518,7 +3518,7 @@ ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h) /*if (old_tex != NULL && old_tex->Status == ImTextureStatus_WantCreate) { // Reuse texture not yet used by backend. - IM_ASSERT(old_tex->TexID == 0 && old_tex->BackendUserData == NULL); + IM_ASSERT(old_tex->TexID == ImTextureID_Invalid && old_tex->BackendUserData == NULL); old_tex->DestroyPixels(); old_tex->Updates.clear(); new_tex = old_tex; From a21a2e855b74d92b33172fc8b7d880a8f6e09d71 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jan 2025 19:12:58 +0100 Subject: [PATCH 0891/2359] Textures: Single Textures[] array allows backend to not have to care about atlases. # Conflicts: # imgui.h --- imgui.cpp | 15 +++++++++++++++ imgui.h | 15 ++++++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5acd91c0c..dd6b939e5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1271,6 +1271,7 @@ static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt); // Misc static void UpdateFontsNewFrame(); static void UpdateTexturesNewFrame(); +static void UpdateTexturesEndFrame(); static void UpdateSettings(); static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowOuterBorders(ImGuiWindow* window); @@ -5182,6 +5183,18 @@ static void ImGui::UpdateTexturesNewFrame() ImFontAtlasUpdateNewFrame(atlas); } +// Build a single texture list +// We want to avoid user reading from atlas->TexList[] in order to facilitate better support for multiple atlases. +static void ImGui::UpdateTexturesEndFrame() +{ + ImGuiContext& g = *GImGui; + ImFontAtlas* atlas = g.IO.Fonts; + g.PlatformIO.Textures.resize(0); + g.PlatformIO.Textures.reserve(atlas->TexList.Size); + for (ImTextureData* tex : atlas->TexList) + g.PlatformIO.Textures.push_back(tex); +} + // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! static void SetupDrawListSharedData() @@ -5759,6 +5772,8 @@ void ImGui::EndFrame() g.Windows.swap(g.WindowsTempSortBuffer); g.IO.MetricsActiveWindows = g.WindowsActiveCount; + UpdateTexturesEndFrame(); + // Unlock font atlas g.IO.Fonts->Locked = false; diff --git a/imgui.h b/imgui.h index e51280e44..936c177fe 100644 --- a/imgui.h +++ b/imgui.h @@ -3496,7 +3496,7 @@ enum ImFontAtlasFlags_ // - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). // - If you don't call any AddFont*** functions, the default font embedded in the code will be loaded for you. // It is the rendering backend responsibility to upload texture into your graphics API: -// - ImGui_ImplXXXX_RenderDrawData() functions generally iterate atlas->TexList[] to create/update/destroy each ImTextureData instance. +// - ImGui_ImplXXXX_RenderDrawData() functions generally iterate platform_io->Textures[] to create/update/destroy each ImTextureData instance. // - Backend then set ImTextureData's TexID and BackendUserData. // - Texture id are passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. // Legacy path: @@ -3597,11 +3597,9 @@ struct ImFontAtlas int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). - // Output - ImTextureData* TexData; // Current texture - ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). - // [Internal] + ImTextureData* TexData; // Current texture + ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetPlatformIO().Textures[] instead! bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. bool TexIsBuilt; // Set when texture was built matching current font input bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. @@ -3788,6 +3786,13 @@ struct ImGuiPlatformIO // Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. void* Renderer_RenderState; + + //------------------------------------------------------------------ + // Output + //------------------------------------------------------------------ + + // Textures list (the list is updated by calling ImGui::EndFrame or ImGui::Render) + ImVector Textures; // Texture list (most often Textures.Size == 1). }; // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). From 208705368efdb9da4c45b377dc9bc0c5ea8458b6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Mar 2025 16:14:11 +0100 Subject: [PATCH 0892/2359] Textures: Adding a RefCount to textures so backend can avoid destroying them on shutdown if atlas is shared. --- imgui.cpp | 19 ++++++++++++++----- imgui.h | 5 +++-- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index dd6b939e5..7821841d4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3942,6 +3942,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) Font = NULL; FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); + IO.Fonts->RefCount++; Time = 0.0f; FrameCount = 0; FrameCountEnded = FrameCountRendered = -1; @@ -4212,12 +4213,15 @@ void ImGui::Shutdown() IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?"); // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) - if (g.IO.Fonts) - ImFontAtlasRemoveDrawListSharedData(g.IO.Fonts, &g.DrawListSharedData); - if (g.IO.Fonts && g.FontAtlasOwnedByContext) + if (ImFontAtlas* atlas = g.IO.Fonts) { - g.IO.Fonts->Locked = false; - IM_DELETE(g.IO.Fonts); + ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData); + atlas->RefCount--; + if (g.FontAtlasOwnedByContext) + { + atlas->Locked = false; + IM_DELETE(atlas); + } } g.IO.Fonts = NULL; g.DrawListSharedData.TempBuffer.clear(); @@ -5192,7 +5196,12 @@ static void ImGui::UpdateTexturesEndFrame() g.PlatformIO.Textures.resize(0); g.PlatformIO.Textures.reserve(atlas->TexList.Size); for (ImTextureData* tex : atlas->TexList) + { + // We provide this information so backends can decide whether to destroy textures. + // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized. + tex->RefCount = (unsigned short)atlas->RefCount; g.PlatformIO.Textures.push_back(tex); + } } // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. diff --git a/imgui.h b/imgui.h index 936c177fe..b9e8f93bc 100644 --- a/imgui.h +++ b/imgui.h @@ -3379,6 +3379,7 @@ struct IMGUI_API ImTextureData ImTextureRect UpdateRect; // Bounding box encompassing all individual updates. ImVector Updates; // Array of individual updates. int UnusedFrames; // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. + unsigned short RefCount; // Number of contexts using this texture. bool UseColors; // Tell whether our texture data is known to use colors (rather than just white + alpha). bool WantDestroyNextFrame; // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. @@ -3591,13 +3592,12 @@ struct ImFontAtlas // Input ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) - ImTextureRef TexRef; // User data to refer to the latest texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. - int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8). int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). // [Internal] + ImTextureRef TexRef; // User data to refer to the latest texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. ImTextureData* TexData; // Current texture ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetPlatformIO().Textures[] instead! bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. @@ -3618,6 +3618,7 @@ struct ImFontAtlas const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name void* FontLoaderData; // Font backend opaque storage unsigned int FontBuilderFlags; // [FIXME: Should be called FontLoaderFlags] Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. . Per-font override is also available in ImFontConfig. + int RefCount; // Number of contexts using this atlas int _PackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. int _PackedRects; // Number of packed rectangles. float _PackNodesFactor = 1.0f; From c20e160e0f22b35fcff66393abe03254c6f00bf1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 9 May 2025 21:41:01 +0200 Subject: [PATCH 0893/2359] Textures: added texture list pointer in ImDrawData. # Conflicts: # imgui.h --- imgui.cpp | 1 + imgui.h | 10 ++++++---- imgui_draw.cpp | 1 + 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7821841d4..ce2b06462 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5588,6 +5588,7 @@ static void InitViewportDrawData(ImGuiViewportP* viewport) draw_data->DisplaySize = viewport->Size; draw_data->FramebufferScale = io.DisplayFramebufferScale; draw_data->OwnerViewport = viewport; + draw_data->Textures = &ImGui::GetPlatformIO().Textures; } // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. diff --git a/imgui.h b/imgui.h index b9e8f93bc..c95f5ac57 100644 --- a/imgui.h +++ b/imgui.h @@ -366,7 +366,7 @@ namespace ImGui IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData(). - IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. + IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). Call ImGui_ImplXXXX_RenderDrawData() function in your Renderer Backend to render. // Demo, Debug, Information IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! @@ -3313,7 +3313,7 @@ struct ImDrawList struct ImDrawData { bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. - int CmdListsCount; // Number of ImDrawList* to render (should always be == CmdLists.size) + int CmdListsCount; // Number of ImDrawList* to render. (== CmdLists.Size). Exists for legacy reason. int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size ImVector CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. @@ -3321,6 +3321,7 @@ struct ImDrawData ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). + ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overriden or set to NULL if you want to manually update textures. // Functions ImDrawData() { Clear(); } @@ -3599,7 +3600,7 @@ struct ImFontAtlas // [Internal] ImTextureRef TexRef; // User data to refer to the latest texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. ImTextureData* TexData; // Current texture - ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetPlatformIO().Textures[] instead! + ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. bool TexIsBuilt; // Set when texture was built matching current font input bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. @@ -3793,7 +3794,8 @@ struct ImGuiPlatformIO //------------------------------------------------------------------ // Textures list (the list is updated by calling ImGui::EndFrame or ImGui::Render) - ImVector Textures; // Texture list (most often Textures.Size == 1). + // The ImGui_ImplXXXX_RenderDrawData() function of each backend generally access this via ImDrawData::Textures which points to this. The array is available here mostly because backends will want to destroy textures on shutdown. + ImVector Textures; // List of textures used by Dear ImGui (most often 1). }; // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1e66a3b9c..0bde7a116 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2244,6 +2244,7 @@ void ImDrawData::Clear() CmdLists.resize(0); // The ImDrawList are NOT owned by ImDrawData but e.g. by ImGuiContext, so we don't clear them. DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.0f, 0.0f); OwnerViewport = NULL; + Textures = NULL; } // Important: 'out_list' is generally going to be draw_data->CmdLists, but may be another temporary list From 372fd27e714893b0c80e9fe0dc554c0caabd3933 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Nov 2024 18:46:02 +0100 Subject: [PATCH 0894/2359] Backends: DirectX11: added ImGuiBackendFlags_RendererHasTextures support. # Conflicts: # backends/imgui_impl_dx11.cpp --- backends/imgui_impl_dx11.cpp | 114 +++++++++++++++++++++++------------ backends/imgui_impl_dx11.h | 6 +- 2 files changed, 82 insertions(+), 38 deletions(-) diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index f6a7f35f6..14e74e9b2 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -16,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: DirectX11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX11: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-01-06: DirectX11: Expose VertexConstantBuffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handler. // 2024-10-07: DirectX11: Changed default texture sampler to Clamp instead of Repeat/Wrap. @@ -51,6 +53,12 @@ #endif // DirectX11 data +struct ImGui_ImplDX11_Texture +{ + ID3D11Texture2D* pTexture; + ID3D11ShaderResourceView* pTextureView; +}; + struct ImGui_ImplDX11_Data { ID3D11Device* pd3dDevice; @@ -63,7 +71,6 @@ struct ImGui_ImplDX11_Data ID3D11Buffer* pVertexConstantBuffer; ID3D11PixelShader* pPixelShader; ID3D11SamplerState* pFontSampler; - ID3D11ShaderResourceView* pFontTextureView; ID3D11RasterizerState* pRasterizerState; ID3D11BlendState* pBlendState; ID3D11DepthStencilState* pDepthStencilState; @@ -153,6 +160,13 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); ID3D11DeviceContext* device = bd->pd3dDeviceContext; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplDX11_UpdateTexture(tex); + // Create and grow vertex/index buffers if needed if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { @@ -320,21 +334,39 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release(); } -static void ImGui_ImplDX11_CreateFontsTexture() +static void ImGui_ImplDX11_DestroyTexture(ImTextureData* tex) { - // Build texture atlas - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData; + if (backend_tex == nullptr) + return; + IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID); + backend_tex->pTextureView->Release(); + backend_tex->pTexture->Release(); + IM_DELETE(backend_tex); - // Upload texture to graphics system + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + tex->BackendUserData = nullptr; +} + +void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex) +{ + ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); + if (tex->Status == ImTextureStatus_WantCreate) { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + unsigned int* pixels = (unsigned int*)tex->GetPixels(); + ImGui_ImplDX11_Texture* backend_tex = IM_NEW(ImGui_ImplDX11_Texture)(); + + // Create texture D3D11_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); - desc.Width = width; - desc.Height = height; + desc.Width = (UINT)tex->Width; + desc.Height = (UINT)tex->Height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; @@ -342,14 +374,12 @@ static void ImGui_ImplDX11_CreateFontsTexture() desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; - - ID3D11Texture2D* pTexture = nullptr; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; - bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); - IM_ASSERT(pTexture != nullptr); + bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &backend_tex->pTexture); + IM_ASSERT(backend_tex->pTexture != nullptr && "Backend failed to create texture!"); // Create texture view D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; @@ -358,23 +388,29 @@ static void ImGui_ImplDX11_CreateFontsTexture() srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; - bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &bd->pFontTextureView); - pTexture->Release(); + bd->pd3dDevice->CreateShaderResourceView(backend_tex->pTexture, &srvDesc, &backend_tex->pTextureView); + IM_ASSERT(backend_tex->pTextureView != nullptr && "Backend failed to create texture!"); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)backend_tex->pTextureView); + tex->SetStatus(ImTextureStatus_OK); + tex->BackendUserData = backend_tex; } - - // Store our identifier - io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView); -} - -static void ImGui_ImplDX11_DestroyFontsTexture() -{ - ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); - if (bd->pFontTextureView) + else if (tex->Status == ImTextureStatus_WantUpdates) { - bd->pFontTextureView->Release(); - bd->pFontTextureView = nullptr; - ImGui::GetIO().Fonts->SetTexID(0); // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well. + // 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. + ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData; + IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID); + for (ImTextureRect& r : tex->Updates) + { + D3D11_BOX box = { (UINT)r.x, (UINT)r.y, (UINT)0, (UINT)(r.x + r.w), (UINT)(r.y + r .h), (UINT)1 }; + bd->pd3dDeviceContext->UpdateSubresource(backend_tex->pTexture, 0, &box, tex->GetPixelsAt(r.x, r.y), (UINT)tex->GetPitch(), 0); + } + tex->SetStatus(ImTextureStatus_OK); } + if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + ImGui_ImplDX11_DestroyTexture(tex); } bool ImGui_ImplDX11_CreateDeviceObjects() @@ -382,8 +418,7 @@ bool ImGui_ImplDX11_CreateDeviceObjects() ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); if (!bd->pd3dDevice) return false; - if (bd->pFontSampler) - ImGui_ImplDX11_InvalidateDeviceObjects(); + ImGui_ImplDX11_InvalidateDeviceObjects(); // By using D3DCompile() from / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) // If you would like to use this DX11 sample code but remove this dependency you can: @@ -542,8 +577,6 @@ bool ImGui_ImplDX11_CreateDeviceObjects() bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler); } - ImGui_ImplDX11_CreateFontsTexture(); - return true; } @@ -553,7 +586,10 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() if (!bd->pd3dDevice) return; - ImGui_ImplDX11_DestroyFontsTexture(); + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplDX11_DestroyTexture(tex); if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } @@ -578,6 +614,10 @@ bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_co io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx11"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; // Get factory from device IDXGIDevice* pDXGIDevice = nullptr; @@ -612,7 +652,7 @@ void ImGui_ImplDX11_Shutdown() if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); } io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } @@ -621,7 +661,7 @@ void ImGui_ImplDX11_NewFrame() ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX11_Init()?"); - if (!bd->pFontSampler) + if (!bd->pVertexShader) ImGui_ImplDX11_CreateDeviceObjects(); } diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h index 772c1b920..c120bf093 100644 --- a/backends/imgui_impl_dx11.h +++ b/backends/imgui_impl_dx11.h @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -33,6 +34,9 @@ IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex); + // [BETA] Selected render state data shared with callbacks. // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX11_RenderDrawData() call. // (Please open an issue if you feel you need access to more data) From 75efba7ec76729d34692187f97b7218c46d51a21 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Nov 2024 18:47:21 +0100 Subject: [PATCH 0895/2359] Backends: DirectX9: added ImGuiBackendFlags_RendererHasTextures support # Conflicts: # backends/imgui_impl_dx9.cpp --- backends/imgui_impl_dx9.cpp | 104 ++++++++++++++++++++++++++---------- backends/imgui_impl_dx9.h | 6 ++- 2 files changed, 81 insertions(+), 29 deletions(-) diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 2cc8681a6..2617988e7 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -16,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: DirectX9: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2024-10-07: DirectX9: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. @@ -50,7 +52,6 @@ struct ImGui_ImplDX9_Data LPDIRECT3DDEVICE9 pd3dDevice; LPDIRECT3DVERTEXBUFFER9 pVB; LPDIRECT3DINDEXBUFFER9 pIB; - LPDIRECT3DTEXTURE9 FontTexture; int VertexBufferSize; int IndexBufferSize; bool HasRgbaSupport; @@ -163,6 +164,13 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); LPDIRECT3DDEVICE9 device = bd->pd3dDevice; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplDX9_UpdateTexture(tex); + // Create and grow buffers if needed if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { @@ -322,6 +330,10 @@ bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx9"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = 4096; bd->pd3dDevice = device; bd->pd3dDevice->AddRef(); @@ -340,12 +352,12 @@ void ImGui_ImplDX9_Shutdown() if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices) -static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, ImU32* src, int src_pitch, ImU32* dst, int dst_pitch, int w, int h) +static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, const ImU32* src, int src_pitch, ImU32* dst, int dst_pitch, int w, int h) { #ifndef IMGUI_USE_BGRA_PACKED_COLOR ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); @@ -366,28 +378,61 @@ static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, ImU32* src, int } } -static bool ImGui_ImplDX9_CreateFontsTexture() +void ImGui_ImplDX9_UpdateTexture(ImTextureData* tex) { - // Build texture atlas - ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); - unsigned char* pixels; - int width, height, bytes_per_pixel; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel); - // Upload texture to graphics system - bd->FontTexture = nullptr; - if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, bd->HasRgbaSupport ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0) - return false; - D3DLOCKED_RECT tex_locked_rect; - if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK) - return false; - ImGui_ImplDX9_CopyTextureRegion(io.Fonts->TexPixelsUseColors, (ImU32*)pixels, width * bytes_per_pixel, (ImU32*)tex_locked_rect.pBits, (int)tex_locked_rect.Pitch, width, height); - bd->FontTexture->UnlockRect(0); + if (tex->Status == ImTextureStatus_WantCreate) + { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + LPDIRECT3DTEXTURE9 dx_tex = nullptr; + HRESULT hr = bd->pd3dDevice->CreateTexture(tex->Width, tex->Height, 1, D3DUSAGE_DYNAMIC, bd->HasRgbaSupport ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &dx_tex, nullptr); + if (hr < 0) + { + IM_ASSERT(hr >= 0 && "Backend failed to create texture!"); + return; + } - // Store our identifier - io.Fonts->SetTexID((ImTextureID)bd->FontTexture); - return true; + D3DLOCKED_RECT locked_rect; + if (dx_tex->LockRect(0, &locked_rect, nullptr, 0) == D3D_OK) + { + ImGui_ImplDX9_CopyTextureRegion(tex->UseColors, (ImU32*)tex->GetPixels(), tex->Width * 4, (ImU32*)locked_rect.pBits, (ImU32)locked_rect.Pitch, tex->Width, tex->Height); + dx_tex->UnlockRect(0); + } + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)dx_tex); + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // 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. + LPDIRECT3DTEXTURE9 backend_tex = (LPDIRECT3DTEXTURE9)(intptr_t)tex->TexID; + RECT update_rect = { (LONG)tex->UpdateRect.x, (LONG)tex->UpdateRect.y, (LONG)(tex->UpdateRect.x + tex->UpdateRect.w), (LONG)(tex->UpdateRect.y + tex->UpdateRect.h) }; + D3DLOCKED_RECT locked_rect; + if (backend_tex->LockRect(0, &locked_rect, &update_rect, 0) == D3D_OK) + for (ImTextureRect& r : tex->Updates) + ImGui_ImplDX9_CopyTextureRegion(tex->UseColors, (ImU32*)tex->GetPixelsAt(r.x, r.y), tex->Width * 4, + (ImU32*)locked_rect.pBits + (r.x - update_rect.left) + (r.y - update_rect.top) * (locked_rect.Pitch / 4), (int)locked_rect.Pitch, r.w, r.h); + backend_tex->UnlockRect(0); + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantDestroy) + { + LPDIRECT3DTEXTURE9 backend_tex = (LPDIRECT3DTEXTURE9)tex->TexID; + if (backend_tex == nullptr) + return; + IM_ASSERT(tex->TexID == (ImTextureID)(intptr_t)backend_tex); + backend_tex->Release(); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + } } bool ImGui_ImplDX9_CreateDeviceObjects() @@ -395,8 +440,6 @@ bool ImGui_ImplDX9_CreateDeviceObjects() ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); if (!bd || !bd->pd3dDevice) return false; - if (!ImGui_ImplDX9_CreateFontsTexture()) - return false; return true; } @@ -405,18 +448,23 @@ void ImGui_ImplDX9_InvalidateDeviceObjects() ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); if (!bd || !bd->pd3dDevice) return; + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + { + tex->SetStatus(ImTextureStatus_WantDestroy); + ImGui_ImplDX9_UpdateTexture(tex); + } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } - if (bd->FontTexture) { bd->FontTexture->Release(); bd->FontTexture = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. } void ImGui_ImplDX9_NewFrame() { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX9_Init()?"); - - if (!bd->FontTexture) - ImGui_ImplDX9_CreateDeviceObjects(); + IM_UNUSED(bd); } //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_dx9.h b/backends/imgui_impl_dx9.h index b693054d9..600f0a750 100644 --- a/backends/imgui_impl_dx9.h +++ b/backends/imgui_impl_dx9.h @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -30,4 +31,7 @@ IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplDX9_UpdateTexture(ImTextureData* tex); + #endif // #ifndef IMGUI_DISABLE From 2d2b1bc1cc17f86c7a2253fcce4ceef41c238d96 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Dec 2024 13:05:27 +0100 Subject: [PATCH 0896/2359] Backends: DirectX10: added ImGuiBackendFlags_RendererHasTextures support. # Conflicts: # backends/imgui_impl_dx10.cpp # backends/imgui_impl_dx10.h --- backends/imgui_impl_dx10.cpp | 112 ++++++++++++++++++++++++----------- backends/imgui_impl_dx10.h | 6 +- 2 files changed, 81 insertions(+), 37 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index dd06e0e7f..4dc5f884e 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -15,6 +16,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: DirectX10: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX10: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-01-06: DirectX10: Expose selected render state in ImGui_ImplDX10_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap. @@ -49,6 +51,12 @@ #endif // DirectX10 data +struct ImGui_ImplDX10_Texture +{ + ID3D10Texture2D* pTexture; + ID3D10ShaderResourceView* pTextureView; +}; + struct ImGui_ImplDX10_Data { ID3D10Device* pd3dDevice; @@ -60,7 +68,6 @@ struct ImGui_ImplDX10_Data ID3D10Buffer* pVertexConstantBuffer; ID3D10PixelShader* pPixelShader; ID3D10SamplerState* pFontSampler; - ID3D10ShaderResourceView* pFontTextureView; ID3D10RasterizerState* pRasterizerState; ID3D10BlendState* pBlendState; ID3D10DepthStencilState* pDepthStencilState; @@ -147,6 +154,13 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); ID3D10Device* device = bd->pd3dDevice; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplDX10_UpdateTexture(tex); + // Create and grow vertex/index buffers if needed if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { @@ -304,21 +318,39 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release(); } -static void ImGui_ImplDX10_CreateFontsTexture() +static void ImGui_ImplDX10_DestroyTexture(ImTextureData* tex) { - // Build texture atlas - ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); - ImGuiIO& io = ImGui::GetIO(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + ImGui_ImplDX10_Texture* backend_tex = (ImGui_ImplDX10_Texture*)tex->BackendUserData; + if (backend_tex == nullptr) + return; + IM_ASSERT(backend_tex->pTextureView == (ID3D10ShaderResourceView*)(intptr_t)tex->TexID); + backend_tex->pTexture->Release(); + backend_tex->pTextureView->Release(); + IM_DELETE(backend_tex); - // Upload texture to graphics system + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + tex->BackendUserData = nullptr; +} + +void ImGui_ImplDX10_UpdateTexture(ImTextureData* tex) +{ + ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); + if (tex->Status == ImTextureStatus_WantCreate) { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + unsigned int* pixels = (unsigned int*)tex->GetPixels(); + ImGui_ImplDX10_Texture* backend_tex = IM_NEW(ImGui_ImplDX10_Texture)(); + + // Create texture D3D10_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); - desc.Width = width; - desc.Height = height; + desc.Width = (UINT)tex->Width; + desc.Height = (UINT)tex->Height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; @@ -327,13 +359,12 @@ static void ImGui_ImplDX10_CreateFontsTexture() desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; - ID3D10Texture2D* pTexture = nullptr; D3D10_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; - bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); - IM_ASSERT(pTexture != nullptr); + bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &backend_tex->pTexture); + IM_ASSERT(backend_tex->pTexture != nullptr && "Backend failed to create texture!"); // Create texture view D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc; @@ -342,23 +373,29 @@ static void ImGui_ImplDX10_CreateFontsTexture() srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; srv_desc.Texture2D.MipLevels = desc.MipLevels; srv_desc.Texture2D.MostDetailedMip = 0; - bd->pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &bd->pFontTextureView); - pTexture->Release(); + bd->pd3dDevice->CreateShaderResourceView(backend_tex->pTexture, &srv_desc, &backend_tex->pTextureView); + IM_ASSERT(backend_tex->pTextureView != nullptr && "Backend failed to create texture!"); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)backend_tex->pTextureView); + tex->SetStatus(ImTextureStatus_OK); + tex->BackendUserData = backend_tex; } - - // Store our identifier - io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView); -} - -static void ImGui_ImplDX10_DestroyFontsTexture() -{ - ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); - if (bd->pFontTextureView) + else if (tex->Status == ImTextureStatus_WantUpdates) { - bd->pFontTextureView->Release(); - bd->pFontTextureView = nullptr; - ImGui::GetIO().Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. + // 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. + ImGui_ImplDX10_Texture* backend_tex = (ImGui_ImplDX10_Texture*)tex->BackendUserData; + IM_ASSERT(backend_tex->pTextureView == (ID3D10ShaderResourceView*)(intptr_t)tex->TexID); + for (ImTextureRect& r : tex->Updates) + { + D3D10_BOX box = { (UINT)r.x, (UINT)r.y, (UINT)0, (UINT)(r.x + r.w), (UINT)(r.y + r.h), (UINT)1 }; + bd->pd3dDevice->UpdateSubresource(backend_tex->pTexture, 0, &box, tex->GetPixelsAt(r.x, r.y), (UINT)tex->GetPitch(), 0); + } + tex->SetStatus(ImTextureStatus_OK); } + if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + ImGui_ImplDX10_DestroyTexture(tex); } bool ImGui_ImplDX10_CreateDeviceObjects() @@ -366,8 +403,7 @@ bool ImGui_ImplDX10_CreateDeviceObjects() ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); if (!bd->pd3dDevice) return false; - if (bd->pFontSampler) - ImGui_ImplDX10_InvalidateDeviceObjects(); + ImGui_ImplDX10_InvalidateDeviceObjects(); // By using D3DCompile() from / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) // If you would like to use this DX10 sample code but remove this dependency you can: @@ -526,8 +562,6 @@ bool ImGui_ImplDX10_CreateDeviceObjects() bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler); } - ImGui_ImplDX10_CreateFontsTexture(); - return true; } @@ -537,8 +571,10 @@ void ImGui_ImplDX10_InvalidateDeviceObjects() if (!bd->pd3dDevice) return; - ImGui_ImplDX10_DestroyFontsTexture(); - + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplDX10_DestroyTexture(tex); if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } @@ -562,6 +598,10 @@ bool ImGui_ImplDX10_Init(ID3D10Device* device) io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx10"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; // Get factory from device IDXGIDevice* pDXGIDevice = nullptr; @@ -592,7 +632,7 @@ void ImGui_ImplDX10_Shutdown() if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h index d9f29987d..38ecbdfe3 100644 --- a/backends/imgui_impl_dx10.h +++ b/backends/imgui_impl_dx10.h @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -31,6 +32,9 @@ IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplDX10_UpdateTexture(ImTextureData* tex); + // [BETA] Selected render state data shared with callbacks. // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX10_RenderDrawData() call. // (Please open an issue if you feel you need access to more data) From eefe5d5aac1a9040020855c3bb918fe469cf4a38 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Nov 2024 18:46:09 +0100 Subject: [PATCH 0897/2359] Backends: DirectX12: added ImGuiBackendFlags_RendererHasTextures support. # Conflicts: # backends/imgui_impl_dx12.cpp --- backends/imgui_impl_dx12.cpp | 233 ++++++++++++++++++++++++----------- backends/imgui_impl_dx12.h | 6 +- 2 files changed, 165 insertions(+), 74 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index a373e8eec..ea7e3b881 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification. @@ -19,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX12: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-02-24: DirectX12: Fixed an issue where ImGui_ImplDX12_Init() signature change from 2024-11-15 combined with change from 2025-01-15 made legacy ImGui_ImplDX12_Init() crash. (#8429) // 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own. @@ -184,6 +186,13 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplDX12_UpdateTexture(tex); + // FIXME: We are assuming that this only gets called once per frame! ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); bd->frameIndex = bd->frameIndex + 1; @@ -316,18 +325,39 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL platform_io.Renderer_RenderState = nullptr; } -static void ImGui_ImplDX12_CreateFontsTexture() +static void ImGui_ImplDX12_DestroyTexture(ImTextureData* tex) { - // Build texture atlas - ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData; + if (backend_tex == nullptr) + return; + IM_ASSERT(backend_tex->hFontSrvGpuDescHandle.ptr == (UINT64)tex->TexID); ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, backend_tex->hFontSrvCpuDescHandle, backend_tex->hFontSrvGpuDescHandle); + SafeRelease(backend_tex->pTextureResource); + backend_tex->hFontSrvCpuDescHandle.ptr = 0; + backend_tex->hFontSrvGpuDescHandle.ptr = 0; + IM_DELETE(backend_tex); - // Upload texture to graphics system - ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture; + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + tex->BackendUserData = nullptr; +} + +void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) +{ + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + bool need_barrier_before_copy = true; // Do we need a resource barrier before we copy new data in? + + if (tex->Status == ImTextureStatus_WantCreate) { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + ImGui_ImplDX12_Texture* backend_tex = IM_NEW(ImGui_ImplDX12_Texture)(); + bd->InitInfo.SrvDescriptorAllocFn(&bd->InitInfo, &backend_tex->hFontSrvCpuDescHandle, &backend_tex->hFontSrvGpuDescHandle); // Allocate a desctriptor handle + D3D12_HEAP_PROPERTIES props = {}; props.Type = D3D12_HEAP_TYPE_DEFAULT; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; @@ -337,8 +367,8 @@ static void ImGui_ImplDX12_CreateFontsTexture() ZeroMemory(&desc, sizeof(desc)); desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; desc.Alignment = 0; - desc.Width = width; - desc.Height = height; + desc.Width = tex->Width; + desc.Height = tex->Height; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; @@ -351,8 +381,47 @@ static void ImGui_ImplDX12_CreateFontsTexture() bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture)); - UINT upload_pitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); - UINT upload_size = height * upload_pitch; + // Create SRV + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc; + ZeroMemory(&srvDesc, sizeof(srvDesc)); + srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srvDesc.Texture2D.MipLevels = desc.MipLevels; + srvDesc.Texture2D.MostDetailedMip = 0; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, backend_tex->hFontSrvCpuDescHandle); + SafeRelease(backend_tex->pTextureResource); + backend_tex->pTextureResource = pTexture; + + // Store identifiers + tex->SetTexID((ImTextureID)backend_tex->hFontSrvGpuDescHandle.ptr); + tex->BackendUserData = backend_tex; + need_barrier_before_copy = false; // Because this is a newly-created texture it will be in D3D12_RESOURCE_STATE_COMMON and thus we don't need a barrier + // We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below. + } + + if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates) + { + ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData; + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + + // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture. + // FIXME-OPT: Uploading single box even when using ImTextureStatus_WantUpdates. Could use tex->Updates[] + // - Copy all blocks contiguously in upload buffer. + // - Barrier before copy, submit all CopyTextureRegion(), barrier after copy. + const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x; + const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y; + const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w; + const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h; + + // Update full texture or selected blocks. We only ever write to textures regions which have never been used before! + // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions. + UINT upload_pitch_src = upload_w * tex->BytesPerPixel; + UINT upload_pitch_dst = (upload_pitch_src + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); + UINT upload_size = upload_pitch_dst * upload_h; + + D3D12_RESOURCE_DESC desc; + ZeroMemory(&desc, sizeof(desc)); desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Alignment = 0; desc.Width = upload_size; @@ -365,47 +434,19 @@ static void ImGui_ImplDX12_CreateFontsTexture() desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; + D3D12_HEAP_PROPERTIES props; + memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + // FIXME-OPT: Can upload buffer be reused? ID3D12Resource* uploadBuffer = nullptr; HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer)); IM_ASSERT(SUCCEEDED(hr)); - void* mapped = nullptr; - D3D12_RANGE range = { 0, upload_size }; - hr = uploadBuffer->Map(0, &range, &mapped); - IM_ASSERT(SUCCEEDED(hr)); - for (int y = 0; y < height; y++) - memcpy((void*) ((uintptr_t) mapped + y * upload_pitch), pixels + y * width * 4, width * 4); - uploadBuffer->Unmap(0, &range); - - D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; - D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; - { - srcLocation.pResource = uploadBuffer; - srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - srcLocation.PlacedFootprint.Footprint.Width = width; - srcLocation.PlacedFootprint.Footprint.Height = height; - srcLocation.PlacedFootprint.Footprint.Depth = 1; - srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch; - - dstLocation.pResource = pTexture; - dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - dstLocation.SubresourceIndex = 0; - } - - D3D12_RESOURCE_BARRIER barrier = {}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barrier.Transition.pResource = pTexture; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - + // Create temporary command list and execute immediately ID3D12Fence* fence = nullptr; hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); IM_ASSERT(SUCCEEDED(hr)); @@ -413,16 +454,63 @@ static void ImGui_ImplDX12_CreateFontsTexture() HANDLE event = ::CreateEvent(0, 0, 0, 0); IM_ASSERT(event != nullptr); + // FIXME-OPT: Create once and reuse? ID3D12CommandAllocator* cmdAlloc = nullptr; hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); IM_ASSERT(SUCCEEDED(hr)); + // FIXME-OPT: Can be use the one from user? (pass ID3D12GraphicsCommandList* to ImGui_ImplDX12_UpdateTextures) ID3D12GraphicsCommandList* cmdList = nullptr; hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList)); IM_ASSERT(SUCCEEDED(hr)); - cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr); - cmdList->ResourceBarrier(1, &barrier); + // Copy to upload buffer + void* mapped = nullptr; + D3D12_RANGE range = { 0, upload_size }; + hr = uploadBuffer->Map(0, &range, &mapped); + IM_ASSERT(SUCCEEDED(hr)); + for (int y = 0; y < upload_h; y++) + memcpy((void*)((uintptr_t)mapped + y * upload_pitch_dst), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch_src); + uploadBuffer->Unmap(0, &range); + + if (need_barrier_before_copy) + { + D3D12_RESOURCE_BARRIER barrier = {}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.Transition.pResource = backend_tex->pTextureResource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + cmdList->ResourceBarrier(1, &barrier); + } + + D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; + D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; + { + srcLocation.pResource = uploadBuffer; + srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srcLocation.PlacedFootprint.Footprint.Width = upload_w; + srcLocation.PlacedFootprint.Footprint.Height = upload_h; + srcLocation.PlacedFootprint.Footprint.Depth = 1; + srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch_dst; + dstLocation.pResource = backend_tex->pTextureResource; + dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dstLocation.SubresourceIndex = 0; + } + cmdList->CopyTextureRegion(&dstLocation, upload_x, upload_y, 0, &srcLocation, nullptr); + + { + D3D12_RESOURCE_BARRIER barrier = {}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.Transition.pResource = backend_tex->pTextureResource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + cmdList->ResourceBarrier(1, &barrier); + } hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); @@ -432,6 +520,10 @@ static void ImGui_ImplDX12_CreateFontsTexture() hr = cmdQueue->Signal(fence, 1); IM_ASSERT(SUCCEEDED(hr)); + // FIXME-OPT: Suboptimal? + // - To remove this may need to create NumFramesInFlight x ImGui_ImplDX12_FrameContext in backend data (mimick docking version) + // - Store per-frame in flight: upload buffer? + // - Where do cmdList and cmdAlloc fit? fence->SetEventOnCompletion(1, event); ::WaitForSingleObject(event, INFINITE); @@ -440,22 +532,11 @@ static void ImGui_ImplDX12_CreateFontsTexture() ::CloseHandle(event); fence->Release(); uploadBuffer->Release(); - - // Create texture view - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc; - ZeroMemory(&srvDesc, sizeof(srvDesc)); - srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - srvDesc.Texture2D.MipLevels = desc.MipLevels; - srvDesc.Texture2D.MostDetailedMip = 0; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, font_tex->hFontSrvCpuDescHandle); - SafeRelease(font_tex->pTextureResource); - font_tex->pTextureResource = pTexture; + tex->SetStatus(ImTextureStatus_OK); } - // Store our identifier - io.Fonts->SetTexID((ImTextureID)font_tex->hFontSrvGpuDescHandle.ptr); + if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames >= (int)bd->numFramesInFlight) + ImGui_ImplDX12_DestroyTexture(tex); } bool ImGui_ImplDX12_CreateDeviceObjects() @@ -687,8 +768,6 @@ bool ImGui_ImplDX12_CreateDeviceObjects() if (result_pipeline_state != S_OK) return false; - ImGui_ImplDX12_CreateFontsTexture(); - return true; } @@ -704,12 +783,10 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() SafeRelease(bd->pRootSignature); SafeRelease(bd->pPipelineState); - // Free SRV descriptor used by texture - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture; - bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, font_tex->hFontSrvCpuDescHandle, font_tex->hFontSrvGpuDescHandle); - SafeRelease(font_tex->pTextureResource); - io.Fonts->SetTexID(0); // We copied bd->hFontSrvGpuDescHandle to io.Fonts->TexID so let's clear that as well. + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplDX12_DestroyTexture(tex); for (UINT i = 0; i < bd->numFramesInFlight; i++) { @@ -741,6 +818,16 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx12"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + ImGui_ImplDX12_InitPlatformInterface(); + + // Create a dummy ImGui_ImplDX12_ViewportData holder for the main viewport, + // Since this is created and managed by the application, we will only use the ->Resources[] fields. + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->RendererUserData = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight); +>>>>>>> dda12fbd9a (Backends: DirectX12: added ImGuiBackendFlags_RendererHasTextures support.) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (init_info->SrvDescriptorAllocFn == nullptr) @@ -763,10 +850,7 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) }; } #endif - - // Allocate 1 SRV descriptor for the font texture IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr); - init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->FontTexture.hFontSrvCpuDescHandle, &bd->FontTexture.hFontSrvGpuDescHandle); // Create buffers with a default size (they will later be grown as needed) bd->frameIndex = UINT_MAX; @@ -806,6 +890,9 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO bool ret = ImGui_ImplDX12_Init(&init_info); ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); bd->commandQueueOwned = true; + ImGuiIO& io = ImGui::GetIO(); + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasTextures; // Using legacy ImGui_ImplDX12_Init() call with 1 SRV descriptor we cannot support multiple textures. + return ret; } #endif @@ -822,7 +909,7 @@ void ImGui_ImplDX12_Shutdown() io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index a79de7b13..4ff510455 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification. @@ -63,6 +64,9 @@ IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex); + // [BETA] Selected render state data shared with callbacks. // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX12_RenderDrawData() call. // (Please open an issue if you feel you need access to more data) From dbb91a574f35e24697754f6344455fd43b97d46d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Nov 2024 18:47:14 +0100 Subject: [PATCH 0898/2359] Backends: OpenGL3: added ImGuiBackendFlags_RendererHasTextures support. + Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture(). --- backends/imgui_impl_opengl3.cpp | 137 ++++++++++++++++++--------- backends/imgui_impl_opengl3.h | 8 +- backends/imgui_impl_opengl3_loader.h | 8 +- 3 files changed, 104 insertions(+), 49 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 8b7a2ecb5..3f6c08756 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -4,8 +4,9 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!] +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // About WebGL/ES: // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. @@ -22,6 +23,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture(). // 2025-06-04: OpenGL: Made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664) // 2025-02-18: OpenGL: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap. @@ -231,7 +233,7 @@ struct ImGui_ImplOpenGL3_Data bool GlProfileIsES3; bool GlProfileIsCompat; GLint GlProfileMask; - GLuint FontTexture; + GLint MaxTextureSize; GLuint ShaderHandle; GLint AttribLocationTex; // Uniforms location GLint AttribLocationProjMtx; @@ -244,6 +246,7 @@ struct ImGui_ImplOpenGL3_Data bool HasPolygonMode; bool HasClipOrigin; bool UseBufferSubData; + ImVector TempBuffer; ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); } }; @@ -326,6 +329,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) if (major == 0 && minor == 0) sscanf(gl_version_str, "%d.%d", &major, &minor); // Query GL_VERSION in desktop GL 2.x, the string will start with "." bd->GlVersion = (GLuint)(major * 100 + minor * 10); + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &bd->MaxTextureSize); #if defined(IMGUI_IMPL_OPENGL_ES3) bd->GlProfileIsES3 = true; @@ -359,6 +363,10 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) if (bd->GlVersion >= 320) io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. #endif + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = (int)bd->MaxTextureSize; // Store GLSL version string so we can refer to it later in case we recreate shaders. // Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure. @@ -411,7 +419,7 @@ void ImGui_ImplOpenGL3_Shutdown() ImGui_ImplOpenGL3_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } @@ -424,8 +432,6 @@ void ImGui_ImplOpenGL3_NewFrame() if (!bd->ShaderHandle) ImGui_ImplOpenGL3_CreateDeviceObjects(); - if (!bd->FontTexture) - ImGui_ImplOpenGL3_CreateFontsTexture(); } static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object) @@ -517,6 +523,13 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplOpenGL3_UpdateTexture(tex); + // Backup GL state GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); glActiveTexture(GL_TEXTURE0); @@ -685,50 +698,82 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) (void)bd; // Not all compilation paths use this } -bool ImGui_ImplOpenGL3_CreateFontsTexture() +static void ImGui_ImplOpenGL3_DestroyTexture(ImTextureData* tex) { - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; + glDeleteTextures(1, &gl_tex_id); - // Build texture atlas - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. - - // Upload texture to graphics system - // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - GLint last_texture; - GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); - GL_CALL(glGenTextures(1, &bd->FontTexture)); - GL_CALL(glBindTexture(GL_TEXTURE_2D, bd->FontTexture)); - GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); - GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); - GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); - GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); -#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES - GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); -#endif - GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); - - // Store identifier - io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); - - // Restore state - GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); - - return true; + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); } -void ImGui_ImplOpenGL3_DestroyFontsTexture() +void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex) { - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); - if (bd->FontTexture) + if (tex->Status == ImTextureStatus_WantCreate) { - glDeleteTextures(1, &bd->FontTexture); - io.Fonts->SetTexID(0); - bd->FontTexture = 0; + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + const void* pixels = tex->GetPixels(); + GLuint gl_texture_id = 0; + + // Upload texture to graphics system + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + GLint last_texture; + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + GL_CALL(glGenTextures(1, &gl_texture_id)); + GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_texture_id)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); +#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); +#endif + GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->Width, tex->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)gl_texture_id); + tex->SetStatus(ImTextureStatus_OK); + + // Restore state + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // 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. + GLint last_texture; + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + + GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; + GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_tex_id)); +#if 0// GL_UNPACK_ROW_LENGTH // Not on WebGL/ES + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->Width)); + for (ImTextureRect& r : tex->Updates) + GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, tex->GetPixelsAt(r.x, r.y))); + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); +#else + // GL ES doesn't have GL_UNPACK_ROW_LENGTH, so we need to (A) copy to a contiguous buffer or (B) upload line by line. + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + for (ImTextureRect& r : tex->Updates) + { + const int src_pitch = r.w * tex->BytesPerPixel; + bd->TempBuffer.resize(r.h * src_pitch); + char* out_p = bd->TempBuffer.Data; + for (int y = 0; y < r.h; y++, out_p += src_pitch) + memcpy(out_p, tex->GetPixelsAt(r.x, r.y + y), src_pitch); + IM_ASSERT(out_p == bd->TempBuffer.end()); + GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, bd->TempBuffer.Data)); + } +#endif + tex->SetStatus(ImTextureStatus_OK); + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); // Restore state + } + else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + ImGui_ImplOpenGL3_DestroyTexture(tex); } // If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file. @@ -951,8 +996,6 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() glGenBuffers(1, &bd->VboHandle); glGenBuffers(1, &bd->ElementsHandle); - ImGui_ImplOpenGL3_CreateFontsTexture(); - // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); @@ -972,7 +1015,11 @@ void ImGui_ImplOpenGL3_DestroyDeviceObjects() if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; } if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; } if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; } - ImGui_ImplOpenGL3_DestroyFontsTexture(); + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplOpenGL3_DestroyTexture(tex); } //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h index 5de51cfdd..b72b5c887 100644 --- a/backends/imgui_impl_opengl3.h +++ b/backends/imgui_impl_opengl3.h @@ -4,8 +4,9 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!] +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // About WebGL/ES: // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. @@ -36,11 +37,12 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); // (Optional) Called by Init/NewFrame/Shutdown -IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex); + // Configuration flags to add in your imconfig file: //#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten) //#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android) diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index d6ffa5a2d..4ca053603 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -167,6 +167,7 @@ typedef khronos_uint8_t GLubyte; #define GL_SCISSOR_TEST 0x0C11 #define GL_UNPACK_ROW_LENGTH 0x0CF2 #define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_TEXTURE_SIZE 0x0D33 #define GL_TEXTURE_2D 0x0DE1 #define GL_UNSIGNED_BYTE 0x1401 #define GL_UNSIGNED_SHORT 0x1403 @@ -224,11 +225,13 @@ typedef khronos_float_t GLclampf; typedef double GLclampd; #define GL_TEXTURE_BINDING_2D 0x8069 typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture); typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures); typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices); +GLAPI void APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture); GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures); GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures); @@ -478,7 +481,7 @@ GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc); /* gl3w internal state */ union ImGL3WProcs { - GL3WglProc ptr[59]; + GL3WglProc ptr[60]; struct { PFNGLACTIVETEXTUREPROC ActiveTexture; PFNGLATTACHSHADERPROC AttachShader; @@ -534,6 +537,7 @@ union ImGL3WProcs { PFNGLSHADERSOURCEPROC ShaderSource; PFNGLTEXIMAGE2DPROC TexImage2D; PFNGLTEXPARAMETERIPROC TexParameteri; + PFNGLTEXSUBIMAGE2DPROC TexSubImage2D; PFNGLUNIFORM1IPROC Uniform1i; PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv; PFNGLUSEPROGRAMPROC UseProgram; @@ -599,6 +603,7 @@ GL3W_API extern union ImGL3WProcs imgl3wProcs; #define glShaderSource imgl3wProcs.gl.ShaderSource #define glTexImage2D imgl3wProcs.gl.TexImage2D #define glTexParameteri imgl3wProcs.gl.TexParameteri +#define glTexSubImage2D imgl3wProcs.gl.TexSubImage2D #define glUniform1i imgl3wProcs.gl.Uniform1i #define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv #define glUseProgram imgl3wProcs.gl.UseProgram @@ -894,6 +899,7 @@ static const char *proc_names[] = { "glShaderSource", "glTexImage2D", "glTexParameteri", + "glTexSubImage2D", "glUniform1i", "glUniformMatrix4fv", "glUseProgram", From 0430c55b84edc8097be1064ad8aafb842c3774ae Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Dec 2024 14:05:55 +0100 Subject: [PATCH 0899/2359] Backends: OpenGL2: added ImGuiBackendFlags_RendererHasTextures support. Removed ImGui_ImplOpenGL2_CreateFontsTexture() and ImGui_ImplOpenGL2_DestroyFontsTexture(). --- backends/imgui_impl_opengl2.cpp | 121 +++++++++++++++++++------------- backends/imgui_impl_opengl2.h | 8 ++- 2 files changed, 78 insertions(+), 51 deletions(-) diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp index 2a255be4c..5e9df1715 100644 --- a/backends/imgui_impl_opengl2.cpp +++ b/backends/imgui_impl_opengl2.cpp @@ -2,7 +2,8 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // Missing features or Issues: // [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). @@ -24,6 +25,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL2_CreateFontsTexture() and ImGui_ImplOpenGL2_DestroyFontsTexture(). // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-06-28: OpenGL: ImGui_ImplOpenGL2_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL2_DestroyFontsTexture(). (#7748) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. @@ -81,8 +83,6 @@ // OpenGL data struct ImGui_ImplOpenGL2_Data { - GLuint FontTexture; - ImGui_ImplOpenGL2_Data() { memset((void*)this, 0, sizeof(*this)); } }; @@ -104,6 +104,7 @@ bool ImGui_ImplOpenGL2_Init() ImGui_ImplOpenGL2_Data* bd = IM_NEW(ImGui_ImplOpenGL2_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_opengl2"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. return true; } @@ -117,6 +118,7 @@ void ImGui_ImplOpenGL2_Shutdown() ImGui_ImplOpenGL2_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } @@ -124,11 +126,7 @@ void ImGui_ImplOpenGL2_NewFrame() { ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL2_Init()?"); - - if (!bd->FontTexture) - ImGui_ImplOpenGL2_CreateDeviceObjects(); - if (!bd->FontTexture) - ImGui_ImplOpenGL2_CreateFontsTexture(); + IM_UNUSED(bd); } static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height) @@ -186,6 +184,13 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) if (fb_width == 0 || fb_height == 0) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplOpenGL2_UpdateTexture(tex); + // Backup GL state GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); @@ -259,57 +264,77 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, last_tex_env_mode); } -bool ImGui_ImplOpenGL2_CreateFontsTexture() +void ImGui_ImplOpenGL2_UpdateTexture(ImTextureData* tex) { - // Build texture atlas - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. - - // Upload texture to graphics system - // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - GLint last_texture; - glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); - glGenTextures(1, &bd->FontTexture); - glBindTexture(GL_TEXTURE_2D, bd->FontTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - - // Store our identifier - io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); - - // Restore state - glBindTexture(GL_TEXTURE_2D, last_texture); - - return true; -} - -void ImGui_ImplOpenGL2_DestroyFontsTexture() -{ - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); - if (bd->FontTexture) + if (tex->Status == ImTextureStatus_WantCreate) { - glDeleteTextures(1, &bd->FontTexture); - io.Fonts->SetTexID(0); - bd->FontTexture = 0; + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + const void* pixels = tex->GetPixels(); + GLuint gl_texture_id = 0; + + // Upload texture to graphics system + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + GLint last_texture; + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + GL_CALL(glGenTextures(1, &gl_texture_id)); + GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_texture_id)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)); + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); + GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->Width, tex->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)gl_texture_id); + tex->SetStatus(ImTextureStatus_OK); + + // Restore state + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); + } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // 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. + GLint last_texture; + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + + GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; + GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_tex_id)); + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->Width)); + for (ImTextureRect& r : tex->Updates) + GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, tex->GetPixelsAt(r.x, r.y))); + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); // Restore state + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantDestroy) + { + GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; + glDeleteTextures(1, &gl_tex_id); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); } } bool ImGui_ImplOpenGL2_CreateDeviceObjects() { - return ImGui_ImplOpenGL2_CreateFontsTexture(); + return true; } void ImGui_ImplOpenGL2_DestroyDeviceObjects() { - ImGui_ImplOpenGL2_DestroyFontsTexture(); + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + { + tex->SetStatus(ImTextureStatus_WantDestroy); + ImGui_ImplOpenGL2_UpdateTexture(tex); + } } //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_opengl2.h b/backends/imgui_impl_opengl2.h index 5832a1765..014a03aca 100644 --- a/backends/imgui_impl_opengl2.h +++ b/backends/imgui_impl_opengl2.h @@ -2,7 +2,8 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // Missing features or Issues: // [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). @@ -33,9 +34,10 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL2_NewFrame(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data); // Called by Init/NewFrame/Shutdown -IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplOpenGL2_UpdateTexture(ImTextureData* tex); + #endif // #ifndef IMGUI_DISABLE From abe294bfd0bfff325bbaa000f2d688085f1d4696 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Nov 2024 18:47:28 +0100 Subject: [PATCH 0900/2359] Backends: Vulkan: added ImGuiBackendFlags_RendererHasTextures support. # Conflicts: # backends/imgui_impl_vulkan.cpp --- backends/imgui_impl_vulkan.cpp | 453 ++++++++++++++++++--------------- backends/imgui_impl_vulkan.h | 13 +- 2 files changed, 250 insertions(+), 216 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 10648c3a4..74c7d791b 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. +// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as texture identifier. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID/ImTextureRef + https://github.com/ocornut/imgui/pull/914 for discussions. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. @@ -26,7 +27,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-05-07- Vulkan: Fixed validation errors during window detach in multi-viewport mode. (#8600, #8176) +// 2025-06-11: Vulkan: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_DestroyFontsTexture(). +// 2025-05-07: Vulkan: Fixed validation errors during window detach in multi-viewport mode. (#8600, #8176) // 2025-05-07: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + try both non-KHR and KHR versions. (#8600, #8326, #8365) // 2025-04-07: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's pColorAttachmentFormats buffer when set, in order to reduce common user-error of specifying a pointer to data that gets out of scope. (#8282) // 2025-02-14: *BREAKING CHANGE*: Added uint32_t api_version to ImGui_ImplVulkan_LoadFunctions(). @@ -251,7 +253,6 @@ struct ImGui_ImplVulkan_Data VkDescriptorPool DescriptorPool; // Texture management - ImGui_ImplVulkan_Texture FontTexture; VkSampler TexSampler; VkCommandPool TexCommandPool; VkCommandBuffer TexCommandBuffer; @@ -502,6 +503,13 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm if (fb_width <= 0 || fb_height <= 0) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplVulkan_UpdateTexture(tex); + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; if (pipeline == VK_NULL_HANDLE) @@ -638,220 +646,222 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm vkCmdSetScissor(command_buffer, 0, 1, &scissor); } -bool ImGui_ImplVulkan_CreateFontsTexture() +static void ImGui_ImplVulkan_DestroyTexture(ImTextureData* tex) { - ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplVulkan_Texture* backend_tex = (ImGui_ImplVulkan_Texture*)tex->BackendUserData; + if (backend_tex == nullptr) + return; + IM_ASSERT(backend_tex->DescriptorSet == (VkDescriptorSet)tex->TexID); + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + ImGui_ImplVulkan_RemoveTexture(backend_tex->DescriptorSet); + vkDestroyImageView(v->Device, backend_tex->ImageView, v->Allocator); + vkDestroyImage(v->Device, backend_tex->Image, v->Allocator); + vkFreeMemory(v->Device, backend_tex->Memory, v->Allocator); + IM_DELETE(backend_tex); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + tex->BackendUserData = nullptr; +} + +void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) +{ + if (tex->Status == ImTextureStatus_OK) + return; ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; VkResult err; - // Destroy existing texture (if any) - if (bd->FontTexture.DescriptorSet) + if (tex->Status == ImTextureStatus_WantCreate) { - vkQueueWaitIdle(v->Queue); - ImGui_ImplVulkan_DestroyFontsTexture(); + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + ImGui_ImplVulkan_Texture* backend_tex = IM_NEW(ImGui_ImplVulkan_Texture)(); + + // Create the Image: + { + VkImageCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + info.imageType = VK_IMAGE_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.extent.width = tex->Width; + info.extent.height = tex->Height; + info.extent.depth = 1; + info.mipLevels = 1; + info.arrayLayers = 1; + info.samples = VK_SAMPLE_COUNT_1_BIT; + info.tiling = VK_IMAGE_TILING_OPTIMAL; + info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + err = vkCreateImage(v->Device, &info, v->Allocator, &backend_tex->Image); + check_vk_result(err); + VkMemoryRequirements req; + vkGetImageMemoryRequirements(v->Device, backend_tex->Image, &req); + VkMemoryAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); + alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &backend_tex->Memory); + check_vk_result(err); + err = vkBindImageMemory(v->Device, backend_tex->Image, backend_tex->Memory, 0); + check_vk_result(err); + } + + // Create the Image View: + { + VkImageViewCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + info.image = backend_tex->Image; + info.viewType = VK_IMAGE_VIEW_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + info.subresourceRange.levelCount = 1; + info.subresourceRange.layerCount = 1; + err = vkCreateImageView(v->Device, &info, v->Allocator, &backend_tex->ImageView); + check_vk_result(err); + } + + // Create the Descriptor Set + backend_tex->DescriptorSet = ImGui_ImplVulkan_AddTexture(bd->TexSampler, backend_tex->ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + + // Store identifiers + tex->SetTexID((ImTextureID)backend_tex->DescriptorSet); + tex->BackendUserData = backend_tex; } - // Create command pool/buffer - if (bd->TexCommandPool == VK_NULL_HANDLE) + if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates) { - VkCommandPoolCreateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; - info.flags = 0; - info.queueFamilyIndex = v->QueueFamily; - vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->TexCommandPool); - } - if (bd->TexCommandBuffer == VK_NULL_HANDLE) - { - VkCommandBufferAllocateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - info.commandPool = bd->TexCommandPool; - info.commandBufferCount = 1; - err = vkAllocateCommandBuffers(v->Device, &info, &bd->TexCommandBuffer); + ImGui_ImplVulkan_Texture* backend_tex = (ImGui_ImplVulkan_Texture*)tex->BackendUserData; + + // Update full texture or selected blocks. We only ever write to textures regions which have never been used before! + // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions. + // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture. + const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x; + const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y; + const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w; + const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h; + + // Create the Upload Buffer: + VkDeviceMemory upload_buffer_memory; + + VkBuffer upload_buffer; + VkDeviceSize upload_pitch = upload_w * tex->BytesPerPixel; + VkDeviceSize upload_size = upload_h * upload_pitch; + { + VkBufferCreateInfo buffer_info = {}; + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = upload_size; + buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &upload_buffer); + check_vk_result(err); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements(v->Device, upload_buffer, &req); + bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment; + VkMemoryAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); + alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &upload_buffer_memory); + check_vk_result(err); + err = vkBindBufferMemory(v->Device, upload_buffer, upload_buffer_memory, 0); + check_vk_result(err); + } + + // Upload to Buffer: + { + char* map = nullptr; + err = vkMapMemory(v->Device, upload_buffer_memory, 0, upload_size, 0, (void**)(&map)); + check_vk_result(err); + for (int y = 0; y < upload_h; y++) + memcpy(map + upload_pitch * y, tex->GetPixelsAt(upload_x, upload_y + y), (size_t)upload_pitch); + VkMappedMemoryRange range[1] = {}; + range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; + range[0].memory = upload_buffer_memory; + range[0].size = upload_size; + err = vkFlushMappedMemoryRanges(v->Device, 1, range); + check_vk_result(err); + vkUnmapMemory(v->Device, upload_buffer_memory); + } + + // Start command buffer + { + err = vkResetCommandPool(v->Device, bd->TexCommandPool, 0); + 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(bd->TexCommandBuffer, &begin_info); + check_vk_result(err); + } + + // Copy to Image: + { + VkImageMemoryBarrier copy_barrier[1] = {}; + copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + copy_barrier[0].image = backend_tex->Image; + copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_barrier[0].subresourceRange.levelCount = 1; + copy_barrier[0].subresourceRange.layerCount = 1; + vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); + + VkBufferImageCopy region = {}; + region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + region.imageSubresource.layerCount = 1; + region.imageExtent.width = upload_w; + region.imageExtent.height = upload_h; + region.imageExtent.depth = 1; + region.imageOffset.x = upload_x; + region.imageOffset.y = upload_y; + vkCmdCopyBufferToImage(bd->TexCommandBuffer, upload_buffer, backend_tex->Image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); + + VkImageMemoryBarrier use_barrier[1] = {}; + use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + use_barrier[0].image = backend_tex->Image; + use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + use_barrier[0].subresourceRange.levelCount = 1; + use_barrier[0].subresourceRange.layerCount = 1; + vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier); + } + + // End command buffer + { + VkSubmitInfo end_info = {}; + end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + end_info.commandBufferCount = 1; + end_info.pCommandBuffers = &bd->TexCommandBuffer; + err = vkEndCommandBuffer(bd->TexCommandBuffer); + check_vk_result(err); + err = vkQueueSubmit(v->Queue, 1, &end_info, VK_NULL_HANDLE); + check_vk_result(err); + } + + err = vkQueueWaitIdle(v->Queue); // FIXME-OPT: Suboptimal! check_vk_result(err); + vkDestroyBuffer(v->Device, upload_buffer, v->Allocator); + vkFreeMemory(v->Device, upload_buffer_memory, v->Allocator); + + tex->SetStatus(ImTextureStatus_OK); } - // Start command buffer - { - err = vkResetCommandPool(v->Device, bd->TexCommandPool, 0); - 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(bd->TexCommandBuffer, &begin_info); - check_vk_result(err); - } - - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - size_t upload_size = width * height * 4 * sizeof(char); - - // Create the Image: - ImGui_ImplVulkan_Texture* backend_tex = &bd->FontTexture; - { - VkImageCreateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - info.imageType = VK_IMAGE_TYPE_2D; - info.format = VK_FORMAT_R8G8B8A8_UNORM; - info.extent.width = width; - info.extent.height = height; - info.extent.depth = 1; - info.mipLevels = 1; - info.arrayLayers = 1; - info.samples = VK_SAMPLE_COUNT_1_BIT; - info.tiling = VK_IMAGE_TILING_OPTIMAL; - info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - err = vkCreateImage(v->Device, &info, v->Allocator, &backend_tex->Image); - check_vk_result(err); - VkMemoryRequirements req; - vkGetImageMemoryRequirements(v->Device, backend_tex->Image, &req); - VkMemoryAllocateInfo alloc_info = {}; - alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); - alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits); - err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &backend_tex->Memory); - check_vk_result(err); - err = vkBindImageMemory(v->Device, backend_tex->Image, backend_tex->Memory, 0); - check_vk_result(err); - } - - // Create the Image View: - { - VkImageViewCreateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - info.image = backend_tex->Image; - info.viewType = VK_IMAGE_VIEW_TYPE_2D; - info.format = VK_FORMAT_R8G8B8A8_UNORM; - info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - info.subresourceRange.levelCount = 1; - info.subresourceRange.layerCount = 1; - err = vkCreateImageView(v->Device, &info, v->Allocator, &backend_tex->ImageView); - check_vk_result(err); - } - - // Create the Descriptor Set: - backend_tex->DescriptorSet = ImGui_ImplVulkan_AddTexture(bd->TexSampler, backend_tex->ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - - // Create the Upload Buffer: - VkDeviceMemory upload_buffer_memory; - VkBuffer upload_buffer; - { - VkBufferCreateInfo buffer_info = {}; - buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - buffer_info.size = upload_size; - buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &upload_buffer); - check_vk_result(err); - VkMemoryRequirements req; - vkGetBufferMemoryRequirements(v->Device, upload_buffer, &req); - bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment; - VkMemoryAllocateInfo alloc_info = {}; - alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); - alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); - err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &upload_buffer_memory); - check_vk_result(err); - err = vkBindBufferMemory(v->Device, upload_buffer, upload_buffer_memory, 0); - check_vk_result(err); - } - - // Upload to Buffer: - { - char* map = nullptr; - err = vkMapMemory(v->Device, upload_buffer_memory, 0, upload_size, 0, (void**)(&map)); - check_vk_result(err); - memcpy(map, pixels, upload_size); - VkMappedMemoryRange range[1] = {}; - range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; - range[0].memory = upload_buffer_memory; - range[0].size = upload_size; - err = vkFlushMappedMemoryRanges(v->Device, 1, range); - check_vk_result(err); - vkUnmapMemory(v->Device, upload_buffer_memory); - } - - // Copy to Image: - { - VkImageMemoryBarrier copy_barrier[1] = {}; - copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - copy_barrier[0].image = backend_tex->Image; - copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copy_barrier[0].subresourceRange.levelCount = 1; - copy_barrier[0].subresourceRange.layerCount = 1; - vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); - - VkBufferImageCopy region = {}; - region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - region.imageSubresource.layerCount = 1; - region.imageExtent.width = width; - region.imageExtent.height = height; - region.imageExtent.depth = 1; - vkCmdCopyBufferToImage(bd->TexCommandBuffer, upload_buffer, backend_tex->Image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); - - VkImageMemoryBarrier use_barrier[1] = {}; - use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - use_barrier[0].image = backend_tex->Image; - use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - use_barrier[0].subresourceRange.levelCount = 1; - use_barrier[0].subresourceRange.layerCount = 1; - vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier); - } - - // Store our identifier - io.Fonts->SetTexID((ImTextureID)backend_tex->DescriptorSet); - - // End command buffer - VkSubmitInfo end_info = {}; - end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - end_info.commandBufferCount = 1; - end_info.pCommandBuffers = &bd->TexCommandBuffer; - err = vkEndCommandBuffer(bd->TexCommandBuffer); - check_vk_result(err); - err = vkQueueSubmit(v->Queue, 1, &end_info, VK_NULL_HANDLE); - check_vk_result(err); - - err = vkQueueWaitIdle(v->Queue); - check_vk_result(err); - - vkDestroyBuffer(v->Device, upload_buffer, v->Allocator); - vkFreeMemory(v->Device, upload_buffer_memory, v->Allocator); - - return true; -} - -// You probably never need to call this, as it is called by ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_Shutdown(). -void ImGui_ImplVulkan_DestroyFontsTexture() -{ - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; - - ImGui_ImplVulkan_Texture* backend_tex = &bd->FontTexture; - - if (backend_tex->DescriptorSet) - { - ImGui_ImplVulkan_RemoveTexture(backend_tex->DescriptorSet); - backend_tex->DescriptorSet = VK_NULL_HANDLE; - io.Fonts->SetTexID(0); - } - if (backend_tex->ImageView) { vkDestroyImageView(v->Device, backend_tex->ImageView, v->Allocator); backend_tex->ImageView = VK_NULL_HANDLE; } - if (backend_tex->Image) { vkDestroyImage(v->Device, backend_tex->Image, v->Allocator); backend_tex->Image = VK_NULL_HANDLE; } - if (backend_tex->Memory) { vkFreeMemory(v->Device, backend_tex->Memory, v->Allocator); backend_tex->Memory = VK_NULL_HANDLE; } + if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames >= (int)bd->VulkanInitInfo.ImageCount) + ImGui_ImplVulkan_DestroyTexture(tex); } static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator) @@ -1066,6 +1076,26 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, &bd->Pipeline, v->Subpass); + // Create command pool/buffer for texture upload + if (!bd->TexCommandPool) + { + VkCommandPoolCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + info.flags = 0; + info.queueFamilyIndex = v->QueueFamily; + err = vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->TexCommandPool); + check_vk_result(err); + } + if (!bd->TexCommandBuffer) + { + VkCommandBufferAllocateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + info.commandPool = bd->TexCommandPool; + info.commandBufferCount = 1; + err = vkAllocateCommandBuffers(v->Device, &info, &bd->TexCommandBuffer); + check_vk_result(err); + } + return true; } @@ -1074,7 +1104,11 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); - ImGui_ImplVulkan_DestroyFontsTexture(); + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplVulkan_DestroyTexture(tex); if (bd->TexCommandBuffer) { vkFreeCommandBuffers(v->Device, bd->TexCommandPool, 1, &bd->TexCommandBuffer); bd->TexCommandBuffer = VK_NULL_HANDLE; } if (bd->TexCommandPool) { vkDestroyCommandPool(v->Device, bd->TexCommandPool, v->Allocator); bd->TexCommandPool = VK_NULL_HANDLE; } @@ -1175,6 +1209,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_vulkan"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. IM_ASSERT(info->Instance != VK_NULL_HANDLE); IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE); @@ -1219,7 +1254,7 @@ void ImGui_ImplVulkan_Shutdown() io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } @@ -1227,9 +1262,7 @@ void ImGui_ImplVulkan_NewFrame() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplVulkan_Init()?"); - - if (!bd->FontTexture.DescriptorSet) - ImGui_ImplVulkan_CreateFontsTexture(); + IM_UNUSED(bd); } void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index c3f40e138..4baa98335 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. +// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as texture identifier. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID/ImTextureRef + https://github.com/ocornut/imgui/pull/914 for discussions. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. @@ -61,9 +62,8 @@ #define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #endif -// Current version of the backend use 1 descriptor for the font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture(). -// It is expected that as early as Q1 2025 the backend will use a few more descriptors. Use this value + number of desired calls to ImGui_ImplVulkan_AddTexture(). -#define IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE (1) // Minimum per atlas +// Backend uses a small number of descriptors per font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture(). +#define IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE (8) // Minimum per atlas // Initialization data, for ImGui_ImplVulkan_Init() // [Please zero-clear before use!] @@ -112,10 +112,11 @@ IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); -IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontsTexture(); IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex); + // Register a texture (VkDescriptorSet == ImTextureID) // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem // Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. From 9fa65cd190017e7a5a838a719a1b9fe05664f4a6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Dec 2024 15:52:52 +0100 Subject: [PATCH 0901/2359] Backends: SDL_Renderer2: added ImGuiBackendFlags_RendererHasTextures support. --- backends/imgui_impl_sdlrenderer2.cpp | 102 ++++++++++++++++----------- backends/imgui_impl_sdlrenderer2.h | 10 +-- 2 files changed, 67 insertions(+), 45 deletions(-) diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index bfaeb9138..dbdeb5c11 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -10,8 +10,9 @@ // and it might be difficult to step out of those boundaries. // Implemented features: -// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -23,6 +24,7 @@ // - Introduction, links and more at the top of imgui.cpp // CHANGELOG +// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLRenderer2_CreateFontsTexture() and ImGui_ImplSDLRenderer2_DestroyFontsTexture(). // 2025-01-18: Use endian-dependent RGBA32 texture format, to match SDL_Color. // 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer2_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter. @@ -54,7 +56,7 @@ struct ImGui_ImplSDLRenderer2_Data { SDL_Renderer* Renderer; // Main viewport's renderer - SDL_Texture* FontTexture; + ImGui_ImplSDLRenderer2_Data() { memset((void*)this, 0, sizeof(*this)); } }; @@ -78,6 +80,7 @@ bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer) io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_sdlrenderer2"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. bd->Renderer = renderer; @@ -94,7 +97,7 @@ void ImGui_ImplSDLRenderer2_Shutdown() io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } @@ -110,9 +113,7 @@ void ImGui_ImplSDLRenderer2_NewFrame() { ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer2_Init()?"); - - if (!bd->FontTexture) - ImGui_ImplSDLRenderer2_CreateDeviceObjects(); + IM_UNUSED(bd); } void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer) @@ -133,6 +134,13 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* if (fb_width == 0 || fb_height == 0) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplSDLRenderer2_UpdateTexture(tex); + // Backup SDL_Renderer state that will be modified to restore it afterwards struct BackupSDLRendererState { @@ -218,55 +226,67 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* SDL_RenderSetClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr); } -// Called by Init/NewFrame/Shutdown -bool ImGui_ImplSDLRenderer2_CreateFontsTexture() +void ImGui_ImplSDLRenderer2_UpdateTexture(ImTextureData* tex) { - ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); - // Build texture atlas - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. - - // Upload texture to graphics system - // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height); - if (bd->FontTexture == nullptr) + if (tex->Status == ImTextureStatus_WantCreate) { - SDL_Log("error creating texture"); - return false; + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + + // Create texture + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + SDL_Texture* sdl_texture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, tex->Width, tex->Height); + IM_ASSERT(sdl_texture != nullptr && "Backend failed to create texture!"); + SDL_UpdateTexture(sdl_texture, nullptr, tex->GetPixels(), tex->GetPitch()); + SDL_SetTextureBlendMode(sdl_texture, SDL_BLENDMODE_BLEND); + SDL_SetTextureScaleMode(sdl_texture, SDL_ScaleModeLinear); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)sdl_texture); + tex->SetStatus(ImTextureStatus_OK); } - SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width); - SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); - SDL_SetTextureScaleMode(bd->FontTexture, SDL_ScaleModeLinear); - - // Store our identifier - io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); - - return true; -} - -void ImGui_ImplSDLRenderer2_DestroyFontsTexture() -{ - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); - if (bd->FontTexture) + else if (tex->Status == ImTextureStatus_WantUpdates) { - io.Fonts->SetTexID(0); - SDL_DestroyTexture(bd->FontTexture); - bd->FontTexture = nullptr; + // 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. + SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID; + for (ImTextureRect& r : tex->Updates) + { + SDL_Rect sdl_r = { r.x, r.y, r.w, r.h }; + SDL_UpdateTexture(sdl_texture, &sdl_r, tex->GetPixelsAt(r.x, r.y), tex->GetPitch()); + } + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantDestroy) + { + SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID; + if (sdl_texture == nullptr) + return; + SDL_DestroyTexture(sdl_texture); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); } } -bool ImGui_ImplSDLRenderer2_CreateDeviceObjects() +void ImGui_ImplSDLRenderer2_CreateDeviceObjects() { - return ImGui_ImplSDLRenderer2_CreateFontsTexture(); } void ImGui_ImplSDLRenderer2_DestroyDeviceObjects() { - ImGui_ImplSDLRenderer2_DestroyFontsTexture(); + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + { + tex->SetStatus(ImTextureStatus_WantDestroy); + ImGui_ImplSDLRenderer2_UpdateTexture(tex); + } } //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h index a0337d314..cf127c1f7 100644 --- a/backends/imgui_impl_sdlrenderer2.h +++ b/backends/imgui_impl_sdlrenderer2.h @@ -10,8 +10,9 @@ // and it might be difficult to step out of those boundaries. // Implemented features: -// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -35,11 +36,12 @@ IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer); // Called by Init/NewFrame/Shutdown -IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyFontsTexture(); -IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_UpdateTexture(ImTextureData* tex); + // [BETA] Selected render state data shared with callbacks. // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLRenderer2_RenderDrawData() call. // (Please open an issue if you feel you need access to more data) From e538883a20bd5896f33f1ee2717b171a593347d3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Dec 2024 15:57:32 +0100 Subject: [PATCH 0902/2359] Backends: SDL_Renderer3: added ImGuiBackendFlags_RendererHasTextures support. --- backends/imgui_impl_sdlrenderer3.cpp | 101 ++++++++++++++++----------- backends/imgui_impl_sdlrenderer3.h | 10 +-- 2 files changed, 66 insertions(+), 45 deletions(-) diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 42fefa0cd..ef6f0441c 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -10,8 +10,9 @@ // and it might be difficult to step out of those boundaries. // Implemented features: -// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -23,6 +24,7 @@ // - Introduction, links and more at the top of imgui.cpp // CHANGELOG +// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLRenderer3_CreateFontsTexture() and ImGui_ImplSDLRenderer3_DestroyFontsTexture(). // 2025-01-18: Use endian-dependent RGBA32 texture format, to match SDL_Color. // 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer3_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. // 2024-07-01: Update for SDL3 api changes: SDL_RenderGeometryRaw() uint32 version was removed (SDL#9009). @@ -51,7 +53,6 @@ struct ImGui_ImplSDLRenderer3_Data { SDL_Renderer* Renderer; // Main viewport's renderer - SDL_Texture* FontTexture; ImVector ColorBuffer; ImGui_ImplSDLRenderer3_Data() { memset((void*)this, 0, sizeof(*this)); } @@ -77,6 +78,7 @@ bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer) io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_sdlrenderer3"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. bd->Renderer = renderer; @@ -93,7 +95,7 @@ void ImGui_ImplSDLRenderer3_Shutdown() io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } @@ -109,9 +111,7 @@ void ImGui_ImplSDLRenderer3_NewFrame() { ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer3_Init()?"); - - if (!bd->FontTexture) - ImGui_ImplSDLRenderer3_CreateDeviceObjects(); + IM_UNUSED(bd); } // https://github.com/libsdl-org/SDL/issues/9009 @@ -152,6 +152,13 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* if (fb_width == 0 || fb_height == 0) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplSDLRenderer3_UpdateTexture(tex); + // Backup SDL_Renderer state that will be modified to restore it afterwards struct BackupSDLRendererState { @@ -235,55 +242,67 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* SDL_SetRenderClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr); } -// Called by Init/NewFrame/Shutdown -bool ImGui_ImplSDLRenderer3_CreateFontsTexture() +void ImGui_ImplSDLRenderer3_UpdateTexture(ImTextureData* tex) { - ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); - // Build texture atlas - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. - - // Upload texture to graphics system - // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height); - if (bd->FontTexture == nullptr) + if (tex->Status == ImTextureStatus_WantCreate) { - SDL_Log("error creating texture"); - return false; + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + + // Create texture + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + SDL_Texture* sdl_texture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, tex->Width, tex->Height); + IM_ASSERT(sdl_texture != nullptr && "Backend failed to create texture!"); + SDL_UpdateTexture(sdl_texture, nullptr, tex->GetPixels(), tex->GetPitch()); + SDL_SetTextureBlendMode(sdl_texture, SDL_BLENDMODE_BLEND); + SDL_SetTextureScaleMode(sdl_texture, SDL_SCALEMODE_LINEAR); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)sdl_texture); + tex->SetStatus(ImTextureStatus_OK); } - SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width); - SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); - SDL_SetTextureScaleMode(bd->FontTexture, SDL_SCALEMODE_LINEAR); - - // Store our identifier - io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); - - return true; -} - -void ImGui_ImplSDLRenderer3_DestroyFontsTexture() -{ - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); - if (bd->FontTexture) + else if (tex->Status == ImTextureStatus_WantUpdates) { - io.Fonts->SetTexID(0); - SDL_DestroyTexture(bd->FontTexture); - bd->FontTexture = nullptr; + // 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. + SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID; + for (ImTextureRect& r : tex->Updates) + { + SDL_Rect sdl_r = { r.x, r.y, r.w, r.h }; + SDL_UpdateTexture(sdl_texture, &sdl_r, tex->GetPixelsAt(r.x, r.y), tex->GetPitch()); + } + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantDestroy) + { + SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID; + if (sdl_texture == nullptr) + return; + SDL_DestroyTexture(sdl_texture); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); } } -bool ImGui_ImplSDLRenderer3_CreateDeviceObjects() +void ImGui_ImplSDLRenderer3_CreateDeviceObjects() { - return ImGui_ImplSDLRenderer3_CreateFontsTexture(); } void ImGui_ImplSDLRenderer3_DestroyDeviceObjects() { - ImGui_ImplSDLRenderer3_DestroyFontsTexture(); + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + { + tex->SetStatus(ImTextureStatus_WantDestroy); + ImGui_ImplSDLRenderer3_UpdateTexture(tex); + } } //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h index 3473bcc77..170560fdc 100644 --- a/backends/imgui_impl_sdlrenderer3.h +++ b/backends/imgui_impl_sdlrenderer3.h @@ -10,8 +10,9 @@ // and it might be difficult to step out of those boundaries. // Implemented features: -// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -35,11 +36,12 @@ IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer); // Called by Init/NewFrame/Shutdown -IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyFontsTexture(); -IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_UpdateTexture(ImTextureData* tex); + // [BETA] Selected render state data shared with callbacks. // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLRenderer3_RenderDrawData() call. // (Please open an issue if you feel you need access to more data) From 16fe666e364785c0a9b534ea18aa5fa62ab06a36 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 12:32:56 +0100 Subject: [PATCH 0903/2359] Backends: SDLGPU3: added ImGuiBackendFlags_RendererHasTextures support. # Conflicts: # backends/imgui_impl_sdlgpu3.cpp # backends/imgui_impl_sdlgpu3.h --- backends/imgui_impl_sdlgpu3.cpp | 203 +++++++++++++++++++------------- backends/imgui_impl_sdlgpu3.h | 9 +- 2 files changed, 128 insertions(+), 84 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 4bcc5bdfc..92515602b 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -3,7 +3,8 @@ // Implemented features: // [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID. -// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ @@ -21,6 +22,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture(). // 2025-04-28: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2025-03-30: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. // 2025-03-21: Fixed typo in function name Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData(). @@ -33,6 +35,11 @@ #include "imgui_impl_sdlgpu3_shaders.h" // SDL_GPU Data +struct ImGui_ImplSDLGPU3_Texture +{ + SDL_GPUTexture* Texture = nullptr; + SDL_GPUTextureSamplerBinding TextureSamplerBinding = { nullptr, nullptr }; +}; // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData() struct ImGui_ImplSDLGPU3_FrameData @@ -50,14 +57,12 @@ struct ImGui_ImplSDLGPU3_Data ImGui_ImplSDLGPU3_InitInfo InitInfo; // Graphics pipeline & shaders - SDL_GPUShader* VertexShader = nullptr; - SDL_GPUShader* FragmentShader = nullptr; - SDL_GPUGraphicsPipeline* Pipeline = nullptr; - - // Font data - SDL_GPUSampler* FontSampler = nullptr; - SDL_GPUTexture* FontTexture = nullptr; - SDL_GPUTextureSamplerBinding FontBinding = { nullptr, nullptr }; + SDL_GPUShader* VertexShader = nullptr; + SDL_GPUShader* FragmentShader = nullptr; + SDL_GPUGraphicsPipeline* Pipeline = nullptr; + SDL_GPUSampler* TexSampler = nullptr; + SDL_GPUTransferBuffer* TexTransferBuffer = nullptr; + uint32_t TexTransferBufferSize = 0; // Frame data for main window ImGui_ImplSDLGPU3_FrameData MainWindowFrameData; @@ -154,6 +159,13 @@ void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff if (fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount <= 0) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplSDLGPU3_UpdateTexture(tex); + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData; @@ -281,91 +293,117 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe SDL_SetGPUScissor(render_pass, &scissor_rect); } -void ImGui_ImplSDLGPU3_CreateFontsTexture() +static void ImGui_ImplSDLGPU3_DestroyTexture(ImTextureData* tex) +{ + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_Texture* backend_tex = (ImGui_ImplSDLGPU3_Texture*)tex->BackendUserData; + if (backend_tex == nullptr) + return; + SDL_GPUTextureSamplerBinding* binding = (SDL_GPUTextureSamplerBinding*)(intptr_t)tex->BackendUserData; + IM_ASSERT(backend_tex->Texture == binding->texture); + SDL_ReleaseGPUTexture(bd->InitInfo.Device, backend_tex->Texture); + IM_DELETE(backend_tex); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + tex->BackendUserData = nullptr; +} + +void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) { - ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - // Destroy existing texture (if any) - if (bd->FontTexture) + if (tex->Status == ImTextureStatus_WantCreate) { - SDL_WaitForGPUIdle(v->Device); - ImGui_ImplSDLGPU3_DestroyFontsTexture(); - } + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + ImGui_ImplSDLGPU3_Texture* backend_tex = IM_NEW(ImGui_ImplSDLGPU3_Texture)(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - uint32_t upload_size = width * height * 4 * sizeof(char); - - // Create the Image: - { + // Create texture SDL_GPUTextureCreateInfo texture_info = {}; - texture_info.type = SDL_GPU_TEXTURETYPE_2D; + texture_info.type = SDL_GPU_TEXTURETYPE_2D; texture_info.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; texture_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER; - texture_info.width = width; - texture_info.height = height; + texture_info.width = tex->Width; + texture_info.height = tex->Height; texture_info.layer_count_or_depth = 1; texture_info.num_levels = 1; texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1; - bd->FontTexture = SDL_CreateGPUTexture(v->Device, &texture_info); - IM_ASSERT(bd->FontTexture && "Failed to create font texture, call SDL_GetError() for more info"); + backend_tex->Texture = SDL_CreateGPUTexture(v->Device, &texture_info); + backend_tex->TextureSamplerBinding.texture = backend_tex->Texture; + backend_tex->TextureSamplerBinding.sampler = bd->TexSampler; + IM_ASSERT(backend_tex->Texture && "Failed to create font texture, call SDL_GetError() for more info"); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)&backend_tex->TextureSamplerBinding); + tex->BackendUserData = backend_tex; } - // Assign the texture to the TextureSamplerBinding - bd->FontBinding.texture = bd->FontTexture; - - // Create all the upload structures and upload: + if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates) { - SDL_GPUTransferBufferCreateInfo transferbuffer_info = {}; - transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; - transferbuffer_info.size = upload_size; + ImGui_ImplSDLGPU3_Texture* backend_tex = (ImGui_ImplSDLGPU3_Texture*)tex->BackendUserData; + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); - SDL_GPUTransferBuffer* transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info); - IM_ASSERT(transferbuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information"); + // Update full texture or selected blocks. We only ever write to textures regions which have never been used before! + // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions. + // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture. + const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x; + const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y; + const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w; + const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h; + uint32_t upload_pitch = upload_w * tex->BytesPerPixel; + uint32_t upload_size = upload_w * upload_h * tex->BytesPerPixel; - void* texture_ptr = SDL_MapGPUTransferBuffer(v->Device, transferbuffer, false); - memcpy(texture_ptr, pixels, upload_size); - SDL_UnmapGPUTransferBuffer(v->Device, transferbuffer); + // Create transfer buffer + if (bd->TexTransferBufferSize < upload_size) + { + SDL_ReleaseGPUTransferBuffer(v->Device, bd->TexTransferBuffer); + SDL_GPUTransferBufferCreateInfo transferbuffer_info = {}; + transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; + transferbuffer_info.size = upload_size + 1024; + bd->TexTransferBufferSize = upload_size + 1024; + bd->TexTransferBuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info); + IM_ASSERT(bd->TexTransferBuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information"); + } + + // Copy to transfer buffer + { + void* texture_ptr = SDL_MapGPUTransferBuffer(v->Device, bd->TexTransferBuffer, false); + for (int y = 0; y < upload_h; y++) + memcpy((void*)((uintptr_t)texture_ptr + y * upload_pitch), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch); + SDL_UnmapGPUTransferBuffer(v->Device, bd->TexTransferBuffer); + } SDL_GPUTextureTransferInfo transfer_info = {}; transfer_info.offset = 0; - transfer_info.transfer_buffer = transferbuffer; + transfer_info.transfer_buffer = bd->TexTransferBuffer; SDL_GPUTextureRegion texture_region = {}; - texture_region.texture = bd->FontTexture; - texture_region.w = width; - texture_region.h = height; + texture_region.texture = backend_tex->Texture; + texture_region.x = (Uint32)upload_x; + texture_region.y = (Uint32)upload_y; + texture_region.w = (Uint32)upload_w; + texture_region.h = (Uint32)upload_h; texture_region.d = 1; - SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->Device); - SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(cmd); - SDL_UploadToGPUTexture(copy_pass, &transfer_info, &texture_region, false); - SDL_EndGPUCopyPass(copy_pass); - SDL_SubmitGPUCommandBuffer(cmd); - SDL_ReleaseGPUTransferBuffer(v->Device, transferbuffer); - } + // Upload + { + SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->Device); + SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(cmd); + SDL_UploadToGPUTexture(copy_pass, &transfer_info, &texture_region, false); + SDL_EndGPUCopyPass(copy_pass); + SDL_SubmitGPUCommandBuffer(cmd); + } - // Store our identifier - io.Fonts->SetTexID((ImTextureID)&bd->FontBinding); -} - -// You probably never need to call this, as it is called by ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_Shutdown(). -void ImGui_ImplSDLGPU3_DestroyFontsTexture() -{ - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - if (bd->FontTexture) - { - SDL_ReleaseGPUTexture(v->Device, bd->FontTexture); - bd->FontBinding.texture = nullptr; - bd->FontTexture = nullptr; + tex->SetStatus(ImTextureStatus_OK); } - io.Fonts->SetTexID(0); + if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + ImGui_ImplSDLGPU3_DestroyTexture(tex); } static void ImGui_ImplSDLGPU3_CreateShaders() @@ -517,7 +555,9 @@ void ImGui_ImplSDLGPU3_CreateDeviceObjects() ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; - if (!bd->FontSampler) + ImGui_ImplSDLGPU3_DestroyDeviceObjects(); + + if (bd->TexSampler == nullptr) { // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. SDL_GPUSamplerCreateInfo sampler_info = {}; @@ -534,13 +574,11 @@ void ImGui_ImplSDLGPU3_CreateDeviceObjects() sampler_info.max_anisotropy = 1.0f; sampler_info.enable_compare = false; - bd->FontSampler = SDL_CreateGPUSampler(v->Device, &sampler_info); - bd->FontBinding.sampler = bd->FontSampler; - IM_ASSERT(bd->FontSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information"); + bd->TexSampler = SDL_CreateGPUSampler(v->Device, &sampler_info); + IM_ASSERT(bd->TexSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information"); } ImGui_ImplSDLGPU3_CreateGraphicsPipeline(); - ImGui_ImplSDLGPU3_CreateFontsTexture(); } void ImGui_ImplSDLGPU3_DestroyFrameData() @@ -564,12 +602,16 @@ void ImGui_ImplSDLGPU3_DestroyDeviceObjects() ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo; ImGui_ImplSDLGPU3_DestroyFrameData(); - ImGui_ImplSDLGPU3_DestroyFontsTexture(); - if (bd->VertexShader) { SDL_ReleaseGPUShader(v->Device, bd->VertexShader); bd->VertexShader = nullptr;} - if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->Device, bd->FragmentShader); bd->FragmentShader = nullptr;} - if (bd->FontSampler) { SDL_ReleaseGPUSampler(v->Device, bd->FontSampler); bd->FontSampler = nullptr;} - if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->Device, bd->Pipeline); bd->Pipeline = nullptr;} + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplSDLGPU3_DestroyTexture(tex); + if (bd->TexTransferBuffer) { SDL_ReleaseGPUTransferBuffer(v->Device, bd->TexTransferBuffer); bd->TexTransferBuffer = nullptr; } + if (bd->VertexShader) { SDL_ReleaseGPUShader(v->Device, bd->VertexShader); bd->VertexShader = nullptr; } + if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->Device, bd->FragmentShader); bd->FragmentShader = nullptr; } + if (bd->TexSampler) { SDL_ReleaseGPUSampler(v->Device, bd->TexSampler); bd->TexSampler = nullptr; } + if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->Device, bd->Pipeline); bd->Pipeline = nullptr; } } bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info) @@ -583,6 +625,7 @@ bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info) io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_sdlgpu3"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. IM_ASSERT(info->Device != nullptr); IM_ASSERT(info->ColorTargetFormat != SDL_GPU_TEXTUREFORMAT_INVALID); @@ -601,7 +644,7 @@ void ImGui_ImplSDLGPU3_Shutdown() ImGui_ImplSDLGPU3_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } @@ -610,10 +653,8 @@ void ImGui_ImplSDLGPU3_NewFrame() ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLGPU3_Init()?"); - if (!bd->FontSampler) + if (!bd->TexSampler) ImGui_ImplSDLGPU3_CreateDeviceObjects(); - if (!bd->FontTexture) - ImGui_ImplSDLGPU3_CreateFontsTexture(); } #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index c6d5a8e5d..380855b29 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -3,7 +3,8 @@ // Implemented features: // [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID. -// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ @@ -41,9 +42,11 @@ IMGUI_IMPL_API void ImGui_ImplSDLGPU3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer); IMGUI_IMPL_API void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline = nullptr); +// Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplSDLGPU3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLGPU3_DestroyDeviceObjects(); -IMGUI_IMPL_API void ImGui_ImplSDLGPU3_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplSDLGPU3_DestroyFontsTexture(); + +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex); #endif // #ifndef IMGUI_DISABLE From ee8941e0de53fb745e7508e71ec5a00ddf2ec3de Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 10:38:11 +0100 Subject: [PATCH 0904/2359] Backends: Allegro5: added ImGuiBackendFlags_RendererHasTextures support. --- backends/imgui_impl_allegro5.cpp | 135 +++++++++++++++++++------------ backends/imgui_impl_allegro5.h | 6 +- 2 files changed, 90 insertions(+), 51 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 9db3e5198..b5f8ca00a 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -2,7 +2,8 @@ // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.) // Implemented features: -// [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Clipboard support (from Allegro 5.1.12). // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. @@ -20,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture(). // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-01-06: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: @@ -137,6 +139,13 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplAllegro5_UpdateTexture(tex); + // Backup Allegro state that will be modified ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); ALLEGRO_TRANSFORM last_transform = *al_get_current_transform(); @@ -232,43 +241,7 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplAllegro5_CreateDeviceObjects() { - // Build texture atlas ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); - ImGuiIO& io = ImGui::GetIO(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - - // Create texture - // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - int flags = al_get_new_bitmap_flags(); - int fmt = al_get_new_bitmap_format(); - al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); - al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE); - ALLEGRO_BITMAP* img = al_create_bitmap(width, height); - al_set_new_bitmap_flags(flags); - al_set_new_bitmap_format(fmt); - if (!img) - return false; - - ALLEGRO_LOCKED_REGION* locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY); - if (!locked_img) - { - al_destroy_bitmap(img); - return false; - } - memcpy(locked_img->data, pixels, sizeof(int) * width * height); - al_unlock_bitmap(img); - - // Convert software texture to hardware texture. - ALLEGRO_BITMAP* cloned_img = al_clone_bitmap(img); - al_destroy_bitmap(img); - if (!cloned_img) - return false; - - // Store our identifier - io.Fonts->SetTexID((ImTextureID)(intptr_t)cloned_img); - bd->Texture = cloned_img; // Create an invisible mouse cursor // Because al_hide_mouse_cursor() seems to mess up with the actual inputs.. @@ -279,16 +252,81 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() return true; } +void ImGui_ImplAllegro5_UpdateTexture(ImTextureData* tex) +{ + if (tex->Status == ImTextureStatus_WantCreate) + { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + + // Create texture + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + const int new_bitmap_flags = al_get_new_bitmap_flags(); + int new_bitmap_format = al_get_new_bitmap_format(); + al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); + al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE); + ALLEGRO_BITMAP* cpu_bitmap = al_create_bitmap(tex->Width, tex->Height); + al_set_new_bitmap_flags(new_bitmap_flags); + al_set_new_bitmap_format(new_bitmap_format); + IM_ASSERT(cpu_bitmap != nullptr && "Backend failed to create texture!"); + + // Upload pixels + ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap(cpu_bitmap, al_get_bitmap_format(cpu_bitmap), ALLEGRO_LOCK_WRITEONLY); + IM_ASSERT(locked_region != nullptr && "Backend failed to create texture!"); + memcpy(locked_region->data, tex->GetPixels(), tex->GetSizeInBytes()); + al_unlock_bitmap(cpu_bitmap); + + // Convert software texture to hardware texture. + ALLEGRO_BITMAP* gpu_bitmap = al_clone_bitmap(cpu_bitmap); + al_destroy_bitmap(cpu_bitmap); + IM_ASSERT(gpu_bitmap != nullptr && "Backend failed to create texture!"); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)gpu_bitmap); + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // 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. + ImTextureRect r_bb = tex->UpdateRect; // Bounding box encompassing all individual updates + ALLEGRO_BITMAP* gpu_bitmap = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID; + ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap_region(gpu_bitmap, r_bb.x, r_bb.y, r_bb.w, r_bb.h, al_get_bitmap_format(gpu_bitmap), ALLEGRO_LOCK_WRITEONLY); + IM_ASSERT(locked_region && "Backend failed to update texture!"); + for (ImTextureRect& r : tex->Updates) + for (int y = 0; y < r.h; y++) + memcpy((unsigned char*)locked_region->data + locked_region->pitch * (r.y - r_bb.y + y) + (r.x - r_bb.x) * tex->BytesPerPixel, // dst + tex->GetPixelsAt(r.x, r.y + y), r.w * tex->BytesPerPixel); // src, block pitch + al_unlock_bitmap(gpu_bitmap); + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantDestroy) + { + ALLEGRO_BITMAP* backend_tex = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID; + if (backend_tex) + al_destroy_bitmap(backend_tex); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + } +} + void ImGui_ImplAllegro5_InvalidateDeviceObjects() { - ImGuiIO& io = ImGui::GetIO(); ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); - if (bd->Texture) - { - io.Fonts->SetTexID(0); - al_destroy_bitmap(bd->Texture); - bd->Texture = nullptr; - } + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + { + tex->SetStatus(ImTextureStatus_WantDestroy); + ImGui_ImplAllegro5_UpdateTexture(tex); + } + + // Destroy mouse cursor if (bd->MouseCursorInvisible) { al_destroy_mouse_cursor(bd->MouseCursorInvisible); @@ -439,6 +477,7 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = io.BackendRendererName = "imgui_impl_allegro5"; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. bd->Display = display; bd->LastCursor = ALLEGRO_SYSTEM_MOUSE_CURSOR_NONE; @@ -478,7 +517,7 @@ void ImGui_ImplAllegro5_Shutdown() io.BackendPlatformName = io.BackendRendererName = nullptr; io.BackendPlatformUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_HasMouseCursors; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } @@ -608,12 +647,8 @@ void ImGui_ImplAllegro5_NewFrame() ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?"); - if (!bd->Texture) - ImGui_ImplAllegro5_CreateDeviceObjects(); - - ImGuiIO& io = ImGui::GetIO(); - // Setup display size (every frame to accommodate for window resizing) + ImGuiIO& io = ImGui::GetIO(); int w, h; w = al_get_display_width(bd->Display); h = al_get_display_height(bd->Display); diff --git a/backends/imgui_impl_allegro5.h b/backends/imgui_impl_allegro5.h index 356ec7d0a..421bbf129 100644 --- a/backends/imgui_impl_allegro5.h +++ b/backends/imgui_impl_allegro5.h @@ -2,7 +2,8 @@ // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.) // Implemented features: -// [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Clipboard support (from Allegro 5.1.12). // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. @@ -36,4 +37,7 @@ IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event); IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplAllegro5_UpdateTexture(ImTextureData* tex); + #endif // #ifndef IMGUI_DISABLE From 26c017d5ea73a7b52271c26438c9dd15b2b46c81 Mon Sep 17 00:00:00 2001 From: thedmd Date: Tue, 17 Dec 2024 00:42:57 +0100 Subject: [PATCH 0905/2359] Backends: Metal: added ImGuiBackendFlags_RendererHasTextures support. # Conflicts: # backends/imgui_impl_metal.h # backends/imgui_impl_metal.mm --- backends/imgui_impl_metal.h | 13 ++- backends/imgui_impl_metal.mm | 173 +++++++++++++++++++++++------------ 2 files changed, 122 insertions(+), 64 deletions(-) diff --git a/backends/imgui_impl_metal.h b/backends/imgui_impl_metal.h index d46998269..2a9a26a02 100644 --- a/backends/imgui_impl_metal.h +++ b/backends/imgui_impl_metal.h @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. OSX) // Implemented features: -// [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'MTLTexture' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -35,11 +36,12 @@ IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id commandEncoder); // Called by Init/NewFrame/Shutdown -IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(id device); -IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(id device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex); + #endif //----------------------------------------------------------------------------- @@ -62,11 +64,12 @@ IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, MTL::RenderCommandEncoder* commandEncoder); // Called by Init/NewFrame/Shutdown -IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device); -IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex); + #endif #endif diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 1cd2308d1..b1decb2bb 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -2,8 +2,9 @@ // This needs to be used along with a Platform Backend (e.g. OSX) // Implemented features: -// [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'MTLTexture' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -15,6 +16,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplMetal_CreateFontsTexture() and ImGui_ImplMetal_DestroyFontsTexture(). // 2025-02-03: Metal: Crash fix. (#8367) // 2024-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419). // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. @@ -59,6 +61,11 @@ - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor; @end +@interface MetalTexture : NSObject +@property (nonatomic, strong) id metalTexture; +- (instancetype)initWithTexture:(id)metalTexture; +@end + // 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. @@ -67,7 +74,6 @@ @property (nonatomic, strong) id depthStencilState; @property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; // framebuffer descriptor for current frame; transient @property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors -@property (nonatomic, strong, nullable) id fontTexture; @property (nonatomic, strong) NSMutableArray* bufferCache; @property (nonatomic, assign) double lastBufferCachePurge; - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; @@ -110,11 +116,6 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, } -bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device) -{ - return ImGui_ImplMetal_CreateFontsTexture((__bridge id)(device)); -} - bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device) { return ImGui_ImplMetal_CreateDeviceObjects((__bridge id)(device)); @@ -134,6 +135,7 @@ bool ImGui_ImplMetal_Init(id device) io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_metal"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. bd->SharedMetalContext = [[MetalContext alloc] init]; bd->SharedMetalContext.device = device; @@ -152,7 +154,7 @@ void ImGui_ImplMetal_Shutdown() ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); } void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor) @@ -168,7 +170,7 @@ void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor) ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device); } -static void ImGui_ImplMetal_SetupRenderState(ImDrawData* drawData, id commandBuffer, +static void ImGui_ImplMetal_SetupRenderState(ImDrawData* draw_data, id commandBuffer, id commandEncoder, id renderPipelineState, MetalBuffer* vertexBuffer, size_t vertexBufferOffset) { @@ -184,17 +186,17 @@ static void ImGui_ImplMetal_SetupRenderState(ImDrawData* drawData, idDisplaySize.x * drawData->FramebufferScale.x), - .height = (double)(drawData->DisplaySize.y * drawData->FramebufferScale.y), + .width = (double)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x), + .height = (double)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y), .znear = 0.0, .zfar = 1.0 }; [commandEncoder setViewport:viewport]; - float L = drawData->DisplayPos.x; - float R = drawData->DisplayPos.x + drawData->DisplaySize.x; - float T = drawData->DisplayPos.y; - float B = drawData->DisplayPos.y + drawData->DisplaySize.y; + float L = draw_data->DisplayPos.x; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; + float T = draw_data->DisplayPos.y; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; float N = (float)viewport.znear; float F = (float)viewport.zfar; const float ortho_projection[4][4] = @@ -213,17 +215,24 @@ static void ImGui_ImplMetal_SetupRenderState(ImDrawData* drawData, id commandBuffer, id commandEncoder) +void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id commandBuffer, id commandEncoder) { ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); MetalContext* ctx = bd->SharedMetalContext; // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x); - int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y); - if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0) + int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplMetal_UpdateTexture(tex); + // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame // The hit rate for this cache should be very near 100%. id renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor]; @@ -236,23 +245,23 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState; } - size_t vertexBufferLength = (size_t)drawData->TotalVtxCount * sizeof(ImDrawVert); - size_t indexBufferLength = (size_t)drawData->TotalIdxCount * sizeof(ImDrawIdx); + size_t vertexBufferLength = (size_t)draw_data->TotalVtxCount * sizeof(ImDrawVert); + size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx); MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; - ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0); + ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0); // Will project scissor/clipping rectangles into framebuffer space - ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports - ImVec2 clip_scale = drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists size_t vertexBufferOffset = 0; size_t indexBufferOffset = 0; - for (int n = 0; n < drawData->CmdListsCount; n++) + for (int n = 0; n < draw_data->CmdListsCount; n++) { - const ImDrawList* draw_list = drawData->CmdLists[n]; + const ImDrawList* draw_list = draw_data->CmdLists[n]; memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); @@ -265,7 +274,7 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) - ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset); + ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset); else pcmd->UserCallback(draw_list, pcmd); } @@ -325,42 +334,71 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id c }]; } -bool ImGui_ImplMetal_CreateFontsTexture(id device) +static void ImGui_ImplMetal_DestroyTexture(ImTextureData* tex) { - ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); - ImGuiIO& io = ImGui::GetIO(); + MetalTexture* backend_tex = (__bridge_transfer MetalTexture*)(tex->BackendUserData); + if (backend_tex == nullptr) + return; + IM_ASSERT(backend_tex.metalTexture == (__bridge id)(void*)(intptr_t)tex->TexID); + backend_tex.metalTexture = nil; - // We are retrieving and uploading the font atlas as a 4-channels RGBA texture here. - // In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth. - // However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures. - // You can make that change in your implementation. - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm - width:(NSUInteger)width - height:(NSUInteger)height - mipmapped:NO]; - textureDescriptor.usage = MTLTextureUsageShaderRead; -#if TARGET_OS_OSX || TARGET_OS_MACCATALYST - textureDescriptor.storageMode = MTLStorageModeManaged; -#else - textureDescriptor.storageMode = MTLStorageModeShared; -#endif - id texture = [device newTextureWithDescriptor:textureDescriptor]; - [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4]; - bd->SharedMetalContext.fontTexture = texture; - io.Fonts->SetTexID((ImTextureID)(intptr_t)(__bridge void*)bd->SharedMetalContext.fontTexture); // ImTextureID == ImU64 - - return (bd->SharedMetalContext.fontTexture != nil); + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + tex->BackendUserData = nullptr; } -void ImGui_ImplMetal_DestroyFontsTexture() +void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex) { ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); - ImGuiIO& io = ImGui::GetIO(); - bd->SharedMetalContext.fontTexture = nil; - io.Fonts->SetTexID(0); + if (tex->Status == ImTextureStatus_WantCreate) + { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + + // We are retrieving and uploading the font atlas as a 4-channels RGBA texture here. + // In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth. + // However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures. + // You can make that change in your implementation. + MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:(NSUInteger)tex->Width + height:(NSUInteger)tex->Height + mipmapped:NO]; + textureDescriptor.usage = MTLTextureUsageShaderRead; + #if TARGET_OS_OSX || TARGET_OS_MACCATALYST + textureDescriptor.storageMode = MTLStorageModeManaged; + #else + textureDescriptor.storageMode = MTLStorageModeShared; + #endif + id texture = [bd->SharedMetalContext.device newTextureWithDescriptor:textureDescriptor]; + [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)tex->Width, (NSUInteger)tex->Height) mipmapLevel:0 withBytes:tex->Pixels bytesPerRow:(NSUInteger)tex->Width * 4]; + MetalTexture* backend_tex = [[MetalTexture alloc] initWithTexture:texture]; + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)texture); + tex->SetStatus(ImTextureStatus_OK); + tex->BackendUserData = (__bridge_retained void*)(backend_tex); + } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // 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. + 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) + mipmapLevel:0 + withBytes:tex->GetPixelsAt(r.x, r.y) + bytesPerRow:(NSUInteger)tex->Width * 4]; + } + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + { + ImGui_ImplMetal_DestroyTexture(tex); + } } bool ImGui_ImplMetal_CreateDeviceObjects(id device) @@ -373,14 +411,19 @@ bool ImGui_ImplMetal_CreateDeviceObjects(id device) #ifdef IMGUI_IMPL_METAL_CPP [depthStencilDescriptor release]; #endif - ImGui_ImplMetal_CreateFontsTexture(device); + return true; } void ImGui_ImplMetal_DestroyDeviceObjects() { ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); - ImGui_ImplMetal_DestroyFontsTexture(); + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplMetal_DestroyTexture(tex); + [bd->SharedMetalContext.renderPipelineStateCache removeAllObjects]; } @@ -446,6 +489,18 @@ void ImGui_ImplMetal_DestroyDeviceObjects() @end +#pragma mark - MetalTexture implementation + +@implementation MetalTexture +- (instancetype)initWithTexture:(id)metalTexture +{ + if ((self = [super init])) + self.metalTexture = metalTexture; + return self; +} + +@end + #pragma mark - MetalContext implementation @implementation MetalContext From 08e1e7681e79da420ae6a433c99f1a890817c031 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 28 Nov 2024 15:26:52 +0100 Subject: [PATCH 0906/2359] imgui_freetype: Added Freetype implementation for new architecture. --- misc/freetype/imgui_freetype.cpp | 291 ++++++++++++++++++++++++------- misc/freetype/imgui_freetype.h | 8 +- 2 files changed, 228 insertions(+), 71 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 1a268365b..1125364bf 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -2,10 +2,12 @@ // (code) // Get the latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype -// Original code by @vuhdo (Aleksei Skriabin). Improvements by @mikesart. Maintained since 2019 by @ocornut. +// Original code by @vuhdo (Aleksei Skriabin) in 2017, with improvements by @mikesart. +// Maintained since 2019 by @ocornut. // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025/XX/XX: refactored for the new ImFontLoader architecture, and ImGuiBackendFlags_RendererHasTextures support. // 2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927) // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics. // 2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG'. (#6591) @@ -151,10 +153,19 @@ namespace bool IsColored; // The glyph is colored }; - // Font parameters and metrics. - struct FontInfo + // Stored in ImFontAtlas::FontLoaderData + struct ImGui_ImplFreeType_Data { - uint32_t PixelHeight; // Size this font was generated with. + FT_Library Library; + FT_MemoryRec_ MemoryManager; + + ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } + }; + + // Font parameters and metrics. + struct ImGui_ImplFreeType_FontInfo + { + float PixelHeight; // Size this font was generated with. float Ascender; // The pixel extents above the baseline in pixels (typically positive). float Descender; // The extents below the baseline in pixels (typically negative). float LineSpacing; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. @@ -162,40 +173,39 @@ namespace float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font. }; - // FreeType glyph rasterizer. - // NB: No ctor/dtor, explicitly call Init()/Shutdown() - struct FreeTypeFont + // Stored in ImFontConfig::FontLoaderData + struct ImGui_ImplFreeType_FontSrcData { - bool InitFont(FT_Library ft_library, ImFontConfig& src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. - void CloseFont(); - void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size - const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); - const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info); - void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr); - FreeTypeFont() { memset((void*)this, 0, sizeof(*this)); } - ~FreeTypeFont() { CloseFont(); } + bool InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. + void CloseFont(); + void SetPixelHeight(float pixel_height); // Change font pixel size. + const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); + const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info); + void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr); + ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); } + ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); } - // [Internals] - FontInfo Info; // Font descriptor of the current font. - FT_Face Face; - unsigned int UserFlags; // = ImFontConfig::RasterizerFlags - FT_Int32 LoadFlags; - FT_Render_Mode RenderMode; - float RasterizationDensity; - float InvRasterizationDensity; + // Members + ImGui_ImplFreeType_FontInfo Info; // Font descriptor of the current font. + FT_Face FtFace; + unsigned int UserFlags; // = ImFontConfig::RasterizerFlags + FT_Int32 LoadFlags; + FT_Render_Mode RenderMode; + float RasterizationDensity; + float InvRasterizationDensity; }; - bool FreeTypeFont::InitFont(FT_Library ft_library, ImFontConfig& src, unsigned int extra_font_builder_flags) + bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_font_builder_flags) { - FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src.FontData, (uint32_t)src.FontDataSize, (uint32_t)src.FontNo, &Face); + FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (uint32_t)src->FontDataSize, (uint32_t)src->FontNo, &FtFace); if (error != 0) return false; - error = FT_Select_Charmap(Face, FT_ENCODING_UNICODE); + error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE); if (error != 0) return false; // Convert to FreeType flags (NB: Bold and Oblique are processed separately) - UserFlags = src.FontBuilderFlags | extra_font_builder_flags; + UserFlags = src->FontBuilderFlags | extra_font_builder_flags; LoadFlags = 0; if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0) @@ -222,40 +232,42 @@ namespace if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor) LoadFlags |= FT_LOAD_COLOR; - RasterizationDensity = src.RasterizerDensity; + RasterizationDensity = src->RasterizerDensity; InvRasterizationDensity = 1.0f / RasterizationDensity; memset(&Info, 0, sizeof(Info)); - SetPixelHeight((uint32_t)src.SizePixels); + SetPixelHeight(src->SizePixels); return true; } - void FreeTypeFont::CloseFont() + void ImGui_ImplFreeType_FontSrcData::CloseFont() { - if (Face) + if (FtFace) { - FT_Done_Face(Face); - Face = nullptr; + FT_Done_Face(FtFace); + FtFace = nullptr; } } - void FreeTypeFont::SetPixelHeight(int pixel_height) + void ImGui_ImplFreeType_FontSrcData::SetPixelHeight(float pixel_height) { - // Vuhdo: I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height' + // Vuhdo (2017): "I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height' // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me. - // NB: FT_Set_Pixel_Sizes() doesn't seem to get us the same result. + // FT_Set_Pixel_Sizes() doesn't seem to get us the same result." + // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL) FT_Size_RequestRec req; req.type = (UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; req.width = 0; req.height = (uint32_t)(pixel_height * 64 * RasterizationDensity); req.horiResolution = 0; req.vertResolution = 0; - FT_Request_Size(Face, &req); + FT_Request_Size(FtFace, &req); + // Note: To handle multiple sizes later, we may need to use FT_New_Size(), FT_Activate_Size() // Update font info - FT_Size_Metrics metrics = Face->size->metrics; - Info.PixelHeight = (uint32_t)(pixel_height * InvRasterizationDensity); + FT_Size_Metrics metrics = FtFace->size->metrics; + Info.PixelHeight = pixel_height * InvRasterizationDensity; Info.Ascender = (float)FT_CEIL(metrics.ascender) * InvRasterizationDensity; Info.Descender = (float)FT_CEIL(metrics.descender) * InvRasterizationDensity; Info.LineSpacing = (float)FT_CEIL(metrics.height) * InvRasterizationDensity; @@ -263,9 +275,9 @@ namespace Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * InvRasterizationDensity; } - const FT_Glyph_Metrics* FreeTypeFont::LoadGlyph(uint32_t codepoint) + const FT_Glyph_Metrics* ImGui_ImplFreeType_FontSrcData::LoadGlyph(uint32_t codepoint) { - uint32_t glyph_index = FT_Get_Char_Index(Face, codepoint); + uint32_t glyph_index = FT_Get_Char_Index(FtFace, codepoint); if (glyph_index == 0) return nullptr; @@ -274,12 +286,12 @@ namespace // - https://github.com/ocornut/imgui/issues/4567 // - https://github.com/ocornut/imgui/issues/4566 // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. - FT_Error error = FT_Load_Glyph(Face, glyph_index, LoadFlags); + FT_Error error = FT_Load_Glyph(FtFace, glyph_index, LoadFlags); if (error) return nullptr; // Need an outline for this to work - FT_GlyphSlot slot = Face->glyph; + FT_GlyphSlot slot = FtFace->glyph; #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG) IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG); #else @@ -304,25 +316,25 @@ namespace return &slot->metrics; } - const FT_Bitmap* FreeTypeFont::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info) + const FT_Bitmap* ImGui_ImplFreeType_FontSrcData::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info) { - FT_GlyphSlot slot = Face->glyph; + FT_GlyphSlot slot = FtFace->glyph; FT_Error error = FT_Render_Glyph(slot, RenderMode); if (error != 0) return nullptr; - FT_Bitmap* ft_bitmap = &Face->glyph->bitmap; + FT_Bitmap* ft_bitmap = &FtFace->glyph->bitmap; out_glyph_info->Width = (int)ft_bitmap->width; out_glyph_info->Height = (int)ft_bitmap->rows; - out_glyph_info->OffsetX = Face->glyph->bitmap_left; - out_glyph_info->OffsetY = -Face->glyph->bitmap_top; + out_glyph_info->OffsetX = FtFace->glyph->bitmap_left; + out_glyph_info->OffsetY = -FtFace->glyph->bitmap_top; out_glyph_info->AdvanceX = (float)slot->advance.x / FT_SCALEFACTOR; out_glyph_info->IsColored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); return ft_bitmap; } - void FreeTypeFont::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table) + void ImGui_ImplFreeType_FontSrcData::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table) { IM_ASSERT(ft_bitmap != nullptr); const uint32_t w = ft_bitmap->width; @@ -398,6 +410,8 @@ namespace } } // namespace +#if 0 + #ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) #ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION #define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0) @@ -764,6 +778,7 @@ bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, u return true; } +#endif // FreeType memory allocation callbacks static void* FreeType_Alloc(FT_Memory /*memory*/, long size) @@ -799,47 +814,189 @@ static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size return block; } -static bool ImFontAtlasBuildWithFreeType(ImFontAtlas* atlas) +bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas) { + IM_ASSERT(atlas->FontLoaderData == NULL); + ImGui_ImplFreeType_Data* bd = IM_NEW(ImGui_ImplFreeType_Data)(); + // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html - FT_MemoryRec_ memory_rec = {}; - memory_rec.user = nullptr; - memory_rec.alloc = &FreeType_Alloc; - memory_rec.free = &FreeType_Free; - memory_rec.realloc = &FreeType_Realloc; + bd->MemoryManager.user = nullptr; + bd->MemoryManager.alloc = &FreeType_Alloc; + bd->MemoryManager.free = &FreeType_Free; + bd->MemoryManager.realloc = &FreeType_Realloc; // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library - FT_Library ft_library; - FT_Error error = FT_New_Library(&memory_rec, &ft_library); + FT_Error error = FT_New_Library(&bd->MemoryManager, &bd->Library); if (error != 0) + { + IM_DELETE(bd); return false; + } // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator. - FT_Add_Default_Modules(ft_library); + FT_Add_Default_Modules(bd->Library); #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG // Install svg hooks for FreeType // https://freetype.org/freetype2/docs/reference/ft2-properties.html#svg-hooks // https://freetype.org/freetype2/docs/reference/ft2-svg_fonts.html#svg_fonts SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot }; - FT_Property_Set(ft_library, "ot-svg", "svg-hooks", &hooks); + FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", &hooks); #endif // IMGUI_ENABLE_FREETYPE_LUNASVG #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG // With plutosvg, use provided hooks - FT_Property_Set(ft_library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks()); + FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks()); #endif // IMGUI_ENABLE_FREETYPE_PLUTOSVG - bool ret = ImFontAtlasBuildWithFreeTypeEx(ft_library, atlas, atlas->FontBuilderFlags); - FT_Done_Library(ft_library); + // Store our data + atlas->FontLoaderData = (void*)bd; - return ret; + return true; } -const ImFontBuilderIO* ImGuiFreeType::GetBuilderForFreeType() +void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas) { - static ImFontBuilderIO io; - io.FontBuilder_Build = ImFontAtlasBuildWithFreeType; - return &io; + ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData; + IM_ASSERT(bd != NULL); + FT_Done_Library(bd->Library); + IM_DELETE(bd); + atlas->FontLoaderData = NULL; +} + +bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) +{ + ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData; + ImGui_ImplFreeType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplFreeType_FontSrcData); + IM_ASSERT(src->FontLoaderData == NULL); + src->FontLoaderData = bd_font_data; + + if (!bd_font_data->InitFont(bd->Library, src, atlas->FontBuilderFlags)) + return false; + + if (src->MergeMode == false) + { + ImFont* font = src->DstFont; + font->Ascent = bd_font_data->Info.Ascender; + font->Descent = bd_font_data->Info.Descender; + } + return true; +} + +void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + IM_DELETE(bd_font_data); + src->FontLoaderData = NULL; +} + +bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) +{ + // Search for first font which has the glyph + ImGui_ImplFreeType_FontSrcData* bd_font_data = NULL; + ImFontConfig* src = NULL; + uint32_t glyph_index = 0; + for (int src_n = 0; src_n < srcs_count; src_n++) + { + src = &srcs[src_n]; + bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); + if (glyph_index != 0) + break; + } + if (glyph_index == 0) + return false; // Not found + + const FT_Glyph_Metrics* metrics = bd_font_data->LoadGlyph(codepoint); + if (metrics == NULL) + return false; + + // Render glyph into a bitmap (currently held by FreeType) + FT_Face face = bd_font_data->FtFace; + FT_GlyphSlot slot = face->glyph; + FT_Error error = FT_Render_Glyph(slot, bd_font_data->RenderMode); + if (error != 0) + return false; + + const FT_Bitmap* ft_bitmap = &slot->bitmap; + if (ft_bitmap == nullptr) + return false; + + const int w = (int)ft_bitmap->width; + const int h = (int)ft_bitmap->rows; + const bool is_visible = (w != 0 && h != 0); + + // Prepare glyph + ImFontGlyph glyph = {}; + glyph.Codepoint = codepoint; + glyph.AdvanceX = (slot->advance.x / FT_SCALEFACTOR) * bd_font_data->InvRasterizationDensity; + + // Pack and retrieve position inside texture atlas + if (is_visible) + { + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + font->MetricsTotalSurface += w * h; + + // Render pixels to our temporary buffer + atlas->Builder->TempBuffer.resize(w * h * 4); + uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data; + bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w, nullptr);// multiply_enabled ? multiply_table : nullptr); + + float font_off_x = src->GlyphOffset.x; + float font_off_y = src->GlyphOffset.y + IM_ROUND(font->Ascent); + float recip_h = 1.0f / src->RasterizerDensity; + float recip_v = 1.0f / src->RasterizerDensity; + + // Register glyph + float glyph_off_x = (float)face->glyph->bitmap_left; + float glyph_off_y = (float)-face->glyph->bitmap_top; + glyph.X0 = glyph_off_x * recip_h + font_off_x; + glyph.Y0 = glyph_off_y * recip_v + font_off_y; + glyph.X1 = (glyph_off_x + w) * recip_h + font_off_x; + glyph.Y1 = (glyph_off_y + h) * recip_v + font_off_y; + glyph.U0 = (r->x) * atlas->TexUvScale.x; + glyph.V0 = (r->y) * atlas->TexUvScale.y; + glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + glyph.PackId = pack_id; + glyph.Visible = true; + glyph.Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); + font->BuildRegisterGlyph(src, &glyph); + + // Copy to texture, post-process and queue update for backend + ImTextureData* tex = atlas->TexData; + IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); + ImFontAtlasTextureBlockConvertAndPostProcess(atlas, font, src, &font->Glyphs.back(), + temp_buffer, ImTextureFormat_RGBA32, w * 4, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); + } + else + { + font->BuildRegisterGlyph(src, &glyph); + } + return true; +} + +bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) +{ + IM_UNUSED(atlas); + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + int glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); + return glyph_index != 0; +} + +const ImFontLoader* ImGuiFreeType::GetFontLoader() +{ + static ImFontLoader loader; + loader.Name = "freetype"; + loader.LoaderInit = ImGui_ImplFreeType_LoaderInit; + loader.LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown; + loader.FontSrcInit = ImGui_ImplFreeType_FontSrcInit; + loader.FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy; + loader.FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph; + loader.FontAddGlyph = ImGui_ImplFreeType_FontAddGlyph; + return &loader; } void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data) diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index 9d367074e..2d7b3a34f 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -14,7 +14,7 @@ // Forward declarations struct ImFontAtlas; -struct ImFontBuilderIO; +struct ImFontLoader; // Hinting greatly impacts visuals (and glyph sizes). // - By default, hinting is enabled and the font's native hinter is preferred over the auto-hinter. @@ -41,9 +41,9 @@ namespace ImGuiFreeType { // This is automatically assigned when using '#define IMGUI_ENABLE_FREETYPE'. // If you need to dynamically select between multiple builders: - // - you can manually assign this builder with 'atlas->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()' - // - prefer deep-copying this into your own ImFontBuilderIO instance if you use hot-reloading that messes up static data. - IMGUI_API const ImFontBuilderIO* GetBuilderForFreeType(); + // - you can manually assign this builder with 'atlas->FontLoader = ImGuiFreeType::GetFontLoader()' + // - prefer deep-copying this into your own ImFontLoader instance if you use hot-reloading that messes up static data. + IMGUI_API const ImFontLoader* GetFontLoader(); // Override allocators. By default ImGuiFreeType will use IM_ALLOC()/IM_FREE() // However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired. From 1269467fa0789c927c70c4013d5ed5477b1ec49c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 28 Nov 2024 15:27:17 +0100 Subject: [PATCH 0907/2359] imgui_freetype: Removing old code. --- misc/freetype/imgui_freetype.cpp | 454 +------------------------------ 1 file changed, 14 insertions(+), 440 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 1125364bf..a8dfa950e 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -142,24 +142,12 @@ namespace // | | // |------------- advanceX ----------->| - // A structure that describe a glyph. - struct GlyphInfo - { - int Width; // Glyph's width in pixels. - int Height; // Glyph's height in pixels. - FT_Int OffsetX; // The distance from the origin ("pen position") to the left of the glyph. - FT_Int OffsetY; // The distance from the origin to the top of the glyph. This is usually a value < 0. - float AdvanceX; // The distance from the origin to the origin of the next glyph. This is usually a value > 0. - bool IsColored; // The glyph is colored - }; - // Stored in ImFontAtlas::FontLoaderData struct ImGui_ImplFreeType_Data { - FT_Library Library; - FT_MemoryRec_ MemoryManager; - - ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } + FT_Library Library; + FT_MemoryRec_ MemoryManager; + ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Font parameters and metrics. @@ -180,8 +168,7 @@ namespace void CloseFont(); void SetPixelHeight(float pixel_height); // Change font pixel size. const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); - const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info); - void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr); + void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch); ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); } ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); } @@ -316,25 +303,7 @@ namespace return &slot->metrics; } - const FT_Bitmap* ImGui_ImplFreeType_FontSrcData::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info) - { - FT_GlyphSlot slot = FtFace->glyph; - FT_Error error = FT_Render_Glyph(slot, RenderMode); - if (error != 0) - return nullptr; - - FT_Bitmap* ft_bitmap = &FtFace->glyph->bitmap; - out_glyph_info->Width = (int)ft_bitmap->width; - out_glyph_info->Height = (int)ft_bitmap->rows; - out_glyph_info->OffsetX = FtFace->glyph->bitmap_left; - out_glyph_info->OffsetY = -FtFace->glyph->bitmap_top; - out_glyph_info->AdvanceX = (float)slot->advance.x / FT_SCALEFACTOR; - out_glyph_info->IsColored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); - - return ft_bitmap; - } - - void ImGui_ImplFreeType_FontSrcData::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table) + void ImGui_ImplFreeType_FontSrcData::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch) { IM_ASSERT(ft_bitmap != nullptr); const uint32_t w = ft_bitmap->width; @@ -346,24 +315,13 @@ namespace { case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel. { - if (multiply_table == nullptr) - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - for (uint32_t x = 0; x < w; x++) - dst[x] = IM_COL32(255, 255, 255, src[x]); - } - else - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - for (uint32_t x = 0; x < w; x++) - dst[x] = IM_COL32(255, 255, 255, multiply_table[src[x]]); - } + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + for (uint32_t x = 0; x < w; x++) + dst[x] = IM_COL32(255, 255, 255, src[x]); break; } case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB. { - uint8_t color0 = multiply_table ? multiply_table[0] : 0; - uint8_t color1 = multiply_table ? multiply_table[255] : 255; for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) { uint8_t bits = 0; @@ -372,7 +330,7 @@ namespace { if ((x & 7) == 0) bits = *bits_ptr++; - dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? color1 : color0); + dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? 255 : 0); } } break; @@ -381,26 +339,12 @@ namespace { // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u) - if (multiply_table == nullptr) - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - for (uint32_t x = 0; x < w; x++) - { - uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3]; - dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a); - } - } - else - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + for (uint32_t x = 0; x < w; x++) { - for (uint32_t x = 0; x < w; x++) - { - uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3]; - dst[x] = IM_COL32(multiply_table[DE_MULTIPLY(r, a)], multiply_table[DE_MULTIPLY(g, a)], multiply_table[DE_MULTIPLY(b, a)], multiply_table[a]); - } + uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3]; + dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a); } - } #undef DE_MULTIPLY break; } @@ -410,376 +354,6 @@ namespace } } // namespace -#if 0 - -#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) -#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION -#define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0) -#define STBRP_STATIC -#define STB_RECT_PACK_IMPLEMENTATION -#endif -#ifdef IMGUI_STB_RECT_PACK_FILENAME -#include IMGUI_STB_RECT_PACK_FILENAME -#else -#include "imstb_rectpack.h" -#endif -#endif - -struct ImFontBuildSrcGlyphFT -{ - GlyphInfo Info; - uint32_t Codepoint; - unsigned int* BitmapData; // Point within one of the dst_tmp_bitmap_buffers[] array - - ImFontBuildSrcGlyphFT() { memset((void*)this, 0, sizeof(*this)); } -}; - -struct ImFontBuildSrcDataFT -{ - FreeTypeFont Font; - stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position. - const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF) - int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[] - int GlyphsHighest; // Highest requested codepoint - int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font) - ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB) - ImVector GlyphsList; -}; - -// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont) -struct ImFontBuildDstDataFT -{ - int SrcCount; // Number of source fonts targeting this destination font. - int GlyphsHighest; - int GlyphsCount; - ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font. -}; - -bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags) -{ - IM_ASSERT(atlas->Sources.Size > 0); - - ImFontAtlasBuildInit(atlas); - - // Clear atlas - atlas->TexID._TexID = 0; - atlas->TexWidth = atlas->TexHeight = 0; - atlas->TexUvScale = ImVec2(0.0f, 0.0f); - atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); - atlas->ClearTexData(); - - // Temporary storage for building - bool src_load_color = false; - ImVector src_tmp_array; - ImVector dst_tmp_array; - src_tmp_array.resize(atlas->Sources.Size); - dst_tmp_array.resize(atlas->Fonts.Size); - memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); - memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes()); - - // 1. Initialize font loading structure, check font data validity - for (int src_i = 0; src_i < atlas->Sources.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - ImFontConfig& src = atlas->Sources[src_i]; - FreeTypeFont& font_face = src_tmp.Font; - IM_ASSERT(src.DstFont && (!src.DstFont->IsLoaded() || src.DstFont->ContainerAtlas == atlas)); - - // Find index from src.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) - src_tmp.DstIndex = -1; - for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++) - if (src.DstFont == atlas->Fonts[output_i]) - src_tmp.DstIndex = output_i; - IM_ASSERT(src_tmp.DstIndex != -1); // src.DstFont not pointing within atlas->Fonts[] array? - if (src_tmp.DstIndex == -1) - return false; - - // Load font - if (!font_face.InitFont(ft_library, src, extra_flags)) - return false; - - // Measure highest codepoints - src_load_color |= (src.FontBuilderFlags & ImGuiFreeTypeBuilderFlags_LoadColor) != 0; - ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.SrcRanges = src.GlyphRanges ? src.GlyphRanges : atlas->GetGlyphRangesDefault(); - for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) - { - // Check for valid range. This may also help detect *some* dangling pointers, because a common - // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent, - // or to forget to zero-terminate the glyph range array. - IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?"); - src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]); - } - dst_tmp.SrcCount++; - dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest); - } - - // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs. - int total_glyphs_count = 0; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1); - if (dst_tmp.GlyphsSet.Storage.empty()) - dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1); - - for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) - for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++) - { - if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite) - continue; - uint32_t glyph_index = FT_Get_Char_Index(src_tmp.Font.Face, codepoint); // It is actually in the font? (FIXME-OPT: We are not storing the glyph_index..) - if (glyph_index == 0) - continue; - - // Add to avail set/counters - src_tmp.GlyphsCount++; - dst_tmp.GlyphsCount++; - src_tmp.GlyphsSet.SetBit(codepoint); - dst_tmp.GlyphsSet.SetBit(codepoint); - total_glyphs_count++; - } - } - - // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another) - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount); - - IM_ASSERT(sizeof(src_tmp.GlyphsSet.Storage.Data[0]) == sizeof(ImU32)); - const ImU32* it_begin = src_tmp.GlyphsSet.Storage.begin(); - const ImU32* it_end = src_tmp.GlyphsSet.Storage.end(); - for (const ImU32* it = it_begin; it < it_end; it++) - if (ImU32 entries_32 = *it) - for (ImU32 bit_n = 0; bit_n < 32; bit_n++) - if (entries_32 & ((ImU32)1 << bit_n)) - { - ImFontBuildSrcGlyphFT src_glyph; - src_glyph.Codepoint = (ImWchar)(((it - it_begin) << 5) + bit_n); - //src_glyph.GlyphIndex = 0; // FIXME-OPT: We had this info in the previous step and lost it.. - src_tmp.GlyphsList.push_back(src_glyph); - } - src_tmp.GlyphsSet.Clear(); - IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount); - } - for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++) - dst_tmp_array[dst_i].GlyphsSet.Clear(); - dst_tmp_array.clear(); - - // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) - // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity) - ImVector buf_rects; - buf_rects.resize(total_glyphs_count); - memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes()); - - // Allocate temporary rasterization data buffers. - // We could not find a way to retrieve accurate glyph size without rendering them. - // (e.g. slot->metrics->width not always matching bitmap->width, especially considering the Oblique transform) - // We allocate in chunks of 256 KB to not waste too much extra memory ahead. Hopefully users of FreeType won't mind the temporary allocations. - const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024; - int buf_bitmap_current_used_bytes = 0; - ImVector buf_bitmap_buffers; - buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE)); - - // 4. Gather glyphs sizes so we can pack them in our virtual canvas. - // 8. Render/rasterize font characters into the texture - int total_surface = 0; - int buf_rects_out_n = 0; - const int pack_padding = atlas->TexGlyphPadding; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - ImFontConfig& src = atlas->Sources[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - src_tmp.Rects = &buf_rects[buf_rects_out_n]; - buf_rects_out_n += src_tmp.GlyphsCount; - - // Compute multiply table if requested - const bool multiply_enabled = (src.RasterizerMultiply != 1.0f); - unsigned char multiply_table[256]; - if (multiply_enabled) - ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, src.RasterizerMultiply); - - // Gather the sizes of all rectangles we will need to pack - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) - { - ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i]; - - const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint); - if (metrics == nullptr) - continue; - - // Render glyph into a bitmap (currently held by FreeType) - const FT_Bitmap* ft_bitmap = src_tmp.Font.RenderGlyphAndGetInfo(&src_glyph.Info); - if (ft_bitmap == nullptr) - continue; - - // Allocate new temporary chunk if needed - const int bitmap_size_in_bytes = src_glyph.Info.Width * src_glyph.Info.Height * 4; - if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE) - { - buf_bitmap_current_used_bytes = 0; - buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE)); - } - IM_ASSERT(buf_bitmap_current_used_bytes + bitmap_size_in_bytes <= BITMAP_BUFFERS_CHUNK_SIZE); // We could probably allocate custom-sized buffer instead. - - // Blit rasterized pixels to our temporary buffer and keep a pointer to it. - src_glyph.BitmapData = (unsigned int*)(buf_bitmap_buffers.back() + buf_bitmap_current_used_bytes); - buf_bitmap_current_used_bytes += bitmap_size_in_bytes; - src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width, multiply_enabled ? multiply_table : nullptr); - - src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + pack_padding); - src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + pack_padding); - total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h; - } - } - for (int i = 0; i < atlas->CustomRects.Size; i++) - total_surface += (atlas->CustomRects[i].Width + pack_padding) * (atlas->CustomRects[i].Height + pack_padding); - - // We need a width for the skyline algorithm, any width! - // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height. - // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface. - const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1; - atlas->TexHeight = 0; - if (atlas->TexDesiredWidth > 0) - atlas->TexWidth = atlas->TexDesiredWidth; - else - atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512; - - // 5. Start packing - // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). - const int TEX_HEIGHT_MAX = 1024 * 32; - const int num_nodes_for_packing_algorithm = atlas->TexWidth - atlas->TexGlyphPadding; - ImVector pack_nodes; - pack_nodes.resize(num_nodes_for_packing_algorithm); - stbrp_context pack_context; - stbrp_init_target(&pack_context, atlas->TexWidth - atlas->TexGlyphPadding, TEX_HEIGHT_MAX - atlas->TexGlyphPadding, pack_nodes.Data, pack_nodes.Size); - ImFontAtlasBuildPackCustomRects(atlas, &pack_context); - - // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point. - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - stbrp_pack_rects(&pack_context, src_tmp.Rects, src_tmp.GlyphsCount); - - // Extend texture height and mark missing glyphs as non-packed so we won't render them. - // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?) - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) - if (src_tmp.Rects[glyph_i].was_packed) - atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h); - } - - // 7. Allocate texture - atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); - atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); - if (src_load_color) - { - size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 4; - atlas->TexPixelsRGBA32 = (unsigned int*)IM_ALLOC(tex_size); - memset(atlas->TexPixelsRGBA32, 0, tex_size); - } - else - { - size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 1; - atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(tex_size); - memset(atlas->TexPixelsAlpha8, 0, tex_size); - } - - // 8. Copy rasterized font characters back into the main texture - // 9. Setup ImFont and glyphs for runtime - bool tex_use_colors = false; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - - // When merging fonts with MergeMode=true: - // - We can have multiple input fonts writing into a same destination font. - // - dst_font->Sources is != from src which is our source configuration. - ImFontConfig& src = atlas->Sources[src_i]; - ImFont* dst_font = src.DstFont; - - const float ascent = src_tmp.Font.Info.Ascender; - const float descent = src_tmp.Font.Info.Descender; - ImFontAtlasBuildSetupFont(atlas, dst_font, &src, ascent, descent); - - if (src_tmp.GlyphsCount == 0) - continue; - const float font_off_x = src.GlyphOffset.x; - const float font_off_y = src.GlyphOffset.y + IM_ROUND(dst_font->Ascent); - - const int padding = atlas->TexGlyphPadding; - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) - { - ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i]; - stbrp_rect& pack_rect = src_tmp.Rects[glyph_i]; - IM_ASSERT(pack_rect.was_packed); - if (pack_rect.w == 0 && pack_rect.h == 0) - continue; - - GlyphInfo& info = src_glyph.Info; - IM_ASSERT(info.Width + padding <= pack_rect.w); - IM_ASSERT(info.Height + padding <= pack_rect.h); - const int tx = pack_rect.x + padding; - const int ty = pack_rect.y + padding; - - // Register glyph - float x0 = info.OffsetX * src_tmp.Font.InvRasterizationDensity + font_off_x; - float y0 = info.OffsetY * src_tmp.Font.InvRasterizationDensity + font_off_y; - float x1 = x0 + info.Width * src_tmp.Font.InvRasterizationDensity; - float y1 = y0 + info.Height * src_tmp.Font.InvRasterizationDensity; - float u0 = (tx) / (float)atlas->TexWidth; - float v0 = (ty) / (float)atlas->TexHeight; - float u1 = (tx + info.Width) / (float)atlas->TexWidth; - float v1 = (ty + info.Height) / (float)atlas->TexHeight; - dst_font->AddGlyph(&src, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX * src_tmp.Font.InvRasterizationDensity); - - ImFontGlyph* dst_glyph = &dst_font->Glyphs.back(); - IM_ASSERT(dst_glyph->Codepoint == src_glyph.Codepoint); - if (src_glyph.Info.IsColored) - dst_glyph->Colored = tex_use_colors = true; - - // Blit from temporary buffer to final texture - size_t blit_src_stride = (size_t)src_glyph.Info.Width; - size_t blit_dst_stride = (size_t)atlas->TexWidth; - unsigned int* blit_src = src_glyph.BitmapData; - if (atlas->TexPixelsAlpha8 != nullptr) - { - unsigned char* blit_dst = atlas->TexPixelsAlpha8 + (ty * blit_dst_stride) + tx; - for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride) - for (int x = 0; x < info.Width; x++) - blit_dst[x] = (unsigned char)((blit_src[x] >> IM_COL32_A_SHIFT) & 0xFF); - } - else - { - unsigned int* blit_dst = atlas->TexPixelsRGBA32 + (ty * blit_dst_stride) + tx; - for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride) - for (int x = 0; x < info.Width; x++) - blit_dst[x] = blit_src[x]; - } - } - - src_tmp.Rects = nullptr; - } - atlas->TexPixelsUseColors = tex_use_colors; - - // Cleanup - for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++) - IM_FREE(buf_bitmap_buffers[buf_i]); - src_tmp_array.clear_destruct(); - - ImFontAtlasBuildFinish(atlas); - - return true; -} -#endif - // FreeType memory allocation callbacks static void* FreeType_Alloc(FT_Memory /*memory*/, long size) { @@ -941,7 +515,7 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon // Render pixels to our temporary buffer atlas->Builder->TempBuffer.resize(w * h * 4); uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data; - bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w, nullptr);// multiply_enabled ? multiply_table : nullptr); + bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w); float font_off_x = src->GlyphOffset.x; float font_off_y = src->GlyphOffset.y + IM_ROUND(font->Ascent); From 0f553c57bd130cbb3207ec493583030c1044bd97 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Nov 2024 14:28:16 +0100 Subject: [PATCH 0908/2359] Fonts: AddFont() actually does the work, so we can handle errors & return an accurate return value. --- imgui.h | 1 + imgui_draw.cpp | 51 +++++++++++++++++++++++++++++++++++++------------- 2 files changed, 39 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index c95f5ac57..8161fb4b4 100644 --- a/imgui.h +++ b/imgui.h @@ -3529,6 +3529,7 @@ struct ImFontAtlas IMGUI_API void Clear(); // Clear all input and output. IMGUI_API void ClearCache(); // Clear cached glyphs + IMGUI_API void BuildInit(); // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0bde7a116..3a9290296 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2887,6 +2887,10 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); IM_ASSERT(font_cfg->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); + // Lazily create builder on the first call to AddFont + if (Builder == NULL) + BuildInit(); + // Create new font if (!font_cfg->MergeMode) Fonts.push_back(IM_NEW(ImFont)); @@ -2912,9 +2916,19 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) // Pointers to Sources are otherwise dangling ImFontAtlasBuildUpdatePointers(this); - - if (Builder != NULL) - ImFontAtlasBuildAddFont(this, &new_font_cfg); + if (!ImFontAtlasBuildAddFont(this, &new_font_cfg)) + { + // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) + if (new_font_cfg.FontDataOwnedByAtlas) + IM_FREE(new_font_cfg.FontData); + Sources.pop_back(); + if (!font_cfg->MergeMode) + { + IM_DELETE(Fonts.back()); + Fonts.pop_back(); + } + return NULL; + } // Invalidate texture //TexReady = false; @@ -3105,14 +3119,8 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso return true; } -bool ImFontAtlas::Build() +void ImFontAtlas::BuildInit() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - - // Default font is none are specified - if (Sources.Size == 0) - AddFontDefault(); - // Select builder // - Note that we do not reassign to atlas->FontLoader, since it is likely to point to static data which // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are @@ -3132,6 +3140,18 @@ bool ImFontAtlas::Build() // Create initial texture size ImFontAtlasBuildAddTexture(this, 512, 128); ImFontAtlasBuildInit(this); +} + +bool ImFontAtlas::Build() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + + if (Builder == NULL) + BuildInit(); + + // Default font is none are specified + if (Sources.Size == 0) + AddFontDefault(); // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs ImFontAtlasBuildUpdateRendererHasTexturesFromContext(this); @@ -3384,7 +3404,7 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) const ImFontLoader* font_loader = atlas->FontLoader; if (!font_loader->FontSrcInit(atlas, src)) - return false; // FIXME-NEWATLAS: error handling + return false; ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, src); return true; @@ -3887,10 +3907,14 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* // Initialize helper structure for font loading and verify that the TTF/OTF data is correct const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src->FontData, src->FontNo); - IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); // FIXME-NEWATLAS: error handling + if (font_offset < 0) + { + IM_ASSERT_USER_ERROR(0, "stbtt_GetFontOffsetForIndex(): FontData is incorrect, or FontNo cannot be found."); + return false; + } if (!stbtt_InitFont(&bd_font_data->FontInfo, (unsigned char*)src->FontData, font_offset)) { - IM_ASSERT(0 && "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); + IM_ASSERT_USER_ERROR(0, "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); return false; } src->FontLoaderData = bd_font_data; @@ -3954,6 +3978,7 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, { src = &srcs[src_n]; bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_ASSERT(bd_font_data); glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); if (glyph_index != 0) break; From b670f799d5e3078477843a044e6fb99a383bbf6f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Nov 2024 15:16:22 +0100 Subject: [PATCH 0909/2359] Fonts: use TexGlyphPadding. Fixed packing issues. Removed old code. --- imgui_draw.cpp | 51 +++++++++++++----------------------------------- imgui_internal.h | 3 +-- 2 files changed, 15 insertions(+), 39 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3a9290296..089fc0c5d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3582,7 +3582,6 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. -#if 1 // Repack + copy pixels // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic. ImFontAtlasPackInit(atlas); @@ -3623,27 +3622,6 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) ImFontAtlasBuildUpdateLinesTexData(atlas, false); ImFontAtlasBuildUpdateBasicTexData(atlas, false); -#else - // Copy previous pixels - ImFontAtlasTextureCopyBlock(atlas, old_tex, 0, 0, new_tex, 0, 0, ImMin(old_tex->Width, new_tex->Width), ImMin(old_tex->Height, new_tex->Height)); - - // Scale UV coordinates - // FIXME-NEWATLAS: Probably lossy? - ImVec2 uv_scale((float)old_tex->Width / new_tex->Width, (float)old_tex->Height / new_tex->Height); - for (ImFont* font : atlas->Fonts) - for (ImFontGlyph& glyph : font->Glyphs) - { - glyph.U0 *= uv_scale.x; - glyph.U1 *= uv_scale.x; - glyph.V0 *= uv_scale.y; - glyph.V1 *= uv_scale.y; - } - ImVec4 uv_scale4(uv_scale.x, uv_scale.y, uv_scale.x, uv_scale.y); - atlas->TexUvWhitePixel *= uv_scale; - for (ImVec4& uv : atlas->TexUvLines) - uv = uv * uv_scale4; -#endif - builder->LockDisableResize = false; ImFontAtlasUpdateDrawListsSharedData(atlas); } @@ -3666,8 +3644,9 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ int new_tex_h = (old_tex_h < old_tex_w) ? old_tex_h * 2 : old_tex_h; // Handle minimum size first (for pathologically large packed rects) - new_tex_w = ImMax(new_tex_w, ImUpperPowerOfTwo(builder->MaxRectSize.x + builder->PackPadding)); - new_tex_h = ImMax(new_tex_h, ImUpperPowerOfTwo(builder->MaxRectSize.y + builder->PackPadding)); + const int pack_padding = atlas->TexGlyphPadding; + new_tex_w = ImMax(new_tex_w, ImUpperPowerOfTwo(builder->MaxRectSize.x + pack_padding)); + new_tex_h = ImMax(new_tex_h, ImUpperPowerOfTwo(builder->MaxRectSize.y + pack_padding)); ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); } @@ -3717,10 +3696,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) const bool builder_is_new = (builder == NULL); if (builder_is_new) - { builder = atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); - builder->PackPadding = 1; - } ImFontAtlasPackInit(atlas); @@ -3762,11 +3738,12 @@ void ImFontAtlasPackInit(ImFontAtlas* atlas) // FIXME-NEWATLAS-V2: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 // FIXME-NEWATLAS-V2: Experiment with number of nodes. 2024-11-05: Seems to be quite fine to reduce this. - int pack_node_count = tex->Width - builder->PackPadding; + //int pack_padding = atlas->TexGlyphPadding; + int pack_node_count = tex->Width; //pack_node_count *= atlas->_PackNodesFactor; builder->PackNodes.resize(pack_node_count); IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque)); - stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width - builder->PackPadding, tex->Height - builder->PackPadding, builder->PackNodes.Data, builder->PackNodes.Size); + stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width, tex->Height, builder->PackNodes.Data, builder->PackNodes.Size); atlas->_PackedSurface = atlas->_PackedRects = 0; builder->MaxRectSize = ImVec2i(0, 0); builder->MaxRectBounds = ImVec2i(0, 0); @@ -3779,6 +3756,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h) IM_ASSERT(h > 0 && h <= 0xFFFF); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + const int pack_padding = atlas->TexGlyphPadding; builder->MaxRectSize.x = ImMax(builder->MaxRectSize.x, w); builder->MaxRectSize.y = ImMax(builder->MaxRectSize.y, h); @@ -3788,11 +3766,11 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h) { // Try packing stbrp_rect pack_r = {}; - pack_r.w = r.w + builder->PackPadding; - pack_r.h = r.h + builder->PackPadding; + pack_r.w = w + pack_padding; + pack_r.h = h + pack_padding; stbrp_pack_rects((stbrp_context*)(void*)&builder->PackContext, &pack_r, 1); - r.x = (unsigned short)(pack_r.x + builder->PackPadding); - r.y = (unsigned short)(pack_r.y + builder->PackPadding); + r.x = (unsigned short)pack_r.x; + r.y = (unsigned short)pack_r.y; if (pack_r.was_packed) break; @@ -3809,9 +3787,9 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h) ImFontAtlasBuildGrowTexture(atlas); } - builder->MaxRectBounds.x = ImMax(builder->MaxRectBounds.x, r.x + r.w); - builder->MaxRectBounds.y = ImMax(builder->MaxRectBounds.y, r.y + r.h); - atlas->_PackedSurface += w * h; + builder->MaxRectBounds.x = ImMax(builder->MaxRectBounds.x, r.x + r.w + pack_padding); + builder->MaxRectBounds.y = ImMax(builder->MaxRectBounds.y, r.y + r.h + pack_padding); + atlas->_PackedSurface += (w + pack_padding) * (h + pack_padding); atlas->_PackedRects++; builder->Rects.push_back(r); @@ -3986,7 +3964,6 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, if (glyph_index == 0) return false; // Not found - // FIXME-NEWATLAS: Handling of atlas->TexGlyphPadding? const float scale_for_layout = bd_font_data->ScaleForLayout; // ~ (font units to pixels) const float scale_for_raster_x = bd_font_data->ScaleForRasterX; // ~ (font units to pixels) * RasterizationDensity * OversampleH const float scale_for_raster_y = bd_font_data->ScaleForRasterY; // ~ (font units to pixels) * RasterizationDensity * OversampleV diff --git a/imgui_internal.h b/imgui_internal.h index 27d1ca8e1..4e8384bee 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3654,10 +3654,9 @@ struct ImFontAtlasBuilder { stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file. ImVector PackNodes; - int PackPadding; // Generally 1 to avoid bilinear filtering issues. ImVector Rects; ImVector TempBuffer; // Misc scratch buffer - ImVec2i MaxRectSize; // Largest rectangle to pack (defacto used as a "minimum texture size") + 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. From 4f27792ffeffa2a922cc6e188a19c08506476fe7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Nov 2024 17:22:33 +0100 Subject: [PATCH 0910/2359] (Breaking) Removed atlas->TexDesiredWidth now unnecessary (github 327) --- docs/FONTS.md | 1 - imgui.h | 1 + imgui_draw.cpp | 5 ++--- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index e9fbcbe42..514af0799 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -60,7 +60,6 @@ Some solutions: - Reduce glyphs ranges by calculating them from source localization data. You can use the `ImFontGlyphRangesBuilder` for this purpose and rebuilding your atlas between frames when new characters are needed. This will be the biggest win! - Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. -- Set `io.Fonts.TexDesiredWidth` to specify a texture width to reduce maximum texture height (see comment in `ImFontAtlas::Build()` function). Future versions of Dear ImGui should solve this problem. diff --git a/imgui.h b/imgui.h index 8161fb4b4..7a57732e6 100644 --- a/imgui.h +++ b/imgui.h @@ -3626,6 +3626,7 @@ struct ImFontAtlas float _PackNodesFactor = 1.0f; // [Obsolete] + //int TexDesiredWidth; // OBSOLETED in 1.91.5 (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 089fc0c5d..a15bf0a60 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3634,9 +3634,8 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ if (old_tex_h == -1) old_tex_h = atlas->TexData->Height; - // FIXME-NEWATLAS-V1: Handle atlas->TexDesiredWidth from user? - // FIXME-NEWATLAS-V1: What to do when reaching limits exposed by backend? - // FIXME-NEWATLAS-V1: does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? + // FIXME-NEWATLAS-V2: What to do when reaching limits exposed by backend? + // FIXME-NEWATLAS-V2: does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h)); // Grow texture so it follows roughly a square. From 43cc3fc8b1a426cdf5cfa9a420c670ca3526ede6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Nov 2024 17:34:52 +0100 Subject: [PATCH 0911/2359] Fonts: optimization bake FallbackAdvanceX into IndexAdvanceX[]. --- imgui_draw.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a15bf0a60..c461accde 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3820,7 +3820,7 @@ ImFontGlyph* ImFont::BuildLoadGlyph(ImWchar codepoint) { // Mark index as not found, so we don't attempt the search twice BuildGrowIndex(codepoint + 1); - IndexAdvanceX[codepoint] = (float)IM_FONTGLYPH_INDEX_NOT_FOUND; + IndexAdvanceX[codepoint] = FallbackAdvanceX; IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; return NULL; } @@ -4546,11 +4546,10 @@ float ImFont::GetCharAdvance(ImWchar c) { if (c < (size_t)IndexAdvanceX.Size) { + // Missing glyphs fitting inside index will have stored FallbackAdvanceX already. const float x = IndexAdvanceX.Data[c]; if (x >= 0.0f) return x; - if (x == (float)IM_FONTGLYPH_INDEX_NOT_FOUND) // FIXME-NEWATLAS: could bake in index - return FallbackAdvanceX; } const ImFontGlyph* glyph = BuildLoadGlyph(c); return glyph ? glyph->AdvanceX : FallbackAdvanceX; From ac13683c269fb0d77635c6f7328ea0d13ec757a2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Dec 2024 21:07:26 +0100 Subject: [PATCH 0912/2359] Fonts: ImFontAtlas accept DrawListSharedData not being set. --- imgui_draw.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c461accde..ae63798f9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2629,8 +2629,11 @@ void ImFontAtlas::ClearFonts() ClearInputData(); Fonts.clear_delete(); TexIsBuilt = false; - DrawListSharedData->Font = NULL; - DrawListSharedData->FontScale = DrawListSharedData->FontSize = 0.0f; + if (DrawListSharedData) + { + DrawListSharedData->Font = NULL; + DrawListSharedData->FontScale = DrawListSharedData->FontSize = 0.0f; + } } void ImFontAtlas::Clear() @@ -3155,7 +3158,7 @@ bool ImFontAtlas::Build() // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs ImFontAtlasBuildUpdateRendererHasTexturesFromContext(this); - if (DrawListSharedData->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures + if (DrawListSharedData && DrawListSharedData->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures ImFontAtlasBuildPreloadAllGlyphRanges(this); TexIsBuilt = true; @@ -3493,6 +3496,8 @@ void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedDat void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex) { ImDrawListSharedData* shared_data = atlas->DrawListSharedData; + if (shared_data == NULL) + return; for (ImDrawList* draw_list : shared_data->DrawLists) { // Replace in command-buffer @@ -3512,6 +3517,8 @@ void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) { ImDrawListSharedData* shared_data = atlas->DrawListSharedData; + if (shared_data == NULL) + return; shared_data->FontAtlas = atlas; shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; shared_data->TexUvLines = atlas->TexUvLines; From 076a1ab85cd0ad18b6c07fe08100c480f0cf3cf1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Dec 2024 16:43:46 +0100 Subject: [PATCH 0913/2359] Fonts: Misc amends, remove _PackNodesFactor, comments. --- imgui.h | 1 - imgui_draw.cpp | 9 +++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 7a57732e6..b733544ac 100644 --- a/imgui.h +++ b/imgui.h @@ -3623,7 +3623,6 @@ struct ImFontAtlas int RefCount; // Number of contexts using this atlas int _PackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. int _PackedRects; // Number of packed rectangles. - float _PackNodesFactor = 1.0f; // [Obsolete] //int TexDesiredWidth; // OBSOLETED in 1.91.5 (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ae63798f9..d100d7e08 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2579,7 +2579,6 @@ ImFontAtlas::ImFontAtlas() TexGlyphPadding = 1; TexRef._TexData = NULL;// this; TexNextUniqueID = 1; - _PackNodesFactor = 1.0f; Builder = NULL; } @@ -3742,11 +3741,8 @@ void ImFontAtlasPackInit(ImFontAtlas* atlas) ImTextureData* tex = atlas->TexData; ImFontAtlasBuilder* builder = atlas->Builder; - // FIXME-NEWATLAS-V2: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 - // FIXME-NEWATLAS-V2: Experiment with number of nodes. 2024-11-05: Seems to be quite fine to reduce this. - //int pack_padding = atlas->TexGlyphPadding; + // In theory we could decide to reduce the number of nodes, e.g. halve them, and waste a little texture space, but it doesn't seem worth it. int pack_node_count = tex->Width; - //pack_node_count *= atlas->_PackNodesFactor; builder->PackNodes.resize(pack_node_count); IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque)); stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width, tex->Height, builder->PackNodes.Data, builder->PackNodes.Size); @@ -3756,6 +3752,7 @@ void ImFontAtlasPackInit(ImFontAtlas* atlas) } // Important: Calling this may recreate a new texture and therefore change atlas->TexData +// FIXME-NEWATLAS-V2: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h) { IM_ASSERT(w > 0 && w <= 0xFFFF); @@ -3857,7 +3854,7 @@ void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) for (const ImTextureRect& r : tex->Updates) { IM_ASSERT(r.x >= 0 && r.y >= 0); - IM_ASSERT(r.x + r.w < tex->Width && r.y + r.h < tex->Height); + IM_ASSERT(r.x + r.w <= tex->Width && r.y + r.h <= tex->Height); // In theory should subtract PackPadding but it's currently part of atlas and mid-frame change would wreck assert. //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); } } From a6c78019266caf640bb8ddae7db60f42677b821a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Dec 2024 19:26:45 +0100 Subject: [PATCH 0914/2359] Fonts: Measured and tweaked CalcTextSize() computation to minimize cost in our stress tests. --- imgui_draw.cpp | 35 ++++++++++++++++++++++++++--------- imgui_widgets.cpp | 4 +--- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d100d7e08..c21925de5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3834,6 +3834,15 @@ ImFontGlyph* ImFont::BuildLoadGlyph(ImWchar codepoint) return glyph; } +// The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b +IM_MSVC_RUNTIME_CHECKS_OFF +static float BuildLoadGlyphGetAdvanceOrFallback(ImFont* font, unsigned int codepoint) +{ + ImFontGlyph* glyph = font->BuildLoadGlyph((ImWchar)codepoint); + return glyph ? glyph->AdvanceX : font->FallbackAdvanceX; +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + #ifndef IMGUI_DISABLE_DEBUG_TOOLS void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) { @@ -4546,18 +4555,23 @@ bool ImFont::IsGlyphInFont(ImWchar c) return false; } +// This is manually inlined in CalcTextSizeA() and CalcWordWrapPositionA(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). +IM_MSVC_RUNTIME_CHECKS_OFF float ImFont::GetCharAdvance(ImWchar c) { - if (c < (size_t)IndexAdvanceX.Size) + if ((int)c < IndexAdvanceX.Size) { // Missing glyphs fitting inside index will have stored FallbackAdvanceX already. const float x = IndexAdvanceX.Data[c]; if (x >= 0.0f) return x; } + + // Same as BuildLoadGlyphGetAdvanceOrFallback(): const ImFontGlyph* glyph = BuildLoadGlyph(c); return glyph ? glyph->AdvanceX : FallbackAdvanceX; } +IM_MSVC_RUNTIME_CHECKS_RESTORE // Trim trailing space and find beginning of next line static inline const char* CalcWordWrapNextLineStartA(const char* text, const char* text_end) @@ -4569,8 +4583,6 @@ static inline const char* CalcWordWrapNextLineStartA(const char* text, const cha return text; } -#define ImFontGetCharAdvanceX(_FONT, _CH) ((int)(_CH) < (_FONT)->IndexAdvanceX.Size ? (_FONT)->IndexAdvanceX.Data[_CH] : (_FONT)->FallbackAdvanceX) - // 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. // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) @@ -4624,9 +4636,11 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha } } - // FIXME-NEWATLAS-V1: Measure perf, inline etc. - //const float char_width = ImFontGetCharAdvanceX(this, c); - const float char_width = GetCharAdvance((ImWchar)c); // ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX); + // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' + float char_width = (c < (unsigned int)IndexAdvanceX.Size) ? IndexAdvanceX.Data[c] : -1.0f; + if (char_width < 0.0f) + char_width = BuildLoadGlyphGetAdvanceOrFallback(this, c); + if (ImCharIsBlankW(c)) { if (inside_word) @@ -4731,9 +4745,12 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons continue; } - // FIXME-NEWATLAS-V1: Measure perf, inline etc. - //const float char_width = ImFontGetCharAdvanceX(this, c) * scale; - const float char_width = GetCharAdvance((ImWchar)c) /* (int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX)*/ * scale; + // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' + float char_width = (c < (unsigned int)IndexAdvanceX.Size) ? IndexAdvanceX.Data[c] : -1.0f; + if (char_width < 0.0f) + char_width = BuildLoadGlyphGetAdvanceOrFallback(this, c); + char_width *= scale; + if (line_width + char_width >= max_width) { s = prev_s; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 186b639b5..47f6f7187 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3984,9 +3984,7 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c if (c == '\r') continue; - // FIXME-NEWATLAS-V1: Measure perf, inline etc. - const float char_width = font->GetCharAdvance((ImWchar)c) * scale;// ((int)c < font->IndexAdvanceX.Size ? font->IndexAdvanceX.Data[c] : font->FallbackAdvanceX)* scale; - line_width += char_width; + line_width += font->GetCharAdvance((ImWchar)c) * scale; } if (text_size.x < line_width) From 553b1c301df1c4ffbb9fe5c47bfa41ea86d750b6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Dec 2024 18:52:30 +0100 Subject: [PATCH 0915/2359] Fonts: repack without full reload, discard rectangle, fixed CustomRect api with stable id, remove public BuildInit(). --- imgui.h | 5 +- imgui_draw.cpp | 207 ++++++++++++++++++++++++++++++++++++----------- imgui_internal.h | 23 +++++- 3 files changed, 182 insertions(+), 53 deletions(-) diff --git a/imgui.h b/imgui.h index b733544ac..3013eb9e0 100644 --- a/imgui.h +++ b/imgui.h @@ -3529,7 +3529,6 @@ struct ImFontAtlas IMGUI_API void Clear(); // Clear all input and output. IMGUI_API void ClearCache(); // Clear cached glyphs - IMGUI_API void BuildInit(); // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). @@ -3583,7 +3582,7 @@ struct ImFontAtlas // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. IMGUI_API int AddCustomRectRegular(int width, int height); IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); - ImFontAtlasCustomRect* GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; } + IMGUI_API ImFontAtlasCustomRect* GetCustomRectByIndex(int index); // [Internal] IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; @@ -3608,8 +3607,8 @@ struct ImFontAtlas ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight) ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. - ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector Sources; // Source/configuration data + //ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines int TexNextUniqueID; // Next value to be stored in TexData->UniqueID ImDrawListSharedData* DrawListSharedData; // In principle this could become an array (e.g. multiple contexts using same atlas) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c21925de5..48f99cdf1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2606,7 +2606,7 @@ void ImFontAtlas::ClearInputData() font->SourcesCount = 0; } Sources.clear(); - CustomRects.clear(); + //CustomRects.clear(); // Important: we leave TexReady untouched } @@ -2646,6 +2646,7 @@ void ImFontAtlas::Clear() ImFontAtlasBuildSetupFontLoader(this, font_loader); } +// FIXME-NEWATLAS: Too widespread purpose. Clarify each call site in current WIP demo. void ImFontAtlas::ClearCache() { int tex_w = (TexData && TexData->Status != ImTextureStatus_WantDestroy) ? TexData->Width : 0; @@ -2891,7 +2892,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) // Lazily create builder on the first call to AddFont if (Builder == NULL) - BuildInit(); + ImFontAtlasBuildInit(this); // Create new font if (!font_cfg->MergeMode) @@ -3066,11 +3067,24 @@ int ImFontAtlas::AddCustomRectRegular(int width, int height) { IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - ImFontAtlasCustomRect r; - r.Width = (unsigned short)width; - r.Height = (unsigned short)height; - CustomRects.push_back(r); - return CustomRects.Size - 1; // Return index + + if (DrawListSharedData && DrawListSharedData->RendererHasTextures) + { + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); + ImFontAtlasRect* r = ImFontAtlasPackGetRect(this, r_id); + ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); + return r_id; + } + else + { + // FIXME-NEWATLAS-V1: Unfinished + ImFontAtlasCustomRect r; + r.Width = (unsigned short)width; + r.Height = (unsigned short)height; + //CustomRects.push_back(r); + //return CustomRects.Size - 1; // Return index + return -1; + } } int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset) @@ -3089,8 +3103,18 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int r.GlyphAdvanceX = advance_x; r.GlyphOffset = offset; r.Font = font; - CustomRects.push_back(r); - return CustomRects.Size - 1; // Return index + //CustomRects.push_back(r); + //return CustomRects.Size - 1; // Return index + return -1; +} + +ImFontAtlasCustomRect* ImFontAtlas::GetCustomRectByIndex(int idx) +{ + IM_STATIC_ASSERT(offsetof(ImFontAtlasCustomRect, X) == offsetof(ImFontAtlasRect, x)); + IM_STATIC_ASSERT(offsetof(ImFontAtlasCustomRect, Y) == offsetof(ImFontAtlasRect, y)); + IM_STATIC_ASSERT(offsetof(ImFontAtlasCustomRect, Width) == offsetof(ImFontAtlasRect, w)); + IM_STATIC_ASSERT(offsetof(ImFontAtlasCustomRect, Height) == offsetof(ImFontAtlasRect, h)); + return (ImFontAtlasCustomRect*)(void*)ImFontAtlasPackGetRect(this, idx); } void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const @@ -3121,35 +3145,12 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso return true; } -void ImFontAtlas::BuildInit() -{ - // Select builder - // - Note that we do not reassign to atlas->FontLoader, since it is likely to point to static data which - // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are - // using a hot-reloading scheme that messes up static data, store your own instance of ImFontLoader somewhere - // and point to it instead of pointing directly to return value of the GetBackendIOXXX functions. - if (FontLoader == NULL) - { -#ifdef IMGUI_ENABLE_FREETYPE - ImFontAtlasBuildSetupFontLoader(this, ImGuiFreeType::GetBackendIOForFreeType()); -#elif defined(IMGUI_ENABLE_STB_TRUETYPE) - ImFontAtlasBuildSetupFontLoader(this, ImFontAtlasGetFontLoaderForStbTruetype()); -#else - IM_ASSERT(0); // Invalid Build function -#endif - } - - // Create initial texture size - ImFontAtlasBuildAddTexture(this, 512, 128); - ImFontAtlasBuildInit(this); -} - bool ImFontAtlas::Build() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); if (Builder == NULL) - BuildInit(); + ImFontAtlasBuildInit(this); // Default font is none are specified if (Sources.Size == 0) @@ -3222,6 +3223,8 @@ void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) } } +// FIXME-NEWATLAS: Unused +#if 0 void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque) { ImTextureData* tex = atlas->TexData; @@ -3253,6 +3256,7 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa tex->Height = ImMax(tex->Height, pack_rects[i].y + pack_rects[i].h); } } +#endif // Render a white-colored bitmap encoded in a string void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char) @@ -3476,6 +3480,28 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* sr font->LockSingleSrcConfigIdx = -1; } +void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font) +{ + for (ImFontGlyph& glyph : font->Glyphs) + if (glyph.PackId >= 0) + ImFontAtlasPackDiscardRect(atlas, glyph.PackId); + font->BuildClearGlyphs(); + + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = (ImFontConfig*)(void*)&font->Sources[src_n]; + IM_ASSERT(src->SizePixels > 0.0f); + + // Reload font in backend + if (atlas->FontLoader && atlas->FontLoader->FontSrcDestroy != NULL) + atlas->FontLoader->FontSrcDestroy(atlas, src); + if (atlas->FontLoader && atlas->FontLoader->FontSrcInit != NULL) + atlas->FontLoader->FontSrcInit(atlas, src); + + ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, src); // Technically this is called for each source sub-font, tho 99.9% of the time the first one fills everything. + } +} + // Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) { @@ -3588,29 +3614,40 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. - // Repack + copy pixels + // Repack, lose discarded rectangle, copy pixels // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic. ImFontAtlasPackInit(atlas); ImVector old_rects; + ImVector old_index = builder->RectsIndex; old_rects.swap(builder->Rects); - for (ImFontAtlasRect& old_r : old_rects) + + for (ImFontAtlasRectEntry& index_entry : builder->RectsIndex) { - ImFontAtlasRectId new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h); + if (index_entry.Used == false) + continue; + ImFontAtlasRect& old_r = old_rects[index_entry.TargetIndex]; + if (old_r.w == 0 && old_r.h == 0) + continue; + ImFontAtlasRectId new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, &index_entry); if (new_r_id == -1) { // Undo, grow texture and try repacking again. // FIXME-NEWATLAS-TESTS: This is a very rarely exercised path! It needs to be automatically tested properly. IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize failed. Will grow.\n", new_tex->UniqueID); new_tex->WantDestroyNextFrame = true; - old_rects.swap(builder->Rects); + builder->Rects.swap(old_rects); + builder->RectsIndex = old_index; ImFontAtlasBuildSetTexture(atlas, old_tex); - ImFontAtlasBuildGrowTexture(atlas, w, h); + ImFontAtlasBuildGrowTexture(atlas, w, h); // Recurse return; } + IM_ASSERT(new_r_id == builder->RectsIndex.index_from_ptr(&index_entry)); ImFontAtlasRect* new_r = ImFontAtlasPackGetRect(atlas, new_r_id); ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r->x, new_r->y, new_r->w, new_r->h); } - IM_ASSERT(old_rects.Size == builder->Rects.Size); + IM_ASSERT(old_rects.Size == builder->Rects.Size + builder->RectsDiscardedCount); + builder->RectsDiscardedCount = 0; + builder->RectsDiscardedSurface = 0; // Patch glyphs UV for (ImFont* font : atlas->Fonts) @@ -3645,6 +3682,7 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h)); // Grow texture so it follows roughly a square. + // FIXME-NEWATLAS-V1: Take account of RectsDiscardedSurface: may not need to grow. int new_tex_w = (old_tex_h < old_tex_w) ? old_tex_w : old_tex_w * 2; int new_tex_h = (old_tex_h < old_tex_w) ? old_tex_h * 2 : old_tex_h; @@ -3669,14 +3707,15 @@ void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) // FIXME-NEWATLAS: Expose atlas->TexMinWidth etc. const int min_w = ImMax(builder->MaxRectSize.x, 512); const int min_h = builder->MaxRectSize.y; - const int surface_sqrt = (int)sqrtf((float)atlas->_PackedSurface); + const int surface_approx = atlas->_PackedSurface - builder->RectsDiscardedSurface; // Expected surface after repack + const int surface_sqrt = (int)sqrtf((float)surface_approx); int new_tex_w; int new_tex_h; if (min_w >= min_h) { new_tex_w = ImMax(min_w, ImUpperPowerOfTwo(surface_sqrt)); - new_tex_h = ImMax(min_h, (int)(atlas->_PackedSurface / new_tex_w)); + new_tex_h = ImMax(min_h, (int)((surface_approx + new_tex_w - 1) / new_tex_w)); if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0) new_tex_h = ImUpperPowerOfTwo(new_tex_h); } @@ -3685,10 +3724,10 @@ void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) new_tex_h = ImMax(min_h, ImUpperPowerOfTwo(surface_sqrt)); if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0) new_tex_h = ImUpperPowerOfTwo(new_tex_h); - new_tex_w = ImMax(min_w, (int)(atlas->_PackedSurface / new_tex_h)); + new_tex_w = ImMax(min_w, (int)((surface_approx + new_tex_h - 1) / new_tex_h)); } - if (new_tex_w == old_tex_w && new_tex_h == old_tex_h) + if (builder->RectsDiscardedCount == 0 && new_tex_w == old_tex_w && new_tex_h == old_tex_h) return; ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); @@ -3699,6 +3738,25 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) { ImFontAtlasBuilder* builder = atlas->Builder; + // Select Backend + // - Note that we do not reassign to atlas->FontBackendIO, since it is likely to point to static data which + // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are + // using a hot-reloading scheme that messes up static data, store your own instance of ImFontBackendIO somewhere + // and point to it instead of pointing directly to return value of the GetBackendIOXXX functions. + if (atlas->FontLoader == NULL) + { +#ifdef IMGUI_ENABLE_FREETYPE + ImFontAtlasBuildSetupFontLoader(atlas, ImGuiFreeType::GetFontLoader()); +#elif defined(IMGUI_ENABLE_STB_TRUETYPE) + ImFontAtlasBuildSetupFontLoader(atlas, ImFontAtlasGetFontLoaderForStbTruetype()); +#else + IM_ASSERT(0); // Invalid Build function +#endif + } + // Create initial texture size + if (atlas->TexData == NULL) + ImFontAtlasBuildAddTexture(atlas, 512, 128); + const bool builder_is_new = (builder == NULL); if (builder_is_new) builder = atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); @@ -3736,7 +3794,7 @@ void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) atlas->Builder = NULL; } -void ImFontAtlasPackInit(ImFontAtlas* atlas) +void ImFontAtlasPackInit(ImFontAtlas * atlas) { ImTextureData* tex = atlas->TexData; ImFontAtlasBuilder* builder = atlas->Builder; @@ -3751,9 +3809,52 @@ void ImFontAtlasPackInit(ImFontAtlas* atlas) builder->MaxRectBounds = ImVec2i(0, 0); } +// This is essentially a free-list pattern, it may be nice to wrap it into a dedicated type. +static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int rect_idx) +{ + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + int index_idx; + ImFontAtlasRectEntry* index_entry; + if (builder->RectsIndexFreeListStart < 0) + { + builder->RectsIndex.resize(builder->RectsIndex.Size + 1); + index_idx = builder->RectsIndex.Size - 1; + index_entry = &builder->RectsIndex[index_idx]; + } + else + { + index_idx = builder->RectsIndexFreeListStart; + index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->Used == false); + builder->RectsIndexFreeListStart = index_entry->TargetIndex; + } + index_entry->TargetIndex = rect_idx; + index_entry->Used = 1; + return (ImFontAtlasRectId)index_idx; +} + +// This is expected to be called in batches and followed by a repack +void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + IM_ASSERT(id >= 0); + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; + IM_ASSERT(index_entry->Used && index_entry->TargetIndex >= 0); + + ImFontAtlasRect* rect = ImFontAtlasPackGetRect(atlas, id); + index_entry->Used = false; + index_entry->TargetIndex = builder->RectsIndexFreeListStart; + + const int pack_padding = atlas->TexGlyphPadding; + builder->RectsIndexFreeListStart = id; + builder->RectsDiscardedCount++; + builder->RectsDiscardedSurface += (rect->w + pack_padding) * (rect->h + pack_padding); + rect->w = rect->h = 0; // Clear rectangle so it won't be packed again +} + // Important: Calling this may recreate a new texture and therefore change atlas->TexData // FIXME-NEWATLAS-V2: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 -ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h) +ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry) { IM_ASSERT(w > 0 && w <= 0xFFFF); IM_ASSERT(h > 0 && h <= 0xFFFF); @@ -3796,13 +3897,25 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h) atlas->_PackedRects++; builder->Rects.push_back(r); - return builder->Rects.Size - 1; + if (overwrite_entry != NULL) + { + // Write into an existing entry instead of adding one (used during repack) + IM_ASSERT(overwrite_entry->Used); + overwrite_entry->TargetIndex = builder->Rects.Size - 1; + return builder->RectsIndex.index_from_ptr(overwrite_entry); + } + else + { + return ImFontAtlasPackAllocRectEntry(atlas, builder->Rects.Size - 1); + } } ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; - return &builder->Rects[id]; + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; + IM_ASSERT(index_entry->Used); + return &builder->Rects[index_entry->TargetIndex]; } ImFontGlyph* ImFont::BuildLoadGlyph(ImWchar codepoint) diff --git a/imgui_internal.h b/imgui_internal.h index 4e8384bee..67a4b50cb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -142,6 +142,7 @@ struct ImGuiTextIndex; // Maintain a line index for a text buffer. struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances struct ImFontAtlasRect; // Packed rectangle (same as ImTextureRect) +struct ImFontAtlasRectEntry; // Packed rectangle lookup entry struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas // ImGui @@ -3639,7 +3640,6 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- -// Packed rectangle (same as ImTextureRect) struct ImFontAtlasRect { unsigned short x, y; @@ -3647,6 +3647,17 @@ struct ImFontAtlasRect }; typedef int ImFontAtlasRectId; // <0 when invalid +// Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) +// User are returned ImFontAtlasRectId values which are meant to be persistent. +// We handle this with an indirection. While Rects[] may be in theory shuffled, compacted etc., RectsIndex[] cannot it is keyed by ImFontAtlasRectId. +// RectsIndex[] is used both as an index into Rects[] and an index into itself. This is basically a free-list. See ImFontAtlasBuildAllocRectIndexEntry() code. +// Having this also makes it easier to e.g. sort rectangles during repack. +struct ImFontAtlasRectEntry +{ + int TargetIndex : 31; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. + unsigned int Used : 1; +}; + // Internal storage for incrementally packing and building a ImFontAtlas struct stbrp_context_opaque { char data[80]; }; struct stbrp_node; @@ -3655,7 +3666,11 @@ struct ImFontAtlasBuilder stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file. ImVector PackNodes; ImVector Rects; + ImVector RectsIndex; // ImFontAtlasRectId -> index into Rects[] ImVector TempBuffer; // Misc scratch buffer + int RectsIndexFreeListStart;// First unused entry + int RectsDiscardedCount; + int RectsDiscardedSurface; 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 @@ -3665,7 +3680,7 @@ struct ImFontAtlasBuilder ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. ImFontAtlasRectId PackIdLinesTexData; - ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); } + ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); RectsIndexFreeListStart = -1; } }; // FIXME-NEWATLAS: Cleanup @@ -3683,11 +3698,13 @@ IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); -IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h); +IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); +IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); From a51a26e2aa9717cc77d8a91416e31f611d4b72db Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Dec 2024 19:21:10 +0100 Subject: [PATCH 0916/2359] Fonts: use a structure for post-processing - easier to pass things around and iterate on. --- imgui_draw.cpp | 45 +++++++++++++------------------- imgui_internal.h | 21 +++++++++++++-- misc/freetype/imgui_freetype.cpp | 5 ++-- 3 files changed, 40 insertions(+), 31 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 48f99cdf1..10e69644f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2460,8 +2460,8 @@ void ImTextureData::DestroyPixels() // - ImFontAtlas::BuildCompactTexture() // - ImFontAtlasUpdateTextures() //----------------------------------------------------------------------------- -// - ImFontAtlasTextureBlockConvertAndPostProcess() // - ImFontAtlasTextureBlockConvert() +// - ImFontAtlasTextureBlockPostProcess() // - ImFontAtlasTextureBlockPostProcessMultiply() // - ImFontAtlasTextureBlockCopy() // - ImFontAtlasTextureBlockQueueUpload() @@ -2734,17 +2734,11 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) // Source buffer may be written to (used for in-place mods). // Post-process hooks may eventually be added here. -void ImFontAtlasTextureBlockConvertAndPostProcess(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, ImFontGlyph* glyph, unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst, ImTextureFormat dst_fmt, int dst_pitch, int w, int h) +void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data) { - IM_UNUSED(atlas); - IM_UNUSED(font); - IM_UNUSED(glyph); - // Multiply operator (legacy) - if (src->RasterizerMultiply != 1.0f) - ImFontAtlasTextureBlockPostProcessMultiply(atlas, font, src, glyph, src_pixels, src_fmt, w, h, src_pitch, src->RasterizerMultiply); - - ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst, dst_fmt, dst_pitch, w, h); + if (data->FontSrc->RasterizerMultiply != 1.0f) + ImFontAtlasTextureBlockPostProcessMultiply(data, data->FontSrc->RasterizerMultiply); } 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) @@ -2782,34 +2776,30 @@ void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFo } } -void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, ImFontGlyph* glyph, unsigned char* pixels, ImTextureFormat format, int w, int h, int pitch, float in_multiply_factor) +void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor) { - IM_UNUSED(atlas); - IM_UNUSED(font); - IM_UNUSED(src); - IM_UNUSED(glyph); - IM_ASSERT(in_multiply_factor >= 0.0f); - IM_ASSERT_PARANOID(w <= pitch); - if (format == ImTextureFormat_Alpha8) + unsigned char* pixels = data->Pixels; + int pitch = data->Pitch; + if (data->Format == ImTextureFormat_Alpha8) { - for (int ny = h; ny > 0; ny--, pixels += pitch) + for (int ny = data->Height; ny > 0; ny--, pixels += pitch) { ImU8* p = (ImU8*)pixels; - for (int nx = w; nx > 0; nx--, p++) + for (int nx = data->Width; nx > 0; nx--, p++) { - unsigned int v = ImMin((unsigned int)(*p * in_multiply_factor), (unsigned int)255); + unsigned int v = ImMin((unsigned int)(*p * multiply_factor), (unsigned int)255); *p = (unsigned char)v; } } } - else if (format == ImTextureFormat_RGBA32) + else if (data->Format == ImTextureFormat_RGBA32) { - for (int ny = h; ny > 0; ny--, pixels += pitch) + for (int ny = data->Height; ny > 0; ny--, pixels += pitch) { ImU32* p = (ImU32*)(void*)pixels; - for (int nx = w; nx > 0; nx--, p++) + for (int nx = data->Width; nx > 0; nx--, p++) { - unsigned int a = ImMin((unsigned int)(((*p >> IM_COL32_A_SHIFT) & 0xFF) * in_multiply_factor), (unsigned int)255); + unsigned int a = ImMin((unsigned int)(((*p >> IM_COL32_A_SHIFT) & 0xFF) * multiply_factor), (unsigned int)255); *p = IM_COL32((*p >> IM_COL32_R_SHIFT) & 0xFF, (*p >> IM_COL32_G_SHIFT) & 0xFF, (*p >> IM_COL32_B_SHIFT) & 0xFF, a); } } @@ -4156,8 +4146,9 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, // Copy to texture, post-process and queue update for backend ImTextureData* tex = atlas->TexData; IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); - ImFontAtlasTextureBlockConvertAndPostProcess(atlas, font, src, &font->Glyphs.back(), - bitmap_pixels, ImTextureFormat_Alpha8, w, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); + ImFontAtlasTextureBlockConvert(bitmap_pixels, ImTextureFormat_Alpha8, w, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); + ImFontAtlasPostProcessData pp_data = { atlas, font, src, &font->Glyphs.back(), tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h }; + ImFontAtlasTextureBlockPostProcess(&pp_data); ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } else diff --git a/imgui_internal.h b/imgui_internal.h index 67a4b50cb..2c97cae01 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -144,6 +144,7 @@ struct ImDrawListSharedData; // Data shared between all ImDrawList instan struct ImFontAtlasRect; // Packed rectangle (same as ImTextureRect) struct ImFontAtlasRectEntry; // Packed rectangle lookup entry struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas +struct ImFontAtlasPostProcessData; // Data available to potential post-process functions // ImGui struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) @@ -3658,6 +3659,22 @@ struct ImFontAtlasRectEntry unsigned int Used : 1; }; +// Data available to potential post-process functions +struct ImFontAtlasPostProcessData +{ + ImFontAtlas* FontAtlas; + ImFont* Font; + ImFontConfig* FontSrc; + ImFontGlyph* Glyph; + + // Pixel data + unsigned char* Pixels; + ImTextureFormat Format; + int Pitch; + int Width; + int Height; +}; + // Internal storage for incrementally packing and building a ImFontAtlas struct stbrp_context_opaque { char data[80]; }; struct stbrp_node; @@ -3714,9 +3731,9 @@ IMGUI_API void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* at IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasTextureBlockConvertAndPostProcess(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, ImFontGlyph* glyph, unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst, ImTextureFormat dst_fmt, int dst_pitch, int w, int h); 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 ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, ImFontGlyph* glyph, unsigned char* pixels, ImTextureFormat format, int w, int h, int pitch, float in_multiply_factor); +IMGUI_API void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data); +IMGUI_API void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor); IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h); IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index a8dfa950e..efe8612ba 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -541,8 +541,9 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon // Copy to texture, post-process and queue update for backend ImTextureData* tex = atlas->TexData; IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); - ImFontAtlasTextureBlockConvertAndPostProcess(atlas, font, src, &font->Glyphs.back(), - temp_buffer, ImTextureFormat_RGBA32, w * 4, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); + ImFontAtlasTextureBlockConvert(temp_buffer, ImTextureFormat_RGBA32, w * 4, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); + ImFontAtlasPostProcessData pp_data = { atlas, font, src, &font->Glyphs.back(), tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h }; + ImFontAtlasTextureBlockPostProcess(&pp_data); ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } else From ef1521b472147c372d4239cda454a8275b201361 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Dec 2024 14:40:45 +0100 Subject: [PATCH 0917/2359] Fonts: fix for password fields --- imgui_widgets.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 47f6f7187..c632b45a4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4321,9 +4321,12 @@ void ImGui::PushPasswordFont() out_font->Ascent = in_font->Ascent; out_font->Descent = in_font->Descent; out_font->ContainerAtlas = in_font->ContainerAtlas; - out_font->FallbackGlyphIndex = in_font->Glyphs.index_from_ptr(glyph); // FIXME: broken + out_font->Glyphs.resize(0); + out_font->Glyphs.push_back(*glyph); + out_font->FallbackGlyphIndex = 0; out_font->FallbackAdvanceX = glyph->AdvanceX; - IM_ASSERT(out_font->Glyphs.Size == 0 && out_font->IndexAdvanceX.Size == 0 && out_font->IndexLookup.Size == 0); + out_font->LockDisableLoading = true; + IM_ASSERT(out_font->Glyphs.Size == 1 && out_font->IndexAdvanceX.Size == 0 && out_font->IndexLookup.Size == 0); PushFont(out_font); } From 4399599de9c10f4adee0b1e484ceb3b5e9d2e399 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Dec 2024 15:21:22 +0100 Subject: [PATCH 0918/2359] Fonts: ClearCache(), ImFontAtlasBuildGetTextureSizeEstimate(), tweak clearing functions. --- imgui.h | 8 +++--- imgui_draw.cpp | 66 ++++++++++++++++++++++++++++++------------------ imgui_internal.h | 1 + 3 files changed, 47 insertions(+), 28 deletions(-) diff --git a/imgui.h b/imgui.h index 3013eb9e0..3ce13eb88 100644 --- a/imgui.h +++ b/imgui.h @@ -3523,12 +3523,12 @@ struct ImFontAtlas IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* 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. // FIXME-NEWATLAS: Clarify meaning/purpose - IMGUI_API void ClearInputData(); // 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 ClearFonts(); // Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). - IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. IMGUI_API void Clear(); // Clear all input and output. - IMGUI_API void ClearCache(); // Clear cached glyphs + // As we are transitioning toward a new font system, we expect to obsolete those soon: + 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 ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). + IMGUI_API void ClearTexData(); // [OBSOLETE] Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 10e69644f..631cb22e6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2569,8 +2569,9 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3 { ImVec2(109,0),ImVec2(13,15), ImVec2( 6, 7) }, // ImGuiMouseCursor_NotAllowed }; -#define IM_FONTGLYPH_INDEX_UNUSED ((ImU16)-1) // 0xFFFF -#define IM_FONTGLYPH_INDEX_NOT_FOUND ((ImU16)-2) // 0xFFFE +#define IM_FONTGLYPH_INDEX_UNUSED ((ImU16)-1) // 0xFFFF +#define IM_FONTGLYPH_INDEX_NOT_FOUND ((ImU16)-2) // 0xFFFE +#define IM_FONTATLAS_DEFAULT_TEXTURE_SIZE ImVec2i(512, 128) ImFontAtlas::ImFontAtlas() { @@ -2600,11 +2601,14 @@ void ImFontAtlas::ClearInputData() // When clearing this we lose access to the font name and other information used to build the font. for (ImFont* font : Fonts) + { if (font->Sources >= Sources.Data && font->Sources < Sources.Data + Sources.Size) { font->Sources = NULL; font->SourcesCount = 0; } + font->LockDisableLoading = true; + } Sources.clear(); //CustomRects.clear(); // Important: we leave TexReady untouched @@ -2616,15 +2620,14 @@ void ImFontAtlas::ClearTexData() TexList.clear(); IM_DELETE(TexData); TexData = NULL; - // TexData.Destroy(); - //IM_ASSERT(0); - // Important: we leave TexReady untouched + // Important: we leave TexReady untouched } void ImFontAtlas::ClearFonts() { // FIXME-NEWATLAS: Illegal to remove currently bound font. IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + ImFontAtlasBuildDestroy(this); ClearInputData(); Fonts.clear_delete(); TexIsBuilt = false; @@ -2637,7 +2640,7 @@ void ImFontAtlas::ClearFonts() void ImFontAtlas::Clear() { - //IM_DELETE(Builder); // FIXME-NEW-ATLAS: ClearXXX functions + //IM_DELETE(Builder); // FIXME-NEW-ATLAS: Clarify ClearXXX functions const ImFontLoader* font_loader = FontLoader; ImFontAtlasBuildSetupFontLoader(this, NULL); ClearInputData(); @@ -2649,11 +2652,9 @@ void ImFontAtlas::Clear() // FIXME-NEWATLAS: Too widespread purpose. Clarify each call site in current WIP demo. void ImFontAtlas::ClearCache() { - int tex_w = (TexData && TexData->Status != ImTextureStatus_WantDestroy) ? TexData->Width : 0; - int tex_h = (TexData && TexData->Status != ImTextureStatus_WantDestroy) ? TexData->Height : 0; + ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(this); ImFontAtlasBuildDestroy(this); - if (tex_w != 0 && tex_h != 0) - ImFontAtlasBuildAddTexture(this, tex_w, tex_h); + ImFontAtlasBuildAddTexture(this, new_tex_size.x, new_tex_size.y); ImFontAtlasBuildInit(this); } @@ -3139,6 +3140,13 @@ bool ImFontAtlas::Build() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + if (TexData && TexData->Format != TexDesiredFormat) + { + ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(this); + ImFontAtlasBuildDestroy(this); + ImFontAtlasBuildAddTexture(this, new_tex_size.x, new_tex_size.y); + } + if (Builder == NULL) ImFontAtlasBuildInit(this); @@ -3168,7 +3176,10 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon return; IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); + // Note that texture size estimate is likely incorrect in this situation, as Freetype backend doesn't use oversampling. + ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); ImFontAtlasBuildDestroy(atlas); + if (atlas->FontLoader && atlas->FontLoader->LoaderShutdown) { atlas->FontLoader->LoaderShutdown(atlas); @@ -3178,8 +3189,9 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon atlas->FontLoaderName = font_loader ? font_loader->Name : "NULL"; if (atlas->FontLoader && atlas->FontLoader->LoaderInit) atlas->FontLoader->LoaderInit(atlas); - if (atlas->Builder && font_loader != NULL) - atlas->ClearCache(); + + ImFontAtlasBuildAddTexture(atlas, new_tex_size.x, new_tex_size.y); + ImFontAtlasBuildInit(atlas); } // Preload all glyph ranges for legacy backends. @@ -3684,17 +3696,13 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); } -// You should not need to call this manually! -// If you think you do, let us know and we can advise about policies auto-compact. -void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) +// FIXME-NEWATLAS: Expose atlas->TexMinWidth etc. +ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) { + if (atlas->Builder == NULL || atlas->TexData == NULL || atlas->TexData->Status == ImTextureStatus_WantDestroy) + return IM_FONTATLAS_DEFAULT_TEXTURE_SIZE; + ImFontAtlasBuilder* builder = atlas->Builder; - - ImTextureData* old_tex = atlas->TexData; - int old_tex_w = old_tex->Width; - int old_tex_h = old_tex->Height; - - // FIXME-NEWATLAS: Expose atlas->TexMinWidth etc. const int min_w = ImMax(builder->MaxRectSize.x, 512); const int min_h = builder->MaxRectSize.y; const int surface_approx = atlas->_PackedSurface - builder->RectsDiscardedSurface; // Expected surface after repack @@ -3716,11 +3724,21 @@ void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) new_tex_h = ImUpperPowerOfTwo(new_tex_h); new_tex_w = ImMax(min_w, (int)((surface_approx + new_tex_h - 1) / new_tex_h)); } + return ImVec2i(new_tex_w, new_tex_h); +} - if (builder->RectsDiscardedCount == 0 && new_tex_w == old_tex_w && new_tex_h == old_tex_h) +// You should not need to call this manually! +// If you think you do, let us know and we can advise about policies auto-compact. +void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + ImTextureData* old_tex = atlas->TexData; + ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height); + ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); + if (builder->RectsDiscardedCount == 0 && new_tex_size.x == old_tex_size.x && new_tex_size.y == old_tex_size.y) return; - ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); + ImFontAtlasBuildRepackTexture(atlas, new_tex_size.x, new_tex_size.y); } // Start packing over current empty texture @@ -3745,7 +3763,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) } // Create initial texture size if (atlas->TexData == NULL) - ImFontAtlasBuildAddTexture(atlas, 512, 128); + ImFontAtlasBuildAddTexture(atlas, IM_FONTATLAS_DEFAULT_TEXTURE_SIZE.x, IM_FONTATLAS_DEFAULT_TEXTURE_SIZE.y); const bool builder_is_new = (builder == NULL); if (builder_is_new) diff --git a/imgui_internal.h b/imgui_internal.h index 2c97cae01..53f0dbd07 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3712,6 +3712,7 @@ IMGUI_API ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w IMGUI_API void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h); IMGUI_API void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); +IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas); IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src); From df8450d928822f8dacd9f07e0bc50dd095c8228d Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Dec 2024 22:33:11 +0100 Subject: [PATCH 0919/2359] Fonts: marked ImFontAtlas::Build() as obsolete --- imgui.cpp | 4 ++-- imgui.h | 6 +++--- imgui_draw.cpp | 41 ++++++++++++++++++++++------------------- imgui_internal.h | 1 + 4 files changed, 28 insertions(+), 24 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ce2b06462..249456c7e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5243,9 +5243,9 @@ void ImGui::NewFrame() // Check that font atlas was built or backend support texture reload in which case we can build now ImFontAtlas* atlas = g.IO.Fonts; if (!atlas->TexIsBuilt && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) - atlas->Build(); + ImFontAtlasBuildMain(atlas); else // Legacy backend - IM_ASSERT(atlas->TexIsBuilt && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()"); + IM_ASSERT(atlas->TexIsBuilt && "Backend does not support ImGuiBackendFlags_RendererHasTexUpdates, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()."); // Check and assert for various common IO and Configuration mistakes ErrorCheckNewFrameSanityChecks(); diff --git a/imgui.h b/imgui.h index 3ce13eb88..7d04ebcd2 100644 --- a/imgui.h +++ b/imgui.h @@ -3530,15 +3530,15 @@ struct ImFontAtlas IMGUI_API void ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). IMGUI_API void ClearTexData(); // [OBSOLETE] Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. + IMGUI_API void BuildGrowTexture(); + IMGUI_API void BuildCompactTexture(); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). // The pitch is always = Width * BytesPerPixels (1 or 4) // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. - IMGUI_API void BuildGrowTexture(); - IMGUI_API void BuildCompactTexture(); -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel void SetTexID(ImTextureID id) { TexRef._TexData = NULL; TexRef._TexID = id; } // Called by legacy backends. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 631cb22e6..13060843e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2466,9 +2466,9 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasTextureBlockCopy() // - ImFontAtlasTextureBlockQueueUpload() //----------------------------------------------------------------------------- +// - ImFontAtlas::Build() [legacy] // - ImFontAtlas::GetTexDataAsAlpha8() [legacy] // - ImFontAtlas::GetTexDataAsRGBA32() [legacy] -// - ImFontAtlas::Build() //----------------------------------------------------------------------------- // - ImFontAtlas::AddFont() // - ImFontAtlas::AddFontDefault() @@ -2872,6 +2872,12 @@ void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, { GetTexDataAsFormat(this, ImTextureFormat_RGBA32, out_pixels, out_width, out_height, out_bytes_per_pixel); } + +bool ImFontAtlas::Build() +{ + ImFontAtlasBuildMain(this); + return true; +} #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) @@ -3136,31 +3142,28 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso return true; } -bool ImFontAtlas::Build() +void ImFontAtlasBuildMain(ImFontAtlas* atlas) { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - - if (TexData && TexData->Format != TexDesiredFormat) + IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); + if (atlas->TexData && atlas->TexData->Format != atlas->TexDesiredFormat) { - ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(this); - ImFontAtlasBuildDestroy(this); - ImFontAtlasBuildAddTexture(this, new_tex_size.x, new_tex_size.y); + ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); + ImFontAtlasBuildDestroy(atlas); + ImFontAtlasBuildAddTexture(atlas, new_tex_size.x, new_tex_size.y); } - if (Builder == NULL) - ImFontAtlasBuildInit(this); + if (atlas->Builder == NULL) + ImFontAtlasBuildInit(atlas); // Default font is none are specified - if (Sources.Size == 0) - AddFontDefault(); + if (atlas->Sources.Size == 0) + atlas->AddFontDefault(); - // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs - ImFontAtlasBuildUpdateRendererHasTexturesFromContext(this); - if (DrawListSharedData && DrawListSharedData->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures - ImFontAtlasBuildPreloadAllGlyphRanges(this); - TexIsBuilt = true; - - return true; + // [LEGACY] For backends not supporting RendererHasTexUpdates: preload all glyphs + ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + if (atlas->DrawListSharedData && atlas->DrawListSharedData->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures + ImFontAtlasBuildPreloadAllGlyphRanges(atlas); + atlas->TexIsBuilt = true; } void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v) diff --git a/imgui_internal.h b/imgui_internal.h index 53f0dbd07..48090ee90 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3705,6 +3705,7 @@ IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); +IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); From cec3e945f02bb2fb2e12d1bbd984971ab4f2be37 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Dec 2024 16:21:07 +0100 Subject: [PATCH 0920/2359] Fonts: added ImFontAtlas::RemoveFont(), fixed various leaks. --- imgui.cpp | 6 ++++ imgui.h | 5 ++-- imgui_draw.cpp | 78 +++++++++++++++++++++++++++++++++++++++++++++--- imgui_internal.h | 1 + 4 files changed, 84 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 249456c7e..adb1e84f1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16484,6 +16484,12 @@ void ImGui::DebugNodeFont(ImFont* font) } if (SmallButton("Set as default")) GetIO().FontDefault = font; + if (font->ContainerAtlas->Fonts.Size > 1 && !font->ContainerAtlas->Locked) + { + SameLine(); + if (SmallButton("Remove")) + font->ContainerAtlas->RemoveFont(font); + } // Display details SetNextItemWidth(GetFontSize() * 8); diff --git a/imgui.h b/imgui.h index 7d04ebcd2..e237e90ae 100644 --- a/imgui.h +++ b/imgui.h @@ -3521,10 +3521,11 @@ struct ImFontAtlas 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(const char* 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); // FIXME-NEWATLAS: Clarify meaning/purpose - IMGUI_API void Clear(); // Clear all input and output. - IMGUI_API void ClearCache(); // Clear cached glyphs + IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) + IMGUI_API void ClearCache(); // Clear cached glyphs and textures. // As we are transitioning toward a new font system, we expect to obsolete those soon: 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 ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 13060843e..faabec1d5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2476,6 +2476,8 @@ void ImTextureData::DestroyPixels() // - ImFontAtlas::AddFontFromMemoryTTF() // - ImFontAtlas::AddFontFromMemoryCompressedTTF() // - ImFontAtlas::AddFontFromMemoryCompressedBase85TTF() +// - ImFontAtlas::RemoveFont() +// - ImFontAtlasBuildNotifySetFont() //----------------------------------------------------------------------------- // - ImFontAtlas::AddCustomRectRegular() // - ImFontAtlas::AddCustomRectFontGlyph() @@ -2593,11 +2595,15 @@ void ImFontAtlas::ClearInputData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); for (ImFontConfig& font_cfg : Sources) + { + if (FontLoader && FontLoader->FontSrcDestroy != NULL) + FontLoader->FontSrcDestroy(this, &font_cfg); if (font_cfg.FontData && font_cfg.FontDataOwnedByAtlas) { IM_FREE(font_cfg.FontData); font_cfg.FontData = NULL; } + } // When clearing this we lose access to the font name and other information used to build the font. for (ImFont* font : Fonts) @@ -2641,12 +2647,12 @@ void ImFontAtlas::ClearFonts() void ImFontAtlas::Clear() { //IM_DELETE(Builder); // FIXME-NEW-ATLAS: Clarify ClearXXX functions - const ImFontLoader* font_loader = FontLoader; - ImFontAtlasBuildSetupFontLoader(this, NULL); + //const ImFontLoader* font_loader = FontLoader; + //ImFontAtlasBuildSetupFontLoader(this, NULL); ClearInputData(); ClearTexData(); ClearFonts(); - ImFontAtlasBuildSetupFontLoader(this, font_loader); + //ImFontAtlasBuildSetupFontLoader(this, font_loader); } // FIXME-NEWATLAS: Too widespread purpose. Clarify each call site in current WIP demo. @@ -3041,6 +3047,59 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed return font; } +// We allow old_font == new_font which forces updating all values (e.g. sizes) +static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font) +{ + if (ImDrawListSharedData* shared_data = atlas->DrawListSharedData) + { + if (shared_data->Font == old_font) + shared_data->Font = new_font; + if (ImGuiContext* ctx = shared_data->Context) + { + if (ctx->IO.FontDefault == old_font) + ctx->IO.FontDefault = new_font; + if (ctx->Font == old_font) + { + ImGuiContext* curr_ctx = ImGui::GetCurrentContext(); + bool need_bind_ctx = ctx != curr_ctx; + if (need_bind_ctx) + ImGui::SetCurrentContext(ctx); + ImGui::SetCurrentFont(new_font); + if (need_bind_ctx) + ImGui::SetCurrentContext(curr_ctx); + } + } + } +} + +void ImFontAtlas::RemoveFont(ImFont* font) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + ImFontAtlasBuildDiscardFontGlyphs(this, font); + + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = (ImFontConfig*)(void*)&font->Sources[src_n]; + if (FontLoader && FontLoader->FontSrcDestroy != NULL) + FontLoader->FontSrcDestroy(this, src); + if (src->FontData != NULL && src->FontDataOwnedByAtlas) + IM_FREE(src->FontData); + } + + bool removed = Fonts.find_erase(font); + IM_ASSERT(removed); + + Sources.erase(font->Sources, font->Sources + font->SourcesCount); + ImFontAtlasBuildUpdatePointers(this); + + font->ContainerAtlas = NULL; + IM_DELETE(font); + + // Notify external systems + ImFont* new_current_font = Fonts.empty() ? NULL : Fonts[0]; + ImFontAtlasBuildNotifySetFont(this, font, new_current_font); +} + // FIXME-NEWATLAS-V1: Feature is broken for now. /* // Register custom rectangle glyphs @@ -3485,13 +3544,19 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* sr font->LockSingleSrcConfigIdx = -1; } -void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font) +void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font) { for (ImFontGlyph& glyph : font->Glyphs) if (glyph.PackId >= 0) ImFontAtlasPackDiscardRect(atlas, glyph.PackId); font->BuildClearGlyphs(); + font->FallbackChar = font->EllipsisChar = 0; +} +// Discard old glyphs and reload font. Use if changing font size. +void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font) +{ + ImFontAtlasBuildDiscardFontGlyphs(atlas, font); for (int src_n = 0; src_n < font->SourcesCount; src_n++) { ImFontConfig* src = (ImFontConfig*)(void*)&font->Sources[src_n]; @@ -3505,6 +3570,9 @@ void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font) ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, src); // Technically this is called for each source sub-font, tho 99.9% of the time the first one fills everything. } + + // Notify external systems + ImFontAtlasBuildNotifySetFont(atlas, font, font); } // Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* @@ -4023,11 +4091,13 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src->FontData, src->FontNo); if (font_offset < 0) { + IM_DELETE(bd_font_data); IM_ASSERT_USER_ERROR(0, "stbtt_GetFontOffsetForIndex(): FontData is incorrect, or FontNo cannot be found."); return false; } if (!stbtt_InitFont(&bd_font_data->FontInfo, (unsigned char*)src->FontData, font_offset)) { + IM_DELETE(bd_font_data); IM_ASSERT_USER_ERROR(0, "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); return false; } diff --git a/imgui_internal.h b/imgui_internal.h index 48090ee90..f340b8e5e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3717,6 +3717,7 @@ IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); From a2bc3d81c2f1866dc6abc454221adfb6b5c0ef43 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 27 Dec 2024 11:23:22 +0100 Subject: [PATCH 0921/2359] Fonts: Fixed support for multiple contexts. --- imgui.cpp | 7 +++-- imgui.h | 3 +- imgui_draw.cpp | 75 ++++++++++++++++++++++++------------------------ imgui_internal.h | 1 - 4 files changed, 44 insertions(+), 42 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index adb1e84f1..0cf8bce21 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5184,7 +5184,8 @@ static void ImGui::UpdateTexturesNewFrame() // FIXME-NEWATLAS: How to reach/target all atlas? ImGuiContext& g = *GImGui; ImFontAtlas* atlas = g.IO.Fonts; - ImFontAtlasUpdateNewFrame(atlas); + if (g.FontAtlasOwnedByContext) + ImFontAtlasUpdateNewFrame(atlas); } // Build a single texture list @@ -5245,7 +5246,7 @@ void ImGui::NewFrame() if (!atlas->TexIsBuilt && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) ImFontAtlasBuildMain(atlas); else // Legacy backend - IM_ASSERT(atlas->TexIsBuilt && "Backend does not support ImGuiBackendFlags_RendererHasTexUpdates, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()."); + IM_ASSERT(atlas->TexIsBuilt && "Backend does not support ImGuiBackendFlags_RendererHasTextures, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()."); // Check and assert for various common IO and Configuration mistakes ErrorCheckNewFrameSanityChecks(); @@ -15615,7 +15616,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL")) { const ImFontLoader* loader_current = atlas->FontLoader; - BeginDisabled(!atlas->DrawListSharedData || !atlas->DrawListSharedData->RendererHasTextures); + BeginDisabled(!atlas->RendererHasTextures); #ifdef IMGUI_ENABLE_STB_TRUETYPE const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype(); if (RadioButton("stb_truetype", loader_current == loader_stbtruetype)) diff --git a/imgui.h b/imgui.h index e237e90ae..2fb54a511 100644 --- a/imgui.h +++ b/imgui.h @@ -3603,6 +3603,7 @@ struct ImFontAtlas ImTextureData* TexData; // Current texture ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. + bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context. bool TexIsBuilt; // Set when texture was built matching current font input bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight) @@ -3612,7 +3613,7 @@ struct ImFontAtlas //ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines int TexNextUniqueID; // Next value to be stored in TexData->UniqueID - ImDrawListSharedData* DrawListSharedData; // In principle this could become an array (e.g. multiple contexts using same atlas) + ImVector DrawListSharedDatas; // [Internal] Font builder ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public diff --git a/imgui_draw.cpp b/imgui_draw.cpp index faabec1d5..b6280afb6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -390,7 +390,6 @@ ImDrawListSharedData::ImDrawListSharedData() ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); } ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError); - RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. } ImDrawListSharedData::~ImDrawListSharedData() @@ -2580,6 +2579,7 @@ ImFontAtlas::ImFontAtlas() memset(this, 0, sizeof(*this)); TexDesiredFormat = ImTextureFormat_RGBA32; TexGlyphPadding = 1; + RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. TexRef._TexData = NULL;// this; TexNextUniqueID = 1; Builder = NULL; @@ -2637,10 +2637,10 @@ void ImFontAtlas::ClearFonts() ClearInputData(); Fonts.clear_delete(); TexIsBuilt = false; - if (DrawListSharedData) + for (ImDrawListSharedData* shared_data : DrawListSharedDatas) { - DrawListSharedData->Font = NULL; - DrawListSharedData->FontScale = DrawListSharedData->FontSize = 0.0f; + shared_data->Font = NULL; + shared_data->FontScale = shared_data->FontSize = 0.0f; } } @@ -2681,18 +2681,21 @@ static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* at // time of an early call to Build(), it would be impossible for us to tell if the backend supports texture update. // - Without this hack, we would have quite a pitfall as many legacy codebases have an early call to Build(). // Whereas conversely, the portion of people using ImDrawList without ImGui is expected to be pathologically rare. - if (atlas->DrawListSharedData) - if (ImGuiContext* imgui_ctx = atlas->DrawListSharedData->Context) - atlas->DrawListSharedData->RendererHasTextures = (imgui_ctx->IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + if (ImGuiContext* imgui_ctx = shared_data->Context) + { + atlas->RendererHasTextures = (imgui_ctx->IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + break; + } } -// Called by NewFrame() +// Called by NewFrame(). When multiple context own the atlas, only the first one calls this. void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) { if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges) { ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); - IM_ASSERT_USER_ERROR(atlas->DrawListSharedData->RendererHasTextures == false, + IM_ASSERT_USER_ERROR(atlas->RendererHasTextures == false, "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build()."); } @@ -3050,7 +3053,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed // We allow old_font == new_font which forces updating all values (e.g. sizes) static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font) { - if (ImDrawListSharedData* shared_data = atlas->DrawListSharedData) + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) { if (shared_data->Font == old_font) shared_data->Font = new_font; @@ -3124,7 +3127,7 @@ int ImFontAtlas::AddCustomRectRegular(int width, int height) IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - if (DrawListSharedData && DrawListSharedData->RendererHasTextures) + if (RendererHasTextures) { ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); ImFontAtlasRect* r = ImFontAtlasPackGetRect(this, r_id); @@ -3220,7 +3223,7 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) // [LEGACY] For backends not supporting RendererHasTexUpdates: preload all glyphs ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); - if (atlas->DrawListSharedData && atlas->DrawListSharedData->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures + if (atlas->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures ImFontAtlasBuildPreloadAllGlyphRanges(atlas); atlas->TexIsBuilt = true; } @@ -3578,48 +3581,46 @@ void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font) // Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) { - IM_ASSERT(atlas->DrawListSharedData == NULL && data->FontAtlas == NULL); - atlas->DrawListSharedData = data; + IM_ASSERT(!atlas->DrawListSharedDatas.contains(data) && data->FontAtlas == NULL); + atlas->DrawListSharedDatas.push_back(data); data->FontAtlas = atlas; } void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) { - IM_ASSERT(atlas->DrawListSharedData == data && data->FontAtlas == atlas); - atlas->DrawListSharedData = data; + IM_ASSERT(atlas->DrawListSharedDatas.contains(data) && data->FontAtlas == atlas); + atlas->DrawListSharedDatas.find_erase(data); data->FontAtlas = NULL; } // Update texture identifier in all active draw lists void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex) { - ImDrawListSharedData* shared_data = atlas->DrawListSharedData; - if (shared_data == NULL) - return; - for (ImDrawList* draw_list : shared_data->DrawLists) - { - // Replace in command-buffer - // (there is not need to replace in ImDrawListSplitter: current channel is in ImDrawList's CmdBuffer[], - // other channels will be on SetCurrentChannel() which already needs to compare CmdHeader anyhow) - if (draw_list->CmdBuffer.Size > 0 && draw_list->_CmdHeader.TexRef == old_tex) - draw_list->_SetTexture(new_tex); + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + for (ImDrawList* draw_list : shared_data->DrawLists) + { + // Replace in command-buffer + // (there is not need to replace in ImDrawListSplitter: current channel is in ImDrawList's CmdBuffer[], + // other channels will be on SetCurrentChannel() which already needs to compare CmdHeader anyhow) + if (draw_list->CmdBuffer.Size > 0 && draw_list->_CmdHeader.TexRef == old_tex) + draw_list->_SetTexture(new_tex); - // Replace in stack - for (ImTextureRef& stacked_tex : draw_list->_TextureStack) - if (stacked_tex == old_tex) - stacked_tex = new_tex; - } + // Replace in stack + for (ImTextureRef& stacked_tex : draw_list->_TextureStack) + if (stacked_tex == old_tex) + stacked_tex = new_tex; + } } // Update texture coordinates in all draw list shared context void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) { - ImDrawListSharedData* shared_data = atlas->DrawListSharedData; - if (shared_data == NULL) - return; - shared_data->FontAtlas = atlas; - shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; - shared_data->TexUvLines = atlas->TexUvLines; + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + { + shared_data->FontAtlas = atlas; + shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; + shared_data->TexUvLines = atlas->TexUvLines; + } } // Set current texture. This is mostly called from AddTexture() + to handle a failed resize. diff --git a/imgui_internal.h b/imgui_internal.h index f340b8e5e..830ca9c6e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -821,7 +821,6 @@ struct IMGUI_API ImDrawListSharedData ImVec2 ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle. float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo() ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) - bool RendererHasTextures; // Copy of (GetIO().BackendFlags & ImGuiBackendFlags_RendererHasTextures). ImDrawListSharedData(); ~ImDrawListSharedData(); From 4ff1631b316fe849da9a649cf30a79aad752d8bb Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Jan 2025 19:07:40 +0100 Subject: [PATCH 0922/2359] Fonts: Rasterizing ellipsis character from dot as one glyph + avoid preloading if it not needed. # Conflicts: # imgui.cpp --- imgui.cpp | 5 ++- imgui.h | 7 ++-- imgui_draw.cpp | 85 +++++++++++++++++++++++++++++++++++++++--------- imgui_internal.h | 1 + 4 files changed, 75 insertions(+), 23 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0cf8bce21..7ac49382e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3738,7 +3738,7 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con const float font_size = draw_list->_Data->FontSize; const float font_scale = draw_list->_Data->FontScale; const char* text_end_ellipsis = NULL; - const float ellipsis_width = font->EllipsisWidth * font_scale; + const float ellipsis_width = font->GetCharAdvance(font->EllipsisChar) * font_scale; // 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); @@ -3754,8 +3754,7 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con RenderTextClippedEx(draw_list, pos_min, pos_max, text, 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)); - for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale) - font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect); + font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect); } else { diff --git a/imgui.h b/imgui.h index 2fb54a511..d5136e2a6 100644 --- a/imgui.h +++ b/imgui.h @@ -3648,13 +3648,10 @@ struct ImFont // [Internal] Members: Cold ~32/40/60 bytes // Conceptually Sources[] is the list of font sources merged to create this font. short SourcesCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. - short EllipsisCharCount; // 1 // out // 1 or 3 - ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). - ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances ImFontAtlas* ContainerAtlas; // 4-8 // out // What we has been loaded into - float EllipsisWidth; // 4 // out // Total ellipsis Width - float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 + ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). + ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b6280afb6..83212712f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2462,6 +2462,7 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasTextureBlockConvert() // - ImFontAtlasTextureBlockPostProcess() // - ImFontAtlasTextureBlockPostProcessMultiply() +// - ImFontAtlasTextureBlockFill() // - ImFontAtlasTextureBlockCopy() // - ImFontAtlasTextureBlockQueueUpload() //----------------------------------------------------------------------------- @@ -2490,6 +2491,7 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildUpdateBasicTexData() // - ImFontAtlasBuildUpdateLinesTexData() // - ImFontAtlasBuildAddFont() +// - ImFontAtlasBuildSetupFontCreateEllipsisFromDot() // - ImFontAtlasBuildSetupFontSpecialGlyphs() // - ImFontAtlasBuildReloadFont() //----------------------------------------------------------------------------- @@ -2820,10 +2822,29 @@ void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data } } -// Convert block from one texture to another +// Fill with single color. We don't use this directly but it is convenient for anyone working on uploading custom rects. +void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col) +{ + if (dst_tex->Format == ImTextureFormat_Alpha8) + { + ImU8 col_a = (col >> IM_COL32_A_SHIFT) & 0xFF; + for (int y = 0; y < h; y++) + memset((ImU8*)dst_tex->GetPixelsAt(dst_x, dst_y + y), col_a, w); + } + else + { + for (int y = 0; y < h; y++) + { + ImU32* p = (ImU32*)(void*)dst_tex->GetPixelsAt(dst_x, dst_y + y); + for (int x = w; x > 0; x--, p++) + *p = col; + } + } +} + +// Copy block from one texture to another void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h) { - IM_ASSERT(src_tex != dst_tex); IM_ASSERT(src_tex->Pixels != NULL && dst_tex->Pixels != NULL); IM_ASSERT(src_tex->Format == dst_tex->Format); IM_ASSERT(src_x >= 0 && src_x + w <= src_tex->Width); @@ -3483,6 +3504,44 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) return true; } +// Rasterize our own ellipsis character from a dot. +// This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. +// FIXME-NEWATLAS: This borrows too much from FontBackend_FontAddGlyph() and suggest that we should add further helpers. +static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFontConfig* cfg, const ImFontGlyph* dot_glyph) +{ + ImFont* font = cfg->DstFont; + + ImFontAtlasRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_glyph->PackId); + const int dot_spacing = 1; + const float dot_step = (dot_glyph->X1 - dot_glyph->X0) + dot_spacing; + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, (dot_r->w * 3 + dot_spacing * 2), dot_r->h); + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + font->MetricsTotalSurface += r->w * r->h; + + ImFontGlyph glyph; + glyph.Codepoint = (ImWchar)0x0085; // FIXME: Using arbitrary codepoint. + glyph.AdvanceX = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + dot_step * 3.0f - dot_spacing); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. + glyph.X0 = dot_glyph->X0; + glyph.Y0 = dot_glyph->Y0; + glyph.X1 = dot_glyph->X0 + dot_step * 3 - dot_spacing; + glyph.Y1 = dot_glyph->Y1; + glyph.U0 = (r->x) * atlas->TexUvScale.x; + glyph.V0 = (r->y) * atlas->TexUvScale.y; + glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + glyph.Visible = true; + glyph.PackId = pack_id; + font->BuildRegisterGlyph(cfg, &glyph); + font->EllipsisChar = (ImWchar)glyph.Codepoint; + + // Copy to texture, post-process and queue update for backend + // FIXME-NEWATLAS-V2: Dot glyph is already post-processed as this point, so this would damage it. + ImTextureData* tex = atlas->TexData; + for (int n = 0; n < 3; n++) + ImFontAtlasTextureBlockCopy(tex, dot_r->x, dot_r->y, tex, r->x + (dot_r->w + dot_spacing) * n, r->y, dot_r->w, dot_r->h); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); +} + // Load/identify special glyphs // (note that this is called again for fonts with MergeMode) void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src) @@ -3526,23 +3585,19 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* sr // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots. const ImWchar ellipsis_chars[] = { src->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 }; if (font->EllipsisChar == 0) - if (const ImFontGlyph* glyph = LoadFirstExistingGlyph(font, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars))) - { - font->EllipsisChar = (ImWchar)glyph->Codepoint; - font->EllipsisCharCount = 1; - font->EllipsisWidth = font->EllipsisCharStep = glyph->X1; - } + for (ImWchar candidate_char : ellipsis_chars) + if (candidate_char != 0 && font->IsGlyphInFont(candidate_char)) + { + font->EllipsisChar = candidate_char; + break; + } if (font->EllipsisChar == 0) { - // FIXME-NEWATLAS-V2: We can now rasterize this into a regular character and register it! const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; if (const ImFontGlyph* dot_glyph = LoadFirstExistingGlyph(font, dots_chars, IM_ARRAYSIZE(dots_chars))) - { - font->EllipsisChar = (ImWchar)dot_glyph->Codepoint; - font->EllipsisCharCount = 3; - font->EllipsisCharStep = (float)(int)(dot_glyph->X1 - dot_glyph->X0) + 1.0f; - font->EllipsisWidth = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + font->EllipsisCharStep * 3.0f - 1.0f); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. - } + ImFontAtlasBuildSetupFontCreateEllipsisFromDot(atlas, src, dot_glyph); + else + font->EllipsisChar = (ImWchar)' '; } font->LockSingleSrcConfigIdx = -1; } diff --git a/imgui_internal.h b/imgui_internal.h index 830ca9c6e..bc98e83d2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3736,6 +3736,7 @@ IMGUI_API void ImFontAtlasUpdateNewFrame(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); IMGUI_API void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor); +IMGUI_API void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col); IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h); IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h); From b06f3c6d1d02816b646a02fa3b30a15325d105fe Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 9 Jan 2025 20:48:50 +0100 Subject: [PATCH 0923/2359] Fonts: turn public facing BuildRegisterGlyph() into ImFontAtlasBuildAddFontGlyph() thats sets up UV. --- imgui.h | 1 - imgui_draw.cpp | 55 +++++++++++++++++--------------- imgui_internal.h | 2 ++ misc/freetype/imgui_freetype.cpp | 10 ++---- 4 files changed, 34 insertions(+), 34 deletions(-) diff --git a/imgui.h b/imgui.h index d5136e2a6..c4e8818d1 100644 --- a/imgui.h +++ b/imgui.h @@ -3687,7 +3687,6 @@ struct ImFont IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst);// , bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); IMGUI_API ImFontGlyph* BuildLoadGlyph(ImWchar c); - IMGUI_API void BuildRegisterGlyph(ImFontConfig* src, const ImFontGlyph* glyph); IMGUI_API void BuildGrowIndex(int new_size); IMGUI_API void BuildClearGlyphs(); }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 83212712f..f8797841b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3507,9 +3507,9 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) // Rasterize our own ellipsis character from a dot. // This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. // FIXME-NEWATLAS: This borrows too much from FontBackend_FontAddGlyph() and suggest that we should add further helpers. -static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFontConfig* cfg, const ImFontGlyph* dot_glyph) +static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFontConfig* src, const ImFontGlyph* dot_glyph) { - ImFont* font = cfg->DstFont; + ImFont* font = src->DstFont; ImFontAtlasRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_glyph->PackId); const int dot_spacing = 1; @@ -3525,13 +3525,9 @@ static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, I glyph.Y0 = dot_glyph->Y0; glyph.X1 = dot_glyph->X0 + dot_step * 3 - dot_spacing; glyph.Y1 = dot_glyph->Y1; - glyph.U0 = (r->x) * atlas->TexUvScale.x; - glyph.V0 = (r->y) * atlas->TexUvScale.y; - glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; - glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; glyph.Visible = true; glyph.PackId = pack_id; - font->BuildRegisterGlyph(cfg, &glyph); + ImFontAtlasBuildAddFontGlyph(atlas, font, NULL, &glyph); font->EllipsisChar = (ImWchar)glyph.Codepoint; // Copy to texture, post-process and queue update for backend @@ -3577,7 +3573,7 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* sr ImFontGlyph tab_glyph; tab_glyph.Codepoint = '\t'; tab_glyph.AdvanceX = space_glyph->AdvanceX * IM_TABSIZE; - font->BuildRegisterGlyph(font->Sources, &tab_glyph); + ImFontAtlasBuildAddFontGlyph(atlas, font, src, &tab_glyph); } // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). @@ -4282,13 +4278,9 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, glyph.Y0 = y0 * recip_v + font_off_y; glyph.X1 = (x0 + (int)r->w) * recip_h + font_off_x; glyph.Y1 = (y0 + (int)r->h) * recip_v + font_off_y; - glyph.U0 = (r->x) * atlas->TexUvScale.x; - glyph.V0 = (r->y) * atlas->TexUvScale.y; - glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; - glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; glyph.Visible = true; glyph.PackId = pack_id; - font->BuildRegisterGlyph(src, &glyph); + ImFontAtlasBuildAddFontGlyph(atlas, font, src, &glyph); // Copy to texture, post-process and queue update for backend ImTextureData* tex = atlas->TexData; @@ -4300,7 +4292,7 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, } else { - font->BuildRegisterGlyph(src, &glyph); + ImFontAtlasBuildAddFontGlyph(atlas, font, src, &glyph); } return true; @@ -4699,12 +4691,23 @@ void ImFont::BuildGrowIndex(int new_size) // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. // Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). // 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. -void ImFont::BuildRegisterGlyph(ImFontConfig* src, const ImFontGlyph* in_glyph) +ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, const ImFontGlyph* in_glyph) { - int glyph_idx = Glyphs.Size; - Glyphs.push_back(*in_glyph); - ImFontGlyph& glyph = Glyphs[glyph_idx]; - IM_ASSERT(Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. + int glyph_idx = font->Glyphs.Size; + font->Glyphs.push_back(*in_glyph); + ImFontGlyph& glyph = font->Glyphs[glyph_idx]; + IM_ASSERT(font->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. + + // Set UV from packed rectangle + if (in_glyph->PackId >= 0) + { + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, in_glyph->PackId); + IM_ASSERT(in_glyph->U0 == 0.0f && in_glyph->V0 == 0.0f && in_glyph->U1 == 0.0f && in_glyph->V1 == 0.0f); + glyph.U0 = (r->x) * atlas->TexUvScale.x; + glyph.V0 = (r->y) * atlas->TexUvScale.y; + glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + } if (src != NULL) { @@ -4725,17 +4728,17 @@ void ImFont::BuildRegisterGlyph(ImFontConfig* src, const ImFontGlyph* in_glyph) glyph.AdvanceX = advance_x + src->GlyphExtraAdvanceX; } if (glyph.Colored) - ContainerAtlas->TexPixelsUseColors = ContainerAtlas->TexData->UseColors = true; + atlas->TexPixelsUseColors = atlas->TexData->UseColors = true; // Update lookup tables int codepoint = glyph.Codepoint; - BuildGrowIndex(codepoint + 1); - IndexAdvanceX[codepoint] = glyph.AdvanceX; - IndexLookup[codepoint] = (ImU16)glyph_idx; - - // Mark 4K page as used + font->BuildGrowIndex(codepoint + 1); + font->IndexAdvanceX[codepoint] = glyph.AdvanceX; + font->IndexLookup[codepoint] = (ImU16)glyph_idx; const int page_n = codepoint / 8192; - Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); + font->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); + + return &glyph; } void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst) diff --git a/imgui_internal.h b/imgui_internal.h index bc98e83d2..212dafbaf 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3721,6 +3721,8 @@ IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFon IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); +IMGUI_API ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* cfg, const ImFontGlyph* in_glyph); + IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index efe8612ba..92238f7fd 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -529,14 +529,10 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon glyph.Y0 = glyph_off_y * recip_v + font_off_y; glyph.X1 = (glyph_off_x + w) * recip_h + font_off_x; glyph.Y1 = (glyph_off_y + h) * recip_v + font_off_y; - glyph.U0 = (r->x) * atlas->TexUvScale.x; - glyph.V0 = (r->y) * atlas->TexUvScale.y; - glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; - glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; - glyph.PackId = pack_id; glyph.Visible = true; glyph.Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); - font->BuildRegisterGlyph(src, &glyph); + glyph.PackId = pack_id; + ImFontAtlasBuildAddFontGlyph(atlas, font, src, &glyph); // Copy to texture, post-process and queue update for backend ImTextureData* tex = atlas->TexData; @@ -548,7 +544,7 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon } else { - font->BuildRegisterGlyph(src, &glyph); + ImFontAtlasBuildAddFontGlyph(atlas, font, src, &glyph); } return true; } From 14614f561b966913d595eb8904e04f66ba23ffb1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 9 Jan 2025 20:57:20 +0100 Subject: [PATCH 0924/2359] Textures: Ensure UpdateBox is set on texture _WantCreate state too. --- imgui_draw.cpp | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f8797841b..d8d46e279 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2435,6 +2435,8 @@ void ImTextureData::Create(ImTextureFormat format, int w, int h) Pixels = (unsigned char*)IM_ALLOC(Width * Height * BytesPerPixel); IM_ASSERT(Pixels != NULL); memset(Pixels, 0, Width * Height * BytesPerPixel); + UpdateRect.x = UpdateRect.y = (unsigned short)~0; + UpdateRect.w = UpdateRect.h = 0; } void ImTextureData::DestroyPixels() @@ -2705,9 +2707,12 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) { ImTextureData* tex = atlas->TexList[tex_n]; bool remove_from_list = false; - tex->Updates.resize(0); - tex->UpdateRect.x = tex->UpdateRect.y = (unsigned short)~0; - tex->UpdateRect.w = tex->UpdateRect.h = 0; + if (tex->Status == ImTextureStatus_OK) + { + tex->Updates.resize(0); + tex->UpdateRect.x = tex->UpdateRect.y = (unsigned short)~0; + tex->UpdateRect.w = tex->UpdateRect.h = 0; + } if (tex->Status == ImTextureStatus_Destroyed) { @@ -2858,22 +2863,23 @@ void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, I // Queue texture block update for renderer backend void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h) { - // Queue texture update (no need to queue if status is _WantCreate) - IM_ASSERT(atlas); + IM_ASSERT(tex->Status != ImTextureStatus_WantDestroy && tex->Status != ImTextureStatus_Destroyed); + IM_ASSERT(x >= 0 && x <= 0xFFFF && y >= 0 && y <= 0xFFFF && w >= 0 && x + w <= 0x10000 && h >= 0 && y + h <= 0x10000); + IM_UNUSED(atlas); + + ImTextureRect req = { (unsigned short)x, (unsigned short)y, (unsigned short)w, (unsigned short)h }; + int new_x1 = ImMax(tex->UpdateRect.w == 0 ? 0 : tex->UpdateRect.x + tex->UpdateRect.w, req.x + req.w); + int new_y1 = ImMax(tex->UpdateRect.h == 0 ? 0 : tex->UpdateRect.y + tex->UpdateRect.h, req.y + req.h); + tex->UpdateRect.x = ImMin(tex->UpdateRect.x, req.x); + tex->UpdateRect.y = ImMin(tex->UpdateRect.y, req.y); + tex->UpdateRect.w = (unsigned short)(new_x1 - tex->UpdateRect.x); + tex->UpdateRect.h = (unsigned short)(new_y1 - tex->UpdateRect.y); + + // No need to queue if status is _WantCreate if (tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantUpdates) { - IM_ASSERT(x >= 0 && x <= 0xFFFF && y >= 0 && y <= 0xFFFF && w >= 0 && x + w <= 0x10000 && h >= 0 && y + h <= 0x10000); - ImTextureRect req = { (unsigned short)x, (unsigned short)y, (unsigned short)w, (unsigned short)h }; tex->Status = ImTextureStatus_WantUpdates; tex->Updates.push_back(req); - int new_x1 = ImMax(tex->UpdateRect.w == 0 ? 0 : tex->UpdateRect.x + tex->UpdateRect.w, req.x + req.w); - int new_y1 = ImMax(tex->UpdateRect.h == 0 ? 0 : tex->UpdateRect.y + tex->UpdateRect.h, req.y + req.h); - IM_ASSERT(new_x1 < 0x8000); - IM_ASSERT(new_y1 < 0x8000); - tex->UpdateRect.x = ImMin(tex->UpdateRect.x, req.x); - tex->UpdateRect.y = ImMin(tex->UpdateRect.y, req.y); - tex->UpdateRect.w = (unsigned short)(new_x1 - tex->UpdateRect.x); - tex->UpdateRect.h = (unsigned short)(new_y1 - tex->UpdateRect.y); } } @@ -3403,6 +3409,7 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r->y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X'); } } + ImFontAtlasTextureBlockQueueUpload(atlas, atlas->TexData, r->x, r->y, r->w, r->h); atlas->TexUvWhitePixel = ImVec2((r->x + 0.5f) * atlas->TexUvScale.x, (r->y + 0.5f) * atlas->TexUvScale.y); } @@ -3472,6 +3479,7 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } //----------------------------------------------------------------------------------------------------------------------------- From 2137b3448b61c389d706da3deed092e32128f5c8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 9 Jan 2025 23:04:00 +0100 Subject: [PATCH 0925/2359] Textures: Added atlas's TexMinWidth/TexMinHeight/TexMaxWidth/TexMaxHeight. Fixed ImFontAtlasBuildGetTextureSizeEstimate(). Basic error handling on OOM. --- imgui.h | 4 ++++ imgui_draw.cpp | 39 +++++++++++++++++++++++++------- imgui_internal.h | 2 +- misc/freetype/imgui_freetype.cpp | 7 ++++++ 4 files changed, 43 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index c4e8818d1..56366ae1e 100644 --- a/imgui.h +++ b/imgui.h @@ -3596,6 +3596,10 @@ struct ImFontAtlas ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8). int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). + int TexMinWidth; // Minimum desired texture width. Must be a power of two. Default to 512. + int TexMinHeight; // Minimum desired texture height. Must be a power of two. Default to 128. + int TexMaxWidth; // Maximum desired texture width. Must be a power of two. Default to 8192. + int TexMaxHeight; // Maximum desired texture height. Must be a power of two. Default to 8192. void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). // [Internal] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d8d46e279..040157190 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2576,13 +2576,16 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3 #define IM_FONTGLYPH_INDEX_UNUSED ((ImU16)-1) // 0xFFFF #define IM_FONTGLYPH_INDEX_NOT_FOUND ((ImU16)-2) // 0xFFFE -#define IM_FONTATLAS_DEFAULT_TEXTURE_SIZE ImVec2i(512, 128) ImFontAtlas::ImFontAtlas() { memset(this, 0, sizeof(*this)); TexDesiredFormat = ImTextureFormat_RGBA32; TexGlyphPadding = 1; + TexMinWidth = 512; + TexMinHeight = 128; + TexMaxWidth = 8192; + TexMaxHeight = 8192; RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. TexRef._TexData = NULL;// this; TexNextUniqueID = 1; @@ -3248,7 +3251,7 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) if (atlas->Sources.Size == 0) atlas->AddFontDefault(); - // [LEGACY] For backends not supporting RendererHasTexUpdates: preload all glyphs + // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); if (atlas->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures ImFontAtlasBuildPreloadAllGlyphRanges(atlas); @@ -3268,7 +3271,7 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon return; IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); - // Note that texture size estimate is likely incorrect in this situation, as Freetype backend doesn't use oversampling. + // Note that texture size estimate is likely incorrect in this situation, as FreeType backend doesn't use oversampling. ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); ImFontAtlasBuildDestroy(atlas); @@ -3390,6 +3393,8 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ if (add_and_draw) builder->PackIdMouseCursors = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); + if (builder->PackIdMouseCursors < 0) + return; ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdMouseCursors); // Draw to texture @@ -3424,6 +3429,8 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ ImFontAtlasBuilder* builder = atlas->Builder; if (add_and_draw) builder->PackIdLinesTexData = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); + if (builder->PackIdLinesTexData < 0) + return; ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdLinesTexData); // Register texture region for thick lines @@ -3813,6 +3820,7 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ // FIXME-NEWATLAS-V2: What to do when reaching limits exposed by backend? // FIXME-NEWATLAS-V2: does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h)); + IM_ASSERT(ImIsPowerOfTwo(atlas->TexMinWidth) && ImIsPowerOfTwo(atlas->TexMaxWidth) && ImIsPowerOfTwo(atlas->TexMinHeight) && ImIsPowerOfTwo(atlas->TexMaxHeight)); // Grow texture so it follows roughly a square. // FIXME-NEWATLAS-V1: Take account of RectsDiscardedSurface: may not need to grow. @@ -3823,19 +3831,24 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ const int pack_padding = atlas->TexGlyphPadding; new_tex_w = ImMax(new_tex_w, ImUpperPowerOfTwo(builder->MaxRectSize.x + pack_padding)); new_tex_h = ImMax(new_tex_h, ImUpperPowerOfTwo(builder->MaxRectSize.y + pack_padding)); + new_tex_w = ImClamp(new_tex_w, atlas->TexMinWidth, atlas->TexMaxWidth); + new_tex_h = ImClamp(new_tex_h, atlas->TexMinHeight, atlas->TexMaxHeight); + if (new_tex_w == old_tex_w && new_tex_h == old_tex_h) + return; ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); } -// FIXME-NEWATLAS: Expose atlas->TexMinWidth etc. ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) { + int min_w = ImUpperPowerOfTwo(atlas->TexMinWidth); + int min_h = ImUpperPowerOfTwo(atlas->TexMinHeight); if (atlas->Builder == NULL || atlas->TexData == NULL || atlas->TexData->Status == ImTextureStatus_WantDestroy) - return IM_FONTATLAS_DEFAULT_TEXTURE_SIZE; + return ImVec2i(min_w, min_h); ImFontAtlasBuilder* builder = atlas->Builder; - const int min_w = ImMax(builder->MaxRectSize.x, 512); - const int min_h = builder->MaxRectSize.y; + min_w = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.x), min_w); + min_h = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.y), min_h); const int surface_approx = atlas->_PackedSurface - builder->RectsDiscardedSurface; // Expected surface after repack const int surface_sqrt = (int)sqrtf((float)surface_approx); @@ -3855,6 +3868,8 @@ ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) new_tex_h = ImUpperPowerOfTwo(new_tex_h); new_tex_w = ImMax(min_w, (int)((surface_approx + new_tex_h - 1) / new_tex_h)); } + + IM_ASSERT(ImIsPowerOfTwo(new_tex_w) && ImIsPowerOfTwo(new_tex_h)); return ImVec2i(new_tex_w, new_tex_h); } @@ -3894,7 +3909,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) } // Create initial texture size if (atlas->TexData == NULL) - ImFontAtlasBuildAddTexture(atlas, IM_FONTATLAS_DEFAULT_TEXTURE_SIZE.x, IM_FONTATLAS_DEFAULT_TEXTURE_SIZE.y); + ImFontAtlasBuildAddTexture(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); const bool builder_is_new = (builder == NULL); if (builder_is_new) @@ -4051,6 +4066,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { + IM_ASSERT(id >= 0); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; IM_ASSERT(index_entry->Used); @@ -4255,6 +4271,13 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, const int w = (x1 - x0 + oversample_h - 1); const int h = (y1 - y0 + oversample_v - 1); ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); + if (pack_id < 0) + { + // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) + IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); + return false; + } + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); font->MetricsTotalSurface += w * h; diff --git a/imgui_internal.h b/imgui_internal.h index 212dafbaf..2e84a5554 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3696,7 +3696,7 @@ struct ImFontAtlasBuilder ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. ImFontAtlasRectId PackIdLinesTexData; - ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); RectsIndexFreeListStart = -1; } + ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } }; // FIXME-NEWATLAS: Cleanup diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 92238f7fd..b388d1531 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -509,6 +509,13 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon if (is_visible) { ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); + if (pack_id < 0) + { + // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) + IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); + return false; + } + ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); font->MetricsTotalSurface += w * h; From 8ed4e2dde7a2832c28d2c20a6a5f97220a0e3d9f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 17:56:36 +0100 Subject: [PATCH 0926/2359] Fonts: Basic heuristic to repack instead of growing. Moved rects count/surface to internals. --- imgui.cpp | 4 ++-- imgui.h | 2 -- imgui_draw.cpp | 33 ++++++++++++++++++++++----------- imgui_internal.h | 3 +++ 4 files changed, 27 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7ac49382e..e617a84d7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15594,7 +15594,7 @@ static void MetricsHelpMarker(const char* desc) } #ifdef IMGUI_ENABLE_FREETYPE -namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetBackendIOForFreeType(); } +namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); } #endif // [DEBUG] List fonts in a font atlas and display its texture @@ -15628,7 +15628,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) #endif SameLine(); #ifdef IMGUI_ENABLE_FREETYPE - const ImFontLoader* loader_freetype = ImGuiFreeType::GetBackendIOForFreeType(); + const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader(); if (RadioButton("FreeType", loader_current == loader_freetype)) ImFontAtlasBuildSetupFontLoader(atlas, loader_freetype); #else diff --git a/imgui.h b/imgui.h index 56366ae1e..c04d1175a 100644 --- a/imgui.h +++ b/imgui.h @@ -3626,8 +3626,6 @@ struct ImFontAtlas void* FontLoaderData; // Font backend opaque storage unsigned int FontBuilderFlags; // [FIXME: Should be called FontLoaderFlags] Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. . Per-font override is also available in ImFontConfig. int RefCount; // Number of contexts using this atlas - int _PackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. - int _PackedRects; // Number of packed rectangles. // [Obsolete] //int TexDesiredWidth; // OBSOLETED in 1.91.5 (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 040157190..65e806c54 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2504,6 +2504,7 @@ void ImTextureData::DestroyPixels() //----------------------------------------------------------------------------- // - ImFontAtlasBuildSetTexture() // - ImFontAtlasBuildAddTexture() +// - ImFontAtlasBuildMakeSpace() // - ImFontAtlasBuildRepackTexture() // - ImFontAtlasBuildGrowTexture() // - ImFontAtlasBuildCompactTexture() @@ -3521,7 +3522,7 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) // Rasterize our own ellipsis character from a dot. // This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. -// FIXME-NEWATLAS: This borrows too much from FontBackend_FontAddGlyph() and suggest that we should add further helpers. +// FIXME-NEWATLAS: This borrows too much from FontLoader's FontAddGlyph() and suggest that we should add further helpers. static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFontConfig* src, const ImFontGlyph* dot_glyph) { ImFont* font = src->DstFont; @@ -3823,7 +3824,7 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ IM_ASSERT(ImIsPowerOfTwo(atlas->TexMinWidth) && ImIsPowerOfTwo(atlas->TexMaxWidth) && ImIsPowerOfTwo(atlas->TexMinHeight) && ImIsPowerOfTwo(atlas->TexMaxHeight)); // Grow texture so it follows roughly a square. - // FIXME-NEWATLAS-V1: Take account of RectsDiscardedSurface: may not need to grow. + // Caller should be taking account of RectsDiscardedSurface and may not need to grow. int new_tex_w = (old_tex_h < old_tex_w) ? old_tex_w : old_tex_w * 2; int new_tex_h = (old_tex_h < old_tex_w) ? old_tex_h * 2 : old_tex_h; @@ -3839,6 +3840,16 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); } +void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas) +{ + // Currently using a heuristic for repack without growing. + ImFontAtlasBuilder* builder = atlas->Builder; + if (builder->RectsDiscardedSurface < builder->RectsPackedSurface * 0.20f) + ImFontAtlasBuildGrowTexture(atlas); + else + ImFontAtlasBuildRepackTexture(atlas, atlas->TexData->Width, atlas->TexData->Height); +} + ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) { int min_w = ImUpperPowerOfTwo(atlas->TexMinWidth); @@ -3849,7 +3860,7 @@ ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) ImFontAtlasBuilder* builder = atlas->Builder; min_w = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.x), min_w); min_h = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.y), min_h); - const int surface_approx = atlas->_PackedSurface - builder->RectsDiscardedSurface; // Expected surface after repack + const int surface_approx = builder->RectsPackedSurface - builder->RectsDiscardedSurface; // Expected surface after repack const int surface_sqrt = (int)sqrtf((float)surface_approx); int new_tex_w; @@ -3893,10 +3904,10 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) ImFontAtlasBuilder* builder = atlas->Builder; // Select Backend - // - Note that we do not reassign to atlas->FontBackendIO, since it is likely to point to static data which + // - Note that we do not reassign to atlas->FontLoader, since it is likely to point to static data which // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are - // using a hot-reloading scheme that messes up static data, store your own instance of ImFontBackendIO somewhere - // and point to it instead of pointing directly to return value of the GetBackendIOXXX functions. + // using a hot-reloading scheme that messes up static data, store your own instance of FontLoader somewhere + // and point to it instead of pointing directly to return value of the GetFontLoaderXXX functions. if (atlas->FontLoader == NULL) { #ifdef IMGUI_ENABLE_FREETYPE @@ -3958,7 +3969,7 @@ void ImFontAtlasPackInit(ImFontAtlas * atlas) builder->PackNodes.resize(pack_node_count); IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque)); stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width, tex->Height, builder->PackNodes.Data, builder->PackNodes.Size); - atlas->_PackedSurface = atlas->_PackedRects = 0; + builder->RectsPackedSurface = builder->RectsPackedCount = 0; builder->MaxRectSize = ImVec2i(0, 0); builder->MaxRectBounds = ImVec2i(0, 0); } @@ -4041,14 +4052,14 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon return -1; } - // Resize atlas! (this should be a rare event) - ImFontAtlasBuildGrowTexture(atlas); + // Resize or repack atlas! (this should be a rare event) + ImFontAtlasBuildMakeSpace(atlas); } builder->MaxRectBounds.x = ImMax(builder->MaxRectBounds.x, r.x + r.w + pack_padding); builder->MaxRectBounds.y = ImMax(builder->MaxRectBounds.y, r.y + r.h + pack_padding); - atlas->_PackedSurface += (w + pack_padding) * (h + pack_padding); - atlas->_PackedRects++; + builder->RectsPackedCount++; + builder->RectsPackedSurface += (w + pack_padding) * (h + pack_padding); builder->Rects.push_back(r); if (overwrite_entry != NULL) diff --git a/imgui_internal.h b/imgui_internal.h index 2e84a5554..71019611a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3685,6 +3685,8 @@ struct ImFontAtlasBuilder ImVector RectsIndex; // ImFontAtlasRectId -> index into Rects[] ImVector TempBuffer; // Misc scratch buffer int RectsIndexFreeListStart;// First unused entry + int RectsPackedCount; // Number of packed rectangles. + int RectsPackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. int RectsDiscardedCount; int RectsDiscardedSurface; ImVec2i MaxRectSize; // Largest rectangle to pack (de-facto used as a "minimum texture size") @@ -3709,6 +3711,7 @@ IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); IMGUI_API ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h); IMGUI_API void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); From 288055180e097cf9260bae7cc15339382a02771a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 20:03:09 +0100 Subject: [PATCH 0927/2359] Fonts: Comments, remove ImFontAtlas facing BuildGrowTexture(), BuildCompactTexture(). Make IsBuilt() obsolete. --- imgui.cpp | 4 +- imgui.h | 9 ++--- imgui_draw.cpp | 97 +++++++++++++++++++++--------------------------- imgui_internal.h | 24 +++++------- 4 files changed, 58 insertions(+), 76 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e617a84d7..a505d5d6c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5180,7 +5180,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) static void ImGui::UpdateTexturesNewFrame() { - // FIXME-NEWATLAS: How to reach/target all atlas? + // FIXME-NEWATLAS-V2: If we aim to support multiple atlases used by same context: how to reach/target all atlases? ImGuiContext& g = *GImGui; ImFontAtlas* atlas = g.IO.Fonts; if (g.FontAtlasOwnedByContext) @@ -8607,7 +8607,7 @@ void ImGui::SetCurrentFont(ImFont* font) // - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID() // the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem // because we have a concrete need and a test bed for multiple atlas textures. -// FIXME-NEWATLAS: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ? +// FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ? void ImGui::PushFont(ImFont* font) { ImGuiContext& g = *GImGui; diff --git a/imgui.h b/imgui.h index c04d1175a..19c116cab 100644 --- a/imgui.h +++ b/imgui.h @@ -3336,6 +3336,7 @@ struct ImDrawData //----------------------------------------------------------------------------- // We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension. +// Most standard backends only support RGBA32 but we provide a single channel option for low-resource/embedded systems. enum ImTextureFormat { ImTextureFormat_RGBA32, // 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 @@ -3523,16 +3524,14 @@ struct ImFontAtlas IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* 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); - // FIXME-NEWATLAS: Clarify meaning/purpose IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) IMGUI_API void ClearCache(); // Clear cached glyphs and textures. + // As we are transitioning toward a new font system, we expect to obsolete those soon: 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 ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). IMGUI_API void ClearTexData(); // [OBSOLETE] Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. - IMGUI_API void BuildGrowTexture(); - IMGUI_API void BuildCompactTexture(); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). @@ -3544,8 +3543,8 @@ struct ImFontAtlas IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel void SetTexID(ImTextureID id) { TexRef._TexData = NULL; TexRef._TexID = id; } // Called by legacy backends. void SetTexID(ImTextureRef id) { TexRef = id; } // Called by legacy backends. + bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... #endif - bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... //------------------------------------------- // Glyph Ranges @@ -3693,7 +3692,7 @@ struct ImFont IMGUI_API void BuildClearGlyphs(); }; -// FIXME-NEWATLAS: Added indirection to avoid patching ImDrawCmd after texture updates. +// Added indirection to avoid patching ImDrawCmd after texture updates. inline ImTextureID ImDrawCmd::GetTexID() const { // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 65e806c54..3369aabe9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2451,16 +2451,14 @@ void ImTextureData::DestroyPixels() // [SECTION] ImFontAtlas, ImFontAtlasBuilder //----------------------------------------------------------------------------- // - Default texture data encoded in ASCII -// - ImFontAtlasBuilder +// - ImFontAtlas() +// - ImFontAtlas::Clear() +// - ImFontAtlas::ClearCache() // - ImFontAtlas::ClearInputData() // - ImFontAtlas::ClearTexData() // - ImFontAtlas::ClearFonts() -// - ImFontAtlas::Clear() -// - ImFontAtlas::ClearCache() -// - ImFontAtlas::BuildGrowTexture() -// - ImFontAtlas::BuildCompactTexture() -// - ImFontAtlasUpdateTextures() //----------------------------------------------------------------------------- +// - ImFontAtlasUpdateNewFrame() // - ImFontAtlasTextureBlockConvert() // - ImFontAtlasTextureBlockPostProcess() // - ImFontAtlasTextureBlockPostProcessMultiply() @@ -2468,9 +2466,9 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasTextureBlockCopy() // - ImFontAtlasTextureBlockQueueUpload() //----------------------------------------------------------------------------- -// - ImFontAtlas::Build() [legacy] // - ImFontAtlas::GetTexDataAsAlpha8() [legacy] // - ImFontAtlas::GetTexDataAsRGBA32() [legacy] +// - ImFontAtlas::Build() [legacy] //----------------------------------------------------------------------------- // - ImFontAtlas::AddFont() // - ImFontAtlas::AddFontDefault() @@ -2483,6 +2481,7 @@ void ImTextureData::DestroyPixels() //----------------------------------------------------------------------------- // - ImFontAtlas::AddCustomRectRegular() // - ImFontAtlas::AddCustomRectFontGlyph() +// - ImFontAtlas::GetCustomRectByIndex() // - ImFontAtlas::CalcCustomRectUV() // - ImFontAtlasGetMouseCursorTexData() //----------------------------------------------------------------------------- @@ -2495,6 +2494,8 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildAddFont() // - ImFontAtlasBuildSetupFontCreateEllipsisFromDot() // - ImFontAtlasBuildSetupFontSpecialGlyphs() +// - ImFontAtlasBuildDiscardFontGlyph() +// - ImFontAtlasBuildDiscardFontGlyphs() // - ImFontAtlasBuildReloadFont() //----------------------------------------------------------------------------- // - ImFontAtlasAddDrawListSharedData() @@ -2507,11 +2508,15 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildMakeSpace() // - ImFontAtlasBuildRepackTexture() // - ImFontAtlasBuildGrowTexture() +// - ImFontAtlasBuildRepackOrGrowTexture() +// - ImFontAtlasBuildGetTextureSizeEstimate() // - ImFontAtlasBuildCompactTexture() // - ImFontAtlasBuildInit() // - ImFontAtlasBuildDestroy() //----------------------------------------------------------------------------- // - ImFontAtlasPackInit() +// - ImFontAtlasPackAllocRectEntry() +// - ImFontAtlasPackDiscardRect() // - ImFontAtlasPackAddRect() // - ImFontAtlasPackGetRect() //----------------------------------------------------------------------------- @@ -2599,6 +2604,21 @@ ImFontAtlas::~ImFontAtlas() Clear(); } +void ImFontAtlas::Clear() +{ + ClearInputData(); + ClearTexData(); + ClearFonts(); +} + +void ImFontAtlas::ClearCache() +{ + ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(this); + ImFontAtlasBuildDestroy(this); + ImFontAtlasBuildAddTexture(this, new_tex_size.x, new_tex_size.y); + ImFontAtlasBuildInit(this); +} + void ImFontAtlas::ClearInputData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); @@ -2624,8 +2644,6 @@ void ImFontAtlas::ClearInputData() font->LockDisableLoading = true; } Sources.clear(); - //CustomRects.clear(); - // Important: we leave TexReady untouched } void ImFontAtlas::ClearTexData() @@ -2634,7 +2652,6 @@ void ImFontAtlas::ClearTexData() TexList.clear(); IM_DELETE(TexData); TexData = NULL; - // Important: we leave TexReady untouched } void ImFontAtlas::ClearFonts() @@ -2652,36 +2669,6 @@ void ImFontAtlas::ClearFonts() } } -void ImFontAtlas::Clear() -{ - //IM_DELETE(Builder); // FIXME-NEW-ATLAS: Clarify ClearXXX functions - //const ImFontLoader* font_loader = FontLoader; - //ImFontAtlasBuildSetupFontLoader(this, NULL); - ClearInputData(); - ClearTexData(); - ClearFonts(); - //ImFontAtlasBuildSetupFontLoader(this, font_loader); -} - -// FIXME-NEWATLAS: Too widespread purpose. Clarify each call site in current WIP demo. -void ImFontAtlas::ClearCache() -{ - ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(this); - ImFontAtlasBuildDestroy(this); - ImFontAtlasBuildAddTexture(this, new_tex_size.x, new_tex_size.y); - ImFontAtlasBuildInit(this); -} - -void ImFontAtlas::BuildGrowTexture() -{ - ImFontAtlasBuildGrowTexture(this, TexData->Width, TexData->Height); -} - -void ImFontAtlas::BuildCompactTexture() -{ - ImFontAtlasBuildCompactTexture(this); -} - static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* atlas) { // [LEGACY] Copy back the ImGuiBackendFlags_RendererHasTextures flag from ImGui context. @@ -2753,15 +2740,6 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) } } -// Source buffer may be written to (used for in-place mods). -// Post-process hooks may eventually be added here. -void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data) -{ - // Multiply operator (legacy) - if (data->FontSrc->RasterizerMultiply != 1.0f) - ImFontAtlasTextureBlockPostProcessMultiply(data, data->FontSrc->RasterizerMultiply); -} - 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) { IM_ASSERT(src_pixels != NULL && dst_pixels != NULL); @@ -2797,6 +2775,15 @@ void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFo } } +// Source buffer may be written to (used for in-place mods). +// Post-process hooks may eventually be added here. +void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data) +{ + // Multiply operator (legacy) + if (data->FontSrc->RasterizerMultiply != 1.0f) + ImFontAtlasTextureBlockPostProcessMultiply(data, data->FontSrc->RasterizerMultiply); +} + void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor) { unsigned char* pixels = data->Pixels; @@ -3753,10 +3740,9 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) new_tex->UseColors = old_tex->UseColors; IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d\n", old_tex->UniqueID, old_tex->Width, old_tex->Height, new_tex->UniqueID, new_tex->Width, new_tex->Height); - // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. - // Repack, lose discarded rectangle, copy pixels // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic. + // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. ImFontAtlasPackInit(atlas); ImVector old_rects; ImVector old_index = builder->RectsIndex; @@ -3819,7 +3805,7 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ old_tex_h = atlas->TexData->Height; // FIXME-NEWATLAS-V2: What to do when reaching limits exposed by backend? - // FIXME-NEWATLAS-V2: does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? + // FIXME-NEWATLAS-V2: Does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? Could we expose e.g. tex->UsedRect. IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h)); IM_ASSERT(ImIsPowerOfTwo(atlas->TexMinWidth) && ImIsPowerOfTwo(atlas->TexMaxWidth) && ImIsPowerOfTwo(atlas->TexMinHeight) && ImIsPowerOfTwo(atlas->TexMaxHeight)); @@ -4018,7 +4004,7 @@ void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) } // Important: Calling this may recreate a new texture and therefore change atlas->TexData -// FIXME-NEWATLAS-V2: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 +// FIXME-NEWFONTS: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry) { IM_ASSERT(w > 0 && w <= 0xFFFF); @@ -4190,9 +4176,10 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* } src->FontLoaderData = bd_font_data; - // FIXME-NEWATLAS-V2: reevaluate sizing metrics + // FIXME-NEWFONTS: reevaluate sizing metrics int oversample_h, oversample_v; ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); + if (src->SizePixels > 0.0f) { bd_font_data->ScaleForRasterX = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, src->SizePixels * src->RasterizerDensity) * oversample_h; @@ -4206,7 +4193,7 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* bd_font_data->ScaleForLayout = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, -src->SizePixels); } - // FIXME-NEWATLAS-V2: make use of line gap value + // FIXME-NEWFONTS: make use of line gap value int unscaled_ascent, unscaled_descent, unscaled_line_gap; stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); diff --git a/imgui_internal.h b/imgui_internal.h index 71019611a..2f0b5b5d7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -141,10 +141,10 @@ struct ImGuiTextIndex; // Maintain a line index for a text buffer. // ImDrawList/ImFontAtlas struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances +struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas +struct ImFontAtlasPostProcessData; // Data available to potential texture post-processing functions struct ImFontAtlasRect; // Packed rectangle (same as ImTextureRect) struct ImFontAtlasRectEntry; // Packed rectangle lookup entry -struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas -struct ImFontAtlasPostProcessData; // Data available to potential post-process functions // ImGui struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) @@ -3658,7 +3658,7 @@ struct ImFontAtlasRectEntry unsigned int Used : 1; }; -// Data available to potential post-process functions +// Data available to potential texture post-processing functions struct ImFontAtlasPostProcessData { ImFontAtlas* FontAtlas; @@ -3701,15 +3701,13 @@ struct ImFontAtlasBuilder ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } }; -// FIXME-NEWATLAS: Cleanup +IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader); IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); -IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); - IMGUI_API ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h); IMGUI_API void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h); @@ -3718,26 +3716,24 @@ IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas); IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, const ImFontGlyph* in_glyph); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font); -IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font); // <--- Your future new best friend! IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); -IMGUI_API ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* cfg, const ImFontGlyph* in_glyph); - IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); -IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); +IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); +IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); 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 void ImFontAtlasUpdateNewFrame(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); IMGUI_API void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor); From 953ce90d27d361d00b4e299aa4aa62fa49cfebf4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 20:25:16 +0100 Subject: [PATCH 0928/2359] Fonts: ImFontAtlasBuildInit() uses the occasion to sync HasTexUpdates from imgui context, narrowing the scope where it isn't set. --- imgui_draw.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3369aabe9..b253b5010 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3912,6 +3912,8 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (builder_is_new) builder = atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); + ImFontAtlasBuildUpdateRendererHasTexUpdatesFromContext(atlas); + ImFontAtlasPackInit(atlas); // Add required texture data From a509790a1c83f8b5727c590887c402f9fb31a2be Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Jan 2025 20:33:36 +0100 Subject: [PATCH 0929/2359] Fonts: Added back support for AddCustomRectFontGlyph() Legacy path naturally works. --- imgui.h | 2 +- imgui_draw.cpp | 130 +++++++++++++++++------------------------------ imgui_internal.h | 1 + 3 files changed, 48 insertions(+), 85 deletions(-) diff --git a/imgui.h b/imgui.h index 19c116cab..15e784b4b 100644 --- a/imgui.h +++ b/imgui.h @@ -3581,7 +3581,7 @@ struct ImFontAtlas // - Read docs/FONTS.md for more details about using colorful icons. // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. IMGUI_API int AddCustomRectRegular(int width, int height); - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); IMGUI_API ImFontAtlasCustomRect* GetCustomRectByIndex(int index); // [Internal] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b253b5010..af8913719 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3121,68 +3121,51 @@ void ImFontAtlas::RemoveFont(ImFont* font) ImFontAtlasBuildNotifySetFont(this, font, new_current_font); } -// FIXME-NEWATLAS-V1: Feature is broken for now. -/* - // Register custom rectangle glyphs - for (int i = 0; i < atlas->CustomRects.Size; i++) - { - const ImFontAtlasCustomRect* r = &atlas->CustomRects[i]; - if (r->Font == NULL || r->GlyphID == 0) - continue; - - // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, PixelSnapH - IM_ASSERT(r->Font->ContainerAtlas == atlas); - ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(r, &uv0, &uv1); - r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX); - if (r->GlyphColored) - r->Font->Glyphs.back().Colored = 1; - } -*/ - int ImFontAtlas::AddCustomRectRegular(int width, int height) { IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - if (RendererHasTextures) - { - ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); - ImFontAtlasRect* r = ImFontAtlasPackGetRect(this, r_id); - ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); - return r_id; - } - else - { - // FIXME-NEWATLAS-V1: Unfinished - ImFontAtlasCustomRect r; - r.Width = (unsigned short)width; - r.Height = (unsigned short)height; - //CustomRects.push_back(r); - //return CustomRects.Size - 1; // Return index + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); + if (r_id < 0) return -1; - } + ImFontAtlasRect* r = ImFontAtlasPackGetRect(this, r_id); + if (RendererHasTextures) + ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); + return r_id; } -int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset) +int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) { #ifdef IMGUI_USE_WCHAR32 - IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX); + IM_ASSERT(codepoint <= IM_UNICODE_CODEPOINT_MAX); #endif IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - ImFontAtlasCustomRect r; - r.Width = (unsigned short)width; - r.Height = (unsigned short)height; - r.GlyphID = id; - r.GlyphColored = 0; // Set to 1 manually to mark glyph as colored // FIXME: No official API for that (#8133) - r.GlyphAdvanceX = advance_x; - r.GlyphOffset = offset; - r.Font = font; - //CustomRects.push_back(r); - //return CustomRects.Size - 1; // Return index - return -1; + + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); + if (r_id < 0) + return -1; + ImFontAtlasRect* r = ImFontAtlasPackGetRect(this, r_id); + if (RendererHasTextures) + ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); + + if (font->IsGlyphLoaded(codepoint)) + ImFontAtlasBuildDiscardFontGlyph(this, font, (ImFontGlyph*)(void*)font->FindGlyph(codepoint)); + + ImFontGlyph glyph; + glyph.Codepoint = codepoint; + glyph.AdvanceX = advance_x; + glyph.X0 = offset.x; + glyph.Y0 = offset.y; + glyph.X1 = offset.x + r->w; + glyph.Y1 = offset.y + r->h; + glyph.Visible = true; + glyph.Colored = true; // FIXME: Arbitrary + glyph.PackId = r_id; + ImFontAtlasBuildAddFontGlyph(this, font, &font->Sources[0], &glyph); + return r_id; } ImFontAtlasCustomRect* ImFontAtlas::GetCustomRectByIndex(int idx) @@ -3308,41 +3291,6 @@ void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) } } -// FIXME-NEWATLAS: Unused -#if 0 -void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque) -{ - ImTextureData* tex = atlas->TexData; - stbrp_context* pack_context = (stbrp_context*)stbrp_context_opaque; - IM_ASSERT(pack_context != NULL); - - ImVector& user_rects = atlas->CustomRects; - IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong. -#ifdef __GNUC__ - if (user_rects.Size < 1) { __builtin_unreachable(); } // Workaround for GCC bug if IM_ASSERT() is defined to conditionally throw (see #5343) -#endif - - const int pack_padding = atlas->TexGlyphPadding; - ImVector pack_rects; - pack_rects.resize(user_rects.Size); - memset(pack_rects.Data, 0, (size_t)pack_rects.size_in_bytes()); - for (int i = 0; i < user_rects.Size; i++) - { - pack_rects[i].w = user_rects[i].Width + pack_padding; - pack_rects[i].h = user_rects[i].Height + pack_padding; - } - stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size); - for (int i = 0; i < pack_rects.Size; i++) - if (pack_rects[i].was_packed) - { - user_rects[i].X = (unsigned short)pack_rects[i].x; - user_rects[i].Y = (unsigned short)pack_rects[i].y; - IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height); - tex->Height = ImMax(tex->Height, pack_rects[i].y + pack_rects[i].h); - } -} -#endif - // Render a white-colored bitmap encoded in a string void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char) { @@ -3601,6 +3549,20 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* sr font->LockSingleSrcConfigIdx = -1; } +void ImFontAtlasBuildDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontGlyph* glyph) +{ + if (glyph->PackId >= 0) + { + ImFontAtlasPackDiscardRect(atlas, glyph->PackId); + glyph->PackId = -1; + } + ImWchar c = glyph->Codepoint; + IM_ASSERT(font->FallbackChar != c && font->EllipsisChar != c); // Unsupported for simplicity + IM_ASSERT(glyph >= font->Glyphs.Data && glyph < font->Glyphs.Data + font->Glyphs.Size); + font->IndexLookup[c] = (ImWchar)IM_FONTGLYPH_INDEX_UNUSED; + font->IndexAdvanceX[c] = font->FallbackAdvanceX; +} + void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font) { for (ImFontGlyph& glyph : font->Glyphs) @@ -3912,7 +3874,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (builder_is_new) builder = atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); - ImFontAtlasBuildUpdateRendererHasTexUpdatesFromContext(atlas); + ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); ImFontAtlasPackInit(atlas); diff --git a/imgui_internal.h b/imgui_internal.h index 2f0b5b5d7..6c9c6de73 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3718,6 +3718,7 @@ IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, const ImFontGlyph* in_glyph); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font); // <--- Your future new best friend! IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy From ba62becb7d0cdf18fcf2caed145b0f8bcb9b13c4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Jan 2025 11:53:24 +0100 Subject: [PATCH 0930/2359] (Breaking) Fonts: remove ImFontAtlasCustomRect which is now the same as ImTextureRect --- imgui.h | 62 ++++++++++++++++++++++++++------------------------ imgui_draw.cpp | 21 +++++++++-------- 2 files changed, 43 insertions(+), 40 deletions(-) diff --git a/imgui.h b/imgui.h index 15e784b4b..c521236bf 100644 --- a/imgui.h +++ b/imgui.h @@ -3468,22 +3468,6 @@ struct ImFontGlyphRangesBuilder IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges }; -// See ImFontAtlas::AddCustomRectXXX functions. -struct ImFontAtlasCustomRect -{ - unsigned short X, Y; // Output // Packed position in Atlas - - // [Internal] - unsigned short Width, Height; // Input // Desired rectangle dimension - unsigned int GlyphID : 31; // Input // For custom font glyphs only (ID < 0x110000) - unsigned int GlyphColored : 1; // Input // For custom font glyphs only: glyph is colored, removed tinting. - float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance - ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset - ImFont* Font; // Input // For custom font glyphs only: target font - ImFontAtlasCustomRect() { X = Y = 0xFFFF; Width = Height = 0; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } - bool IsPacked() const { return X != 0xFFFF; } -}; - // Flags for ImFontAtlas build enum ImFontAtlasFlags_ { @@ -3568,24 +3552,21 @@ struct ImFontAtlas // [ALPHA] Custom Rectangles/Glyphs API //------------------------------------------- - // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. + // You can request arbitrary rectangles to be packed into the atlas, for your own purpose. // You can request your rectangles to be mapped as font glyph (given a font + Unicode point), // so you can render e.g. custom colorful icons and use them as regular glyphs. - // - If your backend supports ImGuiBackendFlags_RendererHasTextures (since 1.92.X): - // - Packing is done immediately. Returns >= on success. Return <0 on error. - // - You can render your pixels into the texture right after calling the AddCustomRectXXX functions. - // - Texture may be resized, so you cannot cache UV coordinates. // FIXME-NEWATLAS-V1: How to handle that smoothly? - // - If your backend does NOT supports ImGuiBackendFlags_RendererHasTextures (older than 1.92.X): - // - After calling Build(), you can query the rectangle position and render your pixels. - // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. + // - Since 1.92.X, packing is done immediately in the function call. Returns >= on success, <0 on error. + // - You can render your pixels into the texture right after calling the AddCustomRectXXX functions, without waiting for the Build() call. + // - If your backend supports ImGuiBackendFlags_RendererHasTextures: + // Texture may be resized, so you cannot cache UV coordinates: always use CalcCustomRectUV(). + // - If you render colored output into your AddCustomRectRegular() rectangle: set 'atlas->TexPixelsUseColors = true' + // as this may help some backends decide of preferred texture format. // - Read docs/FONTS.md for more details about using colorful icons. // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. IMGUI_API int AddCustomRectRegular(int width, int height); IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); - IMGUI_API ImFontAtlasCustomRect* GetCustomRectByIndex(int index); - - // [Internal] - IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; + IMGUI_API ImTextureRect* GetCustomRectByIndex(int index); + IMGUI_API void CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; //------------------------------------------- // Members @@ -3613,7 +3594,6 @@ struct ImFontAtlas ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data - //ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines int TexNextUniqueID; // Next value to be stored in TexData->UniqueID ImVector DrawListSharedDatas; @@ -3627,7 +3607,8 @@ struct ImFontAtlas int RefCount; // Number of contexts using this atlas // [Obsolete] - //int TexDesiredWidth; // OBSOLETED in 1.91.5 (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) + //int TexDesiredWidth; // OBSOLETED in 1.92.X (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) + //typedef ImTextureRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ }; @@ -3905,6 +3886,27 @@ namespace ImGui //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 } +//-- OBSOLETED in 1.91.7 (from January 2025): ImFontAtlasCustomRect becomes ImTextureRect +// - ImFontAtlasCustomRect::X --> ImTextureRect::x +// - ImFontAtlasCustomRect::Y --> ImTextureRect::y +// - ImFontAtlasCustomRect::Width --> ImTextureRect::w +// - ImFontAtlasCustomRect::Height --> ImTextureRect::h +// - ImFontAtlasCustomRect::GlyphColored --> if you need to write to this, instead you can write to 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph() +// We could make ImTextureRect an union to use old names, such 1) this would be confusing 2) the fix is easy 3) ImFontAtlasCustomRect was always a rather esoteric api. +typedef ImTextureRect ImFontAtlasCustomRect; +/*struct ImFontAtlasCustomRect +{ + unsigned short X, Y; // Output // Packed position in Atlas + unsigned short Width, Height; // Input // [Internal] Desired rectangle dimension + unsigned int GlyphID:31; // Input // [Internal] For custom font glyphs only (ID < 0x110000) + unsigned int GlyphColored:1; // Input // [Internal] For custom font glyphs only: glyph is colored, removed tinting. + float GlyphAdvanceX; // Input // [Internal] For custom font glyphs only: glyph xadvance + ImVec2 GlyphOffset; // Input // [Internal] For custom font glyphs only: glyph display offset + ImFont* Font; // Input // [Internal] For custom font glyphs only: target font + ImFontAtlasCustomRect() { X = Y = 0xFFFF; Width = Height = 0; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } + bool IsPacked() const { return X != 0xFFFF; } +};*/ + //-- OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect() //typedef ImDrawFlags ImDrawCornerFlags; //enum ImDrawCornerFlags_ diff --git a/imgui_draw.cpp b/imgui_draw.cpp index af8913719..1f13ed0f6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3135,6 +3135,8 @@ int ImFontAtlas::AddCustomRectRegular(int width, int height) return r_id; } +// FIXME: we automatically set glyph.Colored=true by default. +// If you need to alter this, you can write 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph(). int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) { #ifdef IMGUI_USE_WCHAR32 @@ -3168,21 +3170,20 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int wid return r_id; } -ImFontAtlasCustomRect* ImFontAtlas::GetCustomRectByIndex(int idx) +ImTextureRect* ImFontAtlas::GetCustomRectByIndex(int idx) { - IM_STATIC_ASSERT(offsetof(ImFontAtlasCustomRect, X) == offsetof(ImFontAtlasRect, x)); - IM_STATIC_ASSERT(offsetof(ImFontAtlasCustomRect, Y) == offsetof(ImFontAtlasRect, y)); - IM_STATIC_ASSERT(offsetof(ImFontAtlasCustomRect, Width) == offsetof(ImFontAtlasRect, w)); - IM_STATIC_ASSERT(offsetof(ImFontAtlasCustomRect, Height) == offsetof(ImFontAtlasRect, h)); - return (ImFontAtlasCustomRect*)(void*)ImFontAtlasPackGetRect(this, idx); + IM_STATIC_ASSERT(offsetof(ImTextureRect, x) == offsetof(ImFontAtlasRect, x)); + IM_STATIC_ASSERT(offsetof(ImTextureRect, y) == offsetof(ImFontAtlasRect, y)); + IM_STATIC_ASSERT(offsetof(ImTextureRect, w) == offsetof(ImFontAtlasRect, w)); + IM_STATIC_ASSERT(offsetof(ImTextureRect, h) == offsetof(ImFontAtlasRect, h)); + return (ImTextureRect*)(void*)ImFontAtlasPackGetRect(this, idx); } -void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const +void ImFontAtlas::CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const { IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates - IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed - *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y); - *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y); + *out_uv_min = ImVec2((float)rect->x * TexUvScale.x, (float)rect->y * TexUvScale.y); + *out_uv_max = ImVec2((float)(rect->x + rect->w) * TexUvScale.x, (float)(rect->y + rect->w) * TexUvScale.y); } bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) From 2bf6552f2facc23c5aa84a610fb8c3983ae87d1d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 11:35:55 +0100 Subject: [PATCH 0931/2359] Fonts: Fixed/improved support for legacy backend. SetTexID() writes into our ImTextureData to keep the indirection, clear TexIsBuilt. The idea is that a legacy backend can somehow add a if (!atlas->IsBuilt()) ImGui_ImplXXXXX_CreateFontsTexture() call _after_ Render() and some features are supported. --- imgui.cpp | 16 ++++------------ imgui.h | 29 ++++++++++++++++------------- imgui_draw.cpp | 26 ++++++++++++++++++++------ 3 files changed, 40 insertions(+), 31 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a505d5d6c..f681e71b6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5178,13 +5178,16 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; } +// FIXME-NEWATLAS-V2: If we aim to support multiple atlases used by same context: how to reach/target all atlases? static void ImGui::UpdateTexturesNewFrame() { - // FIXME-NEWATLAS-V2: If we aim to support multiple atlases used by same context: how to reach/target all atlases? ImGuiContext& g = *GImGui; ImFontAtlas* atlas = g.IO.Fonts; if (g.FontAtlasOwnedByContext) + { + atlas->RendererHasTextures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; ImFontAtlasUpdateNewFrame(atlas); + } } // Build a single texture list @@ -5240,13 +5243,6 @@ void ImGui::NewFrame() CallContextHooks(&g, ImGuiContextHookType_NewFramePre); - // Check that font atlas was built or backend support texture reload in which case we can build now - ImFontAtlas* atlas = g.IO.Fonts; - if (!atlas->TexIsBuilt && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) - ImFontAtlasBuildMain(atlas); - else // Legacy backend - IM_ASSERT(atlas->TexIsBuilt && "Backend does not support ImGuiBackendFlags_RendererHasTextures, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()."); - // Check and assert for various common IO and Configuration mistakes ErrorCheckNewFrameSanityChecks(); @@ -8573,11 +8569,7 @@ void ImGui::UpdateFontsNewFrame() { ImGuiContext& g = *GImGui; if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) - { g.IO.Fonts->Locked = true; - for (ImFont* font : g.IO.Fonts->Fonts) - font->LockDisableLoading = true; - } SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); } diff --git a/imgui.h b/imgui.h index c521236bf..73e3f7edd 100644 --- a/imgui.h +++ b/imgui.h @@ -3332,7 +3332,7 @@ struct ImDrawData }; //----------------------------------------------------------------------------- -// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureDataUpdate, ImTextureData +// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData //----------------------------------------------------------------------------- // We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension. @@ -3517,17 +3517,20 @@ struct ImFontAtlas IMGUI_API void ClearTexData(); // [OBSOLETE] Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - // Build atlas, retrieve pixel data. - // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). - // The pitch is always = Width * BytesPerPixels (1 or 4) - // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into - // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. - IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. - IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel - IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel - void SetTexID(ImTextureID id) { TexRef._TexData = NULL; TexRef._TexID = id; } // Called by legacy backends. - void SetTexID(ImTextureRef id) { TexRef = id; } // Called by legacy backends. - bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... + // Legacy path for build atlas + retrieving pixel data. + // - User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). + // - The pitch is always = Width * BytesPerPixels (1 or 4) + // - Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into + // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. + // - From 1.92 with backends supporting ImGuiBackendFlags_RendererHasTextures: + // - Calling Build(), GetTexDataAsAlpha8(), GetTexDataAsRGBA32() is not needed. + // - In backend: replace calls to ImFontAtlas::SetTexID() with calls to ImTextureData::SetTexID() after honoring texture creation. + IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + void SetTexID(ImTextureID id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid); TexRef._TexData->TexID = id; } // Called by legacy backends. May be called before texture creation. + void SetTexID(ImTextureRef id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid && id._TexData == NULL); TexRef._TexData->TexID = id._TexID; } // Called by legacy backends. + bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent.. #endif //------------------------------------------- @@ -3588,7 +3591,7 @@ struct ImFontAtlas ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context. - bool TexIsBuilt; // Set when texture was built matching current font input + bool TexIsBuilt; // Set when texture was built matching current font input. Mostly useful for legacy IsBuilt() call. bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight) ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1f13ed0f6..5e9d1de91 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2485,6 +2485,7 @@ void ImTextureData::DestroyPixels() // - ImFontAtlas::CalcCustomRectUV() // - ImFontAtlasGetMouseCursorTexData() //----------------------------------------------------------------------------- +// - ImFontAtlasBuildMain() // - ImFontAtlasBuildSetupFontLoader() // - ImFontAtlasBuildPreloadAllGlyphRanges() // - ImFontAtlasBuildUpdatePointers() @@ -2685,15 +2686,24 @@ static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* at } // Called by NewFrame(). When multiple context own the atlas, only the first one calls this. +// If you are calling this yourself, ensure atlas->RendererHasTexUpdates is et. void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) { - if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges) + // Check that font atlas was built or backend support texture reload in which case we can build now + if (atlas->RendererHasTextures) { - ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); - IM_ASSERT_USER_ERROR(atlas->RendererHasTextures == false, - "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build()."); + atlas->TexIsBuilt = true; + if (atlas->Builder == NULL) // This will only happen if fonts were not already loaded. + ImFontAtlasBuildMain(atlas); } + else // Legacy backend + { + IM_ASSERT_USER_ERROR(atlas->TexIsBuilt, "Backend does not support ImGuiBackendFlags_RendererHasTextures, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()."); + } + if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges) + IM_ASSERT_USER_ERROR(atlas->RendererHasTextures == false, "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build()."); + // Update texture status for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) { ImTextureData* tex = atlas->TexList[tex_n]; @@ -2865,6 +2875,7 @@ void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, tex->UpdateRect.y = ImMin(tex->UpdateRect.y, req.y); tex->UpdateRect.w = (unsigned short)(new_x1 - tex->UpdateRect.x); tex->UpdateRect.h = (unsigned short)(new_y1 - tex->UpdateRect.y); + atlas->TexIsBuilt = false; // No need to queue if status is _WantCreate if (tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantUpdates) @@ -3206,6 +3217,7 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso return true; } +// When atlas->RendererHasTexUpdates == true, this is only called if no font were loaded. void ImFontAtlasBuildMain(ImFontAtlas* atlas) { IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); @@ -3589,6 +3601,7 @@ void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font) atlas->FontLoader->FontSrcInit(atlas, src); ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, src); // Technically this is called for each source sub-font, tho 99.9% of the time the first one fills everything. + atlas->TexIsBuilt = false; } // Notify external systems @@ -3684,6 +3697,7 @@ ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h) new_tex->Create(atlas->TexDesiredFormat, w, h); new_tex->Status = ImTextureStatus_WantCreate; + atlas->TexIsBuilt = false; ImFontAtlasBuildSetTexture(atlas, new_tex); @@ -4037,12 +4051,12 @@ ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id ImFontGlyph* ImFont::BuildLoadGlyph(ImWchar codepoint) { - if (LockDisableLoading) + ImFontAtlas* atlas = ContainerAtlas; + if (LockDisableLoading || atlas->Locked) return NULL; //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildAddGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); - ImFontAtlas* atlas = ContainerAtlas; // Load from single source or all sources? int srcs_count = (LockSingleSrcConfigIdx != -1) ? 1 : SourcesCount; From bd19bc50858d80113080fd22f7a8538d953e3c7c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 14:57:33 +0100 Subject: [PATCH 0932/2359] Fonts: Removed BuildClearGlyphs(), conflated with ClearOutputData() --- imgui.h | 1 - imgui_draw.cpp | 20 ++------------------ 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/imgui.h b/imgui.h index 73e3f7edd..1baa4067a 100644 --- a/imgui.h +++ b/imgui.h @@ -3673,7 +3673,6 @@ struct ImFont IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); IMGUI_API ImFontGlyph* BuildLoadGlyph(ImWchar c); IMGUI_API void BuildGrowIndex(int new_size); - IMGUI_API void BuildClearGlyphs(); }; // Added indirection to avoid patching ImDrawCmd after texture updates. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5e9d1de91..2351b2f51 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2522,8 +2522,6 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasPackGetRect() //----------------------------------------------------------------------------- // - ImFont::BuildLoadGlyph() -// - ImFont::BuildClearGlyphs() -//----------------------------------------------------------------------------- // - ImFontAtlasDebugLogTextureRequests() //----------------------------------------------------------------------------- // - ImFontAtlasGetFontLoaderForStbTruetype() @@ -3581,7 +3579,7 @@ void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font) for (ImFontGlyph& glyph : font->Glyphs) if (glyph.PackId >= 0) ImFontAtlasPackDiscardRect(atlas, glyph.PackId); - font->BuildClearGlyphs(); + font->ClearOutputData(); font->FallbackChar = font->EllipsisChar = 0; } @@ -3915,7 +3913,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) { for (ImFont* font : atlas->Fonts) - font->BuildClearGlyphs(); + font->ClearOutputData(); if (atlas->FontLoader && atlas->FontLoader->FontSrcDestroy != NULL) for (ImFontConfig& font_cfg : atlas->Sources) atlas->FontLoader->FontSrcDestroy(atlas, &font_cfg); @@ -4650,30 +4648,16 @@ ImFont::~ImFont() void ImFont::ClearOutputData() { - FontSize = 0.0f; FallbackAdvanceX = 0.0f; Glyphs.clear(); IndexAdvanceX.clear(); IndexLookup.clear(); FallbackGlyphIndex = -1; - ContainerAtlas = NULL; Ascent = Descent = 0.0f; MetricsTotalSurface = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); } -void ImFont::BuildClearGlyphs() -{ - FallbackAdvanceX = 0.0f; - Glyphs.clear(); - IndexAdvanceX.clear(); - IndexLookup.clear(); - FallbackGlyphIndex = 0; - MetricsTotalSurface = 0; - memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); - // Don't clear BuilderData -} - // API is designed this way to avoid exposing the 8K page size // e.g. use with IsGlyphRangeUnused(0, 255) bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) From 722f6013ff15957833960ebe46e1ea2eab97b5eb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Jan 2025 15:41:46 +0100 Subject: [PATCH 0933/2359] Fonts: Added a bit of user facing tooling. --- imgui.cpp | 23 +++++++++++++++++++++++ imgui_demo.cpp | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index f681e71b6..24073f715 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15594,6 +15594,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) { ImGuiContext& g = *GImGui; + SeparatorText("Fonts"); Text("Read "); SameLine(0, 0); TextLinkOpenURL("https://www.dearimgui.com/faq/"); @@ -15641,6 +15642,28 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) PopID(); } + SeparatorText("Font Atlas"); + if (Button("Clear Cache")) + atlas->ClearCache(); + SameLine(); + if (Button("Grow")) + ImFontAtlasBuildGrowTexture(atlas); + SameLine(); + if (Button("Compact")) + ImFontAtlasBuildCompactTexture(atlas); + + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) + { + ImTextureData* tex = atlas->TexList[tex_n]; + if (tex_n > 0) + SameLine(); + Text("Tex: %dx%d", tex->Width, tex->Height); + } + const int packed_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsPackedSurface); + const int discarded_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsDiscardedSurface); + Text("Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt); + Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt); + // Texture list for (ImTextureData* tex : atlas->TexList) { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5d5075e81..55b09a2bf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8446,11 +8446,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGuiIO& io = GetIO(); ImFontAtlas* atlas = io.Fonts; - HelpMarker("Read FAQ and docs/FONTS.md for details on font loading."); ShowFontAtlas(atlas); // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). + SeparatorText("Legacy Scaling"); const float MIN_SCALE = 0.3f; const float MAX_SCALE = 2.0f; HelpMarker( From b203ac1e0dce0a770954ca8b1d486d2ea00ff83c Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 18 Jan 2025 15:01:05 +0100 Subject: [PATCH 0934/2359] Fonts: Reduced reliance on ImFontConfig::DstFont. --- imgui_draw.cpp | 41 ++++++++++++++++++----------------------- imgui_internal.h | 2 +- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2351b2f51..18e9501c3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2966,9 +2966,6 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) return NULL; } - // Invalidate texture - //TexReady = false; - //ClearTexData(); return new_font_cfg.DstFont; } @@ -3276,15 +3273,16 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas) { atlas->Builder->PreloadedAllGlyphsRanges = true; - for (int src_n = 0; src_n < atlas->Sources.Size; src_n++) - { - ImFontConfig* src = &atlas->Sources[src_n]; - const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault(); - IM_ASSERT(ranges != NULL); - for (; ranges[0]; ranges += 2) - for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 - src->DstFont->FindGlyphNoFallback((ImWchar)c); - } + for (ImFont* font : atlas->Fonts) + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = &font->Sources[src_n]; + const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault(); + IM_ASSERT(ranges != NULL); + for (; ranges[0]; ranges += 2) + for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 + font->FindGlyphNoFallback((ImWchar)c); + } } void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) @@ -3462,17 +3460,15 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) if (!font_loader->FontSrcInit(atlas, src)) return false; - ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, src); + ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); return true; } // Rasterize our own ellipsis character from a dot. // This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. // FIXME-NEWATLAS: This borrows too much from FontLoader's FontAddGlyph() and suggest that we should add further helpers. -static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFontConfig* src, const ImFontGlyph* dot_glyph) +static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFont* font, const ImFontGlyph* dot_glyph) { - ImFont* font = src->DstFont; - ImFontAtlasRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_glyph->PackId); const int dot_spacing = 1; const float dot_step = (dot_glyph->X1 - dot_glyph->X0) + dot_spacing; @@ -3502,15 +3498,14 @@ static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, I // Load/identify special glyphs // (note that this is called again for fonts with MergeMode) -void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src) +void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src) { - ImFont* font = src->DstFont; - const int cfg_idx_in_font = (int)(src - font->Sources); - IM_ASSERT(cfg_idx_in_font >= 0 && cfg_idx_in_font < font->SourcesCount); + const int src_idx_in_font = (int)(src - font->Sources); + IM_ASSERT(src_idx_in_font >= 0 && src_idx_in_font < font->SourcesCount); IM_UNUSED(atlas); // While manipulating glyphs during init we want to restrict all searches for one source font. - font->LockSingleSrcConfigIdx = (short)cfg_idx_in_font; + font->LockSingleSrcConfigIdx = (short)src_idx_in_font; // Setup Fallback character // FIXME-NEWATLAS: could we use a scheme where this is lazily loaded? @@ -3553,7 +3548,7 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* sr { const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; if (const ImFontGlyph* dot_glyph = LoadFirstExistingGlyph(font, dots_chars, IM_ARRAYSIZE(dots_chars))) - ImFontAtlasBuildSetupFontCreateEllipsisFromDot(atlas, src, dot_glyph); + ImFontAtlasBuildSetupFontCreateEllipsisFromDot(atlas, font, dot_glyph); else font->EllipsisChar = (ImWchar)' '; } @@ -3598,7 +3593,7 @@ void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font) if (atlas->FontLoader && atlas->FontLoader->FontSrcInit != NULL) atlas->FontLoader->FontSrcInit(atlas, src); - ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, src); // Technically this is called for each source sub-font, tho 99.9% of the time the first one fills everything. + ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); // Technically this is called for each source sub-font, tho 99.9% of the time the first one fills everything. atlas->TexIsBuilt = false; } diff --git a/imgui_internal.h b/imgui_internal.h index 6c9c6de73..1126a91ba 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3717,7 +3717,7 @@ IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, const ImFontGlyph* in_glyph); -IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font); // <--- Your future new best friend! From c5653d5f34b50d9edb2d189790df3fbabdc72f82 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 20 Jan 2025 20:01:21 +0100 Subject: [PATCH 0935/2359] Fonts: stb_truetype loader: Reworked scale handling to suggest this is not required caching. --- imgui_draw.cpp | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 18e9501c3..4edddf5fa 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4151,19 +4151,14 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* // FIXME-NEWFONTS: reevaluate sizing metrics int oversample_h, oversample_v; ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); - + float scale; if (src->SizePixels > 0.0f) - { - bd_font_data->ScaleForRasterX = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, src->SizePixels * src->RasterizerDensity) * oversample_h; - bd_font_data->ScaleForRasterY = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, src->SizePixels * src->RasterizerDensity) * oversample_v; - bd_font_data->ScaleForLayout = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, src->SizePixels); - } + scale = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); else - { - bd_font_data->ScaleForRasterX = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, -src->SizePixels * src->RasterizerDensity) * oversample_h; - bd_font_data->ScaleForRasterY = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, -src->SizePixels * src->RasterizerDensity) * oversample_v; - bd_font_data->ScaleForLayout = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, -src->SizePixels); - } + scale = -stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); + bd_font_data->ScaleForRasterX = scale * src->SizePixels * src->RasterizerDensity * oversample_h; + bd_font_data->ScaleForRasterY = scale * src->SizePixels * src->RasterizerDensity * oversample_v; + bd_font_data->ScaleForLayout = scale * src->SizePixels; // FIXME-NEWFONTS: make use of line gap value int unscaled_ascent, unscaled_descent, unscaled_line_gap; From fb69a09d6e324573371daee953232988afc24a6a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Jan 2025 12:12:07 +0100 Subject: [PATCH 0936/2359] Fonts: Fixed leak due to indirectly recursing ImFontAtlasPackInit(). --- imgui_draw.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4edddf5fa..dfb7bb0d6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3857,8 +3857,6 @@ void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) // Start packing over current empty texture void ImFontAtlasBuildInit(ImFontAtlas* atlas) { - ImFontAtlasBuilder* builder = atlas->Builder; - // Select Backend // - Note that we do not reassign to atlas->FontLoader, since it is likely to point to static data which // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are @@ -3873,14 +3871,20 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) #else IM_ASSERT(0); // Invalid Build function #endif + return; // ImFontAtlasBuildSetupFontBackendIO() automatically call ImFontAtlasBuildInit() } + // Create initial texture size if (atlas->TexData == NULL) ImFontAtlasBuildAddTexture(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); + ImFontAtlasBuilder* builder = atlas->Builder; // Do not move above const bool builder_is_new = (builder == NULL); if (builder_is_new) + { + IM_ASSERT(atlas->Builder == NULL); builder = atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); + } ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); From a2371ef90bad9e176e7eaa0693efc4a7329cf66c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Jan 2025 20:01:26 +0100 Subject: [PATCH 0937/2359] Internals: added ImStableVector<> helper. --- imgui_internal.h | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 1126a91ba..07cd84667 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -133,7 +133,7 @@ Index of this file: //----------------------------------------------------------------------------- // Utilities -// (other types which are not forwarded declared are: ImBitArray<>, ImSpan<>, ImSpanAllocator<>, ImPool<>, ImChunkStream<>) +// (other types which are not forwarded declared are: ImBitArray<>, ImSpan<>, ImSpanAllocator<>, ImStableVector<>, ImPool<>, ImChunkStream<>) struct ImBitVector; // Store 1-bit per value struct ImRect; // An axis-aligned rectangle (2 points) struct ImGuiTextIndex; // Maintain a line index for a text buffer. @@ -357,6 +357,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer // - Helper: ImBitArray // - Helper: ImBitVector // - Helper: ImSpan<>, ImSpanAllocator<> +// - Helper: ImStableVector<> // - Helper: ImPool<> // - Helper: ImChunkStream<> // - Helper: ImGuiTextIndex @@ -694,6 +695,39 @@ struct ImSpanAllocator inline void GetSpan(int n, ImSpan* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); } }; +// Helper: ImStableVector<> +// Allocating chunks of BLOCK_SIZE items. Objects pointers are never invalidated when growing, only by clear(). +// Important: does not destruct anything! +// Implemented only the minimum set of functions we need for it. +template +struct ImStableVector +{ + int Size = 0; + int Capacity = 0; + ImVector Blocks; + + // Functions + inline ~ImStableVector() { for (T* block : Blocks) IM_FREE(block); } + + inline void clear() { Size = Capacity = 0; Blocks.clear_delete(); } + inline void resize(int new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; } + inline void reserve(int new_cap) + { + new_cap = IM_MEMALIGN(new_cap, BLOCK_SIZE); + int old_count = Capacity / BLOCK_SIZE; + int new_count = new_cap / BLOCK_SIZE; + if (new_count <= old_count) + return; + Blocks.resize(new_count); + for (int n = old_count; n < new_count; n++) + Blocks[n] = (T*)IM_ALLOC(sizeof(T) * BLOCK_SIZE); + Capacity = new_cap; + } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; } + inline T* push_back(const T& v) { int i = Size; IM_ASSERT(i >= 0); if (Size == Capacity) reserve(Capacity + BLOCK_SIZE); void* ptr = &Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; memcpy(ptr, &v, sizeof(v)); Size++; return (T*)ptr; } +}; + // Helper: ImPool<> // Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, // Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object. From 7aba8da5515e3003be071f5392cac3aaa663c8aa Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Jan 2025 18:10:42 +0100 Subject: [PATCH 0938/2359] (Breaking) Fonts: CalcWordWrapPositionA() -> CalcWordWrapPosition(), takes size instead of scale as this will be needed. --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dfb7bb0d6..c9c32e930 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4795,7 +4795,7 @@ bool ImFont::IsGlyphInFont(ImWchar c) return false; } -// This is manually inlined in CalcTextSizeA() and CalcWordWrapPositionA(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). +// This is manually inlined in CalcTextSizeA() and CalcWordWrapPosition(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). IM_MSVC_RUNTIME_CHECKS_OFF float ImFont::GetCharAdvance(ImWchar c) { From 093d01269a05d5f6fab9eee85d3e187b22364fe7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Jan 2025 15:46:22 +0100 Subject: [PATCH 0939/2359] Fonts: Baked system, with auto-bind, v10. # Conflicts: # imgui_internal.h --- imgui.cpp | 94 +++--- imgui.h | 62 ++-- imgui_draw.cpp | 480 ++++++++++++++++++++----------- imgui_internal.h | 39 ++- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 33 ++- misc/freetype/imgui_freetype.cpp | 131 ++++++--- 7 files changed, 545 insertions(+), 296 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 24073f715..abe3cab3e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3738,7 +3738,8 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con const float font_size = draw_list->_Data->FontSize; const float font_scale = draw_list->_Data->FontScale; const char* text_end_ellipsis = NULL; - const float ellipsis_width = font->GetCharAdvance(font->EllipsisChar) * font_scale; + ImFontBaked* baked = font->GetFontBaked(font_size); + const float ellipsis_width = baked->GetCharAdvance(font->EllipsisChar) * font_scale; // 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); @@ -3939,7 +3940,8 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) Initialized = false; FontAtlasOwnedByContext = shared_font_atlas ? false : true; Font = NULL; - FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f; + FontBaked = NULL; + FontSize = /*FontBaseSize = */FontScale = CurrentDpiScale = 0.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); IO.Fonts->RefCount++; Time = 0.0f; @@ -4275,6 +4277,7 @@ void ImGui::Shutdown() g.MenusIdSubmittedThisFrame.clear(); g.InputTextState.ClearFreeMemory(); g.InputTextDeactivatedState.ClearFreeMemory(); + g.InputTextPasswordFont.ContainerAtlas = NULL; g.SettingsWindows.clear(); g.SettingsHandlers.clear(); @@ -4371,8 +4374,9 @@ static void SetCurrentWindow(ImGuiWindow* window) g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking if (window) { - g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); - g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize; + // FIXME-BAKED + //g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); + //g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize; ImGui::NavUpdateCurrentWindowIsScrollPushableX(); } } @@ -5186,7 +5190,7 @@ static void ImGui::UpdateTexturesNewFrame() if (g.FontAtlasOwnedByContext) { atlas->RendererHasTextures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; - ImFontAtlasUpdateNewFrame(atlas); + ImFontAtlasUpdateNewFrame(atlas, g.FrameCount); } } @@ -8399,11 +8403,14 @@ ImVec2 ImGui::GetFontTexUvWhitePixel() void ImGui::SetWindowFontScale(float scale) { IM_ASSERT(scale > 0.0f); + // FIXME-BAKED + /* ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize; + */ } void ImGui::PushFocusScope(ImGuiID id) @@ -8570,20 +8577,21 @@ void ImGui::UpdateFontsNewFrame() ImGuiContext& g = *GImGui; if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) g.IO.Fonts->Locked = true; - SetCurrentFont(GetDefaultFont()); + SetCurrentFont(GetDefaultFont(), GetDefaultFont()->Sources[0].SizePixels); IM_ASSERT(g.Font->IsLoaded()); } // Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only. -void ImGui::SetCurrentFont(ImFont* font) +void ImGui::SetCurrentFont(ImFont* font, float font_size) { ImGuiContext& g = *GImGui; IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); g.Font = font; - g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); - g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; - g.FontScale = g.FontSize / g.Font->FontSize; + //g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.FontBaked->Size * g.Font->Scale); + g.FontSize = font_size;// g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + g.FontBaked = g.Font->GetFontBaked(g.FontSize); + g.FontScale = g.FontSize / g.FontBaked->Size; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; g.DrawListSharedData.FontScale = g.FontScale; @@ -8606,7 +8614,7 @@ void ImGui::PushFont(ImFont* font) if (font == NULL) font = GetDefaultFont(); g.FontStack.push_back(font); - SetCurrentFont(font); + SetCurrentFont(font, g.FontSize); } void ImGui::PopFont() @@ -8619,7 +8627,14 @@ void ImGui::PopFont() } g.FontStack.pop_back(); ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); - SetCurrentFont(font); + SetCurrentFont(font, g.FontSize); // FIXME-BAKED: size in stack +} + +void ImGui::SetFontSize(float size) +{ + // FIXME-BAKED + ImGuiContext& g = *GImGui; + SetCurrentFont(g.Font, size); } //----------------------------------------------------------------------------- @@ -15512,7 +15527,7 @@ void ImGui::DebugTextEncoding(const char* str) } TableNextColumn(); TextUnformatted(p, p + c_utf8_len); - if (GetFont()->FindGlyphNoFallback((ImWchar)c) == NULL) + if (!GetFont()->IsGlyphInFont((ImWchar)c)) { SameLine(); TextUnformatted("[missing]"); @@ -16478,8 +16493,8 @@ void ImGui::DebugNodeFont(ImFont* font) { ImGuiContext& g = *GImGui; ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; - bool opened = TreeNode(font, "Font: \"%s\": %.2f px, %d glyphs, %d sources(s)", - font->Sources ? font->Sources[0].Name : "", font->FontSize, font->Glyphs.Size, font->SourcesCount); + ImFontAtlas* atlas = font->ContainerAtlas; + bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->Sources ? font->Sources[0].Name : "", font->SourcesCount); // Display preview text if (!opened) @@ -16499,11 +16514,11 @@ void ImGui::DebugNodeFont(ImFont* font) } if (SmallButton("Set as default")) GetIO().FontDefault = font; - if (font->ContainerAtlas->Fonts.Size > 1 && !font->ContainerAtlas->Locked) + if (atlas->Fonts.Size > 1 && !atlas->Locked) { SameLine(); if (SmallButton("Remove")) - font->ContainerAtlas->RemoveFont(font); + atlas->RemoveFont(font); } // Display details @@ -16515,33 +16530,43 @@ void ImGui::DebugNodeFont(ImFont* font) "You may oversample them to get some flexibility with scaling. " "You can also render at multiple sizes and select which one to use at runtime.\n\n" "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)"); - Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + char c_str[5]; Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar); Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar); - const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface); - Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt); - for (int config_i = 0; config_i < font->SourcesCount; config_i++) - if (font->Sources) - { - ImFontConfig* src = &font->Sources[config_i]; - int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); - BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", - config_i, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); - } + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + if (ImFontConfig* src = &font->Sources[src_n]) + BulletText("Input %d: \'%s\', Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); // Display all glyphs of the fonts in separate pages of 256 characters + for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++) { - if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) + ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n]; + if (baked->ContainerFont != font) + continue; + PushID(baked_n); + if (TreeNode("Glyphs", "Baked at %.2fpx: %d glyphs%s", baked->Size, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) { if (SmallButton("Load all")) for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++) - font->FindGlyph((ImWchar)base); + baked->FindGlyph((ImWchar)base); + + const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface); + Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent); + Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt); + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = &font->Sources[src_n]; + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(src, baked->Size, &oversample_h, &oversample_v); + BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); + } ImDrawList* draw_list = GetWindowDrawList(); const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); - const float cell_size = font->FontSize * 1; + const float cell_size = baked->Size * 1; const float cell_spacing = GetStyle().ItemSpacing.y; for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) { @@ -16556,7 +16581,7 @@ void ImGui::DebugNodeFont(ImFont* font) int count = 0; for (unsigned int n = 0; n < 256; n++) - if (font->IsGlyphLoaded((ImWchar)(base + n))) + if (baked->IsGlyphLoaded((ImWchar)(base + n))) count++; if (count <= 0) continue; @@ -16571,7 +16596,7 @@ void ImGui::DebugNodeFont(ImFont* font) // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); - const ImFontGlyph* glyph = font->IsGlyphLoaded((ImWchar)(base + n)) ? font->FindGlyph((ImWchar)(base + n)) : NULL; + const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL; draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); if (!glyph) continue; @@ -16587,6 +16612,7 @@ void ImGui::DebugNodeFont(ImFont* font) } TreePop(); } + PopID(); } TreePop(); Unindent(); diff --git a/imgui.h b/imgui.h index 1baa4067a..85fbb47d9 100644 --- a/imgui.h +++ b/imgui.h @@ -50,7 +50,7 @@ Index of this file: // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) -// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) // [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformImeData) // [SECTION] Obsolete functions and types @@ -172,6 +172,7 @@ struct ImDrawVert; // A single vertex (pos + uv + col = 20 byte struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader struct ImFontAtlasBuilder; // Opaque storage for building a ImFontAtlas +struct ImFontBaked; // Baked data for a ImFont at a given size. struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data @@ -471,6 +472,8 @@ namespace ImGui // Parameters stacks (shared) IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font IMGUI_API void PopFont(); + IMGUI_API void SetFontSize(float size); + //IMGUI_API void PopFontSize(); IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); IMGUI_API void PopStyleColor(int count = 1); @@ -3419,10 +3422,10 @@ struct ImFontConfig int OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED IN 1.91.9: use GlyphExtraAdvanceX) - ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. + ImVec2 GlyphOffset; // 0, 0 // [FIXME-BAKED] Offset all glyphs from this font input. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). - float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font - float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs + float GlyphMinAdvanceX; // 0 // [FIXME-BAKED] Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font + float GlyphMaxAdvanceX; // FLT_MAX // [FIXME-BAKED] Maximum AdvanceX for glyphs float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. @@ -3599,6 +3602,7 @@ struct ImFontAtlas ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines int TexNextUniqueID; // Next value to be stored in TexData->UniqueID + int FontNextUniqueID; // Next value to be stored in ImFont->SourceID ImVector DrawListSharedDatas; // [Internal] Font builder @@ -3616,30 +3620,57 @@ struct ImFontAtlas //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ }; -// Font runtime data and rendering -// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). -struct ImFont +// Font runtime data for a given size +// Important: pointers to ImFontBaked are only valid for the current frame. +struct ImFontBaked { // [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) ImVector IndexAdvanceX; // 12-16 // out // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). float FallbackAdvanceX; // 4 // out // FindGlyph(FallbackChar)->AdvanceX - float FontSize; // 4 // in // Height of characters/line, set during loading (don't change after loading) + float Size; // 4 // in // Height of characters/line, set during loading (doesn't change after loading) // [Internal] Members: Hot ~28/36 bytes (for RenderText loop) ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. ImVector Glyphs; // 12-16 // out // All glyphs. int FallbackGlyphIndex; // 4 // out // Index of FontFallbackChar - // [Internal] Members: Cold ~32/40/60 bytes + // [Internal] Members: Cold + float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) + unsigned int MetricsTotalSurface:26;// 3 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + unsigned int WantDestroy:1; // 1 // // Queued for destroy + int LastUsedFrame; // 4 // // Record of that time this was bounds + ImGuiID BakedId; // 4 // + ImFont* ContainerFont; // 4-8 // in // Parent font + void* FontBackendData; // 4-8 // // Font backend opaque storage (per baked font) + + // Functions + IMGUI_API ImFontBaked(); + IMGUI_API void ClearOutputData(); + IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); // Return U+FFFD glyph if requested glyph doesn't exists. + IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); // Return NULL if glyph doesn't exist + IMGUI_API float GetCharAdvance(ImWchar c); + IMGUI_API bool IsGlyphLoaded(ImWchar c); + IMGUI_API ImFontGlyph* BuildLoadGlyph(ImWchar c); + IMGUI_API void BuildGrowIndex(int new_size); +}; + +// Font runtime data and rendering +// - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. +// - Since 1.92.X a font may be rendered as any size! Therefore a font doesn't have one specific size. +// - Use 'font->GetBakedForSize(size)' to retrieve the ImFontBaked* corresponding to a given size. +// - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetBakedForSize(g.FontSize). +struct ImFont +{ + // [Internal] Members: Cold ~32/40/80 bytes // Conceptually Sources[] is the list of font sources merged to create this font. + ImFontBaked* LastBaked; // Cache last bound baked. DO NOT USE. Use GetFontBaked(). + ImGuiID FontId; // Unique identifier for the font short SourcesCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances ImFontAtlas* ContainerAtlas; // 4-8 // out // What we has been loaded into ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() - float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) - int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool LockDisableLoading; short LockSingleSrcConfigIdx; @@ -3647,10 +3678,7 @@ struct ImFont // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); - IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); // Return fallback glyph if requested glyph doesn't exists. - IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); // Return NULL if glyph doesn't exist - IMGUI_API float GetCharAdvance(ImWchar c); - IMGUI_API bool IsGlyphLoaded(ImWchar c); + IMGUI_API ImFontBaked* GetFontBaked(float font_size); // Get or create baked data for given size IMGUI_API bool IsGlyphInFont(ImWchar c); bool IsLoaded() const { return ContainerAtlas != NULL; } const char* GetDebugName() const { return Sources ? Sources->Name : ""; } @@ -3664,15 +3692,13 @@ struct ImFont 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, bool cpu_fine_clip = false); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(FontSize * scale, text, text_end, wrap_width); } + inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(Sources[0].SizePixels * scale, text, text_end, wrap_width); } #endif // [Internal] Don't use! IMGUI_API void ClearOutputData(); IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst);// , bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); - IMGUI_API ImFontGlyph* BuildLoadGlyph(ImWchar c); - IMGUI_API void BuildGrowIndex(int new_size); }; // Added indirection to avoid patching ImDrawCmd after texture updates. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c9c32e930..e3986229a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2394,6 +2394,7 @@ void ImGui::ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, in // [SECTION] ImFontConfig //----------------------------------------------------------------------------- +// FIXME-NEWATLAS: Oversample specification could be more dynamic. For now, favoring automatic selection. ImFontConfig::ImFontConfig() { memset(this, 0, sizeof(*this)); @@ -2495,9 +2496,9 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildAddFont() // - ImFontAtlasBuildSetupFontCreateEllipsisFromDot() // - ImFontAtlasBuildSetupFontSpecialGlyphs() -// - ImFontAtlasBuildDiscardFontGlyph() -// - ImFontAtlasBuildDiscardFontGlyphs() -// - ImFontAtlasBuildReloadFont() +// - ImFontAtlasBuildDiscardUnusedBakes() +// - ImFontAtlasBuildDiscardFontBaked() +// - ImFontAtlasBuildDiscardFontBakedGlyph() //----------------------------------------------------------------------------- // - ImFontAtlasAddDrawListSharedData() // - ImFontAtlasRemoveDrawListSharedData() @@ -2594,6 +2595,7 @@ ImFontAtlas::ImFontAtlas() RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. TexRef._TexData = NULL;// this; TexNextUniqueID = 1; + FontNextUniqueID = 1; Builder = NULL; } @@ -2685,7 +2687,8 @@ static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* at // Called by NewFrame(). When multiple context own the atlas, only the first one calls this. // If you are calling this yourself, ensure atlas->RendererHasTexUpdates is et. -void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) +// 'frame_count' needs to be provided because we can gc/prioritize baked fonts based on their age. +void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count) { // Check that font atlas was built or backend support texture reload in which case we can build now if (atlas->RendererHasTextures) @@ -2701,6 +2704,33 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas) if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges) IM_ASSERT_USER_ERROR(atlas->RendererHasTextures == false, "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build()."); + // Clear BakedCurrent cache, this is important because it ensure the uncached path gets taken once. + // We also rely on ImFontBaked* pointers never crossing frames. + ImFontAtlasBuilder* builder = atlas->Builder; + builder->FrameCount = frame_count; + for (ImFont* font : atlas->Fonts) + font->LastBaked = NULL; + + // Garbage collect BakedPool + if (builder->BakedDiscardedCount > 0) + { + int dst_n = 0, src_n = 0; + for (; src_n < builder->BakedPool.Size; src_n++) + { + ImFontBaked* p_src = &builder->BakedPool[src_n]; + if (p_src->WantDestroy) + continue; + ImFontBaked* p_dst = &builder->BakedPool[dst_n++]; + if (p_dst == p_src) + continue; + memcpy(p_dst, p_src, sizeof(ImFontBaked)); + builder->BakedMap.SetVoidPtr(p_dst->BakedId, p_dst); + } + IM_ASSERT(dst_n + builder->BakedDiscardedCount == src_n); + builder->BakedPool.Size -= builder->BakedDiscardedCount; + builder->BakedDiscardedCount = 0; + } + // Update texture status for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) { @@ -2928,15 +2958,23 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) ImFontAtlasBuildInit(this); // Create new font + ImFont* font; if (!font_cfg->MergeMode) - Fonts.push_back(IM_NEW(ImFont)); + { + font = IM_NEW(ImFont)(); + font->FontId = FontNextUniqueID++; + Fonts.push_back(font); + } else + { IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. + font = Fonts.back(); + } Sources.push_back(*font_cfg); ImFontConfig& new_font_cfg = Sources.back(); if (new_font_cfg.DstFont == NULL) - new_font_cfg.DstFont = Fonts.back(); + new_font_cfg.DstFont = font; if (!new_font_cfg.FontDataOwnedByAtlas) { new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize); @@ -2960,7 +2998,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) Sources.pop_back(); if (!font_cfg->MergeMode) { - IM_DELETE(Fonts.back()); + IM_DELETE(font); Fonts.pop_back(); } return NULL; @@ -3091,7 +3129,7 @@ static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, bool need_bind_ctx = ctx != curr_ctx; if (need_bind_ctx) ImGui::SetCurrentContext(ctx); - ImGui::SetCurrentFont(new_font); + ImGui::SetCurrentFont(new_font, ctx->FontSize); if (need_bind_ctx) ImGui::SetCurrentContext(curr_ctx); } @@ -3102,7 +3140,7 @@ static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, void ImFontAtlas::RemoveFont(ImFont* font) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - ImFontAtlasBuildDiscardFontGlyphs(this, font); + font->ClearOutputData(); for (int src_n = 0; src_n < font->SourcesCount; src_n++) { @@ -3151,7 +3189,7 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int wid IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - +#if 0 ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); if (r_id < 0) return -1; @@ -3174,6 +3212,12 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int wid glyph.PackId = r_id; ImFontAtlasBuildAddFontGlyph(this, font, &font->Sources[0], &glyph); return r_id; +#endif + // FIXME-BAKED: Need a design for AddCustomRectFontGlyph() + IM_UNUSED(codepoint); + IM_UNUSED(offset); + IM_UNUSED(advance_x); + return -1; } ImTextureRect* ImFontAtlas::GetCustomRectByIndex(int idx) @@ -3237,10 +3281,10 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) atlas->TexIsBuilt = true; } -void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v) +void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v) { // Automatically disable horizontal oversampling over size 36 - *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (src->SizePixels * src->RasterizerDensity > 36.0f || src->PixelSnapH) ? 1 : 2; + *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : ((size * src->RasterizerDensity > 36.0f) || src->PixelSnapH) ? 1 : 2; *out_oversample_v = (src->OversampleV != 0) ? src->OversampleV : 1; } @@ -3277,11 +3321,12 @@ void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas) for (int src_n = 0; src_n < font->SourcesCount; src_n++) { ImFontConfig* src = &font->Sources[src_n]; + ImFontBaked* baked = font->GetFontBaked(src->SizePixels); const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault(); IM_ASSERT(ranges != NULL); for (; ranges[0]; ranges += 2) for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 - font->FindGlyphNoFallback((ImWchar)c); + baked->FindGlyphNoFallback((ImWchar)c); } } @@ -3436,22 +3481,23 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ //----------------------------------------------------------------------------------------------------------------------------- -static const ImFontGlyph* LoadFirstExistingGlyph(ImFont* font, const ImWchar* candidate_chars, int candidate_chars_count) +ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size) { - for (int n = 0; n < candidate_chars_count; n++) - if (candidate_chars[n] != 0) - if (const ImFontGlyph* glyph = font->FindGlyphNoFallback(candidate_chars[n])) - return glyph; - return NULL; + struct { ImGuiID FontId; float BakedSize; } hashed_data; + hashed_data.FontId = font_id; + hashed_data.BakedSize = baked_size; + return ImHashData(&hashed_data, sizeof(hashed_data)); } +//----------------------------------------------------------------------------------------------------------------------------- + bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) { ImFont* font = src->DstFont; if (src->MergeMode == false) { font->ClearOutputData(); - font->FontSize = src->SizePixels; + //font->FontSize = src->SizePixels; font->ContainerAtlas = atlas; IM_ASSERT(font->Sources == src); } @@ -3466,15 +3512,15 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) // Rasterize our own ellipsis character from a dot. // This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. -// FIXME-NEWATLAS: This borrows too much from FontLoader's FontAddGlyph() and suggest that we should add further helpers. -static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFont* font, const ImFontGlyph* dot_glyph) +// FIXME-NEWATLAS: This borrows too much from FontBackend_FontAddGlyph() and suggest that we should add further helpers. +// FIXME-BAKED: prebaked ellipsis +/*static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFont* font, const ImFontGlyph* dot_glyph) { ImFontAtlasRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_glyph->PackId); const int dot_spacing = 1; const float dot_step = (dot_glyph->X1 - dot_glyph->X0) + dot_spacing; ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, (dot_r->w * 3 + dot_spacing * 2), dot_r->h); ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); - font->MetricsTotalSurface += r->w * r->h; ImFontGlyph glyph; glyph.Codepoint = (ImWchar)0x0085; // FIXME: Using arbitrary codepoint. @@ -3494,6 +3540,33 @@ static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, I for (int n = 0; n < 3; n++) ImFontAtlasTextureBlockCopy(tex, dot_r->x, dot_r->y, tex, r->x + (dot_r->w + dot_spacing) * n, r->y, dot_r->w, dot_r->h); ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); +}*/ + +static void ImFontAtlasBuildSetupFontBakedSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) +{ + // FIXME-NEWATLAS: could we use a scheme where this is lazily loaded? + IM_ASSERT(baked->FallbackGlyphIndex == -1); + if (font->FallbackChar != 0) + if (const ImFontGlyph* glyph = baked->FindGlyphNoFallback(font->FallbackChar)) + { + baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(glyph); // Storing index avoid need to update pointer on growth. + baked->FallbackAdvanceX = glyph->AdvanceX; + } + + // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews) + ImFontGlyph* space_glyph = (ImFontGlyph*)(void*)baked->FindGlyphNoFallback((ImWchar)' '); + if (space_glyph != NULL) + space_glyph->Visible = false; + + // Setup Tab character. + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (baked->FindGlyphNoFallback('\t') == NULL && space_glyph != NULL) + { + ImFontGlyph tab_glyph; + tab_glyph.Codepoint = '\t'; + tab_glyph.AdvanceX = space_glyph->AdvanceX * IM_TABSIZE; + ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, &tab_glyph); + } } // Load/identify special glyphs @@ -3507,31 +3580,15 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im // While manipulating glyphs during init we want to restrict all searches for one source font. font->LockSingleSrcConfigIdx = (short)src_idx_in_font; - // Setup Fallback character - // FIXME-NEWATLAS: could we use a scheme where this is lazily loaded? + // Find Fallback character. Actual glyph loaded in GetFontBaked(). const ImWchar fallback_chars[] = { font->FallbackChar, (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; - if (font->FallbackGlyphIndex == -1) - if (const ImFontGlyph* glyph = LoadFirstExistingGlyph(font, fallback_chars, IM_ARRAYSIZE(fallback_chars))) - { - font->FallbackChar = (ImWchar)glyph->Codepoint; - font->FallbackGlyphIndex = font->Glyphs.index_from_ptr(glyph); // Storing index avoid need to update pointer on growth. - font->FallbackAdvanceX = glyph->AdvanceX; - } - - // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews) - ImFontGlyph* space_glyph = (ImFontGlyph*)(void*)font->FindGlyph((ImWchar)' '); - if (space_glyph != NULL) - space_glyph->Visible = false; - - // Setup Tab character. - // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) - if (font->FindGlyphNoFallback('\t') == NULL && space_glyph != NULL) - { - ImFontGlyph tab_glyph; - tab_glyph.Codepoint = '\t'; - tab_glyph.AdvanceX = space_glyph->AdvanceX * IM_TABSIZE; - ImFontAtlasBuildAddFontGlyph(atlas, font, src, &tab_glyph); - } + if (font->FallbackChar == 0) + for (ImWchar candidate_char : fallback_chars) + if (candidate_char != 0 && font->IsGlyphInFont(candidate_char)) // FIXME: does not respect LockSingleSrcConfigIdx() + { + font->FallbackChar = (ImWchar)candidate_char; + break; + } // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. @@ -3546,16 +3603,16 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im } if (font->EllipsisChar == 0) { - const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; + /*const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; if (const ImFontGlyph* dot_glyph = LoadFirstExistingGlyph(font, dots_chars, IM_ARRAYSIZE(dots_chars))) ImFontAtlasBuildSetupFontCreateEllipsisFromDot(atlas, font, dot_glyph); - else + else*/ font->EllipsisChar = (ImWchar)' '; } font->LockSingleSrcConfigIdx = -1; } -void ImFontAtlasBuildDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontGlyph* glyph) +void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph) { if (glyph->PackId >= 0) { @@ -3564,41 +3621,45 @@ void ImFontAtlasBuildDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontGl } ImWchar c = glyph->Codepoint; IM_ASSERT(font->FallbackChar != c && font->EllipsisChar != c); // Unsupported for simplicity - IM_ASSERT(glyph >= font->Glyphs.Data && glyph < font->Glyphs.Data + font->Glyphs.Size); - font->IndexLookup[c] = (ImWchar)IM_FONTGLYPH_INDEX_UNUSED; - font->IndexAdvanceX[c] = font->FallbackAdvanceX; + IM_ASSERT(glyph >= baked->Glyphs.Data && glyph < baked->Glyphs.Data + baked->Glyphs.Size); + baked->IndexLookup[c] = IM_FONTGLYPH_INDEX_UNUSED; + baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; } -void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font) +void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFontBaked* baked) { - for (ImFontGlyph& glyph : font->Glyphs) + ImGuiContext& g = *GImGui; + IM_UNUSED(g); // for IMGUI_DEBUG_LOG_FONT() + + ImFontAtlasBuilder* builder = atlas->Builder; + ImFont* font = baked->ContainerFont; + IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName()); + + for (ImFontGlyph& glyph : baked->Glyphs) if (glyph.PackId >= 0) ImFontAtlasPackDiscardRect(atlas, glyph.PackId); - font->ClearOutputData(); - font->FallbackChar = font->EllipsisChar = 0; + + if (atlas->FontLoader->FontBakedDestroy) + atlas->FontLoader->FontBakedDestroy(atlas, baked); + + builder->BakedMap.SetVoidPtr(baked->BakedId, NULL); + builder->BakedDiscardedCount++; + baked->ClearOutputData(); + baked->WantDestroy = true; + font->LastBaked = NULL; } -// Discard old glyphs and reload font. Use if changing font size. -void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font) +void ImFontAtlasBuildDiscardUnusedBakes(ImFontAtlas* atlas, ImFont* font_filter) { - ImFontAtlasBuildDiscardFontGlyphs(atlas, font); - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + ImFontAtlasBuilder* builder = atlas->Builder; + const int GC_FRAMES = 2; + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) { - ImFontConfig* src = (ImFontConfig*)(void*)&font->Sources[src_n]; - IM_ASSERT(src->SizePixels > 0.0f); - - // Reload font in backend - if (atlas->FontLoader && atlas->FontLoader->FontSrcDestroy != NULL) - atlas->FontLoader->FontSrcDestroy(atlas, src); - if (atlas->FontLoader && atlas->FontLoader->FontSrcInit != NULL) - atlas->FontLoader->FontSrcInit(atlas, src); - - ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); // Technically this is called for each source sub-font, tho 99.9% of the time the first one fills everything. - atlas->TexIsBuilt = false; + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (font_filter == NULL || baked->ContainerFont == font_filter) + if (baked->LastUsedFrame + GC_FRAMES < atlas->Builder->FrameCount && !baked->WantDestroy) + ImFontAtlasBuildDiscardFontBaked(atlas, baked); } - - // Notify external systems - ImFontAtlasBuildNotifySetFont(atlas, font, font); } // Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* @@ -3747,8 +3808,8 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) builder->RectsDiscardedSurface = 0; // Patch glyphs UV - for (ImFont* font : atlas->Fonts) - for (ImFontGlyph& glyph : font->Glyphs) + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + for (ImFontGlyph& glyph : builder->BakedPool[baked_n].Glyphs) if (glyph.PackId != -1) { ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); @@ -3798,8 +3859,11 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas) { - // Currently using a heuristic for repack without growing. + // Can some baked contents be ditched? ImFontAtlasBuilder* builder = atlas->Builder; + ImFontAtlasBuildDiscardUnusedBakes(atlas, NULL); + + // Currently using a heuristic for repack without growing. if (builder->RectsDiscardedSurface < builder->RectsPackedSurface * 0.20f) ImFontAtlasBuildGrowTexture(atlas); else @@ -3845,6 +3909,8 @@ ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) { ImFontAtlasBuilder* builder = atlas->Builder; + ImFontAtlasBuildDiscardUnusedBakes(atlas, NULL); + ImTextureData* old_tex = atlas->TexData; ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height); ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); @@ -3927,7 +3993,7 @@ void ImFontAtlasPackInit(ImFontAtlas * atlas) ImFontAtlasBuilder* builder = atlas->Builder; // In theory we could decide to reduce the number of nodes, e.g. halve them, and waste a little texture space, but it doesn't seem worth it. - int pack_node_count = tex->Width; + const int pack_node_count = tex->Width; builder->PackNodes.resize(pack_node_count); IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque)); stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width, tex->Height, builder->PackNodes.Data, builder->PackNodes.Size); @@ -4046,38 +4112,40 @@ ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id return &builder->Rects[index_entry->TargetIndex]; } -ImFontGlyph* ImFont::BuildLoadGlyph(ImWchar codepoint) +ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) { - ImFontAtlas* atlas = ContainerAtlas; - if (LockDisableLoading || atlas->Locked) + ImFont* font = ContainerFont; + ImFontBaked* baked = this; + ImFontAtlas* atlas = font->ContainerAtlas; + if (font->LockDisableLoading || atlas->Locked) return NULL; //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildAddGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); // Load from single source or all sources? - int srcs_count = (LockSingleSrcConfigIdx != -1) ? 1 : SourcesCount; - ImFontConfig* srcs = (LockSingleSrcConfigIdx != -1) ? &Sources[LockSingleSrcConfigIdx] : Sources; + int srcs_count = (font->LockSingleSrcConfigIdx != -1) ? 1 : font->SourcesCount; + ImFontConfig* srcs = (font->LockSingleSrcConfigIdx != -1) ? &font->Sources[font->LockSingleSrcConfigIdx] : font->Sources; // Call backend const ImFontLoader* font_loader = atlas->FontLoader; - if (!font_loader->FontAddGlyph(atlas, this, srcs, srcs_count, codepoint)) + if (!font_loader->FontBakedAddGlyph(atlas, baked, srcs, srcs_count, codepoint)) { // Mark index as not found, so we don't attempt the search twice - BuildGrowIndex(codepoint + 1); - IndexAdvanceX[codepoint] = FallbackAdvanceX; - IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; + baked->BuildGrowIndex(codepoint + 1); + baked->IndexAdvanceX[codepoint] = baked->FallbackAdvanceX; + baked->IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; return NULL; } // FIXME: Add hooks for e.g. #7962 - ImFontGlyph* glyph = &Glyphs.back(); + ImFontGlyph* glyph = &baked->Glyphs.back(); return glyph; } // The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b IM_MSVC_RUNTIME_CHECKS_OFF -static float BuildLoadGlyphGetAdvanceOrFallback(ImFont* font, unsigned int codepoint) +static float BuildLoadGlyphGetAdvanceOrFallback(ImFontBaked* font, unsigned int codepoint) { ImFontGlyph* glyph = font->BuildLoadGlyph((ImWchar)codepoint); return glyph ? glyph->AdvanceX : font->FallbackAdvanceX; @@ -4124,9 +4192,7 @@ void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) struct ImGui_ImplStbTrueType_FontSrcData { stbtt_fontinfo FontInfo; - float ScaleForRasterX; // Factor in RasterizationDensity * OversampleH - float ScaleForRasterY; // Factor in RasterizationDensity * OversampleV - float ScaleForLayout; + float ScaleFactor; }; static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) @@ -4152,28 +4218,10 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* } src->FontLoaderData = bd_font_data; - // FIXME-NEWFONTS: reevaluate sizing metrics - int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); - float scale; if (src->SizePixels > 0.0f) - scale = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); + bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); else - scale = -stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); - bd_font_data->ScaleForRasterX = scale * src->SizePixels * src->RasterizerDensity * oversample_h; - bd_font_data->ScaleForRasterY = scale * src->SizePixels * src->RasterizerDensity * oversample_v; - bd_font_data->ScaleForLayout = scale * src->SizePixels; - - // FIXME-NEWFONTS: make use of line gap value - int unscaled_ascent, unscaled_descent, unscaled_line_gap; - stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); - - if (src->MergeMode == false) - { - ImFont* font = src->DstFont; - font->Ascent = ImCeil(unscaled_ascent * bd_font_data->ScaleForLayout); - font->Descent = ImFloor(unscaled_descent * bd_font_data->ScaleForLayout); - } + bd_font_data->ScaleFactor = -stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); return true; } @@ -4197,7 +4245,27 @@ static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFon return glyph_index != 0; } -static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) +static void ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontBaked* baked) +{ + IM_UNUSED(atlas); + ImFont* font = baked->ContainerFont; + + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = &font->Sources[src_n]; + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + + // FIXME-NEWFONTS: reevaluate how to use sizing metrics + // FIXME-NEWFONTS: make use of line gap value + float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); + baked->Descent = ImFloor(unscaled_descent * scale_for_layout); + } +} + +static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) { // Search for first font which has the glyph ImGui_ImplStbTrueType_FontSrcData* bd_font_data = NULL; @@ -4215,9 +4283,12 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, if (glyph_index == 0) return false; // Not found - const float scale_for_layout = bd_font_data->ScaleForLayout; // ~ (font units to pixels) - const float scale_for_raster_x = bd_font_data->ScaleForRasterX; // ~ (font units to pixels) * RasterizationDensity * OversampleH - const float scale_for_raster_y = bd_font_data->ScaleForRasterY; // ~ (font units to pixels) * RasterizationDensity * OversampleV + // Fonts unit to pixels + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(src, baked->Size, &oversample_h, &oversample_v); + const float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; + const float scale_for_raster_x = bd_font_data->ScaleFactor * baked->Size * src->RasterizerDensity * oversample_h; + const float scale_for_raster_y = bd_font_data->ScaleFactor * baked->Size * src->RasterizerDensity * oversample_v; // Obtain size and advance int x0, y0, x1, y1; @@ -4235,8 +4306,6 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, // (generally based on stbtt_PackFontRangesRenderIntoRects) if (is_visible) { - int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); const int w = (x1 - x0 + oversample_h - 1); const int h = (y1 - y0 + oversample_v - 1); ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); @@ -4246,9 +4315,7 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); return false; } - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); - font->MetricsTotalSurface += w * h; // Render stbtt_GetGlyphBitmapBox(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, &x0, &y0, &x1, &y1); @@ -4267,7 +4334,7 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, stbtt__v_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_v); float font_off_x = src->GlyphOffset.x + stbtt__oversample_shift(oversample_h); - float font_off_y = src->GlyphOffset.y + stbtt__oversample_shift(oversample_v) + IM_ROUND(font->Ascent); + float font_off_y = src->GlyphOffset.y + stbtt__oversample_shift(oversample_v) + IM_ROUND(baked->Ascent); float recip_h = 1.0f / (oversample_h * src->RasterizerDensity); float recip_v = 1.0f / (oversample_v * src->RasterizerDensity); @@ -4280,19 +4347,19 @@ static bool ImGui_ImplStbTrueType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, glyph.Y1 = (y0 + (int)r->h) * recip_v + font_off_y; glyph.Visible = true; glyph.PackId = pack_id; - ImFontAtlasBuildAddFontGlyph(atlas, font, src, &glyph); + ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph); // Copy to texture, post-process and queue update for backend ImTextureData* tex = atlas->TexData; IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); ImFontAtlasTextureBlockConvert(bitmap_pixels, ImTextureFormat_Alpha8, w, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); - ImFontAtlasPostProcessData pp_data = { atlas, font, src, &font->Glyphs.back(), tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h }; + ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, &baked->Glyphs.back(), tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h }; ImFontAtlasTextureBlockPostProcess(&pp_data); ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } else { - ImFontAtlasBuildAddFontGlyph(atlas, font, src, &glyph); + ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph); } return true; @@ -4305,7 +4372,9 @@ const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() loader.FontSrcInit = ImGui_ImplStbTrueType_FontSrcInit; loader.FontSrcDestroy = ImGui_ImplStbTrueType_FontSrcDestroy; loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph; - loader.FontAddGlyph = ImGui_ImplStbTrueType_FontAddGlyph; + loader.FontBakedInit = ImGui_ImplStbTrueType_FontBakedInit; + loader.FontBakedDestroy = NULL; + loader.FontBakedAddGlyph = ImGui_ImplStbTrueType_FontBakedAddGlyph; return &loader; } @@ -4628,6 +4697,34 @@ void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) // [SECTION] ImFont //----------------------------------------------------------------------------- +ImFontBaked::ImFontBaked() +{ + memset(this, 0, sizeof(*this)); + FallbackGlyphIndex = -1; +} + +void ImFontBaked::ClearOutputData() +{ + FallbackAdvanceX = 0.0f; + Glyphs.clear(); + IndexAdvanceX.clear(); + IndexLookup.clear(); + FallbackGlyphIndex = -1; + Ascent = Descent = 0.0f; + MetricsTotalSurface = 0; +} + +void ImFontBaked::BuildGrowIndex(int new_size) +{ + IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); + if (new_size <= IndexLookup.Size) + return; + //ImGuiContext& g = *GImGui; + //IMGUI_DEBUG_LOG_FONT("[font] BuildGrowIndex(%d)\n", new_size); + IndexAdvanceX.resize(new_size, -1.0f); + IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); +} + ImFont::ImFont() { memset(this, 0, sizeof(*this)); @@ -4642,14 +4739,17 @@ ImFont::~ImFont() void ImFont::ClearOutputData() { - FallbackAdvanceX = 0.0f; - Glyphs.clear(); - IndexAdvanceX.clear(); - IndexLookup.clear(); - FallbackGlyphIndex = -1; - Ascent = Descent = 0.0f; - MetricsTotalSurface = 0; + if (ImFontAtlas* atlas = ContainerAtlas) + if (ImFontAtlasBuilder* builder = atlas->Builder) + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->ContainerFont == this) + ImFontAtlasBuildDiscardFontBaked(atlas, baked); + } + FallbackChar = EllipsisChar = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); + LastBaked = NULL; } // API is designed this way to avoid exposing the 8K page size @@ -4665,24 +4765,15 @@ bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) return true; } -void ImFont::BuildGrowIndex(int new_size) -{ - IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); - if (new_size <= IndexLookup.Size) - return; - IndexAdvanceX.resize(new_size, -1.0f); - IndexLookup.resize(new_size, (ImU16)-1); -} - // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. // Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). // 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. -ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, const ImFontGlyph* in_glyph) +ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph) { - int glyph_idx = font->Glyphs.Size; - font->Glyphs.push_back(*in_glyph); - ImFontGlyph& glyph = font->Glyphs[glyph_idx]; - IM_ASSERT(font->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. + int glyph_idx = baked->Glyphs.Size; + baked->Glyphs.push_back(*in_glyph); + ImFontGlyph& glyph = baked->Glyphs[glyph_idx]; + IM_ASSERT(baked->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. // Set UV from packed rectangle if (in_glyph->PackId >= 0) @@ -4693,6 +4784,7 @@ ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFo glyph.V0 = (r->y) * atlas->TexUvScale.y; glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + baked->MetricsTotalSurface += r->w * r->h; } if (src != NULL) @@ -4718,17 +4810,22 @@ ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFo // Update lookup tables int codepoint = glyph.Codepoint; - font->BuildGrowIndex(codepoint + 1); - font->IndexAdvanceX[codepoint] = glyph.AdvanceX; - font->IndexLookup[codepoint] = (ImU16)glyph_idx; + baked->BuildGrowIndex(codepoint + 1); + baked->IndexAdvanceX[codepoint] = glyph.AdvanceX; + baked->IndexLookup[codepoint] = (ImU16)glyph_idx; const int page_n = codepoint / 8192; - font->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); + baked->ContainerFont->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); return &glyph; } void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst) { + // FIXME-BAKED: Implement AddRemapChar() + IM_UNUSED(from_codepoint); + IM_UNUSED(to_codepoint); + IM_UNUSED(overwrite_dst); + /* IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. unsigned int index_size = (unsigned int)IndexLookup.Size; @@ -4740,10 +4837,11 @@ void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool ove BuildGrowIndex(from_codepoint + 1); IndexLookup[from_codepoint] = (to_codepoint < index_size) ? IndexLookup.Data[to_codepoint] : (ImU16)-1; IndexAdvanceX[from_codepoint] = (to_codepoint < index_size) ? IndexAdvanceX.Data[to_codepoint] : 1.0f; + */ } // Find glyph, load if necessary, return fallback if missing -ImFontGlyph* ImFont::FindGlyph(ImWchar c) +ImFontGlyph* ImFontBaked::FindGlyph(ImWchar c) { if (c < (size_t)IndexLookup.Size) IM_LIKELY { @@ -4758,7 +4856,7 @@ ImFontGlyph* ImFont::FindGlyph(ImWchar c) } // Attempt to load but when missing, return NULL instead of FallbackGlyph -ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) +ImFontGlyph* ImFontBaked::FindGlyphNoFallback(ImWchar c) { if (c < (size_t)IndexLookup.Size) IM_LIKELY { @@ -4768,11 +4866,10 @@ ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) if (i != IM_FONTGLYPH_INDEX_UNUSED) return &Glyphs.Data[i]; } - ImFontGlyph* glyph = BuildLoadGlyph(c); - return glyph; + return BuildLoadGlyph(c); } -bool ImFont::IsGlyphLoaded(ImWchar c) +bool ImFontBaked::IsGlyphLoaded(ImWchar c) { if (c < (size_t)IndexLookup.Size) IM_LIKELY { @@ -4797,7 +4894,7 @@ bool ImFont::IsGlyphInFont(ImWchar c) // This is manually inlined in CalcTextSizeA() and CalcWordWrapPosition(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). IM_MSVC_RUNTIME_CHECKS_OFF -float ImFont::GetCharAdvance(ImWchar c) +float ImFontBaked::GetCharAdvance(ImWchar c) { if ((int)c < IndexAdvanceX.Size) { @@ -4813,6 +4910,46 @@ float ImFont::GetCharAdvance(ImWchar c) } IM_MSVC_RUNTIME_CHECKS_RESTORE +// ImFontBaked pointers are valid for the entire frame but shall never be kept between frames. +ImFontBaked* ImFont::GetFontBaked(float size) +{ + ImFontBaked* baked = LastBaked; + if (baked && baked->Size == size) + return baked; + + ImFontAtlas* atlas = ContainerAtlas; + ImFontAtlasBuilder* builder = atlas->Builder; + + ImGuiID baked_id = ImFontAtlasBakedGetId(FontId, size); + ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); + baked = *p_baked_in_map; + if (baked != NULL) + { + // FIXME-BAKED: Design for picking a nearest size? + IM_ASSERT(baked->Size == size && baked->ContainerFont == this && baked->BakedId == baked_id); + baked->LastUsedFrame = builder->FrameCount; + LastBaked = baked; + return baked; + } + + // Create new + ImGuiContext& g = *GImGui; + IM_UNUSED(g); // for IMGUI_DEBUG_LOG_FONT() + IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", size); + baked = builder->BakedPool.push_back(ImFontBaked()); + baked->Size = size; + baked->BakedId = baked_id; + baked->ContainerFont = this; + baked->LastUsedFrame = ContainerAtlas->Builder->FrameCount; + LastBaked = baked; + *p_baked_in_map = baked; // To avoid 'builder->BakedMap.SetVoidPtr(baked_id, baked);' while we can. + if (atlas->FontLoader->FontBakedInit) + atlas->FontLoader->FontBakedInit(atlas, baked); + ImFontAtlasBuildSetupFontBakedSpecialGlyphs(atlas, baked->ContainerFont, baked); + + return baked; +} + // Trim trailing space and find beginning of next line static inline const char* CalcWordWrapNextLineStartA(const char* text, const char* text_end) { @@ -4839,10 +4976,13 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha // Cut words that cannot possibly fit within one line. // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + ImFontBaked* baked = GetFontBaked(size); + const float scale = size / baked->Size; + float line_width = 0.0f; float word_width = 0.0f; float blank_width = 0.0f; - const float scale = size / FontSize; wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters const char* word_end = text; @@ -4877,9 +5017,9 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha } // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' - float char_width = (c < (unsigned int)IndexAdvanceX.Size) ? IndexAdvanceX.Data[c] : -1.0f; + float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f; if (char_width < 0.0f) - char_width = BuildLoadGlyphGetAdvanceOrFallback(this, c); + char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c); if (ImCharIsBlankW(c)) { @@ -4935,7 +5075,8 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons text_end = text_begin + ImStrlen(text_begin); // FIXME-OPT: Need to avoid this. const float line_height = size; - const float scale = size / FontSize; + ImFontBaked* baked = GetFontBaked(size); + const float scale = size / baked->Size; ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; @@ -4986,9 +5127,9 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons } // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' - float char_width = (c < (unsigned int)IndexAdvanceX.Size) ? IndexAdvanceX.Data[c] : -1.0f; + float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f; if (char_width < 0.0f) - char_width = BuildLoadGlyphGetAdvanceOrFallback(this, c); + char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c); char_width *= scale; if (line_width + char_width >= max_width) @@ -5015,12 +5156,13 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip) { - const ImFontGlyph* glyph = FindGlyph(c); + ImFontBaked* baked = GetFontBaked(size); + const ImFontGlyph* glyph = baked->FindGlyph(c); if (!glyph || !glyph->Visible) return; if (glyph->Colored) col |= ~IM_COL32_A_MASK; - float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + float scale = (size >= 0.0f) ? (size / baked->Size) : 1.0f; float x = IM_TRUNC(pos.x); float y = IM_TRUNC(pos.y); @@ -5062,8 +5204,10 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im 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 scale = size / FontSize; - const float line_height = FontSize * scale; + const float line_height = size; + ImFontBaked* baked = GetFontBaked(size); + + const float scale = size / baked->Size; const float origin_x = x; const bool word_wrap_enabled = (wrap_width > 0.0f); @@ -5158,7 +5302,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im continue; } - const ImFontGlyph* glyph = FindGlyph((ImWchar)c); + const ImFontGlyph* glyph = baked->FindGlyph((ImWchar)c); if (glyph == NULL) continue; diff --git a/imgui_internal.h b/imgui_internal.h index 07cd84667..5075028ca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2130,11 +2130,12 @@ struct ImGuiContext ImGuiIO IO; ImGuiPlatformIO PlatformIO; ImGuiStyle Style; - ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() - float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. - float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. - float FontScale; // == FontSize / Font->FontSize - float CurrentDpiScale; // Current window/viewport DpiScale + ImFont* Font; // == FontStack.back().Font + ImFontBaked* FontBaked; // == Font->GetFontBaked(FontSize) + float FontSize; // == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. + //float FontBaseSize; // == io.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. + float FontScale; // == FontBaked->Size / Font->FontSize. Scale factor over baked size. + float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale ImDrawListSharedData DrawListSharedData; ImVectorTextures; double Time; @@ -2673,7 +2674,7 @@ public: // We don't use g.FontSize because the window may be != g.CurrentWindow. ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } - float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontBaseSize * FontWindowScale * FontWindowScaleParents; } + //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontBaseSize * FontWindowScale * FontWindowScaleParents; } ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } }; @@ -3098,7 +3099,7 @@ namespace ImGui IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); // Fonts, drawing - IMGUI_API void SetCurrentFont(ImFont* font); + IMGUI_API void SetCurrentFont(ImFont* font, float font_size); inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } IMGUI_API void PushPasswordFont(); inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. @@ -3661,7 +3662,9 @@ struct ImFontLoader bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); - bool (*FontAddGlyph)(ImFontAtlas* atlas, ImFont* font, ImFontConfig* srcs, int srcs_count, ImWchar codepoint); + void (*FontBakedInit)(ImFontAtlas* atlas, ImFontBaked* baked); + void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontBaked* baked); + bool (*FontBakedAddGlyph)(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* srcs, int srcs_count, ImWchar codepoint); ImFontLoader() { memset(this, 0, sizeof(*this)); } }; @@ -3698,6 +3701,7 @@ struct ImFontAtlasPostProcessData ImFontAtlas* FontAtlas; ImFont* Font; ImFontConfig* FontSrc; + ImFontBaked* FontBaked; ImFontGlyph* Glyph; // Pixel data @@ -3723,11 +3727,17 @@ struct ImFontAtlasBuilder int RectsPackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. int RectsDiscardedCount; int RectsDiscardedSurface; + int FrameCount; // Current frame count 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. + // Cache of all ImFontBaked + ImStableVector BakedPool; + ImGuiStorage BakedMap; + int BakedDiscardedCount; + // Custom rectangle identifiers ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. ImFontAtlasRectId PackIdLinesTexData; @@ -3750,20 +3760,23 @@ IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas); IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); -IMGUI_API ImFontGlyph* ImFontAtlasBuildAddFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, const ImFontGlyph* in_glyph); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); -IMGUI_API void ImFontAtlasBuildDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontGlyph* glyph); -IMGUI_API void ImFontAtlasBuildDiscardFontGlyphs(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasBuildDiscardUnusedBakes(ImFontAtlas* atlas, ImFont* font_filter); +IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); +IMGUI_API void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font); // <--- Your future new best friend! IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy -IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); +IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); + +IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); +IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size); IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); IMGUI_API ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); -IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count); IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e1813110d..e41041ce1 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3375,7 +3375,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label ButtonBehavior(row_r, row_id, NULL, NULL); KeepAliveID(row_id); - const float ascent_scaled = g.Font->Ascent * g.FontScale; // FIXME: Standardize those scaling factors better + const float ascent_scaled = g.FontBaked->Ascent * g.FontScale; // FIXME: Standardize those scaling factors better const float line_off_for_ascent_x = (ImMax((g.FontSize - ascent_scaled) * 0.5f, 0.0f) / -sin_a) * (flip_label ? -1.0f : 1.0f); const ImVec2 padding = g.Style.CellPadding; // We will always use swapped component const ImVec2 align = g.Style.TableAngledHeadersTextAlign; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c632b45a4..2304aaf37 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1518,7 +1518,7 @@ bool ImGui::TextLink(const char* label) ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z); } - float line_y = bb.Max.y + ImFloor(g.Font->Descent * g.FontScale * 0.20f); + float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontScale * 0.20f); window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode // FIXME-DPI PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); @@ -3956,9 +3956,10 @@ static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining, ImVec2* out_offset, bool stop_on_new_line) { ImGuiContext& g = *ctx; - ImFont* font = g.Font; + //ImFont* font = g.Font; + ImFontBaked* baked = g.FontBaked; const float line_height = g.FontSize; - const float scale = line_height / font->FontSize; + const float scale = line_height / baked->Size; ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; @@ -3984,7 +3985,7 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c if (c == '\r') continue; - line_width += font->GetCharAdvance((ImWchar)c) * scale; + line_width += baked->GetCharAdvance((ImWchar)c) * scale; } if (text_size.x < line_width) @@ -4011,7 +4012,7 @@ namespace ImStb { static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; } static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx <= obj->TextLen); return obj->TextSrc[idx]; } -static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; } +static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.FontBaked->GetCharAdvance((ImWchar)c) * g.FontScale; } static char STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx) { @@ -4314,19 +4315,21 @@ void ImGui::PushPasswordFont() { ImGuiContext& g = *GImGui; ImFont* in_font = g.Font; + ImFontBaked* in_baked = g.FontBaked; + ImFontGlyph glyph = *in_baked->FindGlyph('*'); + glyph.PackId = -1; ImFont* out_font = &g.InputTextPasswordFont; - ImFontGlyph* glyph = in_font->FindGlyph('*'); - out_font->FontSize = in_font->FontSize; out_font->Scale = in_font->Scale; - out_font->Ascent = in_font->Ascent; - out_font->Descent = in_font->Descent; out_font->ContainerAtlas = in_font->ContainerAtlas; - out_font->Glyphs.resize(0); - out_font->Glyphs.push_back(*glyph); - out_font->FallbackGlyphIndex = 0; - out_font->FallbackAdvanceX = glyph->AdvanceX; out_font->LockDisableLoading = true; - IM_ASSERT(out_font->Glyphs.Size == 1 && out_font->IndexAdvanceX.Size == 0 && out_font->IndexLookup.Size == 0); + ImFontBaked* out_baked = out_font->GetFontBaked(in_baked->Size); + IM_ASSERT(out_baked->Glyphs.Size <= 1 && out_baked->IndexAdvanceX.Size == 0 && out_baked->IndexLookup.Size == 0); + out_baked->Ascent = in_baked->Ascent; + out_baked->Descent = in_baked->Descent; + out_baked->Glyphs.resize(0); + out_baked->Glyphs.push_back(glyph); + out_baked->FallbackGlyphIndex = 0; + out_baked->FallbackAdvanceX = glyph.AdvanceX; PushFont(out_font); } @@ -5354,7 +5357,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else { ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, &p, NULL, true); - if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines + if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn)); rect.ClipWith(clip_rect); if (rect.Overlaps(clip_rect)) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index b388d1531..022ec2b2c 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -46,6 +46,7 @@ #include FT_FREETYPE_H // #include FT_MODULE_H // #include FT_GLYPH_H // +#include FT_SIZES_H // #include FT_SYNTHESIS_H // // Handle LunaSVG and PlutoSVG @@ -150,15 +151,19 @@ namespace ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } }; - // Font parameters and metrics. - struct ImGui_ImplFreeType_FontInfo + // Stored in ImFontBaked::FontBackendData: pointer to SourcesCount instances of this. + struct ImGui_ImplFreeType_FontSrcBakedData { - float PixelHeight; // Size this font was generated with. + FT_Size FtSize; // This represent a FT_Face with a given size. + + // Metrics float Ascender; // The pixel extents above the baseline in pixels (typically positive). float Descender; // The extents below the baseline in pixels (typically negative). float LineSpacing; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. float LineGap; // The spacing in pixels between one row's descent and the next row's ascent. float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font. + + ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } }; // Stored in ImFontConfig::FontLoaderData @@ -166,20 +171,19 @@ namespace { bool InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. void CloseFont(); - void SetPixelHeight(float pixel_height); // Change font pixel size. const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch); ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); } ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); } // Members - ImGui_ImplFreeType_FontInfo Info; // Font descriptor of the current font. FT_Face FtFace; unsigned int UserFlags; // = ImFontConfig::RasterizerFlags FT_Int32 LoadFlags; FT_Render_Mode RenderMode; float RasterizationDensity; float InvRasterizationDensity; + ImFontBaked* BakedLastActivated; }; bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_font_builder_flags) @@ -222,9 +226,6 @@ namespace RasterizationDensity = src->RasterizerDensity; InvRasterizationDensity = 1.0f / RasterizationDensity; - memset(&Info, 0, sizeof(Info)); - SetPixelHeight(src->SizePixels); - return true; } @@ -237,31 +238,6 @@ namespace } } - void ImGui_ImplFreeType_FontSrcData::SetPixelHeight(float pixel_height) - { - // Vuhdo (2017): "I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height' - // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me. - // FT_Set_Pixel_Sizes() doesn't seem to get us the same result." - // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL) - FT_Size_RequestRec req; - req.type = (UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; - req.width = 0; - req.height = (uint32_t)(pixel_height * 64 * RasterizationDensity); - req.horiResolution = 0; - req.vertResolution = 0; - FT_Request_Size(FtFace, &req); - // Note: To handle multiple sizes later, we may need to use FT_New_Size(), FT_Activate_Size() - - // Update font info - FT_Size_Metrics metrics = FtFace->size->metrics; - Info.PixelHeight = pixel_height * InvRasterizationDensity; - Info.Ascender = (float)FT_CEIL(metrics.ascender) * InvRasterizationDensity; - Info.Descender = (float)FT_CEIL(metrics.descender) * InvRasterizationDensity; - Info.LineSpacing = (float)FT_CEIL(metrics.height) * InvRasterizationDensity; - Info.LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * InvRasterizationDensity; - Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * InvRasterizationDensity; - } - const FT_Glyph_Metrics* ImGui_ImplFreeType_FontSrcData::LoadGlyph(uint32_t codepoint) { uint32_t glyph_index = FT_Get_Char_Index(FtFace, codepoint); @@ -447,12 +423,6 @@ bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) if (!bd_font_data->InitFont(bd->Library, src, atlas->FontBuilderFlags)) return false; - if (src->MergeMode == false) - { - ImFont* font = src->DstFont; - font->Ascent = bd_font_data->Info.Ascender; - font->Descent = bd_font_data->Info.Descender; - } return true; } @@ -464,7 +434,65 @@ void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) src->FontLoaderData = NULL; } -bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) +void ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontBaked* baked) +{ + IM_UNUSED(atlas); + ImFont* font = baked->ContainerFont; + const float size = baked->Size; + + IM_ASSERT(baked->FontBackendData == NULL); + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_datas = (ImGui_ImplFreeType_FontSrcBakedData*)IM_ALLOC(sizeof(ImGui_ImplFreeType_FontSrcBakedData) * font->SourcesCount); + baked->FontBackendData = bd_baked_datas; + + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = &font->Sources[src_n]; + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontBackendData; + bd_font_data->BakedLastActivated = baked; + + // We need one FT_Size per source, so create one ImGui_ImplFreeType_FontBakedData for each source. + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = &bd_baked_datas[src_n]; + FT_New_Size(bd_font_data->FtFace, &bd_baked_data->FtSize); + FT_Activate_Size(bd_baked_data->FtSize); + + // Vuhdo 2017: "I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height' + // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me. + // FT_Set_Pixel_Sizes() doesn't seem to get us the same result." + // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL) + FT_Size_RequestRec req; + req.type = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; + req.width = 0; + req.height = (uint32_t)(size * 64 * bd_font_data->RasterizationDensity); + req.horiResolution = 0; + req.vertResolution = 0; + FT_Request_Size(bd_font_data->FtFace, &req); + + // Read metrics + FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; + bd_baked_data->Ascender = (float)FT_CEIL(metrics.ascender) * bd_font_data->InvRasterizationDensity; + bd_baked_data->Descender = (float)FT_CEIL(metrics.descender) * bd_font_data->InvRasterizationDensity; + bd_baked_data->LineSpacing = (float)FT_CEIL(metrics.height) * bd_font_data->InvRasterizationDensity; + bd_baked_data->LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * bd_font_data->InvRasterizationDensity; + bd_baked_data->MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * bd_font_data->InvRasterizationDensity; + + // Output + baked->Ascent = bd_baked_data->Ascender; + baked->Descent = bd_baked_data->Descender; + } +} + +void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontBaked* baked) +{ + IM_UNUSED(atlas); + ImFont* font = baked->ContainerFont; + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_datas = (ImGui_ImplFreeType_FontSrcBakedData*)baked->FontBackendData; + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + FT_Done_Size(bd_baked_datas[src_n].FtSize); + IM_FREE(bd_baked_datas); + baked->FontBackendData = NULL; +} + +bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) { // Search for first font which has the glyph ImGui_ImplFreeType_FontSrcData* bd_font_data = NULL; @@ -481,6 +509,15 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon if (glyph_index == 0) return false; // Not found + if (bd_font_data->BakedLastActivated != baked) + { + // Activate current size + int src_n = (int)(font_cfg - srcs); + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = &((ImGui_ImplFreeType_FontSrcBakedData*)baked->FontBackendData)[src_n]; + FT_Activate_Size(bd_baked_data->FtSize); + bd_font_data->BakedLastActivated = baked; + } + const FT_Glyph_Metrics* metrics = bd_font_data->LoadGlyph(codepoint); if (metrics == NULL) return false; @@ -515,9 +552,7 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); return false; } - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); - font->MetricsTotalSurface += w * h; // Render pixels to our temporary buffer atlas->Builder->TempBuffer.resize(w * h * 4); @@ -525,7 +560,7 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w); float font_off_x = src->GlyphOffset.x; - float font_off_y = src->GlyphOffset.y + IM_ROUND(font->Ascent); + float font_off_y = src->GlyphOffset.y + IM_ROUND(baked->Ascent); float recip_h = 1.0f / src->RasterizerDensity; float recip_v = 1.0f / src->RasterizerDensity; @@ -539,19 +574,19 @@ bool ImGui_ImplFreeType_FontAddGlyph(ImFontAtlas* atlas, ImFont* font, ImFontCon glyph.Visible = true; glyph.Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); glyph.PackId = pack_id; - ImFontAtlasBuildAddFontGlyph(atlas, font, src, &glyph); + ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph); // Copy to texture, post-process and queue update for backend ImTextureData* tex = atlas->TexData; IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); ImFontAtlasTextureBlockConvert(temp_buffer, ImTextureFormat_RGBA32, w * 4, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); - ImFontAtlasPostProcessData pp_data = { atlas, font, src, &font->Glyphs.back(), tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h }; + ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, &baked->Glyphs.back(), tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h }; ImFontAtlasTextureBlockPostProcess(&pp_data); ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } else { - ImFontAtlasBuildAddFontGlyph(atlas, font, src, &glyph); + ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph); } return true; } @@ -573,7 +608,9 @@ const ImFontLoader* ImGuiFreeType::GetFontLoader() loader.FontSrcInit = ImGui_ImplFreeType_FontSrcInit; loader.FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy; loader.FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph; - loader.FontAddGlyph = ImGui_ImplFreeType_FontAddGlyph; + loader.FontBakedInit = ImGui_ImplFreeType_FontBakedInit; + loader.FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy; + loader.FontBakedAddGlyph = ImGui_ImplFreeType_FontBakedAddGlyph; return &loader; } From 80404fae3048eb27ae04d06388475ad4b7475deb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jan 2025 16:32:25 +0100 Subject: [PATCH 0940/2359] Fonts: clarify ClearTexData() as not supported with dynamic atlases. --- imgui.cpp | 6 ++++-- imgui.h | 4 ++-- imgui_draw.cpp | 42 ++++++++++++++++++++++++------------------ 3 files changed, 30 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index abe3cab3e..0b1433857 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5785,7 +5785,8 @@ void ImGui::EndFrame() UpdateTexturesEndFrame(); // Unlock font atlas - g.IO.Fonts->Locked = false; + ImFontAtlas* atlas = g.IO.Fonts; + atlas->Locked = false; // Clear Input data for next frame g.IO.MousePosPrev = g.IO.MousePos; @@ -8575,8 +8576,9 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) void ImGui::UpdateFontsNewFrame() { ImGuiContext& g = *GImGui; + ImFontAtlas* atlas = g.IO.Fonts; if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) - g.IO.Fonts->Locked = true; + atlas->Locked = true; SetCurrentFont(GetDefaultFont(), GetDefaultFont()->Sources[0].SizePixels); IM_ASSERT(g.Font->IsLoaded()); } diff --git a/imgui.h b/imgui.h index 85fbb47d9..717c9f0e4 100644 --- a/imgui.h +++ b/imgui.h @@ -3517,7 +3517,7 @@ struct ImFontAtlas // As we are transitioning toward a new font system, we expect to obsolete those soon: 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 ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). - IMGUI_API void ClearTexData(); // [OBSOLETE] Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. + IMGUI_API void ClearTexData(); // [OBSOLETE] Clear CPU-side copy of the texture data. Saves RAM once the texture has been copied to graphics memory. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy path for build atlas + retrieving pixel data. @@ -3592,7 +3592,7 @@ struct ImFontAtlas ImTextureRef TexRef; // User data to refer to the latest texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. ImTextureData* TexData; // Current texture ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! - bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. + bool Locked; // Marked as locked during ImGui::NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert. bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context. bool TexIsBuilt; // Set when texture was built matching current font input. Mostly useful for legacy IsBuilt() call. bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e3986229a..7c7a7916a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2607,9 +2607,11 @@ ImFontAtlas::~ImFontAtlas() void ImFontAtlas::Clear() { - ClearInputData(); - ClearTexData(); ClearFonts(); + bool backup_renderer_has_textures = RendererHasTextures; + RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. + ClearTexData(); + RendererHasTextures = backup_renderer_has_textures; } void ImFontAtlas::ClearCache() @@ -2647,12 +2649,14 @@ void ImFontAtlas::ClearInputData() Sources.clear(); } +// Clear CPU-side copy of the texture data. void ImFontAtlas::ClearTexData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - TexList.clear(); - IM_DELETE(TexData); - TexData = NULL; + IM_ASSERT(RendererHasTextures == false && "Not supported for dynamic atlases, but you may call Clear()."); + for (ImTextureData* tex : TexList) + tex->DestroyPixels(); + //Locked = true; // Hoped to be able to lock this down but some reload patterns may not be happy with it. } void ImFontAtlas::ClearFonts() @@ -2686,7 +2690,7 @@ static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* at } // Called by NewFrame(). When multiple context own the atlas, only the first one calls this. -// If you are calling this yourself, ensure atlas->RendererHasTexUpdates is et. +// If you are calling this yourself, ensure atlas->RendererHasTextures is set. // 'frame_count' needs to be provided because we can gc/prioritize baked fonts based on their age. void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count) { @@ -3256,7 +3260,7 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso return true; } -// When atlas->RendererHasTexUpdates == true, this is only called if no font were loaded. +// When atlas->RendererHasTextures = true, this is only called if no font were loaded. void ImFontAtlasBuildMain(ImFontAtlas* atlas) { IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); @@ -3481,16 +3485,6 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ //----------------------------------------------------------------------------------------------------------------------------- -ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size) -{ - struct { ImGuiID FontId; float BakedSize; } hashed_data; - hashed_data.FontId = font_id; - hashed_data.BakedSize = baked_size; - return ImHashData(&hashed_data, sizeof(hashed_data)); -} - -//----------------------------------------------------------------------------------------------------------------------------- - bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) { ImFont* font = src->DstFont; @@ -4910,6 +4904,14 @@ float ImFontBaked::GetCharAdvance(ImWchar c) } IM_MSVC_RUNTIME_CHECKS_RESTORE +ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size) +{ + struct { ImGuiID FontId; float BakedSize; } hashed_data; + hashed_data.FontId = font_id; + hashed_data.BakedSize = baked_size; + return ImHashData(&hashed_data, sizeof(hashed_data)); +} + // ImFontBaked pointers are valid for the entire frame but shall never be kept between frames. ImFontBaked* ImFont::GetFontBaked(float size) { @@ -4920,18 +4922,22 @@ ImFontBaked* ImFont::GetFontBaked(float size) ImFontAtlas* atlas = ContainerAtlas; ImFontAtlasBuilder* builder = atlas->Builder; + // FIXME-BAKED: Design for picking a nearest size? ImGuiID baked_id = ImFontAtlasBakedGetId(FontId, size); ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); baked = *p_baked_in_map; if (baked != NULL) { - // FIXME-BAKED: Design for picking a nearest size? IM_ASSERT(baked->Size == size && baked->ContainerFont == this && baked->BakedId == baked_id); baked->LastUsedFrame = builder->FrameCount; LastBaked = baked; return baked; } + // FIXME-BAKED: If atlas is locked, find closest match + if (atlas->Locked) + IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! + // Create new ImGuiContext& g = *GImGui; IM_UNUSED(g); // for IMGUI_DEBUG_LOG_FONT() From daaf0e4ef30678540f3ad862008de218e8fbb0f1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jan 2025 20:24:05 +0100 Subject: [PATCH 0941/2359] Fonts: Added PushFontSize(), PopFontSize() api. Added font_size param to PushFont() as well. Fonts: Fixed PopFont() recovery. (To squash into "Added PushFontSize(), PopFontSize() api." --- imgui.cpp | 80 ++++++++++++++++++++++++++++++------------------ imgui.h | 14 +++++---- imgui_draw.cpp | 11 ++++--- imgui_internal.h | 8 ++++- 4 files changed, 73 insertions(+), 40 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0b1433857..fb26c967b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1270,6 +1270,7 @@ static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt); // Misc static void UpdateFontsNewFrame(); +static void UpdateFontsEndFrame(); static void UpdateTexturesNewFrame(); static void UpdateTexturesEndFrame(); static void UpdateSettings(); @@ -5762,6 +5763,7 @@ void ImGui::EndFrame() // End frame g.WithinFrameScope = false; g.FrameCountEnded = g.FrameCount; + UpdateFontsEndFrame(); // Initiate moving window + handle left-click and right-click focus UpdateMouseMovingWindowEndFrame(); @@ -8579,64 +8581,84 @@ void ImGui::UpdateFontsNewFrame() ImFontAtlas* atlas = g.IO.Fonts; if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) atlas->Locked = true; - SetCurrentFont(GetDefaultFont(), GetDefaultFont()->Sources[0].SizePixels); + PushFont(GetDefaultFont(), GetDefaultFont()->Sources[0].SizePixels); IM_ASSERT(g.Font->IsLoaded()); } -// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only. -void ImGui::SetCurrentFont(ImFont* font, float font_size) +void ImGui::UpdateFontsEndFrame() { - ImGuiContext& g = *GImGui; - IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? - IM_ASSERT(font->Scale > 0.0f); - g.Font = font; - //g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.FontBaked->Size * g.Font->Scale); - g.FontSize = font_size;// g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; - g.FontBaked = g.Font->GetFontBaked(g.FontSize); - g.FontScale = g.FontSize / g.FontBaked->Size; - g.DrawListSharedData.Font = g.Font; - g.DrawListSharedData.FontSize = g.FontSize; - g.DrawListSharedData.FontScale = g.FontScale; - ImFontAtlasUpdateDrawListsSharedData(g.Font->ContainerAtlas); - if (g.CurrentWindow) - g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexRef); + PopFont(); } -// Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authoritative against window-local ImDrawList. -// - Whereas ImDrawList::PushTextureID()/PopTextureID() is not to be used across Begin() calls. +// Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList. +// - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls. // - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... // - Some code paths never really fully worked with multiple atlas textures. -// - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID() +// - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture() // the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem // because we have a concrete need and a test bed for multiple atlas textures. // FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ? -void ImGui::PushFont(ImFont* font) +void ImGui::SetCurrentFont(ImFont* font, float font_size) +{ + ImGuiContext& g = *GImGui; + g.Font = font; + //g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.FontBaked->FontSize * g.Font->Scale); + g.FontSize = font_size;// g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + if (font != NULL) + { + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(font->Scale > 0.0f); + g.FontBaked = g.Font->GetFontBaked(g.FontSize); + g.FontScale = g.FontSize / g.FontBaked->Size; + g.DrawListSharedData.Font = g.Font; + g.DrawListSharedData.FontSize = g.FontSize; + g.DrawListSharedData.FontScale = g.FontScale; + ImFontAtlasUpdateDrawListsSharedData(g.Font->ContainerAtlas); + if (g.CurrentWindow != NULL) + g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexRef); + } + else + { + g.FontBaked = NULL; + g.FontScale = 0.0f; + } +} + +void ImGui::PushFont(ImFont* font, float font_size) { ImGuiContext& g = *GImGui; if (font == NULL) font = GetDefaultFont(); - g.FontStack.push_back(font); - SetCurrentFont(font, g.FontSize); + if (font_size < 0.0f) + font_size = g.FontSize; + g.FontStack.push_back({ font, font_size }); + SetCurrentFont(font, font_size); } void ImGui::PopFont() { ImGuiContext& g = *GImGui; - if (g.FontStack.Size <= 0) + if (g.FontStack.Size <= 1 && g.WithinFrameScope) { IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!"); return; } g.FontStack.pop_back(); - ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); - SetCurrentFont(font, g.FontSize); // FIXME-BAKED: size in stack + if (ImFontStackData* font_stack_data = (g.FontStack.Size > 0) ? &g.FontStack.back() : NULL) + SetCurrentFont(font_stack_data->Font, font_stack_data->FontSize); + else + SetCurrentFont(NULL, 0.0f); } -void ImGui::SetFontSize(float size) +void ImGui::PushFontSize(float font_size) { - // FIXME-BAKED ImGuiContext& g = *GImGui; - SetCurrentFont(g.Font, size); + PushFont(g.Font, font_size); +} + +void ImGui::PopFontSize() +{ + PopFont(); } //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 717c9f0e4..d60deceb9 100644 --- a/imgui.h +++ b/imgui.h @@ -469,11 +469,13 @@ namespace ImGui IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. - // Parameters stacks (shared) - IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font + // Parameters stacks (font) + IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. IMGUI_API void PopFont(); - IMGUI_API void SetFontSize(float size); - //IMGUI_API void PopFontSize(); + IMGUI_API void PushFontSize(float size); + IMGUI_API void PopFontSize(); + + // Parameters stacks (shared) IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); IMGUI_API void PopStyleColor(int count = 1); @@ -3657,8 +3659,8 @@ struct ImFontBaked // Font runtime data and rendering // - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. // - Since 1.92.X a font may be rendered as any size! Therefore a font doesn't have one specific size. -// - Use 'font->GetBakedForSize(size)' to retrieve the ImFontBaked* corresponding to a given size. -// - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetBakedForSize(g.FontSize). +// - Use 'font->GetFontBaked(size)' to retrieve the ImFontBaked* corresponding to a given size. +// - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetFontBaked(g.FontSize). struct ImFont { // [Internal] Members: Cold ~32/40/80 bytes diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7c7a7916a..362697609 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -434,7 +434,7 @@ void ImDrawList::_SetDrawListSharedData(ImDrawListSharedData* data) } // Initialize before use in a new frame. We always have a command ready in the buffer. -// In the majority of cases, you would want to call PushClipRect() and PushTextureID() after this. +// In the majority of cases, you would want to call PushClipRect() and PushTexture() after this. void ImDrawList::_ResetForNewFrame() { // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. @@ -683,7 +683,7 @@ void ImDrawList::PopTexture() _OnChangedTexture(); } -// This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTextureID()/PopTextureID(). +// This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture(). void ImDrawList::_SetTexture(ImTextureRef tex_ref) { if (_CmdHeader.TexRef == tex_ref) @@ -3042,7 +3042,7 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f * 1.0f; if (font_cfg.Name[0] == '\0') - ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels); + ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf"); font_cfg.EllipsisChar = (ImWchar)0x0085; font_cfg.GlyphOffset.y = 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units @@ -3074,7 +3074,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, // Store a short copy of filename into 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_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels); + ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s", p); } return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); } @@ -3137,6 +3137,9 @@ static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, if (need_bind_ctx) ImGui::SetCurrentContext(curr_ctx); } + for (ImFontStackData& font_stack_data : ctx->FontStack) + if (font_stack_data.Font == old_font) + font_stack_data.Font = new_font; } } } diff --git a/imgui_internal.h b/imgui_internal.h index 5075028ca..f0812d71f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -869,6 +869,12 @@ struct ImDrawDataBuilder ImDrawDataBuilder() { memset(this, 0, sizeof(*this)); } }; +struct ImFontStackData +{ + ImFont* Font; + float FontSize; +}; + //----------------------------------------------------------------------------- // [SECTION] Style support //----------------------------------------------------------------------------- @@ -2237,7 +2243,7 @@ struct ImGuiContext ImGuiCol DebugFlashStyleColorIdx; // (Keep close to ColorStack to share cache line) ImVector ColorStack; // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() ImVector StyleVarStack; // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() - ImVector FontStack; // Stack for PushFont()/PopFont() - inherited by Begin() + ImVector FontStack; // Stack for PushFont()/PopFont() - inherited by Begin() ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin() ImVector ItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() ImVector GroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin() From be151977ca24c503cc7176d2a1eaf9aa4207ac6f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jan 2025 14:31:13 +0100 Subject: [PATCH 0942/2359] Fonts: Texture resizing favor growing height, halve pack nodes. --- imgui_draw.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 362697609..ff861d8d1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3838,9 +3838,10 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ IM_ASSERT(ImIsPowerOfTwo(atlas->TexMinWidth) && ImIsPowerOfTwo(atlas->TexMaxWidth) && ImIsPowerOfTwo(atlas->TexMinHeight) && ImIsPowerOfTwo(atlas->TexMaxHeight)); // Grow texture so it follows roughly a square. - // Caller should be taking account of RectsDiscardedSurface and may not need to grow. - int new_tex_w = (old_tex_h < old_tex_w) ? old_tex_w : old_tex_w * 2; - int new_tex_h = (old_tex_h < old_tex_w) ? old_tex_h * 2 : old_tex_h; + // - Grow height before width, as width imply more packing nodes. + // - Caller should be taking account of RectsDiscardedSurface and may not need to grow. + int new_tex_w = (old_tex_h <= old_tex_w) ? old_tex_w : old_tex_w * 2; + int new_tex_h = (old_tex_h <= old_tex_w) ? old_tex_h * 2 : old_tex_h; // Handle minimum size first (for pathologically large packed rects) const int pack_padding = atlas->TexGlyphPadding; @@ -3990,7 +3991,7 @@ void ImFontAtlasPackInit(ImFontAtlas * atlas) ImFontAtlasBuilder* builder = atlas->Builder; // In theory we could decide to reduce the number of nodes, e.g. halve them, and waste a little texture space, but it doesn't seem worth it. - const int pack_node_count = tex->Width; + const int pack_node_count = tex->Width / 2; builder->PackNodes.resize(pack_node_count); IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque)); stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width, tex->Height, builder->PackNodes.Data, builder->PackNodes.Size); From 3ce753c489307835eee04a448db18264fe02fa4c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jan 2025 14:36:06 +0100 Subject: [PATCH 0943/2359] Fonts: Debug dump to disk, debug log. --- imgui_draw.cpp | 29 ++++++++++++++++++----------- imgui_internal.h | 2 +- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ff861d8d1..ef7ff1549 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3625,9 +3625,6 @@ void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImF void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFontBaked* baked) { - ImGuiContext& g = *GImGui; - IM_UNUSED(g); // for IMGUI_DEBUG_LOG_FONT() - ImFontAtlasBuilder* builder = atlas->Builder; ImFont* font = baked->ContainerFont; IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName()); @@ -3755,11 +3752,20 @@ ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h) return new_tex; } -void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) +#if 0 +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include "../stb/stb_image_write.h" +static void ImFontAtlasDebugWriteTexToDisk(ImTextureData* tex, const char* description) { ImGuiContext& g = *GImGui; - IM_UNUSED(g); // for IMGUI_DEBUG_LOG_FONT() + char buf[128]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "[%05d] Texture #%03d - %s.png", g.FrameCount, tex->UniqueID, description); + stbi_write_png(buf, tex->Width, tex->Height, tex->BytesPerPixel, tex->Pixels, tex->GetPitch()); // tex->BytesPerPixel is technically not component, but ok for the formats we support. +} +#endif +void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) +{ ImFontAtlasBuilder* builder = atlas->Builder; builder->LockDisableResize = true; @@ -3767,6 +3773,10 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) ImTextureData* new_tex = ImFontAtlasBuildAddTexture(atlas, w, h); new_tex->UseColors = old_tex->UseColors; IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d\n", old_tex->UniqueID, old_tex->Width, old_tex->Height, new_tex->UniqueID, new_tex->Width, new_tex->Height); + //for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + // IMGUI_DEBUG_LOG_FONT("[font] - Baked %.2fpx, %d glyphs, want_destroy=%d\n", builder->BakedPool[baked_n].FontSize, builder->BakedPool[baked_n].Glyphs.Size, builder->BakedPool[baked_n].WantDestroy); + //IMGUI_DEBUG_LOG_FONT("[font] - Old packed rects: %d, area %d px\n", builder->RectsPackedCount, builder->RectsPackedSurface); + //ImFontAtlasDebugWriteTexToDisk(old_tex, "Before Pack"); // Repack, lose discarded rectangle, copy pixels // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic. @@ -3822,10 +3832,12 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) builder->LockDisableResize = false; ImFontAtlasUpdateDrawListsSharedData(atlas); + //ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack"); } void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_h) { + //ImFontAtlasDebugWriteTexToDisk(atlas->TexData, "Before Grow"); ImFontAtlasBuilder* builder = atlas->Builder; if (old_tex_w == -1) old_tex_w = atlas->TexData->Width; @@ -3858,6 +3870,7 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas) { // Can some baked contents be ditched? + //IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()\n"); ImFontAtlasBuilder* builder = atlas->Builder; ImFontAtlasBuildDiscardUnusedBakes(atlas, NULL); @@ -4072,8 +4085,6 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon // If we ran out of attempts, return fallback if (attempts_remaining == 0 || builder->LockDisableResize) { - ImGuiContext& g = *GImGui; - IM_UNUSED(g); IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.\n", w, h); return -1; } @@ -4717,8 +4728,6 @@ void ImFontBaked::BuildGrowIndex(int new_size) IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); if (new_size <= IndexLookup.Size) return; - //ImGuiContext& g = *GImGui; - //IMGUI_DEBUG_LOG_FONT("[font] BuildGrowIndex(%d)\n", new_size); IndexAdvanceX.resize(new_size, -1.0f); IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); } @@ -4943,8 +4952,6 @@ ImFontBaked* ImFont::GetFontBaked(float size) IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! // Create new - ImGuiContext& g = *GImGui; - IM_UNUSED(g); // for IMGUI_DEBUG_LOG_FONT() IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", size); baked = builder->BakedPool.push_back(ImFontBaked()); baked->Size = size; diff --git a/imgui_internal.h b/imgui_internal.h index f0812d71f..3216f2181 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -247,7 +247,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IMGUI_DEBUG_LOG_SELECTION(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_CLIPPER(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_IO(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_FONT(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_FONT(...) do { ImGuiContext& g2 = *GImGui; if (g2.DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) // Static Asserts From 57d345ff80415edbefb0024bdcb7997621292b9b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jan 2025 17:49:52 +0100 Subject: [PATCH 0944/2359] Textures: Comments around ImTextureID type. --- imgui.h | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index d60deceb9..935f2b3b7 100644 --- a/imgui.h +++ b/imgui.h @@ -311,12 +311,17 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- // ImTextureID: user data for renderer backend to identify a texture [Compile-time configurable type] -// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. -// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. -// - You can make this a structure with various constructors if you need. You will have to implement ==/!= operators. -// - (note: before v1.91.4 (2024/10/08) the default type for ImTextureID was void*. Use intermediary intptr_t cast and read FAQ if you have casting warnings) +// Overview: +// - Backend and user/app code provides ImTextureID values that gets stored inside draw commands (ImDrawCmd) during the ImGui frame. +// - Backend uses ImDrawCmd::GetTexID() to retrieve the ImTextureID value during rendering. Then, they can bind the textures of each draw command. +// Configuring the type: +// - To use something else than a 64-bit value: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - This can be whatever to you want it to be! read the FAQ entry about textures for details. +// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various constructors if you like. You will need to implement ==/!= operators. +// History: +// - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requirig 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. #ifndef ImTextureID -typedef ImU64 ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) +typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that. #endif // Define this to another value if you need value of 0 to be valid. From df694c89b00ee69f4a18203630a6a1500e92b665 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 17:16:34 +0100 Subject: [PATCH 0945/2359] Fonts: Baked system, v11. --- imgui_draw.cpp | 38 +++++++++++++++++++++----------------- imgui_internal.h | 4 ++-- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ef7ff1549..b537132fb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2497,8 +2497,9 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildSetupFontCreateEllipsisFromDot() // - ImFontAtlasBuildSetupFontSpecialGlyphs() // - ImFontAtlasBuildDiscardUnusedBakes() -// - ImFontAtlasBuildDiscardFontBaked() // - ImFontAtlasBuildDiscardFontBakedGlyph() +// - ImFontAtlasBuildDiscardFontBaked() +// - ImFontAtlasBuildDiscardFont() //----------------------------------------------------------------------------- // - ImFontAtlasAddDrawListSharedData() // - ImFontAtlasRemoveDrawListSharedData() @@ -3623,10 +3624,9 @@ void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImF baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; } -void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFontBaked* baked) +void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) { ImFontAtlasBuilder* builder = atlas->Builder; - ImFont* font = baked->ContainerFont; IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName()); for (ImFontGlyph& glyph : baked->Glyphs) @@ -3643,16 +3643,25 @@ void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFontBaked* baked) font->LastBaked = NULL; } -void ImFontAtlasBuildDiscardUnusedBakes(ImFontAtlas* atlas, ImFont* font_filter) +void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font) +{ + if (ImFontAtlasBuilder* builder = atlas->Builder) // This can be called from font destructor + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->ContainerFont == font && !baked->WantDestroy) + ImFontAtlasBuildDiscardFontBaked(atlas, font, baked); + } +} + +void ImFontAtlasBuildDiscardUnusedBakes(ImFontAtlas* atlas, int gc_frames) { ImFontAtlasBuilder* builder = atlas->Builder; - const int GC_FRAMES = 2; for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) { ImFontBaked* baked = &builder->BakedPool[baked_n]; - if (font_filter == NULL || baked->ContainerFont == font_filter) - if (baked->LastUsedFrame + GC_FRAMES < atlas->Builder->FrameCount && !baked->WantDestroy) - ImFontAtlasBuildDiscardFontBaked(atlas, baked); + if (baked->LastUsedFrame + gc_frames < atlas->Builder->FrameCount && !baked->WantDestroy) + ImFontAtlasBuildDiscardFontBaked(atlas, baked->ContainerFont, baked); } } @@ -3872,7 +3881,7 @@ void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas) // Can some baked contents be ditched? //IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()\n"); ImFontAtlasBuilder* builder = atlas->Builder; - ImFontAtlasBuildDiscardUnusedBakes(atlas, NULL); + ImFontAtlasBuildDiscardUnusedBakes(atlas, 2); // Currently using a heuristic for repack without growing. if (builder->RectsDiscardedSurface < builder->RectsPackedSurface * 0.20f) @@ -3920,7 +3929,7 @@ ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) { ImFontAtlasBuilder* builder = atlas->Builder; - ImFontAtlasBuildDiscardUnusedBakes(atlas, NULL); + ImFontAtlasBuildDiscardUnusedBakes(atlas, 1); ImTextureData* old_tex = atlas->TexData; ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height); @@ -4747,13 +4756,7 @@ ImFont::~ImFont() void ImFont::ClearOutputData() { if (ImFontAtlas* atlas = ContainerAtlas) - if (ImFontAtlasBuilder* builder = atlas->Builder) - for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) - { - ImFontBaked* baked = &builder->BakedPool[baked_n]; - if (baked->ContainerFont == this) - ImFontAtlasBuildDiscardFontBaked(atlas, baked); - } + ImFontAtlasBuildDiscardFont(atlas, this); FallbackChar = EllipsisChar = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); LastBaked = NULL; @@ -4936,6 +4939,7 @@ ImFontBaked* ImFont::GetFontBaked(float size) ImFontAtlasBuilder* builder = atlas->Builder; // FIXME-BAKED: Design for picking a nearest size? + // FIXME-BAKED: Altering font density won't work right away. ImGuiID baked_id = ImFontAtlasBakedGetId(FontId, size); ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); baked = *p_baked_in_map; diff --git a/imgui_internal.h b/imgui_internal.h index 3216f2181..a54e3a350 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3767,10 +3767,10 @@ IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); -IMGUI_API void ImFontAtlasBuildDiscardUnusedBakes(ImFontAtlas* atlas, ImFont* font_filter); +IMGUI_API void ImFontAtlasBuildDiscardUnusedBakes(ImFontAtlas* atlas, int gc_frames); +IMGUI_API void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); IMGUI_API void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); -IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFont* font); // <--- Your future new best friend! IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); From 99f6b305c1e7d6b08c70f18971b8865af2a1b725 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 17:46:59 +0100 Subject: [PATCH 0946/2359] Fonts: Baked system, v12: support GlyphOffset / GlyphMinAdvanceX / GlyphMaxAdvanceX by scaling from ref value. Overwriting cfg->PixelSnapH = true; in imgui_freetype is weird. --- imgui.cpp | 2 +- imgui.h | 9 +++++---- imgui_draw.cpp | 14 +++++++++++--- misc/freetype/imgui_freetype.cpp | 12 ++++++++++-- 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fb26c967b..a7cc6a81a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8602,7 +8602,7 @@ void ImGui::SetCurrentFont(ImFont* font, float font_size) { ImGuiContext& g = *GImGui; g.Font = font; - //g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.FontBaked->FontSize * g.Font->Scale); + //g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.FontBaked->Size * g.Font->Scale); g.FontSize = font_size;// g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; if (font != NULL) { diff --git a/imgui.h b/imgui.h index 935f2b3b7..24706e062 100644 --- a/imgui.h +++ b/imgui.h @@ -3424,15 +3424,16 @@ struct ImFontConfig bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + bool PixelSnapV; // true // Align Scaled GlyphOffset.y to pixel boundaries. int FontNo; // 0 // Index of font within TTF/OTF file int OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. int OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). - //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED IN 1.91.9: use GlyphExtraAdvanceX) - ImVec2 GlyphOffset; // 0, 0 // [FIXME-BAKED] Offset all glyphs from this font input. + //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. + ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). - float GlyphMinAdvanceX; // 0 // [FIXME-BAKED] Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font - float GlyphMaxAdvanceX; // FLT_MAX // [FIXME-BAKED] Maximum AdvanceX for glyphs + float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. + float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b537132fb..921241185 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4351,8 +4351,15 @@ static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBa if (oversample_v > 1) stbtt__v_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_v); - float font_off_x = src->GlyphOffset.x + stbtt__oversample_shift(oversample_h); - float font_off_y = src->GlyphOffset.y + stbtt__oversample_shift(oversample_v) + IM_ROUND(baked->Ascent); + const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0].SizePixels; + float font_off_x = (src->GlyphOffset.x * offsets_scale); + float font_off_y = (src->GlyphOffset.y * offsets_scale); + if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. + font_off_x = IM_ROUND(font_off_x); + if (src->PixelSnapV) + font_off_y = IM_ROUND(font_off_y); + font_off_x += stbtt__oversample_shift(oversample_h); + font_off_y += stbtt__oversample_shift(oversample_v) + IM_ROUND(baked->Ascent); float recip_h = 1.0f / (oversample_h * src->RasterizerDensity); float recip_v = 1.0f / (oversample_v * src->RasterizerDensity); @@ -4800,7 +4807,8 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked if (src != NULL) { // Clamp & recenter if needed - float advance_x = ImClamp(glyph.AdvanceX, src->GlyphMinAdvanceX, src->GlyphMaxAdvanceX); + const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0].SizePixels; + float advance_x = ImClamp(glyph.AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); if (advance_x != glyph.AdvanceX) { float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - glyph.AdvanceX) * 0.5f) : (advance_x - glyph.AdvanceX) * 0.5f; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 022ec2b2c..326132b41 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -204,6 +204,9 @@ namespace if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting) LoadFlags |= FT_LOAD_NO_HINTING; + else + src->PixelSnapH = true; // FIXME: A bit weird to do this this way. + if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint) LoadFlags |= FT_LOAD_NO_AUTOHINT; if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint) @@ -559,8 +562,13 @@ bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data; bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w); - float font_off_x = src->GlyphOffset.x; - float font_off_y = src->GlyphOffset.y + IM_ROUND(baked->Ascent); + const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0].SizePixels; + float font_off_x = (src->GlyphOffset.x * offsets_scale); + float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent; + if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. + font_off_x = IM_ROUND(font_off_x); + if (src->PixelSnapV) + font_off_y = IM_ROUND(font_off_y); float recip_h = 1.0f / src->RasterizerDensity; float recip_v = 1.0f / src->RasterizerDensity; From 842c313db2d2b25673383cd0830b367fc51104af Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 19:47:41 +0100 Subject: [PATCH 0947/2359] Fonts: Reordered ImFont fields. --- imgui.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 24706e062..e9b31d367 100644 --- a/imgui.h +++ b/imgui.h @@ -3669,13 +3669,15 @@ struct ImFontBaked // - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetFontBaked(g.FontSize). struct ImFont { - // [Internal] Members: Cold ~32/40/80 bytes + // [Internal] Members: Hot ~8-16 bytes + ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. DO NOT USE. Use GetFontBaked(). + ImFontAtlas* ContainerAtlas; // 4-8 // What we has been loaded into + + // [Internal] Members: Cold ~24-52 bytes // Conceptually Sources[] is the list of font sources merged to create this font. - ImFontBaked* LastBaked; // Cache last bound baked. DO NOT USE. Use GetFontBaked(). ImGuiID FontId; // Unique identifier for the font short SourcesCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances - ImFontAtlas* ContainerAtlas; // 4-8 // out // What we has been loaded into ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() From 658059022629077455c5dad7028c667944ddeec8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 19:15:26 +0100 Subject: [PATCH 0948/2359] Fonts: Allow PushFont/NewFrame/PopFont idioms to function. --- imgui.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index a7cc6a81a..dd4dbf15a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8581,7 +8581,13 @@ void ImGui::UpdateFontsNewFrame() ImFontAtlas* atlas = g.IO.Fonts; if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) atlas->Locked = true; - PushFont(GetDefaultFont(), GetDefaultFont()->Sources[0].SizePixels); + + // We do this really unusual thing of calling *push_front()*, the reason behind that we want to support the PushFont()/NewFrame()/PopFont() idiom. + ImFontStackData font_stack_data = { ImGui::GetDefaultFont(), ImGui::GetDefaultFont()->Sources[0].SizePixels }; + g.FontStack.push_front(font_stack_data); + if (g.FontStack.Size == 1) + ImGui::SetCurrentFont(font_stack_data.Font, font_stack_data.FontSize); + IM_ASSERT(g.Font->IsLoaded()); } From 82b81fce685e303db2355a04e1c257eb2eb0d914 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Feb 2025 19:36:11 +0100 Subject: [PATCH 0949/2359] Fonts: PushFontSize() with -1 uses sources[0]'s size for now (backward compat design) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index dd4dbf15a..f416223cd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8636,7 +8636,7 @@ void ImGui::PushFont(ImFont* font, float font_size) if (font == NULL) font = GetDefaultFont(); if (font_size < 0.0f) - font_size = g.FontSize; + font_size = font->Sources[0].SizePixels; // g.FontSize; g.FontStack.push_back({ font, font_size }); SetCurrentFont(font, font_size); } From 066b24d7416be6b1ad640adb0c3c0e66c39193a9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 4 Feb 2025 20:02:10 +0100 Subject: [PATCH 0950/2359] Fonts: Fixed _OnChangedTextureID() asserting when calling on e.g. finalized drawlists. --- imgui_draw.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 921241185..0f3cf4dc8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -599,7 +599,10 @@ void ImDrawList::_OnChangedTexture() AddDrawCmd(); return; } - IM_ASSERT(curr_cmd->UserCallback == NULL); + + // Unlike other _OnChangedXXX functions this may be called by ImFontAtlasUpdateDrawListsTextures() in more locations so we need to handle this case. + if (curr_cmd->UserCallback != NULL) + return; // Try to merge with previous command if it matches, else use current command ImDrawCmd* prev_cmd = curr_cmd - 1; From 96786a183bf78c12e49ece064af316604c4b5fb2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Feb 2025 14:04:05 +0100 Subject: [PATCH 0951/2359] Fonts: Create a fallback glyph if none is available (fix crash on fonts with no fallback) --- imgui_draw.cpp | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0f3cf4dc8..89ceda78f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3545,20 +3545,27 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) static void ImFontAtlasBuildSetupFontBakedSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) { - // FIXME-NEWATLAS: could we use a scheme where this is lazily loaded? - IM_ASSERT(baked->FallbackGlyphIndex == -1); - if (font->FallbackChar != 0) - if (const ImFontGlyph* glyph = baked->FindGlyphNoFallback(font->FallbackChar)) - { - baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(glyph); // Storing index avoid need to update pointer on growth. - baked->FallbackAdvanceX = glyph->AdvanceX; - } - // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews) ImFontGlyph* space_glyph = (ImFontGlyph*)(void*)baked->FindGlyphNoFallback((ImWchar)' '); if (space_glyph != NULL) space_glyph->Visible = false; + // Load fallback in order to obtain its index + // FIXME-NEWATLAS: could we use a scheme where this is lazily loaded? + IM_ASSERT(baked->FallbackGlyphIndex == -1); + ImFontGlyph* fallback_glyph = NULL; + if (font->FallbackChar != 0) + fallback_glyph = baked->FindGlyphNoFallback(font->FallbackChar); + if (fallback_glyph == NULL) + { + ImFontGlyph glyph; + glyph.Codepoint = 0; + glyph.AdvanceX = space_glyph ? space_glyph->AdvanceX : IM_ROUND(baked->Size * 0.40f); + fallback_glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, &glyph); + } + baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(fallback_glyph); // Storing index avoid need to update pointer on growth and simplify inner loop code + baked->FallbackAdvanceX = fallback_glyph->AdvanceX; + // Setup Tab character. // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) if (baked->FindGlyphNoFallback('\t') == NULL && space_glyph != NULL) From 815553c4b462c4284bd1690fe25e62d1a926ed96 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Feb 2025 14:41:59 +0100 Subject: [PATCH 0952/2359] Fonts: ImFontConfig: added GlyphExcludeRanges[]. --- imgui.h | 1 + imgui_draw.cpp | 23 ++++++++++++++++++++++- imgui_internal.h | 1 + misc/freetype/imgui_freetype.cpp | 2 ++ 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index e9b31d367..e0bea0f51 100644 --- a/imgui.h +++ b/imgui.h @@ -3432,6 +3432,7 @@ struct ImFontConfig //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). + const ImWchar* GlyphExcludeRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a VERY SHORT user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 89ceda78f..11f78e8c5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2990,6 +2990,15 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); } + // Sanity check + if (font_cfg->GlyphExcludeRanges != NULL) + { + int size = 0; + for (const ImWchar* p = font_cfg->GlyphExcludeRanges; p[0] != 0; p++, size++) {} + IM_ASSERT((size & 1) == 0 && "GlyphExcludeRanges[] size must be multiple of two!"); + IM_ASSERT((size <= 64) && "GlyphExcludeRanges[] size must be small!"); + } + // Round font size // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. // - Note that using io.FontGlobalScale or SetWindowFontScale(), with are legacy-ish, partially supported features, can still lead to unrounded sizes. @@ -4149,7 +4158,7 @@ ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) return NULL; //char utf8_buf[5]; - //IMGUI_DEBUG_LOG("[font] BuildAddGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); + //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); // Load from single source or all sources? int srcs_count = (font->LockSingleSrcConfigIdx != -1) ? 1 : font->SourcesCount; @@ -4293,6 +4302,16 @@ static void ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontBaked* } } +// Important! This assume by ImFontConfig::GlyphFilter is a SMALL ARRAY (e.g. <10 entries) +bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint) +{ + if (const ImWchar* exclude_list = src->GlyphExcludeRanges) + for (; exclude_list[0] != 0; exclude_list += 2) + if (codepoint >= exclude_list[0] && codepoint <= exclude_list[1]) + return false; + return true; +} + static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) { // Search for first font which has the glyph @@ -4302,6 +4321,8 @@ static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBa for (int src_n = 0; src_n < srcs_count; src_n++) { src = &srcs[src_n]; + if (src->GlyphExcludeRanges && !ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) + continue; bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; IM_ASSERT(bd_font_data); glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); diff --git a/imgui_internal.h b/imgui_internal.h index a54e3a350..7e7a2c697 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3773,6 +3773,7 @@ IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, IMGUI_API void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); +IMGUI_API bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint); IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 326132b41..e71534c52 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -504,6 +504,8 @@ bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked for (int src_n = 0; src_n < srcs_count; src_n++) { src = &srcs[src_n]; + if (src->GlyphExcludeRanges && !ImFontAtlasBuildFilterCodepointForSource(src, codepoint)) + continue; bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); if (glyph_index != 0) From eb79e3ab3d7a329f33a96f3ed1e3f85024b94418 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Feb 2025 17:51:46 +0100 Subject: [PATCH 0953/2359] Fonts: Restore a functional AddCustomRectFontGlyph(). --- imgui.h | 17 +++++++++-------- imgui_draw.cpp | 31 ++++++++++++++++++++----------- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/imgui.h b/imgui.h index e0bea0f51..d62f56fa8 100644 --- a/imgui.h +++ b/imgui.h @@ -3521,7 +3521,7 @@ struct ImFontAtlas IMGUI_API void RemoveFont(ImFont* font); IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) - IMGUI_API void ClearCache(); // Clear cached glyphs and textures. + IMGUI_API void ClearCache(); // Clear cached glyphs and textures. Invalidates all AddCustomRectXXX return values. // As we are transitioning toward a new font system, we expect to obsolete those soon: 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. @@ -3571,7 +3571,7 @@ struct ImFontAtlas // You can request your rectangles to be mapped as font glyph (given a font + Unicode point), // so you can render e.g. custom colorful icons and use them as regular glyphs. // - Since 1.92.X, packing is done immediately in the function call. Returns >= on success, <0 on error. - // - You can render your pixels into the texture right after calling the AddCustomRectXXX functions, without waiting for the Build() call. + // - You can render your pixels into the texture right after calling the AddCustomRectXXX() functions. // - If your backend supports ImGuiBackendFlags_RendererHasTextures: // Texture may be resized, so you cannot cache UV coordinates: always use CalcCustomRectUV(). // - If you render colored output into your AddCustomRectRegular() rectangle: set 'atlas->TexPixelsUseColors = true' @@ -3579,7 +3579,10 @@ struct ImFontAtlas // - Read docs/FONTS.md for more details about using colorful icons. // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. IMGUI_API int AddCustomRectRegular(int width, int height); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); + IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); +#endif IMGUI_API ImTextureRect* GetCustomRectByIndex(int index); IMGUI_API void CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; @@ -3925,13 +3928,11 @@ namespace ImGui //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 } -//-- OBSOLETED in 1.91.7 (from January 2025): ImFontAtlasCustomRect becomes ImTextureRect -// - ImFontAtlasCustomRect::X --> ImTextureRect::x -// - ImFontAtlasCustomRect::Y --> ImTextureRect::y -// - ImFontAtlasCustomRect::Width --> ImTextureRect::w -// - ImFontAtlasCustomRect::Height --> ImTextureRect::h +//-- OBSOLETED in 1.92.x: ImFontAtlasCustomRect becomes ImTextureRect +// - ImFontAtlasCustomRect::X,Y --> ImTextureRect::x,y +// - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h // - ImFontAtlasCustomRect::GlyphColored --> if you need to write to this, instead you can write to 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph() -// We could make ImTextureRect an union to use old names, such 1) this would be confusing 2) the fix is easy 3) ImFontAtlasCustomRect was always a rather esoteric api. +// We could make ImTextureRect an union to use old names, but 1) this would be confusing 2) the fix is easy 3) ImFontAtlasCustomRect was always a rather esoteric api. typedef ImTextureRect ImFontAtlasCustomRect; /*struct ImFontAtlasCustomRect { diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 11f78e8c5..2a0a300a7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3199,9 +3199,21 @@ int ImFontAtlas::AddCustomRectRegular(int width, int height) return r_id; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// This API does not make sense anymore with scalable fonts. +// - Prefer adding a font source (ImFontConfig) using a custom/procedural loader. +// - You may use ImFontFlags_LockBakedSizes to limit an existing font to known baked sizes: +// ImFont* myfont = io.Fonts->AddFontFromFileTTF(....); +// myfont->GetFontBaked(16.0f); +// myfont->Flags |= ImFontFlags_LockBakedSizes; +int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) +{ + float font_size = font->Sources[0].SizePixels; + return AddCustomRectFontGlyphForSize(font, font_size, codepoint, width, height, advance_x, offset); +} // FIXME: we automatically set glyph.Colored=true by default. // If you need to alter this, you can write 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph(). -int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) +int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) { #ifdef IMGUI_USE_WCHAR32 IM_ASSERT(codepoint <= IM_UNICODE_CODEPOINT_MAX); @@ -3209,7 +3221,9 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int wid IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); -#if 0 + + ImFontBaked* baked = font->GetFontBaked(font_size); + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); if (r_id < 0) return -1; @@ -3217,8 +3231,8 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int wid if (RendererHasTextures) ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); - if (font->IsGlyphLoaded(codepoint)) - ImFontAtlasBuildDiscardFontGlyph(this, font, (ImFontGlyph*)(void*)font->FindGlyph(codepoint)); + if (baked->IsGlyphLoaded(codepoint)) + ImFontAtlasBuildDiscardFontBakedGlyph(this, font, baked, (ImFontGlyph*)(void*)baked->FindGlyph(codepoint)); ImFontGlyph glyph; glyph.Codepoint = codepoint; @@ -3230,15 +3244,10 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int wid glyph.Visible = true; glyph.Colored = true; // FIXME: Arbitrary glyph.PackId = r_id; - ImFontAtlasBuildAddFontGlyph(this, font, &font->Sources[0], &glyph); + ImFontAtlasBakedAddFontGlyph(this, baked, &font->Sources[0], &glyph); return r_id; -#endif - // FIXME-BAKED: Need a design for AddCustomRectFontGlyph() - IM_UNUSED(codepoint); - IM_UNUSED(offset); - IM_UNUSED(advance_x); - return -1; } +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImTextureRect* ImFontAtlas::GetCustomRectByIndex(int idx) { From 8a8d8a7b38f0cb13e711bb3e1be74083f5a968ff Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Feb 2025 18:25:52 +0100 Subject: [PATCH 0954/2359] Fonts: Exposed CompactCache(). Hide ClearCache(). --- imgui.cpp | 8 ++++---- imgui.h | 2 +- imgui_draw.cpp | 31 ++++++++++++++++++++----------- imgui_internal.h | 3 ++- 4 files changed, 27 insertions(+), 17 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f416223cd..3f6c01ded 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15688,14 +15688,14 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) } SeparatorText("Font Atlas"); - if (Button("Clear Cache")) - atlas->ClearCache(); + if (Button("Compact")) + atlas->CompactCache(); SameLine(); if (Button("Grow")) ImFontAtlasBuildGrowTexture(atlas); SameLine(); - if (Button("Compact")) - ImFontAtlasBuildCompactTexture(atlas); + if (Button("Clear Output")) + ImFontAtlasBuildClearTexture(atlas); for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) { diff --git a/imgui.h b/imgui.h index d62f56fa8..1b60ddc9c 100644 --- a/imgui.h +++ b/imgui.h @@ -3521,7 +3521,7 @@ struct ImFontAtlas IMGUI_API void RemoveFont(ImFont* font); IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) - IMGUI_API void ClearCache(); // Clear cached glyphs and textures. Invalidates all AddCustomRectXXX return values. + IMGUI_API void CompactCache(); // Compact cached glyphs and texture. // As we are transitioning toward a new font system, we expect to obsolete those soon: 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. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2a0a300a7..01a02367b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2457,7 +2457,7 @@ void ImTextureData::DestroyPixels() // - Default texture data encoded in ASCII // - ImFontAtlas() // - ImFontAtlas::Clear() -// - ImFontAtlas::ClearCache() +// - ImFontAtlas::CompactCache() // - ImFontAtlas::ClearInputData() // - ImFontAtlas::ClearTexData() // - ImFontAtlas::ClearFonts() @@ -2499,7 +2499,7 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildAddFont() // - ImFontAtlasBuildSetupFontCreateEllipsisFromDot() // - ImFontAtlasBuildSetupFontSpecialGlyphs() -// - ImFontAtlasBuildDiscardUnusedBakes() +// - ImFontAtlasBuildDiscardBakes() // - ImFontAtlasBuildDiscardFontBakedGlyph() // - ImFontAtlasBuildDiscardFontBaked() // - ImFontAtlasBuildDiscardFont() @@ -2615,15 +2615,14 @@ void ImFontAtlas::Clear() bool backup_renderer_has_textures = RendererHasTextures; RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. ClearTexData(); + if (Builder != NULL) + ImFontAtlasBuildClearTexture(this); RendererHasTextures = backup_renderer_has_textures; } -void ImFontAtlas::ClearCache() +void ImFontAtlas::CompactCache() { - ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(this); - ImFontAtlasBuildDestroy(this); - ImFontAtlasBuildAddTexture(this, new_tex_size.x, new_tex_size.y); - ImFontAtlasBuildInit(this); + ImFontAtlasBuildCompactTexture(this); } void ImFontAtlas::ClearInputData() @@ -3682,13 +3681,14 @@ void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font) } } -void ImFontAtlasBuildDiscardUnusedBakes(ImFontAtlas* atlas, int gc_frames) +// use unused_frames==0 to discard everything. +void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames) { ImFontAtlasBuilder* builder = atlas->Builder; for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) { ImFontBaked* baked = &builder->BakedPool[baked_n]; - if (baked->LastUsedFrame + gc_frames < atlas->Builder->FrameCount && !baked->WantDestroy) + if (baked->LastUsedFrame + unused_frames <= atlas->Builder->FrameCount && !baked->WantDestroy) ImFontAtlasBuildDiscardFontBaked(atlas, baked->ContainerFont, baked); } } @@ -3909,7 +3909,7 @@ void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas) // Can some baked contents be ditched? //IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()\n"); ImFontAtlasBuilder* builder = atlas->Builder; - ImFontAtlasBuildDiscardUnusedBakes(atlas, 2); + ImFontAtlasBuildDiscardBakes(atlas, 2); // Currently using a heuristic for repack without growing. if (builder->RectsDiscardedSurface < builder->RectsPackedSurface * 0.20f) @@ -3952,12 +3952,21 @@ ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) return ImVec2i(new_tex_w, new_tex_h); } +// Clear all output. Invalidates all AddCustomRectXXX return values. +void ImFontAtlasBuildClearTexture(ImFontAtlas* atlas) +{ + ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); + ImFontAtlasBuildDestroy(atlas); + ImFontAtlasBuildAddTexture(atlas, new_tex_size.x, new_tex_size.y); + ImFontAtlasBuildInit(atlas); +} + // You should not need to call this manually! // If you think you do, let us know and we can advise about policies auto-compact. void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) { ImFontAtlasBuilder* builder = atlas->Builder; - ImFontAtlasBuildDiscardUnusedBakes(atlas, 1); + ImFontAtlasBuildDiscardBakes(atlas, 0); ImTextureData* old_tex = atlas->TexData; ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height); diff --git a/imgui_internal.h b/imgui_internal.h index 7e7a2c697..2f5ba1514 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3761,13 +3761,14 @@ IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* IMGUI_API ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h); IMGUI_API void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasBuildClearTexture(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas); IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); -IMGUI_API void ImFontAtlasBuildDiscardUnusedBakes(ImFontAtlas* atlas, int gc_frames); +IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); IMGUI_API void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); IMGUI_API void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); From dc1320df64d4b93e20c8f95b5ad709e6d46cc49e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Feb 2025 11:57:30 +0100 Subject: [PATCH 0955/2359] Fonts: ImFontFlags: ImFontFlags_NoLoadGlyphs + add ImFontFlags_LockBakedSizes --- imgui.h | 16 +++++++++++++--- imgui_draw.cpp | 21 ++++++++++++++++----- imgui_widgets.cpp | 2 +- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index 1b60ddc9c..fa345e7fe 100644 --- a/imgui.h +++ b/imgui.h @@ -230,7 +230,8 @@ typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A // - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance -typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build +typedef int ImFontFlags; // -> enum ImFontFlags_ // Flags: for ImFont +typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() typedef int ImGuiChildFlags; // -> enum ImGuiChildFlags_ // Flags: for BeginChild() @@ -3666,6 +3667,15 @@ struct ImFontBaked IMGUI_API void BuildGrowIndex(int new_size); }; +// Font flags +// (in future versions as we redesign font loading API, this will become more important and better documented. for now please consider this as internal/advanced use) +enum ImFontFlags_ +{ + ImFontFlags_None = 0, + ImFontFlags_LockBakedSizes = 1 << 0, // Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. + ImFontFlags_NoLoadGlyphs = 1 << 1, // Disable loading new glyphs. +}; + // Font runtime data and rendering // - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. // - Since 1.92.X a font may be rendered as any size! Therefore a font doesn't have one specific size. @@ -3673,9 +3683,10 @@ struct ImFontBaked // - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetFontBaked(g.FontSize). struct ImFont { - // [Internal] Members: Hot ~8-16 bytes + // [Internal] Members: Hot ~12-20 bytes ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. DO NOT USE. Use GetFontBaked(). ImFontAtlas* ContainerAtlas; // 4-8 // What we has been loaded into + ImFontFlags Flags; // 4 // Font flags // [Internal] Members: Cold ~24-52 bytes // Conceptually Sources[] is the list of font sources merged to create this font. @@ -3686,7 +3697,6 @@ struct ImFont ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. - bool LockDisableLoading; short LockSingleSrcConfigIdx; // Methods diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 01a02367b..6f6f2e4ac 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2647,7 +2647,7 @@ void ImFontAtlas::ClearInputData() font->Sources = NULL; font->SourcesCount = 0; } - font->LockDisableLoading = true; + font->Flags |= ImFontFlags_NoLoadGlyphs; } Sources.clear(); } @@ -3688,8 +3688,11 @@ void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames) for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) { ImFontBaked* baked = &builder->BakedPool[baked_n]; - if (baked->LastUsedFrame + unused_frames <= atlas->Builder->FrameCount && !baked->WantDestroy) - ImFontAtlasBuildDiscardFontBaked(atlas, baked->ContainerFont, baked); + if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount) + continue; + if (baked->WantDestroy || (baked->ContainerFont->Flags & ImFontFlags_LockBakedSizes)) + continue; + ImFontAtlasBuildDiscardFontBaked(atlas, baked->ContainerFont, baked); } } @@ -3816,7 +3819,8 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) //ImFontAtlasDebugWriteTexToDisk(old_tex, "Before Pack"); // Repack, lose discarded rectangle, copy pixels - // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic. + // FIXME-NEWATLAS: This is unstable because packing order is based on RectsIndex + // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic, and fix stability. // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. ImFontAtlasPackInit(atlas); ImVector old_rects; @@ -4172,7 +4176,7 @@ ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) ImFont* font = ContainerFont; ImFontBaked* baked = this; ImFontAtlas* atlas = font->ContainerAtlas; - if (font->LockDisableLoading || atlas->Locked) + if (atlas->Locked || (font->Flags & ImFontFlags_NoLoadGlyphs)) return NULL; //char utf8_buf[5]; @@ -5008,6 +5012,13 @@ ImFontBaked* ImFont::GetFontBaked(float size) return baked; } + // FIXME-BAKED: If loading is locked, find closest match + if (Flags & ImFontFlags_LockBakedSizes) + { + IM_ASSERT(LastBaked); + return LastBaked; + } + // FIXME-BAKED: If atlas is locked, find closest match if (atlas->Locked) IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2304aaf37..6a86c7956 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4321,7 +4321,7 @@ void ImGui::PushPasswordFont() ImFont* out_font = &g.InputTextPasswordFont; out_font->Scale = in_font->Scale; out_font->ContainerAtlas = in_font->ContainerAtlas; - out_font->LockDisableLoading = true; + out_font->Flags |= ImFontFlags_NoLoadGlyphs; ImFontBaked* out_baked = out_font->GetFontBaked(in_baked->Size); IM_ASSERT(out_baked->Glyphs.Size <= 1 && out_baked->IndexAdvanceX.Size == 0 && out_baked->IndexLookup.Size == 0); out_baked->Ascent = in_baked->Ascent; From 92993e68c8a401623385ca04724914ae0575afa7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Feb 2025 13:06:05 +0100 Subject: [PATCH 0956/2359] Fonts: Baked system, fix subsequent sources overriding shared font metrics. --- imgui_draw.cpp | 3 ++- misc/freetype/imgui_freetype.cpp | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6f6f2e4ac..48ecc6b1b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4313,7 +4313,8 @@ static void ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontBaked* { ImFontConfig* src = &font->Sources[src_n]; ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; - + if (src_n != 0) + continue; // FIXME-NEWFONTS: reevaluate how to use sizing metrics // FIXME-NEWFONTS: make use of line gap value float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index e71534c52..5de45a75f 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -479,8 +479,11 @@ void ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontBaked* baked) bd_baked_data->MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * bd_font_data->InvRasterizationDensity; // Output - baked->Ascent = bd_baked_data->Ascender; - baked->Descent = bd_baked_data->Descender; + if (src_n == 0) + { + baked->Ascent = bd_baked_data->Ascender; + baked->Descent = bd_baked_data->Descender; + } } } From 76b252f80a3322a12f39952658b82b17630c018f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 14:51:37 +0100 Subject: [PATCH 0957/2359] Fonts: Added ImFontAtlasBakedSetFontGlyphBitmap(). --- imgui_draw.cpp | 43 ++++++++++++++++++-------------- imgui_internal.h | 1 + misc/freetype/imgui_freetype.cpp | 34 +++++++++++-------------- 3 files changed, 39 insertions(+), 39 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 48ecc6b1b..2a9e9a45f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4370,9 +4370,10 @@ static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBa const bool is_visible = (x0 != x1 && y0 != y1); // Prepare glyph - ImFontGlyph glyph; - glyph.Codepoint = codepoint; - glyph.AdvanceX = advance * scale_for_layout; + ImFontGlyph glyph_in = {}; + ImFontGlyph* glyph = &glyph_in; + glyph->Codepoint = codepoint; + glyph->AdvanceX = advance * scale_for_layout; // Pack and retrieve position inside texture atlas // (generally based on stbtt_PackFontRangesRenderIntoRects) @@ -4420,25 +4421,18 @@ static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBa // Register glyph // r->x r->y are coordinates inside texture (in pixels) // glyph.X0, glyph.Y0 are drawing coordinates from base text position, and accounting for oversampling. - glyph.X0 = x0 * recip_h + font_off_x; - glyph.Y0 = y0 * recip_v + font_off_y; - glyph.X1 = (x0 + (int)r->w) * recip_h + font_off_x; - glyph.Y1 = (y0 + (int)r->h) * recip_v + font_off_y; - glyph.Visible = true; - glyph.PackId = pack_id; - ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph); - - // Copy to texture, post-process and queue update for backend - ImTextureData* tex = atlas->TexData; - IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); - ImFontAtlasTextureBlockConvert(bitmap_pixels, ImTextureFormat_Alpha8, w, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); - ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, &baked->Glyphs.back(), tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h }; - ImFontAtlasTextureBlockPostProcess(&pp_data); - ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); + glyph->X0 = x0 * recip_h + font_off_x; + glyph->Y0 = y0 * recip_v + font_off_y; + glyph->X1 = (x0 + (int)r->w) * recip_h + font_off_x; + glyph->Y1 = (y0 + (int)r->h) * recip_v + font_off_y; + glyph->Visible = true; + glyph->PackId = pack_id; + glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); + ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, bitmap_pixels, ImTextureFormat_Alpha8, w); } else { - ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph); + glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); } return true; @@ -4891,6 +4885,17 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked return &glyph; } +// Copy to texture, post-process and queue update for backend +void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImFontAtlasRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch) +{ + ImTextureData* tex = atlas->TexData; + IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); + ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h); + ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, glyph, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h }; + ImFontAtlasTextureBlockPostProcess(&pp_data); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); +} + void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst) { // FIXME-BAKED: Implement AddRemapChar() diff --git a/imgui_internal.h b/imgui_internal.h index 2f5ba1514..9bde7ed43 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3777,6 +3777,7 @@ IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* s IMGUI_API bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint); IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); +IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImFontAtlasRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size); IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 5de45a75f..7be3fc1e5 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -546,9 +546,10 @@ bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked const bool is_visible = (w != 0 && h != 0); // Prepare glyph - ImFontGlyph glyph = {}; - glyph.Codepoint = codepoint; - glyph.AdvanceX = (slot->advance.x / FT_SCALEFACTOR) * bd_font_data->InvRasterizationDensity; + ImFontGlyph glyph_in = {}; + ImFontGlyph* glyph = &glyph_in; + glyph->Codepoint = codepoint; + glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) * bd_font_data->InvRasterizationDensity; // Pack and retrieve position inside texture atlas if (is_visible) @@ -580,26 +581,19 @@ bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked // Register glyph float glyph_off_x = (float)face->glyph->bitmap_left; float glyph_off_y = (float)-face->glyph->bitmap_top; - glyph.X0 = glyph_off_x * recip_h + font_off_x; - glyph.Y0 = glyph_off_y * recip_v + font_off_y; - glyph.X1 = (glyph_off_x + w) * recip_h + font_off_x; - glyph.Y1 = (glyph_off_y + h) * recip_v + font_off_y; - glyph.Visible = true; - glyph.Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); - glyph.PackId = pack_id; - ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph); - - // Copy to texture, post-process and queue update for backend - ImTextureData* tex = atlas->TexData; - IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); - ImFontAtlasTextureBlockConvert(temp_buffer, ImTextureFormat_RGBA32, w * 4, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h); - ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, &baked->Glyphs.back(), tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), w, h }; - ImFontAtlasTextureBlockPostProcess(&pp_data); - ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); + glyph->X0 = glyph_off_x * recip_h + font_off_x; + glyph->Y0 = glyph_off_y * recip_v + font_off_y; + glyph->X1 = (glyph_off_x + w) * recip_h + font_off_x; + glyph->Y1 = (glyph_off_y + h) * recip_v + font_off_y; + glyph->Visible = true; + glyph->Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); + glyph->PackId = pack_id; + glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); + ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, (const unsigned char*)temp_buffer, ImTextureFormat_RGBA32, w * 4); } else { - ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph); + glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); } return true; } From d59f10d7f50402963c3e80521d2e4caf22278e60 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 15:58:16 +0100 Subject: [PATCH 0958/2359] Fonts: reinstated ImFontAtlasBuildSetupFontCreateEllipsisFromDot() compatible with baked system, lazily baked. --- imgui.h | 1 + imgui_draw.cpp | 72 ++++++++++++++++++++++++++++++++++---------------- 2 files changed, 50 insertions(+), 23 deletions(-) diff --git a/imgui.h b/imgui.h index fa345e7fe..46a0b8749 100644 --- a/imgui.h +++ b/imgui.h @@ -3697,6 +3697,7 @@ struct ImFont ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. short LockSingleSrcConfigIdx; // Methods diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2a9e9a45f..bc55b7273 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2497,7 +2497,8 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildUpdateBasicTexData() // - ImFontAtlasBuildUpdateLinesTexData() // - ImFontAtlasBuildAddFont() -// - ImFontAtlasBuildSetupFontCreateEllipsisFromDot() +// - ImFontAtlasBuildSetupFontBakedEllipsis() +// - ImFontAtlasBuildSetupFontBakedBlanks() // - ImFontAtlasBuildSetupFontSpecialGlyphs() // - ImFontAtlasBuildDiscardBakes() // - ImFontAtlasBuildDiscardFontBakedGlyph() @@ -3528,37 +3529,50 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) return true; } -// Rasterize our own ellipsis character from a dot. +// Create a compact, baked "..." if it doesn't exist, by using the ".". // This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. -// FIXME-NEWATLAS: This borrows too much from FontBackend_FontAddGlyph() and suggest that we should add further helpers. -// FIXME-BAKED: prebaked ellipsis -/*static void ImFontAtlasBuildSetupFontCreateEllipsisFromDot(ImFontAtlas* atlas, ImFont* font, const ImFontGlyph* dot_glyph) +// FIXME-NEWATLAS: This borrows too much from FontLoader's FontLoaderGlyph() handlers and suggest that we should add further helpers. +static ImFontGlyph* ImFontAtlasBuildSetupFontBakedEllipsis(ImFontAtlas* atlas, ImFontBaked* baked) { - ImFontAtlasRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_glyph->PackId); + ImFont* font = baked->ContainerFont; + IM_ASSERT(font->EllipsisChar != 0); + + const ImFontGlyph* dot_glyph = baked->FindGlyphNoFallback((ImWchar)'.'); + if (dot_glyph == NULL) + dot_glyph = baked->FindGlyphNoFallback((ImWchar)0xFF0E); + if (dot_glyph == NULL) + return NULL; + ImFontAtlasRectId dot_r_id = dot_glyph->PackId; // Deep copy to avoid invalidation of glyphs and rect pointers + ImFontAtlasRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id); const int dot_spacing = 1; const float dot_step = (dot_glyph->X1 - dot_glyph->X0) + dot_spacing; + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, (dot_r->w * 3 + dot_spacing * 2), dot_r->h); ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); - ImFontGlyph glyph; - glyph.Codepoint = (ImWchar)0x0085; // FIXME: Using arbitrary codepoint. - glyph.AdvanceX = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + dot_step * 3.0f - dot_spacing); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. - glyph.X0 = dot_glyph->X0; - glyph.Y0 = dot_glyph->Y0; - glyph.X1 = dot_glyph->X0 + dot_step * 3 - dot_spacing; - glyph.Y1 = dot_glyph->Y1; - glyph.Visible = true; - glyph.PackId = pack_id; - ImFontAtlasBuildAddFontGlyph(atlas, font, NULL, &glyph); - font->EllipsisChar = (ImWchar)glyph.Codepoint; + ImFontGlyph glyph_in = {}; + ImFontGlyph* glyph = &glyph_in; + glyph->Codepoint = font->EllipsisChar; + glyph->AdvanceX = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + dot_step * 3.0f - dot_spacing); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. + glyph->X0 = dot_glyph->X0; + glyph->Y0 = dot_glyph->Y0; + glyph->X1 = dot_glyph->X0 + dot_step * 3 - dot_spacing; + glyph->Y1 = dot_glyph->Y1; + glyph->Visible = true; + glyph->PackId = pack_id; + glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, glyph); + dot_glyph = NULL; // Invalidated // Copy to texture, post-process and queue update for backend // FIXME-NEWATLAS-V2: Dot glyph is already post-processed as this point, so this would damage it. + dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id); ImTextureData* tex = atlas->TexData; for (int n = 0; n < 3; n++) ImFontAtlasTextureBlockCopy(tex, dot_r->x, dot_r->y, tex, r->x + (dot_r->w + dot_spacing) * n, r->y, dot_r->w, dot_r->h); ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); -}*/ + + return glyph; +} static void ImFontAtlasBuildSetupFontBakedSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) { @@ -3582,6 +3596,14 @@ static void ImFontAtlasBuildSetupFontBakedSpecialGlyphs(ImFontAtlas* atlas, ImFo } baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(fallback_glyph); // Storing index avoid need to update pointer on growth and simplify inner loop code baked->FallbackAdvanceX = fallback_glyph->AdvanceX; +} + +static void ImFontAtlasBuildSetupFontBakedBlanks(ImFontAtlas* atlas, ImFontBaked* baked) +{ + // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews) + ImFontGlyph* space_glyph = baked->FindGlyphNoFallback((ImWchar)' '); + if (space_glyph != NULL) + space_glyph->Visible = false; // Setup Tab character. // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) @@ -3628,11 +3650,8 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im } if (font->EllipsisChar == 0) { - /*const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; - if (const ImFontGlyph* dot_glyph = LoadFirstExistingGlyph(font, dots_chars, IM_ARRAYSIZE(dots_chars))) - ImFontAtlasBuildSetupFontCreateEllipsisFromDot(atlas, font, dot_glyph); - else*/ - font->EllipsisChar = (ImWchar)' '; + font->EllipsisChar = 0x0085; + font->EllipsisAutoBake = true; } font->LockSingleSrcConfigIdx = -1; } @@ -4162,6 +4181,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon } } +// Important: don'return pointer valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { IM_ASSERT(id >= 0); @@ -4182,6 +4202,12 @@ ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); + // Special hook + // FIXME-NEWATLAS: it would be nicer if this used a more standardized way of hooking + if (codepoint == font->EllipsisChar && font->EllipsisAutoBake) + if (ImFontGlyph* glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked)) + return glyph; + // Load from single source or all sources? int srcs_count = (font->LockSingleSrcConfigIdx != -1) ? 1 : font->SourcesCount; ImFontConfig* srcs = (font->LockSingleSrcConfigIdx != -1) ? &font->Sources[font->LockSingleSrcConfigIdx] : font->Sources; From 1cfc0de31df9b76a01a4c19f958d86dd4633202e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Feb 2025 15:19:23 +0100 Subject: [PATCH 0959/2359] Fonts: Core allocates per-baked-per-src backend buffers, to allow having custom backend per font source. Backend BakedInit/Destroy/AddGlyph process a single source. --- imgui.h | 2 +- imgui_draw.cpp | 129 ++++++++++++++++++------------- imgui_internal.h | 12 ++- misc/freetype/imgui_freetype.cpp | 118 ++++++++++++---------------- 4 files changed, 133 insertions(+), 128 deletions(-) diff --git a/imgui.h b/imgui.h index 46a0b8749..e1d83d378 100644 --- a/imgui.h +++ b/imgui.h @@ -3654,7 +3654,7 @@ struct ImFontBaked int LastUsedFrame; // 4 // // Record of that time this was bounds ImGuiID BakedId; // 4 // ImFont* ContainerFont; // 4-8 // in // Parent font - void* FontBackendData; // 4-8 // // Font backend opaque storage (per baked font) + void* FontLoaderDatas; // 4-8 // // Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. // Functions IMGUI_API ImFontBaked(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bc55b7273..ee88d5f8d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3531,7 +3531,7 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) // Create a compact, baked "..." if it doesn't exist, by using the ".". // This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. -// FIXME-NEWATLAS: This borrows too much from FontLoader's FontLoaderGlyph() handlers and suggest that we should add further helpers. +// FIXME-NEWATLAS: This borrows too much from FontLoader's FontLoadGlyph() handlers and suggest that we should add further helpers. static ImFontGlyph* ImFontAtlasBuildSetupFontBakedEllipsis(ImFontAtlas* atlas, ImFontBaked* baked) { ImFont* font = baked->ContainerFont; @@ -3670,6 +3670,31 @@ void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImF baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; } +ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float size, ImGuiID baked_id) +{ + IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", size); + ImFontBaked* baked = atlas->Builder->BakedPool.push_back(ImFontBaked()); + baked->Size = size; + baked->BakedId = baked_id; + baked->ContainerFont = font; + baked->LastUsedFrame = atlas->Builder->FrameCount; + + // Initialize backend data + size_t loader_data_size = font->SourcesCount * atlas->FontLoader->FontBakedSrcLoaderDataSize; + baked->FontLoaderDatas = (loader_data_size > 0) ? IM_ALLOC(loader_data_size) : NULL; + char* backend_user_data_p = (char*)baked->FontLoaderDatas; + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = &font->Sources[src_n]; + if (atlas->FontLoader->FontBakedInit) + atlas->FontLoader->FontBakedInit(atlas, src, baked, backend_user_data_p); + backend_user_data_p += atlas->FontLoader->FontBakedSrcLoaderDataSize; + } + + ImFontAtlasBuildSetupFontBakedSpecialGlyphs(atlas, baked->ContainerFont, baked); + return baked; +} + void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) { ImFontAtlasBuilder* builder = atlas->Builder; @@ -3679,9 +3704,19 @@ void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBa if (glyph.PackId >= 0) ImFontAtlasPackDiscardRect(atlas, glyph.PackId); - if (atlas->FontLoader->FontBakedDestroy) - atlas->FontLoader->FontBakedDestroy(atlas, baked); - + char* backend_user_data_p = (char*)baked->FontLoaderDatas; + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = &font->Sources[src_n]; + if (atlas->FontLoader->FontBakedDestroy) + atlas->FontLoader->FontBakedDestroy(atlas, src, baked, backend_user_data_p); + backend_user_data_p += atlas->FontLoader->FontBakedSrcLoaderDataSize; + } + if (baked->FontLoaderDatas) + { + IM_FREE(baked->FontLoaderDatas); + baked->FontLoaderDatas = NULL; + } builder->BakedMap.SetVoidPtr(baked->BakedId, NULL); builder->BakedDiscardedCount++; baked->ClearOutputData(); @@ -4017,7 +4052,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) #else IM_ASSERT(0); // Invalid Build function #endif - return; // ImFontAtlasBuildSetupFontBackendIO() automatically call ImFontAtlasBuildInit() + return; // ImFontAtlasBuildSetupFontLoader() automatically call ImFontAtlasBuildInit() } // Create initial texture size @@ -4191,6 +4226,16 @@ ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id return &builder->Rects[index_entry->TargetIndex]; } +// Important! This assume by ImFontConfig::GlyphFilter is a SMALL ARRAY (e.g. <10 entries) +static bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint) +{ + if (const ImWchar* exclude_list = src->GlyphExcludeRanges) + for (; exclude_list[0] != 0; exclude_list += 2) + if (codepoint >= exclude_list[0] && codepoint <= exclude_list[1]) + return false; + return true; +} + ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) { ImFont* font = ContainerFont; @@ -4214,18 +4259,25 @@ ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) // Call backend const ImFontLoader* font_loader = atlas->FontLoader; - if (!font_loader->FontBakedAddGlyph(atlas, baked, srcs, srcs_count, codepoint)) + char* backend_user_data_p = (char*)baked->FontLoaderDatas; + for (int src_n = 0; src_n < srcs_count; src_n++) { - // Mark index as not found, so we don't attempt the search twice - baked->BuildGrowIndex(codepoint + 1); - baked->IndexAdvanceX[codepoint] = baked->FallbackAdvanceX; - baked->IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; - return NULL; + ImFontConfig* src = &srcs[src_n]; + if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) + if (font_loader->FontBakedAddGlyph(atlas, src, baked, backend_user_data_p, codepoint)) + { + // FIXME: Add hooks for e.g. #7962 + ImFontGlyph* glyph = &baked->Glyphs.back(); + return glyph; + } + backend_user_data_p += font_loader->FontBakedSrcLoaderDataSize; } - // FIXME: Add hooks for e.g. #7962 - ImFontGlyph* glyph = &baked->Glyphs.back(); - return glyph; + // Mark index as not found, so we don't attempt the search twice + baked->BuildGrowIndex(codepoint + 1); + baked->IndexAdvanceX[codepoint] = baked->FallbackAdvanceX; + baked->IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; + return NULL; } // The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b @@ -4330,17 +4382,13 @@ static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFon return glyph_index != 0; } -static void ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontBaked* baked) +static void ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*) { IM_UNUSED(atlas); - ImFont* font = baked->ContainerFont; - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + if (src->MergeMode == false) { - ImFontConfig* src = &font->Sources[src_n]; - ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; - if (src_n != 0) - continue; // FIXME-NEWFONTS: reevaluate how to use sizing metrics // FIXME-NEWFONTS: make use of line gap value float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; @@ -4351,33 +4399,12 @@ static void ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontBaked* } } -// Important! This assume by ImFontConfig::GlyphFilter is a SMALL ARRAY (e.g. <10 entries) -bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint) -{ - if (const ImWchar* exclude_list = src->GlyphExcludeRanges) - for (; exclude_list[0] != 0; exclude_list += 2) - if (codepoint >= exclude_list[0] && codepoint <= exclude_list[1]) - return false; - return true; -} - -static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) +static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint) { // Search for first font which has the glyph - ImGui_ImplStbTrueType_FontSrcData* bd_font_data = NULL; - ImFontConfig* src = NULL; - int glyph_index = 0; - for (int src_n = 0; src_n < srcs_count; src_n++) - { - src = &srcs[src_n]; - if (src->GlyphExcludeRanges && !ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) - continue; - bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; - IM_ASSERT(bd_font_data); - glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); - if (glyph_index != 0) - break; - } + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_ASSERT(bd_font_data); + int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); if (glyph_index == 0) return false; // Not found @@ -5056,17 +5083,9 @@ ImFontBaked* ImFont::GetFontBaked(float size) IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! // Create new - IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", size); - baked = builder->BakedPool.push_back(ImFontBaked()); - baked->Size = size; - baked->BakedId = baked_id; - baked->ContainerFont = this; - baked->LastUsedFrame = ContainerAtlas->Builder->FrameCount; + baked = ImFontAtlasBuildAddFontBaked(atlas, this, size, baked_id); LastBaked = baked; *p_baked_in_map = baked; // To avoid 'builder->BakedMap.SetVoidPtr(baked_id, baked);' while we can. - if (atlas->FontLoader->FontBakedInit) - atlas->FontLoader->FontBakedInit(atlas, baked); - ImFontAtlasBuildSetupFontBakedSpecialGlyphs(atlas, baked->ContainerFont, baked); return baked; } diff --git a/imgui_internal.h b/imgui_internal.h index 9bde7ed43..caca87463 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3668,9 +3668,13 @@ struct ImFontLoader bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); - void (*FontBakedInit)(ImFontAtlas* atlas, ImFontBaked* baked); - void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontBaked* baked); - bool (*FontBakedAddGlyph)(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* srcs, int srcs_count, ImWchar codepoint); + void (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + bool (*FontBakedAddGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint); + + // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. + // FIXME: At this point the two other types of buffers may be managed by core to be consistent? + size_t FontBakedSrcLoaderDataSize; ImFontLoader() { memset(this, 0, sizeof(*this)); } }; @@ -3770,11 +3774,11 @@ IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontCo IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); IMGUI_API void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font); +IMGUI_API ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); IMGUI_API void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); -IMGUI_API bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint); IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImFontAtlasRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 7be3fc1e5..17cd2caaa 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -143,7 +143,7 @@ namespace // | | // |------------- advanceX ----------->| - // Stored in ImFontAtlas::FontLoaderData + // Stored in ImFontAtlas::FontLoaderData. ALLOCATED BY US. struct ImGui_ImplFreeType_Data { FT_Library Library; @@ -151,7 +151,7 @@ namespace ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } }; - // Stored in ImFontBaked::FontBackendData: pointer to SourcesCount instances of this. + // Stored in ImFontBaked::FontLoaderDatas: pointer to SourcesCount instances of this. ALLOCATED BY CORE. struct ImGui_ImplFreeType_FontSrcBakedData { FT_Size FtSize; // This represent a FT_Face with a given size. @@ -166,7 +166,7 @@ namespace ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } }; - // Stored in ImFontConfig::FontLoaderData + // Stored in ImFontConfig::FontLoaderData. ALLOCATED BY US. struct ImGui_ImplFreeType_FontSrcData { bool InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. @@ -437,91 +437,72 @@ void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) src->FontLoaderData = NULL; } -void ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontBaked* baked) +void ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { IM_UNUSED(atlas); - ImFont* font = baked->ContainerFont; const float size = baked->Size; - IM_ASSERT(baked->FontBackendData == NULL); - ImGui_ImplFreeType_FontSrcBakedData* bd_baked_datas = (ImGui_ImplFreeType_FontSrcBakedData*)IM_ALLOC(sizeof(ImGui_ImplFreeType_FontSrcBakedData) * font->SourcesCount); - baked->FontBackendData = bd_baked_datas; + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + bd_font_data->BakedLastActivated = baked; - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + // We use one FT_Size per (source + baked) combination. + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; + IM_ASSERT(bd_baked_data != NULL); + IM_PLACEMENT_NEW(bd_baked_data) ImGui_ImplFreeType_FontSrcBakedData(); + + FT_New_Size(bd_font_data->FtFace, &bd_baked_data->FtSize); + FT_Activate_Size(bd_baked_data->FtSize); + + // Vuhdo 2017: "I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height' + // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me. + // FT_Set_Pixel_Sizes() doesn't seem to get us the same result." + // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL) + FT_Size_RequestRec req; + req.type = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; + req.width = 0; + req.height = (uint32_t)(size * 64 * bd_font_data->RasterizationDensity); + req.horiResolution = 0; + req.vertResolution = 0; + FT_Request_Size(bd_font_data->FtFace, &req); + + // Read metrics + FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; + bd_baked_data->Ascender = (float)FT_CEIL(metrics.ascender) * bd_font_data->InvRasterizationDensity; + bd_baked_data->Descender = (float)FT_CEIL(metrics.descender) * bd_font_data->InvRasterizationDensity; + bd_baked_data->LineSpacing = (float)FT_CEIL(metrics.height) * bd_font_data->InvRasterizationDensity; + bd_baked_data->LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * bd_font_data->InvRasterizationDensity; + bd_baked_data->MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * bd_font_data->InvRasterizationDensity; + + // Output + if (src->MergeMode == false) { - ImFontConfig* src = &font->Sources[src_n]; - ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontBackendData; - bd_font_data->BakedLastActivated = baked; - - // We need one FT_Size per source, so create one ImGui_ImplFreeType_FontBakedData for each source. - ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = &bd_baked_datas[src_n]; - FT_New_Size(bd_font_data->FtFace, &bd_baked_data->FtSize); - FT_Activate_Size(bd_baked_data->FtSize); - - // Vuhdo 2017: "I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height' - // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me. - // FT_Set_Pixel_Sizes() doesn't seem to get us the same result." - // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL) - FT_Size_RequestRec req; - req.type = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; - req.width = 0; - req.height = (uint32_t)(size * 64 * bd_font_data->RasterizationDensity); - req.horiResolution = 0; - req.vertResolution = 0; - FT_Request_Size(bd_font_data->FtFace, &req); - - // Read metrics - FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; - bd_baked_data->Ascender = (float)FT_CEIL(metrics.ascender) * bd_font_data->InvRasterizationDensity; - bd_baked_data->Descender = (float)FT_CEIL(metrics.descender) * bd_font_data->InvRasterizationDensity; - bd_baked_data->LineSpacing = (float)FT_CEIL(metrics.height) * bd_font_data->InvRasterizationDensity; - bd_baked_data->LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * bd_font_data->InvRasterizationDensity; - bd_baked_data->MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * bd_font_data->InvRasterizationDensity; - - // Output - if (src_n == 0) - { - baked->Ascent = bd_baked_data->Ascender; - baked->Descent = bd_baked_data->Descender; - } + baked->Ascent = bd_baked_data->Ascender; + baked->Descent = bd_baked_data->Descender; } } -void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontBaked* baked) +void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { IM_UNUSED(atlas); - ImFont* font = baked->ContainerFont; - ImGui_ImplFreeType_FontSrcBakedData* bd_baked_datas = (ImGui_ImplFreeType_FontSrcBakedData*)baked->FontBackendData; - for (int src_n = 0; src_n < font->SourcesCount; src_n++) - FT_Done_Size(bd_baked_datas[src_n].FtSize); - IM_FREE(bd_baked_datas); - baked->FontBackendData = NULL; + IM_UNUSED(baked); + IM_UNUSED(src); + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; + IM_ASSERT(bd_baked_data != NULL); + FT_Done_Size(bd_baked_data->FtSize); + bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() } -bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* srcs, int srcs_count, ImWchar codepoint) +bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint) { - // Search for first font which has the glyph - ImGui_ImplFreeType_FontSrcData* bd_font_data = NULL; - ImFontConfig* src = NULL; - uint32_t glyph_index = 0; - for (int src_n = 0; src_n < srcs_count; src_n++) - { - src = &srcs[src_n]; - if (src->GlyphExcludeRanges && !ImFontAtlasBuildFilterCodepointForSource(src, codepoint)) - continue; - bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; - glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); - if (glyph_index != 0) - break; - } + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); if (glyph_index == 0) return false; // Not found if (bd_font_data->BakedLastActivated != baked) { // Activate current size - int src_n = (int)(font_cfg - srcs); - ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = &((ImGui_ImplFreeType_FontSrcBakedData*)baked->FontBackendData)[src_n]; + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; FT_Activate_Size(bd_baked_data->FtSize); bd_font_data->BakedLastActivated = baked; } @@ -618,6 +599,7 @@ const ImFontLoader* ImGuiFreeType::GetFontLoader() loader.FontBakedInit = ImGui_ImplFreeType_FontBakedInit; loader.FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy; loader.FontBakedAddGlyph = ImGui_ImplFreeType_FontBakedAddGlyph; + loader.FontBakedSrcLoaderDataSize = sizeof(ImGui_ImplFreeType_FontSrcBakedData); return &loader; } From c06a7585a3bfea23f69d791e1f011b3f2c3440fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Feb 2025 19:31:13 +0100 Subject: [PATCH 0960/2359] Fonts: A font source can specify its own loader/backend. --- imgui.h | 2 ++ imgui_draw.cpp | 82 +++++++++++++++++++++++++++++++++----------------- 2 files changed, 57 insertions(+), 27 deletions(-) diff --git a/imgui.h b/imgui.h index e1d83d378..28e84e2a5 100644 --- a/imgui.h +++ b/imgui.h @@ -3444,7 +3444,9 @@ struct ImFontConfig // [Internal] char Name[40]; // Name (strictly to ease debugging) + ImFontFlags Flags; // Font flags (don't use just yet) ImFont* DstFont; // Target font (as we merging fonts, multiple ImFontConfig may target the same font) + const ImFontLoader* FontLoader; // Custom font backend for this source (other use one stored in ImFontAtlas) void* FontLoaderData; // Font loader opaque storage (per font config) IMGUI_API ImFontConfig(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ee88d5f8d..3106f2fe7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2607,14 +2607,18 @@ ImFontAtlas::ImFontAtlas() ImFontAtlas::~ImFontAtlas() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - Clear(); + RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. + ClearFonts(); + ClearTexData(); + TexList.clear_delete(); + TexData = NULL; } void ImFontAtlas::Clear() { - ClearFonts(); bool backup_renderer_has_textures = RendererHasTextures; RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. + ClearFonts(); ClearTexData(); if (Builder != NULL) ImFontAtlasBuildClearTexture(this); @@ -2631,8 +2635,9 @@ void ImFontAtlas::ClearInputData() IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); for (ImFontConfig& font_cfg : Sources) { - if (FontLoader && FontLoader->FontSrcDestroy != NULL) - FontLoader->FontSrcDestroy(this, &font_cfg); + const ImFontLoader* loader = font_cfg.FontLoader ? font_cfg.FontLoader : FontLoader; + if (loader && loader->FontSrcDestroy != NULL) + loader->FontSrcDestroy(this, &font_cfg); if (font_cfg.FontData && font_cfg.FontDataOwnedByAtlas) { IM_FREE(font_cfg.FontData); @@ -2957,7 +2962,7 @@ bool ImFontAtlas::Build() ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); + IM_ASSERT((font_cfg->FontData != NULL && font_cfg->FontDataSize > 0) || (font_cfg->FontLoader != NULL)); IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); IM_ASSERT(font_cfg->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); @@ -2971,6 +2976,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) { font = IM_NEW(ImFont)(); font->FontId = FontNextUniqueID++; + font->Flags = font_cfg->Flags; Fonts.push_back(font); } else @@ -2998,6 +3004,9 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) IM_ASSERT((size & 1) == 0 && "GlyphExcludeRanges[] size must be multiple of two!"); IM_ASSERT((size <= 64) && "GlyphExcludeRanges[] size must be small!"); } + if (font_cfg->FontLoader != NULL) + IM_ASSERT(font_cfg->FontLoader->FontBakedAddGlyph != NULL); + IM_ASSERT(font_cfg->FontLoaderData == NULL); // Round font size // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. @@ -3165,8 +3174,9 @@ void ImFontAtlas::RemoveFont(ImFont* font) for (int src_n = 0; src_n < font->SourcesCount; src_n++) { ImFontConfig* src = (ImFontConfig*)(void*)&font->Sources[src_n]; - if (FontLoader && FontLoader->FontSrcDestroy != NULL) - FontLoader->FontSrcDestroy(this, src); + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : FontLoader; + if (loader && loader->FontSrcDestroy != NULL) + loader->FontSrcDestroy(this, src); if (src->FontData != NULL && src->FontDataOwnedByAtlas) IM_FREE(src->FontData); } @@ -3317,6 +3327,8 @@ void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* ou *out_oversample_v = (src->OversampleV != 0) ? src->OversampleV : 1; } +// Setup main font loader for the atlas +// Every font source (ImFontConfig) will use this unless ImFontConfig::FontLoader specify a custom loader. void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader) { if (atlas->FontLoader == font_loader) @@ -3521,9 +3533,10 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) IM_ASSERT(font->Sources == src); } - const ImFontLoader* font_loader = atlas->FontLoader; - if (!font_loader->FontSrcInit(atlas, src)) - return false; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontSrcInit != NULL) + if (!loader->FontSrcInit(atlas, src)) + return false; ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); return true; @@ -3680,15 +3693,22 @@ ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, floa baked->LastUsedFrame = atlas->Builder->FrameCount; // Initialize backend data - size_t loader_data_size = font->SourcesCount * atlas->FontLoader->FontBakedSrcLoaderDataSize; + size_t loader_data_size = 0; + for (int src_n = 0; src_n < font->SourcesCount; src_n++) // Cannot easily be cached as we allow changing backend + { + ImFontConfig* src = &font->Sources[src_n]; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + loader_data_size += loader->FontBakedSrcLoaderDataSize; + } baked->FontLoaderDatas = (loader_data_size > 0) ? IM_ALLOC(loader_data_size) : NULL; - char* backend_user_data_p = (char*)baked->FontLoaderDatas; + char* loader_data_p = (char*)baked->FontLoaderDatas; for (int src_n = 0; src_n < font->SourcesCount; src_n++) { ImFontConfig* src = &font->Sources[src_n]; - if (atlas->FontLoader->FontBakedInit) - atlas->FontLoader->FontBakedInit(atlas, src, baked, backend_user_data_p); - backend_user_data_p += atlas->FontLoader->FontBakedSrcLoaderDataSize; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontBakedInit) + loader->FontBakedInit(atlas, src, baked, loader_data_p); + loader_data_p += loader->FontBakedSrcLoaderDataSize; } ImFontAtlasBuildSetupFontBakedSpecialGlyphs(atlas, baked->ContainerFont, baked); @@ -3704,13 +3724,14 @@ void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBa if (glyph.PackId >= 0) ImFontAtlasPackDiscardRect(atlas, glyph.PackId); - char* backend_user_data_p = (char*)baked->FontLoaderDatas; + char* loader_data_p = (char*)baked->FontLoaderDatas; for (int src_n = 0; src_n < font->SourcesCount; src_n++) { ImFontConfig* src = &font->Sources[src_n]; - if (atlas->FontLoader->FontBakedDestroy) - atlas->FontLoader->FontBakedDestroy(atlas, src, baked, backend_user_data_p); - backend_user_data_p += atlas->FontLoader->FontBakedSrcLoaderDataSize; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontBakedDestroy) + loader->FontBakedDestroy(atlas, src, baked, loader_data_p); + loader_data_p += loader->FontBakedSrcLoaderDataSize; } if (baked->FontLoaderDatas) { @@ -4094,9 +4115,12 @@ void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) { for (ImFont* font : atlas->Fonts) font->ClearOutputData(); - if (atlas->FontLoader && atlas->FontLoader->FontSrcDestroy != NULL) - for (ImFontConfig& font_cfg : atlas->Sources) - atlas->FontLoader->FontSrcDestroy(atlas, &font_cfg); + for (ImFontConfig& font_cfg : atlas->Sources) + { + const ImFontLoader* loader = font_cfg.FontLoader ? font_cfg.FontLoader : atlas->FontLoader; + if (loader && loader->FontSrcDestroy != NULL) + loader->FontSrcDestroy(atlas, &font_cfg); + } IM_DELETE(atlas->Builder); atlas->Builder = NULL; @@ -4258,19 +4282,19 @@ ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) ImFontConfig* srcs = (font->LockSingleSrcConfigIdx != -1) ? &font->Sources[font->LockSingleSrcConfigIdx] : font->Sources; // Call backend - const ImFontLoader* font_loader = atlas->FontLoader; - char* backend_user_data_p = (char*)baked->FontLoaderDatas; + char* loader_user_data_p = (char*)baked->FontLoaderDatas; for (int src_n = 0; src_n < srcs_count; src_n++) { ImFontConfig* src = &srcs[src_n]; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) - if (font_loader->FontBakedAddGlyph(atlas, src, baked, backend_user_data_p, codepoint)) + if (loader->FontBakedAddGlyph(atlas, src, baked, loader_user_data_p, codepoint)) { // FIXME: Add hooks for e.g. #7962 ImFontGlyph* glyph = &baked->Glyphs.back(); return glyph; } - backend_user_data_p += font_loader->FontBakedSrcLoaderDataSize; + loader_user_data_p += loader->FontBakedSrcLoaderDataSize; } // Mark index as not found, so we don't attempt the search twice @@ -5017,8 +5041,12 @@ bool ImFont::IsGlyphInFont(ImWchar c) { ImFontAtlas* atlas = ContainerAtlas; for (int src_n = 0; src_n < SourcesCount; src_n++) - if (atlas->FontLoader->FontSrcContainsGlyph(atlas, &Sources[src_n], c)) + { + ImFontConfig* src = &Sources[src_n]; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontSrcContainsGlyph != NULL && loader->FontSrcContainsGlyph(atlas, src, c)) return true; + } return false; } From 18c8a93cca8133bf74039b23c2ac30bb185a5cf0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Feb 2025 18:48:01 +0100 Subject: [PATCH 0961/2359] Fonts: Rework ImFontLoader signatures. InitBaked may return false to signify this size is not supported. --- imgui_draw.cpp | 23 ++++++++++------------- imgui_internal.h | 4 ++-- misc/freetype/imgui_freetype.cpp | 22 ++++++++++------------ 3 files changed, 22 insertions(+), 27 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3106f2fe7..0a6726366 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3005,7 +3005,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) IM_ASSERT((size <= 64) && "GlyphExcludeRanges[] size must be small!"); } if (font_cfg->FontLoader != NULL) - IM_ASSERT(font_cfg->FontLoader->FontBakedAddGlyph != NULL); + IM_ASSERT(font_cfg->FontLoader->FontBakedLoadGlyph != NULL); IM_ASSERT(font_cfg->FontLoaderData == NULL); // Round font size @@ -4288,12 +4288,8 @@ ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) ImFontConfig* src = &srcs[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) - if (loader->FontBakedAddGlyph(atlas, src, baked, loader_user_data_p, codepoint)) - { - // FIXME: Add hooks for e.g. #7962 - ImFontGlyph* glyph = &baked->Glyphs.back(); - return glyph; - } + if (ImFontGlyph* glyph = loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint)) + return glyph; // FIXME: Add hooks for e.g. #7962 loader_user_data_p += loader->FontBakedSrcLoaderDataSize; } @@ -4406,7 +4402,7 @@ static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFon return glyph_index != 0; } -static void ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*) +static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*) { IM_UNUSED(atlas); @@ -4421,16 +4417,17 @@ static void ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); baked->Descent = ImFloor(unscaled_descent * scale_for_layout); } + return true; } -static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint) +static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint) { // Search for first font which has the glyph ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; IM_ASSERT(bd_font_data); int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); if (glyph_index == 0) - return false; // Not found + return NULL; // Fonts unit to pixels int oversample_h, oversample_v; @@ -4463,7 +4460,7 @@ static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontCo { // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); - return false; + return NULL; } ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); @@ -4512,7 +4509,7 @@ static bool ImGui_ImplStbTrueType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontCo glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); } - return true; + return glyph; } const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() @@ -4524,7 +4521,7 @@ const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph; loader.FontBakedInit = ImGui_ImplStbTrueType_FontBakedInit; loader.FontBakedDestroy = NULL; - loader.FontBakedAddGlyph = ImGui_ImplStbTrueType_FontBakedAddGlyph; + loader.FontBakedLoadGlyph = ImGui_ImplStbTrueType_FontBakedLoadGlyph; return &loader; } diff --git a/imgui_internal.h b/imgui_internal.h index caca87463..40975abd7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3668,9 +3668,9 @@ struct ImFontLoader bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); - void (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); - bool (*FontBakedAddGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint); + ImFontGlyph* (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint); // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. // FIXME: At this point the two other types of buffers may be managed by core to be consistent? diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 17cd2caaa..39919c8e4 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -437,7 +437,7 @@ void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) src->FontLoaderData = NULL; } -void ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { IM_UNUSED(atlas); const float size = baked->Size; @@ -479,6 +479,7 @@ void ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF baked->Ascent = bd_baked_data->Ascender; baked->Descent = bd_baked_data->Descender; } + return true; } void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) @@ -492,12 +493,12 @@ void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() } -bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint) +ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint) { ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); if (glyph_index == 0) - return false; // Not found + return NULL; if (bd_font_data->BakedLastActivated != baked) { @@ -509,18 +510,15 @@ bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontConfig* src, const FT_Glyph_Metrics* metrics = bd_font_data->LoadGlyph(codepoint); if (metrics == NULL) - return false; + return NULL; // Render glyph into a bitmap (currently held by FreeType) FT_Face face = bd_font_data->FtFace; FT_GlyphSlot slot = face->glyph; FT_Error error = FT_Render_Glyph(slot, bd_font_data->RenderMode); - if (error != 0) - return false; - const FT_Bitmap* ft_bitmap = &slot->bitmap; - if (ft_bitmap == nullptr) - return false; + if (error != 0 || ft_bitmap == nullptr) + return NULL; const int w = (int)ft_bitmap->width; const int h = (int)ft_bitmap->rows; @@ -540,7 +538,7 @@ bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontConfig* src, { // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); - return false; + return NULL; } ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); @@ -576,7 +574,7 @@ bool ImGui_ImplFreeType_FontBakedAddGlyph(ImFontAtlas* atlas, ImFontConfig* src, { glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); } - return true; + return glyph; } bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) @@ -598,7 +596,7 @@ const ImFontLoader* ImGuiFreeType::GetFontLoader() loader.FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph; loader.FontBakedInit = ImGui_ImplFreeType_FontBakedInit; loader.FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy; - loader.FontBakedAddGlyph = ImGui_ImplFreeType_FontBakedAddGlyph; + loader.FontBakedLoadGlyph = ImGui_ImplFreeType_FontBakedLoadGlyph; loader.FontBakedSrcLoaderDataSize = sizeof(ImGui_ImplFreeType_FontSrcBakedData); return &loader; } From 78a17038c2437aeedb29e4654588713896dd4abc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 15:09:46 +0100 Subject: [PATCH 0962/2359] imgui_freetype: no need to store metrics locally. --- misc/freetype/imgui_freetype.cpp | 28 +++++++++------------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 39919c8e4..fd6920e0c 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -155,14 +155,6 @@ namespace struct ImGui_ImplFreeType_FontSrcBakedData { FT_Size FtSize; // This represent a FT_Face with a given size. - - // Metrics - float Ascender; // The pixel extents above the baseline in pixels (typically positive). - float Descender; // The extents below the baseline in pixels (typically negative). - float LineSpacing; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. - float LineGap; // The spacing in pixels between one row's descent and the next row's ascent. - float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font. - ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } }; @@ -465,19 +457,17 @@ bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF req.vertResolution = 0; FT_Request_Size(bd_font_data->FtFace, &req); - // Read metrics - FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; - bd_baked_data->Ascender = (float)FT_CEIL(metrics.ascender) * bd_font_data->InvRasterizationDensity; - bd_baked_data->Descender = (float)FT_CEIL(metrics.descender) * bd_font_data->InvRasterizationDensity; - bd_baked_data->LineSpacing = (float)FT_CEIL(metrics.height) * bd_font_data->InvRasterizationDensity; - bd_baked_data->LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * bd_font_data->InvRasterizationDensity; - bd_baked_data->MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * bd_font_data->InvRasterizationDensity; - // Output if (src->MergeMode == false) { - baked->Ascent = bd_baked_data->Ascender; - baked->Descent = bd_baked_data->Descender; + // Read metrics + FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; + const float scale = bd_font_data->InvRasterizationDensity; + baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). + baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). + //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. + //LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * scale; // The spacing in pixels between one row's descent and the next row's ascent. + //MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * scale; // This field gives the maximum horizontal cursor advance for all glyphs in the font. } return true; } @@ -500,7 +490,7 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon if (glyph_index == 0) return NULL; - if (bd_font_data->BakedLastActivated != baked) + if (bd_font_data->BakedLastActivated != baked) // <-- could use id { // Activate current size ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; From d8a612f73b34fb10a763b50cf1bc48a81447b1d7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 22:32:09 +0100 Subject: [PATCH 0963/2359] Fonts: Fallback glyph is now lazily loaded on demand (yay!). Moving ImFontBaked:: functions outside of class. --- imgui.h | 5 ++-- imgui_draw.cpp | 79 +++++++++++++++++++++++++++++--------------------- 2 files changed, 48 insertions(+), 36 deletions(-) diff --git a/imgui.h b/imgui.h index 28e84e2a5..811125c97 100644 --- a/imgui.h +++ b/imgui.h @@ -3652,7 +3652,8 @@ struct ImFontBaked // [Internal] Members: Cold float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) unsigned int MetricsTotalSurface:26;// 3 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) - unsigned int WantDestroy:1; // 1 // // Queued for destroy + unsigned int WantDestroy:1; // 0 // // Queued for destroy + unsigned int LockLoadingFallback:1; // 0 // // int LastUsedFrame; // 4 // // Record of that time this was bounds ImGuiID BakedId; // 4 // ImFont* ContainerFont; // 4-8 // in // Parent font @@ -3665,8 +3666,6 @@ struct ImFontBaked IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); // Return NULL if glyph doesn't exist IMGUI_API float GetCharAdvance(ImWchar c); IMGUI_API bool IsGlyphLoaded(ImWchar c); - IMGUI_API ImFontGlyph* BuildLoadGlyph(ImWchar c); - IMGUI_API void BuildGrowIndex(int new_size); }; // Font flags diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0a6726366..54a7acab2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2499,6 +2499,7 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildAddFont() // - ImFontAtlasBuildSetupFontBakedEllipsis() // - ImFontAtlasBuildSetupFontBakedBlanks() +// - ImFontAtlasBuildSetupFontBakedFallback() // - ImFontAtlasBuildSetupFontSpecialGlyphs() // - ImFontAtlasBuildDiscardBakes() // - ImFontAtlasBuildDiscardFontBakedGlyph() @@ -2527,7 +2528,8 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasPackAddRect() // - ImFontAtlasPackGetRect() //----------------------------------------------------------------------------- -// - ImFont::BuildLoadGlyph() +// - ImFontBaked_BuildGrowIndex() +// - ImFontBaked_BuildLoadGlyph() // - ImFontAtlasDebugLogTextureRequests() //----------------------------------------------------------------------------- // - ImFontAtlasGetFontLoaderForStbTruetype() @@ -3242,7 +3244,7 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); if (baked->IsGlyphLoaded(codepoint)) - ImFontAtlasBuildDiscardFontBakedGlyph(this, font, baked, (ImFontGlyph*)(void*)baked->FindGlyph(codepoint)); + ImFontAtlasBuildDiscardFontBakedGlyph(this, font, baked, baked->FindGlyph(codepoint)); ImFontGlyph glyph; glyph.Codepoint = codepoint; @@ -3367,7 +3369,7 @@ void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas) IM_ASSERT(ranges != NULL); for (; ranges[0]; ranges += 2) for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 - baked->FindGlyphNoFallback((ImWchar)c); + baked->FindGlyph((ImWchar)c); } } @@ -3587,25 +3589,23 @@ static ImFontGlyph* ImFontAtlasBuildSetupFontBakedEllipsis(ImFontAtlas* atlas, I return glyph; } -static void ImFontAtlasBuildSetupFontBakedSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) +// Load fallback in order to obtain its index +// (this is called from in hot-path so we avoid extraneous parameters to minimize impact on code size) +static void ImFontAtlasBuildSetupFontBakedFallback(ImFontBaked* baked) { - // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews) - ImFontGlyph* space_glyph = (ImFontGlyph*)(void*)baked->FindGlyphNoFallback((ImWchar)' '); - if (space_glyph != NULL) - space_glyph->Visible = false; - - // Load fallback in order to obtain its index - // FIXME-NEWATLAS: could we use a scheme where this is lazily loaded? IM_ASSERT(baked->FallbackGlyphIndex == -1); + IM_ASSERT(baked->FallbackAdvanceX == 0.0f); + ImFont* font = baked->ContainerFont; ImFontGlyph* fallback_glyph = NULL; if (font->FallbackChar != 0) fallback_glyph = baked->FindGlyphNoFallback(font->FallbackChar); if (fallback_glyph == NULL) { + ImFontGlyph* space_glyph = baked->FindGlyphNoFallback((ImWchar)' '); ImFontGlyph glyph; glyph.Codepoint = 0; glyph.AdvanceX = space_glyph ? space_glyph->AdvanceX : IM_ROUND(baked->Size * 0.40f); - fallback_glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, &glyph); + fallback_glyph = ImFontAtlasBakedAddFontGlyph(font->ContainerAtlas, baked, NULL, &glyph); } baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(fallback_glyph); // Storing index avoid need to update pointer on growth and simplify inner loop code baked->FallbackAdvanceX = fallback_glyph->AdvanceX; @@ -3711,7 +3711,7 @@ ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, floa loader_data_p += loader->FontBakedSrcLoaderDataSize; } - ImFontAtlasBuildSetupFontBakedSpecialGlyphs(atlas, baked->ContainerFont, baked); + ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked); return baked; } @@ -4260,13 +4260,26 @@ static bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar return true; } -ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) +static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size) { - ImFont* font = ContainerFont; - ImFontBaked* baked = this; + IM_ASSERT(baked->IndexAdvanceX.Size == baked->IndexLookup.Size); + if (new_size <= baked->IndexLookup.Size) + return; + baked->IndexAdvanceX.resize(new_size, -1.0f); + baked->IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); +} + +static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint) +{ + ImFont* font = baked->ContainerFont; ImFontAtlas* atlas = font->ContainerAtlas; if (atlas->Locked || (font->Flags & ImFontFlags_NoLoadGlyphs)) + { + // Lazily load fallback glyph + if (baked->FallbackGlyphIndex == -1 && baked->LockLoadingFallback == 0) + ImFontAtlasBuildSetupFontBakedFallback(baked); return NULL; + } //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); @@ -4293,8 +4306,14 @@ ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) loader_user_data_p += loader->FontBakedSrcLoaderDataSize; } + // Lazily load fallback glyph + if (baked->LockLoadingFallback) + return NULL; + if (baked->FallbackGlyphIndex == -1) + ImFontAtlasBuildSetupFontBakedFallback(baked); + // Mark index as not found, so we don't attempt the search twice - baked->BuildGrowIndex(codepoint + 1); + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); baked->IndexAdvanceX[codepoint] = baked->FallbackAdvanceX; baked->IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; return NULL; @@ -4302,10 +4321,10 @@ ImFontGlyph* ImFontBaked::BuildLoadGlyph(ImWchar codepoint) // The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b IM_MSVC_RUNTIME_CHECKS_OFF -static float BuildLoadGlyphGetAdvanceOrFallback(ImFontBaked* font, unsigned int codepoint) +static float BuildLoadGlyphGetAdvanceOrFallback(ImFontBaked* baked, unsigned int codepoint) { - ImFontGlyph* glyph = font->BuildLoadGlyph((ImWchar)codepoint); - return glyph ? glyph->AdvanceX : font->FallbackAdvanceX; + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint); + return glyph ? glyph->AdvanceX : baked->FallbackAdvanceX; } IM_MSVC_RUNTIME_CHECKS_RESTORE @@ -4861,15 +4880,6 @@ void ImFontBaked::ClearOutputData() MetricsTotalSurface = 0; } -void ImFontBaked::BuildGrowIndex(int new_size) -{ - IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); - if (new_size <= IndexLookup.Size) - return; - IndexAdvanceX.resize(new_size, -1.0f); - IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); -} - ImFont::ImFont() { memset(this, 0, sizeof(*this)); @@ -4950,7 +4960,7 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked // Update lookup tables int codepoint = glyph.Codepoint; - baked->BuildGrowIndex(codepoint + 1); + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); baked->IndexAdvanceX[codepoint] = glyph.AdvanceX; baked->IndexLookup[codepoint] = (ImU16)glyph_idx; const int page_n = codepoint / 8192; @@ -5002,7 +5012,7 @@ ImFontGlyph* ImFontBaked::FindGlyph(ImWchar c) if (i != IM_FONTGLYPH_INDEX_UNUSED) return &Glyphs.Data[i]; } - ImFontGlyph* glyph = BuildLoadGlyph(c); + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c); return glyph ? glyph : &Glyphs.Data[FallbackGlyphIndex]; } @@ -5017,7 +5027,10 @@ ImFontGlyph* ImFontBaked::FindGlyphNoFallback(ImWchar c) if (i != IM_FONTGLYPH_INDEX_UNUSED) return &Glyphs.Data[i]; } - return BuildLoadGlyph(c); + LockLoadingFallback = true; // This is actually a rare call, not done in hot-loop, so we prioritize not adding extra cruft to ImFontBaked_BuildLoadGlyph() call sites. + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c); + LockLoadingFallback = false; + return glyph; } bool ImFontBaked::IsGlyphLoaded(ImWchar c) @@ -5060,7 +5073,7 @@ float ImFontBaked::GetCharAdvance(ImWchar c) } // Same as BuildLoadGlyphGetAdvanceOrFallback(): - const ImFontGlyph* glyph = BuildLoadGlyph(c); + const ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c); return glyph ? glyph->AdvanceX : FallbackAdvanceX; } IM_MSVC_RUNTIME_CHECKS_RESTORE From ef6beaeff68951a8c0f736843dd6f8a0b638796c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Feb 2025 22:53:33 +0100 Subject: [PATCH 0964/2359] Fonts: removed LockSingleSrcConfigIdx which isn't needed anymore since we don't load glyphs in ImFontAtlasBuildAddFont(). --- imgui.h | 1 - imgui_draw.cpp | 15 +++------------ 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index 811125c97..05bda5b54 100644 --- a/imgui.h +++ b/imgui.h @@ -3699,7 +3699,6 @@ struct ImFont float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. - short LockSingleSrcConfigIdx; // Methods IMGUI_API ImFont(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 54a7acab2..ebf42bcb4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3637,14 +3637,11 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im IM_ASSERT(src_idx_in_font >= 0 && src_idx_in_font < font->SourcesCount); IM_UNUSED(atlas); - // While manipulating glyphs during init we want to restrict all searches for one source font. - font->LockSingleSrcConfigIdx = (short)src_idx_in_font; - // Find Fallback character. Actual glyph loaded in GetFontBaked(). const ImWchar fallback_chars[] = { font->FallbackChar, (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; if (font->FallbackChar == 0) for (ImWchar candidate_char : fallback_chars) - if (candidate_char != 0 && font->IsGlyphInFont(candidate_char)) // FIXME: does not respect LockSingleSrcConfigIdx() + if (candidate_char != 0 && font->IsGlyphInFont(candidate_char)) { font->FallbackChar = (ImWchar)candidate_char; break; @@ -3666,7 +3663,6 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im font->EllipsisChar = 0x0085; font->EllipsisAutoBake = true; } - font->LockSingleSrcConfigIdx = -1; } void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph) @@ -4290,15 +4286,11 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep if (ImFontGlyph* glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked)) return glyph; - // Load from single source or all sources? - int srcs_count = (font->LockSingleSrcConfigIdx != -1) ? 1 : font->SourcesCount; - ImFontConfig* srcs = (font->LockSingleSrcConfigIdx != -1) ? &font->Sources[font->LockSingleSrcConfigIdx] : font->Sources; - // Call backend char* loader_user_data_p = (char*)baked->FontLoaderDatas; - for (int src_n = 0; src_n < srcs_count; src_n++) + for (int src_n = 0; src_n < font->SourcesCount; src_n++) { - ImFontConfig* src = &srcs[src_n]; + ImFontConfig* src = &font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) if (ImFontGlyph* glyph = loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint)) @@ -4884,7 +4876,6 @@ ImFont::ImFont() { memset(this, 0, sizeof(*this)); Scale = 1.0f; - LockSingleSrcConfigIdx = -1; } ImFont::~ImFont() From 2bf6879daee8b4f1eae10ee03af953389baae061 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Feb 2025 15:16:19 +0100 Subject: [PATCH 0965/2359] Fonts: tidying up font scale logic. # Conflicts: # imgui_internal.h --- imgui.cpp | 43 ++++++++++++++++++++++--------------------- imgui_internal.h | 9 ++++++--- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3f6c01ded..2d5c33753 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3942,7 +3942,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) FontAtlasOwnedByContext = shared_font_atlas ? false : true; Font = NULL; FontBaked = NULL; - FontSize = /*FontBaseSize = */FontScale = CurrentDpiScale = 0.0f; + FontSize = FontSizeBeforeScaling = FontScale = CurrentDpiScale = 0.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); IO.Fonts->RefCount++; Time = 0.0f; @@ -4375,9 +4375,7 @@ static void SetCurrentWindow(ImGuiWindow* window) g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking if (window) { - // FIXME-BAKED - //g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); - //g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize; + ImGui::UpdateCurrentFontSize(); ImGui::NavUpdateCurrentWindowIsScrollPushableX(); } } @@ -8406,14 +8404,9 @@ ImVec2 ImGui::GetFontTexUvWhitePixel() void ImGui::SetWindowFontScale(float scale) { IM_ASSERT(scale > 0.0f); - // FIXME-BAKED - /* - ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; - g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); - g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize; - */ + UpdateCurrentFontSize(); } void ImGui::PushFocusScope(ImGuiID id) @@ -8608,26 +8601,34 @@ void ImGui::SetCurrentFont(ImFont* font, float font_size) { ImGuiContext& g = *GImGui; g.Font = font; - //g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.FontBaked->Size * g.Font->Scale); - g.FontSize = font_size;// g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + g.FontSizeBeforeScaling = font_size; + UpdateCurrentFontSize(); + if (font != NULL) { IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); - g.FontBaked = g.Font->GetFontBaked(g.FontSize); - g.FontScale = g.FontSize / g.FontBaked->Size; g.DrawListSharedData.Font = g.Font; - g.DrawListSharedData.FontSize = g.FontSize; - g.DrawListSharedData.FontScale = g.FontScale; ImFontAtlasUpdateDrawListsSharedData(g.Font->ContainerAtlas); if (g.CurrentWindow != NULL) g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexRef); } - else - { - g.FontBaked = NULL; - g.FontScale = 0.0f; - } +} + +void ImGui::UpdateCurrentFontSize() +{ + ImGuiContext& g = *GImGui; + float final_size = g.FontSizeBeforeScaling * g.IO.FontGlobalScale; + final_size *= g.Font->Scale; + if (ImGuiWindow* window = g.CurrentWindow) + final_size *= window->FontWindowScale; + final_size = ImMax(1.0f, IM_ROUND(final_size)); + + g.FontSize = final_size; + g.FontBaked = (g.Font != NULL) ? g.Font->GetFontBaked(g.FontSize) : NULL; + g.FontScale = (g.Font != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; + g.DrawListSharedData.FontSize = g.FontSize; + g.DrawListSharedData.FontScale = g.FontScale; } void ImGui::PushFont(ImFont* font, float font_size) diff --git a/imgui_internal.h b/imgui_internal.h index 40975abd7..c0c8002fd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2138,8 +2138,8 @@ struct ImGuiContext ImGuiStyle Style; ImFont* Font; // == FontStack.back().Font ImFontBaked* FontBaked; // == Font->GetFontBaked(FontSize) - float FontSize; // == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. - //float FontBaseSize; // == io.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. + float FontSize; // == FontSizeBeforeScaling * io.FontGlobalScale * font->Scale * g.CurrentWindow->FontWindowScale. Current text height. + float FontSizeBeforeScaling; // == value passed to PushFontSize() float FontScale; // == FontBaked->Size / Font->FontSize. Scale factor over baked size. float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale ImDrawListSharedData DrawListSharedData; @@ -2680,9 +2680,11 @@ public: // We don't use g.FontSize because the window may be != g.CurrentWindow. ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } - //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontBaseSize * FontWindowScale * FontWindowScaleParents; } ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } + + // [Obsolete] ImGuiWindow::CalcFontSize() was removed in 1.92.x because error-prone/misleading. You can use window->FontRefSize for a copy of g.FontSize at the time of the last Begin() call for this window. + //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontBaseSize * FontWindowScale * FontWindowScaleParents; } }; //----------------------------------------------------------------------------- @@ -3106,6 +3108,7 @@ namespace ImGui // Fonts, drawing IMGUI_API void SetCurrentFont(ImFont* font, float font_size); + IMGUI_API void UpdateCurrentFontSize(); inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } IMGUI_API void PushPasswordFont(); inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. From e98a314e0620346b9d9da14fb88fe9fbd88a74af Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Feb 2025 15:41:26 +0100 Subject: [PATCH 0966/2359] Textures: Added ImTextureData::UsedRect. # Conflicts: # imgui_internal.h --- imgui.cpp | 9 ++++++--- imgui.h | 3 ++- imgui_draw.cpp | 7 ++++++- imgui_internal.h | 1 + 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2d5c33753..a8a04080c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15724,10 +15724,13 @@ void ImGui::DebugNodeTexture(ImTextureData* tex) ImGuiContext& g = *GImGui; if (TreeNode(tex, "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height)) { + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + Checkbox("Show used rect", &cfg->ShowTextureUsedRect); PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); - ImTextureRef tex_id; - tex_id._TexData = tex; // Don't use tex->TexID directly so first frame works. - ImageWithBg(tex_id, ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + ImVec2 p = GetCursorScreenPos(); + ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + if (cfg->ShowTextureUsedRect) + GetWindowDrawList()->AddRect(ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255)); PopStyleVar(); char texid_desc[20]; diff --git a/imgui.h b/imgui.h index 05bda5b54..1d7cfbc92 100644 --- a/imgui.h +++ b/imgui.h @@ -3389,7 +3389,8 @@ struct IMGUI_API ImTextureData unsigned char* Pixels; // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. ImTextureID TexID; // Always use SetTexID() to modify! Identifier stored in ImDrawCmd::GetTexID() and passed to backend RenderDrawData loop. void* BackendUserData; // Convenience storage for backend. Some backends may have enough with TexID. - ImTextureRect UpdateRect; // Bounding box encompassing all individual updates. + ImTextureRect UsedRect; // Bounding box encompassing all past and queued Updates[]. + ImTextureRect UpdateRect; // Bounding box encompassing all queued Updates[]. ImVector Updates; // Array of individual updates. int UnusedFrames; // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. unsigned short RefCount; // Number of contexts using this texture. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ebf42bcb4..558dd28e4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2439,6 +2439,7 @@ void ImTextureData::Create(ImTextureFormat format, int w, int h) Pixels = (unsigned char*)IM_ALLOC(Width * Height * BytesPerPixel); IM_ASSERT(Pixels != NULL); memset(Pixels, 0, Width * Height * BytesPerPixel); + UsedRect.x = UsedRect.y = UsedRect.w = UsedRect.h = 0; UpdateRect.x = UpdateRect.y = (unsigned short)~0; UpdateRect.w = UpdateRect.h = 0; } @@ -2918,6 +2919,10 @@ void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, tex->UpdateRect.y = ImMin(tex->UpdateRect.y, req.y); tex->UpdateRect.w = (unsigned short)(new_x1 - tex->UpdateRect.x); tex->UpdateRect.h = (unsigned short)(new_y1 - tex->UpdateRect.y); + tex->UsedRect.x = ImMin(tex->UsedRect.x, req.x); + tex->UsedRect.y = ImMin(tex->UsedRect.y, req.y); + tex->UsedRect.w = (unsigned short)(ImMax(tex->UsedRect.x + tex->UsedRect.w, req.x + req.w) - tex->UsedRect.x); + tex->UsedRect.h = (unsigned short)(ImMax(tex->UsedRect.y + tex->UsedRect.h, req.y + req.h) - tex->UsedRect.y); atlas->TexIsBuilt = false; // No need to queue if status is _WantCreate @@ -3957,7 +3962,7 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ old_tex_h = atlas->TexData->Height; // FIXME-NEWATLAS-V2: What to do when reaching limits exposed by backend? - // FIXME-NEWATLAS-V2: Does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? Could we expose e.g. tex->UsedRect. + // FIXME-NEWATLAS-V2: Does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h)); IM_ASSERT(ImIsPowerOfTwo(atlas->TexMinWidth) && ImIsPowerOfTwo(atlas->TexMaxWidth) && ImIsPowerOfTwo(atlas->TexMinHeight) && ImIsPowerOfTwo(atlas->TexMaxHeight)); diff --git a/imgui_internal.h b/imgui_internal.h index c0c8002fd..12f188b68 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2075,6 +2075,7 @@ struct ImGuiMetricsConfig bool ShowDrawCmdMesh = true; bool ShowDrawCmdBoundingBoxes = true; bool ShowTextEncodingViewer = false; + bool ShowTextureUsedRect = false; int ShowWindowsRectsType = -1; int ShowTablesRectsType = -1; int HighlightMonitorIdx = -1; From 161e2223220b2fa1002c963f1c801ebbb8897316 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Mar 2025 16:14:41 +0100 Subject: [PATCH 0967/2359] Fonts: GetFontBaked() default to searching for closest size font. --- imgui_draw.cpp | 53 ++++++++++++++++++++++++++++++++++++++---------- imgui_internal.h | 1 + 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 558dd28e4..c3275550a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3716,6 +3716,30 @@ ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, floa return baked; } +// FIXME-OPT: This is not a fast query. Adding a BakedCount field in Font might allow to take a shortcut for the most common case. +ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + ImFontBaked* closest_larger_match = NULL; + ImFontBaked* closest_smaller_match = NULL; + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->ContainerFont != font || baked->WantDestroy) + continue; + if (baked->Size > font_size && (closest_larger_match == NULL || baked->Size < closest_larger_match->Size)) + closest_larger_match = baked; + if (baked->Size < font_size && (closest_smaller_match == NULL || baked->Size > closest_smaller_match->Size)) + closest_smaller_match = baked; + } + if (closest_larger_match) + if (closest_smaller_match == NULL || (closest_larger_match->Size >= font_size * 2.0f && closest_smaller_match->Size > font_size * 0.5f)) + return closest_larger_match; + if (closest_smaller_match) + return closest_smaller_match; + return NULL; +} + void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) { ImFontAtlasBuilder* builder = atlas->Builder; @@ -4976,9 +5000,9 @@ void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } +// FIXME-NEWATLAS: Implement AddRemapChar() which was removed since transitioning to baked logic. void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst) { - // FIXME-BAKED: Implement AddRemapChar() IM_UNUSED(from_codepoint); IM_UNUSED(to_codepoint); IM_UNUSED(overwrite_dst); @@ -5092,8 +5116,8 @@ ImFontBaked* ImFont::GetFontBaked(float size) ImFontAtlas* atlas = ContainerAtlas; ImFontAtlasBuilder* builder = atlas->Builder; - // FIXME-BAKED: Design for picking a nearest size? - // FIXME-BAKED: Altering font density won't work right away. + // FIXME-NEWATLAS: Design for picking a nearest size based on some criterias? + // FIXME-NEWATLAS: Altering font density won't work right away. ImGuiID baked_id = ImFontAtlasBakedGetId(FontId, size); ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); baked = *p_baked_in_map; @@ -5105,17 +5129,24 @@ ImFontBaked* ImFont::GetFontBaked(float size) return baked; } - // FIXME-BAKED: If loading is locked, find closest match - if (Flags & ImFontFlags_LockBakedSizes) + // If atlas is locked, find closest match + // FIXME-OPT: This is not an optimal query. + if ((Flags & ImFontFlags_LockBakedSizes) || atlas->Locked) { - IM_ASSERT(LastBaked); - return LastBaked; + baked = ImFontAtlasBuildGetClosestFontBakedMatch(atlas, this, size); + if (baked != NULL) + { + baked->LastUsedFrame = builder->FrameCount; + LastBaked = baked; + return baked;; + } + if (atlas->Locked) + { + IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! + return NULL; + } } - // FIXME-BAKED: If atlas is locked, find closest match - if (atlas->Locked) - IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! - // Create new baked = ImFontAtlasBuildAddFontBaked(atlas, this, size, baked_id); LastBaked = baked; diff --git a/imgui_internal.h b/imgui_internal.h index 12f188b68..a7e481629 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3779,6 +3779,7 @@ IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); IMGUI_API void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font); IMGUI_API ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); +IMGUI_API ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size); IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); IMGUI_API void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy From 0b71339122fabecf925a0a9fb8ca90dacaac71f9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 17:05:24 +0100 Subject: [PATCH 0968/2359] Demo: Add a "Fonts" section for visibility. --- imgui.cpp | 16 ++++++++++------ imgui_demo.cpp | 4 +--- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a8a04080c..ef311491c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15640,6 +15640,11 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) { ImGuiContext& g = *GImGui; + SeparatorText("Backend Support for Dynamic Fonts"); + BeginDisabled(); + CheckboxFlags("io.BackendFlags: RendererHasTextures", &GetIO().BackendFlags, ImGuiBackendFlags_RendererHasTextures); + EndDisabled(); + SeparatorText("Fonts"); Text("Read "); SameLine(0, 0); @@ -16548,12 +16553,11 @@ void ImGui::DebugNodeFont(ImFont* font) } if (SmallButton("Set as default")) GetIO().FontDefault = font; - if (atlas->Fonts.Size > 1 && !atlas->Locked) - { - SameLine(); - if (SmallButton("Remove")) - atlas->RemoveFont(font); - } + SameLine(); + BeginDisabled(atlas->Fonts.Size <= 1 || atlas->Locked); + if (SmallButton("Remove")) + atlas->RemoveFont(font); + EndDisabled(); // Display details SetNextItemWidth(GetFontSize() * 8); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 55b09a2bf..894012903 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1745,6 +1745,7 @@ static void DemoWindowWidgetsFonts() { ImFontAtlas* atlas = ImGui::GetIO().Fonts; ImGui::ShowFontAtlas(atlas); + // FIXME-NEWATLAS: Provide a demo to add/create a procedural font? ImGui::TreePop(); } } @@ -8171,9 +8172,6 @@ void ImGui::ShowAboutWindow(bool* p_open) // - ShowStyleEditor() //----------------------------------------------------------------------------- -// Forward declare ShowFontAtlas() which isn't worth putting in public API yet -namespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); } - // 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) From 131f5c57ab1836cdbf0c6962d9d9cfa7ebd34d49 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 17:18:54 +0100 Subject: [PATCH 0969/2359] Textures: Detect when using a texture that's about to be destroyed. --- imgui.cpp | 5 ++++- imgui_draw.cpp | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index ef311491c..b8dca131c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15733,7 +15733,10 @@ void ImGui::DebugNodeTexture(ImTextureData* tex) Checkbox("Show used rect", &cfg->ShowTextureUsedRect); PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); ImVec2 p = GetCursorScreenPos(); - ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + if (tex->WantDestroyNextFrame) + Dummy(ImVec2((float)tex->Width, (float)tex->Height)); + else + ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); if (cfg->ShowTextureUsedRect) GetWindowDrawList()->AddRect(ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255)); PopStyleVar(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c3275550a..4c5a47143 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -676,6 +676,8 @@ void ImDrawList::PushTexture(ImTextureRef tex_ref) { _TextureStack.push_back(tex_ref); _CmdHeader.TexRef = tex_ref; + if (tex_ref._TexData != NULL) + IM_ASSERT(tex_ref._TexData->WantDestroyNextFrame == false); _OnChangedTexture(); } From dec8d3863abdd126fdce044bb0a0f808f2ae3ba6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 20:08:00 +0100 Subject: [PATCH 0970/2359] Fonts: Added a ImFontFlags_NoLoadError flag to let user code try file paths. (3611) --- imgui.h | 1 + imgui_draw.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 1d7cfbc92..6703c128b 100644 --- a/imgui.h +++ b/imgui.h @@ -3676,6 +3676,7 @@ enum ImFontFlags_ ImFontFlags_None = 0, ImFontFlags_LockBakedSizes = 1 << 0, // Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. ImFontFlags_NoLoadGlyphs = 1 << 1, // Disable loading new glyphs. + ImFontFlags_NoLoadError = 1 << 2, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. }; // Font runtime data and rendering diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4c5a47143..ec379ffa1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3096,7 +3096,8 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0); if (!data) { - IM_ASSERT_USER_ERROR(0, "Could not load font file!"); + if (font_cfg_template == NULL || (font_cfg_template->Flags & ImFontFlags_NoLoadError) == 0) + IM_ASSERT_USER_ERROR(0, "Could not load font file!"); return NULL; } ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); From 93410c47e11c2f9d719a1c87111a1d5b08af6e96 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Mar 2025 18:42:41 +0100 Subject: [PATCH 0971/2359] Fonts: Fixed various small warnings / build issues. --- imgui.cpp | 2 +- imgui.h | 4 ++-- imgui_draw.cpp | 9 +++++++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b8dca131c..644275201 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16670,7 +16670,7 @@ void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) if (glyph->PackId >= 0) { ImFontAtlasRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId); - Text("PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y);; + Text("PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y); } } diff --git a/imgui.h b/imgui.h index 6703c128b..f03a20306 100644 --- a/imgui.h +++ b/imgui.h @@ -339,7 +339,7 @@ struct ImTextureRef { ImTextureRef() { memset(this, 0, sizeof(*this)); } ImTextureRef(ImTextureID tex_id) { memset(this, 0, sizeof(*this)); _TexID = tex_id; } -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureUserID) ImTextureRef(void* tex_id) { memset(this, 0, sizeof(*this)); _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID //inline operator intptr_t() const { return (intptr_t)_TexID; } // For legacy backends casting to ImTextureID #endif @@ -3406,7 +3406,7 @@ struct IMGUI_API ImTextureData unsigned char* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } int GetPitch() const { return Width * BytesPerPixel; } - ImTextureRef GetTexRef() const { ImTextureRef tex_ref; tex_ref._TexData = (ImTextureData*)(void*)this; tex_ref._TexID = TexID; return tex_ref; } + ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = TexID; return tex_ref; } ImTextureID GetTexID() const { return TexID; } // Called by Renderer backend diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ec379ffa1..d51ae9e50 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -40,6 +40,7 @@ Index of this file: #endif #include // vsnprintf, sscanf, printf +#include // intptr_t // Visual Studio warnings #ifdef _MSC_VER @@ -3193,6 +3194,7 @@ void ImFontAtlas::RemoveFont(ImFont* font) bool removed = Fonts.find_erase(font); IM_ASSERT(removed); + IM_UNUSED(removed); Sources.erase(font->Sources, font->Sources + font->SourcesCount); ImFontAtlasBuildUpdatePointers(this); @@ -3644,6 +3646,7 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im const int src_idx_in_font = (int)(src - font->Sources); IM_ASSERT(src_idx_in_font >= 0 && src_idx_in_font < font->SourcesCount); IM_UNUSED(atlas); + IM_UNUSED(src_idx_in_font); // Find Fallback character. Actual glyph loaded in GetFontBaked(). const ImWchar fallback_chars[] = { font->FallbackChar, (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; @@ -3680,9 +3683,10 @@ void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImF ImFontAtlasPackDiscardRect(atlas, glyph->PackId); glyph->PackId = -1; } - ImWchar c = glyph->Codepoint; + ImWchar c = (ImWchar)glyph->Codepoint; IM_ASSERT(font->FallbackChar != c && font->EllipsisChar != c); // Unsupported for simplicity IM_ASSERT(glyph >= baked->Glyphs.Data && glyph < baked->Glyphs.Data + baked->Glyphs.Size); + IM_UNUSED(font); baked->IndexLookup[c] = IM_FONTGLYPH_INDEX_UNUSED; baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; } @@ -4371,6 +4375,7 @@ void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); for (const ImTextureRect& r : tex->Updates) { + IM_UNUSED(r); IM_ASSERT(r.x >= 0 && r.y >= 0); IM_ASSERT(r.x + r.w <= tex->Width && r.y + r.h <= tex->Height); // In theory should subtract PackPadding but it's currently part of atlas and mid-frame change would wreck assert. //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); @@ -5141,7 +5146,7 @@ ImFontBaked* ImFont::GetFontBaked(float size) { baked->LastUsedFrame = builder->FrameCount; LastBaked = baked; - return baked;; + return baked; } if (atlas->Locked) { From da51485e17e08ef156aada958bf05b4e27b0d739 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Mar 2025 18:15:25 +0100 Subject: [PATCH 0972/2359] Fonts: Obsolete GetGlyphRangesXXX() functions. Update font documentation. --- docs/FONTS.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ imgui.h | 5 ++++- imgui_draw.cpp | 3 +++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index 514af0799..9b783dcdc 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -12,6 +12,7 @@ In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) fo ## Index - [Troubleshooting](#troubleshooting) +- [New! Dynamic Fonts system in 1.92 (March 2025)](#new-dynamic-fonts-system-in-192-march-2025) - [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application) - [Fonts Loading Instructions](#fonts-loading-instructions) - [Loading Font Data from Memory](#loading-font-data-from-memory) @@ -43,6 +44,8 @@ See [About UTF-8 Encoding](#about-utf-8-encoding). Use the encoding viewer to co ### (3) Missing glyph ranges. +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary.** + You need to load a font with explicit glyph ranges if you want to use non-ASCII characters. See [Fonts Loading Instructions](#fonts-loading-instructions). Use [Debug Tools](#debug-tools) confirm loaded fonts and loaded glyph ranges. This is a current constraint of Dear ImGui (which we will lift in the future): when loading a font you need to specify which characters glyphs to load. @@ -50,6 +53,8 @@ All loaded fonts glyphs are rendered into a single texture atlas ahead of time. ### (4) Font atlas texture fails to upload to GPU. +🆕 **Since 1.92, with an up to date backend: atlas is built incrementally and dynamically resized, this is less likely to happen** + This is often of byproduct of point 3. If you have large number of glyphs or multiple fonts, the texture may become too big for your graphics API. **The typical result of failing to upload a texture is if every glyph or everything appears as empty white rectangles.** Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. ![empty squares](https://github.com/user-attachments/assets/68b50fb5-8b9d-4c38-baec-6ac384f06d26) @@ -63,6 +68,22 @@ Some solutions: Future versions of Dear ImGui should solve this problem. +##### [Return to Index](#index) + +--------------------------------------- + +## New! Dynamic Fonts system in 1.92 (March 2025+) + +v1.92 will introduce a newer, dynamic font system. It requires backend to support the `ImGuiBackendFlags_HasTextures` feature: +- Users of icons, Asian and non-English languages do not need to pre-build all glyphs ahead of time. Saving on loading time, memory, and also reducing issues with missing glyphs. Specifying glyph ranges is not needed anymore. +- PushFontSize() may be used anytime to change font size. +- Packing custom rectangles is more convenient as pixels may be written to immediately. +- Any update to fonts previously required backend specific calls to re-upload the texture, and said calls were not portable across backends. It is now possible to scale fonts etc. in a way that doesn't require you to make backend-specific calls. +- It is possible to plug a custom loader/backend to any font source. + +See [#8465](https://github.com/ocornut/imgui/issues/8465) for more details. + + ##### [Return to Index](#index) --------------------------------------- @@ -131,6 +152,8 @@ io.Fonts->Build(); **Add a fourth parameter to bake specific font ranges only:** +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary. All the GetGlyphRangesXXX() functions are marked obsolete.** + ```cpp // Basic Latin, Extended Latin io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesDefault()); @@ -145,10 +168,20 @@ See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create yo **Example loading and using a Japanese font:** +🆕 **Since 1.92, with an up to date backend:** + +```cpp +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f); +``` + +**Before 1.92, or without an up to date backend:** + ```cpp ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); ``` + ```cpp ImGui::Text(u8"こんにちは!テスト %d", 123); if (ImGui::Button(u8"ロード")) @@ -215,6 +248,8 @@ To refer to the icon UTF-8 codepoints from your C++ code, you may use those head So you can use `ICON_FA_SEARCH` as a string that will render as a "Search" icon. +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary. You can omit this parameter.** + Example Setup: ```cpp // Merge icons into default tool font @@ -289,6 +324,8 @@ io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg, ra ## Using Custom Glyph Ranges +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary, so this is not needed.** + You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. ```cpp ImVector ranges; @@ -308,6 +345,15 @@ io.Fonts->Build(); // Build the atlas while ## Using Custom Colorful Icons +🆕 **Since 1.92, with an up to date backend: this system has been revamped.** + +TL;DR; With the new system, it is recommended that you create a custom `ImFontLoader` and register your fonts with it. +`AddCustomRectFontGlyph()` has been obsolete because its API does not make much sense with resizable fonts. + +You can ask questions in [#8466](https://github.com/ocornut/imgui/issues/8466). + +🆕 **Before 1.92:** + As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiFreeTypeBuilderFlags_LoadColor`, you may allocate your own space in the texture atlas and write yourself into it. **(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)** - You can use the `ImFontAtlas::AddCustomRect()` and `ImFontAtlas::AddCustomRectFontGlyph()` api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build()`. diff --git a/imgui.h b/imgui.h index f03a20306..8f01ff7ef 100644 --- a/imgui.h +++ b/imgui.h @@ -3553,11 +3553,13 @@ struct ImFontAtlas // Glyph Ranges //------------------------------------------- + // Since 1.92: specifying glyph ranges is only useful/necessary if your backend doesn't support ImGuiBackendFlags_HasTextures! + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) // NB: Make sure that your string are UTF-8 and NOT in your local code page. // Read https://github.com/ocornut/imgui/blob/master/docs/FONTS.md/#about-utf-8-encoding for details. // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. - IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin IMGUI_API const ImWchar* GetGlyphRangesGreek(); // Default + Greek and Coptic IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs @@ -3566,6 +3568,7 @@ struct ImFontAtlas IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters +#endif //------------------------------------------- // [ALPHA] Custom Rectangles/Glyphs API diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d51ae9e50..c99dbb5a8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4579,6 +4579,7 @@ const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() // [SECTION] ImFontAtlas: glyph ranges helpers //------------------------------------------------------------------------- // - GetGlyphRangesDefault() +// Obsolete functions since 1.92: // - GetGlyphRangesGreek() // - GetGlyphRangesKorean() // - GetGlyphRangesChineseFull() @@ -4600,6 +4601,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesDefault() return &ranges[0]; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS const ImWchar* ImFontAtlas::GetGlyphRangesGreek() { static const ImWchar ranges[] = @@ -4849,6 +4851,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese() }; return &ranges[0]; } +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //----------------------------------------------------------------------------- // [SECTION] ImFontGlyphRangesBuilder From c98e3c0effe9887d29c426560da8803be005c069 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Mar 2025 18:39:32 +0100 Subject: [PATCH 0973/2359] Fonts: ImFontConfig::GlyphExcludeRanges is owner and copied. --- imgui.cpp | 6 ++++++ imgui.h | 2 +- imgui_draw.cpp | 24 +++++++++++++++--------- imgui_internal.h | 2 ++ 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 644275201..cb546e4ba 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2011,6 +2011,12 @@ char* ImStrdup(const char* str) return (char*)memcpy(buf, (const void*)str, len + 1); } +void* ImMemdup(const void* src, size_t size) +{ + void* dst = IM_ALLOC(size); + return memcpy(dst, src, size); +} + char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) { size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1; diff --git a/imgui.h b/imgui.h index 8f01ff7ef..550af74ba 100644 --- a/imgui.h +++ b/imgui.h @@ -3434,7 +3434,7 @@ struct ImFontConfig //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). - const ImWchar* GlyphExcludeRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a VERY SHORT user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. + const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a VERY SHORT user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c99dbb5a8..f154e5628 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2644,11 +2644,7 @@ void ImFontAtlas::ClearInputData() const ImFontLoader* loader = font_cfg.FontLoader ? font_cfg.FontLoader : FontLoader; if (loader && loader->FontSrcDestroy != NULL) loader->FontSrcDestroy(this, &font_cfg); - if (font_cfg.FontData && font_cfg.FontDataOwnedByAtlas) - { - IM_FREE(font_cfg.FontData); - font_cfg.FontData = NULL; - } + ImFontAtlasBuildDiscardFontSource(this, &font_cfg); } // When clearing this we lose access to the font name and other information used to build the font. @@ -2969,6 +2965,17 @@ bool ImFontAtlas::Build() } #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +void ImFontAtlasBuildDiscardFontSource(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + if (src->FontDataOwnedByAtlas) + IM_FREE(src->FontData); + if (src->GlyphExcludeRanges) + IM_FREE((void*)src->GlyphExcludeRanges); + src->FontData = NULL; + src->GlyphExcludeRanges = NULL; +} + ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); @@ -3001,9 +3008,8 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) new_font_cfg.DstFont = font; if (!new_font_cfg.FontDataOwnedByAtlas) { - new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize); new_font_cfg.FontDataOwnedByAtlas = true; - memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + new_font_cfg.FontData = ImMemdup(font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); } // Sanity check @@ -3013,6 +3019,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) for (const ImWchar* p = font_cfg->GlyphExcludeRanges; p[0] != 0; p++, size++) {} IM_ASSERT((size & 1) == 0 && "GlyphExcludeRanges[] size must be multiple of two!"); IM_ASSERT((size <= 64) && "GlyphExcludeRanges[] size must be small!"); + new_font_cfg.GlyphExcludeRanges = (ImWchar*)ImMemdup(font_cfg->GlyphExcludeRanges, sizeof(font_cfg->GlyphExcludeRanges[0]) * (size + 1)); } if (font_cfg->FontLoader != NULL) IM_ASSERT(font_cfg->FontLoader->FontBakedLoadGlyph != NULL); @@ -3029,8 +3036,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) if (!ImFontAtlasBuildAddFont(this, &new_font_cfg)) { // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) - if (new_font_cfg.FontDataOwnedByAtlas) - IM_FREE(new_font_cfg.FontData); + ImFontAtlasBuildDiscardFontSource(this, &new_font_cfg); Sources.pop_back(); if (!font_cfg->MergeMode) { diff --git a/imgui_internal.h b/imgui_internal.h index a7e481629..6252ee818 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -389,6 +389,7 @@ IMGUI_API int ImStricmp(const char* str1, const char* str2); 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* 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 @@ -3778,6 +3779,7 @@ IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontCo IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); IMGUI_API void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasBuildDiscardFontSource(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); IMGUI_API ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size); IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); From 40f988ce2a23e64be2831abe94f28345ce60e7a2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Mar 2025 19:57:49 +0100 Subject: [PATCH 0974/2359] Fonts: in ShowFontAtlas() preserve open-state for latest texture. Improve debug display. --- imgui.cpp | 20 ++++++++++++-------- imgui_draw.cpp | 17 ++++++++++++++--- imgui_internal.h | 5 ++++- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cb546e4ba..466ab28c7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15420,7 +15420,8 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImG // - RenderViewportsThumbnails() [Internal] // - DebugTextEncoding() // - MetricsHelpMarker() [Internal] -// - ShowFontAtlas() [Internal] +// - ShowFontAtlas() [Internal but called by Demo!] +// - DebugNodeTexture() [Internal] // - ShowMetricsWindow() // - DebugNodeColumns() [Internal] // - DebugNodeDrawList() [Internal] @@ -15722,18 +15723,20 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt); // Texture list - for (ImTextureData* tex : atlas->TexList) + // (ensure the last texture always use the same ID, so we can keep it open neatly) + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) { - PushID(tex); - DebugNodeTexture(tex); - PopID(); + if (tex_n == atlas->TexList.Size - 1) + SetNextItemOpen(true, ImGuiCond_Once); + DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n); } } -void ImGui::DebugNodeTexture(ImTextureData* tex) +void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id) { ImGuiContext& g = *GImGui; - if (TreeNode(tex, "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height)) + PushID(int_id); + if (TreeNode("", "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height)) { ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; Checkbox("Show used rect", &cfg->ShowTextureUsedRect); @@ -15748,12 +15751,13 @@ void ImGui::DebugNodeTexture(ImTextureData* tex) PopStyleVar(); char texid_desc[20]; - Text("Format = %d", tex->Format); + Text("Format = %s (%d)", ImTextureDataGetFormatName(tex->Format), tex->Format); Text("TexID = %s", FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->TexID)); Text("BackendUserData = %p", tex->BackendUserData); Text("UseColors = %d", tex->UseColors); TreePop(); } + PopID(); } void ImGui::ShowMetricsWindow(bool* p_open) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f154e5628..04a00c422 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2420,7 +2420,7 @@ ImFontConfig::ImFontConfig() // - ImTextureData::DestroyPixels() //----------------------------------------------------------------------------- -static int GetTextureFormatBytesPerPixel(ImTextureFormat format) +int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format) { switch (format) { @@ -2431,13 +2431,24 @@ static int GetTextureFormatBytesPerPixel(ImTextureFormat format) return 0; } +const char* ImTextureDataGetFormatName(ImTextureFormat format) +{ + switch (format) + { + case ImTextureFormat_Alpha8: return "Alpha8"; + case ImTextureFormat_RGBA32: return "RGBA32"; + } + return "N/A"; +} + + void ImTextureData::Create(ImTextureFormat format, int w, int h) { DestroyPixels(); Format = format; Width = w; Height = h; - BytesPerPixel = GetTextureFormatBytesPerPixel(format); + BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format); UseColors = false; Pixels = (unsigned char*)IM_ALLOC(Width * Height * BytesPerPixel); IM_ASSERT(Pixels != NULL); @@ -2798,7 +2809,7 @@ void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFo IM_ASSERT(src_pixels != NULL && dst_pixels != NULL); if (src_fmt == dst_fmt) { - int line_sz = w * GetTextureFormatBytesPerPixel(src_fmt); + int line_sz = w * ImTextureDataGetFormatBytesPerPixel(src_fmt); for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) memcpy(dst_pixels, src_pixels, line_sz); } diff --git a/imgui_internal.h b/imgui_internal.h index 6252ee818..c1857aafb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3625,7 +3625,7 @@ namespace ImGui IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); IMGUI_API void DebugNodeFont(ImFont* font); IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph); - IMGUI_API void DebugNodeTexture(ImTextureData* tex); + IMGUI_API void DebugNodeTexture(ImTextureData* tex, int int_id); // ID used to facilitate persisting the "current" texture. IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label); IMGUI_API void DebugNodeTable(ImGuiTable* table); @@ -3809,6 +3809,9 @@ IMGUI_API void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h); IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h); +IMGUI_API int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format); +IMGUI_API const char* ImTextureDataGetFormatName(ImTextureFormat format); + #ifndef IMGUI_DISABLE_DEBUG_TOOLS IMGUI_API void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas); #endif From 41a0e991f0ea621b93cfe3672a274147a5457a72 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Mar 2025 20:34:18 +0100 Subject: [PATCH 0975/2359] Fonts: Added UI to edit FreeType loader flags. Added ImFontAtlasBuildReloadAll() / ImFontAtlasBuildReloadFont() --- imgui.cpp | 26 +++++++++++++++++++++++--- imgui_draw.cpp | 22 +++++++++++++++++++--- imgui_internal.h | 5 ++++- misc/freetype/imgui_freetype.cpp | 18 +++++++++++++++++- misc/freetype/imgui_freetype.h | 3 +++ 5 files changed, 66 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 466ab28c7..1d1ad8650 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15639,7 +15639,7 @@ static void MetricsHelpMarker(const char* desc) } #ifdef IMGUI_ENABLE_FREETYPE -namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); } +namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontBuilderFlags(unsigned int* p_font_builder_flags); } #endif // [DEBUG] List fonts in a font atlas and display its texture @@ -15682,6 +15682,12 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader(); if (RadioButton("FreeType", loader_current == loader_freetype)) ImFontAtlasBuildSetupFontLoader(atlas, loader_freetype); + if (loader_current == loader_freetype) + { + Text("Shared FreeType Loader Flags:"); + if (ImGuiFreeType::DebugEditFontBuilderFlags(&atlas->FontBuilderFlags)) + ImFontAtlasBuildReloadAll(atlas); + } #else BeginDisabled(); RadioButton("FreeType", false); @@ -16585,10 +16591,24 @@ void ImGui::DebugNodeFont(ImFont* font) char c_str[5]; Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar); Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar); + for (int src_n = 0; src_n < font->SourcesCount; src_n++) if (ImFontConfig* src = &font->Sources[src_n]) - BulletText("Input %d: \'%s\', Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", - src_n, src->Name, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); + if (TreeNode(src, "Input %d: \'%s\', Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y)) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + Text("Loader: '%s'", loader->Name ? loader->Name : "N/A"); +#ifdef IMGUI_ENABLE_FREETYPE + if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0) + { + Text("FreeType Loader Flags: 0x%08X", src->FontBuilderFlags); + if (ImGuiFreeType::DebugEditFontBuilderFlags(&src->FontBuilderFlags)) + ImFontAtlasBuildReloadFont(atlas, src); + } +#endif + TreePop(); + } // Display all glyphs of the fonts in separate pages of 256 characters for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 04a00c422..c7418cfca 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2519,7 +2519,7 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildDiscardBakes() // - ImFontAtlasBuildDiscardFontBakedGlyph() // - ImFontAtlasBuildDiscardFontBaked() -// - ImFontAtlasBuildDiscardFont() +// - ImFontAtlasBuildDiscardFontBakes() //----------------------------------------------------------------------------- // - ImFontAtlasAddDrawListSharedData() // - ImFontAtlasRemoveDrawListSharedData() @@ -3551,6 +3551,22 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ //----------------------------------------------------------------------------------------------------------------------------- +void ImFontAtlasBuildReloadAll(ImFontAtlas* atlas) +{ + const ImFontLoader* main_loader = atlas->FontLoader; + ImFontAtlasBuildSetupFontLoader(atlas, NULL); + ImFontAtlasBuildSetupFontLoader(atlas, main_loader); +} + +void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFontConfig* src) +{ + // FIXME-NEWATLAS: rebuild single font not supported yet. + IM_UNUSED(src); + ImFontAtlasBuildReloadAll(atlas); +} + +//----------------------------------------------------------------------------------------------------------------------------- + bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) { ImFont* font = src->DstFont; @@ -3794,7 +3810,7 @@ void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBa font->LastBaked = NULL; } -void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font) +void ImFontAtlasBuildDiscardFontBakes(ImFontAtlas* atlas, ImFont* font) { if (ImFontAtlasBuilder* builder = atlas->Builder) // This can be called from font destructor for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) @@ -4943,7 +4959,7 @@ ImFont::~ImFont() void ImFont::ClearOutputData() { if (ImFontAtlas* atlas = ContainerAtlas) - ImFontAtlasBuildDiscardFont(atlas, this); + ImFontAtlasBuildDiscardFontBakes(atlas, this); FallbackChar = EllipsisChar = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); LastBaked = NULL; diff --git a/imgui_internal.h b/imgui_internal.h index c1857aafb..c92aea666 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3775,10 +3775,13 @@ IMGUI_API void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildReloadAll(ImFontAtlas* atlas); // Reinit/rebuild, notably if font loader params have changed. +IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFontConfig* src); // Reinit/rebuild, notably if font loader params have changed. + IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); -IMGUI_API void ImFontAtlasBuildDiscardFont(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasBuildDiscardFontBakes(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildDiscardFontSource(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); IMGUI_API ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index fd6920e0c..edd6bdd14 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -578,7 +578,7 @@ bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* s const ImFontLoader* ImGuiFreeType::GetFontLoader() { static ImFontLoader loader; - loader.Name = "freetype"; + loader.Name = "FreeType"; loader.LoaderInit = ImGui_ImplFreeType_LoaderInit; loader.LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown; loader.FontSrcInit = ImGui_ImplFreeType_FontSrcInit; @@ -598,6 +598,22 @@ void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* u GImGuiFreeTypeAllocatorUserData = user_data; } +bool ImGuiFreeType::DebugEditFontBuilderFlags(unsigned int* p_font_loader_flags) +{ + bool edited = false; + edited |= ImGui::CheckboxFlags("NoHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_NoHinting); + edited |= ImGui::CheckboxFlags("NoAutoHint", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_NoAutoHint); + edited |= ImGui::CheckboxFlags("ForceAutoHint",p_font_loader_flags, ImGuiFreeTypeBuilderFlags_ForceAutoHint); + edited |= ImGui::CheckboxFlags("LightHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_LightHinting); + edited |= ImGui::CheckboxFlags("MonoHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_MonoHinting); + edited |= ImGui::CheckboxFlags("Bold", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Bold); + edited |= ImGui::CheckboxFlags("Oblique", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Oblique); + edited |= ImGui::CheckboxFlags("Monochrome", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Monochrome); + edited |= ImGui::CheckboxFlags("LoadColor", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_LoadColor); + edited |= ImGui::CheckboxFlags("Bitmap", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Bitmap); + return edited; +} + #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG // For more details, see https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/rsvg-port.c // The original code from the demo is licensed under CeCILL-C Free Software License Agreement (https://gitlab.freedesktop.org/freetype/freetype/-/blob/master/LICENSE.TXT) diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index 2d7b3a34f..b4e9ba1fd 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -49,6 +49,9 @@ namespace ImGuiFreeType // However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired. IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = nullptr); + // Display UI to edit FontBuilderFlags in ImFontAtlas (shared) or ImFontConfig (single source) + IMGUI_API bool DebugEditFontBuilderFlags(unsigned int* p_font_loader_flags); + // Obsolete names (will be removed soon) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontBuilderFlags = flags; return atlas->Build(); } // Prefer using '#define IMGUI_ENABLE_FREETYPE' From 735d31e54a481e4ca6c90630ee6eb338999364d5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Mar 2025 20:50:00 +0100 Subject: [PATCH 0976/2359] Demo: Exposed some basic UI in demo for sanity. --- imgui_demo.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 894012903..43c3cf9db 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -430,6 +430,17 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); ImGui::Spacing(); + ImGui::SeparatorText("dynamic_fonts branch"); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 5); + ImGui::DragFloat("io.FontGlobalScale", &ImGui::GetIO().FontGlobalScale, 0.05f, 0.5f, 5.0f); + ImGui::BulletText("This is scaling font only. General scaling will come later."); + ImGui::BulletText("Load an actual font that's not the default for best result!"); + ImGui::BulletText("See 'Widgets->Fonts' below for more.."); + ImGui::BulletText("Current font loader: '%s'", ImGui::GetIO().Fonts->FontLoaderName); + ImGui::BulletText("Please submit feedback:"); ImGui::SameLine(); + ImGui::TextLinkOpenURL("https://github.com/ocornut/imgui/issues/8465"); + ImGui::Spacing(); + IMGUI_DEMO_MARKER("Help"); if (ImGui::CollapsingHeader("Help")) { From 8ea0ae454f1fe427c4968b9b562d66c0f40a6ca4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 9 Mar 2025 21:36:44 +0100 Subject: [PATCH 0977/2359] Fonts: fixed a bug using size specified by secondary font sources. --- imgui_draw.cpp | 2 ++ misc/freetype/imgui_freetype.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c7418cfca..52aeeee9d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4460,6 +4460,8 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); else bd_font_data->ScaleFactor = -stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); + if (src > src->DstFont->Sources) + bd_font_data->ScaleFactor *= src->SizePixels / src->DstFont->Sources[0].SizePixels; // FIXME-NEWATLAS: Should tidy up that a bit return true; } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index edd6bdd14..7264fc263 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -432,7 +432,7 @@ void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { IM_UNUSED(atlas); - const float size = baked->Size; + const float size = baked->Size * (src->SizePixels / baked->ContainerFont->Sources[0].SizePixels); // FIXME-NEWATLAS: Should tidy up that a bit ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; bd_font_data->BakedLastActivated = baked; From 52a6863771df71a0a1031512eea8f1b37b9311f1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Mar 2025 10:55:29 +0100 Subject: [PATCH 0978/2359] Textures: ImTextureData pixels are not immediately destroyed on setting ImTextureStatus_WantDestroy. --- imgui_draw.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 52aeeee9d..df4429d9f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2780,9 +2780,9 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count) else if (tex->WantDestroyNextFrame && tex->Status != ImTextureStatus_WantDestroy) { // Request destroy. Keep bool as it allows us to keep track of things. + // We don't destroy pixels right away, as backend may have an in-flight copy from RAM. IM_ASSERT(tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates); tex->Status = ImTextureStatus_WantDestroy; - tex->DestroyPixels(); } // The backend may need defer destroying by a few frames, to handle texture used by previous in-flight rendering. @@ -2794,9 +2794,10 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count) if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL) remove_from_list = true; - // Remove + // Destroy and remove if (remove_from_list) { + tex->DestroyPixels(); IM_DELETE(tex); atlas->TexList.erase(atlas->TexList.begin() + tex_n); tex_n--; From 144f444217576121f1b16dba18a20e715ad01cf0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Mar 2025 11:46:18 +0100 Subject: [PATCH 0979/2359] Fonts: fixed memory leaks, shutting down font loader, and on AddFont() failure in FreeType backend. --- imgui.h | 3 +-- imgui_draw.cpp | 14 ++++++++------ misc/freetype/imgui_freetype.cpp | 4 ++++ 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index 550af74ba..cdb27e7e9 100644 --- a/imgui.h +++ b/imgui.h @@ -3711,7 +3711,7 @@ struct ImFont IMGUI_API ImFontBaked* GetFontBaked(float font_size); // Get or create baked data for given size IMGUI_API bool IsGlyphInFont(ImWchar c); bool IsLoaded() const { return ContainerAtlas != NULL; } - const char* GetDebugName() const { return Sources ? Sources->Name : ""; } + const char* GetDebugName() const { return Sources ? Sources[0].Name : ""; } // [Internal] Don't use! // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. @@ -3720,7 +3720,6 @@ struct ImFont IMGUI_API const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, 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, bool cpu_fine_clip = false); - #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(Sources[0].SizePixels * scale, text, text_end, wrap_width); } #endif diff --git a/imgui_draw.cpp b/imgui_draw.cpp index df4429d9f..88f623c8b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3034,7 +3034,10 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) new_font_cfg.GlyphExcludeRanges = (ImWchar*)ImMemdup(font_cfg->GlyphExcludeRanges, sizeof(font_cfg->GlyphExcludeRanges[0]) * (size + 1)); } if (font_cfg->FontLoader != NULL) + { IM_ASSERT(font_cfg->FontLoader->FontBakedLoadGlyph != NULL); + IM_ASSERT(font_cfg->FontLoader->LoaderInit == NULL && font_cfg->FontLoader->LoaderShutdown == NULL); // FIXME-NEWATLAS: Unsupported yet. + } IM_ASSERT(font_cfg->FontLoaderData == NULL); // Round font size @@ -3369,11 +3372,6 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); ImFontAtlasBuildDestroy(atlas); - if (atlas->FontLoader && atlas->FontLoader->LoaderShutdown) - { - atlas->FontLoader->LoaderShutdown(atlas); - IM_ASSERT(atlas->FontLoaderData == NULL); - } atlas->FontLoader = font_loader; atlas->FontLoaderName = font_loader ? font_loader->Name : "NULL"; if (atlas->FontLoader && atlas->FontLoader->LoaderInit) @@ -4187,7 +4185,11 @@ void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) if (loader && loader->FontSrcDestroy != NULL) loader->FontSrcDestroy(atlas, &font_cfg); } - + if (atlas->FontLoader && atlas->FontLoader->LoaderShutdown) + { + atlas->FontLoader->LoaderShutdown(atlas); + IM_ASSERT(atlas->FontLoaderData == NULL); + } IM_DELETE(atlas->Builder); atlas->Builder = NULL; } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 7264fc263..72140f952 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -416,7 +416,11 @@ bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) src->FontLoaderData = bd_font_data; if (!bd_font_data->InitFont(bd->Library, src, atlas->FontBuilderFlags)) + { + IM_DELETE(bd_font_data); + src->FontLoaderData = NULL; return false; + } return true; } From 7ac1bff482b6c982df4cc4a9a2e1b1503c6cfa88 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Mar 2025 19:54:33 +0100 Subject: [PATCH 0980/2359] Fonts: fixed an issue calling legacy ImFontAtlas::Clear(). --- imgui_draw.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 88f623c8b..f6cf1f4a6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2637,8 +2637,6 @@ void ImFontAtlas::Clear() RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. ClearFonts(); ClearTexData(); - if (Builder != NULL) - ImFontAtlasBuildClearTexture(this); RendererHasTextures = backup_renderer_has_textures; } @@ -3374,8 +3372,6 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon atlas->FontLoader = font_loader; atlas->FontLoaderName = font_loader ? font_loader->Name : "NULL"; - if (atlas->FontLoader && atlas->FontLoader->LoaderInit) - atlas->FontLoader->LoaderInit(atlas); ImFontAtlasBuildAddTexture(atlas, new_tex_size.x, new_tex_size.y); ImFontAtlasBuildInit(atlas); @@ -4140,8 +4136,12 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) return; // ImFontAtlasBuildSetupFontLoader() automatically call ImFontAtlasBuildInit() } + IM_ASSERT(atlas->FontLoaderData == NULL); + if (atlas->FontLoader && atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); + // Create initial texture size - if (atlas->TexData == NULL) + if (atlas->TexData == NULL || atlas->TexData->Pixels == NULL) ImFontAtlasBuildAddTexture(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); ImFontAtlasBuilder* builder = atlas->Builder; // Do not move above From e76cfe5aad93e52b00302f3a9182c64336ab7169 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Mar 2025 16:30:20 +0100 Subject: [PATCH 0981/2359] Fonts: fixed implicit init when calling AddCustomRectRegular(). LoaderShutdown match BuildDestroy. --- imgui_draw.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f6cf1f4a6..873e77508 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3231,6 +3231,9 @@ int ImFontAtlas::AddCustomRectRegular(int width, int height) IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); + if (Builder == NULL) + ImFontAtlasBuildInit(this); + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); if (r_id < 0) return -1; @@ -4185,7 +4188,7 @@ void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) if (loader && loader->FontSrcDestroy != NULL) loader->FontSrcDestroy(atlas, &font_cfg); } - if (atlas->FontLoader && atlas->FontLoader->LoaderShutdown) + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) { atlas->FontLoader->LoaderShutdown(atlas); IM_ASSERT(atlas->FontLoaderData == NULL); From b12c42e75db8deeb56dff989f90bd7413f5d39b9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Mar 2025 16:50:19 +0100 Subject: [PATCH 0982/2359] Fonts: change uses of ImFontAtlasRect to ImTextureRect for simplicity. --- imgui.cpp | 2 +- imgui_draw.cpp | 40 ++++++++++++++------------------ imgui_internal.h | 12 +++------- misc/freetype/imgui_freetype.cpp | 2 +- 4 files changed, 23 insertions(+), 33 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1d1ad8650..ef3abcb46 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16699,7 +16699,7 @@ void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); if (glyph->PackId >= 0) { - ImFontAtlasRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId); + ImTextureRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId); Text("PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y); } } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 873e77508..cea3bc07a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3237,7 +3237,7 @@ int ImFontAtlas::AddCustomRectRegular(int width, int height) ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); if (r_id < 0) return -1; - ImFontAtlasRect* r = ImFontAtlasPackGetRect(this, r_id); + ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); if (RendererHasTextures) ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); return r_id; @@ -3271,7 +3271,7 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); if (r_id < 0) return -1; - ImFontAtlasRect* r = ImFontAtlasPackGetRect(this, r_id); + ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); if (RendererHasTextures) ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); @@ -3295,11 +3295,7 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im ImTextureRect* ImFontAtlas::GetCustomRectByIndex(int idx) { - IM_STATIC_ASSERT(offsetof(ImTextureRect, x) == offsetof(ImFontAtlasRect, x)); - IM_STATIC_ASSERT(offsetof(ImTextureRect, y) == offsetof(ImFontAtlasRect, y)); - IM_STATIC_ASSERT(offsetof(ImTextureRect, w) == offsetof(ImFontAtlasRect, w)); - IM_STATIC_ASSERT(offsetof(ImTextureRect, h) == offsetof(ImFontAtlasRect, h)); - return (ImTextureRect*)(void*)ImFontAtlasPackGetRect(this, idx); + return ImFontAtlasPackGetRect(this, idx); } void ImFontAtlas::CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const @@ -3316,7 +3312,7 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) return false; - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, atlas->Builder->PackIdMouseCursors); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, atlas->Builder->PackIdMouseCursors); ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->x, (float)r->y); ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; *out_size = size; @@ -3453,7 +3449,7 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ builder->PackIdMouseCursors = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); if (builder->PackIdMouseCursors < 0) return; - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdMouseCursors); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdMouseCursors); // Draw to texture if (add_and_draw) @@ -3489,7 +3485,7 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ builder->PackIdLinesTexData = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); if (builder->PackIdLinesTexData < 0) return; - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdLinesTexData); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdLinesTexData); // Register texture region for thick lines // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row @@ -3599,12 +3595,12 @@ static ImFontGlyph* ImFontAtlasBuildSetupFontBakedEllipsis(ImFontAtlas* atlas, I if (dot_glyph == NULL) return NULL; ImFontAtlasRectId dot_r_id = dot_glyph->PackId; // Deep copy to avoid invalidation of glyphs and rect pointers - ImFontAtlasRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id); + ImTextureRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id); const int dot_spacing = 1; const float dot_step = (dot_glyph->X1 - dot_glyph->X0) + dot_spacing; ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, (dot_r->w * 3 + dot_spacing * 2), dot_r->h); - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); ImFontGlyph glyph_in = {}; ImFontGlyph* glyph = &glyph_in; @@ -3961,7 +3957,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic, and fix stability. // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. ImFontAtlasPackInit(atlas); - ImVector old_rects; + ImVector old_rects; ImVector old_index = builder->RectsIndex; old_rects.swap(builder->Rects); @@ -3969,7 +3965,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) { if (index_entry.Used == false) continue; - ImFontAtlasRect& old_r = old_rects[index_entry.TargetIndex]; + ImTextureRect& old_r = old_rects[index_entry.TargetIndex]; if (old_r.w == 0 && old_r.h == 0) continue; ImFontAtlasRectId new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, &index_entry); @@ -3986,7 +3982,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) return; } IM_ASSERT(new_r_id == builder->RectsIndex.index_from_ptr(&index_entry)); - ImFontAtlasRect* new_r = ImFontAtlasPackGetRect(atlas, new_r_id); + ImTextureRect* new_r = ImFontAtlasPackGetRect(atlas, new_r_id); ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r->x, new_r->y, new_r->w, new_r->h); } IM_ASSERT(old_rects.Size == builder->Rects.Size + builder->RectsDiscardedCount); @@ -3998,7 +3994,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) for (ImFontGlyph& glyph : builder->BakedPool[baked_n].Glyphs) if (glyph.PackId != -1) { - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); glyph.U0 = (r->x) * atlas->TexUvScale.x; glyph.V0 = (r->y) * atlas->TexUvScale.y; glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; @@ -4244,7 +4240,7 @@ void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; IM_ASSERT(index_entry->Used && index_entry->TargetIndex >= 0); - ImFontAtlasRect* rect = ImFontAtlasPackGetRect(atlas, id); + ImTextureRect* rect = ImFontAtlasPackGetRect(atlas, id); index_entry->Used = false; index_entry->TargetIndex = builder->RectsIndexFreeListStart; @@ -4268,7 +4264,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon builder->MaxRectSize.y = ImMax(builder->MaxRectSize.y, h); // Pack - ImFontAtlasRect r = { 0, 0, (unsigned short)w, (unsigned short)h }; + ImTextureRect r = { 0, 0, (unsigned short)w, (unsigned short)h }; for (int attempts_remaining = 3; attempts_remaining >= 0; attempts_remaining--) { // Try packing @@ -4312,7 +4308,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon } // Important: don'return pointer valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. -ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) +ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { IM_ASSERT(id >= 0); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; @@ -4551,7 +4547,7 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); return NULL; } - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); // Render stbtt_GetGlyphBitmapBox(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, &x0, &y0, &x1, &y1); @@ -4999,7 +4995,7 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked // Set UV from packed rectangle if (in_glyph->PackId >= 0) { - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, in_glyph->PackId); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, in_glyph->PackId); IM_ASSERT(in_glyph->U0 == 0.0f && in_glyph->V0 == 0.0f && in_glyph->U1 == 0.0f && in_glyph->V1 == 0.0f); glyph.U0 = (r->x) * atlas->TexUvScale.x; glyph.V0 = (r->y) * atlas->TexUvScale.y; @@ -5042,7 +5038,7 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked } // Copy to texture, post-process and queue update for backend -void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImFontAtlasRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch) +void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch) { ImTextureData* tex = atlas->TexData; IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); diff --git a/imgui_internal.h b/imgui_internal.h index c92aea666..940473abe 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -143,7 +143,6 @@ struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas struct ImFontAtlasPostProcessData; // Data available to potential texture post-processing functions -struct ImFontAtlasRect; // Packed rectangle (same as ImTextureRect) struct ImFontAtlasRectEntry; // Packed rectangle lookup entry // ImGui @@ -3692,11 +3691,6 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- -struct ImFontAtlasRect -{ - unsigned short x, y; - unsigned short w, h; -}; typedef int ImFontAtlasRectId; // <0 when invalid // Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) @@ -3734,7 +3728,7 @@ struct ImFontAtlasBuilder { stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file. ImVector PackNodes; - ImVector Rects; + ImVector Rects; ImVector RectsIndex; // ImFontAtlasRectId -> index into Rects[] ImVector TempBuffer; // Misc scratch buffer int RectsIndexFreeListStart;// First unused entry @@ -3791,12 +3785,12 @@ IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* a IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); -IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImFontAtlasRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); +IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size); IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); -IMGUI_API ImFontAtlasRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); +IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 72140f952..5151a90d5 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -534,7 +534,7 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); return NULL; } - ImFontAtlasRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); // Render pixels to our temporary buffer atlas->Builder->TempBuffer.resize(w * h * 4); From 85d050758024d04bf8f3911bafce4bee433cf0c0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Mar 2025 16:54:39 +0100 Subject: [PATCH 0983/2359] Fonts: narrowed invalid value for ImFontAtlasRectId to -1 a we will change implementation. --- imgui.h | 2 +- imgui_draw.cpp | 22 +++++++++++----------- imgui_internal.h | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index cdb27e7e9..c3e568cfe 100644 --- a/imgui.h +++ b/imgui.h @@ -3577,7 +3577,7 @@ struct ImFontAtlas // You can request arbitrary rectangles to be packed into the atlas, for your own purpose. // You can request your rectangles to be mapped as font glyph (given a font + Unicode point), // so you can render e.g. custom colorful icons and use them as regular glyphs. - // - Since 1.92.X, packing is done immediately in the function call. Returns >= on success, <0 on error. + // - Since 1.92.X, packing is done immediately in the function call. Returns -1 on error. // - You can render your pixels into the texture right after calling the AddCustomRectXXX() functions. // - If your backend supports ImGuiBackendFlags_RendererHasTextures: // Texture may be resized, so you cannot cache UV coordinates: always use CalcCustomRectUV(). diff --git a/imgui_draw.cpp b/imgui_draw.cpp index cea3bc07a..92c6b0655 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3235,7 +3235,7 @@ int ImFontAtlas::AddCustomRectRegular(int width, int height) ImFontAtlasBuildInit(this); ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); - if (r_id < 0) + if (r_id == -1) return -1; ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); if (RendererHasTextures) @@ -3269,7 +3269,7 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im ImFontBaked* baked = font->GetFontBaked(font_size); ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); - if (r_id < 0) + if (r_id == -1) return -1; ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); if (RendererHasTextures) @@ -3447,7 +3447,7 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ if (add_and_draw) builder->PackIdMouseCursors = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); - if (builder->PackIdMouseCursors < 0) + if (builder->PackIdMouseCursors == -1) return; ImTextureRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdMouseCursors); @@ -3483,7 +3483,7 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ ImFontAtlasBuilder* builder = atlas->Builder; if (add_and_draw) builder->PackIdLinesTexData = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); - if (builder->PackIdLinesTexData < 0) + if (builder->PackIdLinesTexData == -1) return; ImTextureRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdLinesTexData); @@ -3705,7 +3705,7 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph) { - if (glyph->PackId >= 0) + if (glyph->PackId != -1) { ImFontAtlasPackDiscardRect(atlas, glyph->PackId); glyph->PackId = -1; @@ -3780,7 +3780,7 @@ void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBa IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName()); for (ImFontGlyph& glyph : baked->Glyphs) - if (glyph.PackId >= 0) + if (glyph.PackId != -1) ImFontAtlasPackDiscardRect(atlas, glyph.PackId); char* loader_data_p = (char*)baked->FontLoaderDatas; @@ -4235,7 +4235,7 @@ static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int r // This is expected to be called in batches and followed by a repack void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { - IM_ASSERT(id >= 0); + IM_ASSERT(id != -1); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; IM_ASSERT(index_entry->Used && index_entry->TargetIndex >= 0); @@ -4310,7 +4310,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon // Important: don'return pointer valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { - IM_ASSERT(id >= 0); + IM_ASSERT(id != -1); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; IM_ASSERT(index_entry->Used); @@ -4541,10 +4541,10 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, const int w = (x1 - x0 + oversample_h - 1); const int h = (y1 - y0 + oversample_v - 1); ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); - if (pack_id < 0) + if (pack_id == -1) { // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) - IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); + IM_ASSERT_USER_ERROR(pack_id != -1, "Out of texture memory."); return NULL; } ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); @@ -4993,7 +4993,7 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked IM_ASSERT(baked->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. // Set UV from packed rectangle - if (in_glyph->PackId >= 0) + if (in_glyph->PackId != -1) { ImTextureRect* r = ImFontAtlasPackGetRect(atlas, in_glyph->PackId); IM_ASSERT(in_glyph->U0 == 0.0f && in_glyph->V0 == 0.0f && in_glyph->U1 == 0.0f && in_glyph->V1 == 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index 940473abe..6d13087f4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3691,7 +3691,7 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- -typedef int ImFontAtlasRectId; // <0 when invalid +typedef int ImFontAtlasRectId; // -1 when invalid // Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) // User are returned ImFontAtlasRectId values which are meant to be persistent. From f816b861fc506d2d438868d4bc0667cd65ab8ae8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Mar 2025 17:10:52 +0100 Subject: [PATCH 0984/2359] (Breaking) Fonts: rename GetCustomRectByIndex() to GetCustomRect(). Made return struct const. --- docs/FONTS.md | 7 ++----- imgui.h | 28 ++++++++++++++-------------- imgui_draw.cpp | 6 +++--- imgui_internal.h | 4 +++- 4 files changed, 22 insertions(+), 23 deletions(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index 9b783dcdc..452499059 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -357,7 +357,7 @@ You can ask questions in [#8466](https://github.com/ocornut/imgui/issues/8466). As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiFreeTypeBuilderFlags_LoadColor`, you may allocate your own space in the texture atlas and write yourself into it. **(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)** - You can use the `ImFontAtlas::AddCustomRect()` and `ImFontAtlas::AddCustomRectFontGlyph()` api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build()`. -- You can then use `ImFontAtlas::GetCustomRectByIndex(int)` to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles. +- You can then use `ImFontAtlas::GetCustomRect(int)` to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles. - This API is beta because it is likely to change in order to support multi-dpi (multiple viewports on multiple monitors with varying DPI scale). #### Pseudo-code: @@ -377,9 +377,7 @@ int tex_width, tex_height; io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) -{ - int rect_id = rect_ids[rect_n]; - if (const ImFontAtlasCustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) + if (const ImTextureRect* rect = io.Fonts->GetCustomRect(rect_ids[rect_n])) { // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!) for (int y = 0; y < rect->Height; y++) @@ -389,7 +387,6 @@ for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) *p++ = IM_COL32(255, 0, 0, 255); } } -} ``` ##### [Return to Index](#index) diff --git a/imgui.h b/imgui.h index c3e568cfe..2a781b765 100644 --- a/imgui.h +++ b/imgui.h @@ -3574,24 +3574,24 @@ struct ImFontAtlas // [ALPHA] Custom Rectangles/Glyphs API //------------------------------------------- - // You can request arbitrary rectangles to be packed into the atlas, for your own purpose. - // You can request your rectangles to be mapped as font glyph (given a font + Unicode point), - // so you can render e.g. custom colorful icons and use them as regular glyphs. - // - Since 1.92.X, packing is done immediately in the function call. Returns -1 on error. + // Register and retrieve custom rectangles + // - You can request arbitrary rectangles to be packed into the atlas, for your own purpose. + // - You can request your rectangles to be mapped as font glyph (given a font + Unicode point), + // so you can render e.g. custom colorful icons and use them as regular glyphs. + // - Since 1.92.X, packing is done immediately in the function call. // - You can render your pixels into the texture right after calling the AddCustomRectXXX() functions. - // - If your backend supports ImGuiBackendFlags_RendererHasTextures: - // Texture may be resized, so you cannot cache UV coordinates: always use CalcCustomRectUV(). - // - If you render colored output into your AddCustomRectRegular() rectangle: set 'atlas->TexPixelsUseColors = true' - // as this may help some backends decide of preferred texture format. + // - Texture may be resized, so you cannot cache UV coordinates: always use CalcCustomRectUV()! + // - If you render colored output into your AddCustomRectRegular() rectangle: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. // - Read docs/FONTS.md for more details about using colorful icons. - // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. - IMGUI_API int AddCustomRectRegular(int width, int height); + // - Note: this API may be reworked further in order to facilitate supporting e.g. multi-monitor, varying DPI settings. + IMGUI_API int AddCustomRectRegular(int width, int height); // Register a rectangle. Return -1 on error. + IMGUI_API const ImTextureRect* GetCustomRect(int id); // Get rectangle coordinate in current texture. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); - IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); + IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); + inline const ImTextureRect* GetCustomRectByIndex(int id) { return GetCustomRect(id); } #endif - IMGUI_API ImTextureRect* GetCustomRectByIndex(int index); - IMGUI_API void CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; + IMGUI_API void CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; //------------------------------------------- // Members diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 92c6b0655..c83d5b94a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2500,7 +2500,7 @@ void ImTextureData::DestroyPixels() //----------------------------------------------------------------------------- // - ImFontAtlas::AddCustomRectRegular() // - ImFontAtlas::AddCustomRectFontGlyph() -// - ImFontAtlas::GetCustomRectByIndex() +// - ImFontAtlas::GetCustomRect() // - ImFontAtlas::CalcCustomRectUV() // - ImFontAtlasGetMouseCursorTexData() //----------------------------------------------------------------------------- @@ -3293,9 +3293,9 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im } #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -ImTextureRect* ImFontAtlas::GetCustomRectByIndex(int idx) +const ImTextureRect* ImFontAtlas::GetCustomRect(int id) { - return ImFontAtlasPackGetRect(this, idx); + return ImFontAtlasPackGetRect(this, (ImFontAtlasRectId)id); } void ImFontAtlas::CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const diff --git a/imgui_internal.h b/imgui_internal.h index 6d13087f4..045064363 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3691,7 +3691,9 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- -typedef int ImFontAtlasRectId; // -1 when invalid +// An identifier to a rectangle in the atlas. -1 when invalid. +// The rectangle may move, use GetCustomRect() to retrieve it. +typedef int ImFontAtlasRectId; // Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) // User are returned ImFontAtlasRectId values which are meant to be persistent. From 4048494aa1dfb61858ca96247542b1e4b8b2e958 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Mar 2025 17:28:13 +0100 Subject: [PATCH 0985/2359] Fonts: rename ImFontAtlasBuildClearTexture() to ImFontAtlasBuildClear(). --- imgui.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ef3abcb46..5e51dfa55 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15714,7 +15714,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) ImFontAtlasBuildGrowTexture(atlas); SameLine(); if (Button("Clear Output")) - ImFontAtlasBuildClearTexture(atlas); + ImFontAtlasBuildClear(atlas); for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) { diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c83d5b94a..20151496e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4091,7 +4091,7 @@ ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) } // Clear all output. Invalidates all AddCustomRectXXX return values. -void ImFontAtlasBuildClearTexture(ImFontAtlas* atlas) +void ImFontAtlasBuildClear(ImFontAtlas* atlas) { ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); ImFontAtlasBuildDestroy(atlas); diff --git a/imgui_internal.h b/imgui_internal.h index 045064363..dfd11f6dc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3762,11 +3762,11 @@ IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader); IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); +IMGUI_API void ImFontAtlasBuildClear(ImFontAtlas* atlas); // Clear output and custom rects IMGUI_API ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h); IMGUI_API void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h); -IMGUI_API void ImFontAtlasBuildClearTexture(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas); From 41517bca0c42e7fa5ab3207c528a988f0bc556b1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Mar 2025 19:14:10 +0100 Subject: [PATCH 0986/2359] (Breaking) Fonts: renamed CalcCustomRectUV() to GetCustomRectUV() for simplicity. --- imgui.h | 27 ++++++++++++++++----------- imgui_draw.cpp | 2 +- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/imgui.h b/imgui.h index 2a781b765..44f48c263 100644 --- a/imgui.h +++ b/imgui.h @@ -3580,18 +3580,17 @@ struct ImFontAtlas // so you can render e.g. custom colorful icons and use them as regular glyphs. // - Since 1.92.X, packing is done immediately in the function call. // - You can render your pixels into the texture right after calling the AddCustomRectXXX() functions. - // - Texture may be resized, so you cannot cache UV coordinates: always use CalcCustomRectUV()! + // - Texture may be resized, so you cannot cache UV coordinates: always use GetCustomRectUV()! // - If you render colored output into your AddCustomRectRegular() rectangle: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. // - Read docs/FONTS.md for more details about using colorful icons. // - Note: this API may be reworked further in order to facilitate supporting e.g. multi-monitor, varying DPI settings. + // - Pre-1.92 names: + // - AddCustomRectFontGlyph() --> Use custom ImFontLoader inside ImFontConfig + // - GetCustomRectByIndex() --> Use GetCustomRect() + // - CalcCustomRectUV() --> Use GetCustomRectUV() IMGUI_API int AddCustomRectRegular(int width, int height); // Register a rectangle. Return -1 on error. IMGUI_API const ImTextureRect* GetCustomRect(int id); // Get rectangle coordinate in current texture. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); - IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); - inline const ImTextureRect* GetCustomRectByIndex(int id) { return GetCustomRect(id); } -#endif - IMGUI_API void CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; + IMGUI_API void GetCustomRectUV(const ImTextureRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const; // Get UV coordinates for a given rectangle //------------------------------------------- // Members @@ -3633,10 +3632,16 @@ struct ImFontAtlas int RefCount; // Number of contexts using this atlas // [Obsolete] - //int TexDesiredWidth; // OBSOLETED in 1.92.X (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) - //typedef ImTextureRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X - //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ - //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig + IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X + inline const ImTextureRect* GetCustomRectByIndex(int id) { return GetCustomRect(id); } // OBSOLETED in 1.92.X + inline void CalcCustomRectUV(const ImTextureRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { return GetCustomRectUV(r, out_uv_min, out_uv_max); } // OBSOLETED in 1.92.X +#endif + //int TexDesiredWidth; // OBSOLETED in 1.92.X (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) + //typedef ImTextureRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X + //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ + //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ }; // Font runtime data for a given size diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 20151496e..3207c92c7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3298,7 +3298,7 @@ const ImTextureRect* ImFontAtlas::GetCustomRect(int id) return ImFontAtlasPackGetRect(this, (ImFontAtlasRectId)id); } -void ImFontAtlas::CalcCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const +void ImFontAtlas::GetCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const { IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates *out_uv_min = ImVec2((float)rect->x * TexUvScale.x, (float)rect->y * TexUvScale.y); From cc65015e4e1ecd7fffb4e8838bb2d9da2b9deecd Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 17:18:05 +0100 Subject: [PATCH 0987/2359] Fonts: fixed crashing password fields. # Conflicts: # imgui_internal.h --- imgui.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 4 +++- imgui_widgets.cpp | 44 +++++++++++++++++++++++++------------------- 4 files changed, 30 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5e51dfa55..f65cd777c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4086,6 +4086,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) MouseCursor = ImGuiMouseCursor_Arrow; MouseStationaryTimer = 0.0f; + InputTextPasswordFontBackupFlags = ImFontFlags_None; TempInputId = 0; memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue)); BeginMenuDepth = BeginComboDepth = 0; @@ -4284,7 +4285,6 @@ void ImGui::Shutdown() g.MenusIdSubmittedThisFrame.clear(); g.InputTextState.ClearFreeMemory(); g.InputTextDeactivatedState.ClearFreeMemory(); - g.InputTextPasswordFont.ContainerAtlas = NULL; g.SettingsWindows.clear(); g.SettingsHandlers.clear(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3207c92c7..fa15be25e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4136,7 +4136,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) } IM_ASSERT(atlas->FontLoaderData == NULL); - if (atlas->FontLoader && atlas->FontLoader->LoaderInit) + if (atlas->FontLoader->LoaderInit) atlas->FontLoader->LoaderInit(atlas); // Create initial texture size diff --git a/imgui_internal.h b/imgui_internal.h index dfd11f6dc..83a16aa9d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2391,7 +2391,8 @@ struct ImGuiContext // Widget state ImGuiInputTextState InputTextState; ImGuiInputTextDeactivatedState InputTextDeactivatedState; - ImFont InputTextPasswordFont; + ImFontBaked InputTextPasswordFontBackupBaked; + ImFontFlags InputTextPasswordFontBackupFlags; ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc. ImGuiDataTypeStorage DataTypeZeroValue; // 0 for all data types int BeginMenuDepth; @@ -3112,6 +3113,7 @@ namespace ImGui IMGUI_API void UpdateCurrentFontSize(); inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } IMGUI_API void PushPasswordFont(); + IMGUI_API void PopPasswordFont(); inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport); // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport); // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6a86c7956..91d50933f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4314,23 +4314,29 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons void ImGui::PushPasswordFont() { ImGuiContext& g = *GImGui; - ImFont* in_font = g.Font; - ImFontBaked* in_baked = g.FontBaked; - ImFontGlyph glyph = *in_baked->FindGlyph('*'); - glyph.PackId = -1; - ImFont* out_font = &g.InputTextPasswordFont; - out_font->Scale = in_font->Scale; - out_font->ContainerAtlas = in_font->ContainerAtlas; - out_font->Flags |= ImFontFlags_NoLoadGlyphs; - ImFontBaked* out_baked = out_font->GetFontBaked(in_baked->Size); - IM_ASSERT(out_baked->Glyphs.Size <= 1 && out_baked->IndexAdvanceX.Size == 0 && out_baked->IndexLookup.Size == 0); - out_baked->Ascent = in_baked->Ascent; - out_baked->Descent = in_baked->Descent; - out_baked->Glyphs.resize(0); - out_baked->Glyphs.push_back(glyph); - out_baked->FallbackGlyphIndex = 0; - out_baked->FallbackAdvanceX = glyph.AdvanceX; - PushFont(out_font); + ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked; + IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0); + ImFontGlyph* glyph = g.FontBaked->FindGlyph('*'); + g.InputTextPasswordFontBackupFlags = g.Font->Flags; + backup->FallbackGlyphIndex = g.FontBaked->FallbackGlyphIndex; + backup->FallbackAdvanceX = g.FontBaked->FallbackAdvanceX; + backup->IndexLookup.swap(g.FontBaked->IndexLookup); + backup->IndexAdvanceX.swap(g.FontBaked->IndexAdvanceX); + g.Font->Flags |= ImFontFlags_NoLoadGlyphs; + g.FontBaked->FallbackGlyphIndex = g.FontBaked->Glyphs.index_from_ptr(glyph); + g.FontBaked->FallbackAdvanceX = glyph->AdvanceX; +} + +void ImGui::PopPasswordFont() +{ + ImGuiContext& g = *GImGui; + ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked; + g.Font->Flags = g.InputTextPasswordFontBackupFlags; + g.FontBaked->FallbackGlyphIndex = backup->FallbackGlyphIndex; + g.FontBaked->FallbackAdvanceX = backup->FallbackAdvanceX; + g.FontBaked->IndexLookup.swap(backup->IndexLookup); + g.FontBaked->IndexAdvanceX.swap(backup->IndexAdvanceX); + IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0); } // Return false to discard a character. @@ -5232,7 +5238,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (new_is_displaying_hint != is_displaying_hint) { if (is_password && !is_displaying_hint) - PopFont(); + PopPasswordFont(); is_displaying_hint = new_is_displaying_hint; if (is_password && !is_displaying_hint) PushPasswordFont(); @@ -5423,7 +5429,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } if (is_password && !is_displaying_hint) - PopFont(); + PopPasswordFont(); if (is_multiline) { From 8bd1fc4f04b8e2ae62ebdd76de128b2929b16fa0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Mar 2025 22:08:58 +0100 Subject: [PATCH 0988/2359] Textures: Added ImTextureRef::GetTexID() mostly for consistency. Without it the logic may seem more confusing to grok for end-user. --- imgui.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 44f48c263..14396377e 100644 --- a/imgui.h +++ b/imgui.h @@ -343,6 +343,7 @@ struct ImTextureRef ImTextureRef(void* tex_id) { memset(this, 0, sizeof(*this)); _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID //inline operator intptr_t() const { return (intptr_t)_TexID; } // For legacy backends casting to ImTextureID #endif + inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file. // Members ImTextureData* _TexData; // Texture, generally owned by a ImFontAtlas @@ -3072,7 +3073,7 @@ struct ImDrawCmd // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! // If for some reason you non C++ tech stack makes it difficult to call it, we may decide to separate the fields in ImDrawCmd. - inline ImTextureID GetTexID() const; + inline ImTextureID GetTexID() const; // == (TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID }; // Vertex layout @@ -3735,7 +3736,12 @@ struct ImFont IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); }; -// Added indirection to avoid patching ImDrawCmd after texture updates. +// We added an indirection to avoid patching ImDrawCmd after texture updates but this could be a solution too. +inline ImTextureID ImTextureRef::GetTexID() const +{ + return _TexData ? _TexData->TexID : _TexID; +} + inline ImTextureID ImDrawCmd::GetTexID() const { // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92) From e41bf16ff155f0626c32d7b2ea158a1880847fda Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Mar 2025 18:03:40 +0100 Subject: [PATCH 0989/2359] Fonts: fixed ImTextureID() being zero-cleared instead of using ImTextureUserID_Invalid. . --- imgui.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index 14396377e..ba9c16b22 100644 --- a/imgui.h +++ b/imgui.h @@ -337,11 +337,11 @@ typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or IM_MSVC_RUNTIME_CHECKS_OFF struct ImTextureRef { - ImTextureRef() { memset(this, 0, sizeof(*this)); } - ImTextureRef(ImTextureID tex_id) { memset(this, 0, sizeof(*this)); _TexID = tex_id; } -#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureUserID) - ImTextureRef(void* tex_id) { memset(this, 0, sizeof(*this)); _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID - //inline operator intptr_t() const { return (intptr_t)_TexID; } // For legacy backends casting to ImTextureID + ImTextureRef() { _TexData = NULL; _TexID = ImTextureID_Invalid; } + ImTextureRef(ImTextureID tex_id) { _TexData = NULL; _TexID = tex_id; } +#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureID) + ImTextureRef(void* tex_id) { _TexData = NULL; _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID + //inline operator intptr_t() const { return (intptr_t)_TexID; } // For legacy backends casting to ImTextureID #endif inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file. From 0fff7ceda450994b221df7538ea9d934b17a5611 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Mar 2025 14:06:08 +0100 Subject: [PATCH 0990/2359] Fonts: comments, tweaks, minor amends. Comments, tweaks --- imgui.cpp | 2 +- imgui.h | 88 +++++++++++++++++++++++++++++++------------------- imgui_demo.cpp | 18 +++++++---- 3 files changed, 67 insertions(+), 41 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f65cd777c..0e5a4c775 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16552,7 +16552,7 @@ void ImGui::DebugNodeFont(ImFont* font) ImGuiContext& g = *GImGui; ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; ImFontAtlas* atlas = font->ContainerAtlas; - bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->Sources ? font->Sources[0].Name : "", font->SourcesCount); + bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->SourcesCount); // Display preview text if (!opened) diff --git a/imgui.h b/imgui.h index ba9c16b22..f8e5b6c55 100644 --- a/imgui.h +++ b/imgui.h @@ -311,29 +311,44 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // [SECTION] Texture identifiers (ImTextureID, ImTextureRef) //----------------------------------------------------------------------------- -// ImTextureID: user data for renderer backend to identify a texture [Compile-time configurable type] +// ImTextureID = backend specific, low-level identifier for a texture uploaded in GPU/graphics system. +// [Compile-time configurable type] // Overview: -// - Backend and user/app code provides ImTextureID values that gets stored inside draw commands (ImDrawCmd) during the ImGui frame. -// - Backend uses ImDrawCmd::GetTexID() to retrieve the ImTextureID value during rendering. Then, they can bind the textures of each draw command. +// - When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value. +// (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint'; +// Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.). +// - User may submit their own textures to e.g. ImGui::Image() function by passing the same type. +// - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside +// ImTextureRef, which is stored inside ImDrawCmd. // Configuring the type: -// - To use something else than a 64-bit value: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file. // - This can be whatever to you want it to be! read the FAQ entry about textures for details. -// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various constructors if you like. You will need to implement ==/!= operators. +// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various +// constructors if you like. You will need to implement ==/!= operators. // History: // - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requirig 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. +// - In v1.92.0 (2025/XX/XX): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef #ifndef ImTextureID typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that. #endif -// Define this to another value if you need value of 0 to be valid. +// Define this if you need 0 to be a valid ImTextureID for your backend. #ifndef ImTextureID_Invalid #define ImTextureID_Invalid ((ImTextureID)0) #endif -// ImTextureRef contains: -// - a texture/atlas pointer, typically when created by Dear ImGui itself. -// - OR a raw ImTextureID value (user/backend identifier), typically when created by user code to load images. -// There is no constructor to create a ImTextureID from a ImTextureData* as we don't expect this to be useful to the end-user. +// ImTextureRef = higher-level identifier for a texture. +// The identifier is valid even before the texture has been uploaded to the GPU/graphics system. +// This is what gets passed to functions such as ImGui::Image(), ImDrawList::AddImage(). +// This is what gets stored in draw commands (ImDrawCmd) to identify a texture during rendering. +// - When a texture is created by user code (e.g. custom images), we directly stores the low-level ImTextureID. +// - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection +// to extract the ImTextureID value during rendering, after texture upload has happened. +// - There is no constructor to create a ImTextureID from a ImTextureData* as we don't expect this +// to be useful to the end-user, and it would be erroneously called by many legacy code. +// - If you want to bind the current atlas when using custom rectangle, you can use io.Fonts->TexRef. +// - Binding generators for languages such as C (which don't have constructors), should provide a helper: +// inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; } IM_MSVC_RUNTIME_CHECKS_OFF struct ImTextureRef { @@ -341,13 +356,12 @@ struct ImTextureRef ImTextureRef(ImTextureID tex_id) { _TexData = NULL; _TexID = tex_id; } #if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureID) ImTextureRef(void* tex_id) { _TexData = NULL; _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID - //inline operator intptr_t() const { return (intptr_t)_TexID; } // For legacy backends casting to ImTextureID #endif inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file. - // Members - ImTextureData* _TexData; // Texture, generally owned by a ImFontAtlas - ImTextureID _TexID; // _OR_ Underlying texture identifier for backend, if already uploaded (otherwise pulled from _TexData) + // Members (either are set, never both!) + ImTextureData* _TexData; // A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. + ImTextureID _TexID; // _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui::Image() calls. }; IM_MSVC_RUNTIME_CHECKS_RESTORE @@ -604,7 +618,7 @@ namespace ImGui IMGUI_API bool TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked // Widgets: Images - // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + // - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. // - Image() pads adds style.ImageBorderSize on each side, ImageButton() adds style.FramePadding on each side. // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. @@ -2817,7 +2831,8 @@ static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return IM_MSVC_RUNTIME_CHECKS_RESTORE #endif -// Helpers: ImTexture ==/!= operators provided as convenience (not strictly necessary) +// Helpers: ImTextureRef ==/!= operators provided as convenience +// (note that _TexID and _TexData are never set simultaneously) static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } //#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // For legacy backends @@ -3072,7 +3087,6 @@ struct ImDrawCmd // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! - // If for some reason you non C++ tech stack makes it difficult to call it, we may decide to separate the fields in ImDrawCmd. inline ImTextureID GetTexID() const; // == (TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID }; @@ -3295,8 +3309,8 @@ struct ImDrawList // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - //IMGUI_API void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x - //IMGUI_API void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x + IMGUI_API void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x + IMGUI_API void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x #endif //inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) @@ -3344,7 +3358,11 @@ struct ImDrawData }; //----------------------------------------------------------------------------- -// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData +// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +//----------------------------------------------------------------------------- +// In principle, the only data types that user/application code should care about are 'ImTextureRef' and 'ImTextureID'. +// They are defined above in this header file. Read their description to the difference between ImTextureRef and ImTextureID. +// FOR ALL OTHER ImTextureXXXX TYPES: ONLY CORE LIBRARY AND RENDERER BACKENDS NEED TO KNOW AND CARE ABOUT THEM. //----------------------------------------------------------------------------- // We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension. @@ -3355,7 +3373,7 @@ enum ImTextureFormat ImTextureFormat_Alpha8, // 1 component per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight }; -// Status of a texture +// Status of a texture to communicate with Renderer Backend. enum ImTextureStatus { ImTextureStatus_OK, @@ -3366,7 +3384,7 @@ enum ImTextureStatus }; // Coordinates of a rectangle within a texture. -// When a texture is in ImTextureStatus_WantUpdates state, we provide a list of individual rectangles to copy to GPU texture. +// When a texture is in ImTextureStatus_WantUpdates state, we provide a list of individual rectangles to copy to the graphics system. // You may use ImTextureData::Updates[] for the list, or ImTextureData::UpdateBox for a single bounding box. struct ImTextureRect { @@ -3375,7 +3393,8 @@ struct ImTextureRect }; // Specs and pixel storage for a texture used by Dear ImGui. -// The renderer backend will generally create a GPU-side version of this. +// This is only useful for (1) core library and (2) backends. End-user/applications do not need to care about this. +// Renderer Backends will create a GPU-side version of this. // Why does we store two identifiers: TexID and BackendUserData? // - ImTextureID TexID = lower-level identifier stored in ImDrawCmd. ImDrawCmd can refer to textures not created by the backend, and for which there's no ImTextureData. // - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both. @@ -3407,7 +3426,7 @@ struct IMGUI_API ImTextureData unsigned char* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } int GetPitch() const { return Width * BytesPerPixel; } - ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = TexID; return tex_ref; } + ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = TexID; return tex_ref; } // FIXME-TEXREF ImTextureID GetTexID() const { return TexID; } // Called by Renderer backend @@ -3502,7 +3521,7 @@ enum ImFontAtlasFlags_ // It is the rendering backend responsibility to upload texture into your graphics API: // - ImGui_ImplXXXX_RenderDrawData() functions generally iterate platform_io->Textures[] to create/update/destroy each ImTextureData instance. // - Backend then set ImTextureData's TexID and BackendUserData. -// - Texture id are passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. +// - Texture id are passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID/ImTextureRef for more details. // Legacy path: // - Call Build() + GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. // - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. @@ -3554,7 +3573,7 @@ struct ImFontAtlas // Glyph Ranges //------------------------------------------- - // Since 1.92: specifying glyph ranges is only useful/necessary if your backend doesn't support ImGuiBackendFlags_HasTextures! + // Since 1.92: specifying glyph ranges is only useful/necessary if your backend doesn't support ImGuiBackendFlags_RendererHasTextures! IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) @@ -3607,9 +3626,14 @@ struct ImFontAtlas int TexMaxHeight; // Maximum desired texture height. Must be a power of two. Default to 8192. void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). + // Output + ImTextureRef TexRef; // Current texture identifier == TexData->GetTexRef(). +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImTextureRef& TexID = TexRef; // RENAMED in 1.92.x +#endif + ImTextureData* TexData; // Current texture. + // [Internal] - ImTextureRef TexRef; // User data to refer to the latest texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. - ImTextureData* TexData; // Current texture ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! bool Locked; // Marked as locked during ImGui::NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert. bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context. @@ -3622,10 +3646,8 @@ struct ImFontAtlas ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->SourceID - ImVector DrawListSharedDatas; - - // [Internal] Font builder - ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public + ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. + ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. const ImFontLoader* FontLoader; // Font loader opaque interface (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). Don't set directly! const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name void* FontLoaderData; // Font backend opaque storage @@ -3717,7 +3739,7 @@ struct ImFont IMGUI_API ImFontBaked* GetFontBaked(float font_size); // Get or create baked data for given size IMGUI_API bool IsGlyphInFont(ImWchar c); bool IsLoaded() const { return ContainerAtlas != NULL; } - const char* GetDebugName() const { return Sources ? Sources[0].Name : ""; } + const char* GetDebugName() const { return Sources ? Sources[0].Name : ""; } // Fill ImFontConfig::Name. // [Internal] Don't use! // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 43c3cf9db..dda817eb8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1777,13 +1777,12 @@ static void DemoWindowWidgetsImages() "Hover the texture for a zoomed view!"); // Below we are displaying the font texture because it is the only texture we have access to inside the demo! - // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that - // will be passed to the rendering backend via the ImDrawCmd structure. + // Read description about ImTextureID/ImTextureRef and FAQ for details about texture identifiers. // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top - // of their respective source file to specify what they expect to be stored in ImTextureID, for example: - // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer + // of their respective source file to specify what they are using as texture identifier, for example: + // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer. // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. - // More: + // So with the DirectX11 backend, you call ImGui::Image() with a 'ID3D11ShaderResourceView*' cast to ImTextureID. // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers // to ImGui::Image(), and gather width/height through your own functions, etc. // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, @@ -1791,14 +1790,19 @@ static void DemoWindowWidgetsImages() // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + + // Grab the current texture identifier used by the font atlas. ImTextureRef my_tex_id = io.Fonts->TexRef; + + // Regular user code should never have to care about TexData-> fields, but since we want to display the entire texture here, we pull Width/Height from it. float my_tex_w = (float)io.Fonts->TexData->Width; float my_tex_h = (float)io.Fonts->TexData->Height; + { ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); ImVec2 pos = ImGui::GetCursorScreenPos(); - ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left - ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right + ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left + ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right ImGui::PushStyleVar(ImGuiStyleVar_ImageBorderSize, IM_MAX(1.0f, ImGui::GetStyle().ImageBorderSize)); ImGui::ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); if (ImGui::BeginItemTooltip()) From a548cd9934e4064b9eb4c7565973499fc5357fa0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Mar 2025 15:00:13 +0100 Subject: [PATCH 0991/2359] Fonts: avoid both ImTextureRef fields being set simultaneously. --- imgui.h | 5 +++-- imgui_draw.cpp | 6 ++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/imgui.h b/imgui.h index f8e5b6c55..320f4f1c1 100644 --- a/imgui.h +++ b/imgui.h @@ -3426,7 +3426,7 @@ struct IMGUI_API ImTextureData unsigned char* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } int GetPitch() const { return Width * BytesPerPixel; } - ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = TexID; return tex_ref; } // FIXME-TEXREF + ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = ImTextureID_Invalid; return tex_ref; } ImTextureID GetTexID() const { return TexID; } // Called by Renderer backend @@ -3761,6 +3761,7 @@ struct ImFont // We added an indirection to avoid patching ImDrawCmd after texture updates but this could be a solution too. inline ImTextureID ImTextureRef::GetTexID() const { + IM_ASSERT(!(_TexData != NULL && _TexID != ImTextureID_Invalid)); return _TexData ? _TexData->TexID : _TexID; } @@ -3768,7 +3769,7 @@ inline ImTextureID ImDrawCmd::GetTexID() const { // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92) // must iterate and handle ImTextureData requests stored in ImDrawData::Textures[]. - ImTextureID tex_id = TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID; + ImTextureID tex_id = TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID; // == TexRef.GetTexID() above. if (TexRef._TexData != NULL) IM_ASSERT(tex_id != ImTextureID_Invalid && "ImDrawCmd is referring to ImTextureData that wasn't uploaded to graphics system. Backend must call ImTextureData::SetTexID() after handling ImTextureStatus_WantCreate request!"); return tex_id; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index fa15be25e..8ecc2ecdb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2615,7 +2615,6 @@ ImFontAtlas::ImFontAtlas() TexMaxWidth = 8192; TexMaxHeight = 8192; RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. - TexRef._TexData = NULL;// this; TexNextUniqueID = 1; FontNextUniqueID = 1; Builder = NULL; @@ -3882,9 +3881,8 @@ static void ImFontAtlasBuildSetTexture(ImFontAtlas* atlas, ImTextureData* tex) atlas->TexData = tex; atlas->TexUvScale = ImVec2(1.0f / tex->Width, 1.0f / tex->Height); atlas->TexRef._TexData = tex; - //atlas->TexID._TexID = tex->TexID; // <-- We intentionally don't do that and leave it 0, to allow late upload. - ImTextureRef new_tex_ref = atlas->TexRef; - ImFontAtlasUpdateDrawListsTextures(atlas, old_tex_ref, new_tex_ref); + //atlas->TexRef._TexID = tex->TexID; // <-- We intentionally don't do that. It would be misleading and betray promise that both fields aren't set. + ImFontAtlasUpdateDrawListsTextures(atlas, old_tex_ref, atlas->TexRef); } // Create a new texture, discard previous one From cb4c03756a825516f66ddd6e981ef284ab6a20ba Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Mar 2025 19:57:03 +0100 Subject: [PATCH 0992/2359] Fonts: detect if backend assign to texture on creation but doesn't update Status. --- imgui_draw.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8ecc2ecdb..991b45f8d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2765,10 +2765,12 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count) tex->UpdateRect.x = tex->UpdateRect.y = (unsigned short)~0; tex->UpdateRect.w = tex->UpdateRect.h = 0; } + if (tex->Status == ImTextureStatus_WantCreate && atlas->RendererHasTextures) + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture's TexID/BackendUserData but did not update Status to OK."); if (tex->Status == ImTextureStatus_Destroyed) { - IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!"); if (tex->WantDestroyNextFrame) remove_from_list = true; // Destroy was scheduled by us else From 5460903f9674b9ed8fb31802f44032ca1cdff7aa Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Mar 2025 20:12:02 +0100 Subject: [PATCH 0993/2359] Fonts: awkwardly alias old TexID name to TexRef using an union (may backtrack and just keep old name) --- imgui.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 320f4f1c1..a04ac423a 100644 --- a/imgui.h +++ b/imgui.h @@ -3627,9 +3627,10 @@ struct ImFontAtlas void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). // Output - ImTextureRef TexRef; // Current texture identifier == TexData->GetTexRef(). #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImTextureRef& TexID = TexRef; // RENAMED in 1.92.x + union { ImTextureRef TexRef; ImTextureRef TexID; }; // Current texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.x +#else + ImTextureRef TexRef; // Current texture identifier == TexData->GetTexRef(). #endif ImTextureData* TexData; // Current texture. From 2de15dc64bd3e6a3d4fc1746721b97b2cf6ef11b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Mar 2025 15:44:35 +0100 Subject: [PATCH 0994/2359] Fonts: fixed legacy backend path preloading all sources sizes erroneously + failing to use ellipsis. --- imgui_draw.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 991b45f8d..e23431584 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3383,16 +3383,22 @@ void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas) { atlas->Builder->PreloadedAllGlyphsRanges = true; for (ImFont* font : atlas->Fonts) + { + ImFontConfig* src = &font->Sources[0]; + ImFontBaked* baked = font->GetFontBaked(src->SizePixels); + if (font->FallbackChar != 0) + baked->FindGlyph(font->FallbackChar); + if (font->EllipsisChar != 0) + baked->FindGlyph(font->EllipsisChar); for (int src_n = 0; src_n < font->SourcesCount; src_n++) { - ImFontConfig* src = &font->Sources[src_n]; - ImFontBaked* baked = font->GetFontBaked(src->SizePixels); + src = &font->Sources[src_n]; const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault(); - IM_ASSERT(ranges != NULL); for (; ranges[0]; ranges += 2) for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 baked->FindGlyph((ImWchar)c); } + } } void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) From 168b97c2912e7261bd26af09619cc1a60bc05954 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Mar 2025 15:45:27 +0100 Subject: [PATCH 0995/2359] Fonts: removed size rounding in AddFont() which breaks relative sizing of merged fonts (8502) # Conflicts: # imgui.cpp --- imgui.cpp | 7 ++++++- imgui_draw.cpp | 12 ++++++------ imgui_internal.h | 1 + 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0e5a4c775..334ace32c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8628,7 +8628,12 @@ void ImGui::UpdateCurrentFontSize() final_size *= g.Font->Scale; if (ImGuiWindow* window = g.CurrentWindow) final_size *= window->FontWindowScale; - final_size = ImMax(1.0f, IM_ROUND(final_size)); + + // Round font size + // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. + // - We may support it better later and remove this rounding. + final_size = GetRoundedFontSize(final_size); + final_size = ImMax(1.0f, final_size); g.FontSize = final_size; g.FontBaked = (g.Font != NULL) ? g.Font->GetFontBaked(g.FontSize) : NULL; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e23431584..db95fd14d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3024,6 +3024,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) } // Sanity check + // We don't round cfg.SizePixels yet as relative size of merged fonts are used afterwards. if (font_cfg->GlyphExcludeRanges != NULL) { int size = 0; @@ -3039,12 +3040,6 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) } IM_ASSERT(font_cfg->FontLoaderData == NULL); - // Round font size - // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. - // - Note that using io.FontGlobalScale or SetWindowFontScale(), with are legacy-ish, partially supported features, can still lead to unrounded sizes. - // - We may support it better later and remove this rounding. - new_font_cfg.SizePixels = ImTrunc(new_font_cfg.SizePixels); - // Pointers to Sources are otherwise dangling ImFontAtlasBuildUpdatePointers(this); if (!ImFontAtlasBuildAddFont(this, &new_font_cfg)) @@ -5164,6 +5159,11 @@ ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size) ImFontBaked* ImFont::GetFontBaked(float size) { ImFontBaked* baked = LastBaked; + + // Round font size + // - ImGui::PushFontSize() will already round, but other paths calling GetFontBaked() directly also needs it (e.g. ImFontAtlasBuildPreloadAllGlyphRanges) + size = ImGui::GetRoundedFontSize(size); + if (baked && baked->Size == size) return baked; diff --git a/imgui_internal.h b/imgui_internal.h index 83a16aa9d..6c46fde5c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3111,6 +3111,7 @@ namespace ImGui // Fonts, drawing IMGUI_API void SetCurrentFont(ImFont* font, float font_size); IMGUI_API void UpdateCurrentFontSize(); + inline float GetRoundedFontSize(float size) { return IM_ROUND(size); } inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } IMGUI_API void PushPasswordFont(); IMGUI_API void PopPasswordFont(); From 44498825cd9a5bf8c3f2e7c5b4bb439b537fb91e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Mar 2025 19:13:23 +0100 Subject: [PATCH 0996/2359] (Breaking) Fonts: PushFont() default to preserve current font size. --- imgui.cpp | 11 ++++++++--- imgui.h | 12 +++++++++--- imgui_draw.cpp | 3 ++- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 334ace32c..20ebdc56a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8582,7 +8582,7 @@ void ImGui::UpdateFontsNewFrame() atlas->Locked = true; // We do this really unusual thing of calling *push_front()*, the reason behind that we want to support the PushFont()/NewFrame()/PopFont() idiom. - ImFontStackData font_stack_data = { ImGui::GetDefaultFont(), ImGui::GetDefaultFont()->Sources[0].SizePixels }; + ImFontStackData font_stack_data = { ImGui::GetDefaultFont(), ImGui::GetDefaultFont()->DefaultSize }; g.FontStack.push_front(font_stack_data); if (g.FontStack.Size == 1) ImGui::SetCurrentFont(font_stack_data.Font, font_stack_data.FontSize); @@ -8647,8 +8647,13 @@ void ImGui::PushFont(ImFont* font, float font_size) ImGuiContext& g = *GImGui; if (font == NULL) font = GetDefaultFont(); - if (font_size < 0.0f) - font_size = font->Sources[0].SizePixels; // g.FontSize; + if (font_size <= 0.0f) + { + if (font->Flags & ImFontFlags_UseDefaultSize) + font_size = font->DefaultSize; // Legacy: use default font size. Same as doing PushFont(font, font->DefaultSize). // FIXME-NEWATLAS + else + font_size = g.FontSizeBeforeScaling; // Keep current font size + } g.FontStack.push_back({ font, font_size }); SetCurrentFont(font, font_size); } diff --git a/imgui.h b/imgui.h index a04ac423a..5e1737a5d 100644 --- a/imgui.h +++ b/imgui.h @@ -491,9 +491,13 @@ namespace ImGui IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. // Parameters stacks (font) - IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. + // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. + // - Before 1.92: PushFont() always used font default size. + // - Since 1.92: PushFont() preserve the current shared font size. + // - To use old behavior: use 'PushFont(font, font->DefaultSize)' in call site, or set 'ImFontConfig::Flags |= ImFontFlags_UseDefaultSize' before calling AddFont(). + IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. Use font->DefaultSize to revert to font default size. IMGUI_API void PopFont(); - IMGUI_API void PushFontSize(float size); + IMGUI_API void PushFontSize(float font_size); IMGUI_API void PopFontSize(); // Parameters stacks (shared) @@ -3709,6 +3713,7 @@ enum ImFontFlags_ ImFontFlags_LockBakedSizes = 1 << 0, // Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. ImFontFlags_NoLoadGlyphs = 1 << 1, // Disable loading new glyphs. ImFontFlags_NoLoadError = 1 << 2, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. + ImFontFlags_UseDefaultSize = 1 << 3, // Legacy compatibility: make PushFont() calls without explicit size use font->DefaultSize instead of current font size. }; // Font runtime data and rendering @@ -3726,6 +3731,7 @@ struct ImFont // [Internal] Members: Cold ~24-52 bytes // Conceptually Sources[] is the list of font sources merged to create this font. ImGuiID FontId; // Unique identifier for the font + float DefaultSize; // 4 // in // Default font size short SourcesCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). @@ -3750,7 +3756,7 @@ struct ImFont 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, bool cpu_fine_clip = false); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(Sources[0].SizePixels * scale, text, text_end, wrap_width); } + inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(DefaultSize * scale, text, text_end, wrap_width); } #endif // [Internal] Don't use! diff --git a/imgui_draw.cpp b/imgui_draw.cpp index db95fd14d..4a7bff240 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3005,6 +3005,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) font = IM_NEW(ImFont)(); font->FontId = FontNextUniqueID++; font->Flags = font_cfg->Flags; + font->DefaultSize = font_cfg->SizePixels; Fonts.push_back(font); } else @@ -3248,7 +3249,7 @@ int ImFontAtlas::AddCustomRectRegular(int width, int height) // myfont->Flags |= ImFontFlags_LockBakedSizes; int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) { - float font_size = font->Sources[0].SizePixels; + float font_size = font->DefaultSize; return AddCustomRectFontGlyphForSize(font, font_size, codepoint, width, height, advance_x, offset); } // FIXME: we automatically set glyph.Colored=true by default. From 9324961cd28bb2690a6f9867ba098c771750769c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Mar 2025 14:38:49 +0100 Subject: [PATCH 0997/2359] Fonts: fixed calling AddFontXXX not invalidating texture for legacy backends. --- imgui_draw.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4a7bff240..8535c32c2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3580,6 +3580,7 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) if (!loader->FontSrcInit(atlas, src)) return false; + atlas->TexIsBuilt = false; // For legacy backends ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); return true; } From fc870811333e4d6d2d8f0e78e26247762020d5f4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 22 Mar 2025 15:15:10 +0100 Subject: [PATCH 0998/2359] Fonts: fixed GetCustomRectUV(). Fixing typo. Broken by fe598f7 --- imgui_draw.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8535c32c2..fe639e99b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2501,7 +2501,7 @@ void ImTextureData::DestroyPixels() // - ImFontAtlas::AddCustomRectRegular() // - ImFontAtlas::AddCustomRectFontGlyph() // - ImFontAtlas::GetCustomRect() -// - ImFontAtlas::CalcCustomRectUV() +// - ImFontAtlas::GetCustomRectUV() // - ImFontAtlasGetMouseCursorTexData() //----------------------------------------------------------------------------- // - ImFontAtlasBuildMain() @@ -3298,8 +3298,10 @@ const ImTextureRect* ImFontAtlas::GetCustomRect(int id) void ImFontAtlas::GetCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const { IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates - *out_uv_min = ImVec2((float)rect->x * TexUvScale.x, (float)rect->y * TexUvScale.y); - *out_uv_max = ImVec2((float)(rect->x + rect->w) * TexUvScale.x, (float)(rect->y + rect->w) * TexUvScale.y); + ImVec2 pos = ImVec2((float)rect->x, (float)rect->y); + ImVec2 size = ImVec2((float)rect->w, (float)rect->h); + *out_uv_min = (pos) * TexUvScale; + *out_uv_max = (pos + size) * TexUvScale; } bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) From 253dff76565b10491ccc2205706b033bb7f209af Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 30 Mar 2025 16:00:29 +0200 Subject: [PATCH 0999/2359] Fonts: Comments. --- imgui.h | 41 +++++++++++++++++++++++------------------ imgui_internal.h | 2 +- 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/imgui.h b/imgui.h index 5e1737a5d..ae488a177 100644 --- a/imgui.h +++ b/imgui.h @@ -3484,9 +3484,9 @@ struct ImFontGlyph unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. unsigned int Codepoint : 30; // 0x0000..0x10FFFF - float AdvanceX; // Horizontal distance to advance layout with - float X0, Y0, X1, Y1; // Glyph corners - float U0, V0, U1, V1; // Texture coordinates + float AdvanceX; // Horizontal distance to advance cursor/layout position. + float X0, Y0, X1, Y1; // Glyph corners. Offsets from current cursor/layout position. + float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRectUV() with PackId. int PackId; // [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) ImFontGlyph() { memset(this, 0, sizeof(*this)); PackId = -1; } @@ -3600,21 +3600,23 @@ struct ImFontAtlas // Register and retrieve custom rectangles // - You can request arbitrary rectangles to be packed into the atlas, for your own purpose. - // - You can request your rectangles to be mapped as font glyph (given a font + Unicode point), - // so you can render e.g. custom colorful icons and use them as regular glyphs. - // - Since 1.92.X, packing is done immediately in the function call. - // - You can render your pixels into the texture right after calling the AddCustomRectXXX() functions. + // - Since 1.92.X, packing is done immediately in the function call (previously packing was done during the Build call) + // - You can render your pixels into the texture right after calling the AddCustomRect() functions. // - Texture may be resized, so you cannot cache UV coordinates: always use GetCustomRectUV()! - // - If you render colored output into your AddCustomRectRegular() rectangle: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. + // VERY IMPORTANT: + // - RECTANGLE DATA AND UV COORDINATES MAY BE INVALIDATED BY *ANY* CALL TO IMGUI FUNCTIONS (e.g. ImGui::Text call) OR BY atlas->AddCustomRectegular(). NEVER CACHE THOSE!!! + // - RECTANGLE DATA AND UV COORDINATES ARE ASSOCIATED TO THE CURRENT TEXTURE IDENTIFIER AKA 'atlas->TexRef'. Both are typically invalidated at the same time. + // - If you render colored output into your AddCustomRect() rectangle: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. // - Read docs/FONTS.md for more details about using colorful icons. // - Note: this API may be reworked further in order to facilitate supporting e.g. multi-monitor, varying DPI settings. - // - Pre-1.92 names: - // - AddCustomRectFontGlyph() --> Use custom ImFontLoader inside ImFontConfig + // - (Pre-1.92 names) ------------> (1.92 names) // - GetCustomRectByIndex() --> Use GetCustomRect() // - CalcCustomRectUV() --> Use GetCustomRectUV() + // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig + // - ImFontAtlasCustomRect --> ImTextureRect IMGUI_API int AddCustomRectRegular(int width, int height); // Register a rectangle. Return -1 on error. - IMGUI_API const ImTextureRect* GetCustomRect(int id); // Get rectangle coordinate in current texture. - IMGUI_API void GetCustomRectUV(const ImTextureRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const; // Get UV coordinates for a given rectangle + IMGUI_API const ImTextureRect* GetCustomRect(int id); // Get rectangle coordinate in current texture. Valid immediately, never store this (read above)! + IMGUI_API void GetCustomRectUV(const ImTextureRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const; // Get UV coordinates for a given rectangle. Valid immediately, never store this (read above)! //------------------------------------------- // Members @@ -3631,12 +3633,14 @@ struct ImFontAtlas void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). // Output -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - union { ImTextureRef TexRef; ImTextureRef TexID; }; // Current texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.x + // - Because textures are dynamically created/resized, the current texture identifier may changed at *ANY TIME* during the frame. + // - This should not affect you as you can always use the latest value. But note that any precomputed UV coordinates are only valid for the current TexRef. +#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImTextureRef TexRef; // Latest texture identifier == TexData->GetTexRef(). #else - ImTextureRef TexRef; // Current texture identifier == TexData->GetTexRef(). + union { ImTextureRef TexRef; ImTextureRef TexID; }; // Latest texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.x #endif - ImTextureData* TexData; // Current texture. + ImTextureData* TexData; // Latest texture. // [Internal] ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! @@ -3644,8 +3648,8 @@ struct ImFontAtlas bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context. bool TexIsBuilt; // Set when texture was built matching current font input. Mostly useful for legacy IsBuilt() call. bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. - ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight) - ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight). May change as new texture gets created. + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines @@ -3661,6 +3665,7 @@ struct ImFontAtlas // [Obsolete] #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X inline const ImTextureRect* GetCustomRectByIndex(int id) { return GetCustomRect(id); } // OBSOLETED in 1.92.X diff --git a/imgui_internal.h b/imgui_internal.h index 6c46fde5c..aa5da5777 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3695,7 +3695,7 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); //----------------------------------------------------------------------------- // An identifier to a rectangle in the atlas. -1 when invalid. -// The rectangle may move, use GetCustomRect() to retrieve it. +// The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it. typedef int ImFontAtlasRectId; // Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) From f40274702dcf15985c257b6b32677bfe7bae1595 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 17:03:03 +0200 Subject: [PATCH 1000/2359] (Breaking) Fonts: renamed AddCustomRectRegular() -> AddCustomRect(). --- imgui.h | 4 +++- imgui_draw.cpp | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index ae488a177..cbf353dd8 100644 --- a/imgui.h +++ b/imgui.h @@ -3612,9 +3612,10 @@ struct ImFontAtlas // - (Pre-1.92 names) ------------> (1.92 names) // - GetCustomRectByIndex() --> Use GetCustomRect() // - CalcCustomRectUV() --> Use GetCustomRectUV() + // - AddCustomRectRegular() --> Renamed to AddCustomRect() // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig // - ImFontAtlasCustomRect --> ImTextureRect - IMGUI_API int AddCustomRectRegular(int width, int height); // Register a rectangle. Return -1 on error. + IMGUI_API int AddCustomRect(int width, int height); // Register a rectangle. Return -1 on error. IMGUI_API const ImTextureRect* GetCustomRect(int id); // Get rectangle coordinate in current texture. Valid immediately, never store this (read above)! IMGUI_API void GetCustomRectUV(const ImTextureRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const; // Get UV coordinates for a given rectangle. Valid immediately, never store this (read above)! @@ -3666,6 +3667,7 @@ struct ImFontAtlas // [Obsolete] #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. + IMGUI_API int AddCustomRectRegular(int width, int height) { return AddCustomRect(width, height); } // RENAMED in 1.92.X IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X inline const ImTextureRect* GetCustomRectByIndex(int id) { return GetCustomRect(id); } // OBSOLETED in 1.92.X diff --git a/imgui_draw.cpp b/imgui_draw.cpp index fe639e99b..0a39cfabe 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2498,7 +2498,7 @@ void ImTextureData::DestroyPixels() // - ImFontAtlas::RemoveFont() // - ImFontAtlasBuildNotifySetFont() //----------------------------------------------------------------------------- -// - ImFontAtlas::AddCustomRectRegular() +// - ImFontAtlas::AddCustomRect() // - ImFontAtlas::AddCustomRectFontGlyph() // - ImFontAtlas::GetCustomRect() // - ImFontAtlas::GetCustomRectUV() @@ -3223,7 +3223,7 @@ void ImFontAtlas::RemoveFont(ImFont* font) ImFontAtlasBuildNotifySetFont(this, font, new_current_font); } -int ImFontAtlas::AddCustomRectRegular(int width, int height) +int ImFontAtlas::AddCustomRect(int width, int height) { IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); From db30e1b5b6d55423a967fe6b6947bf6296f08786 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 17:36:24 +0200 Subject: [PATCH 1001/2359] (Breaking) Fonts: rework GetCustomRect() api. Reintroduce ImFontAtlasRect. --- imgui.h | 48 ++++++++++++++++++++++++++++++------------------ imgui_draw.cpp | 22 +++++++++++----------- 2 files changed, 41 insertions(+), 29 deletions(-) diff --git a/imgui.h b/imgui.h index cbf353dd8..fbd9d5b6c 100644 --- a/imgui.h +++ b/imgui.h @@ -172,6 +172,7 @@ struct ImDrawVert; // A single vertex (pos + uv + col = 20 byte struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader struct ImFontAtlasBuilder; // Opaque storage for building a ImFontAtlas +struct ImFontAtlasRect; // Output of ImFontAtlas::GetCustomRect() when using custom rectangles. struct ImFontBaked; // Baked data for a ImFont at a given size. struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) @@ -3486,7 +3487,7 @@ struct ImFontGlyph unsigned int Codepoint : 30; // 0x0000..0x10FFFF float AdvanceX; // Horizontal distance to advance cursor/layout position. float X0, Y0, X1, Y1; // Glyph corners. Offsets from current cursor/layout position. - float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRectUV() with PackId. + float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. int PackId; // [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) ImFontGlyph() { memset(this, 0, sizeof(*this)); PackId = -1; } @@ -3508,6 +3509,17 @@ struct ImFontGlyphRangesBuilder IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges }; +// Output of ImFontAtlas::GetCustomRect() when using custom rectangles. +// Those values may not be cached/stored as they are only valid for the current value of atlas->TexRef +struct ImFontAtlasRect +{ + unsigned short x, y; // Position (in current texture) + unsigned short w, h; // Size + ImVec2 uv0, uv1; // UV coordinates (in current texture) + + ImFontAtlasRect() { memset(this, 0, sizeof(*this)); } +}; + // Flags for ImFontAtlas build enum ImFontAtlasFlags_ { @@ -3602,22 +3614,21 @@ struct ImFontAtlas // - You can request arbitrary rectangles to be packed into the atlas, for your own purpose. // - Since 1.92.X, packing is done immediately in the function call (previously packing was done during the Build call) // - You can render your pixels into the texture right after calling the AddCustomRect() functions. - // - Texture may be resized, so you cannot cache UV coordinates: always use GetCustomRectUV()! - // VERY IMPORTANT: - // - RECTANGLE DATA AND UV COORDINATES MAY BE INVALIDATED BY *ANY* CALL TO IMGUI FUNCTIONS (e.g. ImGui::Text call) OR BY atlas->AddCustomRectegular(). NEVER CACHE THOSE!!! - // - RECTANGLE DATA AND UV COORDINATES ARE ASSOCIATED TO THE CURRENT TEXTURE IDENTIFIER AKA 'atlas->TexRef'. Both are typically invalidated at the same time. - // - If you render colored output into your AddCustomRect() rectangle: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. + // - VERY IMPORTANT: + // - Texture may be created/resized at any time when calling ImGui or ImFontAtlas functions. + // - IT WILL INVALIDATE RECTANGLE DATA SUCH AS UV COORDINATES. Always use latest values from GetCustomRect(). + // - UV coordinates are associated to the current texture identifier aka 'atlas->TexRef'. Both TexRef and UV coordinates are typically changed at the same time. + // - If you render colored output into your custom rectangles: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. // - Read docs/FONTS.md for more details about using colorful icons. // - Note: this API may be reworked further in order to facilitate supporting e.g. multi-monitor, varying DPI settings. // - (Pre-1.92 names) ------------> (1.92 names) // - GetCustomRectByIndex() --> Use GetCustomRect() - // - CalcCustomRectUV() --> Use GetCustomRectUV() + // - CalcCustomRectUV() --> Use GetCustomRect() and read uv0, uv1 fields. // - AddCustomRectRegular() --> Renamed to AddCustomRect() // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig - // - ImFontAtlasCustomRect --> ImTextureRect - IMGUI_API int AddCustomRect(int width, int height); // Register a rectangle. Return -1 on error. - IMGUI_API const ImTextureRect* GetCustomRect(int id); // Get rectangle coordinate in current texture. Valid immediately, never store this (read above)! - IMGUI_API void GetCustomRectUV(const ImTextureRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const; // Get UV coordinates for a given rectangle. Valid immediately, never store this (read above)! + // - ImFontAtlasCustomRect --> Renamed to ImFontAtlasRect + IMGUI_API int AddCustomRect(int width, int height); // Register a rectangle. Return -1 on error. + IMGUI_API bool GetCustomRect(int id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)! //------------------------------------------- // Members @@ -3667,14 +3678,15 @@ struct ImFontAtlas // [Obsolete] #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. - IMGUI_API int AddCustomRectRegular(int width, int height) { return AddCustomRect(width, height); } // RENAMED in 1.92.X - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig - IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X - inline const ImTextureRect* GetCustomRectByIndex(int id) { return GetCustomRect(id); } // OBSOLETED in 1.92.X - inline void CalcCustomRectUV(const ImTextureRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { return GetCustomRectUV(r, out_uv_min, out_uv_max); } // OBSOLETED in 1.92.X + ImFontAtlasRect TempRect; // For old GetCustomRectByIndex() API + inline int AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.X + inline const ImFontAtlasRect* GetCustomRectByIndex(int id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.X + inline void CalcCustomRectUV(const ImFontAtlasRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { *out_uv_min = r->uv0; *out_uv_max = r->uv1; } // OBSOLETED in 1.92.X + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig + IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X #endif //int TexDesiredWidth; // OBSOLETED in 1.92.X (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) - //typedef ImTextureRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X + //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ }; @@ -3996,7 +4008,7 @@ namespace ImGui // - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h // - ImFontAtlasCustomRect::GlyphColored --> if you need to write to this, instead you can write to 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph() // We could make ImTextureRect an union to use old names, but 1) this would be confusing 2) the fix is easy 3) ImFontAtlasCustomRect was always a rather esoteric api. -typedef ImTextureRect ImFontAtlasCustomRect; +typedef ImFontAtlasRect ImFontAtlasCustomRect; /*struct ImFontAtlasCustomRect { unsigned short X, Y; // Output // Packed position in Atlas diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0a39cfabe..f6849701c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2501,7 +2501,6 @@ void ImTextureData::DestroyPixels() // - ImFontAtlas::AddCustomRect() // - ImFontAtlas::AddCustomRectFontGlyph() // - ImFontAtlas::GetCustomRect() -// - ImFontAtlas::GetCustomRectUV() // - ImFontAtlasGetMouseCursorTexData() //----------------------------------------------------------------------------- // - ImFontAtlasBuildMain() @@ -3290,18 +3289,19 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im } #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -const ImTextureRect* ImFontAtlas::GetCustomRect(int id) -{ - return ImFontAtlasPackGetRect(this, (ImFontAtlasRectId)id); -} - -void ImFontAtlas::GetCustomRectUV(const ImTextureRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const +bool ImFontAtlas::GetCustomRect(int id, ImFontAtlasRect* out_r) const { + ImTextureRect* r = ImFontAtlasPackGetRect((ImFontAtlas*)this, (ImFontAtlasRectId)id); + if (r == NULL) + return false; IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates - ImVec2 pos = ImVec2((float)rect->x, (float)rect->y); - ImVec2 size = ImVec2((float)rect->w, (float)rect->h); - *out_uv_min = (pos) * TexUvScale; - *out_uv_max = (pos + size) * TexUvScale; + out_r->x = r->x; + out_r->y = r->y; + out_r->w = r->w; + out_r->h = r->h; + out_r->uv0 = ImVec2((float)(r->x), (float)(r->y)) * TexUvScale; + out_r->uv1 = ImVec2((float)(r->x + r->w), (float)(r->y + r->h)) * TexUvScale; + return true; } bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) From 69d28f867cdc04e2ade221ea14304058fe4055d7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 18:36:32 +0200 Subject: [PATCH 1002/2359] Fonts: added ImFontAtlasRectId_Invalid == -1 --- imgui_draw.cpp | 34 +++++++++++++++++----------------- imgui_internal.h | 1 + 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f6849701c..7556fc593 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3231,8 +3231,8 @@ int ImFontAtlas::AddCustomRect(int width, int height) ImFontAtlasBuildInit(this); ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); - if (r_id == -1) - return -1; + if (r_id == ImFontAtlasRectId_Invalid) + return ImFontAtlasRectId_Invalid; ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); if (RendererHasTextures) ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); @@ -3265,8 +3265,8 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im ImFontBaked* baked = font->GetFontBaked(font_size); ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); - if (r_id == -1) - return -1; + if (r_id == ImFontAtlasRectId_Invalid) + return ImFontAtlasRectId_Invalid; ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); if (RendererHasTextures) ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); @@ -3452,7 +3452,7 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ if (add_and_draw) builder->PackIdMouseCursors = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); - if (builder->PackIdMouseCursors == -1) + if (builder->PackIdMouseCursors == ImFontAtlasRectId_Invalid) return; ImTextureRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdMouseCursors); @@ -3488,7 +3488,7 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ ImFontAtlasBuilder* builder = atlas->Builder; if (add_and_draw) builder->PackIdLinesTexData = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); - if (builder->PackIdLinesTexData == -1) + if (builder->PackIdLinesTexData == ImFontAtlasRectId_Invalid) return; ImTextureRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdLinesTexData); @@ -3711,10 +3711,10 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph) { - if (glyph->PackId != -1) + if (glyph->PackId != ImFontAtlasRectId_Invalid) { ImFontAtlasPackDiscardRect(atlas, glyph->PackId); - glyph->PackId = -1; + glyph->PackId = ImFontAtlasRectId_Invalid; } ImWchar c = (ImWchar)glyph->Codepoint; IM_ASSERT(font->FallbackChar != c && font->EllipsisChar != c); // Unsupported for simplicity @@ -3786,7 +3786,7 @@ void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBa IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName()); for (ImFontGlyph& glyph : baked->Glyphs) - if (glyph.PackId != -1) + if (glyph.PackId != ImFontAtlasRectId_Invalid) ImFontAtlasPackDiscardRect(atlas, glyph.PackId); char* loader_data_p = (char*)baked->FontLoaderDatas; @@ -3974,7 +3974,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) if (old_r.w == 0 && old_r.h == 0) continue; ImFontAtlasRectId new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, &index_entry); - if (new_r_id == -1) + if (new_r_id == ImFontAtlasRectId_Invalid) { // Undo, grow texture and try repacking again. // FIXME-NEWATLAS-TESTS: This is a very rarely exercised path! It needs to be automatically tested properly. @@ -3997,7 +3997,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) // Patch glyphs UV for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) for (ImFontGlyph& glyph : builder->BakedPool[baked_n].Glyphs) - if (glyph.PackId != -1) + if (glyph.PackId != ImFontAtlasRectId_Invalid) { ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); glyph.U0 = (r->x) * atlas->TexUvScale.x; @@ -4240,7 +4240,7 @@ static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int r // This is expected to be called in batches and followed by a repack void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { - IM_ASSERT(id != -1); + IM_ASSERT(id != ImFontAtlasRectId_Invalid); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; IM_ASSERT(index_entry->Used && index_entry->TargetIndex >= 0); @@ -4286,7 +4286,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon if (attempts_remaining == 0 || builder->LockDisableResize) { IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.\n", w, h); - return -1; + return ImFontAtlasRectId_Invalid; } // Resize or repack atlas! (this should be a rare event) @@ -4315,7 +4315,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon // Important: don'return pointer valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { - IM_ASSERT(id != -1); + IM_ASSERT(id != ImFontAtlasRectId_Invalid); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; IM_ASSERT(index_entry->Used); @@ -4546,10 +4546,10 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, const int w = (x1 - x0 + oversample_h - 1); const int h = (y1 - y0 + oversample_v - 1); ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); - if (pack_id == -1) + if (pack_id == ImFontAtlasRectId_Invalid) { // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) - IM_ASSERT_USER_ERROR(pack_id != -1, "Out of texture memory."); + IM_ASSERT_USER_ERROR(pack_id != ImFontAtlasRectId_Invalid, "Out of texture memory."); return NULL; } ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); @@ -4998,7 +4998,7 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked IM_ASSERT(baked->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. // Set UV from packed rectangle - if (in_glyph->PackId != -1) + if (in_glyph->PackId != ImFontAtlasRectId_Invalid) { ImTextureRect* r = ImFontAtlasPackGetRect(atlas, in_glyph->PackId); IM_ASSERT(in_glyph->U0 == 0.0f && in_glyph->V0 == 0.0f && in_glyph->U1 == 0.0f && in_glyph->V1 == 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index aa5da5777..a064a8dab 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3697,6 +3697,7 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // An identifier to a rectangle in the atlas. -1 when invalid. // The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it. typedef int ImFontAtlasRectId; +#define ImFontAtlasRectId_Invalid -1 // Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) // User are returned ImFontAtlasRectId values which are meant to be persistent. From e9cf3de58ff7e53e82d08bfd2dc7615bcb8a002e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 18:37:11 +0200 Subject: [PATCH 1003/2359] Fonts: moved ImFontAtlasRectId back to public API. --- imgui.h | 18 ++++++++++++------ imgui_draw.cpp | 6 +++--- imgui_internal.h | 5 ----- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/imgui.h b/imgui.h index fbd9d5b6c..ce5decfa4 100644 --- a/imgui.h +++ b/imgui.h @@ -3509,8 +3509,14 @@ struct ImFontGlyphRangesBuilder IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges }; +// An identifier to a rectangle in the atlas. -1 when invalid. +// The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it. +typedef int ImFontAtlasRectId; +#define ImFontAtlasRectId_Invalid -1 + // Output of ImFontAtlas::GetCustomRect() when using custom rectangles. // Those values may not be cached/stored as they are only valid for the current value of atlas->TexRef +// (this is in theory derived from ImTextureRect but we use separate structures for reasons) struct ImFontAtlasRect { unsigned short x, y; // Position (in current texture) @@ -3627,8 +3633,8 @@ struct ImFontAtlas // - AddCustomRectRegular() --> Renamed to AddCustomRect() // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig // - ImFontAtlasCustomRect --> Renamed to ImFontAtlasRect - IMGUI_API int AddCustomRect(int width, int height); // Register a rectangle. Return -1 on error. - IMGUI_API bool GetCustomRect(int id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)! + IMGUI_API ImFontAtlasRectId AddCustomRect(int width, int height); // Register a rectangle. Return -1 (ImFontAtlasRectId_Invalid) on error. + IMGUI_API bool GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)! //------------------------------------------- // Members @@ -3679,11 +3685,11 @@ struct ImFontAtlas #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. ImFontAtlasRect TempRect; // For old GetCustomRectByIndex() API - inline int AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.X - inline const ImFontAtlasRect* GetCustomRectByIndex(int id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.X + inline ImFontAtlasRectId AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.X + inline const ImFontAtlasRect* GetCustomRectByIndex(ImFontAtlasRectId id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.X inline void CalcCustomRectUV(const ImFontAtlasRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { *out_uv_min = r->uv0; *out_uv_max = r->uv1; } // OBSOLETED in 1.92.X - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig - IMGUI_API int AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X + IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig + IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X #endif //int TexDesiredWidth; // OBSOLETED in 1.92.X (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7556fc593..83db3576b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3222,7 +3222,7 @@ void ImFontAtlas::RemoveFont(ImFont* font) ImFontAtlasBuildNotifySetFont(this, font, new_current_font); } -int ImFontAtlas::AddCustomRect(int width, int height) +ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height) { IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); @@ -3289,9 +3289,9 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im } #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -bool ImFontAtlas::GetCustomRect(int id, ImFontAtlasRect* out_r) const +bool ImFontAtlas::GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const { - ImTextureRect* r = ImFontAtlasPackGetRect((ImFontAtlas*)this, (ImFontAtlasRectId)id); + ImTextureRect* r = ImFontAtlasPackGetRect((ImFontAtlas*)this, id); if (r == NULL) return false; IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates diff --git a/imgui_internal.h b/imgui_internal.h index a064a8dab..7389c0216 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3694,11 +3694,6 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- -// An identifier to a rectangle in the atlas. -1 when invalid. -// The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it. -typedef int ImFontAtlasRectId; -#define ImFontAtlasRectId_Invalid -1 - // Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) // User are returned ImFontAtlasRectId values which are meant to be persistent. // We handle this with an indirection. While Rects[] may be in theory shuffled, compacted etc., RectsIndex[] cannot it is keyed by ImFontAtlasRectId. From 23dc46c4f8bf6aaf83d70f54441916404bf1aba5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 19:24:59 +0200 Subject: [PATCH 1004/2359] Fonts: added RemoveCustomRect(). + internally add ImFontAtlasPackReuseRectEntry() --- imgui.h | 1 + imgui_draw.cpp | 29 +++++++++++++++++++---------- imgui_internal.h | 4 ++-- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/imgui.h b/imgui.h index ce5decfa4..a3d70bb98 100644 --- a/imgui.h +++ b/imgui.h @@ -3634,6 +3634,7 @@ struct ImFontAtlas // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig // - ImFontAtlasCustomRect --> Renamed to ImFontAtlasRect IMGUI_API ImFontAtlasRectId AddCustomRect(int width, int height); // Register a rectangle. Return -1 (ImFontAtlasRectId_Invalid) on error. + IMGUI_API void RemoveCustomRect(ImFontAtlasRectId id); // Unregister a rectangle. Existing pixels will stay in texture until resized / garbage collected. IMGUI_API bool GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)! //------------------------------------------- diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 83db3576b..7cc1351fb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2499,8 +2499,10 @@ void ImTextureData::DestroyPixels() // - ImFontAtlasBuildNotifySetFont() //----------------------------------------------------------------------------- // - ImFontAtlas::AddCustomRect() -// - ImFontAtlas::AddCustomRectFontGlyph() +// - ImFontAtlas::RemoveCustomRect() // - ImFontAtlas::GetCustomRect() +// - ImFontAtlas::AddCustomRectFontGlyph() [legacy] +// - ImFontAtlas::AddCustomRectFontGlyphForSize() [legacy] // - ImFontAtlasGetMouseCursorTexData() //----------------------------------------------------------------------------- // - ImFontAtlasBuildMain() @@ -2538,6 +2540,7 @@ void ImTextureData::DestroyPixels() //----------------------------------------------------------------------------- // - ImFontAtlasPackInit() // - ImFontAtlasPackAllocRectEntry() +// - ImFontAtlasPackReuseRectEntry() // - ImFontAtlasPackDiscardRect() // - ImFontAtlasPackAddRect() // - ImFontAtlasPackGetRect() @@ -3239,6 +3242,12 @@ ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height) return r_id; } +void ImFontAtlas::RemoveCustomRect(ImFontAtlasRectId id) +{ + IM_ASSERT(id != ImFontAtlasRectId_Invalid); + ImFontAtlasPackDiscardRect(this, id); +} + #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // This API does not make sense anymore with scalable fonts. // - Prefer adding a font source (ImFontConfig) using a custom/procedural loader. @@ -4095,7 +4104,7 @@ ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) return ImVec2i(new_tex_w, new_tex_h); } -// Clear all output. Invalidates all AddCustomRectXXX return values. +// Clear all output. Invalidates all AddCustomRect() return values! void ImFontAtlasBuildClear(ImFontAtlas* atlas) { ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); @@ -4237,6 +4246,13 @@ static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int r return (ImFontAtlasRectId)index_idx; } +static ImFontAtlasRectId ImFontAtlasPackReuseRectEntry(ImFontAtlas* atlas, ImFontAtlasRectEntry* overwrite_entry) +{ + IM_ASSERT(overwrite_entry->Used); + overwrite_entry->TargetIndex = atlas->Builder->Rects.Size - 1; + return atlas->Builder->RectsIndex.index_from_ptr(overwrite_entry); +} + // This is expected to be called in batches and followed by a repack void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { @@ -4300,16 +4316,9 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon builder->Rects.push_back(r); if (overwrite_entry != NULL) - { - // Write into an existing entry instead of adding one (used during repack) - IM_ASSERT(overwrite_entry->Used); - overwrite_entry->TargetIndex = builder->Rects.Size - 1; - return builder->RectsIndex.index_from_ptr(overwrite_entry); - } + return ImFontAtlasPackReuseRectEntry(atlas, overwrite_entry); // Write into an existing entry instead of adding one (used during repack) else - { return ImFontAtlasPackAllocRectEntry(atlas, builder->Rects.Size - 1); - } } // Important: don'return pointer valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. diff --git a/imgui_internal.h b/imgui_internal.h index 7389c0216..0a9961a45 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3701,8 +3701,8 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // Having this also makes it easier to e.g. sort rectangles during repack. struct ImFontAtlasRectEntry { - int TargetIndex : 31; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. - unsigned int Used : 1; + int TargetIndex : 31; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. + unsigned int Used : 1; }; // Data available to potential texture post-processing functions From 074bf39e403fd4123b605bd8062624876381e59f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 21:43:15 +0200 Subject: [PATCH 1005/2359] Fonts: GC Compact All exposed in Metrics->Memory Allocations includes compacting texture data. --- imgui.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui.cpp b/imgui.cpp index 20ebdc56a..00bb950fc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4394,6 +4394,7 @@ void ImGui::GcCompactTransientMiscBuffers() g.MultiSelectTempDataStacked = 0; g.MultiSelectTempData.clear_destruct(); TableGcCompactSettings(); + g.IO.Fonts->CompactCache(); } // Free up/compact internal window buffers, we can use this when a window becomes unused. From 1ea9ff36771ef4d77566f4f738404ea20573ea4b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 22:18:42 +0200 Subject: [PATCH 1006/2359] Fonts: add optional out parameter to AddCustomRect() --- imgui.h | 2 +- imgui_draw.cpp | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/imgui.h b/imgui.h index a3d70bb98..001cc414d 100644 --- a/imgui.h +++ b/imgui.h @@ -3633,7 +3633,7 @@ struct ImFontAtlas // - AddCustomRectRegular() --> Renamed to AddCustomRect() // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig // - ImFontAtlasCustomRect --> Renamed to ImFontAtlasRect - IMGUI_API ImFontAtlasRectId AddCustomRect(int width, int height); // Register a rectangle. Return -1 (ImFontAtlasRectId_Invalid) on error. + IMGUI_API ImFontAtlasRectId AddCustomRect(int width, int height, ImFontAtlasRect* out_r = NULL);// Register a rectangle. Return -1 (ImFontAtlasRectId_Invalid) on error. IMGUI_API void RemoveCustomRect(ImFontAtlasRectId id); // Unregister a rectangle. Existing pixels will stay in texture until resized / garbage collected. IMGUI_API bool GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)! diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7cc1351fb..945122b35 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3225,7 +3225,8 @@ void ImFontAtlas::RemoveFont(ImFont* font) ImFontAtlasBuildNotifySetFont(this, font, new_current_font); } -ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height) +// At it is common to do an AddCustomRect() followed by a GetCustomRect(), we provide an optional 'ImFontAtlasRect* out_r = NULL' argument to retrieve the info straight away. +ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height, ImFontAtlasRect* out_r) { IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); @@ -3236,9 +3237,14 @@ ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height) ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); if (r_id == ImFontAtlasRectId_Invalid) return ImFontAtlasRectId_Invalid; - ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); + if (out_r != NULL) + GetCustomRect(r_id, out_r); + if (RendererHasTextures) + { + ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); + } return r_id; } @@ -4321,7 +4327,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon return ImFontAtlasPackAllocRectEntry(atlas, builder->Rects.Size - 1); } -// Important: don'return pointer valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. +// Important: return pointer is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { IM_ASSERT(id != ImFontAtlasRectId_Invalid); From 526a5d0f8a6363c850fc82aaca1645109cb9336f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 2 Apr 2025 15:10:11 +0200 Subject: [PATCH 1007/2359] Fonts: tidying up. --- imgui_draw.cpp | 22 +++++++++------------- imgui_internal.h | 14 +++++++------- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 945122b35..f3a79b4e7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2654,17 +2654,14 @@ void ImFontAtlas::ClearInputData() const ImFontLoader* loader = font_cfg.FontLoader ? font_cfg.FontLoader : FontLoader; if (loader && loader->FontSrcDestroy != NULL) loader->FontSrcDestroy(this, &font_cfg); - ImFontAtlasBuildDiscardFontSource(this, &font_cfg); + ImFontAtlasBuildDestroyFontSourceData(this, &font_cfg); } - // When clearing this we lose access to the font name and other information used to build the font. for (ImFont* font : Fonts) { - if (font->Sources >= Sources.Data && font->Sources < Sources.Data + Sources.Size) - { - font->Sources = NULL; - font->SourcesCount = 0; - } + // When clearing this we lose access to the font name and other information used to build the font. + font->Sources = NULL; + font->SourcesCount = 0; font->Flags |= ImFontFlags_NoLoadGlyphs; } Sources.clear(); @@ -2978,14 +2975,14 @@ bool ImFontAtlas::Build() } #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -void ImFontAtlasBuildDiscardFontSource(ImFontAtlas* atlas, ImFontConfig* src) +void ImFontAtlasBuildDestroyFontSourceData(ImFontAtlas* atlas, ImFontConfig* src) { IM_UNUSED(atlas); if (src->FontDataOwnedByAtlas) IM_FREE(src->FontData); + src->FontData = NULL; if (src->GlyphExcludeRanges) IM_FREE((void*)src->GlyphExcludeRanges); - src->FontData = NULL; src->GlyphExcludeRanges = NULL; } @@ -3048,7 +3045,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) if (!ImFontAtlasBuildAddFont(this, &new_font_cfg)) { // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) - ImFontAtlasBuildDiscardFontSource(this, &new_font_cfg); + ImFontAtlasBuildDestroyFontSourceData(this, &new_font_cfg); Sources.pop_back(); if (!font_cfg->MergeMode) { @@ -3593,9 +3590,8 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) } const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - if (loader->FontSrcInit != NULL) - if (!loader->FontSrcInit(atlas, src)) - return false; + if (loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src)) + return false; atlas->TexIsBuilt = false; // For legacy backends ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); diff --git a/imgui_internal.h b/imgui_internal.h index 0a9961a45..41b99b438 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3770,20 +3770,20 @@ IMGUI_API void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas); +IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy +IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); +IMGUI_API void ImFontAtlasBuildDestroyFontSourceData(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildReloadAll(ImFontAtlas* atlas); // Reinit/rebuild, notably if font loader params have changed. IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFontConfig* src); // Reinit/rebuild, notably if font loader params have changed. -IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); -IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); -IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); -IMGUI_API void ImFontAtlasBuildDiscardFontBakes(ImFontAtlas* atlas, ImFont* font); -IMGUI_API void ImFontAtlasBuildDiscardFontSource(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); IMGUI_API ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size); +IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); +IMGUI_API void ImFontAtlasBuildDiscardFontBakes(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); IMGUI_API void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); -IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy -IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); From fb5c53708075709a4f859d8b5721893aad89a244 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 3 Apr 2025 19:10:16 +0200 Subject: [PATCH 1008/2359] Fonts: changing loader/backend or loader flags may be done without losing custom rects. Sharing more code. --- imgui.cpp | 27 ++++++++++++----- imgui_draw.cpp | 79 ++++++++++++++++++++++++------------------------ imgui_internal.h | 4 +-- 3 files changed, 61 insertions(+), 49 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 00bb950fc..a713390c3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15695,9 +15695,16 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) ImFontAtlasBuildSetupFontLoader(atlas, loader_freetype); if (loader_current == loader_freetype) { - Text("Shared FreeType Loader Flags:"); - if (ImGuiFreeType::DebugEditFontBuilderFlags(&atlas->FontBuilderFlags)) - ImFontAtlasBuildReloadAll(atlas); + unsigned int loader_flags = atlas->FontBuilderFlags; + Text("Shared FreeType Loader Flags: 0x%08", loader_flags); + if (ImGuiFreeType::DebugEditFontBuilderFlags(&loader_flags)) + { + for (ImFont* font : atlas->Fonts) + ImFontAtlasBuildDestroyFontOutput(atlas, font); + atlas->FontBuilderFlags = loader_flags; + for (ImFont* font : atlas->Fonts) + ImFontAtlasBuildInitFontOutput(atlas, font); + } } #else BeginDisabled(); @@ -15724,8 +15731,9 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) if (Button("Grow")) ImFontAtlasBuildGrowTexture(atlas); SameLine(); - if (Button("Clear Output")) + if (Button("Clear All")) ImFontAtlasBuildClear(atlas); + SetItemTooltip("Destroy cache and custom rectangles."); for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) { @@ -16613,9 +16621,14 @@ void ImGui::DebugNodeFont(ImFont* font) #ifdef IMGUI_ENABLE_FREETYPE if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0) { - Text("FreeType Loader Flags: 0x%08X", src->FontBuilderFlags); - if (ImGuiFreeType::DebugEditFontBuilderFlags(&src->FontBuilderFlags)) - ImFontAtlasBuildReloadFont(atlas, src); + unsigned int loader_flags = src->FontBuilderFlags; + Text("FreeType Loader Flags: 0x%08X", loader_flags); + if (ImGuiFreeType::DebugEditFontBuilderFlags(&loader_flags)) + { + ImFontAtlasBuildDestroyFontOutput(atlas, font); + src->FontBuilderFlags = loader_flags; + ImFontAtlasBuildInitFontOutput(atlas, font); + } } #endif TreePop(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f3a79b4e7..b1683e204 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2649,14 +2649,11 @@ void ImFontAtlas::CompactCache() void ImFontAtlas::ClearInputData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - for (ImFontConfig& font_cfg : Sources) - { - const ImFontLoader* loader = font_cfg.FontLoader ? font_cfg.FontLoader : FontLoader; - if (loader && loader->FontSrcDestroy != NULL) - loader->FontSrcDestroy(this, &font_cfg); - ImFontAtlasBuildDestroyFontSourceData(this, &font_cfg); - } + for (ImFont* font : Fonts) + ImFontAtlasBuildDestroyFontOutput(this, font); + for (ImFontConfig& font_cfg : Sources) + ImFontAtlasBuildDestroyFontSourceData(this, &font_cfg); for (ImFont* font : Fonts) { // When clearing this we lose access to the font name and other information used to build the font. @@ -3197,15 +3194,9 @@ void ImFontAtlas::RemoveFont(ImFont* font) IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); font->ClearOutputData(); + ImFontAtlasBuildDestroyFontOutput(this, font); for (int src_n = 0; src_n < font->SourcesCount; src_n++) - { - ImFontConfig* src = (ImFontConfig*)(void*)&font->Sources[src_n]; - const ImFontLoader* loader = src->FontLoader ? src->FontLoader : FontLoader; - if (loader && loader->FontSrcDestroy != NULL) - loader->FontSrcDestroy(this, src); - if (src->FontData != NULL && src->FontDataOwnedByAtlas) - IM_FREE(src->FontData); - } + ImFontAtlasBuildDestroyFontSourceData(this, &font->Sources[src_n]); bool removed = Fonts.find_erase(font); IM_ASSERT(removed); @@ -3376,15 +3367,19 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon return; IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); - // Note that texture size estimate is likely incorrect in this situation, as FreeType backend doesn't use oversampling. - ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); - ImFontAtlasBuildDestroy(atlas); + for (ImFont* font : atlas->Fonts) + ImFontAtlasBuildDestroyFontOutput(atlas, font); + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) + atlas->FontLoader->LoaderShutdown(atlas); atlas->FontLoader = font_loader; atlas->FontLoaderName = font_loader ? font_loader->Name : "NULL"; + IM_ASSERT(atlas->FontLoaderData == NULL); - ImFontAtlasBuildAddTexture(atlas, new_tex_size.x, new_tex_size.y); - ImFontAtlasBuildInit(atlas); + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); + for (ImFont* font : atlas->Fonts) + ImFontAtlasBuildInitFontOutput(atlas, font); } // Preload all glyph ranges for legacy backends. @@ -3562,18 +3557,31 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ //----------------------------------------------------------------------------------------------------------------------------- -void ImFontAtlasBuildReloadAll(ImFontAtlas* atlas) +bool ImFontAtlasBuildInitFontOutput(ImFontAtlas* atlas, ImFont* font) { - const ImFontLoader* main_loader = atlas->FontLoader; - ImFontAtlasBuildSetupFontLoader(atlas, NULL); - ImFontAtlasBuildSetupFontLoader(atlas, main_loader); + bool ret = true; + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = &font->Sources[src_n]; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader && loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src)) + ret = false; + } + IM_ASSERT(ret); // Unclear how to react to this meaningfully. Assume that result will be same as initial AddFont() call. + return ret; } -void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFontConfig* src) +// Keep source/input FontData +void ImFontAtlasBuildDestroyFontOutput(ImFontAtlas* atlas, ImFont* font) { - // FIXME-NEWATLAS: rebuild single font not supported yet. - IM_UNUSED(src); - ImFontAtlasBuildReloadAll(atlas); + font->ClearOutputData(); + for (int src_n = 0; src_n < font->SourcesCount; src_n++) + { + ImFontConfig* src = &font->Sources[src_n]; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader && loader->FontSrcDestroy != NULL) + loader->FontSrcDestroy(atlas, src); + } } //----------------------------------------------------------------------------------------------------------------------------- @@ -4148,13 +4156,8 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) #else IM_ASSERT(0); // Invalid Build function #endif - return; // ImFontAtlasBuildSetupFontLoader() automatically call ImFontAtlasBuildInit() } - IM_ASSERT(atlas->FontLoaderData == NULL); - if (atlas->FontLoader->LoaderInit) - atlas->FontLoader->LoaderInit(atlas); - // Create initial texture size if (atlas->TexData == NULL || atlas->TexData->Pixels == NULL) ImFontAtlasBuildAddTexture(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); @@ -4165,6 +4168,8 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) { IM_ASSERT(atlas->Builder == NULL); builder = atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); + if (atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); } ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); @@ -4193,13 +4198,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) { for (ImFont* font : atlas->Fonts) - font->ClearOutputData(); - for (ImFontConfig& font_cfg : atlas->Sources) - { - const ImFontLoader* loader = font_cfg.FontLoader ? font_cfg.FontLoader : atlas->FontLoader; - if (loader && loader->FontSrcDestroy != NULL) - loader->FontSrcDestroy(atlas, &font_cfg); - } + ImFontAtlasBuildDestroyFontOutput(atlas, font); if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) { atlas->FontLoader->LoaderShutdown(atlas); diff --git a/imgui_internal.h b/imgui_internal.h index 41b99b438..009f6f9c9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3774,9 +3774,9 @@ IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontCo IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); +IMGUI_API bool ImFontAtlasBuildInitFontOutput(ImFontAtlas* atlas, ImFont* font); // Using DestroyFontOutput/InitFontOutput sequence useful notably if font loader params have changed +IMGUI_API void ImFontAtlasBuildDestroyFontOutput(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildDestroyFontSourceData(ImFontAtlas* atlas, ImFontConfig* src); -IMGUI_API void ImFontAtlasBuildReloadAll(ImFontAtlas* atlas); // Reinit/rebuild, notably if font loader params have changed. -IMGUI_API void ImFontAtlasBuildReloadFont(ImFontAtlas* atlas, ImFontConfig* src); // Reinit/rebuild, notably if font loader params have changed. IMGUI_API ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); IMGUI_API ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size); From 12599da53df30612a7f13f6b1c0532a4d9e67b81 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Apr 2025 15:16:59 +0200 Subject: [PATCH 1009/2359] Fonts: do not mark whole ImTextureData struct as IMGUI_API to fix warning when used in ImVector<> (8559) --- imgui.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 001cc414d..3d9ff1b72 100644 --- a/imgui.h +++ b/imgui.h @@ -3403,7 +3403,7 @@ struct ImTextureRect // Why does we store two identifiers: TexID and BackendUserData? // - ImTextureID TexID = lower-level identifier stored in ImDrawCmd. ImDrawCmd can refer to textures not created by the backend, and for which there's no ImTextureData. // - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both. -struct IMGUI_API ImTextureData +struct ImTextureData { ImTextureStatus Status; // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! ImTextureFormat Format; // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8 @@ -3425,8 +3425,8 @@ struct IMGUI_API ImTextureData // Functions ImTextureData() { memset(this, 0, sizeof(*this)); } ~ImTextureData() { DestroyPixels(); } - void Create(ImTextureFormat format, int w, int h); - void DestroyPixels(); + IMGUI_API void Create(ImTextureFormat format, int w, int h); + IMGUI_API void DestroyPixels(); unsigned char* GetPixels() { IM_ASSERT(Pixels != NULL); return Pixels; } unsigned char* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } From d789263e08383beab8a6482109071712792316f3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Apr 2025 18:42:06 +0200 Subject: [PATCH 1010/2359] Fonts: internal rendering uses higher level functions. --- imgui_draw.cpp | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b1683e204..562a4b6e4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3461,7 +3461,8 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ builder->PackIdMouseCursors = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); if (builder->PackIdMouseCursors == ImFontAtlasRectId_Invalid) return; - ImTextureRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdMouseCursors); + ImFontAtlasRect r; + atlas->GetCustomRect(builder->PackIdMouseCursors, &r); // Draw to texture if (add_and_draw) @@ -3469,19 +3470,19 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) { // 2x2 white pixels - ImFontAtlasBuildRenderBitmapFromString(atlas, r->x, r->y, 2, 2, "XX" "XX", 'X'); + ImFontAtlasBuildRenderBitmapFromString(atlas, r.x, r.y, 2, 2, "XX" "XX", 'X'); } else { // 2x2 white pixels + mouse cursors - const int x_for_white = r->x; - const int x_for_black = r->x + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; - ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r->y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.'); - ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r->y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X'); + const int x_for_white = r.x; + const int x_for_black = r.x + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; + ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.'); + ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X'); } } - ImFontAtlasTextureBlockQueueUpload(atlas, atlas->TexData, r->x, r->y, r->w, r->h); - atlas->TexUvWhitePixel = ImVec2((r->x + 0.5f) * atlas->TexUvScale.x, (r->y + 0.5f) * atlas->TexUvScale.y); + ImFontAtlasTextureBlockQueueUpload(atlas, atlas->TexData, r.x, r.y, r.w, r.h); + atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y); } static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_draw) @@ -3497,7 +3498,8 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ builder->PackIdLinesTexData = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); if (builder->PackIdLinesTexData == ImFontAtlasRectId_Invalid) return; - ImTextureRect* r = ImFontAtlasPackGetRect(atlas, builder->PackIdLinesTexData); + ImFontAtlasRect r; + atlas->GetCustomRect(builder->PackIdLinesTexData, &r); // Register texture region for thick lines // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row @@ -3508,18 +3510,18 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle int y = n; int line_width = n; - int pad_left = (r->w - line_width) / 2; - int pad_right = r->w - (pad_left + line_width); + int pad_left = (r.w - line_width) / 2; + int pad_right = r.w - (pad_left + line_width); // Write each slice - IM_ASSERT(pad_left + line_width + pad_right == r->w && y < r->h); // Make sure we're inside the texture bounds before we start writing pixels + IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels if (add_and_draw) { switch (tex->Format) { case ImTextureFormat_Alpha8: { - ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r->x, r->y + y); + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); for (int i = 0; i < pad_left; i++) *(write_ptr + i) = 0x00; @@ -3532,7 +3534,7 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ } case ImTextureFormat_RGBA32: { - ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r->x, r->y + y); + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); for (int i = 0; i < pad_left; i++) *(write_ptr + i) = IM_COL32(255, 255, 255, 0); @@ -3547,12 +3549,12 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ } // Calculate UVs for this line - ImVec2 uv0 = ImVec2((float)(r->x + pad_left - 1), (float)(r->y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r->x + pad_left + line_width + 1), (float)(r->y + y + 1)) * atlas->TexUvScale; + ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } - ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r.x, r.y, r.w, r.h); } //----------------------------------------------------------------------------------------------------------------------------- From e8035b94e5c739cfd0d1d8bb52ece31629ccb3bd Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Apr 2025 17:16:40 +0200 Subject: [PATCH 1011/2359] Fonts: misc tidying up. --- imgui_draw.cpp | 72 +++++++++++++++++++++++--------------------------- 1 file changed, 33 insertions(+), 39 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 562a4b6e4..a20d63bd0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3451,11 +3451,10 @@ void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, in static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_draw) { - ImVec2i pack_size = (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) ? ImVec2i(2, 2) : ImVec2i(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); - // Pack and store identifier so we can refresh UV coordinates on texture resize. // FIXME-NEWATLAS: User/custom rects where user code wants to store UV coordinates will need to do the same thing. ImFontAtlasBuilder* builder = atlas->Builder; + ImVec2i pack_size = (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) ? ImVec2i(2, 2) : ImVec2i(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); if (add_and_draw) builder->PackIdMouseCursors = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); @@ -3480,8 +3479,10 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.'); ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X'); } + ImFontAtlasTextureBlockQueueUpload(atlas, atlas->TexData, r.x, r.y, r.w, r.h); } - ImFontAtlasTextureBlockQueueUpload(atlas, atlas->TexData, r.x, r.y, r.w, r.h); + + // Refresh UV coordinates atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y); } @@ -3490,71 +3491,64 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) return; - ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); - // Pack and store identifier so we can refresh UV coordinates on texture resize. + ImTextureData* tex = atlas->TexData; ImFontAtlasBuilder* builder = atlas->Builder; + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); if (add_and_draw) builder->PackIdLinesTexData = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); if (builder->PackIdLinesTexData == ImFontAtlasRectId_Invalid) return; + ImFontAtlasRect r; atlas->GetCustomRect(builder->PackIdLinesTexData, &r); // Register texture region for thick lines // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them - ImTextureData* tex = atlas->TexData; for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle - int y = n; - int line_width = n; - int pad_left = (r.w - line_width) / 2; - int pad_right = r.w - (pad_left + line_width); + const int y = n; + const int line_width = n; + const int pad_left = (r.w - line_width) / 2; + const int pad_right = r.w - (pad_left + line_width); + IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels // Write each slice - IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels - if (add_and_draw) + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) { - switch (tex->Format) - { - case ImTextureFormat_Alpha8: - { - ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); - for (int i = 0; i < pad_left; i++) - *(write_ptr + i) = 0x00; + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = 0x00; - for (int i = 0; i < line_width; i++) - *(write_ptr + pad_left + i) = 0xFF; + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = 0xFF; - for (int i = 0; i < pad_right; i++) - *(write_ptr + pad_left + line_width + i) = 0x00; - break; - } - case ImTextureFormat_RGBA32: - { - ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); - for (int i = 0; i < pad_left; i++) - *(write_ptr + i) = IM_COL32(255, 255, 255, 0); + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = 0x00; + } + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) + { + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = IM_COL32(255, 255, 255, 0); - for (int i = 0; i < line_width; i++) - *(write_ptr + pad_left + i) = IM_COL32_WHITE; + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = IM_COL32_WHITE; - for (int i = 0; i < pad_right; i++) - *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); - break; - } - } + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); } - // Calculate UVs for this line + // Refresh UV coordinates ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } - ImFontAtlasTextureBlockQueueUpload(atlas, tex, r.x, r.y, r.w, r.h); + if (add_and_draw) + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r.x, r.y, r.w, r.h); } //----------------------------------------------------------------------------------------------------------------------------- From 0436fba13cea6ad527c3fcbf6a6e20c6a490fd78 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Mar 2025 22:38:05 +0200 Subject: [PATCH 1012/2359] Fonts: fixed compaction gc-ing baked fonts used in the current frame + rename. --- imgui_draw.cpp | 23 ++++++++++++----------- imgui_internal.h | 2 +- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a20d63bd0..3feba78a1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3983,7 +3983,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) for (ImFontAtlasRectEntry& index_entry : builder->RectsIndex) { - if (index_entry.Used == false) + if (index_entry.IsUsed == false) continue; ImTextureRect& old_r = old_rects[index_entry.TargetIndex]; if (old_r.w == 0 && old_r.h == 0) @@ -4124,7 +4124,7 @@ void ImFontAtlasBuildClear(ImFontAtlas* atlas) void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) { ImFontAtlasBuilder* builder = atlas->Builder; - ImFontAtlasBuildDiscardBakes(atlas, 0); + ImFontAtlasBuildDiscardBakes(atlas, 1); ImTextureData* old_tex = atlas->TexData; ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height); @@ -4235,19 +4235,20 @@ static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int r { index_idx = builder->RectsIndexFreeListStart; index_entry = &builder->RectsIndex[index_idx]; - IM_ASSERT(index_entry->Used == false); + IM_ASSERT(index_entry->IsUsed == false); builder->RectsIndexFreeListStart = index_entry->TargetIndex; } index_entry->TargetIndex = rect_idx; - index_entry->Used = 1; + index_entry->IsUsed = 1; return (ImFontAtlasRectId)index_idx; } -static ImFontAtlasRectId ImFontAtlasPackReuseRectEntry(ImFontAtlas* atlas, ImFontAtlasRectEntry* overwrite_entry) +// Overwrite existing entry +static ImFontAtlasRectId ImFontAtlasPackReuseRectEntry(ImFontAtlas* atlas, ImFontAtlasRectEntry* index_entry) { - IM_ASSERT(overwrite_entry->Used); - overwrite_entry->TargetIndex = atlas->Builder->Rects.Size - 1; - return atlas->Builder->RectsIndex.index_from_ptr(overwrite_entry); + IM_ASSERT(index_entry->IsUsed); + index_entry->TargetIndex = atlas->Builder->Rects.Size - 1; + return atlas->Builder->RectsIndex.index_from_ptr(index_entry); } // This is expected to be called in batches and followed by a repack @@ -4256,10 +4257,10 @@ void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) IM_ASSERT(id != ImFontAtlasRectId_Invalid); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; - IM_ASSERT(index_entry->Used && index_entry->TargetIndex >= 0); + IM_ASSERT(index_entry->IsUsed && index_entry->TargetIndex >= 0); ImTextureRect* rect = ImFontAtlasPackGetRect(atlas, id); - index_entry->Used = false; + index_entry->IsUsed = false; index_entry->TargetIndex = builder->RectsIndexFreeListStart; const int pack_padding = atlas->TexGlyphPadding; @@ -4324,7 +4325,7 @@ ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) IM_ASSERT(id != ImFontAtlasRectId_Invalid); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; - IM_ASSERT(index_entry->Used); + IM_ASSERT(index_entry->IsUsed); return &builder->Rects[index_entry->TargetIndex]; } diff --git a/imgui_internal.h b/imgui_internal.h index 009f6f9c9..3e519325a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3702,7 +3702,7 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); struct ImFontAtlasRectEntry { int TargetIndex : 31; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. - unsigned int Used : 1; + unsigned int IsUsed : 1; }; // Data available to potential texture post-processing functions From ed2bb2cff08d4d1e9b26bf744902b2131fa5fc4b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 11 Apr 2025 17:16:06 +0200 Subject: [PATCH 1013/2359] Fonts: encode additional data in ImFontAtlasRectId to detect invalid id + added Rects debug browser. --- imgui.cpp | 41 ++++++++++++++++++++++++++++++++++-- imgui.h | 2 +- imgui_draw.cpp | 54 +++++++++++++++++++++++++++++++++++++----------- imgui_internal.h | 14 +++++++++++-- 4 files changed, 94 insertions(+), 17 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a713390c3..881d40727 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15747,17 +15747,47 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) Text("Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt); Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt); + ImFontAtlasRectId highlight_r_id = ImFontAtlasRectId_Invalid; + if (TreeNode("Rects Index", "Rects Index (%d)", atlas->Builder->RectsPackedCount)) // <-- Use count of used rectangles + { + PushStyleVar(ImGuiStyleVar_ImageBorderSize, 1.0f); + if (BeginTable("##table", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY, ImVec2(0.0f, GetTextLineHeightWithSpacing() * 12))) + { + for (const ImFontAtlasRectEntry& entry : atlas->Builder->RectsIndex) + if (entry.IsUsed) + { + 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); + TableNextColumn(); + Selectable(buf); + if (IsItemHovered()) + highlight_r_id = id; + TableNextColumn(); + Image(atlas->TexID, ImVec2(r.w, r.h), r.uv0, r.uv1); + } + EndTable(); + } + PopStyleVar(); + TreePop(); + } + // Texture list // (ensure the last texture always use the same ID, so we can keep it open neatly) + ImFontAtlasRect highlight_r; + if (highlight_r_id != ImFontAtlasRectId_Invalid) + atlas->GetCustomRect(highlight_r_id, &highlight_r); for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) { if (tex_n == atlas->TexList.Size - 1) SetNextItemOpen(true, ImGuiCond_Once); - DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n); + DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n, (highlight_r_id != ImFontAtlasRectId_Invalid) ? &highlight_r : NULL); } } -void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id) +void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect) { ImGuiContext& g = *GImGui; PushID(int_id); @@ -15773,6 +15803,13 @@ void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id) ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); if (cfg->ShowTextureUsedRect) GetWindowDrawList()->AddRect(ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255)); + if (highlight_rect != NULL) + { + ImRect r_outer(p.x, p.y, p.x + tex->Width, p.y + tex->Height); + ImRect r_inner(p.x + highlight_rect->x, p.y + highlight_rect->y, p.x + highlight_rect->x + highlight_rect->w, p.y + highlight_rect->y + highlight_rect->h); + RenderRectFilledWithHole(GetWindowDrawList(), r_outer, r_inner, IM_COL32(0, 0, 0, 100), 0.0f); + GetWindowDrawList()->AddRect(r_inner.Min - ImVec2(1, 1), r_inner.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255)); + } PopStyleVar(); char texid_desc[20]; diff --git a/imgui.h b/imgui.h index 3d9ff1b72..2a0cf3546 100644 --- a/imgui.h +++ b/imgui.h @@ -3509,7 +3509,7 @@ struct ImFontGlyphRangesBuilder IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges }; -// An identifier to a rectangle in the atlas. -1 when invalid. +// An opaque identifier to a rectangle in the atlas. -1 when invalid. // The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it. typedef int ImFontAtlasRectId; #define ImFontAtlasRectId_Invalid -1 diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3feba78a1..f1d1cf0b2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3238,7 +3238,8 @@ ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height, ImFontAtlasR void ImFontAtlas::RemoveCustomRect(ImFontAtlasRectId id) { - IM_ASSERT(id != ImFontAtlasRectId_Invalid); + if (ImFontAtlasPackGetRectSafe(this, id) == NULL) + return; ImFontAtlasPackDiscardRect(this, id); } @@ -3294,10 +3295,12 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im bool ImFontAtlas::GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const { - ImTextureRect* r = ImFontAtlasPackGetRect((ImFontAtlas*)this, id); + ImTextureRect* r = ImFontAtlasPackGetRectSafe((ImFontAtlas*)this, id); if (r == NULL) return false; IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates + if (out_r == NULL) + return true; out_r->x = r->x; out_r->y = r->y; out_r->w = r->w; @@ -4001,7 +4004,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) ImFontAtlasBuildGrowTexture(atlas, w, h); // Recurse return; } - IM_ASSERT(new_r_id == builder->RectsIndex.index_from_ptr(&index_entry)); + IM_ASSERT(ImFontAtlasRectId_GetIndex(new_r_id) == builder->RectsIndex.index_from_ptr(&index_entry)); ImTextureRect* new_r = ImFontAtlasPackGetRect(atlas, new_r_id); ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r->x, new_r->y, new_r->w, new_r->h); } @@ -4230,17 +4233,18 @@ static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int r builder->RectsIndex.resize(builder->RectsIndex.Size + 1); index_idx = builder->RectsIndex.Size - 1; index_entry = &builder->RectsIndex[index_idx]; + memset(index_entry, 0, sizeof(*index_entry)); } else { index_idx = builder->RectsIndexFreeListStart; index_entry = &builder->RectsIndex[index_idx]; - IM_ASSERT(index_entry->IsUsed == false); + IM_ASSERT(index_entry->IsUsed == false && index_entry->Generation > 0); // Generation is incremented during DiscardRect builder->RectsIndexFreeListStart = index_entry->TargetIndex; } index_entry->TargetIndex = rect_idx; index_entry->IsUsed = 1; - return (ImFontAtlasRectId)index_idx; + return ImFontAtlasRectId_Make(index_idx, index_entry->Generation); } // Overwrite existing entry @@ -4248,23 +4252,29 @@ static ImFontAtlasRectId ImFontAtlasPackReuseRectEntry(ImFontAtlas* atlas, ImFon { IM_ASSERT(index_entry->IsUsed); index_entry->TargetIndex = atlas->Builder->Rects.Size - 1; - return atlas->Builder->RectsIndex.index_from_ptr(index_entry); + int index_idx = atlas->Builder->RectsIndex.index_from_ptr(index_entry); + return ImFontAtlasRectId_Make(index_idx, index_entry->Generation); } // This is expected to be called in batches and followed by a repack void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { IM_ASSERT(id != ImFontAtlasRectId_Invalid); - ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; - ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; - IM_ASSERT(index_entry->IsUsed && index_entry->TargetIndex >= 0); ImTextureRect* rect = ImFontAtlasPackGetRect(atlas, id); + if (rect == NULL) + return; + + ImFontAtlasBuilder* builder = atlas->Builder; + int index_idx = ImFontAtlasRectId_GetIndex(id); + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->IsUsed && index_entry->TargetIndex >= 0); index_entry->IsUsed = false; index_entry->TargetIndex = builder->RectsIndexFreeListStart; + index_entry->Generation++; const int pack_padding = atlas->TexGlyphPadding; - builder->RectsIndexFreeListStart = id; + builder->RectsIndexFreeListStart = index_idx; builder->RectsDiscardedCount++; builder->RectsDiscardedSurface += (rect->w + pack_padding) * (rect->h + pack_padding); rect->w = rect->h = 0; // Clear rectangle so it won't be packed again @@ -4319,16 +4329,36 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon return ImFontAtlasPackAllocRectEntry(atlas, builder->Rects.Size - 1); } -// Important: return pointer is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. +// Generally for non-user facing functions: assert on invalid ID. ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { IM_ASSERT(id != ImFontAtlasRectId_Invalid); + int index_idx = ImFontAtlasRectId_GetIndex(id); + int generation = ImFontAtlasRectId_GetGeneration(id); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; - ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[id]; + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->Generation == generation); IM_ASSERT(index_entry->IsUsed); return &builder->Rects[index_entry->TargetIndex]; } +// For user-facing functions: return NULL on invalid ID. +// Important: return pointer is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. +ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + if (id == ImFontAtlasRectId_Invalid) + return NULL; + int index_idx = ImFontAtlasRectId_GetIndex(id); + int generation = ImFontAtlasRectId_GetGeneration(id); + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + if (index_idx >= builder->RectsIndex.Size) + return NULL; + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + if (index_entry->Generation != generation || !index_entry->IsUsed) + return NULL; + return &builder->Rects[index_entry->TargetIndex]; +} + // Important! This assume by ImFontConfig::GlyphFilter is a SMALL ARRAY (e.g. <10 entries) static bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint) { diff --git a/imgui_internal.h b/imgui_internal.h index 3e519325a..cb8ba5169 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3627,7 +3627,7 @@ namespace ImGui IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); IMGUI_API void DebugNodeFont(ImFont* font); IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph); - IMGUI_API void DebugNodeTexture(ImTextureData* tex, int int_id); // ID used to facilitate persisting the "current" texture. + IMGUI_API void DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect = NULL); // ID used to facilitate persisting the "current" texture. IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label); IMGUI_API void DebugNodeTable(ImGuiTable* table); @@ -3694,6 +3694,14 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- +// Refer to ImFontAtlasPackGetRect() to better understand how this works. +#define ImFontAtlasRectId_IndexMask_ (0x000FFFFF) // 20-bits: index to access builder->RectsIndex[]. +#define ImFontAtlasRectId_GenerationMask_ (0x3FF00000) // 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. +#define ImFontAtlasRectId_GenerationShift_ (20) +inline int ImFontAtlasRectId_GetIndex(ImFontAtlasRectId id) { return id & ImFontAtlasRectId_IndexMask_; } +inline int ImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id) { return (id & ImFontAtlasRectId_GenerationMask_) >> ImFontAtlasRectId_GenerationShift_; } +inline ImFontAtlasRectId ImFontAtlasRectId_Make(int index_idx, int gen_idx) { IM_ASSERT(index_idx < ImFontAtlasRectId_IndexMask_ && gen_idx < (ImFontAtlasRectId_GenerationMask_ >> ImFontAtlasRectId_GenerationShift_)); return (ImFontAtlasRectId)(index_idx | (gen_idx << ImFontAtlasRectId_GenerationShift_)); } + // Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) // User are returned ImFontAtlasRectId values which are meant to be persistent. // We handle this with an indirection. While Rects[] may be in theory shuffled, compacted etc., RectsIndex[] cannot it is keyed by ImFontAtlasRectId. @@ -3701,7 +3709,8 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // Having this also makes it easier to e.g. sort rectangles during repack. struct ImFontAtlasRectEntry { - int TargetIndex : 31; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. + int TargetIndex : 20; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. + int Generation : 10; // Increased each time the entry is reused for a new rectangle. unsigned int IsUsed : 1; }; @@ -3792,6 +3801,7 @@ IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_s IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); +IMGUI_API ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count); From cdfa537adf060c1d3fe13c87ad4ed25d967e814b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 14 Apr 2025 16:20:31 +0200 Subject: [PATCH 1014/2359] Fonts: packing of shared basic/line/cursor data uses more public API. --- imgui_draw.cpp | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f1d1cf0b2..b7507821e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3452,23 +3452,21 @@ void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, in } } -static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_draw) +static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas) { // Pack and store identifier so we can refresh UV coordinates on texture resize. // FIXME-NEWATLAS: User/custom rects where user code wants to store UV coordinates will need to do the same thing. ImFontAtlasBuilder* builder = atlas->Builder; ImVec2i pack_size = (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) ? ImVec2i(2, 2) : ImVec2i(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); - if (add_and_draw) - builder->PackIdMouseCursors = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); - if (builder->PackIdMouseCursors == ImFontAtlasRectId_Invalid) - return; ImFontAtlasRect r; - atlas->GetCustomRect(builder->PackIdMouseCursors, &r); - - // Draw to texture + bool add_and_draw = (atlas->GetCustomRect(builder->PackIdMouseCursors, &r) == false); if (add_and_draw) { + builder->PackIdMouseCursors = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); + IM_ASSERT(builder->PackIdMouseCursors != ImFontAtlasRectId_Invalid); + + // Draw to texture if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) { // 2x2 white pixels @@ -3482,14 +3480,13 @@ static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas, bool add_and_ ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.'); ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X'); } - ImFontAtlasTextureBlockQueueUpload(atlas, atlas->TexData, r.x, r.y, r.w, r.h); } // Refresh UV coordinates atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y); } -static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_draw) +static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas) { if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) return; @@ -3497,14 +3494,15 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ // Pack and store identifier so we can refresh UV coordinates on texture resize. ImTextureData* tex = atlas->TexData; ImFontAtlasBuilder* builder = atlas->Builder; - ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); - if (add_and_draw) - builder->PackIdLinesTexData = ImFontAtlasPackAddRect(atlas, pack_size.x, pack_size.y); - if (builder->PackIdLinesTexData == ImFontAtlasRectId_Invalid) - return; ImFontAtlasRect r; - atlas->GetCustomRect(builder->PackIdLinesTexData, &r); + bool add_and_draw = atlas->GetCustomRect(builder->PackIdLinesTexData, &r) == false; + if (add_and_draw) + { + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + builder->PackIdLinesTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); + IM_ASSERT(builder->PackIdLinesTexData != ImFontAtlasRectId_Invalid); + } // Register texture region for thick lines // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row @@ -3550,8 +3548,6 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas, bool add_and_ float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } - if (add_and_draw) - ImFontAtlasTextureBlockQueueUpload(atlas, tex, r.x, r.y, r.w, r.h); } //----------------------------------------------------------------------------------------------------------------------------- @@ -4025,8 +4021,8 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) } // Update other cached UV - ImFontAtlasBuildUpdateLinesTexData(atlas, false); - ImFontAtlasBuildUpdateBasicTexData(atlas, false); + ImFontAtlasBuildUpdateLinesTexData(atlas); + ImFontAtlasBuildUpdateBasicTexData(atlas); builder->LockDisableResize = false; ImFontAtlasUpdateDrawListsSharedData(atlas); @@ -4176,8 +4172,8 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) ImFontAtlasPackInit(atlas); // Add required texture data - ImFontAtlasBuildUpdateLinesTexData(atlas, true); - ImFontAtlasBuildUpdateBasicTexData(atlas, true); + ImFontAtlasBuildUpdateLinesTexData(atlas); + ImFontAtlasBuildUpdateBasicTexData(atlas); // Register fonts if (builder_is_new) From c43b138a6988ada530d03b821cfdbc8a578149d2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 17 Apr 2025 15:00:35 +0200 Subject: [PATCH 1015/2359] Fonts: no need to load current baked on SkipItems window? + removed unused field. Avoid baked staying active after GC. Might cause issues. # Conflicts: # imgui.cpp --- imgui.cpp | 6 +++++- imgui_internal.h | 1 - 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 881d40727..e2765edac 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8625,9 +8625,13 @@ void ImGui::SetCurrentFont(ImFont* font, float font_size) void ImGui::UpdateCurrentFontSize() { ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window != NULL && window->SkipItems) + return; + float final_size = g.FontSizeBeforeScaling * g.IO.FontGlobalScale; final_size *= g.Font->Scale; - if (ImGuiWindow* window = g.CurrentWindow) + if (window != NULL) final_size *= window->FontWindowScale; // Round font size diff --git a/imgui_internal.h b/imgui_internal.h index cb8ba5169..c4e064052 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2144,7 +2144,6 @@ struct ImGuiContext float FontScale; // == FontBaked->Size / Font->FontSize. Scale factor over baked size. float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale ImDrawListSharedData DrawListSharedData; - ImVectorTextures; double Time; int FrameCount; int FrameCountEnded; From eb650c468a42b71ff83d1b3405068ad4c8cebbf6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 17 Apr 2025 16:47:54 +0200 Subject: [PATCH 1016/2359] Fonts: fixed unused variable warning. --- imgui_draw.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b7507821e..f982df4e6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4330,10 +4330,9 @@ ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) { IM_ASSERT(id != ImFontAtlasRectId_Invalid); int index_idx = ImFontAtlasRectId_GetIndex(id); - int generation = ImFontAtlasRectId_GetGeneration(id); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; - IM_ASSERT(index_entry->Generation == generation); + IM_ASSERT(index_entry->Generation == ImFontAtlasRectId_GetGeneration(id)); IM_ASSERT(index_entry->IsUsed); return &builder->Rects[index_entry->TargetIndex]; } @@ -4345,12 +4344,11 @@ ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId if (id == ImFontAtlasRectId_Invalid) return NULL; int index_idx = ImFontAtlasRectId_GetIndex(id); - int generation = ImFontAtlasRectId_GetGeneration(id); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; if (index_idx >= builder->RectsIndex.Size) return NULL; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; - if (index_entry->Generation != generation || !index_entry->IsUsed) + if (index_entry->Generation != ImFontAtlasRectId_GetGeneration(id) || !index_entry->IsUsed) return NULL; return &builder->Rects[index_entry->TargetIndex]; } From 7840e453b58f8b0950166e67adce8df15ddebfa2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 17 Apr 2025 16:53:12 +0200 Subject: [PATCH 1017/2359] Fonts: ImFontAtlasBuildInit() is always called with atlas->Builder == NULL. --- imgui_draw.cpp | 22 +++++++--------------- imgui_internal.h | 2 +- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f982df4e6..f78ff9901 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3552,6 +3552,7 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas) //----------------------------------------------------------------------------------------------------------------------------- +// Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() bool ImFontAtlasBuildInitFontOutput(ImFontAtlas* atlas, ImFont* font) { bool ret = true; @@ -4157,15 +4158,9 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (atlas->TexData == NULL || atlas->TexData->Pixels == NULL) ImFontAtlasBuildAddTexture(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); - ImFontAtlasBuilder* builder = atlas->Builder; // Do not move above - const bool builder_is_new = (builder == NULL); - if (builder_is_new) - { - IM_ASSERT(atlas->Builder == NULL); - builder = atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); - if (atlas->FontLoader->LoaderInit) - atlas->FontLoader->LoaderInit(atlas); - } + atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); + if (atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); @@ -4176,12 +4171,9 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) ImFontAtlasBuildUpdateBasicTexData(atlas); // Register fonts - if (builder_is_new) - { - ImFontAtlasBuildUpdatePointers(atlas); - for (ImFontConfig& cfg : atlas->Sources) - ImFontAtlasBuildAddFont(atlas, &cfg); - } + ImFontAtlasBuildUpdatePointers(atlas); + for (ImFontConfig& cfg : atlas->Sources) + ImFontAtlasBuildAddFont(atlas, &cfg); // Update UV coordinates etc. stored in bound ImDrawListSharedData instance ImFontAtlasUpdateDrawListsSharedData(atlas); diff --git a/imgui_internal.h b/imgui_internal.h index c4e064052..7c615d323 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3753,7 +3753,7 @@ struct ImFontAtlasBuilder // Cache of all ImFontBaked ImStableVector BakedPool; - ImGuiStorage BakedMap; + ImGuiStorage BakedMap; // BakedId --> ImFontBaked* int BakedDiscardedCount; // Custom rectangle identifiers From bcd1a94b89c478de8beee33d92e30ed00e5cda50 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 17 Apr 2025 17:48:29 +0200 Subject: [PATCH 1018/2359] Fonts: Extract ImFontAtlasBuildGetFontBaked() out of ImFont::GetFontBaked() mostly for consistency with upcoming changes + tweak locals in AddFont(). --- imgui.cpp | 2 +- imgui.h | 2 +- imgui_draw.cpp | 87 ++++++++++++++++++++++++------------------------ imgui_internal.h | 1 + 4 files changed, 46 insertions(+), 46 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e2765edac..2b8c8f8db 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15770,7 +15770,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) if (IsItemHovered()) highlight_r_id = id; TableNextColumn(); - Image(atlas->TexID, ImVec2(r.w, r.h), r.uv0, r.uv1); + Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1); } EndTable(); } diff --git a/imgui.h b/imgui.h index 2a0cf3546..6ae7c9e52 100644 --- a/imgui.h +++ b/imgui.h @@ -3673,7 +3673,7 @@ struct ImFontAtlas ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines int TexNextUniqueID; // Next value to be stored in TexData->UniqueID - int FontNextUniqueID; // Next value to be stored in ImFont->SourceID + int FontNextUniqueID; // Next value to be stored in ImFont->FontID ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. const ImFontLoader* FontLoader; // Font loader opaque interface (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). Don't set directly! diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f78ff9901..dffe5ccf5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2983,12 +2983,12 @@ void ImFontAtlasBuildDestroyFontSourceData(ImFontAtlas* atlas, ImFontConfig* src src->GlyphExcludeRanges = NULL; } -ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) +ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - IM_ASSERT((font_cfg->FontData != NULL && font_cfg->FontDataSize > 0) || (font_cfg->FontLoader != NULL)); - IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); - IM_ASSERT(font_cfg->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); + IM_ASSERT((font_cfg_in->FontData != NULL && font_cfg_in->FontDataSize > 0) || (font_cfg_in->FontLoader != NULL)); + IM_ASSERT(font_cfg_in->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); + IM_ASSERT(font_cfg_in->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); // Lazily create builder on the first call to AddFont if (Builder == NULL) @@ -2996,12 +2996,12 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) // Create new font ImFont* font; - if (!font_cfg->MergeMode) + if (!font_cfg_in->MergeMode) { font = IM_NEW(ImFont)(); font->FontId = FontNextUniqueID++; - font->Flags = font_cfg->Flags; - font->DefaultSize = font_cfg->SizePixels; + font->Flags = font_cfg_in->Flags; + font->DefaultSize = font_cfg_in->SizePixels; Fonts.push_back(font); } else @@ -3010,14 +3010,14 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) font = Fonts.back(); } - Sources.push_back(*font_cfg); - ImFontConfig& new_font_cfg = Sources.back(); - if (new_font_cfg.DstFont == NULL) - new_font_cfg.DstFont = font; - if (!new_font_cfg.FontDataOwnedByAtlas) + Sources.push_back(*font_cfg_in); + ImFontConfig* font_cfg = &Sources.back(); + if (font_cfg->DstFont == NULL) + font_cfg->DstFont = font; + if (font_cfg->FontDataOwnedByAtlas == false) { - new_font_cfg.FontDataOwnedByAtlas = true; - new_font_cfg.FontData = ImMemdup(font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + font_cfg->FontDataOwnedByAtlas = true; + font_cfg->FontData = ImMemdup(font_cfg->FontData, (size_t)font_cfg->FontDataSize); } // Sanity check @@ -3028,7 +3028,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) for (const ImWchar* p = font_cfg->GlyphExcludeRanges; p[0] != 0; p++, size++) {} IM_ASSERT((size & 1) == 0 && "GlyphExcludeRanges[] size must be multiple of two!"); IM_ASSERT((size <= 64) && "GlyphExcludeRanges[] size must be small!"); - new_font_cfg.GlyphExcludeRanges = (ImWchar*)ImMemdup(font_cfg->GlyphExcludeRanges, sizeof(font_cfg->GlyphExcludeRanges[0]) * (size + 1)); + font_cfg->GlyphExcludeRanges = (ImWchar*)ImMemdup(font_cfg->GlyphExcludeRanges, sizeof(font_cfg->GlyphExcludeRanges[0]) * (size + 1)); } if (font_cfg->FontLoader != NULL) { @@ -3038,12 +3038,14 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) IM_ASSERT(font_cfg->FontLoaderData == NULL); // Pointers to Sources are otherwise dangling + font->SourcesCount++; ImFontAtlasBuildUpdatePointers(this); - if (!ImFontAtlasBuildAddFont(this, &new_font_cfg)) + if (!ImFontAtlasBuildAddFont(this, font_cfg)) { // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) - ImFontAtlasBuildDestroyFontSourceData(this, &new_font_cfg); + ImFontAtlasBuildDestroyFontSourceData(this, font_cfg); Sources.pop_back(); + font->SourcesCount--; if (!font_cfg->MergeMode) { IM_DELETE(font); @@ -3051,8 +3053,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) } return NULL; } - - return new_font_cfg.DstFont; + return font; } // Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder) @@ -3416,11 +3417,7 @@ void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) ImFontConfig* src = &atlas->Sources[src_n]; ImFont* font = src->DstFont; if (!src->MergeMode) - { font->Sources = src; - font->SourcesCount = 0; - } - font->SourcesCount++; } } @@ -3739,11 +3736,11 @@ void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImF baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; } -ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float size, ImGuiID baked_id) +ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id) { - IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", size); + IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", font_size); ImFontBaked* baked = atlas->Builder->BakedPool.push_back(ImFontBaked()); - baked->Size = size; + baked->Size = font_size; baked->BakedId = baked_id; baked->ContainerFont = font; baked->LastUsedFrame = atlas->Builder->FrameCount; @@ -5021,10 +5018,10 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked IM_ASSERT(baked->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. // Set UV from packed rectangle - if (in_glyph->PackId != ImFontAtlasRectId_Invalid) + if (glyph.PackId != ImFontAtlasRectId_Invalid) { - ImTextureRect* r = ImFontAtlasPackGetRect(atlas, in_glyph->PackId); - IM_ASSERT(in_glyph->U0 == 0.0f && in_glyph->V0 == 0.0f && in_glyph->U1 == 0.0f && in_glyph->V1 == 0.0f); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); + IM_ASSERT(glyph.U0 == 0.0f && glyph.V0 == 0.0f && glyph.U1 == 0.0f && glyph.V1 == 0.0f); glyph.U0 = (r->x) * atlas->TexUvScale.x; glyph.V0 = (r->y) * atlas->TexUvScale.y; glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; @@ -5196,31 +5193,35 @@ ImFontBaked* ImFont::GetFontBaked(float size) ImFontAtlas* atlas = ContainerAtlas; ImFontAtlasBuilder* builder = atlas->Builder; + baked = ImFontAtlasBuildGetFontBaked(atlas, this, size); + if (baked == NULL) + return NULL; + baked->LastUsedFrame = builder->FrameCount; + LastBaked = baked; + return baked; +} - // FIXME-NEWATLAS: Design for picking a nearest size based on some criterias? +ImFontBaked* ImFontAtlasBuildGetFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size) +{ + // FIXME-NEWATLAS: Design for picking a nearest size based on some criteria? // FIXME-NEWATLAS: Altering font density won't work right away. - ImGuiID baked_id = ImFontAtlasBakedGetId(FontId, size); + ImGuiID baked_id = ImFontAtlasBakedGetId(font->FontId, font_size); + ImFontAtlasBuilder* builder = atlas->Builder; ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); - baked = *p_baked_in_map; + ImFontBaked* baked = *p_baked_in_map; if (baked != NULL) { - IM_ASSERT(baked->Size == size && baked->ContainerFont == this && baked->BakedId == baked_id); - baked->LastUsedFrame = builder->FrameCount; - LastBaked = baked; + IM_ASSERT(baked->Size == font_size && baked->ContainerFont == font && baked->BakedId == baked_id); return baked; } // If atlas is locked, find closest match // FIXME-OPT: This is not an optimal query. - if ((Flags & ImFontFlags_LockBakedSizes) || atlas->Locked) + if ((font->Flags & ImFontFlags_LockBakedSizes) || atlas->Locked) { - baked = ImFontAtlasBuildGetClosestFontBakedMatch(atlas, this, size); + baked = ImFontAtlasBuildGetClosestFontBakedMatch(atlas, font, font_size); if (baked != NULL) - { - baked->LastUsedFrame = builder->FrameCount; - LastBaked = baked; return baked; - } if (atlas->Locked) { IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! @@ -5229,10 +5230,8 @@ ImFontBaked* ImFont::GetFontBaked(float size) } // Create new - baked = ImFontAtlasBuildAddFontBaked(atlas, this, size, baked_id); - LastBaked = baked; + baked = ImFontAtlasBuildAddFontBaked(atlas, font, font_size, baked_id); *p_baked_in_map = baked; // To avoid 'builder->BakedMap.SetVoidPtr(baked_id, baked);' while we can. - return baked; } diff --git a/imgui_internal.h b/imgui_internal.h index 7c615d323..7f9420cda 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3786,6 +3786,7 @@ IMGUI_API bool ImFontAtlasBuildInitFontOutput(ImFontAtlas* atlas, I IMGUI_API void ImFontAtlasBuildDestroyFontOutput(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasBuildDestroyFontSourceData(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API ImFontBaked* ImFontAtlasBuildGetFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size); IMGUI_API ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); IMGUI_API ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size); IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); From c4fa9bb61fb69fa5f322b3e621baedfd101a72a6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Apr 2025 18:06:50 +0200 Subject: [PATCH 1019/2359] Fonts: add ImFontGlyph::SourceIdx. Extract code out of DebugNodeFont() into DebugNodeFontGlyphesForSrcMask(). (src_mask unused in this commit) --- imgui.cpp | 100 +++++++++++++++++++++++++---------------------- imgui.h | 3 +- imgui_draw.cpp | 6 ++- imgui_internal.h | 1 + 4 files changed, 62 insertions(+), 48 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2b8c8f8db..66b0609cd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16700,52 +16700,7 @@ void ImGui::DebugNodeFont(ImFont* font) src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); } - ImDrawList* draw_list = GetWindowDrawList(); - const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); - const float cell_size = baked->Size * 1; - const float cell_spacing = GetStyle().ItemSpacing.y; - for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) - { - // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) - // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT - // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) - if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191)) - { - base += 8192 - 256; - continue; - } - - int count = 0; - for (unsigned int n = 0; n < 256; n++) - if (baked->IsGlyphLoaded((ImWchar)(base + n))) - count++; - if (count <= 0) - continue; - if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) - continue; - - // Draw a 16x16 grid of glyphs - ImVec2 base_pos = GetCursorScreenPos(); - for (unsigned int n = 0; n < 256; n++) - { - // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions - // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. - ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); - ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); - const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL; - draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); - if (!glyph) - continue; - font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); - if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip()) - { - DebugNodeFontGlyph(font, glyph); - EndTooltip(); - } - } - Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); - TreePop(); - } + DebugNodeFontGlyphesForSrcMask(font, baked, ~0); TreePop(); } PopID(); @@ -16754,6 +16709,57 @@ void ImGui::DebugNodeFont(ImFont* font) Unindent(); } +void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask) +{ + ImDrawList* draw_list = GetWindowDrawList(); + const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); + const float cell_size = baked->Size * 1; + const float cell_spacing = GetStyle().ItemSpacing.y; + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) + { + // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) + // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT + // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) + if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191)) + { + base += 8192 - 256; + continue; + } + + int count = 0; + for (unsigned int n = 0; n < 256; n++) + if (const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL) + if (src_mask & (1 << glyph->SourceIdx)) + count++; + if (count <= 0) + continue; + if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) + continue; + + // Draw a 16x16 grid of glyphs + ImVec2 base_pos = GetCursorScreenPos(); + for (unsigned int n = 0; n < 256; n++) + { + // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions + // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); + const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL; + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); + if (!glyph || (src_mask & (1 << glyph->SourceIdx)) == 0) + continue; + font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); + if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip()) + { + DebugNodeFontGlyph(font, glyph); + EndTooltip(); + } + } + Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); + TreePop(); + } +} + void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) { Text("Codepoint: U+%04X", glyph->Codepoint); @@ -16767,6 +16773,7 @@ void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) ImTextureRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId); Text("PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y); } + Text("SourceIdx: %d", glyph->SourceIdx); } // [DEBUG] Display contents of ImGuiStorage @@ -17429,6 +17436,7 @@ void ImGui::DebugNodeColumns(ImGuiOldColumns*) {} void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {} void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} void ImGui::DebugNodeFont(ImFont*) {} +void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont*, ImFontBaked*, int) {} void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {} void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {} diff --git a/imgui.h b/imgui.h index 6ae7c9e52..f99eaedd3 100644 --- a/imgui.h +++ b/imgui.h @@ -3484,7 +3484,8 @@ struct ImFontGlyph { unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. - unsigned int Codepoint : 30; // 0x0000..0x10FFFF + unsigned int SourceIdx : 4; // Index of source in parent font + unsigned int Codepoint : 26; // 0x0000..0x10FFFF float AdvanceX; // Horizontal distance to advance cursor/layout position. float X0, Y0, X1, Y1; // Glyph corners. Offsets from current cursor/layout position. float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dffe5ccf5..a0c34901d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4390,7 +4390,11 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) if (ImFontGlyph* glyph = loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint)) - return glyph; // FIXME: Add hooks for e.g. #7962 + { + // FIXME: Add hooks for e.g. #7962 + glyph->SourceIdx = src_n; + return glyph; + } loader_user_data_p += loader->FontBakedSrcLoaderDataSize; } diff --git a/imgui_internal.h b/imgui_internal.h index 7f9420cda..137ba7d46 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3625,6 +3625,7 @@ namespace ImGui IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label); IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); IMGUI_API void DebugNodeFont(ImFont* font); + IMGUI_API void DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask); IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph); IMGUI_API void DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect = NULL); // ID used to facilitate persisting the "current" texture. IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); From 890fff92fd071e2c70139205e065eca0c1061761 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Apr 2025 12:08:28 +0200 Subject: [PATCH 1020/2359] Fonts: rename many internal functions for consistency. No other changes. --- imgui.cpp | 10 ++-- imgui_draw.cpp | 118 +++++++++++++++++++++++------------------------ imgui_internal.h | 38 +++++++-------- 3 files changed, 83 insertions(+), 83 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 66b0609cd..8f7c8fe62 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15704,10 +15704,10 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) if (ImGuiFreeType::DebugEditFontBuilderFlags(&loader_flags)) { for (ImFont* font : atlas->Fonts) - ImFontAtlasBuildDestroyFontOutput(atlas, font); + ImFontAtlasFontDestroyOutput(atlas, font); atlas->FontBuilderFlags = loader_flags; for (ImFont* font : atlas->Fonts) - ImFontAtlasBuildInitFontOutput(atlas, font); + ImFontAtlasFontInitOutput(atlas, font); } } #else @@ -15733,7 +15733,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) atlas->CompactCache(); SameLine(); if (Button("Grow")) - ImFontAtlasBuildGrowTexture(atlas); + ImFontAtlasTextureGrow(atlas); SameLine(); if (Button("Clear All")) ImFontAtlasBuildClear(atlas); @@ -16666,9 +16666,9 @@ void ImGui::DebugNodeFont(ImFont* font) Text("FreeType Loader Flags: 0x%08X", loader_flags); if (ImGuiFreeType::DebugEditFontBuilderFlags(&loader_flags)) { - ImFontAtlasBuildDestroyFontOutput(atlas, font); + ImFontAtlasFontDestroyOutput(atlas, font); src->FontBuilderFlags = loader_flags; - ImFontAtlasBuildInitFontOutput(atlas, font); + ImFontAtlasFontInitOutput(atlas, font); } } #endif diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a0c34901d..40ae02ed5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2643,7 +2643,7 @@ void ImFontAtlas::Clear() void ImFontAtlas::CompactCache() { - ImFontAtlasBuildCompactTexture(this); + ImFontAtlasTextureCompact(this); } void ImFontAtlas::ClearInputData() @@ -2651,9 +2651,9 @@ void ImFontAtlas::ClearInputData() IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); for (ImFont* font : Fonts) - ImFontAtlasBuildDestroyFontOutput(this, font); + ImFontAtlasFontDestroyOutput(this, font); for (ImFontConfig& font_cfg : Sources) - ImFontAtlasBuildDestroyFontSourceData(this, &font_cfg); + ImFontAtlasFontDestroySourceData(this, &font_cfg); for (ImFont* font : Fonts) { // When clearing this we lose access to the font name and other information used to build the font. @@ -2972,17 +2972,6 @@ bool ImFontAtlas::Build() } #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -void ImFontAtlasBuildDestroyFontSourceData(ImFontAtlas* atlas, ImFontConfig* src) -{ - IM_UNUSED(atlas); - if (src->FontDataOwnedByAtlas) - IM_FREE(src->FontData); - src->FontData = NULL; - if (src->GlyphExcludeRanges) - IM_FREE((void*)src->GlyphExcludeRanges); - src->GlyphExcludeRanges = NULL; -} - ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); @@ -3040,10 +3029,10 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) // Pointers to Sources are otherwise dangling font->SourcesCount++; ImFontAtlasBuildUpdatePointers(this); - if (!ImFontAtlasBuildAddFont(this, font_cfg)) + if (!ImFontAtlasFontInitSource(this, font_cfg)) { // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) - ImFontAtlasBuildDestroyFontSourceData(this, font_cfg); + ImFontAtlasFontDestroySourceData(this, font_cfg); Sources.pop_back(); font->SourcesCount--; if (!font_cfg->MergeMode) @@ -3195,9 +3184,9 @@ void ImFontAtlas::RemoveFont(ImFont* font) IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); font->ClearOutputData(); - ImFontAtlasBuildDestroyFontOutput(this, font); + ImFontAtlasFontDestroyOutput(this, font); for (int src_n = 0; src_n < font->SourcesCount; src_n++) - ImFontAtlasBuildDestroyFontSourceData(this, &font->Sources[src_n]); + ImFontAtlasFontDestroySourceData(this, &font->Sources[src_n]); bool removed = Fonts.find_erase(font); IM_ASSERT(removed); @@ -3251,14 +3240,14 @@ void ImFontAtlas::RemoveCustomRect(ImFontAtlasRectId id) // ImFont* myfont = io.Fonts->AddFontFromFileTTF(....); // myfont->GetFontBaked(16.0f); // myfont->Flags |= ImFontFlags_LockBakedSizes; -int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) +ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) { float font_size = font->DefaultSize; return AddCustomRectFontGlyphForSize(font, font_size, codepoint, width, height, advance_x, offset); } // FIXME: we automatically set glyph.Colored=true by default. // If you need to alter this, you can write 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph(). -int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) +ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) { #ifdef IMGUI_USE_WCHAR32 IM_ASSERT(codepoint <= IM_UNICODE_CODEPOINT_MAX); @@ -3277,7 +3266,7 @@ int ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, Im ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); if (baked->IsGlyphLoaded(codepoint)) - ImFontAtlasBuildDiscardFontBakedGlyph(this, font, baked, baked->FindGlyph(codepoint)); + ImFontAtlasBakedDiscardFontGlyph(this, font, baked, baked->FindGlyph(codepoint)); ImFontGlyph glyph; glyph.Codepoint = codepoint; @@ -3337,9 +3326,9 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); if (atlas->TexData && atlas->TexData->Format != atlas->TexDesiredFormat) { - ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); + ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); ImFontAtlasBuildDestroy(atlas); - ImFontAtlasBuildAddTexture(atlas, new_tex_size.x, new_tex_size.y); + ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y); } if (atlas->Builder == NULL) @@ -3372,7 +3361,7 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); for (ImFont* font : atlas->Fonts) - ImFontAtlasBuildDestroyFontOutput(atlas, font); + ImFontAtlasFontDestroyOutput(atlas, font); if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) atlas->FontLoader->LoaderShutdown(atlas); @@ -3383,7 +3372,7 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderInit) atlas->FontLoader->LoaderInit(atlas); for (ImFont* font : atlas->Fonts) - ImFontAtlasBuildInitFontOutput(atlas, font); + ImFontAtlasFontInitOutput(atlas, font); } // Preload all glyph ranges for legacy backends. @@ -3550,7 +3539,7 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas) //----------------------------------------------------------------------------------------------------------------------------- // Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() -bool ImFontAtlasBuildInitFontOutput(ImFontAtlas* atlas, ImFont* font) +bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font) { bool ret = true; for (int src_n = 0; src_n < font->SourcesCount; src_n++) @@ -3565,7 +3554,7 @@ bool ImFontAtlasBuildInitFontOutput(ImFontAtlas* atlas, ImFont* font) } // Keep source/input FontData -void ImFontAtlasBuildDestroyFontOutput(ImFontAtlas* atlas, ImFont* font) +void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font) { font->ClearOutputData(); for (int src_n = 0; src_n < font->SourcesCount; src_n++) @@ -3579,7 +3568,7 @@ void ImFontAtlasBuildDestroyFontOutput(ImFontAtlas* atlas, ImFont* font) //----------------------------------------------------------------------------------------------------------------------------- -bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) +bool ImFontAtlasFontInitSource(ImFontAtlas* atlas, ImFontConfig* src) { ImFont* font = src->DstFont; if (src->MergeMode == false) @@ -3599,6 +3588,17 @@ bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src) return true; } +void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + if (src->FontDataOwnedByAtlas) + IM_FREE(src->FontData); + src->FontData = NULL; + if (src->GlyphExcludeRanges) + IM_FREE((void*)src->GlyphExcludeRanges); + src->GlyphExcludeRanges = NULL; +} + // Create a compact, baked "..." if it doesn't exist, by using the ".". // This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. // FIXME-NEWATLAS: This borrows too much from FontLoader's FontLoadGlyph() handlers and suggest that we should add further helpers. @@ -3721,7 +3721,7 @@ void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, Im } } -void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph) +void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph) { if (glyph->PackId != ImFontAtlasRectId_Invalid) { @@ -3736,7 +3736,7 @@ void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImF baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; } -ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id) +ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id) { IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", font_size); ImFontBaked* baked = atlas->Builder->BakedPool.push_back(ImFontBaked()); @@ -3769,7 +3769,7 @@ ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, floa } // FIXME-OPT: This is not a fast query. Adding a BakedCount field in Font might allow to take a shortcut for the most common case. -ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size) +ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size) { ImFontAtlasBuilder* builder = atlas->Builder; ImFontBaked* closest_larger_match = NULL; @@ -3792,7 +3792,7 @@ ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont return NULL; } -void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) +void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) { ImFontAtlasBuilder* builder = atlas->Builder; IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName()); @@ -3822,14 +3822,14 @@ void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBa font->LastBaked = NULL; } -void ImFontAtlasBuildDiscardFontBakes(ImFontAtlas* atlas, ImFont* font) +void ImFontAtlasFontDiscardOutputBakes(ImFontAtlas* atlas, ImFont* font) { if (ImFontAtlasBuilder* builder = atlas->Builder) // This can be called from font destructor for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) { ImFontBaked* baked = &builder->BakedPool[baked_n]; if (baked->ContainerFont == font && !baked->WantDestroy) - ImFontAtlasBuildDiscardFontBaked(atlas, font, baked); + ImFontAtlasBakedDiscard(atlas, font, baked); } } @@ -3844,7 +3844,7 @@ void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames) continue; if (baked->WantDestroy || (baked->ContainerFont->Flags & ImFontFlags_LockBakedSizes)) continue; - ImFontAtlasBuildDiscardFontBaked(atlas, baked->ContainerFont, baked); + ImFontAtlasBakedDiscard(atlas, baked->ContainerFont, baked); } } @@ -3905,7 +3905,7 @@ static void ImFontAtlasBuildSetTexture(ImFontAtlas* atlas, ImTextureData* tex) } // Create a new texture, discard previous one -ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h) +ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h) { ImTextureData* old_tex = atlas->TexData; ImTextureData* new_tex; @@ -3955,13 +3955,13 @@ static void ImFontAtlasDebugWriteTexToDisk(ImTextureData* tex, const char* descr } #endif -void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) +void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h) { ImFontAtlasBuilder* builder = atlas->Builder; builder->LockDisableResize = true; ImTextureData* old_tex = atlas->TexData; - ImTextureData* new_tex = ImFontAtlasBuildAddTexture(atlas, w, h); + ImTextureData* new_tex = ImFontAtlasTextureAdd(atlas, w, h); new_tex->UseColors = old_tex->UseColors; IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d\n", old_tex->UniqueID, old_tex->Width, old_tex->Height, new_tex->UniqueID, new_tex->Width, new_tex->Height); //for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) @@ -3995,7 +3995,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) builder->Rects.swap(old_rects); builder->RectsIndex = old_index; ImFontAtlasBuildSetTexture(atlas, old_tex); - ImFontAtlasBuildGrowTexture(atlas, w, h); // Recurse + ImFontAtlasTextureGrow(atlas, w, h); // Recurse return; } IM_ASSERT(ImFontAtlasRectId_GetIndex(new_r_id) == builder->RectsIndex.index_from_ptr(&index_entry)); @@ -4027,7 +4027,7 @@ void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h) //ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack"); } -void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_h) +void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_tex_w, int old_tex_h) { //ImFontAtlasDebugWriteTexToDisk(atlas->TexData, "Before Grow"); ImFontAtlasBuilder* builder = atlas->Builder; @@ -4056,10 +4056,10 @@ void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_tex_w, int old_tex_ if (new_tex_w == old_tex_w && new_tex_h == old_tex_h) return; - ImFontAtlasBuildRepackTexture(atlas, new_tex_w, new_tex_h); + ImFontAtlasTextureRepack(atlas, new_tex_w, new_tex_h); } -void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas) +void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas) { // Can some baked contents be ditched? //IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()\n"); @@ -4068,12 +4068,12 @@ void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas) // Currently using a heuristic for repack without growing. if (builder->RectsDiscardedSurface < builder->RectsPackedSurface * 0.20f) - ImFontAtlasBuildGrowTexture(atlas); + ImFontAtlasTextureGrow(atlas); else - ImFontAtlasBuildRepackTexture(atlas, atlas->TexData->Width, atlas->TexData->Height); + ImFontAtlasTextureRepack(atlas, atlas->TexData->Width, atlas->TexData->Height); } -ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) +ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas) { int min_w = ImUpperPowerOfTwo(atlas->TexMinWidth); int min_h = ImUpperPowerOfTwo(atlas->TexMinHeight); @@ -4110,26 +4110,26 @@ ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas) // Clear all output. Invalidates all AddCustomRect() return values! void ImFontAtlasBuildClear(ImFontAtlas* atlas) { - ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); + ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); ImFontAtlasBuildDestroy(atlas); - ImFontAtlasBuildAddTexture(atlas, new_tex_size.x, new_tex_size.y); + ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y); ImFontAtlasBuildInit(atlas); } // You should not need to call this manually! // If you think you do, let us know and we can advise about policies auto-compact. -void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas) +void ImFontAtlasTextureCompact(ImFontAtlas* atlas) { ImFontAtlasBuilder* builder = atlas->Builder; ImFontAtlasBuildDiscardBakes(atlas, 1); ImTextureData* old_tex = atlas->TexData; ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height); - ImVec2i new_tex_size = ImFontAtlasBuildGetTextureSizeEstimate(atlas); + ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); if (builder->RectsDiscardedCount == 0 && new_tex_size.x == old_tex_size.x && new_tex_size.y == old_tex_size.y) return; - ImFontAtlasBuildRepackTexture(atlas, new_tex_size.x, new_tex_size.y); + ImFontAtlasTextureRepack(atlas, new_tex_size.x, new_tex_size.y); } // Start packing over current empty texture @@ -4153,7 +4153,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) // Create initial texture size if (atlas->TexData == NULL || atlas->TexData->Pixels == NULL) - ImFontAtlasBuildAddTexture(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); + ImFontAtlasTextureAdd(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); if (atlas->FontLoader->LoaderInit) @@ -4170,7 +4170,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) // Register fonts ImFontAtlasBuildUpdatePointers(atlas); for (ImFontConfig& cfg : atlas->Sources) - ImFontAtlasBuildAddFont(atlas, &cfg); + ImFontAtlasFontInitSource(atlas, &cfg); // Update UV coordinates etc. stored in bound ImDrawListSharedData instance ImFontAtlasUpdateDrawListsSharedData(atlas); @@ -4182,7 +4182,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) { for (ImFont* font : atlas->Fonts) - ImFontAtlasBuildDestroyFontOutput(atlas, font); + ImFontAtlasFontDestroyOutput(atlas, font); if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) { atlas->FontLoader->LoaderShutdown(atlas); @@ -4299,7 +4299,7 @@ ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFon } // Resize or repack atlas! (this should be a rare event) - ImFontAtlasBuildMakeSpace(atlas); + ImFontAtlasTextureMakeSpace(atlas); } builder->MaxRectBounds.x = ImMax(builder->MaxRectBounds.x, r.x + r.w + pack_padding); @@ -4992,7 +4992,7 @@ ImFont::~ImFont() void ImFont::ClearOutputData() { if (ImFontAtlas* atlas = ContainerAtlas) - ImFontAtlasBuildDiscardFontBakes(atlas, this); + ImFontAtlasFontDiscardOutputBakes(atlas, this); FallbackChar = EllipsisChar = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); LastBaked = NULL; @@ -5197,7 +5197,7 @@ ImFontBaked* ImFont::GetFontBaked(float size) ImFontAtlas* atlas = ContainerAtlas; ImFontAtlasBuilder* builder = atlas->Builder; - baked = ImFontAtlasBuildGetFontBaked(atlas, this, size); + baked = ImFontAtlasBakedGetOrAdd(atlas, this, size); if (baked == NULL) return NULL; baked->LastUsedFrame = builder->FrameCount; @@ -5205,7 +5205,7 @@ ImFontBaked* ImFont::GetFontBaked(float size) return baked; } -ImFontBaked* ImFontAtlasBuildGetFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size) +ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size) { // FIXME-NEWATLAS: Design for picking a nearest size based on some criteria? // FIXME-NEWATLAS: Altering font density won't work right away. @@ -5223,7 +5223,7 @@ ImFontBaked* ImFontAtlasBuildGetFontBaked(ImFontAtlas* atlas, ImFont* font, floa // FIXME-OPT: This is not an optimal query. if ((font->Flags & ImFontFlags_LockBakedSizes) || atlas->Locked) { - baked = ImFontAtlasBuildGetClosestFontBakedMatch(atlas, font, font_size); + baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size); if (baked != NULL) return baked; if (atlas->Locked) @@ -5234,7 +5234,7 @@ ImFontBaked* ImFontAtlasBuildGetFontBaked(ImFontAtlas* atlas, ImFont* font, floa } // Create new - baked = ImFontAtlasBuildAddFontBaked(atlas, font, font_size, baked_id); + baked = ImFontAtlasBakedAdd(atlas, font, font_size, baked_id); *p_baked_in_map = baked; // To avoid 'builder->BakedMap.SetVoidPtr(baked_id, baked);' while we can. return baked; } diff --git a/imgui_internal.h b/imgui_internal.h index 137ba7d46..3274940c0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3772,32 +3772,32 @@ IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); IMGUI_API void ImFontAtlasBuildClear(ImFontAtlas* atlas); // Clear output and custom rects -IMGUI_API ImTextureData* ImFontAtlasBuildAddTexture(ImFontAtlas* atlas, int w, int h); -IMGUI_API void ImFontAtlasBuildMakeSpace(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildRepackTexture(ImFontAtlas* atlas, int w, int h); -IMGUI_API void ImFontAtlasBuildGrowTexture(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); -IMGUI_API void ImFontAtlasBuildCompactTexture(ImFontAtlas* atlas); -IMGUI_API ImVec2i ImFontAtlasBuildGetTextureSizeEstimate(ImFontAtlas* atlas); +IMGUI_API ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); +IMGUI_API void ImFontAtlasTextureCompact(ImFontAtlas* atlas); +IMGUI_API ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas); -IMGUI_API bool ImFontAtlasBuildAddFont(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); -IMGUI_API bool ImFontAtlasBuildInitFontOutput(ImFontAtlas* atlas, ImFont* font); // Using DestroyFontOutput/InitFontOutput sequence useful notably if font loader params have changed -IMGUI_API void ImFontAtlasBuildDestroyFontOutput(ImFontAtlas* atlas, ImFont* font); -IMGUI_API void ImFontAtlasBuildDestroyFontSourceData(ImFontAtlas* atlas, ImFontConfig* src); - -IMGUI_API ImFontBaked* ImFontAtlasBuildGetFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size); -IMGUI_API ImFontBaked* ImFontAtlasBuildAddFontBaked(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); -IMGUI_API ImFontBaked* ImFontAtlasBuildGetClosestFontBakedMatch(ImFontAtlas* atlas, ImFont* font, float font_size); IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); -IMGUI_API void ImFontAtlasBuildDiscardFontBakes(ImFontAtlas* atlas, ImFont* font); -IMGUI_API void ImFontAtlasBuildDiscardFontBaked(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); -IMGUI_API void ImFontAtlasBuildDiscardFontBakedGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); -IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); -IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); +IMGUI_API bool ImFontAtlasFontInitSource(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font); // Using FontDestroyOutput/FontInitOutput sequence useful notably if font loader params have changed +IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasFontDiscardOutputBakes(ImFontAtlas* atlas, ImFont* font); + IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size); +IMGUI_API ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size); +IMGUI_API ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size); +IMGUI_API ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); +IMGUI_API void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); +IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); +IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); +IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); From e7efe94fd2fe8c8707ad2692083f26c64062b624 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Apr 2025 17:56:00 +0200 Subject: [PATCH 1021/2359] Fonts: shallow rework of ImFontAtlasBakedAddFontGlyph() to facilitate upcoming change. --- imgui.h | 2 +- imgui_draw.cpp | 38 +++++++++++++++++++------------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/imgui.h b/imgui.h index f99eaedd3..b63b0ed4e 100644 --- a/imgui.h +++ b/imgui.h @@ -3479,7 +3479,7 @@ struct ImFontConfig }; // Hold rendering data for one glyph. -// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this) +// (Note: some language parsers may fail to convert the bitfield members, in this case maybe drop store a single u32 or we can rework this) struct ImFontGlyph { unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 40ae02ed5..c311b18af 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5013,23 +5013,23 @@ bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. // Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). -// 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. +// - 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph) { int glyph_idx = baked->Glyphs.Size; baked->Glyphs.push_back(*in_glyph); - ImFontGlyph& glyph = baked->Glyphs[glyph_idx]; + ImFontGlyph* glyph = &baked->Glyphs[glyph_idx]; IM_ASSERT(baked->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. // Set UV from packed rectangle - if (glyph.PackId != ImFontAtlasRectId_Invalid) + if (glyph->PackId != ImFontAtlasRectId_Invalid) { - ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); - IM_ASSERT(glyph.U0 == 0.0f && glyph.V0 == 0.0f && glyph.U1 == 0.0f && glyph.V1 == 0.0f); - glyph.U0 = (r->x) * atlas->TexUvScale.x; - glyph.V0 = (r->y) * atlas->TexUvScale.y; - glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; - glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph->PackId); + IM_ASSERT(glyph->U0 == 0.0f && glyph->V0 == 0.0f && glyph->U1 == 0.0f && glyph->V1 == 0.0f); + glyph->U0 = (r->x) * atlas->TexUvScale.x; + glyph->V0 = (r->y) * atlas->TexUvScale.y; + glyph->U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph->V1 = (r->y + r->h) * atlas->TexUvScale.y; baked->MetricsTotalSurface += r->w * r->h; } @@ -5037,12 +5037,12 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked { // Clamp & recenter if needed const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0].SizePixels; - float advance_x = ImClamp(glyph.AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); - if (advance_x != glyph.AdvanceX) + float advance_x = ImClamp(glyph->AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); + if (advance_x != glyph->AdvanceX) { - float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - glyph.AdvanceX) * 0.5f) : (advance_x - glyph.AdvanceX) * 0.5f; - glyph.X0 += char_off_x; - glyph.X1 += char_off_x; + float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - glyph->AdvanceX) * 0.5f) : (advance_x - glyph->AdvanceX) * 0.5f; + glyph->X0 += char_off_x; + glyph->X1 += char_off_x; } // Snap to pixel @@ -5050,20 +5050,20 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked advance_x = IM_ROUND(advance_x); // Bake spacing - glyph.AdvanceX = advance_x + src->GlyphExtraAdvanceX; + glyph->AdvanceX = advance_x + src->GlyphExtraAdvanceX; } - if (glyph.Colored) + if (glyph->Colored) atlas->TexPixelsUseColors = atlas->TexData->UseColors = true; // Update lookup tables - int codepoint = glyph.Codepoint; + const int codepoint = glyph->Codepoint; ImFontBaked_BuildGrowIndex(baked, codepoint + 1); - baked->IndexAdvanceX[codepoint] = glyph.AdvanceX; + baked->IndexAdvanceX[codepoint] = glyph->AdvanceX; baked->IndexLookup[codepoint] = (ImU16)glyph_idx; const int page_n = codepoint / 8192; baked->ContainerFont->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); - return &glyph; + return glyph; } // Copy to texture, post-process and queue update for backend From 2b0d49a9054d21bc5cea57a8b21b8a7e4c885b43 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 24 Apr 2025 17:54:16 +0200 Subject: [PATCH 1022/2359] Fonts: make ImFont::Sources a vector. Later it should become a ImSpan<> --- imgui.cpp | 44 +++++++++---------- imgui.h | 5 +-- imgui_draw.cpp | 72 ++++++++++++++------------------ misc/freetype/imgui_freetype.cpp | 4 +- 4 files changed, 58 insertions(+), 67 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8f7c8fe62..04cb11264 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16612,7 +16612,7 @@ void ImGui::DebugNodeFont(ImFont* font) ImGuiContext& g = *GImGui; ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; ImFontAtlas* atlas = font->ContainerAtlas; - bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->SourcesCount); + bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size); // Display preview text if (!opened) @@ -16652,28 +16652,30 @@ void ImGui::DebugNodeFont(ImFont* font) Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar); Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar); - for (int src_n = 0; src_n < font->SourcesCount; src_n++) - if (ImFontConfig* src = &font->Sources[src_n]) - if (TreeNode(src, "Input %d: \'%s\', Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", - src_n, src->Name, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y)) - { - const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - Text("Loader: '%s'", loader->Name ? loader->Name : "N/A"); + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + { + ImFontConfig* src = font->Sources[src_n]; + if (TreeNode(src, "Input %d: \'%s\', Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y)) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + Text("Loader: '%s'", loader->Name ? loader->Name : "N/A"); #ifdef IMGUI_ENABLE_FREETYPE - if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0) + if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0) + { + unsigned int loader_flags = src->FontBuilderFlags; + Text("FreeType Loader Flags: 0x%08X", loader_flags); + if (ImGuiFreeType::DebugEditFontBuilderFlags(&loader_flags)) { - unsigned int loader_flags = src->FontBuilderFlags; - Text("FreeType Loader Flags: 0x%08X", loader_flags); - if (ImGuiFreeType::DebugEditFontBuilderFlags(&loader_flags)) - { - ImFontAtlasFontDestroyOutput(atlas, font); - src->FontBuilderFlags = loader_flags; - ImFontAtlasFontInitOutput(atlas, font); - } + ImFontAtlasFontDestroyOutput(atlas, font); + src->FontBuilderFlags = loader_flags; + ImFontAtlasFontInitOutput(atlas, font); } -#endif - TreePop(); } +#endif + TreePop(); + } + } // Display all glyphs of the fonts in separate pages of 256 characters for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++) @@ -16691,9 +16693,9 @@ void ImGui::DebugNodeFont(ImFont* font) const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface); Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent); Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt); - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + for (int src_n = 0; src_n < font->Sources.Size; src_n++) { - ImFontConfig* src = &font->Sources[src_n]; + ImFontConfig* src = font->Sources[src_n]; int oversample_h, oversample_v; ImFontAtlasBuildGetOversampleFactors(src, baked->Size, &oversample_h, &oversample_v); BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", diff --git a/imgui.h b/imgui.h index b63b0ed4e..005c9c01b 100644 --- a/imgui.h +++ b/imgui.h @@ -3759,8 +3759,7 @@ struct ImFont // Conceptually Sources[] is the list of font sources merged to create this font. ImGuiID FontId; // Unique identifier for the font float DefaultSize; // 4 // in // Default font size - short SourcesCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. - ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances + ImVector Sources; // 16 // in // List of sources. Pointers within ContainerAtlas->Sources[] ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() @@ -3773,7 +3772,7 @@ struct ImFont IMGUI_API ImFontBaked* GetFontBaked(float font_size); // Get or create baked data for given size IMGUI_API bool IsGlyphInFont(ImWchar c); bool IsLoaded() const { return ContainerAtlas != NULL; } - const char* GetDebugName() const { return Sources ? Sources[0].Name : ""; } // Fill ImFontConfig::Name. + const char* GetDebugName() const { return Sources.Size ? Sources[0]->Name : ""; } // Fill ImFontConfig::Name. // [Internal] Don't use! // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c311b18af..30bdba58c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2657,8 +2657,7 @@ void ImFontAtlas::ClearInputData() for (ImFont* font : Fonts) { // When clearing this we lose access to the font name and other information used to build the font. - font->Sources = NULL; - font->SourcesCount = 0; + font->Sources.clear(); font->Flags |= ImFontFlags_NoLoadGlyphs; } Sources.clear(); @@ -3027,14 +3026,14 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) IM_ASSERT(font_cfg->FontLoaderData == NULL); // Pointers to Sources are otherwise dangling - font->SourcesCount++; + font->Sources.push_back(font_cfg); ImFontAtlasBuildUpdatePointers(this); if (!ImFontAtlasFontInitSource(this, font_cfg)) { // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) ImFontAtlasFontDestroySourceData(this, font_cfg); Sources.pop_back(); - font->SourcesCount--; + font->Sources.pop_back(); if (!font_cfg->MergeMode) { IM_DELETE(font); @@ -3185,14 +3184,16 @@ void ImFontAtlas::RemoveFont(ImFont* font) font->ClearOutputData(); ImFontAtlasFontDestroyOutput(this, font); - for (int src_n = 0; src_n < font->SourcesCount; src_n++) - ImFontAtlasFontDestroySourceData(this, &font->Sources[src_n]); + for (ImFontConfig* src : font->Sources) + { + ImFontAtlasFontDestroySourceData(this, src); + Sources.erase(src); + } bool removed = Fonts.find_erase(font); IM_ASSERT(removed); IM_UNUSED(removed); - Sources.erase(font->Sources, font->Sources + font->SourcesCount); ImFontAtlasBuildUpdatePointers(this); font->ContainerAtlas = NULL; @@ -3278,7 +3279,7 @@ ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float glyph.Visible = true; glyph.Colored = true; // FIXME: Arbitrary glyph.PackId = r_id; - ImFontAtlasBakedAddFontGlyph(this, baked, &font->Sources[0], &glyph); + ImFontAtlasBakedAddFontGlyph(this, baked, font->Sources[0], &glyph); return r_id; } #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -3382,15 +3383,13 @@ void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas) atlas->Builder->PreloadedAllGlyphsRanges = true; for (ImFont* font : atlas->Fonts) { - ImFontConfig* src = &font->Sources[0]; - ImFontBaked* baked = font->GetFontBaked(src->SizePixels); + ImFontBaked* baked = font->GetFontBaked(font->Sources[0]->SizePixels); if (font->FallbackChar != 0) baked->FindGlyph(font->FallbackChar); if (font->EllipsisChar != 0) baked->FindGlyph(font->EllipsisChar); - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + for (ImFontConfig* src : font->Sources) { - src = &font->Sources[src_n]; const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault(); for (; ranges[0]; ranges += 2) for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 @@ -3399,15 +3398,13 @@ void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas) } } +// FIXME: May make ImFont::Sources a ImSpan<> and move ownership to ImFontAtlas void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) { - for (int src_n = 0; src_n < atlas->Sources.Size; src_n++) - { - ImFontConfig* src = &atlas->Sources[src_n]; - ImFont* font = src->DstFont; - if (!src->MergeMode) - font->Sources = src; - } + for (ImFont* font : atlas->Fonts) + font->Sources.resize(0); + for (ImFontConfig& src : atlas->Sources) + src.DstFont->Sources.push_back(&src); } // Render a white-colored bitmap encoded in a string @@ -3542,9 +3539,8 @@ static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas) bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font) { bool ret = true; - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + for (ImFontConfig* src : font->Sources) { - ImFontConfig* src = &font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (loader && loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src)) ret = false; @@ -3557,9 +3553,8 @@ bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font) void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font) { font->ClearOutputData(); - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + for (ImFontConfig* src : font->Sources) { - ImFontConfig* src = &font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (loader && loader->FontSrcDestroy != NULL) loader->FontSrcDestroy(atlas, src); @@ -3576,7 +3571,7 @@ bool ImFontAtlasFontInitSource(ImFontAtlas* atlas, ImFontConfig* src) font->ClearOutputData(); //font->FontSize = src->SizePixels; font->ContainerAtlas = atlas; - IM_ASSERT(font->Sources == src); + IM_ASSERT(font->Sources[0] == src); } const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; @@ -3688,10 +3683,8 @@ static void ImFontAtlasBuildSetupFontBakedBlanks(ImFontAtlas* atlas, ImFontBaked // (note that this is called again for fonts with MergeMode) void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src) { - const int src_idx_in_font = (int)(src - font->Sources); - IM_ASSERT(src_idx_in_font >= 0 && src_idx_in_font < font->SourcesCount); IM_UNUSED(atlas); - IM_UNUSED(src_idx_in_font); + IM_ASSERT(font->Sources.contains(src)); // Find Fallback character. Actual glyph loaded in GetFontBaked(). const ImWchar fallback_chars[] = { font->FallbackChar, (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; @@ -3747,17 +3740,15 @@ ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_si // Initialize backend data size_t loader_data_size = 0; - for (int src_n = 0; src_n < font->SourcesCount; src_n++) // Cannot easily be cached as we allow changing backend + for (ImFontConfig* src : font->Sources) // Cannot easily be cached as we allow changing backend { - ImFontConfig* src = &font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; loader_data_size += loader->FontBakedSrcLoaderDataSize; } baked->FontLoaderDatas = (loader_data_size > 0) ? IM_ALLOC(loader_data_size) : NULL; char* loader_data_p = (char*)baked->FontLoaderDatas; - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + for (ImFontConfig* src : font->Sources) { - ImFontConfig* src = &font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (loader->FontBakedInit) loader->FontBakedInit(atlas, src, baked, loader_data_p); @@ -3802,9 +3793,8 @@ void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* bake ImFontAtlasPackDiscardRect(atlas, glyph.PackId); char* loader_data_p = (char*)baked->FontLoaderDatas; - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + for (ImFontConfig* src : font->Sources) { - ImFontConfig* src = &font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (loader->FontBakedDestroy) loader->FontBakedDestroy(atlas, src, baked, loader_data_p); @@ -4384,9 +4374,9 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep // Call backend char* loader_user_data_p = (char*)baked->FontLoaderDatas; - for (int src_n = 0; src_n < font->SourcesCount; src_n++) + int src_n = 0; + for (ImFontConfig* src : font->Sources) { - ImFontConfig* src = &font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) if (ImFontGlyph* glyph = loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint)) @@ -4396,6 +4386,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep return glyph; } loader_user_data_p += loader->FontBakedSrcLoaderDataSize; + src_n++; } // Lazily load fallback glyph @@ -4491,8 +4482,8 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); else bd_font_data->ScaleFactor = -stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); - if (src > src->DstFont->Sources) - bd_font_data->ScaleFactor *= src->SizePixels / src->DstFont->Sources[0].SizePixels; // FIXME-NEWATLAS: Should tidy up that a bit + if (src != src->DstFont->Sources[0]) + bd_font_data->ScaleFactor *= src->SizePixels / src->DstFont->Sources[0]->SizePixels; // FIXME-NEWATLAS: Should tidy up that a bit return true; } @@ -4594,7 +4585,7 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, if (oversample_v > 1) stbtt__v_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_v); - const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0].SizePixels; + const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0]->SizePixels; float font_off_x = (src->GlyphOffset.x * offsets_scale); float font_off_y = (src->GlyphOffset.y * offsets_scale); if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. @@ -5036,7 +5027,7 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked if (src != NULL) { // Clamp & recenter if needed - const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0].SizePixels; + const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0]->SizePixels; float advance_x = ImClamp(glyph->AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); if (advance_x != glyph->AdvanceX) { @@ -5147,9 +5138,8 @@ bool ImFontBaked::IsGlyphLoaded(ImWchar c) bool ImFont::IsGlyphInFont(ImWchar c) { ImFontAtlas* atlas = ContainerAtlas; - for (int src_n = 0; src_n < SourcesCount; src_n++) + for (ImFontConfig* src : Sources) { - ImFontConfig* src = &Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (loader->FontSrcContainsGlyph != NULL && loader->FontSrcContainsGlyph(atlas, src, c)) return true; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 5151a90d5..b4263fc82 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -436,7 +436,7 @@ void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { IM_UNUSED(atlas); - const float size = baked->Size * (src->SizePixels / baked->ContainerFont->Sources[0].SizePixels); // FIXME-NEWATLAS: Should tidy up that a bit + const float size = baked->Size * (src->SizePixels / baked->ContainerFont->Sources[0]->SizePixels); // FIXME-NEWATLAS: Should tidy up that a bit ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; bd_font_data->BakedLastActivated = baked; @@ -541,7 +541,7 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data; bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w); - const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0].SizePixels; + const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0]->SizePixels; float font_off_x = (src->GlyphOffset.x * offsets_scale); float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent; if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. From 5310f5fba347d32572206fe80439314507c90ab1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 24 Apr 2025 18:27:55 +0200 Subject: [PATCH 1023/2359] Fonts: rework toward reducing reliance on ImFontConfig::DstFont since we ought to separate them. --- imgui_draw.cpp | 35 +++++++++++++++++++++-------------- imgui_internal.h | 3 ++- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 30bdba58c..7bb6ae108 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2998,10 +2998,14 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) font = Fonts.back(); } + // Add to list Sources.push_back(*font_cfg_in); ImFontConfig* font_cfg = &Sources.back(); if (font_cfg->DstFont == NULL) font_cfg->DstFont = font; + font->Sources.push_back(font_cfg); + ImFontAtlasBuildUpdatePointers(this); // Pointers to Sources are otherwise dangling after we called Sources.push_back(). + if (font_cfg->FontDataOwnedByAtlas == false) { font_cfg->FontDataOwnedByAtlas = true; @@ -3025,10 +3029,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) } IM_ASSERT(font_cfg->FontLoaderData == NULL); - // Pointers to Sources are otherwise dangling - font->Sources.push_back(font_cfg); - ImFontAtlasBuildUpdatePointers(this); - if (!ImFontAtlasFontInitSource(this, font_cfg)) + if (!ImFontAtlasFontSourceInit(this, font_cfg)) { // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) ImFontAtlasFontDestroySourceData(this, font_cfg); @@ -3041,6 +3042,8 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) } return NULL; } + ImFontAtlasFontSourceAddToFont(this, font, font_cfg); + return font; } @@ -3563,9 +3566,16 @@ void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font) //----------------------------------------------------------------------------------------------------------------------------- -bool ImFontAtlasFontInitSource(ImFontAtlas* atlas, ImFontConfig* src) +bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src) +{ + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src)) + return false; + return true; +} + +void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src) { - ImFont* font = src->DstFont; if (src->MergeMode == false) { font->ClearOutputData(); @@ -3573,14 +3583,8 @@ bool ImFontAtlasFontInitSource(ImFontAtlas* atlas, ImFontConfig* src) font->ContainerAtlas = atlas; IM_ASSERT(font->Sources[0] == src); } - - const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - if (loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src)) - return false; - atlas->TexIsBuilt = false; // For legacy backends ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); - return true; } void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src) @@ -4104,6 +4108,11 @@ void ImFontAtlasBuildClear(ImFontAtlas* atlas) ImFontAtlasBuildDestroy(atlas); ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y); ImFontAtlasBuildInit(atlas); + for (ImFontConfig& src : atlas->Sources) + ImFontAtlasFontSourceInit(atlas, &src); + for (ImFont* font : atlas->Fonts) + for (ImFontConfig* src : font->Sources) + ImFontAtlasFontSourceAddToFont(atlas, font, src); } // You should not need to call this manually! @@ -4159,8 +4168,6 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) // Register fonts ImFontAtlasBuildUpdatePointers(atlas); - for (ImFontConfig& cfg : atlas->Sources) - ImFontAtlasFontInitSource(atlas, &cfg); // Update UV coordinates etc. stored in bound ImDrawListSharedData instance ImFontAtlasUpdateDrawListsSharedData(atlas); diff --git a/imgui_internal.h b/imgui_internal.h index 3274940c0..28e907488 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3784,7 +3784,8 @@ IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* a IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); -IMGUI_API bool ImFontAtlasFontInitSource(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); IMGUI_API void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font); // Using FontDestroyOutput/FontInitOutput sequence useful notably if font loader params have changed IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font); From 6a455e1281535bc7d79eb40445892b7894fbbbac Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 26 Apr 2025 17:05:36 +0200 Subject: [PATCH 1024/2359] imgui_freetype: moving data out of ImGui_ImplFreeType_FontSrcData. The reasoning behind that we would ideally transition ImGui_ImplFreeType_FontSrcData to be shared between fonts using same source. --- misc/freetype/imgui_freetype.cpp | 45 +++++++++++++------------------- 1 file changed, 18 insertions(+), 27 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index b4263fc82..a667f458d 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -151,17 +151,11 @@ namespace ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } }; - // Stored in ImFontBaked::FontLoaderDatas: pointer to SourcesCount instances of this. ALLOCATED BY CORE. - struct ImGui_ImplFreeType_FontSrcBakedData - { - FT_Size FtSize; // This represent a FT_Face with a given size. - ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } - }; - // Stored in ImFontConfig::FontLoaderData. ALLOCATED BY US. struct ImGui_ImplFreeType_FontSrcData { - bool InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. + // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. + bool InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeBuilderFlags extra_user_flags); void CloseFont(); const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch); @@ -170,15 +164,19 @@ namespace // Members FT_Face FtFace; - unsigned int UserFlags; // = ImFontConfig::RasterizerFlags + ImGuiFreeTypeBuilderFlags UserFlags; // = ImFontConfig::FontBuilderFlags FT_Int32 LoadFlags; - FT_Render_Mode RenderMode; - float RasterizationDensity; - float InvRasterizationDensity; ImFontBaked* BakedLastActivated; }; - bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_font_builder_flags) + // Stored in ImFontBaked::FontLoaderDatas: pointer to SourcesCount instances of this. ALLOCATED BY CORE. + struct ImGui_ImplFreeType_FontSrcBakedData + { + FT_Size FtSize; // This represent a FT_Face with a given size. + ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } + }; + + bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeBuilderFlags extra_font_builder_flags) { FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (uint32_t)src->FontDataSize, (uint32_t)src->FontNo, &FtFace); if (error != 0) @@ -188,7 +186,7 @@ namespace return false; // Convert to FreeType flags (NB: Bold and Oblique are processed separately) - UserFlags = src->FontBuilderFlags | extra_font_builder_flags; + UserFlags = (ImGuiFreeTypeBuilderFlags)(src->FontBuilderFlags | extra_font_builder_flags); LoadFlags = 0; if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0) @@ -210,17 +208,9 @@ namespace else LoadFlags |= FT_LOAD_TARGET_NORMAL; - if (UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome) - RenderMode = FT_RENDER_MODE_MONO; - else - RenderMode = FT_RENDER_MODE_NORMAL; - if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor) LoadFlags |= FT_LOAD_COLOR; - RasterizationDensity = src->RasterizerDensity; - InvRasterizationDensity = 1.0f / RasterizationDensity; - return true; } @@ -415,7 +405,7 @@ bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) IM_ASSERT(src->FontLoaderData == NULL); src->FontLoaderData = bd_font_data; - if (!bd_font_data->InitFont(bd->Library, src, atlas->FontBuilderFlags)) + if (!bd_font_data->InitFont(bd->Library, src, (ImGuiFreeTypeBuilderFlags)atlas->FontBuilderFlags)) { IM_DELETE(bd_font_data); src->FontLoaderData = NULL; @@ -456,7 +446,7 @@ bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF FT_Size_RequestRec req; req.type = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; req.width = 0; - req.height = (uint32_t)(size * 64 * bd_font_data->RasterizationDensity); + req.height = (uint32_t)(size * 64 * src->RasterizerDensity); req.horiResolution = 0; req.vertResolution = 0; FT_Request_Size(bd_font_data->FtFace, &req); @@ -466,7 +456,7 @@ bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF { // Read metrics FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; - const float scale = bd_font_data->InvRasterizationDensity; + const float scale = 1.0f / src->RasterizerDensity; baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. @@ -509,7 +499,8 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon // Render glyph into a bitmap (currently held by FreeType) FT_Face face = bd_font_data->FtFace; FT_GlyphSlot slot = face->glyph; - FT_Error error = FT_Render_Glyph(slot, bd_font_data->RenderMode); + FT_Render_Mode render_mode = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL; + FT_Error error = FT_Render_Glyph(slot, render_mode); const FT_Bitmap* ft_bitmap = &slot->bitmap; if (error != 0 || ft_bitmap == nullptr) return NULL; @@ -522,7 +513,7 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon ImFontGlyph glyph_in = {}; ImFontGlyph* glyph = &glyph_in; glyph->Codepoint = codepoint; - glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) * bd_font_data->InvRasterizationDensity; + glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) / src->RasterizerDensity; // Pack and retrieve position inside texture atlas if (is_visible) From 42e7bb80b642b48c7a5c54775be3bec19bac571b Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 26 Apr 2025 17:24:38 +0200 Subject: [PATCH 1025/2359] imgui_freetype: removed anonymous namespace + extracting two functions outside of ImGui_ImplFreeType_FontSrcData. --- misc/freetype/imgui_freetype.cpp | 377 +++++++++++++++---------------- 1 file changed, 186 insertions(+), 191 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index a667f458d..8ad2d6cea 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -110,210 +110,205 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ #define FT_CEIL(X) (((X + 63) & -64) / 64) // From SDL_ttf: Handy routines for converting from fixed point #define FT_SCALEFACTOR 64.0f -namespace +// Glyph metrics: +// -------------- +// +// xmin xmax +// | | +// |<-------- width -------->| +// | | +// | +-------------------------+----------------- ymax +// | | ggggggggg ggggg | ^ ^ +// | | g:::::::::ggg::::g | | | +// | | g:::::::::::::::::g | | | +// | | g::::::ggggg::::::gg | | | +// | | g:::::g g:::::g | | | +// offsetX -|-------->| g:::::g g:::::g | offsetY | +// | | g:::::g g:::::g | | | +// | | g::::::g g:::::g | | | +// | | g:::::::ggggg:::::g | | | +// | | g::::::::::::::::g | | height +// | | gg::::::::::::::g | | | +// baseline ---*---------|---- gggggggg::::::g-----*-------- | +// / | | g:::::g | | +// origin | | gggggg g:::::g | | +// | | g:::::gg gg:::::g | | +// | | g::::::ggg:::::::g | | +// | | gg:::::::::::::g | | +// | | ggg::::::ggg | | +// | | gggggg | v +// | +-------------------------+----------------- ymin +// | | +// |------------- advanceX ----------->| + +// Stored in ImFontAtlas::FontLoaderData. ALLOCATED BY US. +struct ImGui_ImplFreeType_Data { - // Glyph metrics: - // -------------- - // - // xmin xmax - // | | - // |<-------- width -------->| - // | | - // | +-------------------------+----------------- ymax - // | | ggggggggg ggggg | ^ ^ - // | | g:::::::::ggg::::g | | | - // | | g:::::::::::::::::g | | | - // | | g::::::ggggg::::::gg | | | - // | | g:::::g g:::::g | | | - // offsetX -|-------->| g:::::g g:::::g | offsetY | - // | | g:::::g g:::::g | | | - // | | g::::::g g:::::g | | | - // | | g:::::::ggggg:::::g | | | - // | | g::::::::::::::::g | | height - // | | gg::::::::::::::g | | | - // baseline ---*---------|---- gggggggg::::::g-----*-------- | - // / | | g:::::g | | - // origin | | gggggg g:::::g | | - // | | g:::::gg gg:::::g | | - // | | g::::::ggg:::::::g | | - // | | gg:::::::::::::g | | - // | | ggg::::::ggg | | - // | | gggggg | v - // | +-------------------------+----------------- ymin - // | | - // |------------- advanceX ----------->| + FT_Library Library; + FT_MemoryRec_ MemoryManager; + ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } +}; - // Stored in ImFontAtlas::FontLoaderData. ALLOCATED BY US. - struct ImGui_ImplFreeType_Data +// Stored in ImFontConfig::FontLoaderData. ALLOCATED BY US. +struct ImGui_ImplFreeType_FontSrcData +{ + // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. + bool InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeBuilderFlags extra_user_flags); + void CloseFont(); + ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); } + ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); } + + // Members + FT_Face FtFace; + ImGuiFreeTypeBuilderFlags UserFlags; // = ImFontConfig::FontBuilderFlags + FT_Int32 LoadFlags; + ImFontBaked* BakedLastActivated; +}; + +// Stored in ImFontBaked::FontLoaderDatas: pointer to SourcesCount instances of this. ALLOCATED BY CORE. +struct ImGui_ImplFreeType_FontSrcBakedData +{ + FT_Size FtSize; // This represent a FT_Face with a given size. + ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } +}; + +bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeBuilderFlags extra_font_builder_flags) +{ + FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (uint32_t)src->FontDataSize, (uint32_t)src->FontNo, &FtFace); + if (error != 0) + return false; + error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE); + if (error != 0) + return false; + + // Convert to FreeType flags (NB: Bold and Oblique are processed separately) + UserFlags = (ImGuiFreeTypeBuilderFlags)(src->FontBuilderFlags | extra_font_builder_flags); + + LoadFlags = 0; + if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0) + LoadFlags |= FT_LOAD_NO_BITMAP; + + if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting) + LoadFlags |= FT_LOAD_NO_HINTING; + else + src->PixelSnapH = true; // FIXME: A bit weird to do this this way. + + if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint) + LoadFlags |= FT_LOAD_NO_AUTOHINT; + if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint) + LoadFlags |= FT_LOAD_FORCE_AUTOHINT; + if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting) + LoadFlags |= FT_LOAD_TARGET_LIGHT; + else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting) + LoadFlags |= FT_LOAD_TARGET_MONO; + else + LoadFlags |= FT_LOAD_TARGET_NORMAL; + + if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor) + LoadFlags |= FT_LOAD_COLOR; + + return true; +} + +void ImGui_ImplFreeType_FontSrcData::CloseFont() +{ + if (FtFace) { - FT_Library Library; - FT_MemoryRec_ MemoryManager; - ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } - }; - - // Stored in ImFontConfig::FontLoaderData. ALLOCATED BY US. - struct ImGui_ImplFreeType_FontSrcData - { - // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. - bool InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeBuilderFlags extra_user_flags); - void CloseFont(); - const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); - void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch); - ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); } - ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); } - - // Members - FT_Face FtFace; - ImGuiFreeTypeBuilderFlags UserFlags; // = ImFontConfig::FontBuilderFlags - FT_Int32 LoadFlags; - ImFontBaked* BakedLastActivated; - }; - - // Stored in ImFontBaked::FontLoaderDatas: pointer to SourcesCount instances of this. ALLOCATED BY CORE. - struct ImGui_ImplFreeType_FontSrcBakedData - { - FT_Size FtSize; // This represent a FT_Face with a given size. - ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } - }; - - bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeBuilderFlags extra_font_builder_flags) - { - FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (uint32_t)src->FontDataSize, (uint32_t)src->FontNo, &FtFace); - if (error != 0) - return false; - error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE); - if (error != 0) - return false; - - // Convert to FreeType flags (NB: Bold and Oblique are processed separately) - UserFlags = (ImGuiFreeTypeBuilderFlags)(src->FontBuilderFlags | extra_font_builder_flags); - - LoadFlags = 0; - if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0) - LoadFlags |= FT_LOAD_NO_BITMAP; - - if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting) - LoadFlags |= FT_LOAD_NO_HINTING; - else - src->PixelSnapH = true; // FIXME: A bit weird to do this this way. - - if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint) - LoadFlags |= FT_LOAD_NO_AUTOHINT; - if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint) - LoadFlags |= FT_LOAD_FORCE_AUTOHINT; - if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting) - LoadFlags |= FT_LOAD_TARGET_LIGHT; - else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting) - LoadFlags |= FT_LOAD_TARGET_MONO; - else - LoadFlags |= FT_LOAD_TARGET_NORMAL; - - if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor) - LoadFlags |= FT_LOAD_COLOR; - - return true; + FT_Done_Face(FtFace); + FtFace = nullptr; } +} - void ImGui_ImplFreeType_FontSrcData::CloseFont() - { - if (FtFace) - { - FT_Done_Face(FtFace); - FtFace = nullptr; - } - } +static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_FontSrcData* src_data, uint32_t codepoint) +{ + uint32_t glyph_index = FT_Get_Char_Index(src_data->FtFace, codepoint); + if (glyph_index == 0) + return nullptr; - const FT_Glyph_Metrics* ImGui_ImplFreeType_FontSrcData::LoadGlyph(uint32_t codepoint) - { - uint32_t glyph_index = FT_Get_Char_Index(FtFace, codepoint); - if (glyph_index == 0) - return nullptr; + // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts. + // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076 + // - https://github.com/ocornut/imgui/issues/4567 + // - https://github.com/ocornut/imgui/issues/4566 + // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. + FT_Error error = FT_Load_Glyph(src_data->FtFace, glyph_index, src_data->LoadFlags); + if (error) + return nullptr; - // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts. - // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076 - // - https://github.com/ocornut/imgui/issues/4567 - // - https://github.com/ocornut/imgui/issues/4566 - // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. - FT_Error error = FT_Load_Glyph(FtFace, glyph_index, LoadFlags); - if (error) - return nullptr; - - // Need an outline for this to work - FT_GlyphSlot slot = FtFace->glyph; + // Need an outline for this to work + FT_GlyphSlot slot = src_data->FtFace->glyph; #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG) - IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG); + IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG); #else #if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12)) - IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font"); + IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font"); #endif - IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP); + IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP); #endif // IMGUI_ENABLE_FREETYPE_LUNASVG - // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting) - if (UserFlags & ImGuiFreeTypeBuilderFlags_Bold) - FT_GlyphSlot_Embolden(slot); - if (UserFlags & ImGuiFreeTypeBuilderFlags_Oblique) - { - FT_GlyphSlot_Oblique(slot); - //FT_BBox bbox; - //FT_Outline_Get_BBox(&slot->outline, &bbox); - //slot->metrics.width = bbox.xMax - bbox.xMin; - //slot->metrics.height = bbox.yMax - bbox.yMin; - } - - return &slot->metrics; - } - - void ImGui_ImplFreeType_FontSrcData::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch) + // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting) + if (src_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bold) + FT_GlyphSlot_Embolden(slot); + if (src_data->UserFlags & ImGuiFreeTypeBuilderFlags_Oblique) { - IM_ASSERT(ft_bitmap != nullptr); - const uint32_t w = ft_bitmap->width; - const uint32_t h = ft_bitmap->rows; - const uint8_t* src = ft_bitmap->buffer; - const uint32_t src_pitch = ft_bitmap->pitch; - - switch (ft_bitmap->pixel_mode) - { - case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel. - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - for (uint32_t x = 0; x < w; x++) - dst[x] = IM_COL32(255, 255, 255, src[x]); - break; - } - case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB. - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - { - uint8_t bits = 0; - const uint8_t* bits_ptr = src; - for (uint32_t x = 0; x < w; x++, bits <<= 1) - { - if ((x & 7) == 0) - bits = *bits_ptr++; - dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? 255 : 0); - } - } - break; - } - case FT_PIXEL_MODE_BGRA: - { - // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. - #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++) - { - uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3]; - dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a); - } - #undef DE_MULTIPLY - break; - } - default: - IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!"); - } + FT_GlyphSlot_Oblique(slot); + //FT_BBox bbox; + //FT_Outline_Get_BBox(&slot->outline, &bbox); + //slot->metrics.width = bbox.xMax - bbox.xMin; + //slot->metrics.height = bbox.yMax - bbox.yMin; } -} // namespace + + return &slot->metrics; +} + +static void ImGui_ImplFreeType_BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch) +{ + IM_ASSERT(ft_bitmap != nullptr); + const uint32_t w = ft_bitmap->width; + const uint32_t h = ft_bitmap->rows; + const uint8_t* src = ft_bitmap->buffer; + const uint32_t src_pitch = ft_bitmap->pitch; + + switch (ft_bitmap->pixel_mode) + { + case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel. + { + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + for (uint32_t x = 0; x < w; x++) + dst[x] = IM_COL32(255, 255, 255, src[x]); + break; + } + case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB. + { + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + { + uint8_t bits = 0; + const uint8_t* bits_ptr = src; + for (uint32_t x = 0; x < w; x++, bits <<= 1) + { + if ((x & 7) == 0) + bits = *bits_ptr++; + dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? 255 : 0); + } + } + break; + } + case FT_PIXEL_MODE_BGRA: + { + // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. + #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++) + { + uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3]; + dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a); + } + #undef DE_MULTIPLY + break; + } + default: + IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!"); + } +} // FreeType memory allocation callbacks static void* FreeType_Alloc(FT_Memory /*memory*/, long size) @@ -492,7 +487,7 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon bd_font_data->BakedLastActivated = baked; } - const FT_Glyph_Metrics* metrics = bd_font_data->LoadGlyph(codepoint); + const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, codepoint); if (metrics == NULL) return NULL; @@ -530,7 +525,7 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon // Render pixels to our temporary buffer atlas->Builder->TempBuffer.resize(w * h * 4); uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data; - bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w); + ImGui_ImplFreeType_BlitGlyph(ft_bitmap, temp_buffer, w); const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0]->SizePixels; float font_off_x = (src->GlyphOffset.x * offsets_scale); From 8140a9d8a69951dd99ba3bc1bcac73350cec412c Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 27 Apr 2025 15:33:44 +0200 Subject: [PATCH 1026/2359] Fonts: comments on ImTextureData fields. --- imgui.cpp | 59 +++++++++++++++++++++++++++++++++++-------------------- imgui.h | 36 +++++++++++++++++---------------- 2 files changed, 57 insertions(+), 38 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 04cb11264..6c6ead519 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -298,7 +298,7 @@ CODE // Any application code here ImGui::Text("Hello, world!"); - // Render dear imgui into screen + // Render dear imgui into framebuffer ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); g_pSwapChain->Present(1, 0); @@ -311,24 +311,14 @@ CODE EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE - // Application init: create a dear imgui context, setup some options, load fonts + // Application init: create a Dear ImGui context, setup some options, load fonts ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); - // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. - // TODO: Fill optional fields of the io structure later. + // TODO: set io.ConfigXXX values, e.g. + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard controls + // TODO: Load TTF/OTF fonts if you don't want to use the default font. - - // Build and load the texture atlas into a texture - // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer) - int width, height; - unsigned char* pixels = nullptr; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - - // At this point you've got the texture data and you need to upload that to your graphic system: - // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'. - // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID. - MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32) - io.Fonts->SetTexID((void*)texture); + io.Fonts->AddFontFromFileTTF("NotoSans.ttf", 18.0f); // Application main loop while (true) @@ -351,12 +341,19 @@ CODE MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); MyGameRender(); // may use any Dear ImGui functions as well! - // Render dear imgui, swap buffers + // End the dear imgui frame // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code) - ImGui::EndFrame(); + ImGui::EndFrame(); // this is automatically called by Render(), but available ImGui::Render(); + + // Update textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->Status != ImTextureStatus_OK) + MyImGuiBackend_UpdateTexture(tex); + + // Render dear imgui contents, swap buffers ImDrawData* draw_data = ImGui::GetDrawData(); - MyImGuiRenderFunction(draw_data); + MyImGuiBackend_RenderDrawData(draw_data); SwapBuffers(); } @@ -367,12 +364,32 @@ CODE you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this. - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE --------------------------------------------- The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function. - void MyImGuiRenderFunction(ImDrawData* draw_data) + void MyImGuiBackend_UpdateTexture(ImTextureData* tex) + { + if (tex->Status == ImTextureStatus_WantCreate) + { + // create texture based on tex->Width/Height/Pixels + // call tex->SetTexID() to specify backend-specific identifiers + // tex->Status = ImTextureStatus_OK; + } + if (tex->Status == ImTextureStatus_WantUpdates) + { + // update texture blocks based on tex->UpdateRect + // tex->Status = ImTextureStatus_OK; + } + if (tex->Status == ImTextureStatus_WantDestroy) + { + // destroy texture + // call tex->SetTexID(ImTextureID_Invalid) + // tex->Status = ImTextureStatus_Destroyed; + } + } + + void MyImGuiBackend_RenderDrawData(ImDrawData* draw_data) { // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering. diff --git a/imgui.h b/imgui.h index 005c9c01b..e38cce771 100644 --- a/imgui.h +++ b/imgui.h @@ -3079,7 +3079,7 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c struct ImDrawCmd { ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates - ImTextureRef TexRef; // 16 // User-provided texture ID. Set by user in ImFontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + ImTextureRef TexRef; // 16 // Reference to a font/texture atlas (where backend called ImTextureData::SetTexID()) or to a user-provided texture ID (via e.g. ImGui::Image() calls). Both will lead to a ImTextureID value. unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. unsigned int IdxOffset; // 4 // Start offset in index buffer. unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. @@ -3403,24 +3403,26 @@ struct ImTextureRect // Why does we store two identifiers: TexID and BackendUserData? // - ImTextureID TexID = lower-level identifier stored in ImDrawCmd. ImDrawCmd can refer to textures not created by the backend, and for which there's no ImTextureData. // - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both. + // In columns below: who reads/writes each fields? 'r'=read, 'w'=write, 'core'=main library, 'backend'=renderer backend struct ImTextureData { - ImTextureStatus Status; // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! - ImTextureFormat Format; // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8 - int Width; // Texture width - int Height; // Texture height - int BytesPerPixel; // 4 or 1 - int UniqueID; // Sequential index to facilitate identifying a texture when debugging/printing. Only unique per atlas. - unsigned char* Pixels; // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. - ImTextureID TexID; // Always use SetTexID() to modify! Identifier stored in ImDrawCmd::GetTexID() and passed to backend RenderDrawData loop. - void* BackendUserData; // Convenience storage for backend. Some backends may have enough with TexID. - ImTextureRect UsedRect; // Bounding box encompassing all past and queued Updates[]. - ImTextureRect UpdateRect; // Bounding box encompassing all queued Updates[]. - ImVector Updates; // Array of individual updates. - int UnusedFrames; // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. - unsigned short RefCount; // Number of contexts using this texture. - bool UseColors; // Tell whether our texture data is known to use colors (rather than just white + alpha). - bool WantDestroyNextFrame; // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. + //------------------------------------------ core / backend --------------------------------------- + int UniqueID; // w - // Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. + ImTextureStatus Status; // rw rw // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! + void* BackendUserData; // - rw // Convenience storage for backend. Some backends may have enough with TexID. + ImTextureID TexID; // r w // Backend-specific texture identifier. Always use SetTexID() to modify! The identifier will stored in ImDrawCmd::GetTexID() and passed to backend's RenderDrawData function. + ImTextureFormat Format; // w r // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8 + int Width; // w r // Texture width + int Height; // w r // Texture height + int BytesPerPixel; // w r // 4 or 1 + unsigned char* Pixels; // w r // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. + ImTextureRect UsedRect; // w r // Bounding box encompassing all past and queued Updates[]. + ImTextureRect UpdateRect; // w r // Bounding box encompassing all queued Updates[]. + ImVector Updates; // w r // Array of individual updates. + int UnusedFrames; // w r // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. + unsigned short RefCount; // w r // Number of contexts using this texture. Used during backend shutdown. + bool UseColors; // w r // Tell whether our texture data is known to use colors (rather than just white + alpha). + bool WantDestroyNextFrame; // rw - // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. // Functions ImTextureData() { memset(this, 0, sizeof(*this)); } From b32ef3c05dab094995944b982cbb38328628ab2a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Apr 2025 21:29:09 +0200 Subject: [PATCH 1027/2359] Fonts: make RasterizerDensity a dynamic field. (temporarily exposed as SetFontRasterizerDensity()). # Conflicts: # imgui.cpp # imgui.h --- imgui.cpp | 20 ++++++++++++---- imgui.h | 10 ++++---- imgui_draw.cpp | 40 ++++++++++++++++++-------------- imgui_internal.h | 13 +++++++---- misc/freetype/imgui_freetype.cpp | 12 ++++++---- 5 files changed, 60 insertions(+), 35 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6c6ead519..68560fdb6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3966,6 +3966,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) Font = NULL; FontBaked = NULL; FontSize = FontSizeBeforeScaling = FontScale = CurrentDpiScale = 0.0f; + FontRasterizerDensity = 1.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); IO.Fonts->RefCount++; Time = 0.0f; @@ -8656,14 +8657,25 @@ void ImGui::UpdateCurrentFontSize() // - We may support it better later and remove this rounding. final_size = GetRoundedFontSize(final_size); final_size = ImMax(1.0f, final_size); - + if (g.Font != NULL) + g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity; + g.FontBaked = (g.Font != NULL) ? g.Font->GetFontBaked(final_size) : NULL; g.FontSize = final_size; - g.FontBaked = (g.Font != NULL) ? g.Font->GetFontBaked(g.FontSize) : NULL; g.FontScale = (g.Font != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; g.DrawListSharedData.FontSize = g.FontSize; g.DrawListSharedData.FontScale = g.FontScale; } +// FIXME-DPI: Not sure how to expose this. It may be automatically applied based on current viewport, if we had this information stored in viewport or monitor. +void ImGui::SetFontRasterizerDensity(float rasterizer_density) +{ + ImGuiContext& g = *GImGui; + if (g.FontRasterizerDensity == rasterizer_density) + return; + g.FontRasterizerDensity = rasterizer_density; + UpdateCurrentFontSize(); +} + void ImGui::PushFont(ImFont* font, float font_size) { ImGuiContext& g = *GImGui; @@ -16701,7 +16713,7 @@ void ImGui::DebugNodeFont(ImFont* font) if (baked->ContainerFont != font) continue; PushID(baked_n); - if (TreeNode("Glyphs", "Baked at %.2fpx: %d glyphs%s", baked->Size, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) + if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.1f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) { if (SmallButton("Load all")) for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++) @@ -16714,7 +16726,7 @@ void ImGui::DebugNodeFont(ImFont* font) { ImFontConfig* src = font->Sources[src_n]; int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(src, baked->Size, &oversample_h, &oversample_v); + ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v); BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); } diff --git a/imgui.h b/imgui.h index e38cce771..9bf4db914 100644 --- a/imgui.h +++ b/imgui.h @@ -3467,7 +3467,7 @@ struct ImFontConfig float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. - float RasterizerDensity; // 1.0f // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. + float RasterizerDensity; // 1.0f // DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. // [Internal] @@ -3709,6 +3709,7 @@ struct ImFontBaked ImVector IndexAdvanceX; // 12-16 // out // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). float FallbackAdvanceX; // 4 // out // FindGlyph(FallbackChar)->AdvanceX float Size; // 4 // in // Height of characters/line, set during loading (doesn't change after loading) + float RasterizerDensity; // 4 // in // Density this is baked at // [Internal] Members: Hot ~28/36 bytes (for RenderText loop) ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. @@ -3753,9 +3754,10 @@ enum ImFontFlags_ struct ImFont { // [Internal] Members: Hot ~12-20 bytes - ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. DO NOT USE. Use GetFontBaked(). - ImFontAtlas* ContainerAtlas; // 4-8 // What we has been loaded into - ImFontFlags Flags; // 4 // Font flags + ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked(). + ImFontAtlas* ContainerAtlas; // 4-8 // What we have been loaded into. + ImFontFlags Flags; // 4 // Font flags. + float CurrentRasterizerDensity; // Current rasterizer density. This is a varying state of the font. // [Internal] Members: Cold ~24-52 bytes // Conceptually Sources[] is the list of font sources merged to create this font. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7bb6ae108..14440592e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3349,10 +3349,11 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) atlas->TexIsBuilt = true; } -void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v) +void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v) { // Automatically disable horizontal oversampling over size 36 - *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : ((size * src->RasterizerDensity > 36.0f) || src->PixelSnapH) ? 1 : 2; + const float raster_size = baked->Size * baked->RasterizerDensity * src->RasterizerDensity; + *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (raster_size > 36.0f || src->PixelSnapH) ? 1 : 2; *out_oversample_v = (src->OversampleV != 0) ? src->OversampleV : 1; } @@ -3733,11 +3734,12 @@ void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBa baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; } -ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id) +ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id) { IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", font_size); ImFontBaked* baked = atlas->Builder->BakedPool.push_back(ImFontBaked()); baked->Size = font_size; + baked->RasterizerDensity = font_rasterizer_density; baked->BakedId = baked_id; baked->ContainerFont = font; baked->LastUsedFrame = atlas->Builder->FrameCount; @@ -3764,7 +3766,7 @@ ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_si } // FIXME-OPT: This is not a fast query. Adding a BakedCount field in Font might allow to take a shortcut for the most common case. -ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size) +ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density) { ImFontAtlasBuilder* builder = atlas->Builder; ImFontBaked* closest_larger_match = NULL; @@ -3774,6 +3776,8 @@ ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, f ImFontBaked* baked = &builder->BakedPool[baked_n]; if (baked->ContainerFont != font || baked->WantDestroy) continue; + if (baked->RasterizerDensity != font_rasterizer_density) + continue; if (baked->Size > font_size && (closest_larger_match == NULL || baked->Size < closest_larger_match->Size)) closest_larger_match = baked; if (baked->Size < font_size && (closest_smaller_match == NULL || baked->Size > closest_smaller_match->Size)) @@ -4543,10 +4547,11 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, // Fonts unit to pixels int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(src, baked->Size, &oversample_h, &oversample_v); + ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v); const float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; - const float scale_for_raster_x = bd_font_data->ScaleFactor * baked->Size * src->RasterizerDensity * oversample_h; - const float scale_for_raster_y = bd_font_data->ScaleFactor * baked->Size * src->RasterizerDensity * oversample_v; + const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; + const float scale_for_raster_x = bd_font_data->ScaleFactor * baked->Size * rasterizer_density * oversample_h; + const float scale_for_raster_y = bd_font_data->ScaleFactor * baked->Size * rasterizer_density * oversample_v; // Obtain size and advance int x0, y0, x1, y1; @@ -4601,8 +4606,8 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, font_off_y = IM_ROUND(font_off_y); font_off_x += stbtt__oversample_shift(oversample_h); font_off_y += stbtt__oversample_shift(oversample_v) + IM_ROUND(baked->Ascent); - float recip_h = 1.0f / (oversample_h * src->RasterizerDensity); - float recip_v = 1.0f / (oversample_v * src->RasterizerDensity); + float recip_h = 1.0f / (oversample_h * rasterizer_density); + float recip_v = 1.0f / (oversample_v * rasterizer_density); // Register glyph // r->x r->y are coordinates inside texture (in pixels) @@ -5172,11 +5177,12 @@ float ImFontBaked::GetCharAdvance(ImWchar c) } IM_MSVC_RUNTIME_CHECKS_RESTORE -ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size) +ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density) { - struct { ImGuiID FontId; float BakedSize; } hashed_data; + struct { ImGuiID FontId; float BakedSize; float RasterizerDensity; } hashed_data; hashed_data.FontId = font_id; hashed_data.BakedSize = baked_size; + hashed_data.RasterizerDensity = rasterizer_density; return ImHashData(&hashed_data, sizeof(hashed_data)); } @@ -5189,12 +5195,12 @@ ImFontBaked* ImFont::GetFontBaked(float size) // - ImGui::PushFontSize() will already round, but other paths calling GetFontBaked() directly also needs it (e.g. ImFontAtlasBuildPreloadAllGlyphRanges) size = ImGui::GetRoundedFontSize(size); - if (baked && baked->Size == size) + if (baked && baked->Size == size && baked->RasterizerDensity == CurrentRasterizerDensity) return baked; ImFontAtlas* atlas = ContainerAtlas; ImFontAtlasBuilder* builder = atlas->Builder; - baked = ImFontAtlasBakedGetOrAdd(atlas, this, size); + baked = ImFontAtlasBakedGetOrAdd(atlas, this, size, CurrentRasterizerDensity); if (baked == NULL) return NULL; baked->LastUsedFrame = builder->FrameCount; @@ -5202,11 +5208,11 @@ ImFontBaked* ImFont::GetFontBaked(float size) return baked; } -ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size) +ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density) { // FIXME-NEWATLAS: Design for picking a nearest size based on some criteria? // FIXME-NEWATLAS: Altering font density won't work right away. - ImGuiID baked_id = ImFontAtlasBakedGetId(font->FontId, font_size); + ImGuiID baked_id = ImFontAtlasBakedGetId(font->FontId, font_size, font_rasterizer_density); ImFontAtlasBuilder* builder = atlas->Builder; ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); ImFontBaked* baked = *p_baked_in_map; @@ -5220,7 +5226,7 @@ ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float fo // FIXME-OPT: This is not an optimal query. if ((font->Flags & ImFontFlags_LockBakedSizes) || atlas->Locked) { - baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size); + baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density); if (baked != NULL) return baked; if (atlas->Locked) @@ -5231,7 +5237,7 @@ ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float fo } // Create new - baked = ImFontAtlasBakedAdd(atlas, font, font_size, baked_id); + baked = ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id); *p_baked_in_map = baked; // To avoid 'builder->BakedMap.SetVoidPtr(baked_id, baked);' while we can. return baked; } diff --git a/imgui_internal.h b/imgui_internal.h index 28e907488..fbd0ec148 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2142,6 +2142,7 @@ struct ImGuiContext float FontSize; // == FontSizeBeforeScaling * io.FontGlobalScale * font->Scale * g.CurrentWindow->FontWindowScale. Current text height. float FontSizeBeforeScaling; // == value passed to PushFontSize() float FontScale; // == FontBaked->Size / Font->FontSize. Scale factor over baked size. + float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale ImDrawListSharedData DrawListSharedData; double Time; @@ -3109,6 +3110,8 @@ namespace ImGui // Fonts, drawing IMGUI_API void SetCurrentFont(ImFont* font, float font_size); + IMGUI_API void SetFontRasterizerDensity(float rasterizer_density); + inline float GetFontRasterizerDensity() { return GImGui->FontRasterizerDensity; } IMGUI_API void UpdateCurrentFontSize(); inline float GetRoundedFontSize(float size) { return IM_ROUND(size); } inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } @@ -3781,7 +3784,7 @@ IMGUI_API ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy -IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, float size, int* out_oversample_h, int* out_oversample_v); +IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v); IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); IMGUI_API bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src); @@ -3791,10 +3794,10 @@ IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasFontDiscardOutputBakes(ImFontAtlas* atlas, ImFont* font); -IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size); -IMGUI_API ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size); -IMGUI_API ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size); -IMGUI_API ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, ImGuiID baked_id); +IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id); IMGUI_API void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 8ad2d6cea..121320b09 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -438,10 +438,11 @@ bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me. // FT_Set_Pixel_Sizes() doesn't seem to get us the same result." // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL) + const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; FT_Size_RequestRec req; req.type = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; req.width = 0; - req.height = (uint32_t)(size * 64 * src->RasterizerDensity); + req.height = (uint32_t)(size * 64 * rasterizer_density); req.horiResolution = 0; req.vertResolution = 0; FT_Request_Size(bd_font_data->FtFace, &req); @@ -451,7 +452,7 @@ bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF { // Read metrics FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; - const float scale = 1.0f / src->RasterizerDensity; + const float scale = 1.0f / rasterizer_density; baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. @@ -503,12 +504,13 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon const int w = (int)ft_bitmap->width; const int h = (int)ft_bitmap->rows; const bool is_visible = (w != 0 && h != 0); + const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; // Prepare glyph ImFontGlyph glyph_in = {}; ImFontGlyph* glyph = &glyph_in; glyph->Codepoint = codepoint; - glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) / src->RasterizerDensity; + glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) / rasterizer_density; // Pack and retrieve position inside texture atlas if (is_visible) @@ -534,8 +536,8 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon font_off_x = IM_ROUND(font_off_x); if (src->PixelSnapV) font_off_y = IM_ROUND(font_off_y); - float recip_h = 1.0f / src->RasterizerDensity; - float recip_v = 1.0f / src->RasterizerDensity; + float recip_h = 1.0f / rasterizer_density; + float recip_v = 1.0f / rasterizer_density; // Register glyph float glyph_off_x = (float)face->glyph->bitmap_left; From 4dec946ae671099bbf0e846778b7aebdb7b481d8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 May 2025 20:58:38 +0200 Subject: [PATCH 1028/2359] Fonts: don't pretend to half recover from OOM for now + debug log filename on load failure. --- imgui_draw.cpp | 5 ++++- misc/freetype/imgui_freetype.cpp | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 14440592e..2cec1439d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3102,7 +3102,10 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, if (!data) { if (font_cfg_template == NULL || (font_cfg_template->Flags & ImFontFlags_NoLoadError) == 0) + { + IMGUI_DEBUG_LOG("While loading '%s'\n", filename); IM_ASSERT_USER_ERROR(0, "Could not load font file!"); + } return NULL; } ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); @@ -4576,7 +4579,7 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, if (pack_id == ImFontAtlasRectId_Invalid) { // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) - IM_ASSERT_USER_ERROR(pack_id != ImFontAtlasRectId_Invalid, "Out of texture memory."); + IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory."); return NULL; } ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 121320b09..afd3e0cec 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -516,10 +516,10 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon if (is_visible) { ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); - if (pack_id < 0) + if (pack_id == ImFontAtlasRectId_Invalid) { // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) - IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory."); + IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory."); return NULL; } ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); From 8523cbdf58f1851c007751cf7e43317fb146a259 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 May 2025 17:03:52 +0200 Subject: [PATCH 1029/2359] Fonts: rework ImFontLoader::FontBakedLoadGlyph() interface --- imgui_draw.cpp | 42 +++++++++++++++----------------- imgui_internal.h | 4 +-- misc/freetype/imgui_freetype.cpp | 36 ++++++++++++--------------- 3 files changed, 36 insertions(+), 46 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2cec1439d..968dc47d4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4393,12 +4393,15 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep { const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) - if (ImFontGlyph* glyph = loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint)) + { + ImFontGlyph glyph_buf; + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf)) { // FIXME: Add hooks for e.g. #7962 - glyph->SourceIdx = src_n; - return glyph; + glyph_buf.SourceIdx = src_n; + return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); } + } loader_user_data_p += loader->FontBakedSrcLoaderDataSize; src_n++; } @@ -4539,14 +4542,14 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig return true; } -static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint) +static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph) { // Search for first font which has the glyph ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; IM_ASSERT(bd_font_data); int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); if (glyph_index == 0) - return NULL; + return false; // Fonts unit to pixels int oversample_h, oversample_v; @@ -4564,10 +4567,8 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, const bool is_visible = (x0 != x1 && y0 != y1); // Prepare glyph - ImFontGlyph glyph_in = {}; - ImFontGlyph* glyph = &glyph_in; - glyph->Codepoint = codepoint; - glyph->AdvanceX = advance * scale_for_layout; + out_glyph->Codepoint = codepoint; + out_glyph->AdvanceX = advance * scale_for_layout; // Pack and retrieve position inside texture atlas // (generally based on stbtt_PackFontRangesRenderIntoRects) @@ -4580,7 +4581,7 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, { // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory."); - return NULL; + return false; } ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); @@ -4615,21 +4616,16 @@ static ImFontGlyph* ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, // Register glyph // r->x r->y are coordinates inside texture (in pixels) // glyph.X0, glyph.Y0 are drawing coordinates from base text position, and accounting for oversampling. - glyph->X0 = x0 * recip_h + font_off_x; - glyph->Y0 = y0 * recip_v + font_off_y; - glyph->X1 = (x0 + (int)r->w) * recip_h + font_off_x; - glyph->Y1 = (y0 + (int)r->h) * recip_v + font_off_y; - glyph->Visible = true; - glyph->PackId = pack_id; - glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); - ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, bitmap_pixels, ImTextureFormat_Alpha8, w); - } - else - { - glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); + out_glyph->X0 = x0 * recip_h + font_off_x; + out_glyph->Y0 = y0 * recip_v + font_off_y; + out_glyph->X1 = (x0 + (int)r->w) * recip_h + font_off_x; + out_glyph->Y1 = (y0 + (int)r->h) * recip_v + font_off_y; + out_glyph->Visible = true; + out_glyph->PackId = pack_id; + ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, bitmap_pixels, ImTextureFormat_Alpha8, w); } - return glyph; + return true; } const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() diff --git a/imgui_internal.h b/imgui_internal.h index fbd0ec148..00cb159d2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3669,7 +3669,7 @@ namespace ImGui // Hooks and storage for a given font backend. // This structure is likely to evolve as we add support for incremental atlas updates. -// Conceptually this could be in ImGuiPlatformIO, but we are far from ready to make this public. +// Conceptually this could be public, but API is still going to be evolve. struct ImFontLoader { const char* Name; @@ -3680,7 +3680,7 @@ struct ImFontLoader bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); - ImFontGlyph* (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint); + bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph); // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. // FIXME: At this point the two other types of buffers may be managed by core to be consistent? diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index afd3e0cec..a0fc96926 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -473,12 +473,12 @@ void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() } -ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint) +bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph) { ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); if (glyph_index == 0) - return NULL; + return false; if (bd_font_data->BakedLastActivated != baked) // <-- could use id { @@ -490,7 +490,7 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, codepoint); if (metrics == NULL) - return NULL; + return false; // Render glyph into a bitmap (currently held by FreeType) FT_Face face = bd_font_data->FtFace; @@ -507,10 +507,8 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; // Prepare glyph - ImFontGlyph glyph_in = {}; - ImFontGlyph* glyph = &glyph_in; - glyph->Codepoint = codepoint; - glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) / rasterizer_density; + out_glyph->Codepoint = codepoint; + out_glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) / rasterizer_density; // Pack and retrieve position inside texture atlas if (is_visible) @@ -542,21 +540,17 @@ ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontCon // Register glyph float glyph_off_x = (float)face->glyph->bitmap_left; float glyph_off_y = (float)-face->glyph->bitmap_top; - glyph->X0 = glyph_off_x * recip_h + font_off_x; - glyph->Y0 = glyph_off_y * recip_v + font_off_y; - glyph->X1 = (glyph_off_x + w) * recip_h + font_off_x; - glyph->Y1 = (glyph_off_y + h) * recip_v + font_off_y; - glyph->Visible = true; - glyph->Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); - glyph->PackId = pack_id; - glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); - ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, (const unsigned char*)temp_buffer, ImTextureFormat_RGBA32, w * 4); + out_glyph->X0 = glyph_off_x * recip_h + font_off_x; + out_glyph->Y0 = glyph_off_y * recip_v + font_off_y; + out_glyph->X1 = (glyph_off_x + w) * recip_h + font_off_x; + out_glyph->Y1 = (glyph_off_y + h) * recip_v + font_off_y; + out_glyph->Visible = true; + out_glyph->Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); + out_glyph->PackId = pack_id; + ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, (const unsigned char*)temp_buffer, ImTextureFormat_RGBA32, w * 4); } - else - { - glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph); - } - return glyph; + + return true; } bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) From 89e880dfd18d7a7ebfc684831d787f6b620db6c7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 May 2025 17:35:20 +0200 Subject: [PATCH 1030/2359] Fonts: adding ImFontHooks for codepoint remapping. --- imgui.h | 3 +++ imgui_draw.cpp | 16 +++++++++++++++- imgui_internal.h | 12 ++++++++++-- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 9bf4db914..8cf3f7ff4 100644 --- a/imgui.h +++ b/imgui.h @@ -177,6 +177,7 @@ struct ImFontBaked; // Baked data for a ImFont at a given size. struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data +struct ImFontHooks; // Opaque interface to font hooks struct ImFontLoader; // Opaque interface to a font loading backend (stb_truetype, FreeType etc.). struct ImTextureData; // Specs and pixel storage for a texture used by Dear ImGui. struct ImTextureRect; // Coordinates of a rectangle within a texture. @@ -3682,6 +3683,7 @@ struct ImFontAtlas const ImFontLoader* FontLoader; // Font loader opaque interface (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). Don't set directly! const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name void* FontLoaderData; // Font backend opaque storage + const ImFontHooks* FontHooks; // Shared font hooks for all fonts. unsigned int FontBuilderFlags; // [FIXME: Should be called FontLoaderFlags] Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. . Per-font override is also available in ImFontConfig. int RefCount; // Number of contexts using this atlas @@ -3769,6 +3771,7 @@ struct ImFont float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. + const ImFontHooks* FontHooks; // 8 // in // Custom font hooks for the font. // Methods IMGUI_API ImFont(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 968dc47d4..8661de762 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4365,6 +4365,14 @@ static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size) baked->IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); } +static void ImFont_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c) +{ + if (font->FontHooks && font->FontHooks->FontHookRemapCodepoint != NULL) + font->FontHooks->FontHookRemapCodepoint(atlas, font, c); + else if (atlas->FontHooks && atlas->FontHooks->FontHookRemapCodepoint != NULL) + atlas->FontHooks->FontHookRemapCodepoint(atlas, font, c); +} + static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint) { ImFont* font = baked->ContainerFont; @@ -4377,6 +4385,10 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep return NULL; } + // User remapping hooks + ImWchar src_codepoint = codepoint; + ImFont_FontHookRemapCodepoint(atlas, font, &codepoint); + //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); @@ -4398,6 +4410,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf)) { // FIXME: Add hooks for e.g. #7962 + glyph_buf.Codepoint = src_codepoint; glyph_buf.SourceIdx = src_n; return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); } @@ -5079,7 +5092,7 @@ void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } -// FIXME-NEWATLAS: Implement AddRemapChar() which was removed since transitioning to baked logic. +// FIXME: Use ImFontHooks::FontHookRemapCodepoint() hooks. void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst) { IM_UNUSED(from_codepoint); @@ -5149,6 +5162,7 @@ bool ImFontBaked::IsGlyphLoaded(ImWchar c) bool ImFont::IsGlyphInFont(ImWchar c) { ImFontAtlas* atlas = ContainerAtlas; + ImFont_FontHookRemapCodepoint(atlas, this, &c); for (ImFontConfig* src : Sources) { const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; diff --git a/imgui_internal.h b/imgui_internal.h index 00cb159d2..b486430ad 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -37,7 +37,7 @@ Index of this file: // [SECTION] Tab bar, Tab item support // [SECTION] Table support // [SECTION] ImGui internal API -// [SECTION] ImFontLoader +// [SECTION] ImFontLoader, ImFontHooks // [SECTION] ImFontAtlas internal API // [SECTION] Test Engine specific hooks (imgui_test_engine) @@ -3664,7 +3664,7 @@ namespace ImGui //----------------------------------------------------------------------------- -// [SECTION] ImFontLoader +// [SECTION] ImFontLoader, ImFontHooks //----------------------------------------------------------------------------- // Hooks and storage for a given font backend. @@ -3693,6 +3693,14 @@ struct ImFontLoader IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); #endif +// User hooks +// Conceptually this could be public, but API is still going to be evolve. +struct ImFontHooks +{ + // Modify codepoint to map to another value. + void (*FontHookRemapCodepoint)(ImFontAtlas* atlas, ImFont* font, ImWchar* io_codepoint); +}; + //----------------------------------------------------------------------------- // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- From f6735c223c469ac0952fbf0f2bf336f8f43e3fe1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 May 2025 17:59:18 +0200 Subject: [PATCH 1031/2359] Fonts: remove ImFontHooks in favor of a AddRemapChar() implementation. --- imgui.h | 6 ++---- imgui_draw.cpp | 33 ++++++++------------------------- imgui_internal.h | 12 ++---------- 3 files changed, 12 insertions(+), 39 deletions(-) diff --git a/imgui.h b/imgui.h index 8cf3f7ff4..4639e2c2e 100644 --- a/imgui.h +++ b/imgui.h @@ -177,7 +177,6 @@ struct ImFontBaked; // Baked data for a ImFont at a given size. struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data -struct ImFontHooks; // Opaque interface to font hooks struct ImFontLoader; // Opaque interface to a font loading backend (stb_truetype, FreeType etc.). struct ImTextureData; // Specs and pixel storage for a texture used by Dear ImGui. struct ImTextureRect; // Coordinates of a rectangle within a texture. @@ -3683,7 +3682,6 @@ struct ImFontAtlas const ImFontLoader* FontLoader; // Font loader opaque interface (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). Don't set directly! const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name void* FontLoaderData; // Font backend opaque storage - const ImFontHooks* FontHooks; // Shared font hooks for all fonts. unsigned int FontBuilderFlags; // [FIXME: Should be called FontLoaderFlags] Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. . Per-font override is also available in ImFontConfig. int RefCount; // Number of contexts using this atlas @@ -3771,7 +3769,7 @@ struct ImFont float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. - const ImFontHooks* FontHooks; // 8 // in // Custom font hooks for the font. + ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty. // Methods IMGUI_API ImFont(); @@ -3794,7 +3792,7 @@ struct ImFont // [Internal] Don't use! IMGUI_API void ClearOutputData(); - IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst);// , bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. + IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8661de762..541043dd4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4365,12 +4365,11 @@ static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size) baked->IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); } -static void ImFont_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c) +static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c) { - if (font->FontHooks && font->FontHooks->FontHookRemapCodepoint != NULL) - font->FontHooks->FontHookRemapCodepoint(atlas, font, c); - else if (atlas->FontHooks && atlas->FontHooks->FontHookRemapCodepoint != NULL) - atlas->FontHooks->FontHookRemapCodepoint(atlas, font, c); + IM_UNUSED(atlas); + if (font->RemapPairs.Data.Size != 0) + *c = (ImWchar)font->RemapPairs.GetInt((ImGuiID)*c, (int)*c); } static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint) @@ -4387,7 +4386,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep // User remapping hooks ImWchar src_codepoint = codepoint; - ImFont_FontHookRemapCodepoint(atlas, font, &codepoint); + ImFontAtlas_FontHookRemapCodepoint(atlas, font, &codepoint); //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); @@ -5092,25 +5091,9 @@ void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } -// FIXME: Use ImFontHooks::FontHookRemapCodepoint() hooks. -void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint, bool overwrite_dst) +void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) { - IM_UNUSED(from_codepoint); - IM_UNUSED(to_codepoint); - IM_UNUSED(overwrite_dst); - /* - IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. - unsigned int index_size = (unsigned int)IndexLookup.Size; - - if (from_codepoint < index_size && IndexLookup.Data[from_codepoint] == (ImU16)-1 && !overwrite_dst) // 'from_codepoint' already exists - return; - if (to_codepoint >= index_size && from_codepoint >= index_size) // both 'from_codepoint' and 'to_codepoint' don't exist -> no-op - return; - - BuildGrowIndex(from_codepoint + 1); - IndexLookup[from_codepoint] = (to_codepoint < index_size) ? IndexLookup.Data[to_codepoint] : (ImU16)-1; - IndexAdvanceX[from_codepoint] = (to_codepoint < index_size) ? IndexAdvanceX.Data[to_codepoint] : 1.0f; - */ + RemapPairs.SetInt((ImGuiID)from_codepoint, (int)to_codepoint); } // Find glyph, load if necessary, return fallback if missing @@ -5162,7 +5145,7 @@ bool ImFontBaked::IsGlyphLoaded(ImWchar c) bool ImFont::IsGlyphInFont(ImWchar c) { ImFontAtlas* atlas = ContainerAtlas; - ImFont_FontHookRemapCodepoint(atlas, this, &c); + ImFontAtlas_FontHookRemapCodepoint(atlas, this, &c); for (ImFontConfig* src : Sources) { const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; diff --git a/imgui_internal.h b/imgui_internal.h index b486430ad..00cb159d2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -37,7 +37,7 @@ Index of this file: // [SECTION] Tab bar, Tab item support // [SECTION] Table support // [SECTION] ImGui internal API -// [SECTION] ImFontLoader, ImFontHooks +// [SECTION] ImFontLoader // [SECTION] ImFontAtlas internal API // [SECTION] Test Engine specific hooks (imgui_test_engine) @@ -3664,7 +3664,7 @@ namespace ImGui //----------------------------------------------------------------------------- -// [SECTION] ImFontLoader, ImFontHooks +// [SECTION] ImFontLoader //----------------------------------------------------------------------------- // Hooks and storage for a given font backend. @@ -3693,14 +3693,6 @@ struct ImFontLoader IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); #endif -// User hooks -// Conceptually this could be public, but API is still going to be evolve. -struct ImFontHooks -{ - // Modify codepoint to map to another value. - void (*FontHookRemapCodepoint)(ImFontAtlas* atlas, ImFont* font, ImWchar* io_codepoint); -}; - //----------------------------------------------------------------------------- // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- From 46fa9e8efb4e09244704699e69c0487915ec7812 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 9 May 2025 21:55:07 +0200 Subject: [PATCH 1032/2359] Fonts: Debug display status. Fixed truncated raw texture id. Fixed FormatTextureIDForDebugDisplay(). Comments. --- imgui.cpp | 27 ++++++++++++++++++--------- imgui_draw.cpp | 16 +++++++++++++++- imgui_internal.h | 1 + 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 68560fdb6..92f0f92bf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15666,7 +15666,7 @@ static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, const char* buf_end = buf + buf_size; if (cmd->TexRef._TexData != NULL) buf += ImFormatString(buf, buf_end - buf, "#%03d: ", cmd->TexRef._TexData->UniqueID); - return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), cmd->GetTexID()); + return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), cmd->TexRef.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID() } // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. @@ -15690,18 +15690,26 @@ namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_A void ImGui::ShowFontAtlas(ImFontAtlas* atlas) { ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + + Text("Read "); SameLine(0, 0); + TextLinkOpenURL("https://www.dearimgui.com/faq/"); SameLine(0, 0); + Text(" for details on font loading."); SeparatorText("Backend Support for Dynamic Fonts"); BeginDisabled(); - CheckboxFlags("io.BackendFlags: RendererHasTextures", &GetIO().BackendFlags, ImGuiBackendFlags_RendererHasTextures); + CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures); + EndDisabled(); + + BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); + SetNextItemWidth(GetFontSize() * 5); + DragFloat("io.FontGlobalScale", &io.FontGlobalScale, 0.05f, 0.5f, 5.0f); + BulletText("This is scaling font only. General scaling will come later."); + BulletText("Load an actual font that's not the default for best result!"); + BulletText("Please submit feedback:"); SameLine(); TextLinkOpenURL("https://github.com/ocornut/imgui/issues/8465"); EndDisabled(); SeparatorText("Fonts"); - Text("Read "); - SameLine(0, 0); - TextLinkOpenURL("https://www.dearimgui.com/faq/"); - SameLine(0, 0); - Text(" for details on font loading."); ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; Checkbox("Show font preview", &cfg->ShowFontPreview); @@ -15845,7 +15853,8 @@ void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRe } PopStyleVar(); - char texid_desc[20]; + char texid_desc[30]; + Text("Status = %s (%d)", ImTextureDataGetStatusName(tex->Status), tex->Status); Text("Format = %s (%d)", ImTextureDataGetFormatName(tex->Format), tex->Format); Text("TexID = %s", FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->TexID)); Text("BackendUserData = %p", tex->BackendUserData); @@ -16545,7 +16554,7 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con continue; } - char texid_desc[20]; + char texid_desc[30]; FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd); char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 541043dd4..a76767b9b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2431,6 +2431,19 @@ int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format) return 0; } +const char* ImTextureDataGetStatusName(ImTextureStatus status) +{ + switch (status) + { + case ImTextureStatus_OK: return "OK"; + case ImTextureStatus_Destroyed: return "Destroyed"; + case ImTextureStatus_WantCreate: return "WantCreate"; + case ImTextureStatus_WantUpdates: return "WantUpdates"; + case ImTextureStatus_WantDestroy: return "WantDestroy"; + } + return "N/A"; +} + const char* ImTextureDataGetFormatName(ImTextureFormat format) { switch (format) @@ -2441,7 +2454,6 @@ const char* ImTextureDataGetFormatName(ImTextureFormat format) return "N/A"; } - void ImTextureData::Create(ImTextureFormat format, int w, int h) { DestroyPixels(); @@ -3156,6 +3168,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed return font; } +// On font removal we need to remove references (otherwise we could queue removal?) // We allow old_font == new_font which forces updating all values (e.g. sizes) static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font) { @@ -3884,6 +3897,7 @@ void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex } // Update texture coordinates in all draw list shared context +// FIXME-NEWATLAS FIXME-OPT: Doesn't seem necessary to update for all, only one bound to current context? void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) { for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) diff --git a/imgui_internal.h b/imgui_internal.h index 00cb159d2..5f2a06fe4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3823,6 +3823,7 @@ IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h); IMGUI_API int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format); +IMGUI_API const char* ImTextureDataGetStatusName(ImTextureStatus status); IMGUI_API const char* ImTextureDataGetFormatName(ImTextureFormat format); #ifndef IMGUI_DISABLE_DEBUG_TOOLS From 65e60399794295d28b552941114f41da8be148a0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 9 May 2025 22:46:39 +0200 Subject: [PATCH 1033/2359] Fonts: remove unnecessary ImDrawListSharedData::FontAtlas which is actually getting in the way of using multiple atlases. --- imgui_draw.cpp | 7 ++----- imgui_internal.h | 1 - 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a76767b9b..eaba28b06 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3865,16 +3865,14 @@ void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames) // Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) { - IM_ASSERT(!atlas->DrawListSharedDatas.contains(data) && data->FontAtlas == NULL); + IM_ASSERT(!atlas->DrawListSharedDatas.contains(data)); atlas->DrawListSharedDatas.push_back(data); - data->FontAtlas = atlas; } void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) { - IM_ASSERT(atlas->DrawListSharedDatas.contains(data) && data->FontAtlas == atlas); + IM_ASSERT(atlas->DrawListSharedDatas.contains(data)); atlas->DrawListSharedDatas.find_erase(data); - data->FontAtlas = NULL; } // Update texture identifier in all active draw lists @@ -3902,7 +3900,6 @@ void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) { for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) { - shared_data->FontAtlas = atlas; shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; shared_data->TexUvLines = atlas->TexUvLines; } diff --git a/imgui_internal.h b/imgui_internal.h index 5f2a06fe4..f145fd012 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -838,7 +838,6 @@ struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) - ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current/default font (optional, for simplified AddText overload) float FontSize; // Current/default font size (optional, for simplified AddText overload) float FontScale; // Current/default font scale (== FontSize / Font->FontSize) From fad5280d4c131f3ebbbc30f6d1dc0d4e8463df4c Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 11 May 2025 23:51:45 +0200 Subject: [PATCH 1034/2359] Fonts: fixed broken support for legacy backend due to a mismatch with initial pre-build baked id. --- imgui.cpp | 2 +- imgui.h | 2 +- imgui_draw.cpp | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 92f0f92bf..bd01afed5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8657,7 +8657,7 @@ void ImGui::UpdateCurrentFontSize() // - We may support it better later and remove this rounding. final_size = GetRoundedFontSize(final_size); final_size = ImMax(1.0f, final_size); - if (g.Font != NULL) + if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity; g.FontBaked = (g.Font != NULL) ? g.Font->GetFontBaked(final_size) : NULL; g.FontSize = final_size; diff --git a/imgui.h b/imgui.h index 4639e2c2e..71e49efe4 100644 --- a/imgui.h +++ b/imgui.h @@ -3467,7 +3467,7 @@ struct ImFontConfig float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. - float RasterizerDensity; // 1.0f // DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. + float RasterizerDensity; // 1.0f // (Legacy: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported). DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. // [Internal] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index eaba28b06..65485fb20 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3002,6 +3002,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) font->FontId = FontNextUniqueID++; font->Flags = font_cfg_in->Flags; font->DefaultSize = font_cfg_in->SizePixels; + font->CurrentRasterizerDensity = font_cfg_in->RasterizerDensity; Fonts.push_back(font); } else From 91ed6e67b439b9dabc213ab2a05e4f88c70e526a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 9 May 2025 22:17:48 +0200 Subject: [PATCH 1035/2359] Fonts: fixed support for multiple atlases. Moved FontAtlasOwnedByContext to OwnerContext # Conflicts: # imgui.cpp # imgui_internal.h --- imgui.cpp | 91 +++++++++++++++++++++++++++++------------------- imgui.h | 1 + imgui_internal.h | 4 ++- 3 files changed, 59 insertions(+), 37 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bd01afed5..d79690088 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3962,13 +3962,13 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) InputTextState.Ctx = this; Initialized = false; - FontAtlasOwnedByContext = shared_font_atlas ? false : true; Font = NULL; FontBaked = NULL; FontSize = FontSizeBeforeScaling = FontScale = CurrentDpiScale = 0.0f; FontRasterizerDensity = 1.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); - IO.Fonts->RefCount++; + if (shared_font_atlas == NULL) + IO.Fonts->OwnerContext = this; Time = 0.0f; FrameCount = 0; FrameCountEnded = FrameCountRendered = -1; @@ -4226,8 +4226,9 @@ void ImGui::Initialize() // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context. // But this link allows us to facilitate/handle a few edge cases better. + ImFontAtlas* atlas = g.IO.Fonts; g.DrawListSharedData.Context = &g; - ImFontAtlasAddDrawListSharedData(g.IO.Fonts, &g.DrawListSharedData); + RegisterFontAtlas(atlas); g.Initialized = true; } @@ -4240,17 +4241,15 @@ void ImGui::Shutdown() IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?"); // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) - if (ImFontAtlas* atlas = g.IO.Fonts) + for (ImFontAtlas* atlas : g.FontAtlases) { - ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData); - atlas->RefCount--; - if (g.FontAtlasOwnedByContext) + UnregisterFontAtlas(atlas); + if (atlas->OwnerContext == &g) { atlas->Locked = false; IM_DELETE(atlas); } } - g.IO.Fonts = NULL; g.DrawListSharedData.TempBuffer.clear(); // Cleanup of other data are conditional on actually having initialized Dear ImGui. @@ -4412,7 +4411,8 @@ void ImGui::GcCompactTransientMiscBuffers() g.MultiSelectTempDataStacked = 0; g.MultiSelectTempData.clear_destruct(); TableGcCompactSettings(); - g.IO.Fonts->CompactCache(); + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->CompactCache(); } // Free up/compact internal window buffers, we can use this when a window becomes unused. @@ -5210,29 +5210,27 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) static void ImGui::UpdateTexturesNewFrame() { ImGuiContext& g = *GImGui; - ImFontAtlas* atlas = g.IO.Fonts; - if (g.FontAtlasOwnedByContext) - { - atlas->RendererHasTextures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; - ImFontAtlasUpdateNewFrame(atlas, g.FrameCount); - } + for (ImFontAtlas* atlas : g.FontAtlases) + if (atlas->OwnerContext == &g) + { + atlas->RendererHasTextures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + ImFontAtlasUpdateNewFrame(atlas, g.FrameCount); + } } // Build a single texture list -// We want to avoid user reading from atlas->TexList[] in order to facilitate better support for multiple atlases. static void ImGui::UpdateTexturesEndFrame() { ImGuiContext& g = *GImGui; - ImFontAtlas* atlas = g.IO.Fonts; g.PlatformIO.Textures.resize(0); - g.PlatformIO.Textures.reserve(atlas->TexList.Size); - for (ImTextureData* tex : atlas->TexList) - { - // We provide this information so backends can decide whether to destroy textures. - // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized. - tex->RefCount = (unsigned short)atlas->RefCount; - g.PlatformIO.Textures.push_back(tex); - } + for (ImFontAtlas* atlas : g.FontAtlases) + for (ImTextureData* tex : atlas->TexList) + { + // We provide this information so backends can decide whether to destroy textures. + // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized. + tex->RefCount = (unsigned short)atlas->RefCount; + g.PlatformIO.Textures.push_back(tex); + } } // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. @@ -5810,8 +5808,8 @@ void ImGui::EndFrame() UpdateTexturesEndFrame(); // Unlock font atlas - ImFontAtlas* atlas = g.IO.Fonts; - atlas->Locked = false; + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->Locked = false; // Clear Input data for next frame g.IO.MousePosPrev = g.IO.MousePos; @@ -5890,7 +5888,8 @@ void ImGui::Render() #ifndef IMGUI_DISABLE_DEBUG_TOOLS if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) - ImFontAtlasDebugLogTextureRequests(g.IO.Fonts); + for (ImFontAtlas* atlas : g.FontAtlases) + ImFontAtlasDebugLogTextureRequests(atlas); #endif CallContextHooks(&g, ImGuiContextHookType_RenderPost); @@ -8596,9 +8595,9 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) void ImGui::UpdateFontsNewFrame() { ImGuiContext& g = *GImGui; - ImFontAtlas* atlas = g.IO.Fonts; if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) - atlas->Locked = true; + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->Locked = true; // We do this really unusual thing of calling *push_front()*, the reason behind that we want to support the PushFont()/NewFrame()/PopFont() idiom. ImFontStackData font_stack_data = { ImGui::GetDefaultFont(), ImGui::GetDefaultFont()->DefaultSize }; @@ -8614,6 +8613,25 @@ void ImGui::UpdateFontsEndFrame() PopFont(); } +void ImGui::RegisterFontAtlas(ImFontAtlas* atlas) +{ + ImGuiContext& g = *GImGui; + if (g.FontAtlases.Size == 0) + IM_ASSERT(atlas == g.IO.Fonts); + atlas->RefCount++; + g.FontAtlases.push_back(atlas); + ImFontAtlasAddDrawListSharedData(atlas, &g.DrawListSharedData); +} + +void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(atlas->RefCount > 0); + ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData); + g.FontAtlases.find_erase(atlas); + atlas->RefCount--; +} + // Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList. // - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls. // - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... @@ -8670,6 +8688,7 @@ void ImGui::UpdateCurrentFontSize() void ImGui::SetFontRasterizerDensity(float rasterizer_density) { ImGuiContext& g = *GImGui; + IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures); if (g.FontRasterizerDensity == rasterizer_density) return; g.FontRasterizerDensity = rasterizer_density; @@ -16104,12 +16123,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) } // Details for Fonts - ImFontAtlas* atlas = g.IO.Fonts; - if (TreeNode("Fonts", "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size)) - { - ShowFontAtlas(atlas); - TreePop(); - } + for (ImFontAtlas* atlas : g.FontAtlases) + if (TreeNode((void*)atlas, "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size)) + { + ShowFontAtlas(atlas); + TreePop(); + } // Details for Popups if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) diff --git a/imgui.h b/imgui.h index 71e49efe4..4ae0bd84b 100644 --- a/imgui.h +++ b/imgui.h @@ -3684,6 +3684,7 @@ struct ImFontAtlas void* FontLoaderData; // Font backend opaque storage unsigned int FontBuilderFlags; // [FIXME: Should be called FontLoaderFlags] Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. . Per-font override is also available in ImFontConfig. int RefCount; // Number of contexts using this atlas + ImGuiContext* OwnerContext; // Context which own the atlas will be in charge of updating and destroying it. // [Obsolete] #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_internal.h b/imgui_internal.h index f145fd012..fc44490d4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2132,10 +2132,10 @@ struct ImGuiContextHook struct ImGuiContext { bool Initialized; - bool FontAtlasOwnedByContext; // IO.Fonts-> is owned by the ImGuiContext and will be destructed along with it. ImGuiIO IO; ImGuiPlatformIO PlatformIO; ImGuiStyle Style; + ImVector FontAtlases; // List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) ImFont* Font; // == FontStack.back().Font ImFontBaked* FontBaked; // == Font->GetFontBaked(FontSize) float FontSize; // == FontSizeBeforeScaling * io.FontGlobalScale * font->Scale * g.CurrentWindow->FontWindowScale. Current text height. @@ -3108,6 +3108,8 @@ namespace ImGui IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); // Fonts, drawing + IMGUI_API void RegisterFontAtlas(ImFontAtlas* atlas); + IMGUI_API void UnregisterFontAtlas(ImFontAtlas* atlas); IMGUI_API void SetCurrentFont(ImFont* font, float font_size); IMGUI_API void SetFontRasterizerDensity(float rasterizer_density); inline float GetFontRasterizerDensity() { return GImGui->FontRasterizerDensity; } From 39f6c793b33aefa7769d262b3a12610fb49bd7ef Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 May 2025 10:22:15 +0200 Subject: [PATCH 1036/2359] Fonts: proof of concept support for user textures. # Conflicts: # imgui.h # imgui_internal.h --- imgui.cpp | 15 +++++++++++++++ imgui.h | 2 +- imgui_internal.h | 6 ++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index d79690088..2a4001d65 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5231,6 +5231,8 @@ static void ImGui::UpdateTexturesEndFrame() tex->RefCount = (unsigned short)atlas->RefCount; g.PlatformIO.Textures.push_back(tex); } + for (ImTextureData* tex : g.UserTextures) + g.PlatformIO.Textures.push_back(tex); } // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. @@ -8613,6 +8615,19 @@ void ImGui::UpdateFontsEndFrame() PopFont(); } +void ImGui::RegisterUserTexture(ImTextureData* tex) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(tex->RefCount > 0); + g.UserTextures.push_back(tex); +} + +void ImGui::UnregisterUserTexture(ImTextureData* tex) +{ + ImGuiContext& g = *GImGui; + g.UserTextures.find_erase(tex); +} + void ImGui::RegisterFontAtlas(ImFontAtlas* atlas) { ImGuiContext& g = *GImGui; diff --git a/imgui.h b/imgui.h index 4ae0bd84b..3a8d05377 100644 --- a/imgui.h +++ b/imgui.h @@ -3905,7 +3905,7 @@ struct ImGuiPlatformIO // Textures list (the list is updated by calling ImGui::EndFrame or ImGui::Render) // The ImGui_ImplXXXX_RenderDrawData() function of each backend generally access this via ImDrawData::Textures which points to this. The array is available here mostly because backends will want to destroy textures on shutdown. - ImVector Textures; // List of textures used by Dear ImGui (most often 1). + ImVector Textures; // List of textures used by Dear ImGui (most often 1) + contents of external texture list is automatically appended into this. }; // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). diff --git a/imgui_internal.h b/imgui_internal.h index fc44490d4..a390add19 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2426,6 +2426,10 @@ struct ImGuiContext ImGuiPlatformImeData PlatformImeData; // Data updated by current frame. Will be applied at end of the frame. For some backends, this is required to have WantVisible=true in order to receive text message. ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. + // Extensions + // FIXME: We could provide an API to register one slot in an array held in ImGuiContext? + ImVector UserTextures; // List of textures created/managed by user or third-party extension. Automatically appended into platform_io.Textures[]. + // Settings bool SettingsLoaded; float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero @@ -3108,6 +3112,8 @@ namespace ImGui IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); // Fonts, drawing + IMGUI_API void RegisterUserTexture(ImTextureData* tex); // Register external texture + IMGUI_API void UnregisterUserTexture(ImTextureData* tex); IMGUI_API void RegisterFontAtlas(ImFontAtlas* atlas); IMGUI_API void UnregisterFontAtlas(ImFontAtlas* atlas); IMGUI_API void SetCurrentFont(ImFont* font, float font_size); From 1b51a88bba9315f656ad9280bd98caddac0dc243 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 May 2025 16:08:05 +0200 Subject: [PATCH 1037/2359] Fonts: moved compare operators to internal. Removed commented out ones aimed legacy backends: not needed anymore since we didn't rename ImTextureID. --- imgui.h | 9 --------- imgui_internal.h | 5 +++++ 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index 3a8d05377..c431a8320 100644 --- a/imgui.h +++ b/imgui.h @@ -2836,15 +2836,6 @@ static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return IM_MSVC_RUNTIME_CHECKS_RESTORE #endif -// Helpers: ImTextureRef ==/!= operators provided as convenience -// (note that _TexID and _TexData are never set simultaneously) -static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } -static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } -//#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // For legacy backends -//static inline bool operator==(ImTextureID lhs, const ImTextureRef& rhs) { return lhs == rhs._TexID && rhs._TexData == NULL; } -//static inline bool operator==(const ImTextureRef& lhs, ImTextureID rhs) { return lhs._TexID == rhs && lhs._TexData == NULL; } -//#endif - // Helpers macros to generate 32-bit encoded colors // - User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file. // - Any setting other than the default will need custom backend support. The only standard backend that supports anything else than the default is DirectX9. diff --git a/imgui_internal.h b/imgui_internal.h index a390add19..7c6305734 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3704,6 +3704,11 @@ IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- +// Helpers: ImTextureRef ==/!= operators provided as convenience +// (note that _TexID and _TexData are never set simultaneously) +static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } +static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } + // Refer to ImFontAtlasPackGetRect() to better understand how this works. #define ImFontAtlasRectId_IndexMask_ (0x000FFFFF) // 20-bits: index to access builder->RectsIndex[]. #define ImFontAtlasRectId_GenerationMask_ (0x3FF00000) // 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. From ea756ede16fde3634ea3099cfd379fa2692d9625 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 May 2025 16:14:08 +0200 Subject: [PATCH 1038/2359] Fonts: reorder ImFontFlags according likelihood of being useful. --- imgui.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index c431a8320..61056bb6f 100644 --- a/imgui.h +++ b/imgui.h @@ -3732,10 +3732,10 @@ struct ImFontBaked enum ImFontFlags_ { ImFontFlags_None = 0, - ImFontFlags_LockBakedSizes = 1 << 0, // Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. - ImFontFlags_NoLoadGlyphs = 1 << 1, // Disable loading new glyphs. - ImFontFlags_NoLoadError = 1 << 2, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. - ImFontFlags_UseDefaultSize = 1 << 3, // Legacy compatibility: make PushFont() calls without explicit size use font->DefaultSize instead of current font size. + ImFontFlags_UseDefaultSize = 1 << 0, // Legacy compatibility: make PushFont() calls without explicit size use font->DefaultSize instead of current font size. + ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. + ImFontFlags_NoLoadGlyphs = 1 << 2, // Disable loading new glyphs. + ImFontFlags_LockBakedSizes = 1 << 3, // Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. }; // Font runtime data and rendering @@ -3788,13 +3788,14 @@ struct ImFont IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); }; -// We added an indirection to avoid patching ImDrawCmd after texture updates but this could be a solution too. +// This is provided for consistency (but we don't actually use this) inline ImTextureID ImTextureRef::GetTexID() const { IM_ASSERT(!(_TexData != NULL && _TexID != ImTextureID_Invalid)); return _TexData ? _TexData->TexID : _TexID; } +// Using an indirection to avoid patching ImDrawCmd after a SetTexID() call (but this could be an alternative solution too) inline ImTextureID ImDrawCmd::GetTexID() const { // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92) From 5ee984555984979e39e0fd5584be6dc442686499 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 16 May 2025 18:04:44 +0200 Subject: [PATCH 1039/2359] Fonts: automatically set current rasterizer density to viewport density. Effectively should fix most things on macOS. # Conflicts: # imgui.cpp # imgui.h --- docs/FONTS.md | 2 +- imgui.cpp | 6 +++++- imgui.h | 13 +++++++------ imgui_draw.cpp | 45 +++++++++++++++++++++++++-------------------- 4 files changed, 38 insertions(+), 28 deletions(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index 452499059..baa53adde 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -130,7 +130,7 @@ ImGui::PopFont(); **For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** ```cpp ImFontConfig config; -config.RasterizerDensity = 2.0f; +config.OversampleH = 1.0f; ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); ``` diff --git a/imgui.cpp b/imgui.cpp index 2a4001d65..58455df8d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4398,6 +4398,8 @@ static void SetCurrentWindow(ImGuiWindow* window) g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking if (window) { + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + g.FontRasterizerDensity = window->Viewport->FramebufferScale.x; // == SetFontRasterizerDensity() ImGui::UpdateCurrentFontSize(); ImGui::NavUpdateCurrentWindowIsScrollPushableX(); } @@ -8699,7 +8701,8 @@ void ImGui::UpdateCurrentFontSize() g.DrawListSharedData.FontScale = g.FontScale; } -// FIXME-DPI: Not sure how to expose this. It may be automatically applied based on current viewport, if we had this information stored in viewport or monitor. +// Exposed in case user may want to override setting density. +// IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it. void ImGui::SetFontRasterizerDensity(float rasterizer_density) { ImGuiContext& g = *GImGui; @@ -15240,6 +15243,7 @@ static void ImGui::UpdateViewportsNewFrame() main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp; main_viewport->Pos = ImVec2(0.0f, 0.0f); main_viewport->Size = g.IO.DisplaySize; + main_viewport->FramebufferScale = g.IO.DisplayFramebufferScale; for (ImGuiViewportP* viewport : g.Viewports) { diff --git a/imgui.h b/imgui.h index 61056bb6f..0eb83cd9a 100644 --- a/imgui.h +++ b/imgui.h @@ -2322,7 +2322,8 @@ struct ImGuiIO ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc. ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. - ImVec2 DisplaySize; // // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame. + ImVec2 DisplaySize; // // Main display size, in pixels (== GetMainViewport()->Size). May change every frame. + ImVec2 DisplayFramebufferScale; // = (1, 1) // Main display density. For retina display where window coordinates are different from framebuffer coordinates. This will affect font density + will end up in ImDrawData::FramebufferScale. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame. float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions. @@ -2334,7 +2335,6 @@ struct ImGuiIO float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. - ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale. // Keyboard/Gamepad Navigation options bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. @@ -3341,7 +3341,7 @@ struct ImDrawData ImVector CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications) ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) - ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. + ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Copied from viewport->FramebufferScale (== io.DisplayFramebufferScale for main viewport). Generally (1,1) on normal display, (2,2) on OSX with Retina display. ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overriden or set to NULL if you want to manually update textures. @@ -3734,8 +3734,8 @@ enum ImFontFlags_ ImFontFlags_None = 0, ImFontFlags_UseDefaultSize = 1 << 0, // Legacy compatibility: make PushFont() calls without explicit size use font->DefaultSize instead of current font size. ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. - ImFontFlags_NoLoadGlyphs = 1 << 2, // Disable loading new glyphs. - ImFontFlags_LockBakedSizes = 1 << 3, // Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. + ImFontFlags_NoLoadGlyphs = 1 << 2, // [Internal] Disable loading new glyphs. + ImFontFlags_LockBakedSizes = 1 << 3, // [Internal] Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. Important: if you use this to preload given sizes, consider the possibility of multiple font density used on Retina display. }; // Font runtime data and rendering @@ -3766,7 +3766,7 @@ struct ImFont // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); - IMGUI_API ImFontBaked* GetFontBaked(float font_size); // Get or create baked data for given size + IMGUI_API ImFontBaked* GetFontBaked(float font_size, float density = -1.0f); // Get or create baked data for given size IMGUI_API bool IsGlyphInFont(ImWchar c); bool IsLoaded() const { return ContainerAtlas != NULL; } const char* GetDebugName() const { return Sources.Size ? Sources[0]->Name : ""; } // Fill ImFontConfig::Name. @@ -3832,6 +3832,7 @@ struct ImGuiViewport ImGuiViewportFlags Flags; // See ImGuiViewportFlags_ ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) ImVec2 Size; // Main Area: Size of the viewport. + ImVec2 FramebufferScale; // Density of the viewport for Retina display (always 1,1 on Windows, may be 2,2 etc on macOS/iOS). This will affect font rasterizer density. ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 65485fb20..6306e9c75 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3786,25 +3786,28 @@ ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_si ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density) { ImFontAtlasBuilder* builder = atlas->Builder; - ImFontBaked* closest_larger_match = NULL; - ImFontBaked* closest_smaller_match = NULL; - for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + for (int step_n = 0; step_n < 2; step_n++) { - ImFontBaked* baked = &builder->BakedPool[baked_n]; - if (baked->ContainerFont != font || baked->WantDestroy) - continue; - if (baked->RasterizerDensity != font_rasterizer_density) - continue; - if (baked->Size > font_size && (closest_larger_match == NULL || baked->Size < closest_larger_match->Size)) - closest_larger_match = baked; - if (baked->Size < font_size && (closest_smaller_match == NULL || baked->Size > closest_smaller_match->Size)) - closest_smaller_match = baked; + ImFontBaked* closest_larger_match = NULL; + ImFontBaked* closest_smaller_match = NULL; + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->ContainerFont != font || baked->WantDestroy) + continue; + if (step_n == 0 && baked->RasterizerDensity != font_rasterizer_density) // First try with same density + continue; + if (baked->Size > font_size && (closest_larger_match == NULL || baked->Size < closest_larger_match->Size)) + closest_larger_match = baked; + if (baked->Size < font_size && (closest_smaller_match == NULL || baked->Size > closest_smaller_match->Size)) + closest_smaller_match = baked; + } + if (closest_larger_match) + if (closest_smaller_match == NULL || (closest_larger_match->Size >= font_size * 2.0f && closest_smaller_match->Size > font_size * 0.5f)) + return closest_larger_match; + if (closest_smaller_match) + return closest_smaller_match; } - if (closest_larger_match) - if (closest_smaller_match == NULL || (closest_larger_match->Size >= font_size * 2.0f && closest_smaller_match->Size > font_size * 0.5f)) - return closest_larger_match; - if (closest_smaller_match) - return closest_smaller_match; return NULL; } @@ -5195,7 +5198,7 @@ ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterize } // ImFontBaked pointers are valid for the entire frame but shall never be kept between frames. -ImFontBaked* ImFont::GetFontBaked(float size) +ImFontBaked* ImFont::GetFontBaked(float size, float density) { ImFontBaked* baked = LastBaked; @@ -5203,12 +5206,14 @@ ImFontBaked* ImFont::GetFontBaked(float size) // - ImGui::PushFontSize() will already round, but other paths calling GetFontBaked() directly also needs it (e.g. ImFontAtlasBuildPreloadAllGlyphRanges) size = ImGui::GetRoundedFontSize(size); - if (baked && baked->Size == size && baked->RasterizerDensity == CurrentRasterizerDensity) + if (density < 0.0f) + density = CurrentRasterizerDensity; + if (baked && baked->Size == size && baked->RasterizerDensity == density) return baked; ImFontAtlas* atlas = ContainerAtlas; ImFontAtlasBuilder* builder = atlas->Builder; - baked = ImFontAtlasBakedGetOrAdd(atlas, this, size, CurrentRasterizerDensity); + baked = ImFontAtlasBakedGetOrAdd(atlas, this, size, density); if (baked == NULL) return NULL; baked->LastUsedFrame = builder->FrameCount; From 822903e56debba39530ecc3bebfdf7709737c217 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 16 May 2025 16:55:29 +0200 Subject: [PATCH 1040/2359] Fonts: fixed ImFontAtlas::RemoveFont() with multiple sources. Thanks cyfewlp! --- imgui_draw.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6306e9c75..3d719820f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3205,10 +3205,10 @@ void ImFontAtlas::RemoveFont(ImFont* font) ImFontAtlasFontDestroyOutput(this, font); for (ImFontConfig* src : font->Sources) - { ImFontAtlasFontDestroySourceData(this, src); - Sources.erase(src); - } + for (int src_n = 0; src_n < Sources.Size; src_n++) + if (Sources[src_n].DstFont == font) + Sources.erase(&Sources[src_n--]); bool removed = Fonts.find_erase(font); IM_ASSERT(removed); From 3d848a886a4a071e4b3157b08f37254a4f0d9166 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 May 2025 13:43:16 +0200 Subject: [PATCH 1041/2359] Fonts: fixed support for IMGUI_STB_NAMESPACE. --- imgui_internal.h | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 7c6305734..de68b9b3b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3746,13 +3746,21 @@ struct ImFontAtlasPostProcessData int Height; }; -// Internal storage for incrementally packing and building a ImFontAtlas -struct stbrp_context_opaque { char data[80]; }; +// We avoid dragging imstb_rectpack.h into public header (partly because binding generators are having issues with it) +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE { struct stbrp_node; } +typedef IMGUI_STB_NAMESPACE::stbrp_node stbrp_node_im; +#else struct stbrp_node; +typedef stbrp_node stbrp_node_im; +#endif +struct stbrp_context_opaque { char data[80]; }; + +// Internal storage for incrementally packing and building a ImFontAtlas struct ImFontAtlasBuilder { stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file. - ImVector PackNodes; + ImVector PackNodes; ImVector Rects; ImVector RectsIndex; // ImFontAtlasRectId -> index into Rects[] ImVector TempBuffer; // Misc scratch buffer From 92ff153763cc9f701d288a24957ffd552c172060 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 May 2025 14:03:45 +0200 Subject: [PATCH 1042/2359] Fonts: added notes/comments and dummy type about renaming ImFontBuilderIO::GetBuilderForFreeType() to ImFontLoader::GetFontLoader(). --- imgui_internal.h | 3 +++ misc/freetype/imgui_freetype.h | 7 +++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index de68b9b3b..b1d8774ce 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3699,6 +3699,9 @@ struct ImFontLoader #ifdef IMGUI_ENABLE_STB_TRUETYPE IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); #endif +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are not actually compatible but we provide this as a compile-time error report helper. +#endif //----------------------------------------------------------------------------- // [SECTION] ImFontAtlas internal API diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index b4e9ba1fd..2b4810e32 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -6,7 +6,9 @@ #ifndef IMGUI_DISABLE // Usage: -// - Add '#define IMGUI_ENABLE_FREETYPE' in your imconfig to enable support for imgui_freetype in imgui. +// - Add '#define IMGUI_ENABLE_FREETYPE' in your imconfig to automatically enable support +// for imgui_freetype in imgui. It is equivalent to selecting the default loader with: +// io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader() // Optional support for OpenType SVG fonts: // - Add '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG' to use plutosvg (not provided). See #7927. @@ -52,8 +54,9 @@ namespace ImGuiFreeType // Display UI to edit FontBuilderFlags in ImFontAtlas (shared) or ImFontConfig (single source) IMGUI_API bool DebugEditFontBuilderFlags(unsigned int* p_font_loader_flags); - // Obsolete names (will be removed soon) + // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //IMGUI_API const ImFontBuilderIO* GetBuilderForFreeType(); // Renamed/changed in 1.92. Change 'io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()' to 'io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader()' if you need runtime selection. //static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontBuilderFlags = flags; return atlas->Build(); } // Prefer using '#define IMGUI_ENABLE_FREETYPE' #endif } From f3780c73544466ebe10c6c31749d57d605210b48 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 May 2025 18:14:12 +0200 Subject: [PATCH 1043/2359] Fonts: adding GetFontBaked() in public API. --- imgui.cpp | 5 +++++ imgui.h | 5 +++-- imgui_internal.h | 6 +++--- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 58455df8d..13cb78f0b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8419,6 +8419,11 @@ ImFont* ImGui::GetFont() return GImGui->Font; } +ImFontBaked* ImGui::GetFontBaked() +{ + return GImGui->FontBaked; +} + float ImGui::GetFontSize() { return GImGui->FontSize; diff --git a/imgui.h b/imgui.h index 0eb83cd9a..916ad7547 100644 --- a/imgui.h +++ b/imgui.h @@ -495,7 +495,7 @@ namespace ImGui // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. // - Before 1.92: PushFont() always used font default size. // - Since 1.92: PushFont() preserve the current shared font size. - // - To use old behavior: use 'PushFont(font, font->DefaultSize)' in call site, or set 'ImFontConfig::Flags |= ImFontFlags_UseDefaultSize' before calling AddFont(). + // - To use old behavior (single size font): use 'PushFont(font, font->DefaultSize)' in call site, or set 'ImFontConfig::Flags |= ImFontFlags_UseDefaultSize' before calling AddFont(). IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. Use font->DefaultSize to revert to font default size. IMGUI_API void PopFont(); IMGUI_API void PushFontSize(float font_size); @@ -526,6 +526,7 @@ namespace ImGui IMGUI_API ImFont* GetFont(); // get current font IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a white pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList IMGUI_API ImU32 GetColorU32(ImU32 col, float alpha_mul = 1.0f); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList @@ -3754,7 +3755,7 @@ struct ImFont // [Internal] Members: Cold ~24-52 bytes // Conceptually Sources[] is the list of font sources merged to create this font. ImGuiID FontId; // Unique identifier for the font - float DefaultSize; // 4 // in // Default font size + float DefaultSize; // 4 // in // Default font size passed to AddFont(). It's unlikely you should use this (use ImGui::GetFontBaked() to get font baked at current bound size). ImVector Sources; // 16 // in // List of sources. Pointers within ContainerAtlas->Sources[] ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') diff --git a/imgui_internal.h b/imgui_internal.h index b1d8774ce..b4ddf4175 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2136,9 +2136,9 @@ struct ImGuiContext ImGuiPlatformIO PlatformIO; ImGuiStyle Style; ImVector FontAtlases; // List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) - ImFont* Font; // == FontStack.back().Font - ImFontBaked* FontBaked; // == Font->GetFontBaked(FontSize) - float FontSize; // == FontSizeBeforeScaling * io.FontGlobalScale * font->Scale * g.CurrentWindow->FontWindowScale. Current text height. + ImFont* Font; // Currently bound font. (== FontStack.back().Font) + ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) + float FontSize; // Currently bound font size == line height (== FontSizeBeforeScaling * io.FontGlobalScale * font->Scale * g.CurrentWindow->FontWindowScale). float FontSizeBeforeScaling; // == value passed to PushFontSize() float FontScale; // == FontBaked->Size / Font->FontSize. Scale factor over baked size. float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). From 83aad812798ff8a0cd7f583f07a4adc6d9b809a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 20 May 2025 18:12:08 +0200 Subject: [PATCH 1044/2359] Fonts: comments + made IMGUI_DEBUG_LOG_FONT() work without an ImGui context. --- imgui.h | 5 ++++- imgui_internal.h | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 916ad7547..0e4c73915 100644 --- a/imgui.h +++ b/imgui.h @@ -350,6 +350,8 @@ typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or // - If you want to bind the current atlas when using custom rectangle, you can use io.Fonts->TexRef. // - Binding generators for languages such as C (which don't have constructors), should provide a helper: // inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; } +// In 1.92 we changed most drawing functions using ImTextureID to use ImTextureRef. +// We intentionally do not provide an implicit ImTextureRef -> ImTextureID cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering. IM_MSVC_RUNTIME_CHECKS_OFF struct ImTextureRef { @@ -358,7 +360,8 @@ struct ImTextureRef #if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureID) ImTextureRef(void* tex_id) { _TexData = NULL; _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID #endif - inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file. + + inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file. // Members (either are set, never both!) ImTextureData* _TexData; // A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. diff --git a/imgui_internal.h b/imgui_internal.h index b4ddf4175..55ca3ba89 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -246,7 +246,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IMGUI_DEBUG_LOG_SELECTION(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_CLIPPER(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_IO(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_FONT(...) do { ImGuiContext& g2 = *GImGui; if (g2.DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_FONT(...) do { ImGuiContext* g2 = GImGui; if (g2 && g2->DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) // Called from ImFontAtlas function which may operate without a context. #define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) // Static Asserts From b2343d62474e87b241c6cd2e27464142bb2dd2ba Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 20 May 2025 19:56:27 +0200 Subject: [PATCH 1045/2359] Fonts: fallback to default default rasterizer density + pick one from existing viewports at the time of calling AddUpdateViewport(). # Conflicts: # imgui.cpp --- imgui.cpp | 6 +++++- imgui_draw.cpp | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 13cb78f0b..d869da7fe 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4399,7 +4399,10 @@ static void SetCurrentWindow(ImGuiWindow* window) if (window) { if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) - g.FontRasterizerDensity = window->Viewport->FramebufferScale.x; // == SetFontRasterizerDensity() + { + ImGuiViewport* viewport = window->Viewport; + g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity() + } ImGui::UpdateCurrentFontSize(); ImGui::NavUpdateCurrentWindowIsScrollPushableX(); } @@ -15249,6 +15252,7 @@ static void ImGui::UpdateViewportsNewFrame() main_viewport->Pos = ImVec2(0.0f, 0.0f); main_viewport->Size = g.IO.DisplaySize; main_viewport->FramebufferScale = g.IO.DisplayFramebufferScale; + IM_ASSERT(main_viewport->FramebufferScale.x > 0.0f && main_viewport->FramebufferScale.y > 0.0f); for (ImGuiViewportP* viewport : g.Viewports) { diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3d719820f..93f5fdf8d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5225,6 +5225,7 @@ ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float fo { // FIXME-NEWATLAS: Design for picking a nearest size based on some criteria? // FIXME-NEWATLAS: Altering font density won't work right away. + IM_ASSERT(font_size > 0.0f && font_rasterizer_density > 0.0f); ImGuiID baked_id = ImFontAtlasBakedGetId(font->FontId, font_size, font_rasterizer_density); ImFontAtlasBuilder* builder = atlas->Builder; ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); From 9f8b4bdaf1bc7565ebd9e0f762048d7754868ff3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 21 May 2025 20:35:04 +0200 Subject: [PATCH 1046/2359] Fonts: fixed edge case calling RenderText() without priming with CalcTextSize(). --- imgui_draw.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 93f5fdf8d..e84de2baa 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5502,6 +5502,7 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, Im 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, bool cpu_fine_clip) { // Align to be pixel perfect +begin: float x = IM_TRUNC(pos.x); float y = IM_TRUNC(pos.y); if (y > clip_rect.w) @@ -5556,6 +5557,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im return; // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) + const int cmd_count = draw_list->CmdBuffer.Size; const int vtx_count_max = (int)(text_end - s) * 4; const int idx_count_max = (int)(text_end - s) * 6; const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; @@ -5678,6 +5680,18 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im x += char_width; } + // Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui:: calls because CalcTextSize() is always used. + if (cmd_count != draw_list->CmdBuffer.Size) + { + IM_ASSERT(draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount == 0); + draw_list->CmdBuffer.pop_back(); + draw_list->PrimUnreserve(idx_count_max, vtx_count_max); + draw_list->AddDrawCmd(); + goto begin; + //RenderText(draw_list, size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip); // FIXME-OPT: Would a 'goto begin' be better for code-gen? + //return; + } + // Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. draw_list->VtxBuffer.Size = (int)(vtx_write - draw_list->VtxBuffer.Data); // Same as calling shrink() draw_list->IdxBuffer.Size = (int)(idx_write - draw_list->IdxBuffer.Data); From 5926c877a115d626260f60fc4d80fdb46e92c3ec Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 May 2025 16:32:46 +0200 Subject: [PATCH 1047/2359] Fonts: detect if ImFontAtlasUpdateNewFrame() is not being called. --- imgui.cpp | 12 ++++++++++-- imgui_draw.cpp | 7 +++++-- imgui_internal.h | 2 +- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d869da7fe..f5c4330e8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5211,16 +5211,24 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; } -// FIXME-NEWATLAS-V2: If we aim to support multiple atlases used by same context: how to reach/target all atlases? static void ImGui::UpdateTexturesNewFrame() { + // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count. ImGuiContext& g = *GImGui; + const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; for (ImFontAtlas* atlas : g.FontAtlases) + { if (atlas->OwnerContext == &g) { - atlas->RendererHasTextures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + atlas->RendererHasTextures = has_textures; ImFontAtlasUpdateNewFrame(atlas, g.FrameCount); } + else + { + IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1 && "If you manage font atlases yourself you need to call ImFontAtlasUpdateNewFrame() on it."); + IM_ASSERT(atlas->RendererHasTextures == has_textures && "If you manage font atlases yourself make sure atlas->RendererHasTextures is set consistently with all contexts using it."); + } + } } // Build a single texture list diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e84de2baa..e0d34c977 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2715,11 +2715,14 @@ static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* at } } -// Called by NewFrame(). When multiple context own the atlas, only the first one calls this. -// If you are calling this yourself, ensure atlas->RendererHasTextures is set. +// Called by NewFrame() for atlases owned by a context. +// If you manually manage font atlases, you'll need to call this yourself + ensure atlas->RendererHasTextures is set. // 'frame_count' needs to be provided because we can gc/prioritize baked fonts based on their age. +// 'frame_count' may not match those of imgui contexts using this atlas, as contexts may be updated as different frequencies. void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count) { + IM_ASSERT(atlas->Builder == NULL || atlas->Builder->FrameCount < frame_count); // Protection against being called twice? + // Check that font atlas was built or backend support texture reload in which case we can build now if (atlas->RendererHasTextures) { diff --git a/imgui_internal.h b/imgui_internal.h index 55ca3ba89..62b98f1f0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3787,7 +3787,7 @@ struct ImFontAtlasBuilder ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. ImFontAtlasRectId PackIdLinesTexData; - ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } + ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } }; IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); From 25f9c318e315e5275ca0993adf3b632574ee490c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 May 2025 17:45:22 +0200 Subject: [PATCH 1048/2359] Fonts: added "Input Glyphs Overlap Detection Tool". Added "Clear bakes", "Clear unused" buttons. Move code. --- imgui.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++++++++ imgui.h | 2 +- imgui_draw.cpp | 15 +++++++++----- imgui_internal.h | 2 +- 4 files changed, 64 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f5c4330e8..9b9874a5a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16699,6 +16699,21 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co out_draw_list->Flags = backup_flags; } +// [DEBUG] Compute mask of inputs with the same codepoint. +static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigned int codepoint) +{ + int mask = 0, count = 0; + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + { + ImFontConfig* src = font->Sources[src_n]; + if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint)) + continue; + mask |= (1 << src_n); + count++; + } + return count > 1 ? mask : 0; +} + // [DEBUG] Display details for a single font, called by ShowStyleEditor(). void ImGui::DebugNodeFont(ImFont* font) { @@ -16730,6 +16745,12 @@ void ImGui::DebugNodeFont(ImFont* font) if (SmallButton("Remove")) atlas->RemoveFont(font); EndDisabled(); + SameLine(); + if (SmallButton("Clear bakes")) + ImFontAtlasFontDiscardBakes(atlas, font, 0); + SameLine(); + if (SmallButton("Clear unused")) + ImFontAtlasFontDiscardBakes(atlas, font, 2); // Display details SetNextItemWidth(GetFontSize() * 8); @@ -16769,6 +16790,37 @@ void ImGui::DebugNodeFont(ImFont* font) TreePop(); } } + if (font->Sources.Size > 1 && TreeNode("Input Glyphs Overlap Detection Tool")) + { + TextWrapped("- First Input that contains the glyph is used.\n- Use ImFontConfig::GlyphExcludeRanges[] to specify ranges to ignore glyph in given Input.\n- This tool doesn't cache results and is slow, don't keep it open!"); + if (BeginTable("table", 2)) + { + for (unsigned int c = 0; c < 0x10000; c++) + if (int overlap_mask = CalcFontGlyphSrcOverlapMask(atlas, font, c)) + { + unsigned int c_end = c + 1; + while (c_end < 0x10000 && CalcFontGlyphSrcOverlapMask(atlas, font, c_end) == overlap_mask) + c_end++; + if (TableNextColumn() && TreeNode((void*)(intptr_t)c, "U+%04X-U+%04X: %d codepoints in %d inputs", c, c_end - 1, c_end - c, ImCountSetBits(overlap_mask))) + { + char utf8_buf[5]; + for (unsigned int n = c; n < c_end; n++) + BulletText("Codepoint U+%04X (%s)", n, ImTextCharToUtf8(utf8_buf, n)); + TreePop(); + } + TableNextColumn(); + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + if (overlap_mask & (1 << src_n)) + { + Text("%d ", src_n); + SameLine(); + } + c = c_end - 1; + } + EndTable(); + } + TreePop(); + } // Display all glyphs of the fonts in separate pages of 256 characters for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++) diff --git a/imgui.h b/imgui.h index 0e4c73915..8ed8f2318 100644 --- a/imgui.h +++ b/imgui.h @@ -3456,7 +3456,7 @@ struct ImFontConfig //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). - const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a VERY SHORT user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. + const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a VERY SHORT user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e0d34c977..b2380dfc0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3843,14 +3843,18 @@ void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* bake font->LastBaked = NULL; } -void ImFontAtlasFontDiscardOutputBakes(ImFontAtlas* atlas, ImFont* font) +// use unused_frames==0 to discard everything. +void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames) { if (ImFontAtlasBuilder* builder = atlas->Builder) // This can be called from font destructor for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) { ImFontBaked* baked = &builder->BakedPool[baked_n]; - if (baked->ContainerFont == font && !baked->WantDestroy) - ImFontAtlasBakedDiscard(atlas, font, baked); + if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount) + continue; + if (baked->ContainerFont != font || baked->WantDestroy) + continue; + ImFontAtlasBakedDiscard(atlas, font, baked); } } @@ -4364,7 +4368,8 @@ ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId return &builder->Rects[index_entry->TargetIndex]; } -// Important! This assume by ImFontConfig::GlyphFilter is a SMALL ARRAY (e.g. <10 entries) +// Important! This assume by ImFontConfig::GlyphExcludeRanges[] is a SMALL ARRAY (e.g. <10 entries) +// Use "Input Glyphs Overlap Detection Tool" to display a list of glyphs provided by multiple sources in order to set this array up. static bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint) { if (const ImWchar* exclude_list = src->GlyphExcludeRanges) @@ -5024,7 +5029,7 @@ ImFont::~ImFont() void ImFont::ClearOutputData() { if (ImFontAtlas* atlas = ContainerAtlas) - ImFontAtlasFontDiscardOutputBakes(atlas, this); + ImFontAtlasFontDiscardBakes(atlas, this, 0); FallbackChar = EllipsisChar = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); LastBaked = NULL; diff --git a/imgui_internal.h b/imgui_internal.h index 62b98f1f0..59666f3e5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3815,7 +3815,7 @@ IMGUI_API void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, I IMGUI_API void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font); // Using FontDestroyOutput/FontInitOutput sequence useful notably if font loader params have changed IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font); -IMGUI_API void ImFontAtlasFontDiscardOutputBakes(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames); IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density); IMGUI_API ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); From e3860aa6ac0be98df8df0aeaa194107a27f5f4d4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 May 2025 13:52:20 +0200 Subject: [PATCH 1049/2359] (Breaking) Fonts: removing obsolete ImFont::Scale. --- imgui.cpp | 13 ++++++++++--- imgui.h | 4 +++- imgui_draw.cpp | 2 ++ imgui_internal.h | 2 +- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9b9874a5a..79d36db59 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8683,7 +8683,9 @@ void ImGui::SetCurrentFont(ImFont* font, float font_size) if (font != NULL) { IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS IM_ASSERT(font->Scale > 0.0f); +#endif g.DrawListSharedData.Font = g.Font; ImFontAtlasUpdateDrawListsSharedData(g.Font->ContainerAtlas); if (g.CurrentWindow != NULL) @@ -8699,7 +8701,10 @@ void ImGui::UpdateCurrentFontSize() return; float final_size = g.FontSizeBeforeScaling * g.IO.FontGlobalScale; - final_size *= g.Font->Scale; +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (g.Font != NULL) + final_size *= g.Font->Scale; +#endif if (window != NULL) final_size *= window->FontWindowScale; @@ -16753,14 +16758,16 @@ void ImGui::DebugNodeFont(ImFont* font) ImFontAtlasFontDiscardBakes(atlas, font, 2); // Display details +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS SetNextItemWidth(GetFontSize() * 8); DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); - SameLine(); MetricsHelpMarker( + /*SameLine(); MetricsHelpMarker( "Note that the default embedded font is NOT meant to be scaled.\n\n" "Font are currently rendered into bitmaps at a given size at the time of building the atlas. " "You may oversample them to get some flexibility with scaling. " "You can also render at multiple sizes and select which one to use at runtime.\n\n" - "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)"); + "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");*/ +#endif char c_str[5]; Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar); diff --git a/imgui.h b/imgui.h index 8ed8f2318..9a9473760 100644 --- a/imgui.h +++ b/imgui.h @@ -3762,10 +3762,12 @@ struct ImFont ImVector Sources; // 16 // in // List of sources. Pointers within ContainerAtlas->Sources[] ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') - float Scale; // 4 // in // Base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() +#endif // Methods IMGUI_API ImFont(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b2380dfc0..7e5b10f34 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5018,7 +5018,9 @@ void ImFontBaked::ClearOutputData() ImFont::ImFont() { memset(this, 0, sizeof(*this)); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS Scale = 1.0f; +#endif } ImFont::~ImFont() diff --git a/imgui_internal.h b/imgui_internal.h index 59666f3e5..5dacf666e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2139,7 +2139,7 @@ struct ImGuiContext ImFont* Font; // Currently bound font. (== FontStack.back().Font) ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) float FontSize; // Currently bound font size == line height (== FontSizeBeforeScaling * io.FontGlobalScale * font->Scale * g.CurrentWindow->FontWindowScale). - float FontSizeBeforeScaling; // == value passed to PushFontSize() + float FontSizeBeforeScaling; // == value passed to PushFont() / PushFontSize() when specified. float FontScale; // == FontBaked->Size / Font->FontSize. Scale factor over baked size. float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale From 69547bd4bdfb50841548b18574809d14dc83f05e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 May 2025 14:54:26 +0200 Subject: [PATCH 1050/2359] Fonts: ImFont::DefaultSize -> ImFont::LegacySize. ImFontFlags_UseDefaultSize -> ImFontFlags_DefaultToLegacySize. --- imgui.cpp | 6 +++--- imgui.h | 10 +++++----- imgui_draw.cpp | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 79d36db59..0a637be0e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8620,7 +8620,7 @@ void ImGui::UpdateFontsNewFrame() atlas->Locked = true; // We do this really unusual thing of calling *push_front()*, the reason behind that we want to support the PushFont()/NewFrame()/PopFont() idiom. - ImFontStackData font_stack_data = { ImGui::GetDefaultFont(), ImGui::GetDefaultFont()->DefaultSize }; + ImFontStackData font_stack_data = { ImGui::GetDefaultFont(), ImGui::GetDefaultFont()->LegacySize }; g.FontStack.push_front(font_stack_data); if (g.FontStack.Size == 1) ImGui::SetCurrentFont(font_stack_data.Font, font_stack_data.FontSize); @@ -8741,8 +8741,8 @@ void ImGui::PushFont(ImFont* font, float font_size) font = GetDefaultFont(); if (font_size <= 0.0f) { - if (font->Flags & ImFontFlags_UseDefaultSize) - font_size = font->DefaultSize; // Legacy: use default font size. Same as doing PushFont(font, font->DefaultSize). // FIXME-NEWATLAS + if (font->Flags & ImFontFlags_DefaultToLegacySize) + font_size = font->LegacySize; // Legacy: use AddFont() specified font size. Same as doing PushFont(font, font->LegacySize) else font_size = g.FontSizeBeforeScaling; // Keep current font size } diff --git a/imgui.h b/imgui.h index 9a9473760..a10e8d1a3 100644 --- a/imgui.h +++ b/imgui.h @@ -498,8 +498,8 @@ namespace ImGui // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. // - Before 1.92: PushFont() always used font default size. // - Since 1.92: PushFont() preserve the current shared font size. - // - To use old behavior (single size font): use 'PushFont(font, font->DefaultSize)' in call site, or set 'ImFontConfig::Flags |= ImFontFlags_UseDefaultSize' before calling AddFont(). - IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. Use font->DefaultSize to revert to font default size. + // - To use old behavior (single size font): use 'PushFont(font, font->LegacySize)' in call site, or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' before calling AddFont(). + IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. Use font->LegacySize to revert to font size specified by AddFont(). IMGUI_API void PopFont(); IMGUI_API void PushFontSize(float font_size); IMGUI_API void PopFontSize(); @@ -3736,7 +3736,7 @@ struct ImFontBaked enum ImFontFlags_ { ImFontFlags_None = 0, - ImFontFlags_UseDefaultSize = 1 << 0, // Legacy compatibility: make PushFont() calls without explicit size use font->DefaultSize instead of current font size. + ImFontFlags_DefaultToLegacySize = 1 << 0, // Legacy compatibility: make PushFont() calls without explicit size use font->LegacySize instead of current font size. ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. ImFontFlags_NoLoadGlyphs = 1 << 2, // [Internal] Disable loading new glyphs. ImFontFlags_LockBakedSizes = 1 << 3, // [Internal] Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. Important: if you use this to preload given sizes, consider the possibility of multiple font density used on Retina display. @@ -3758,7 +3758,7 @@ struct ImFont // [Internal] Members: Cold ~24-52 bytes // Conceptually Sources[] is the list of font sources merged to create this font. ImGuiID FontId; // Unique identifier for the font - float DefaultSize; // 4 // in // Default font size passed to AddFont(). It's unlikely you should use this (use ImGui::GetFontBaked() to get font baked at current bound size). + float LegacySize; // 4 // in // Font size passed to AddFont(). Use for old code calling PushFont() expecting to use that size. (use ImGui::GetFontBaked() to get font baked at current bound size). ImVector Sources; // 16 // in // List of sources. Pointers within ContainerAtlas->Sources[] ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') @@ -3785,7 +3785,7 @@ struct ImFont 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, bool cpu_fine_clip = false); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(DefaultSize * scale, 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, text, text_end, wrap_width); } #endif // [Internal] Don't use! diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7e5b10f34..e067d57ba 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3004,7 +3004,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) font = IM_NEW(ImFont)(); font->FontId = FontNextUniqueID++; font->Flags = font_cfg_in->Flags; - font->DefaultSize = font_cfg_in->SizePixels; + font->LegacySize = font_cfg_in->SizePixels; font->CurrentRasterizerDensity = font_cfg_in->RasterizerDensity; Fonts.push_back(font); } @@ -3266,7 +3266,7 @@ void ImFontAtlas::RemoveCustomRect(ImFontAtlasRectId id) // myfont->Flags |= ImFontFlags_LockBakedSizes; ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) { - float font_size = font->DefaultSize; + float font_size = font->LegacySize; return AddCustomRectFontGlyphForSize(font, font_size, codepoint, width, height, advance_x, offset); } // FIXME: we automatically set glyph.Colored=true by default. From 033cdc41338e3b5947ac85ec57a997d964e31abb Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 May 2025 15:08:54 +0200 Subject: [PATCH 1051/2359] Fonts: comments and slight packing of ImFontConfig fields. --- imgui.cpp | 7 ++----- imgui.h | 17 ++++++++++------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0a637be0e..38f0cf096 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15914,11 +15914,8 @@ void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRe PopStyleVar(); char texid_desc[30]; - Text("Status = %s (%d)", ImTextureDataGetStatusName(tex->Status), tex->Status); - Text("Format = %s (%d)", ImTextureDataGetFormatName(tex->Format), tex->Format); - Text("TexID = %s", FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->TexID)); - Text("BackendUserData = %p", tex->BackendUserData); - Text("UseColors = %d", tex->UseColors); + Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors); + Text("TexID = %s, BackendUserData = %p", FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->TexID), tex->BackendUserData); TreePop(); } PopID(); diff --git a/imgui.h b/imgui.h index a10e8d1a3..44aa078ae 100644 --- a/imgui.h +++ b/imgui.h @@ -3443,20 +3443,24 @@ struct ImTextureData // A font input/source (we may rename this to ImFontSource in the future) struct ImFontConfig { + // Data Source + char Name[40]; // // Name (strictly to ease debugging, hence limited size buffer) void* FontData; // // TTF/OTF data int FontDataSize; // // TTF/OTF data size bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). + + // Options bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. bool PixelSnapV; // true // Align Scaled GlyphOffset.y to pixel boundaries. - int FontNo; // 0 // Index of font within TTF/OTF file - int OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. - int OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. + ImS8 FontNo; // 0 // Index of font within TTF/OTF file + ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. + ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). + const ImWchar* GlyphRanges; // NULL // *LEGACY* THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). + const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a VERY SHORT user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. - const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). - const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a VERY SHORT user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. @@ -3466,8 +3470,7 @@ struct ImFontConfig ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. // [Internal] - char Name[40]; // Name (strictly to ease debugging) - ImFontFlags Flags; // Font flags (don't use just yet) + ImFontFlags Flags; // Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) ImFont* DstFont; // Target font (as we merging fonts, multiple ImFontConfig may target the same font) const ImFontLoader* FontLoader; // Custom font backend for this source (other use one stored in ImFontAtlas) void* FontLoaderData; // Font loader opaque storage (per font config) From b029be6b6c251e4bb647b9b5c60b239b38c93a9c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 May 2025 18:55:55 +0200 Subject: [PATCH 1052/2359] Fonts: avoid calling GetFontBaked() during SetFontSize(). Also fixes loading extraneous baked on atlas that will be locked e.g. PushFontSize() before NewFrame() on legacy backend. --- imgui.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 38f0cf096..7b4fc8638 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8715,9 +8715,9 @@ void ImGui::UpdateCurrentFontSize() final_size = ImMax(1.0f, final_size); if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity; - g.FontBaked = (g.Font != NULL) ? g.Font->GetFontBaked(final_size) : NULL; g.FontSize = final_size; - g.FontScale = (g.Font != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; + g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL; + g.FontScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; g.DrawListSharedData.FontSize = g.FontSize; g.DrawListSharedData.FontScale = g.FontScale; } From 1e118ab8911625bf49938dd5d29c2833af216096 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 May 2025 20:24:06 +0200 Subject: [PATCH 1053/2359] Fonts: added ImGuiStyle::FontSizeBase. Ensuring PushFontSize() works before main loop and across NewFrame(). # Conflicts: # imgui.cpp --- imgui.cpp | 106 +++++++++++++++++++++++++++++++++-------------- imgui.h | 20 +++++++-- imgui_demo.cpp | 44 +++++++++++++------- imgui_draw.cpp | 2 +- imgui_internal.h | 9 ++-- 5 files changed, 125 insertions(+), 56 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7b4fc8638..d18beab96 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1354,6 +1354,7 @@ static void* GImAllocatorUserData = NULL; ImGuiStyle::ImGuiStyle() { + FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame. Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui. DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. WindowPadding = ImVec2(8,8); // Padding within a window @@ -1415,6 +1416,10 @@ ImGuiStyle::ImGuiStyle() HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. + // [Internal] + _MainScale = 1.0f; + _NextFrameFontSizeBase = 0.0f; + // Default theme ImGui::StyleColorsDark(this); } @@ -1423,6 +1428,8 @@ ImGuiStyle::ImGuiStyle() // Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. void ImGuiStyle::ScaleAllSizes(float scale_factor) { + _MainScale *= scale_factor; + FontSizeBase = ImTrunc(FontSizeBase * scale_factor); WindowPadding = ImTrunc(WindowPadding * scale_factor); WindowRounding = ImTrunc(WindowRounding * scale_factor); WindowMinSize = ImTrunc(WindowMinSize * scale_factor); @@ -4403,7 +4410,7 @@ static void SetCurrentWindow(ImGuiWindow* window) ImGuiViewport* viewport = window->Viewport; g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity() } - ImGui::UpdateCurrentFontSize(); + ImGui::UpdateCurrentFontSize(0.0f); ImGui::NavUpdateCurrentWindowIsScrollPushableX(); } } @@ -8450,7 +8457,7 @@ void ImGui::SetWindowFontScale(float scale) IM_ASSERT(scale > 0.0f); ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; - UpdateCurrentFontSize(); + UpdateCurrentFontSize(0.0f); } void ImGui::PushFocusScope(ImGuiID id) @@ -8619,12 +8626,24 @@ void ImGui::UpdateFontsNewFrame() for (ImFontAtlas* atlas : g.FontAtlases) atlas->Locked = true; - // We do this really unusual thing of calling *push_front()*, the reason behind that we want to support the PushFont()/NewFrame()/PopFont() idiom. - ImFontStackData font_stack_data = { ImGui::GetDefaultFont(), ImGui::GetDefaultFont()->LegacySize }; - g.FontStack.push_front(font_stack_data); - if (g.FontStack.Size == 1) - ImGui::SetCurrentFont(font_stack_data.Font, font_stack_data.FontSize); + if (g.Style._NextFrameFontSizeBase != 0.0f) + { + g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase; + g.Style._NextFrameFontSizeBase = 0.0f; + } + // Apply default font size the first time + ImFont* font = ImGui::GetDefaultFont(); + if (g.Style.FontSizeBase <= 0.0f) + g.Style.FontSizeBase = font->LegacySize * g.Style._MainScale; + + // Set initial font + g.Font = font; + g.FontSizeBeforeScaling = g.Style.FontSizeBase; + g.FontSize = 0.0f; + ImFontStackData font_stack_data = { font, g.Style.FontSizeBase, g.Style.FontSizeBase }; // <--- Will restore FontSize + SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0f); // <--- but use 0.0f to enable scale + g.FontStack.push_back(font_stack_data); IM_ASSERT(g.Font->IsLoaded()); } @@ -8633,6 +8652,15 @@ void ImGui::UpdateFontsEndFrame() PopFont(); } +ImFont* ImGui::GetDefaultFont() +{ + ImGuiContext& g = *GImGui; + ImFontAtlas* atlas = g.IO.Fonts; + if (atlas->Builder == NULL) + ImFontAtlasBuildMain(atlas); + return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0]; +} + void ImGui::RegisterUserTexture(ImTextureData* tex) { ImGuiContext& g = *GImGui; @@ -8673,12 +8701,12 @@ void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas) // the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem // because we have a concrete need and a test bed for multiple atlas textures. // FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ? -void ImGui::SetCurrentFont(ImFont* font, float font_size) +void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling) { ImGuiContext& g = *GImGui; g.Font = font; - g.FontSizeBeforeScaling = font_size; - UpdateCurrentFontSize(); + g.FontSizeBeforeScaling = font_size_before_scaling; + UpdateCurrentFontSize(font_size_after_scaling); if (font != NULL) { @@ -8693,20 +8721,27 @@ void ImGui::SetCurrentFont(ImFont* font, float font_size) } } -void ImGui::UpdateCurrentFontSize() +void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + + g.Style.FontSizeBase = g.FontSizeBeforeScaling; if (window != NULL && window->SkipItems) return; - float final_size = g.FontSizeBeforeScaling * g.IO.FontGlobalScale; + // Restoring is pretty much only used by PopFont()/PopFontSize() + float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; + if (final_size == 0.0f) + { + final_size = g.FontSizeBeforeScaling * g.IO.FontGlobalScale; #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - if (g.Font != NULL) - final_size *= g.Font->Scale; + if (g.Font != NULL) + final_size *= g.Font->Scale; #endif - if (window != NULL) - final_size *= window->FontWindowScale; + if (window != NULL) + final_size *= window->FontWindowScale; + } // Round font size // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. @@ -8731,12 +8766,16 @@ void ImGui::SetFontRasterizerDensity(float rasterizer_density) if (g.FontRasterizerDensity == rasterizer_density) return; g.FontRasterizerDensity = rasterizer_density; - UpdateCurrentFontSize(); + UpdateCurrentFontSize(0.0f); } +// If you want to scale an existing font size: +// - Use e.g. PushFontSize(style.FontSizeBase * factor) (= value before external scale factors applied). +// - Do NOT use PushFontSize(GetFontSize() * factor) (= value after external scale factors applied). void ImGui::PushFont(ImFont* font, float font_size) { ImGuiContext& g = *GImGui; + g.FontStack.push_back({ g.Font, g.FontSizeBeforeScaling, g.FontSize }); if (font == NULL) font = GetDefaultFont(); if (font_size <= 0.0f) @@ -8746,23 +8785,20 @@ void ImGui::PushFont(ImFont* font, float font_size) else font_size = g.FontSizeBeforeScaling; // Keep current font size } - g.FontStack.push_back({ font, font_size }); - SetCurrentFont(font, font_size); + SetCurrentFont(font, font_size, 0.0f); } void ImGui::PopFont() { ImGuiContext& g = *GImGui; - if (g.FontStack.Size <= 1 && g.WithinFrameScope) + if (g.FontStack.Size <= 0 && g.WithinFrameScope) { IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!"); return; } + ImFontStackData* font_stack_data = &g.FontStack.back(); + SetCurrentFont(font_stack_data->Font, font_stack_data->FontSizeBeforeScaling, font_stack_data->FontSizeAfterScaling); g.FontStack.pop_back(); - if (ImFontStackData* font_stack_data = (g.FontStack.Size > 0) ? &g.FontStack.back() : NULL) - SetCurrentFont(font_stack_data->Font, font_stack_data->FontSize); - else - SetCurrentFont(NULL, 0.0f); } void ImGui::PushFontSize(float font_size) @@ -15751,10 +15787,11 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) { ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; + ImGuiStyle& style = g.Style; Text("Read "); SameLine(0, 0); TextLinkOpenURL("https://www.dearimgui.com/faq/"); SameLine(0, 0); - Text(" for details on font loading."); + Text(" for details."); SeparatorText("Backend Support for Dynamic Fonts"); BeginDisabled(); @@ -15762,11 +15799,16 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) EndDisabled(); BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); - SetNextItemWidth(GetFontSize() * 5); - DragFloat("io.FontGlobalScale", &io.FontGlobalScale, 0.05f, 0.5f, 5.0f); - BulletText("This is scaling font only. General scaling will come later."); - BulletText("Load an actual font that's not the default for best result!"); - BulletText("Please submit feedback:"); SameLine(); TextLinkOpenURL("https://github.com/ocornut/imgui/issues/8465"); + SetNextItemWidth(GetFontSize() * 10); + if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) + style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. + SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); + SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later."); + SetNextItemWidth(GetFontSize() * 10); + DragFloat("io.FontGlobalScale", &io.FontGlobalScale, 0.05f, 0.5f, 5.0f); // <-- This works, but no need to make it too visible. + BulletText("Load a nice font for better results!"); + BulletText("Please submit feedback:"); + SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); EndDisabled(); SeparatorText("Fonts"); @@ -15786,7 +15828,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) #else BeginDisabled(); RadioButton("stb_truetype", false); - SetItemTooltip("Requires IMGUI_ENABLE_STB_TRUETYPE"); + SetItemTooltip("Requires #define IMGUI_ENABLE_STB_TRUETYPE"); EndDisabled(); #endif SameLine(); @@ -15810,7 +15852,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) #else BeginDisabled(); RadioButton("FreeType", false); - SetItemTooltip("Requires IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp."); + SetItemTooltip("Requires #define IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp."); EndDisabled(); #endif EndDisabled(); diff --git a/imgui.h b/imgui.h index 44aa078ae..d2bc7ce77 100644 --- a/imgui.h +++ b/imgui.h @@ -498,8 +498,13 @@ namespace ImGui // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. // - Before 1.92: PushFont() always used font default size. // - Since 1.92: PushFont() preserve the current shared font size. - // - To use old behavior (single size font): use 'PushFont(font, font->LegacySize)' in call site, or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' before calling AddFont(). - IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. Use font->LegacySize to revert to font size specified by AddFont(). + // - To use old behavior (single size font, size specified in AddFontXXX() call: + // - Use 'PushFont(font, font->LegacySize)' at call site + // - Or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' before calling AddFont(), and then 'PushFont(font)' will use this size. + // *IMPORTANT* If you want to scale an existing font size: + // - OK: PushFontSize(style.FontSizeBase * factor) (= value before external scale factors applied). + // - KO: PushFontSize(GetFontSize() * factor) (= value after external scale factors applied. external scale factors are io.FontGlobalScale and per-viewport scales.). + IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. IMGUI_API void PopFont(); IMGUI_API void PushFontSize(float font_size); IMGUI_API void PopFontSize(); @@ -2222,6 +2227,8 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE struct ImGuiStyle { + float FontSizeBase; // Current base font size (scaling applied). Use PushFont()/PushFontSize() to modify. Use ImGui::GetFontSize() to obtain scaled value. + float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. ImVec2 WindowPadding; // Padding within a window. @@ -2287,8 +2294,13 @@ struct ImGuiStyle ImGuiHoveredFlags HoverFlagsForTooltipMouse;// Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. ImGuiHoveredFlags HoverFlagsForTooltipNav; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. - IMGUI_API ImGuiStyle(); - IMGUI_API void ScaleAllSizes(float scale_factor); + // [Internal] + float _MainScale; // FIXME-WIP: Reference scale, as applied by ScaleAllSizes(). + float _NextFrameFontSizeBase; // FIXME: Temporary hack until we finish remaining work. + + // Functions + IMGUI_API ImGuiStyle(); + IMGUI_API void ScaleAllSizes(float scale_factor); // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_demo.cpp b/imgui_demo.cpp index dda817eb8..fc1d16953 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -430,16 +430,25 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); ImGui::Spacing(); - ImGui::SeparatorText("dynamic_fonts branch"); - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 5); - ImGui::DragFloat("io.FontGlobalScale", &ImGui::GetIO().FontGlobalScale, 0.05f, 0.5f, 5.0f); - ImGui::BulletText("This is scaling font only. General scaling will come later."); - ImGui::BulletText("Load an actual font that's not the default for best result!"); - ImGui::BulletText("See 'Widgets->Fonts' below for more.."); - ImGui::BulletText("Current font loader: '%s'", ImGui::GetIO().Fonts->FontLoaderName); - ImGui::BulletText("Please submit feedback:"); ImGui::SameLine(); - ImGui::TextLinkOpenURL("https://github.com/ocornut/imgui/issues/8465"); - ImGui::Spacing(); + { + ImGui::SeparatorText("dynamic_fonts branch"); + ImGuiStyle& style = ImGui::GetStyle(); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); + ImGui::ShowFontSelector("Font"); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); + if (ImGui::DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) + style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. + ImGui::SameLine(0.0f, 0.0f); Text(" (out %.2f)", ImGui::GetFontSize()); + ImGui::SameLine(); HelpMarker("- This is scaling font only. General scaling will come later."); + //ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); + //ImGui::DragFloat("FontGlobalScale", &ImGui::GetIO().FontGlobalScale, 0.05f, 0.5f, 5.0f); + ImGui::BulletText("Load a nice font for better results!"); + ImGui::BulletText("See 'Widgets->Fonts' below for more."); + //ImGui::BulletText("Current font loader: '%s'", ImGui::GetIO().Fonts->FontLoaderName); + ImGui::BulletText("Please submit feedback:"); ImGui::SameLine(); + ImGui::TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); + ImGui::Spacing(); + } IMGUI_DEMO_MARKER("Help"); if (ImGui::CollapsingHeader("Help")) @@ -8207,11 +8216,16 @@ void ImGui::ShowFontSelector(const char* label) ImGui::EndCombo(); } ImGui::SameLine(); - HelpMarker( - "- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n" - "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" - "- Read FAQ and docs/FONTS.md for more details.\n" - "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + HelpMarker( + "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" + "- Read FAQ and docs/FONTS.md for more details."); + else + HelpMarker( + "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" + "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" + "- Read FAQ and docs/FONTS.md for more details.\n" + "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); } // Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e067d57ba..69c207fd2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3190,7 +3190,7 @@ static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, bool need_bind_ctx = ctx != curr_ctx; if (need_bind_ctx) ImGui::SetCurrentContext(ctx); - ImGui::SetCurrentFont(new_font, ctx->FontSize); + ImGui::SetCurrentFont(new_font, ctx->FontSizeBeforeScaling, ctx->FontSize); if (need_bind_ctx) ImGui::SetCurrentContext(curr_ctx); } diff --git a/imgui_internal.h b/imgui_internal.h index 5dacf666e..4c1d1f392 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -871,7 +871,8 @@ struct ImDrawDataBuilder struct ImFontStackData { ImFont* Font; - float FontSize; + float FontSizeBeforeScaling; + float FontSizeAfterScaling; }; //----------------------------------------------------------------------------- @@ -3116,12 +3117,12 @@ namespace ImGui IMGUI_API void UnregisterUserTexture(ImTextureData* tex); IMGUI_API void RegisterFontAtlas(ImFontAtlas* atlas); IMGUI_API void UnregisterFontAtlas(ImFontAtlas* atlas); - IMGUI_API void SetCurrentFont(ImFont* font, float font_size); + IMGUI_API void SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling); + IMGUI_API void UpdateCurrentFontSize(float restore_font_size_after_scaling); IMGUI_API void SetFontRasterizerDensity(float rasterizer_density); inline float GetFontRasterizerDensity() { return GImGui->FontRasterizerDensity; } - IMGUI_API void UpdateCurrentFontSize(); inline float GetRoundedFontSize(float size) { return IM_ROUND(size); } - inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } + IMGUI_API ImFont* GetDefaultFont(); IMGUI_API void PushPasswordFont(); IMGUI_API void PopPasswordFont(); inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. From 402db2ef326735fe537f051980d569b668db4179 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Jun 2025 15:21:52 +0200 Subject: [PATCH 1054/2359] Fonts: fixed passing negative sizes to stb_truetype loader. --- imgui_draw.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 69c207fd2..e74477dc6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4530,10 +4530,10 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* } src->FontLoaderData = bd_font_data; - if (src->SizePixels > 0.0f) + if (src->SizePixels >= 0.0f) bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); else - bd_font_data->ScaleFactor = -stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); + bd_font_data->ScaleFactor = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); if (src != src->DstFont->Sources[0]) bd_font_data->ScaleFactor *= src->SizePixels / src->DstFont->Sources[0]->SizePixels; // FIXME-NEWATLAS: Should tidy up that a bit From 59a11363a52071b438043e35c0865f377b630d43 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 May 2025 23:13:34 +0200 Subject: [PATCH 1055/2359] Fonts: ground work for allowing SizePixels to be optional. --- imgui.cpp | 5 ++++- imgui.h | 4 ++-- imgui_draw.cpp | 11 ++++++++--- misc/freetype/imgui_freetype.cpp | 3 ++- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d18beab96..1ffa0652f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1204,6 +1204,9 @@ CODE #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction. #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window +// Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls. +static const float FONT_DEFAULT_SIZE = 20.0f; + // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear @@ -8635,7 +8638,7 @@ void ImGui::UpdateFontsNewFrame() // Apply default font size the first time ImFont* font = ImGui::GetDefaultFont(); if (g.Style.FontSizeBase <= 0.0f) - g.Style.FontSizeBase = font->LegacySize * g.Style._MainScale; + g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE) * g.Style._MainScale; // Set initial font g.Font = font; diff --git a/imgui.h b/imgui.h index d2bc7ce77..6e99b0be9 100644 --- a/imgui.h +++ b/imgui.h @@ -3475,10 +3475,10 @@ struct ImFontConfig ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs - float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. + float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. // FIXME-NEWATLAS: Intentionally unscaled unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. - float RasterizerDensity; // 1.0f // (Legacy: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported). DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. + float RasterizerDensity; // 1.0f // [LEGACY: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported] DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. // [Internal] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e74477dc6..6fabbac9e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2988,10 +2988,13 @@ bool ImFontAtlas::Build() ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) { + // Sanity Checks IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); IM_ASSERT((font_cfg_in->FontData != NULL && font_cfg_in->FontDataSize > 0) || (font_cfg_in->FontLoader != NULL)); - IM_ASSERT(font_cfg_in->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); + //IM_ASSERT(font_cfg_in->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); IM_ASSERT(font_cfg_in->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); + if (font_cfg_in->GlyphOffset.x != 0.0f || font_cfg_in->GlyphOffset.y != 0.0f || font_cfg_in->GlyphMinAdvanceX != 0.0f || font_cfg_in->GlyphMaxAdvanceX != FLT_MAX) + IM_ASSERT(font_cfg_in->SizePixels != 0.0f && "Specifying glyph offset/advances requires a reference size to base it on."); // Lazily create builder on the first call to AddFont if (Builder == NULL) @@ -4636,7 +4639,8 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC if (oversample_v > 1) stbtt__v_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_v); - const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0]->SizePixels; + const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; float font_off_x = (src->GlyphOffset.x * offsets_scale); float font_off_y = (src->GlyphOffset.y * offsets_scale); if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. @@ -5075,7 +5079,8 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked if (src != NULL) { // Clamp & recenter if needed - const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0]->SizePixels; + const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; float advance_x = ImClamp(glyph->AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); if (advance_x != glyph->AdvanceX) { diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index a0fc96926..4c10ff42d 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -527,7 +527,8 @@ bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data; ImGui_ImplFreeType_BlitGlyph(ft_bitmap, temp_buffer, w); - const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0]->SizePixels; + const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; float font_off_x = (src->GlyphOffset.x * offsets_scale); float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent; if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. From 80c08f228667c5921a1b11a26fda05673059481a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Jun 2025 14:58:30 +0200 Subject: [PATCH 1056/2359] (Breaking) Fonts: obsoleting SetWindowFontScale(). + Comments # Conflicts: # imgui.cpp --- imgui.cpp | 17 ++++++++++++----- imgui.h | 5 +++-- imgui_demo.cpp | 6 +++--- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1ffa0652f..b4a4478b4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8445,6 +8445,7 @@ ImFontBaked* ImGui::GetFontBaked() return GImGui->FontBaked; } +// Get current font size (= height in pixels) of current font, with external scale factors applied. Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. float ImGui::GetFontSize() { return GImGui->FontSize; @@ -8455,6 +8456,8 @@ ImVec2 ImGui::GetFontTexUvWhitePixel() return GImGui->DrawListSharedData.TexUvWhitePixel; } +// Prefer using PushFontSize(style.FontSize * factor), or use io.FontGlobalScale to scale all windows. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS void ImGui::SetWindowFontScale(float scale) { IM_ASSERT(scale > 0.0f); @@ -8462,6 +8465,7 @@ void ImGui::SetWindowFontScale(float scale) window->FontWindowScale = scale; UpdateCurrentFontSize(0.0f); } +#endif void ImGui::PushFocusScope(ImGuiID id) { @@ -8737,13 +8741,16 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; if (final_size == 0.0f) { - final_size = g.FontSizeBeforeScaling * g.IO.FontGlobalScale; -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - if (g.Font != NULL) - final_size *= g.Font->Scale; -#endif + final_size = g.FontSizeBeforeScaling; + + // External scale factors + final_size *= g.IO.FontGlobalScale; if (window != NULL) final_size *= window->FontWindowScale; +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (g.Font != NULL) + final_size *= g.Font->Scale; +#endif } // Round font size diff --git a/imgui.h b/imgui.h index 6e99b0be9..e5a61be75 100644 --- a/imgui.h +++ b/imgui.h @@ -474,7 +474,6 @@ 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 SetWindowFontScale(float scale); // [OBSOLETE] set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes(). 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 @@ -532,7 +531,7 @@ namespace ImGui // Style read access // - Use the ShowStyleEditor() function to interactively see/edit the colors. IMGUI_API ImFont* GetFont(); // get current font - IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with external scale factors applied. Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a white pixel, useful to draw custom shapes via the ImDrawList API IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList @@ -3943,6 +3942,8 @@ struct ImGuiPlatformImeData #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.92.0 (from June 2025) + IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFontSize(style.FontSize * factor) or use io.FontGlobalScale to scale all windows. // OBSOLETED in 1.91.9 (from February 2025) IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index fc1d16953..581a49eb0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8485,11 +8485,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, " "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" "Using those settings here will give you poor quality results."); - static float window_scale = 1.0f; PushItemWidth(GetFontSize() * 8); - if (DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window - SetWindowFontScale(window_scale); DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything + //static float window_scale = 1.0f; + //if (DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window + // SetWindowFontScale(window_scale); PopItemWidth(); EndTabItem(); From 8766efcba6a0c2e62afd5ec22260cd54dd82cc5c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Jun 2025 18:16:14 +0200 Subject: [PATCH 1057/2359] (Breaking) Renamed io.FontGlobalScale to style.FontScaleMain. # Conflicts: # imgui.cpp --- imgui.cpp | 33 +++++++++++++++++++-------------- imgui.h | 12 +++++++----- imgui_demo.cpp | 18 +++++++++++++----- imgui_internal.h | 2 +- 4 files changed, 40 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b4a4478b4..527aae3f4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1358,6 +1358,8 @@ static void* GImAllocatorUserData = NULL; ImGuiStyle::ImGuiStyle() { FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame. + FontScaleMain = 1.0f; // Main global scale factor. + Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui. DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. WindowPadding = ImVec2(8,8); // Padding within a window @@ -1481,9 +1483,11 @@ ImGuiIO::ImGuiIO() UserData = NULL; Fonts = NULL; - FontGlobalScale = 1.0f; FontDefault = NULL; FontAllowUserScaling = false; +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + FontGlobalScale = 1.0f; // Use style.FontScaleMain instead! +#endif DisplayFramebufferScale = ImVec2(1.0f, 1.0f); // Keyboard/Gamepad Navigation options @@ -8456,7 +8460,7 @@ ImVec2 ImGui::GetFontTexUvWhitePixel() return GImGui->DrawListSharedData.TexUvWhitePixel; } -// Prefer using PushFontSize(style.FontSize * factor), or use io.FontGlobalScale to scale all windows. +// Prefer using PushFontSize(style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS void ImGui::SetWindowFontScale(float scale) { @@ -8744,12 +8748,15 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) final_size = g.FontSizeBeforeScaling; // External scale factors - final_size *= g.IO.FontGlobalScale; + final_size *= g.Style.FontScaleMain; if (window != NULL) final_size *= window->FontWindowScale; + + // Legacy scale factors #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead! if (g.Font != NULL) - final_size *= g.Font->Scale; + final_size *= g.Font->Scale; // Was never really useful. #endif } @@ -10544,6 +10551,9 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL); #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!"); + // Remap legacy names if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) { @@ -15799,29 +15809,24 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) ImGuiIO& io = g.IO; ImGuiStyle& style = g.Style; - Text("Read "); SameLine(0, 0); - TextLinkOpenURL("https://www.dearimgui.com/faq/"); SameLine(0, 0); - Text(" for details."); - - SeparatorText("Backend Support for Dynamic Fonts"); BeginDisabled(); CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures); EndDisabled(); - + ShowFontSelector("Font"); BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); - SetNextItemWidth(GetFontSize() * 10); if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later."); - SetNextItemWidth(GetFontSize() * 10); - DragFloat("io.FontGlobalScale", &io.FontGlobalScale, 0.05f, 0.5f, 5.0f); // <-- This works, but no need to make it too visible. + DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 5.0f); BulletText("Load a nice font for better results!"); BulletText("Please submit feedback:"); SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); + BulletText("Read FAQ for more details:"); + SameLine(); TextLinkOpenURL("dearimgui.com/faq", "https://www.dearimgui.com/faq/"); EndDisabled(); - SeparatorText("Fonts"); + SeparatorText("Font List"); ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; Checkbox("Show font preview", &cfg->ShowFontPreview); diff --git a/imgui.h b/imgui.h index e5a61be75..8fa8c65e1 100644 --- a/imgui.h +++ b/imgui.h @@ -502,7 +502,7 @@ namespace ImGui // - Or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' before calling AddFont(), and then 'PushFont(font)' will use this size. // *IMPORTANT* If you want to scale an existing font size: // - OK: PushFontSize(style.FontSizeBase * factor) (= value before external scale factors applied). - // - KO: PushFontSize(GetFontSize() * factor) (= value after external scale factors applied. external scale factors are io.FontGlobalScale and per-viewport scales.). + // - KO: PushFontSize(GetFontSize() * factor) (= value after external scale factors applied. external scale factors are style.FontScaleMain + per-viewport scales.). IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. IMGUI_API void PopFont(); IMGUI_API void PushFontSize(float font_size); @@ -2227,6 +2227,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE struct ImGuiStyle { float FontSizeBase; // Current base font size (scaling applied). Use PushFont()/PushFontSize() to modify. Use ImGui::GetFontSize() to obtain scaled value. + float FontScaleMain; // Main global scale factor. Other scale factors may apply. float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. @@ -2347,9 +2348,8 @@ struct ImGuiIO // Font system ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. - float FontGlobalScale; // = 1.0f // Global scale all fonts - bool FontAllowUserScaling; // = false // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. + bool FontAllowUserScaling; // = false // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel. // Keyboard/Gamepad Navigation options bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. @@ -2546,9 +2546,11 @@ struct ImGuiIO //float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. //void* ImeWindowHandle; // [Obsoleted in 1.87] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + float FontGlobalScale; // Moved io.FontGlobalScale to style.FontScaleMain in 1.92 (June 2025) + // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS const char* (*GetClipboardTextFn)(void* user_data); void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; @@ -3943,7 +3945,7 @@ struct ImGuiPlatformImeData namespace ImGui { // OBSOLETED in 1.92.0 (from June 2025) - IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFontSize(style.FontSize * factor) or use io.FontGlobalScale to scale all windows. + IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFontSize(style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. // OBSOLETED in 1.91.9 (from February 2025) IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 581a49eb0..5aa9dc02b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -440,13 +440,13 @@ void ImGui::ShowDemoWindow(bool* p_open) style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. ImGui::SameLine(0.0f, 0.0f); Text(" (out %.2f)", ImGui::GetFontSize()); ImGui::SameLine(); HelpMarker("- This is scaling font only. General scaling will come later."); - //ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); - //ImGui::DragFloat("FontGlobalScale", &ImGui::GetIO().FontGlobalScale, 0.05f, 0.5f, 5.0f); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); + ImGui::DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); ImGui::BulletText("Load a nice font for better results!"); - ImGui::BulletText("See 'Widgets->Fonts' below for more."); //ImGui::BulletText("Current font loader: '%s'", ImGui::GetIO().Fonts->FontLoaderName); ImGui::BulletText("Please submit feedback:"); ImGui::SameLine(); ImGui::TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); + ImGui::BulletText("See 'Widgets->Fonts' below for more."); ImGui::Spacing(); } @@ -8276,9 +8276,16 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { // General + SeparatorText("General"); if (ShowStyleSelector("Colors##Selector")) ref_saved_style = style; ShowFontSelector("Fonts##Selector"); + BeginDisabled((GetIO().BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); + if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) + style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. + SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); + DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); + EndDisabled(); // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) if (SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) @@ -8301,8 +8308,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "Save/Revert in local non-persistent storage. Default Colors definition are not affected. " "Use \"Export\" below to save them somewhere."); - Separator(); - + SeparatorText("Details"); if (BeginTabBar("##tabs", ImGuiTabBarFlags_None)) { if (BeginTabItem("Sizes")) @@ -8477,6 +8483,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). + /* SeparatorText("Legacy Scaling"); const float MIN_SCALE = 0.3f; const float MAX_SCALE = 2.0f; @@ -8491,6 +8498,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) //if (DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window // SetWindowFontScale(window_scale); PopItemWidth(); + */ EndTabItem(); } diff --git a/imgui_internal.h b/imgui_internal.h index 4c1d1f392..f4db19273 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2139,7 +2139,7 @@ struct ImGuiContext ImVector FontAtlases; // List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) ImFont* Font; // Currently bound font. (== FontStack.back().Font) ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) - float FontSize; // Currently bound font size == line height (== FontSizeBeforeScaling * io.FontGlobalScale * font->Scale * g.CurrentWindow->FontWindowScale). + float FontSize; // Currently bound font size == line height (== FontSizeBeforeScaling + externals scales applied in the UpdateCurrentFontSize() function). float FontSizeBeforeScaling; // == value passed to PushFont() / PushFontSize() when specified. float FontScale; // == FontBaked->Size / Font->FontSize. Scale factor over baked size. float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). From d85e22d205d347695944532fe1fcc6c23cacdc11 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Jun 2025 16:44:42 +0200 Subject: [PATCH 1058/2359] Added style.FontScaleDpi which is the field overwritten by ImGuiConfigFlags_DpiEnableScaleFonts. # Conflicts: # imgui.cpp # imgui.h # imgui_demo.cpp --- imgui.cpp | 16 ++++++++++++---- imgui.h | 3 ++- imgui_demo.cpp | 4 ++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 527aae3f4..f6dd39c9d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1359,6 +1359,7 @@ ImGuiStyle::ImGuiStyle() { FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame. FontScaleMain = 1.0f; // Main global scale factor. + FontScaleDpi = 1.0f; // Scale factor from viewport/monitor. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui. DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. @@ -1429,12 +1430,12 @@ ImGuiStyle::ImGuiStyle() ImGui::StyleColorsDark(this); } -// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you. + +// Scale all spacing/padding/thickness values. Do not scale fonts. // Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. void ImGuiStyle::ScaleAllSizes(float scale_factor) { _MainScale *= scale_factor; - FontSizeBase = ImTrunc(FontSizeBase * scale_factor); WindowPadding = ImTrunc(WindowPadding * scale_factor); WindowRounding = ImTrunc(WindowRounding * scale_factor); WindowMinSize = ImTrunc(WindowMinSize * scale_factor); @@ -8646,7 +8647,7 @@ void ImGui::UpdateFontsNewFrame() // Apply default font size the first time ImFont* font = ImGui::GetDefaultFont(); if (g.Style.FontSizeBase <= 0.0f) - g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE) * g.Style._MainScale; + g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE); // Set initial font g.Font = font; @@ -8748,7 +8749,10 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) final_size = g.FontSizeBeforeScaling; // External scale factors - final_size *= g.Style.FontScaleMain; + final_size *= g.Style.FontScaleMain; // Main global scale factor + final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled. + + // Window scale (mostly obsolete now) if (window != NULL) final_size *= window->FontWindowScale; @@ -15819,6 +15823,10 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later."); DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 5.0f); + //BeginDisabled(io.ConfigDpiScaleFonts); + DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 5.0f); + //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); + //EndDisabled(); BulletText("Load a nice font for better results!"); BulletText("Please submit feedback:"); SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); diff --git a/imgui.h b/imgui.h index 8fa8c65e1..3b69ac1ff 100644 --- a/imgui.h +++ b/imgui.h @@ -2228,6 +2228,7 @@ struct ImGuiStyle { float FontSizeBase; // Current base font size (scaling applied). Use PushFont()/PushFontSize() to modify. Use ImGui::GetFontSize() to obtain scaled value. float FontScaleMain; // Main global scale factor. Other scale factors may apply. + float FontScaleDpi; // Scale factor from viewport/monitor. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor. float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. @@ -2300,7 +2301,7 @@ struct ImGuiStyle // Functions IMGUI_API ImGuiStyle(); - IMGUI_API void ScaleAllSizes(float scale_factor); + IMGUI_API void ScaleAllSizes(float scale_factor); // Scale all spacing/padding/thickness values. Do not scale fonts. // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5aa9dc02b..985a490ea 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8285,6 +8285,10 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); + //BeginDisabled(GetIO().ConfigDpiScaleFonts); + DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 5.0f); + //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); + //EndDisabled(); EndDisabled(); // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) From 3c27c643a9c79f2248aee53336c754749b8622e5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Jun 2025 14:40:37 +0200 Subject: [PATCH 1059/2359] Fonts: internals: renamed g.FontScale to g.FontBakedScale for clarity. Comments. --- imgui.cpp | 20 ++++++++++---------- imgui.h | 11 ++++++----- imgui_internal.h | 8 ++++---- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 4 ++-- 5 files changed, 23 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f6dd39c9d..3fb75eb25 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3979,7 +3979,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) Initialized = false; Font = NULL; FontBaked = NULL; - FontSize = FontSizeBeforeScaling = FontScale = CurrentDpiScale = 0.0f; + FontSize = FontSizeBeforeScaling = FontBakedScale = CurrentDpiScale = 0.0f; FontRasterizerDensity = 1.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); if (shared_font_atlas == NULL) @@ -8773,9 +8773,9 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity; g.FontSize = final_size; g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL; - g.FontScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; + g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; g.DrawListSharedData.FontSize = g.FontSize; - g.DrawListSharedData.FontScale = g.FontScale; + g.DrawListSharedData.FontScale = g.FontBakedScale; } // Exposed in case user may want to override setting density. @@ -8793,20 +8793,20 @@ void ImGui::SetFontRasterizerDensity(float rasterizer_density) // If you want to scale an existing font size: // - Use e.g. PushFontSize(style.FontSizeBase * factor) (= value before external scale factors applied). // - Do NOT use PushFontSize(GetFontSize() * factor) (= value after external scale factors applied). -void ImGui::PushFont(ImFont* font, float font_size) +void ImGui::PushFont(ImFont* font, float font_size_base) { ImGuiContext& g = *GImGui; g.FontStack.push_back({ g.Font, g.FontSizeBeforeScaling, g.FontSize }); if (font == NULL) font = GetDefaultFont(); - if (font_size <= 0.0f) + if (font_size_base <= 0.0f) { if (font->Flags & ImFontFlags_DefaultToLegacySize) - font_size = font->LegacySize; // Legacy: use AddFont() specified font size. Same as doing PushFont(font, font->LegacySize) + font_size_base = font->LegacySize; // Legacy: use AddFont() specified font size. Same as doing PushFont(font, font->LegacySize) else - font_size = g.FontSizeBeforeScaling; // Keep current font size + font_size_base = g.FontSizeBeforeScaling; // Keep current font size } - SetCurrentFont(font, font_size, 0.0f); + SetCurrentFont(font, font_size_base, 0.0f); } void ImGui::PopFont() @@ -8822,10 +8822,10 @@ void ImGui::PopFont() g.FontStack.pop_back(); } -void ImGui::PushFontSize(float font_size) +void ImGui::PushFontSize(float font_size_base) { ImGuiContext& g = *GImGui; - PushFont(g.Font, font_size); + PushFont(g.Font, font_size_base); } void ImGui::PopFontSize() diff --git a/imgui.h b/imgui.h index 3b69ac1ff..563d2eb92 100644 --- a/imgui.h +++ b/imgui.h @@ -500,12 +500,13 @@ namespace ImGui // - To use old behavior (single size font, size specified in AddFontXXX() call: // - Use 'PushFont(font, font->LegacySize)' at call site // - Or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' before calling AddFont(), and then 'PushFont(font)' will use this size. + // - External scale factors are applied over the provided value. // *IMPORTANT* If you want to scale an existing font size: // - OK: PushFontSize(style.FontSizeBase * factor) (= value before external scale factors applied). // - KO: PushFontSize(GetFontSize() * factor) (= value after external scale factors applied. external scale factors are style.FontScaleMain + per-viewport scales.). - IMGUI_API void PushFont(ImFont* font, float font_size = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. + IMGUI_API void PushFont(ImFont* font, float font_size_base = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. IMGUI_API void PopFont(); - IMGUI_API void PushFontSize(float font_size); + IMGUI_API void PushFontSize(float font_size_base); IMGUI_API void PopFontSize(); // Parameters stacks (shared) @@ -2226,9 +2227,9 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE struct ImGuiStyle { - float FontSizeBase; // Current base font size (scaling applied). Use PushFont()/PushFontSize() to modify. Use ImGui::GetFontSize() to obtain scaled value. - float FontScaleMain; // Main global scale factor. Other scale factors may apply. - float FontScaleDpi; // Scale factor from viewport/monitor. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor. + float FontSizeBase; // Current base font size before external scaling factors are applied. Use PushFont()/PushFontSize() to modify. Use ImGui::GetFontSize() to obtain scaled value. Final FontSize = FontSizeBase * (FontScaleBase * FontScaleDpi * other_factors) + float FontScaleMain; // Main scale factor. May be set by application once, or exposed to end-user. + float FontScaleDpi; // Scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor. float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. diff --git a/imgui_internal.h b/imgui_internal.h index f4db19273..db308bc7a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -871,8 +871,8 @@ struct ImDrawDataBuilder struct ImFontStackData { ImFont* Font; - float FontSizeBeforeScaling; - float FontSizeAfterScaling; + float FontSizeBeforeScaling; // ~~ style.FontSizeBase + float FontSizeAfterScaling; // ~~ g.FontSize }; //----------------------------------------------------------------------------- @@ -2140,8 +2140,8 @@ struct ImGuiContext ImFont* Font; // Currently bound font. (== FontStack.back().Font) ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) float FontSize; // Currently bound font size == line height (== FontSizeBeforeScaling + externals scales applied in the UpdateCurrentFontSize() function). - float FontSizeBeforeScaling; // == value passed to PushFont() / PushFontSize() when specified. - float FontScale; // == FontBaked->Size / Font->FontSize. Scale factor over baked size. + float FontSizeBeforeScaling; // Font size before scaling == style.FontSizeBase == value passed to PushFont() / PushFontSize() when specified. + float FontBakedScale; // == FontBaked->Size / FontSize. Scale factor over baked size. Rarely used nowadays, very often == 1.0f. float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale ImDrawListSharedData DrawListSharedData; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e41041ce1..61bc576ca 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3375,7 +3375,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label ButtonBehavior(row_r, row_id, NULL, NULL); KeepAliveID(row_id); - const float ascent_scaled = g.FontBaked->Ascent * g.FontScale; // FIXME: Standardize those scaling factors better + const float ascent_scaled = g.FontBaked->Ascent * g.FontBakedScale; // FIXME: Standardize those scaling factors better const float line_off_for_ascent_x = (ImMax((g.FontSize - ascent_scaled) * 0.5f, 0.0f) / -sin_a) * (flip_label ? -1.0f : 1.0f); const ImVec2 padding = g.Style.CellPadding; // We will always use swapped component const ImVec2 align = g.Style.TableAngledHeadersTextAlign; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 91d50933f..cdca228c4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1518,7 +1518,7 @@ bool ImGui::TextLink(const char* label) ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z); } - float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontScale * 0.20f); + float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f); window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode // FIXME-DPI PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); @@ -4012,7 +4012,7 @@ namespace ImStb { static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; } static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx <= obj->TextLen); return obj->TextSrc[idx]; } -static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.FontBaked->GetCharAdvance((ImWchar)c) * g.FontScale; } +static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.FontBaked->GetCharAdvance((ImWchar)c) * g.FontBakedScale; } static char STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx) { From 2d2b1cee6b7c1e741375b09ddcda8a2d68602655 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Jun 2025 14:54:46 +0200 Subject: [PATCH 1060/2359] Fonts: internals: renamed g.FontSizeBeforeScaling to g.FontSizeBase for consistency. # Conflicts: # imgui_internal.h --- imgui.cpp | 18 +++++++++--------- imgui.h | 5 +++-- imgui_draw.cpp | 2 +- imgui_internal.h | 6 +++--- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3fb75eb25..39a79a398 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1358,8 +1358,8 @@ static void* GImAllocatorUserData = NULL; ImGuiStyle::ImGuiStyle() { FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame. - FontScaleMain = 1.0f; // Main global scale factor. - FontScaleDpi = 1.0f; // Scale factor from viewport/monitor. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. + FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user. + FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui. DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. @@ -3979,7 +3979,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) Initialized = false; Font = NULL; FontBaked = NULL; - FontSize = FontSizeBeforeScaling = FontBakedScale = CurrentDpiScale = 0.0f; + FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f; FontRasterizerDensity = 1.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); if (shared_font_atlas == NULL) @@ -8651,7 +8651,7 @@ void ImGui::UpdateFontsNewFrame() // Set initial font g.Font = font; - g.FontSizeBeforeScaling = g.Style.FontSizeBase; + g.FontSizeBase = g.Style.FontSizeBase; g.FontSize = 0.0f; ImFontStackData font_stack_data = { font, g.Style.FontSizeBase, g.Style.FontSizeBase }; // <--- Will restore FontSize SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0f); // <--- but use 0.0f to enable scale @@ -8717,7 +8717,7 @@ void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float f { ImGuiContext& g = *GImGui; g.Font = font; - g.FontSizeBeforeScaling = font_size_before_scaling; + g.FontSizeBase = font_size_before_scaling; UpdateCurrentFontSize(font_size_after_scaling); if (font != NULL) @@ -8738,7 +8738,7 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - g.Style.FontSizeBase = g.FontSizeBeforeScaling; + g.Style.FontSizeBase = g.FontSizeBase; if (window != NULL && window->SkipItems) return; @@ -8746,7 +8746,7 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; if (final_size == 0.0f) { - final_size = g.FontSizeBeforeScaling; + final_size = g.FontSizeBase; // External scale factors final_size *= g.Style.FontScaleMain; // Main global scale factor @@ -8796,7 +8796,7 @@ void ImGui::SetFontRasterizerDensity(float rasterizer_density) void ImGui::PushFont(ImFont* font, float font_size_base) { ImGuiContext& g = *GImGui; - g.FontStack.push_back({ g.Font, g.FontSizeBeforeScaling, g.FontSize }); + g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize }); if (font == NULL) font = GetDefaultFont(); if (font_size_base <= 0.0f) @@ -8804,7 +8804,7 @@ void ImGui::PushFont(ImFont* font, float font_size_base) if (font->Flags & ImFontFlags_DefaultToLegacySize) font_size_base = font->LegacySize; // Legacy: use AddFont() specified font size. Same as doing PushFont(font, font->LegacySize) else - font_size_base = g.FontSizeBeforeScaling; // Keep current font size + font_size_base = g.FontSizeBase; // Keep current font size } SetCurrentFont(font, font_size_base, 0.0f); } diff --git a/imgui.h b/imgui.h index 563d2eb92..cdcdae68b 100644 --- a/imgui.h +++ b/imgui.h @@ -2227,9 +2227,10 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE struct ImGuiStyle { - float FontSizeBase; // Current base font size before external scaling factors are applied. Use PushFont()/PushFontSize() to modify. Use ImGui::GetFontSize() to obtain scaled value. Final FontSize = FontSizeBase * (FontScaleBase * FontScaleDpi * other_factors) + // ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors) + float FontSizeBase; // Current base font size before external scaling factors are applied. Use PushFont()/PushFontSize() to modify. Use ImGui::GetFontSize() to obtain scaled value. float FontScaleMain; // Main scale factor. May be set by application once, or exposed to end-user. - float FontScaleDpi; // Scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor. + float FontScaleDpi; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6fabbac9e..c4f342e54 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3193,7 +3193,7 @@ static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, bool need_bind_ctx = ctx != curr_ctx; if (need_bind_ctx) ImGui::SetCurrentContext(ctx); - ImGui::SetCurrentFont(new_font, ctx->FontSizeBeforeScaling, ctx->FontSize); + ImGui::SetCurrentFont(new_font, ctx->FontSizeBase, ctx->FontSize); if (need_bind_ctx) ImGui::SetCurrentContext(curr_ctx); } diff --git a/imgui_internal.h b/imgui_internal.h index db308bc7a..e344cbccf 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2139,8 +2139,8 @@ struct ImGuiContext ImVector FontAtlases; // List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) ImFont* Font; // Currently bound font. (== FontStack.back().Font) ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) - float FontSize; // Currently bound font size == line height (== FontSizeBeforeScaling + externals scales applied in the UpdateCurrentFontSize() function). - float FontSizeBeforeScaling; // Font size before scaling == style.FontSizeBase == value passed to PushFont() / PushFontSize() when specified. + float FontSize; // Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function). + float FontSizeBase; // Font size before scaling == style.FontSizeBase == value passed to PushFont() / PushFontSize() when specified. float FontBakedScale; // == FontBaked->Size / FontSize. Scale factor over baked size. Rarely used nowadays, very often == 1.0f. float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale @@ -2690,7 +2690,7 @@ public: ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } // [Obsolete] ImGuiWindow::CalcFontSize() was removed in 1.92.x because error-prone/misleading. You can use window->FontRefSize for a copy of g.FontSize at the time of the last Begin() call for this window. - //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontBaseSize * FontWindowScale * FontWindowScaleParents; } + //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontSizeBase * FontWindowScale * FontWindowScaleParents; }; //----------------------------------------------------------------------------- From d72e66cdee550cfa9735e8199dceac2a7ac27ab5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Jun 2025 16:47:58 +0200 Subject: [PATCH 1061/2359] Examples: remove comments/references about baking and GetGlyphRangesJapanese(). --- examples/example_allegro5/main.cpp | 3 +-- examples/example_android_opengl3/main.cpp | 3 +-- examples/example_apple_metal/main.mm | 3 +-- examples/example_apple_opengl2/main.mm | 3 +-- examples/example_glfw_metal/main.mm | 3 +-- examples/example_glfw_opengl2/main.cpp | 3 +-- examples/example_glfw_opengl3/main.cpp | 3 +-- examples/example_glfw_vulkan/main.cpp | 3 +-- examples/example_glfw_wgpu/main.cpp | 3 +-- examples/example_glut_opengl2/main.cpp | 3 +-- examples/example_sdl2_directx11/main.cpp | 3 +-- examples/example_sdl2_metal/main.mm | 3 +-- examples/example_sdl2_opengl2/main.cpp | 3 +-- examples/example_sdl2_opengl3/main.cpp | 3 +-- examples/example_sdl2_sdlrenderer2/main.cpp | 3 +-- examples/example_sdl2_vulkan/main.cpp | 3 +-- examples/example_sdl3_opengl3/main.cpp | 3 +-- examples/example_sdl3_sdlgpu3/main.cpp | 3 +-- examples/example_sdl3_sdlrenderer3/main.cpp | 3 +-- examples/example_sdl3_vulkan/main.cpp | 3 +-- examples/example_win32_directx10/main.cpp | 3 +-- examples/example_win32_directx11/main.cpp | 3 +-- examples/example_win32_directx12/main.cpp | 3 +-- examples/example_win32_directx9/main.cpp | 3 +-- examples/example_win32_opengl3/main.cpp | 3 +-- examples/example_win32_vulkan/main.cpp | 3 +-- 26 files changed, 26 insertions(+), 52 deletions(-) diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 3ca061cc6..67fc7ee65 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -52,7 +52,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -61,7 +60,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); bool show_demo_window = true; diff --git a/examples/example_android_opengl3/main.cpp b/examples/example_android_opengl3/main.cpp index 42aa622f7..452cb77d9 100644 --- a/examples/example_android_opengl3/main.cpp +++ b/examples/example_android_opengl3/main.cpp @@ -154,7 +154,6 @@ void Init(struct android_app* app) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them. @@ -181,7 +180,7 @@ void Init(struct android_app* app) //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 15.0f); //IM_ASSERT(font != nullptr); //font_data_size = GetAssetData("ArialUni.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 18.0f); //IM_ASSERT(font != nullptr); // Arbitrary scale-up diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 3ad7cff46..9b9db8c61 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -72,7 +72,6 @@ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -81,7 +80,7 @@ //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); return self; diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 815c0f72e..5f1fd1e50 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -60,7 +60,6 @@ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -69,7 +68,7 @@ //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); } diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index e9bc63acb..c4380d5c3 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -42,7 +42,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -51,7 +50,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Setup window diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 1fcec2b2a..af4edbe2b 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -65,7 +65,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -74,7 +73,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index e5f29d405..e133376bc 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -99,7 +99,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -109,7 +108,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 3d2181e89..10b9ab2ed 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -417,7 +417,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -426,7 +425,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index f510987ed..58c5b34f7 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -114,7 +114,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -126,7 +125,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); #endif diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 58539ca5f..5720f8558 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -83,7 +83,6 @@ int main(int argc, char** argv) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -92,7 +91,7 @@ int main(int argc, char** argv) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Main loop diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index 47c852d27..fdb7ad458 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -84,7 +84,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -93,7 +92,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index d54812710..4dc4788a8 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -33,7 +33,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -42,7 +41,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Setup SDL diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index a70edd225..feba216f0 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -70,7 +70,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -79,7 +78,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index 51add5c1f..7b7b17ad2 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -110,7 +110,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -120,7 +119,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 31fa3f9bf..eee25c272 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -72,7 +72,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -81,7 +80,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index c62222577..6a8f68e8b 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -417,7 +417,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -426,7 +425,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 46eeb59b5..ef2573324 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -106,7 +106,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -116,7 +115,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 4178f94b5..4051edc3d 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -83,7 +83,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -92,7 +91,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 9a2732b45..2821f7b80 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -68,7 +68,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -78,7 +77,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 183965a84..bdaf3aa02 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -422,7 +422,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -431,7 +430,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 21198da9a..d6b23e63f 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -67,7 +67,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -76,7 +75,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 5285df102..838e5493b 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -67,7 +67,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -76,7 +75,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 2df2751c5..ce672f353 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -161,7 +161,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -170,7 +169,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 422248bcb..d13351b0a 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -65,7 +65,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -74,7 +73,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 8ecd27a20..b516de7a7 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -75,7 +75,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -84,7 +83,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 427a2494a..8699b61a9 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -408,7 +408,6 @@ int main(int, char**) // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -417,7 +416,7 @@ int main(int, char**) //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); //IM_ASSERT(font != nullptr); // Our state From 9da3e6696abce7f294d0d4f3bfb1db6ce80c6265 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 6 Jun 2025 15:54:25 +0200 Subject: [PATCH 1062/2359] Backends: SDL2: added ImGui_ImplSDL2_GetDpiScaleForDisplay(), ImGui_ImplSDL2_GetContentScaleForWindow() helpers. --- backends/imgui_impl_sdl2.cpp | 21 +++++++++++++++++++++ backends/imgui_impl_sdl2.h | 4 ++++ 2 files changed, 25 insertions(+) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index fa2714bb9..3780b322b 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: Added ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) and ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) helper to facilitate making DPI-aware apps. // 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) @@ -702,6 +703,26 @@ static void ImGui_ImplSDL2_UpdateMouseCursor() } } +// - On Windows the process needs to be marked DPI-aware!! SDL2 doesn't do it by default. You can call ::SetProcessDPIAware() or call ImGui_ImplWin32_EnableDpiAwareness() from Win32 backend. +// - Apple platforms use FramebufferScale so we always return 1.0f. +// - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle. +float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) +{ + return ImGui_ImplSDL2_GetContentScaleForDisplay(SDL_GetWindowDisplayIndex(window)); +} + +float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) +{ +#if SDL_HAS_PER_MONITOR_DPI +#ifndef __APPLE__ + float dpi = 0.0f; + if (SDL_GetDisplayDPI(display_index, &dpi, nullptr, nullptr) == 0) + return dpi / 96.0f; +#endif +#endif + return 1.0f; +} + static void ImGui_ImplSDL2_CloseGamepads() { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); diff --git a/backends/imgui_impl_sdl2.h b/backends/imgui_impl_sdl2.h index 9f7b551fc..3c0a4a7e4 100644 --- a/backends/imgui_impl_sdl2.h +++ b/backends/imgui_impl_sdl2.h @@ -38,6 +38,10 @@ IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(); IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); +// DPI-related helpers (optional) +IMGUI_IMPL_API float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window); +IMGUI_IMPL_API float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index); + // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. // When using manual mode, caller is responsible for opening/closing gamepad. enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual }; From 8269924c33f3af562a83a5eada77b924bab5d7b1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 6 Jun 2025 16:14:22 +0200 Subject: [PATCH 1063/2359] Backends: GLFW: added ImGui_ImplGlfw_GetContentScaleForMonitor(), ImGui_ImplGlfw_GetContentScaleForWindow() helpers. # Conflicts: # backends/imgui_impl_glfw.cpp --- backends/imgui_impl_glfw.cpp | 28 ++++++++++++++++++++++++++++ backends/imgui_impl_glfw.h | 3 +++ 2 files changed, 31 insertions(+) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index ba7569970..70369f38b 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -28,6 +28,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-11: Added ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) and ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) helper to facilitate making DPI-aware apps. // 2025-03-10: Map GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 into ImGuiKey_Oem102. // 2025-03-03: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. // 2024-08-22: Moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: @@ -840,6 +841,33 @@ static void ImGui_ImplGlfw_UpdateGamepads() #undef MAP_ANALOG } +// - On Windows the process needs to be marked DPI-aware!! SDL2 doesn't do it by default. You can call ::SetProcessDPIAware() or call ImGui_ImplWin32_EnableDpiAwareness() from Win32 backend. +// - Apple platforms use FramebufferScale so we always return 1.0f. +// - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle. +float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) +{ +#if GLFW_HAS_PER_MONITOR_DPI && !defined(__APPLE__) + float x_scale, y_scale; + glfwGetWindowContentScale(window, &x_scale, &y_scale); + return x_scale; +#else + IM_UNUSED(window); + return 1.0f; +#endif +} + +float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) +{ +#if GLFW_HAS_PER_MONITOR_DPI && !defined(__APPLE__) + float x_scale, y_scale; + glfwGetMonitorContentScale(monitor, &x_scale, &y_scale); + return x_scale; +#else + IM_UNUSED(monitor); + return 1.0f; +#endif +} + void ImGui_ImplGlfw_NewFrame() { ImGuiIO& io = ImGui::GetIO(); diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index e203b556f..1ef9ade17 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -62,5 +62,8 @@ IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int // GLFW helpers IMGUI_IMPL_API void ImGui_ImplGlfw_Sleep(int milliseconds); +IMGUI_IMPL_API float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window); +IMGUI_IMPL_API float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor); + #endif // #ifndef IMGUI_DISABLE From b98e92839c997fcab03f2be4453f42afb8676888 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 16:17:54 +0200 Subject: [PATCH 1064/2359] Backends: SDL2, SDL3, GLFW: Backport small part of c90ea13 from docking. --- backends/imgui_impl_glfw.cpp | 22 ++++++++++++------- backends/imgui_impl_sdl2.cpp | 41 +++++++++++++++++++++--------------- backends/imgui_impl_sdl3.cpp | 26 ++++++++++++++--------- 3 files changed, 54 insertions(+), 35 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 70369f38b..aac9eca2e 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -868,20 +868,26 @@ float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) #endif } +static void ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(GLFWwindow* window, ImVec2* out_size, ImVec2* out_framebuffer_scale) +{ + int w, h; + int display_w, display_h; + glfwGetWindowSize(window, &w, &h); + glfwGetFramebufferSize(window, &display_w, &display_h); + if (out_size != nullptr) + *out_size = ImVec2((float)w, (float)h); + if (out_framebuffer_scale != nullptr) + *out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / (float)w, (float)display_h / (float)h) : ImVec2(1.0f, 1.0f); +} + void ImGui_ImplGlfw_NewFrame() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?"); - // Setup display size (every frame to accommodate for window resizing) - int w, h; - int display_w, display_h; - glfwGetWindowSize(bd->Window, &w, &h); - glfwGetFramebufferSize(bd->Window, &display_w, &display_h); - io.DisplaySize = ImVec2((float)w, (float)h); - if (w > 0 && h > 0) - io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h); + // Setup main viewport size (every frame to accommodate for window resizing) + ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(bd->Window, &io.DisplaySize, &io.DisplayFramebufferScale); // Setup time step // (Accept glfwGetTime() not returning a monotonically increasing value. Seems to happens on disconnecting peripherals and probably on VMs and Emscripten, see #6491, #6189, #6114, #3644) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 3780b322b..84ecc55e0 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -720,6 +720,7 @@ float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) return dpi / 96.0f; #endif #endif + IM_UNUSED(display_index); return 1.0f; } @@ -825,29 +826,35 @@ static void ImGui_ImplSDL2_UpdateGamepads() ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767); } +static void ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(SDL_Window* window, SDL_Renderer* renderer, ImVec2* out_size, ImVec2* out_framebuffer_scale) +{ + int w, h; + int display_w, display_h; + SDL_GetWindowSize(window, &w, &h); + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + w = h = 0; + if (renderer != nullptr) + SDL_GetRendererOutputSize(renderer, &display_w, &display_h); +#if SDL_HAS_VULKAN + else if (SDL_GetWindowFlags(window) & SDL_WINDOW_VULKAN) + SDL_Vulkan_GetDrawableSize(window, &display_w, &display_h); +#endif + else + SDL_GL_GetDrawableSize(window, &display_w, &display_h); + if (out_size != nullptr) + *out_size = ImVec2((float)w, (float)h); + if (out_framebuffer_scale != nullptr) + *out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / w, (float)display_h / h) : ImVec2(1.0f, 1.0f); +} + void ImGui_ImplSDL2_NewFrame() { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?"); ImGuiIO& io = ImGui::GetIO(); - // Setup display size (every frame to accommodate for window resizing) - int w, h; - int display_w, display_h; - SDL_GetWindowSize(bd->Window, &w, &h); - if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED) - w = h = 0; - if (bd->Renderer != nullptr) - SDL_GetRendererOutputSize(bd->Renderer, &display_w, &display_h); -#if SDL_HAS_VULKAN - else if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_VULKAN) - SDL_Vulkan_GetDrawableSize(bd->Window, &display_w, &display_h); -#endif - else - SDL_GL_GetDrawableSize(bd->Window, &display_w, &display_h); - io.DisplaySize = ImVec2((float)w, (float)h); - if (w > 0 && h > 0) - io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); + // Setup main viewport size (every frame to accommodate for window resizing) + ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(bd->Window, bd->Renderer, &io.DisplaySize, &io.DisplayFramebufferScale); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 58cc11c44..4f099595a 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -771,22 +771,28 @@ static void ImGui_ImplSDL3_UpdateGamepads() ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767); } +static void ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(SDL_Window* window, ImVec2* out_size, ImVec2* out_framebuffer_scale) +{ + int w, h; + int display_w, display_h; + SDL_GetWindowSize(window, &w, &h); + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + w = h = 0; + SDL_GetWindowSizeInPixels(window, &display_w, &display_h); + if (out_size != nullptr) + *out_size = ImVec2((float)w, (float)h); + if (out_framebuffer_scale != nullptr) + *out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / w, (float)display_h / h) : ImVec2(1.0f, 1.0f); +} + void ImGui_ImplSDL3_NewFrame() { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?"); ImGuiIO& io = ImGui::GetIO(); - // Setup display size (every frame to accommodate for window resizing) - int w, h; - int display_w, display_h; - SDL_GetWindowSize(bd->Window, &w, &h); - if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED) - w = h = 0; - SDL_GetWindowSizeInPixels(bd->Window, &display_w, &display_h); - io.DisplaySize = ImVec2((float)w, (float)h); - if (w > 0 && h > 0) - io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); + // Setup main viewport size (every frame to accommodate for window resizing) + ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(bd->Window, &io.DisplaySize, &io.DisplayFramebufferScale); // Setup time step (we could also use SDL_GetTicksNS() available since SDL3) // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) From bc394410a2ad10bc36575eeaff1ec3918ddee830 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Jun 2025 15:32:54 +0200 Subject: [PATCH 1065/2359] Examples: Win32+DX9/DX10/DX11/DX12, SDL2+DX11/OpenGL2/OpenGL3/SDLRenderer/Vulkan, SDL3+OpenGL/SDLGPU/SDLRenderer/Vulkan: made example DPI aware by default. (master + docking: partial support for multi-dpi by scaling fonts + viewports but not style) We don't bother with WIN32_LEAN_AND_MEAN. # Conflicts: # examples/example_glfw_opengl3/main.cpp # examples/example_sdl2_directx11/main.cpp # examples/example_sdl2_opengl2/main.cpp # examples/example_sdl2_opengl3/main.cpp # examples/example_sdl2_vulkan/main.cpp # examples/example_sdl3_opengl3/main.cpp # examples/example_sdl3_sdlgpu3/main.cpp # examples/example_sdl3_vulkan/main.cpp # examples/example_win32_directx10/main.cpp # examples/example_win32_directx11/main.cpp # examples/example_win32_directx12/main.cpp # examples/example_win32_directx9/main.cpp --- examples/example_glfw_opengl3/main.cpp | 8 +++++++- examples/example_sdl2_directx11/main.cpp | 11 ++++++++++- examples/example_sdl2_opengl2/main.cpp | 14 +++++++++++++- examples/example_sdl2_opengl3/main.cpp | 14 +++++++++++++- examples/example_sdl2_sdlrenderer2/main.cpp | 14 +++++++++++++- examples/example_sdl2_vulkan/main.cpp | 14 +++++++++++++- examples/example_sdl3_opengl3/main.cpp | 8 +++++++- examples/example_sdl3_sdlgpu3/main.cpp | 8 +++++++- examples/example_sdl3_sdlrenderer3/main.cpp | 8 +++++++- examples/example_sdl3_vulkan/main.cpp | 8 +++++++- examples/example_win32_directx10/main.cpp | 12 ++++++++++-- examples/example_win32_directx11/main.cpp | 12 ++++++++++-- examples/example_win32_directx12/main.cpp | 12 ++++++++++-- examples/example_win32_directx9/main.cpp | 12 ++++++++++-- 14 files changed, 137 insertions(+), 18 deletions(-) diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index e133376bc..53dc69ce2 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -71,7 +71,8 @@ int main(int, char**) #endif // Create window with graphics context - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL3 example", nullptr, nullptr); + float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); // Valid on GLFW 3.3+ only + GLFWwindow* window = glfwCreateWindow((int)(1280 * main_scale), (int)(800 * main_scale), "Dear ImGui GLFW+OpenGL3 example", nullptr, nullptr); if (window == nullptr) return 1; glfwMakeContextCurrent(window); @@ -88,6 +89,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); #ifdef __EMSCRIPTEN__ diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index fdb7ad458..d2e151e54 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -33,6 +33,9 @@ int main(int, char**) // Setup SDL // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems, // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to the latest version of SDL is recommended!) +#ifdef _WIN32 + ::SetProcessDPIAware(); +#endif if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); @@ -45,8 +48,9 @@ int main(int, char**) #endif // Setup window + float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -76,6 +80,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForD3D(window); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index feba216f0..1fe0c5864 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -17,11 +17,17 @@ #include #include #include +#ifdef _WIN32 +#include // SetProcessDPIAware() +#endif // Main code int main(int, char**) { // Setup SDL +#ifdef _WIN32 + ::SetProcessDPIAware(); +#endif if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); @@ -39,8 +45,9 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); + float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -62,6 +69,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(window, gl_context); ImGui_ImplOpenGL2_Init(); diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index 7b7b17ad2..63934cd88 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -17,6 +17,9 @@ #else #include #endif +#ifdef _WIN32 +#include // SetProcessDPIAware() +#endif // This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. #ifdef __EMSCRIPTEN__ @@ -27,6 +30,9 @@ int main(int, char**) { // Setup SDL +#ifdef _WIN32 + ::SetProcessDPIAware(); +#endif if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); @@ -73,8 +79,9 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); + float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -102,6 +109,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(window, gl_context); ImGui_ImplOpenGL3_Init(glsl_version); diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index eee25c272..564729bad 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -15,6 +15,9 @@ #include "imgui_impl_sdlrenderer2.h" #include #include +#ifdef _WIN32 +#include // SetProcessDPIAware() +#endif #if !SDL_VERSION_ATLEAST(2,0,17) #error This backend requires SDL 2.0.17+ because of SDL_RenderGeometry() function @@ -24,6 +27,9 @@ int main(int, char**) { // Setup SDL +#ifdef _WIN32 + ::SetProcessDPIAware(); +#endif if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); @@ -36,8 +42,9 @@ int main(int, char**) #endif // Create window with SDL_Renderer graphics context + float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+SDL_Renderer example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+SDL_Renderer example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -64,6 +71,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForSDLRenderer(window, renderer); ImGui_ImplSDLRenderer2_Init(renderer); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 6a8f68e8b..807751b01 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -20,6 +20,9 @@ #include // abort #include #include +#ifdef _WIN32 +#include // SetProcessDPIAware() +#endif // Volk headers #ifdef IMGUI_IMPL_VULKAN_USE_VOLK @@ -340,6 +343,9 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) int main(int, char**) { // Setup SDL +#ifdef _WIN32 + ::SetProcessDPIAware(); +#endif if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); @@ -352,8 +358,9 @@ int main(int, char**) #endif // Create window with Vulkan graphics context + float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -393,6 +400,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForVulkan(window); ImGui_ImplVulkan_InitInfo init_info = {}; diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index ef2573324..4af533fa3 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -68,8 +68,9 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); + float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -98,6 +99,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForOpenGL(window, gl_context); ImGui_ImplOpenGL3_Init(glsl_version); diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 4051edc3d..e6678899b 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -34,8 +34,9 @@ int main(int, char**) } // Create SDL window graphics context + float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -71,6 +72,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForSDLGPU(window); ImGui_ImplSDLGPU3_InitInfo init_info = {}; diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 2821f7b80..0c8d67b53 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -32,8 +32,9 @@ int main(int, char**) } // Create window with SDL_Renderer graphics context + float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -60,6 +61,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForSDLRenderer(window, renderer); ImGui_ImplSDLRenderer3_Init(renderer); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index bdaf3aa02..895681544 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -353,8 +353,9 @@ int main(int, char**) } // Create window with Vulkan graphics context + float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Vulkan example", 1280, 720, window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Vulkan example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -398,6 +399,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForVulkan(window); ImGui_ImplVulkan_InitInfo init_info = {}; diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index d6b23e63f..2b40e090b 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -30,11 +30,14 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Main code int main(int, char**) { + // Make process DPI aware and obtain main monitor scale + ImGui_ImplWin32_EnableDpiAwareness(); + float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); + // Create application window - //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; ::RegisterClassExW(&wc); - HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX10 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX10 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) @@ -59,6 +62,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX10_Init(g_pd3dDevice); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 838e5493b..fbb6833fd 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -30,11 +30,14 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Main code int main(int, char**) { + // Make process DPI aware and obtain main monitor scale + ImGui_ImplWin32_EnableDpiAwareness(); + float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); + // Create application window - //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; ::RegisterClassExW(&wc); - HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX11 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX11 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) @@ -59,6 +62,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index ce672f353..80aef78c5 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -109,11 +109,14 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Main code int main(int, char**) { + // Make process DPI aware and obtain main monitor scale + ImGui_ImplWin32_EnableDpiAwareness(); + float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); + // Create application window - //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; ::RegisterClassExW(&wc); - HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX12 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX12 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) @@ -138,6 +141,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index d13351b0a..b7e905360 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -28,11 +28,14 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Main code int main(int, char**) { + // Make process DPI aware and obtain main monitor scale + ImGui_ImplWin32_EnableDpiAwareness(); + float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); + // Create application window - //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; ::RegisterClassExW(&wc); - HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) @@ -57,6 +60,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX9_Init(g_pd3dDevice); From 02f58b3207b22c5b038f81bc0d2b6adbcebcafa1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 6 Jun 2025 16:33:02 +0200 Subject: [PATCH 1066/2359] Fonts: AddFont() functions now allow size_pixels==0.0f (only required when using certain functions) Fonts: AddFont() funcitons allow size_pixels==0 for merged fonts. --- imgui.h | 8 ++++---- imgui_draw.cpp | 5 ++++- misc/freetype/imgui_freetype.cpp | 6 ++++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index cdcdae68b..2a07af801 100644 --- a/imgui.h +++ b/imgui.h @@ -3577,10 +3577,10 @@ struct ImFontAtlas IMGUI_API ~ImFontAtlas(); IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); - IMGUI_API ImFont* AddFontFromFileTTF(const char* 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(const char* 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 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 void RemoveFont(ImFont* font); IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c4f342e54..4bde225d6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4533,11 +4533,14 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* } src->FontLoaderData = bd_font_data; + if (src->MergeMode && src->SizePixels == 0.0f) + src->SizePixels = src->DstFont->Sources[0]->SizePixels; + if (src->SizePixels >= 0.0f) bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); else bd_font_data->ScaleFactor = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); - if (src != src->DstFont->Sources[0]) + if (src->MergeMode && src->SizePixels != 0.0f) bd_font_data->ScaleFactor *= src->SizePixels / src->DstFont->Sources[0]->SizePixels; // FIXME-NEWATLAS: Should tidy up that a bit return true; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 4c10ff42d..a6cd13d0d 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -421,7 +421,9 @@ void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { IM_UNUSED(atlas); - const float size = baked->Size * (src->SizePixels / baked->ContainerFont->Sources[0]->SizePixels); // FIXME-NEWATLAS: Should tidy up that a bit + float size = baked->Size; + if (src->MergeMode && src->SizePixels != 0.0f) + size *= (src->SizePixels / baked->ContainerFont->Sources[0]->SizePixels); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; bd_font_data->BakedLastActivated = baked; @@ -637,7 +639,7 @@ static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state) #else state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated -#endif +#endif state->err = FT_Err_Ok; return state->err; } From c18301f356caea8ea47db3375b681cf934d90304 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 6 Jun 2025 16:36:58 +0200 Subject: [PATCH 1067/2359] Examples: remove explicit font sizes from AddFontXXX() calls. Add commented out style.FontSizeBase assignment. --- examples/example_allegro5/main.cpp | 11 ++++++----- examples/example_apple_metal/main.mm | 11 ++++++----- examples/example_apple_opengl2/main.mm | 11 ++++++----- examples/example_glfw_metal/main.mm | 11 ++++++----- examples/example_glfw_opengl2/main.cpp | 11 ++++++----- examples/example_glfw_opengl3/main.cpp | 11 ++++++----- examples/example_glfw_vulkan/main.cpp | 11 ++++++----- examples/example_glfw_wgpu/main.cpp | 13 +++++++------ examples/example_glut_opengl2/main.cpp | 11 ++++++----- examples/example_sdl2_directx11/main.cpp | 11 ++++++----- examples/example_sdl2_metal/main.mm | 11 ++++++----- examples/example_sdl2_opengl2/main.cpp | 11 ++++++----- examples/example_sdl2_opengl3/main.cpp | 11 ++++++----- examples/example_sdl2_sdlrenderer2/main.cpp | 11 ++++++----- examples/example_sdl2_vulkan/main.cpp | 11 ++++++----- examples/example_sdl3_opengl3/main.cpp | 11 ++++++----- examples/example_sdl3_sdlgpu3/main.cpp | 11 ++++++----- examples/example_sdl3_sdlrenderer3/main.cpp | 11 ++++++----- examples/example_sdl3_vulkan/main.cpp | 11 ++++++----- examples/example_win32_directx10/main.cpp | 11 ++++++----- examples/example_win32_directx11/main.cpp | 11 ++++++----- examples/example_win32_directx12/main.cpp | 11 ++++++----- examples/example_win32_directx9/main.cpp | 11 ++++++----- examples/example_win32_opengl3/main.cpp | 11 ++++++----- examples/example_win32_vulkan/main.cpp | 11 ++++++----- 25 files changed, 151 insertions(+), 126 deletions(-) diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 67fc7ee65..02db84a48 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -55,12 +55,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); bool show_demo_window = true; diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 9b9db8c61..301a2b4ad 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -75,12 +75,13 @@ // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); return self; diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 5f1fd1e50..c3f0c313b 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -63,12 +63,13 @@ // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); } diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index c4380d5c3..ef314702a 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -45,12 +45,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Setup window diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index af4edbe2b..83fcab65f 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -68,12 +68,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 53dc69ce2..4bd7bc591 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -109,12 +109,13 @@ int main(int, char**) // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 10b9ab2ed..19766b9f3 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -420,12 +420,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 58c5b34f7..c150b5961 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -119,13 +119,14 @@ int main(int, char**) // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details. //io.Fonts->AddFontDefault(); + //style.FontSizeBase = 20.0f; #ifndef IMGUI_DISABLE_FILE_FUNCTIONS - //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf"); + //io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf"); //IM_ASSERT(font != nullptr); #endif diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 5720f8558..69f85a245 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -86,12 +86,13 @@ int main(int argc, char** argv) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Main loop diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index d2e151e54..194dd0e03 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -96,12 +96,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index 4dc4788a8..c1750b16b 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -36,12 +36,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Setup SDL diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index 1fe0c5864..c8363fece 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -85,12 +85,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index 63934cd88..16a73deb6 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -126,12 +126,13 @@ int main(int, char**) // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 564729bad..e456b2e9e 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -87,12 +87,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 807751b01..300543fba 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -432,12 +432,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 4af533fa3..cfd6f6a1a 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -116,12 +116,13 @@ int main(int, char**) // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index e6678899b..581b11c11 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -92,12 +92,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 0c8d67b53..6e39429d2 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -78,12 +78,13 @@ int main(int, char**) // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 895681544..df7f5efbd 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -431,12 +431,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 2b40e090b..23033d6c1 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -78,12 +78,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index fbb6833fd..c80114cfb 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -78,12 +78,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 80aef78c5..3a9ba4fb4 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -172,12 +172,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index b7e905360..430a2b448 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -76,12 +76,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index b516de7a7..820248c64 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -78,12 +78,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 8699b61a9..a98f16fe2 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -411,12 +411,13 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); // Our state From 2e67bd4de7a94a9f48a92bfcf487c92594f7cf5a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 6 Jun 2025 18:07:27 +0200 Subject: [PATCH 1068/2359] Fonts: rename to ImFontAtlasBuildLegacyPreloadAllGlyphRanges(). --- imgui_draw.cpp | 6 +++--- imgui_internal.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4bde225d6..b208b6836 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3368,7 +3368,7 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); if (atlas->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures - ImFontAtlasBuildPreloadAllGlyphRanges(atlas); + ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas); atlas->TexIsBuilt = true; } @@ -3405,12 +3405,12 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon // Preload all glyph ranges for legacy backends. // This may lead to multiple texture creation which might be a little slower than before. -void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas) +void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas) { atlas->Builder->PreloadedAllGlyphsRanges = true; for (ImFont* font : atlas->Fonts) { - ImFontBaked* baked = font->GetFontBaked(font->Sources[0]->SizePixels); + ImFontBaked* baked = font->GetFontBaked(font->LegacySize); if (font->FallbackChar != 0) baked->FindGlyph(font->FallbackChar); if (font->EllipsisChar != 0) diff --git a/imgui_internal.h b/imgui_internal.h index e344cbccf..b80bf50b6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3807,7 +3807,7 @@ IMGUI_API void ImFontAtlasTextureCompact(ImFontAtlas* atlas); IMGUI_API ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); -IMGUI_API void ImFontAtlasBuildPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy +IMGUI_API void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v); IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); From 573f08135d8ce0d8cde6db2cd0156b2b602e137e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Jun 2025 17:47:30 +0200 Subject: [PATCH 1069/2359] Fonts: fixed PopFont() broken recovery. "misc_recover_1" test would assert in EndFrame() --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 39a79a398..faf8ae690 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8812,7 +8812,7 @@ void ImGui::PushFont(ImFont* font, float font_size_base) void ImGui::PopFont() { ImGuiContext& g = *GImGui; - if (g.FontStack.Size <= 0 && g.WithinFrameScope) + if (g.FontStack.Size <= 0) { IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!"); return; From 0e769c541835af126e344f9a4d0e3f19d6ba9163 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Jun 2025 17:56:09 +0200 Subject: [PATCH 1070/2359] Fonts: amend UpdateCurentFontSize() early out optimization. --- imgui.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index faf8ae690..e97f5e6fb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8739,8 +8739,15 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) ImGuiWindow* window = g.CurrentWindow; g.Style.FontSizeBase = g.FontSizeBase; + + // Early out to avoid hidden window keeping bakes referenced and out of GC reach. + // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching, so for now we null it. if (window != NULL && window->SkipItems) - return; + if (g.CurrentTable == NULL || g.CurrentTable->CurrentColumn != -1) // See 8465#issuecomment-2951509561. Ideally the SkipItems=true in tables would be amended with extra data. + { + g.FontBaked = NULL; + return; + } // Restoring is pretty much only used by PopFont()/PopFontSize() float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; From 29fbf3c1ec458e5765c40762e6cfda2cb2ed81e7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Jun 2025 18:09:44 +0200 Subject: [PATCH 1071/2359] Fonts: demote ImFont::GetFontBaked() as slighty internal. --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 2a07af801..1c5dec57d 100644 --- a/imgui.h +++ b/imgui.h @@ -3791,7 +3791,6 @@ struct ImFont // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); - IMGUI_API ImFontBaked* GetFontBaked(float font_size, float density = -1.0f); // Get or create baked data for given size IMGUI_API bool IsGlyphInFont(ImWchar c); bool IsLoaded() const { return ContainerAtlas != NULL; } const char* GetDebugName() const { return Sources.Size ? Sources[0]->Name : ""; } // Fill ImFontConfig::Name. @@ -3799,6 +3798,7 @@ struct ImFont // [Internal] Don't use! // '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** remaining = NULL); // utf8 IMGUI_API const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, 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); From e1481a731d0fd9f68157cdfbce0b6e7627456aae Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 13:20:17 +0200 Subject: [PATCH 1072/2359] Fonts: fixed NewFrame() when atlas builder has been created but fonts not added. Fixed GetCustomRect() after atlas clear. --- imgui.cpp | 2 +- imgui_draw.cpp | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index e97f5e6fb..ff2d18a67 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8668,7 +8668,7 @@ ImFont* ImGui::GetDefaultFont() { ImGuiContext& g = *GImGui; ImFontAtlas* atlas = g.IO.Fonts; - if (atlas->Builder == NULL) + if (atlas->Builder == NULL || atlas->Fonts.Size == 0) ImFontAtlasBuildMain(atlas); return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0]; } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b208b6836..195f5bece 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4362,6 +4362,8 @@ ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId if (id == ImFontAtlasRectId_Invalid) return NULL; int index_idx = ImFontAtlasRectId_GetIndex(id); + if (atlas->Builder == NULL) + ImFontAtlasBuildInit(atlas); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; if (index_idx >= builder->RectsIndex.Size) return NULL; From cc3d4cab21ac1d7f2ca42a4de9512134f663b419 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 14:38:45 +0200 Subject: [PATCH 1073/2359] (Breaking) renamed ImFontConfig::FontBuilderFlags -> FontLoaderFlags. ImFontAtlas::FontBuilderFlags -> FontLoaderFlags. ImGuiFreeTypeBuilderFlags -> ImGuiFreeTypeLoaderFlags. --- imgui.cpp | 14 ++++----- imgui.h | 14 +++++---- misc/freetype/imgui_freetype.cpp | 12 ++++---- misc/freetype/imgui_freetype.h | 51 ++++++++++++++++++++++---------- 4 files changed, 56 insertions(+), 35 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ff2d18a67..2909dfb8e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15810,7 +15810,7 @@ static void MetricsHelpMarker(const char* desc) } #ifdef IMGUI_ENABLE_FREETYPE -namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontBuilderFlags(unsigned int* p_font_builder_flags); } +namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); } #endif // [DEBUG] List fonts in a font atlas and display its texture @@ -15868,13 +15868,13 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) ImFontAtlasBuildSetupFontLoader(atlas, loader_freetype); if (loader_current == loader_freetype) { - unsigned int loader_flags = atlas->FontBuilderFlags; + unsigned int loader_flags = atlas->FontLoaderFlags; Text("Shared FreeType Loader Flags: 0x%08", loader_flags); - if (ImGuiFreeType::DebugEditFontBuilderFlags(&loader_flags)) + if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags)) { for (ImFont* font : atlas->Fonts) ImFontAtlasFontDestroyOutput(atlas, font); - atlas->FontBuilderFlags = loader_flags; + atlas->FontLoaderFlags = loader_flags; for (ImFont* font : atlas->Fonts) ImFontAtlasFontInitOutput(atlas, font); } @@ -16853,12 +16853,12 @@ void ImGui::DebugNodeFont(ImFont* font) #ifdef IMGUI_ENABLE_FREETYPE if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0) { - unsigned int loader_flags = src->FontBuilderFlags; + unsigned int loader_flags = src->FontLoaderFlags; Text("FreeType Loader Flags: 0x%08X", loader_flags); - if (ImGuiFreeType::DebugEditFontBuilderFlags(&loader_flags)) + if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags)) { ImFontAtlasFontDestroyOutput(atlas, font); - src->FontBuilderFlags = loader_flags; + src->FontLoaderFlags = loader_flags; ImFontAtlasFontInitOutput(atlas, font); } } diff --git a/imgui.h b/imgui.h index 1c5dec57d..1d27953f2 100644 --- a/imgui.h +++ b/imgui.h @@ -29,9 +29,9 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19197 -#define IMGUI_HAS_TABLE -#define IMGUI_HAS_TEXTURES // 1.92+ WIP branch with ImGuiBackendFlags_RendererHasTextures +#define IMGUI_VERSION_NUM 19198 +#define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 +#define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 /* @@ -3480,7 +3480,8 @@ struct ImFontConfig float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. // FIXME-NEWATLAS: Intentionally unscaled - unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + unsigned int FontLoaderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + //unsigned int FontBuilderFlags; // -- // [Renamed in 1.92] Ue FontLoaderFlags. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. float RasterizerDensity; // 1.0f // [LEGACY: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported] DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. @@ -3696,7 +3697,7 @@ struct ImFontAtlas const ImFontLoader* FontLoader; // Font loader opaque interface (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). Don't set directly! const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name void* FontLoaderData; // Font backend opaque storage - unsigned int FontBuilderFlags; // [FIXME: Should be called FontLoaderFlags] Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. . Per-font override is also available in ImFontConfig. + unsigned int FontLoaderFlags; // Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig). int RefCount; // Number of contexts using this atlas ImGuiContext* OwnerContext; // Context which own the atlas will be in charge of updating and destroying it. @@ -3710,7 +3711,8 @@ struct ImFontAtlas IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X #endif - //int TexDesiredWidth; // OBSOLETED in 1.92.X (force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) + //unsigned int FontBuilderFlags; // OBSOLETED in 1.92.X: Renamed to FontLoaderFlags. + //int TexDesiredWidth; // OBSOLETED in 1.92.X: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index a6cd13d0d..35a277f7c 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -153,14 +153,14 @@ struct ImGui_ImplFreeType_Data struct ImGui_ImplFreeType_FontSrcData { // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. - bool InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeBuilderFlags extra_user_flags); + bool InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_user_flags); void CloseFont(); ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); } ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); } // Members FT_Face FtFace; - ImGuiFreeTypeBuilderFlags UserFlags; // = ImFontConfig::FontBuilderFlags + ImGuiFreeTypeLoaderFlags UserFlags; // = ImFontConfig::FontLoaderFlags FT_Int32 LoadFlags; ImFontBaked* BakedLastActivated; }; @@ -172,7 +172,7 @@ struct ImGui_ImplFreeType_FontSrcBakedData ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } }; -bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeBuilderFlags extra_font_builder_flags) +bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_font_loader_flags) { FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (uint32_t)src->FontDataSize, (uint32_t)src->FontNo, &FtFace); if (error != 0) @@ -182,7 +182,7 @@ bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfi return false; // Convert to FreeType flags (NB: Bold and Oblique are processed separately) - UserFlags = (ImGuiFreeTypeBuilderFlags)(src->FontBuilderFlags | extra_font_builder_flags); + UserFlags = (ImGuiFreeTypeLoaderFlags)(src->FontLoaderFlags | extra_font_loader_flags); LoadFlags = 0; if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0) @@ -400,7 +400,7 @@ bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) IM_ASSERT(src->FontLoaderData == NULL); src->FontLoaderData = bd_font_data; - if (!bd_font_data->InitFont(bd->Library, src, (ImGuiFreeTypeBuilderFlags)atlas->FontBuilderFlags)) + if (!bd_font_data->InitFont(bd->Library, src, (ImGuiFreeTypeLoaderFlags)atlas->FontLoaderFlags)) { IM_DELETE(bd_font_data); src->FontLoaderData = NULL; @@ -587,7 +587,7 @@ void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* u GImGuiFreeTypeAllocatorUserData = user_data; } -bool ImGuiFreeType::DebugEditFontBuilderFlags(unsigned int* p_font_loader_flags) +bool ImGuiFreeType::DebugEditFontLoaderFlags(unsigned int* p_font_loader_flags) { bool edited = false; edited |= ImGui::CheckboxFlags("NoHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_NoHinting); diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index 2b4810e32..4f7306790 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -23,22 +23,41 @@ struct ImFontLoader; // - When disabled, FreeType generates blurrier glyphs, more or less matches the stb_truetype.h // - The Default hinting mode usually looks good, but may distort glyphs in an unusual way. // - The Light hinting mode generates fuzzier glyphs but better matches Microsoft's rasterizer. -// You can set those flags globally in ImFontAtlas::FontBuilderFlags -// You can set those flags on a per font basis in ImFontConfig::FontBuilderFlags -enum ImGuiFreeTypeBuilderFlags +// You can set those flags globally in ImFontAtlas::FontLoaderFlags +// You can set those flags on a per font basis in ImFontConfig::FontLoaderFlags +typedef unsigned int ImGuiFreeTypeLoaderFlags; +enum ImGuiFreeTypeLoaderFlags_ { - ImGuiFreeTypeBuilderFlags_NoHinting = 1 << 0, // Disable hinting. This generally generates 'blurrier' bitmap glyphs when the glyph are rendered in any of the anti-aliased modes. - ImGuiFreeTypeBuilderFlags_NoAutoHint = 1 << 1, // Disable auto-hinter. - ImGuiFreeTypeBuilderFlags_ForceAutoHint = 1 << 2, // Indicates that the auto-hinter is preferred over the font's native hinter. - ImGuiFreeTypeBuilderFlags_LightHinting = 1 << 3, // A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by Microsoft's ClearType and Adobe's proprietary font renderer. This preserves inter-glyph spacing in horizontal text. - ImGuiFreeTypeBuilderFlags_MonoHinting = 1 << 4, // Strong hinting algorithm that should only be used for monochrome output. - ImGuiFreeTypeBuilderFlags_Bold = 1 << 5, // Styling: Should we artificially embolden the font? - ImGuiFreeTypeBuilderFlags_Oblique = 1 << 6, // Styling: Should we slant the font, emulating italic style? - ImGuiFreeTypeBuilderFlags_Monochrome = 1 << 7, // Disable anti-aliasing. Combine this with MonoHinting for best results! - ImGuiFreeTypeBuilderFlags_LoadColor = 1 << 8, // Enable FreeType color-layered glyphs - ImGuiFreeTypeBuilderFlags_Bitmap = 1 << 9 // Enable FreeType bitmap glyphs + ImGuiFreeTypeLoaderFlags_NoHinting = 1 << 0, // Disable hinting. This generally generates 'blurrier' bitmap glyphs when the glyph are rendered in any of the anti-aliased modes. + ImGuiFreeTypeLoaderFlags_NoAutoHint = 1 << 1, // Disable auto-hinter. + ImGuiFreeTypeLoaderFlags_ForceAutoHint = 1 << 2, // Indicates that the auto-hinter is preferred over the font's native hinter. + ImGuiFreeTypeLoaderFlags_LightHinting = 1 << 3, // A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by Microsoft's ClearType and Adobe's proprietary font renderer. This preserves inter-glyph spacing in horizontal text. + ImGuiFreeTypeLoaderFlags_MonoHinting = 1 << 4, // Strong hinting algorithm that should only be used for monochrome output. + ImGuiFreeTypeLoaderFlags_Bold = 1 << 5, // Styling: Should we artificially embolden the font? + ImGuiFreeTypeLoaderFlags_Oblique = 1 << 6, // Styling: Should we slant the font, emulating italic style? + ImGuiFreeTypeLoaderFlags_Monochrome = 1 << 7, // Disable anti-aliasing. Combine this with MonoHinting for best results! + ImGuiFreeTypeLoaderFlags_LoadColor = 1 << 8, // Enable FreeType color-layered glyphs + ImGuiFreeTypeLoaderFlags_Bitmap = 1 << 9, // Enable FreeType bitmap glyphs + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiFreeTypeBuilderFlags_NoHinting = ImGuiFreeTypeLoaderFlags_NoHinting, + ImGuiFreeTypeBuilderFlags_NoAutoHint = ImGuiFreeTypeLoaderFlags_NoAutoHint, + ImGuiFreeTypeBuilderFlags_ForceAutoHint = ImGuiFreeTypeLoaderFlags_ForceAutoHint, + ImGuiFreeTypeBuilderFlags_LightHinting = ImGuiFreeTypeLoaderFlags_LightHinting, + ImGuiFreeTypeBuilderFlags_MonoHinting = ImGuiFreeTypeLoaderFlags_MonoHinting, + ImGuiFreeTypeBuilderFlags_Bold = ImGuiFreeTypeLoaderFlags_Bold, + ImGuiFreeTypeBuilderFlags_Oblique = ImGuiFreeTypeLoaderFlags_Oblique, + ImGuiFreeTypeBuilderFlags_Monochrome = ImGuiFreeTypeLoaderFlags_Monochrome, + ImGuiFreeTypeBuilderFlags_LoadColor = ImGuiFreeTypeLoaderFlags_LoadColor, + ImGuiFreeTypeBuilderFlags_Bitmap = ImGuiFreeTypeLoaderFlags_Bitmap, +#endif }; +// Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +typedef ImGuiFreeTypeLoaderFlags_ ImGuiFreeTypeBuilderFlags_; +#endif + namespace ImGuiFreeType { // This is automatically assigned when using '#define IMGUI_ENABLE_FREETYPE'. @@ -51,13 +70,13 @@ namespace ImGuiFreeType // However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired. IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = nullptr); - // Display UI to edit FontBuilderFlags in ImFontAtlas (shared) or ImFontConfig (single source) - IMGUI_API bool DebugEditFontBuilderFlags(unsigned int* p_font_loader_flags); + // Display UI to edit ImFontAtlas::FontLoaderFlags (shared) or ImFontConfig::FontLoaderFlags (single source) + IMGUI_API bool DebugEditFontLoaderFlags(ImGuiFreeTypeLoaderFlags* p_font_loader_flags); // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //IMGUI_API const ImFontBuilderIO* GetBuilderForFreeType(); // Renamed/changed in 1.92. Change 'io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()' to 'io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader()' if you need runtime selection. - //static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontBuilderFlags = flags; return atlas->Build(); } // Prefer using '#define IMGUI_ENABLE_FREETYPE' + //static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontLoaderFlags = flags; return atlas->Build(); } // Prefer using '#define IMGUI_ENABLE_FREETYPE' #endif } From 4acce8565602ef30f29fa13e24da1991c6fe951e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 17:12:07 +0200 Subject: [PATCH 1074/2359] Fonts: tweaks demo and exposure to sliders, etc. --- imgui.cpp | 5 +++-- imgui_demo.cpp | 29 +++++------------------------ 2 files changed, 8 insertions(+), 26 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2909dfb8e..b9b5fbbc1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15824,7 +15824,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures); EndDisabled(); ShowFontSelector("Font"); - BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); + //BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); @@ -15834,12 +15834,13 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 5.0f); //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); //EndDisabled(); + BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); BulletText("Load a nice font for better results!"); BulletText("Please submit feedback:"); SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); BulletText("Read FAQ for more details:"); SameLine(); TextLinkOpenURL("dearimgui.com/faq", "https://www.dearimgui.com/faq/"); - EndDisabled(); + //EndDisabled(); SeparatorText("Font List"); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 985a490ea..cd48ee0ff 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -430,26 +430,6 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); ImGui::Spacing(); - { - ImGui::SeparatorText("dynamic_fonts branch"); - ImGuiStyle& style = ImGui::GetStyle(); - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); - ImGui::ShowFontSelector("Font"); - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); - if (ImGui::DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) - style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. - ImGui::SameLine(0.0f, 0.0f); Text(" (out %.2f)", ImGui::GetFontSize()); - ImGui::SameLine(); HelpMarker("- This is scaling font only. General scaling will come later."); - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); - ImGui::DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); - ImGui::BulletText("Load a nice font for better results!"); - //ImGui::BulletText("Current font loader: '%s'", ImGui::GetIO().Fonts->FontLoaderName); - ImGui::BulletText("Please submit feedback:"); ImGui::SameLine(); - ImGui::TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); - ImGui::BulletText("See 'Widgets->Fonts' below for more."); - ImGui::Spacing(); - } - IMGUI_DEMO_MARKER("Help"); if (ImGui::CollapsingHeader("Help")) { @@ -603,8 +583,8 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Spacing(); } - IMGUI_DEMO_MARKER("Configuration/Style"); - if (ImGui::TreeNode("Style")) + IMGUI_DEMO_MARKER("Configuration/Style, Fonts"); + if (ImGui::TreeNode("Style, Fonts")) { ImGui::Checkbox("Style Editor", &demo_data.ShowStyleEditor); ImGui::SameLine(); @@ -8277,10 +8257,12 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { // General SeparatorText("General"); + if ((GetIO().BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); + if (ShowStyleSelector("Colors##Selector")) ref_saved_style = style; ShowFontSelector("Fonts##Selector"); - BeginDisabled((GetIO().BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); @@ -8289,7 +8271,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 5.0f); //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); //EndDisabled(); - EndDisabled(); // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) if (SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) From 96be9573156549f6ebcda15c8783a582fe91c09f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 14:09:38 +0200 Subject: [PATCH 1075/2359] Docs: update Changelog, FAQ, Fonts docs. --- docs/CHANGELOG.txt | 329 +++++++++++++++++++++++++++++++++++++++------ docs/FAQ.md | 101 ++++++++++---- docs/FONTS.md | 65 ++++++--- imgui.h | 23 ++-- 4 files changed, 421 insertions(+), 97 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 059daf5b5..2a16008f6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,16 +39,161 @@ HOW TO UPDATE? VERSION 1.92.0 WIP (In Progress) ----------------------------------------------------------------------- +THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! +I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, +BUT INEVITABLY SOME USERS WILL BE AFFECTED. + +IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, +PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: + https://github.com/ocornut/imgui/issues/ + +As part of the plan to reduce impact of API breaking changes, several unfinished +changes/features/refactors related to font and text systems and scaling will be +part of subsequent releases (1.92.1+). + +If you are updating from an old version, and expecting a massive or difficult update, +consider first updating to 1.91.9 to reduce the amount of changes. + Breaking changes: +- Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific + logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f): + This WILL NOT map correctly to the new system! Because font will rasterize as requested size. + - With a legacy backend (< 1.92): + - Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. + - This already worked before, but is now pretty much required. + - With a new backend (1.92+) + - FramebufferScale is automatically used to set current font RasterizerDensity. + - FramebufferScale is a per-viewport property provided by backend through the + Platform_GetWindowFramebufferScale() handler in 'docking' branch. + - So this should be all automatic. +- Fonts: **IMPORTANT** on Font Sizing: + - Before 1.92, fonts were of a single size. They can now be dynamically sized. + - PushFont() API now has an optional size parameter. PushFontSize() was also added. + void PushFont(ImFont* font) --> void PushFont(ImFont* font, float size = 0.0f); + - Before 1.92: ImGui::PushFont() always used font "default" size specified in AddFont() call. + - Since 1.92: ImGui::PushFont() preserve the current font size which is a shared value. + - To use old behavior: + - use 'ImGui::PushFont(font, font->LegacySize)' at call site. + - or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call + (not desirable as it requires e.g. third-party code to be aware of it). + - ImFont::FontSize was removed and does not make sense anymore. + ImFont::LegacySize is the size passed to AddFont(). + - Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. + +- Textures: + - All API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef': + - ImTextureRef a small composite structure which may be constructed from a ImTextureID. + (or constructed from a ImTextureData* which represent a texture which will generally + be ready by the time of rendering). + - Affected functions are: + - ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), + - ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded(). + - We suggest that C users and any higher-level language bindings generators may + facilitate converting this in some way, aka emulating the trivial C++ constructor. +- Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID() + and IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. + Kept redirection functions (will obsolete). + - A majority of old backends should still work with new code (behaving like they did before). + - Calling ImFontAtlas::Build() before initializing new backends will erroneously trigger + preloading all glyphs. Will be detected with an assertion after the backend is initialized. +- Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) + since v1.91.8. It is quite important you keep it automatic until we decide if we want + to provide a way to express finer policy, otherwise you will likely waste texture space + when using large glyphs. Note that the imgui_freetype backend doesn't use and does not + need oversampling. +- Fonts: specifying glyph ranges is now unnecessary. + - The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. + - All GetGlyphRangesXXXX() functions are now marked obsolete: + - GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), + GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), + GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), + GetGlyphRangesThai(), GetGlyphRangesVietnamese(). +- Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327) + (it vaguely made sense with the old system as if unspecified textures width maxed up + to 4096 but that limit isn't necessary anymore, and Renderer_TextureMaxWidth covers this) + However you may set TexMinWidth = TexMaxWidth for the same effect. +- Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on + ImGuiContext to create one, you'll need to set the atlas->RendererHasTextures field + and call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. +- Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using + PushFontSize(style.FontSizeBase * factor) or to manipulate other scaling factors. +- Fonts: obsoleted ImFont::Scale which is not useful anymore. +- Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition(): + - old: const char* CalcWordWrapPositionA(float scale, const char* text, ....); + - new: const char* CalcWordWrapPosition (float size, const char* text, ....); + The leading 'float scale' parameters was changed to 'float size'. + This was necessary as 'scale' is assuming a unique font size. + Kept inline redirection function assuming using font->LegacySize. +- Fonts: generally reworked Internals of ImFontAtlas and ImFont. + While in theory a vast majority of users shouldn't be affected, some use cases or + extensions might be. Among other things: + - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef. + - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[] + - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. + - Each ImFont has a number of ImFontBaked instances corresponding to actively used + sizes. ImFont::GetFontBaked(size) retrieves the one for a given size. + - Things moved from ImFont to ImFontBaked: + - ImFont::IndexAdvanceX[] -> ImFontBaked::IndexAdvanceX[] + - ImFont::Glyphs[] -> ImFontBaked::Glyphs[] + - ImFont::Ascent, Descent -> ImFontBaked::Ascent, Descent + - ImFont::FindGlyph() -> ImFontBaked::FindGlyph() + - ImFont::FindGlyphNoFallback() -> ImFontBaked::FindGlyphNoFallback() + - ImFont::GetCharAdvance() -> ImFontBaked::GetCharAdvance() + - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to + access font data for current font at current font size. + (and you may use font->GetFontBaked(size) to access it for any other size.) + g.Font == ImGui::GetFont() + g.FontSize == ImGui::GetFontSize() + g.FontBaked == ImGui::GetFontBaked() == ImGui::GetFont()->GetFontBaked(ImGui::GetFontSize()) + Please report if you are affected! +- Fonts: (users of imgui_freetype) + - renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. + - renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. + - renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags. + - if you used runtime imgui_freetype selection rather than the default compile-time + option provided by IMGUI_ENABLE_FREETYPE: + - renamed/reworked ImFontBuilderIO into ImFontLoader, + - renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader(). + - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() + - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader() +- DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). +- Fonts: (users of custom rectangles) + - Renamed AddCustomRectRegular() to AddCustomRect(). (#8466) + - Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV(). (#8466) + - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. + - ImFontAtlasCustomRect::X --> ImFontAtlasRect::x + - ImFontAtlasCustomRect::Y --> ImFontAtlasRect::y + - ImFontAtlasCustomRect::Width --> ImFontAtlasRect::w + - ImFontAtlasCustomRect::Height --> ImFontAtlasRect::h + Before: + const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id); + ImVec2 uv0, uv1; + atlas->GetCustomRectUV(r, &uv0, &uv1); + ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1); + After: + ImFontAtlasRect r; + atlas->GetCustomRect(custom_rect_id, &r); + ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1); + We added a redirecting typedef but haven't attempted to magically redirect + the field names, as this API is rarely used and the fix is simple. + - Obsoleted AddCustomRectFontGlyph() as the API does not make sense for scalable fonts: + - Kept existing function which uses the font "default size" (Sources[0]->LegacySize). + - Added a helper AddCustomRectFontGlyphForSize() which is immediately marked obsolete, + but can facilitate transitioning old code. + - Prefer adding a font source (ImFontConfig) using a custom/procedural loader. +- Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() + for all backends that had them. They should not be necessary any more. + - removed ImGui_ImplMetal_CreateFontsTexture(), ImGui_ImplMetal_DestroyFontsTexture(). + - removed ImGui_ImplOpenGL2_CreateFontsTexture(), ImGui_ImplOpenGL2_DestroyFontsTexture(). + - removed ImGui_ImplOpenGL3_CreateFontsTexture(), ImGui_ImplOpenGL3_DestroyFontsTexture(). + - removed ImGui_ImplSDLGPU3_CreateFontsTexture(), ImGui_ImplSDLGPU3_DestroyFontsTexture(). + - removed ImGui_ImplSDLRenderer2_CreateFontsTexture(), ImGui_ImplSDLRenderer2_DestroyFontsTexture(). + - removed ImGui_ImplSDLRenderer3_CreateFontsTexture(), ImGui_ImplSDLRenderer3_DestroyFontsTexture(). + - removed ImGui_ImplVulkan_CreateFontsTexture(), ImGui_ImplVulkan_DestroyFontsTexture(). - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). (#1079, #8639) -- Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition(): - - old: const char* CalcWordWrapPositionA(float scale, const char* text, ....); - - new: const char* CalcWordWrapPosition (float size, const char* text, ....); - The leading 'float scale' parameters was changed to 'float size'. - This was necessary as 'scale' is assuming standard font size which is a concept we aim to - eliminate in an upcoming update. Kept inline redirection function. - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4 (March 2023). (#3092) - PushAllowKeyboardFocus(bool tab_stop) --> PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); @@ -63,6 +208,89 @@ Breaking changes: Other changes: +- Textures: added partial texture update protocol. (#8465, #3761) + - The Renderer Backend needs to set io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures + and handle texture updates requests. + - New structs: ImTextureData, ImTextureRect. + - New enums: ImTextureStatus, ImTextureFormat. + - During its ImGui_ImplXXXX_RenderDrawData() call, the backend can now access a texture list + in ImDrawData::Textures[]. Textures may have four distinct states: + - ImTextureStatus_WantCreate: requesting backend to create a texture. + - ImTextureStatus_WantUpdates: requesting backend to copy given blocks from the CPU side + copy of the texture to your graphics pipeline. + A 'tex->Updates[]' list of update is provided as well as a single 'tex->UpdatesRect' bounding box. + - ImTextureStatus_WantDestroy: requesting backend to destroy the texture. + - A 'int UnusedFrames' value is provided to conveniently defer destroying. + - Backend is generally free to destroy textures whenever they like. + - ImTextureStatus_OK: nothing to do. + - Almost all standard backends have been updated to support this. + - Backends have allowed to destroy textures at any time if they desire so. + A list is available in platform_io.Textures[] for this purpose and for backend shutdown. + - Both stb_truetype and FreeType backends have been updated to work with the new + system, and they now share more code than before. + - Added '#define IMGUI_HAS_TEXTURES' to facilitate compile-time checks for third-party + extensions until this is merged with a definitive version number to check. +- Fonts: font backend/loader may easily be changed dynamically, allowing users to compare + rasterizers outputs and features. imgui_freetype is generally beneficial. +- Fonts: ImFontAtlas::AddFontXXX() functions may be called at any time during the frame. +- Fonts: ImFontAtlas::AddFontXXX() can fail more gracefully if error handling is configured + to not assert (this will be better exposed via future font flags). +- Fonts: added ImGui::PushFontSize()/PopFontSize() functions. +- Fonts: added style.FontScaleBase scaling factor (previously called io.FontGlobalScale). +- Fonts: added style.FontScaleDpi scaling factor. This is designed to be be changed on + per-monitor/per-viewport basis, which `io.ConfigDpiScaleFonts` does automatically. + (which is why it is separate from FontScaleBase). +- Fonts: added optional font_size parameter to ImGui::PushFont() function. +- Fonts: added ImFontAtlas::RemoveFont() function. +- Fonts: added ImFontAtlas::CompactCache() function. +- Fonts: added ImFontAtlas::TexDesiredFormat field (default to ImTextureFormat_RGBA32, + can be changed to ImTextureFormat_Alpha8). +- Fonts: added ImFontAtlas::TexMinWidth, TexMinHeight, TexMaxWidth, TexMaxHeight fields. +- Fonts: added ImFontConfig::PixelSnapV to align scaled GlyphOffset.y to pixel boundaries. +- Fonts: added ImFontConfig::GlyphExcludeRanges[], which behave similarly to + ImFontConfig::GlyphRanges[], but has the opposite meaning. It is tailored to situations + where merged fonts have overlapping characters. +- Fonts: added "Input Glyphs Overlap Detection Tool" which dumps a list of glyphs + provided by merged sources, which may help setting up a GlyphExcludeRanges[] filter. +- Fonts: added ImFontAtlas::FontBackendName (which is surfaced in the "About Dear ImGui" + window and other locations). +- Fonts: added ImFontFlags (currently needs to be passed through ImFontConfig until + we revamp font loading API): + - ImFontFlags_DefaultToLegacySize: for legacy compatibility: make PushFont() calls + without explicit size use font->LegacySize instead of current font size. + - ImFontFlags_NoLoadError: disable erroring/assert when calling AddFontXXX() + with missing file/data. Calling code is expected to check AddFontXXX() return value. + - ImFontFlags_NoLoadGlyphs: disable loading new glyphs. + - ImFontFlags_LockBakedSizes: disable loading new baked sizes, disable garbage + collecting current ones. e.g. if you want to lock a font to a single size. +- Fonts: the general design has changed toward meaning that a ImFont doesn't have + have a specific size: it may be bound and drawn with any size. + - We store ImFontBaked structures internally, which are a cache of information + for a given size being drawn. You should not need to deal with ImFontBaked directly. + - ImFontBaked structures may be cleaned up between frames when unused, pointers + to them are only valid for the current frame. + - Added ImFontBaked::IsGlyphLoaded() function. +- Fonts: custom rect packing has generally been reworked. (#8107, #7962, #1282) + - ImFontAtlas::AddCustomRect() (previously AddCustomRectRegular()/AddCustomRectFontGlyph()) + functions will immediately return a packed rectangle identifier, and you can write your + pixels immediately - previously had to wait for Build() to be called. + This is also the case when using a legacy backend. + - Custom packed rectangles may be moved during a texture change, aka practically anytime. + Always refer to latest uvs/position returned by GetCustomRect(). + - AddCustomRect() returns ImFontAtlasRectId_Invalid on failure. + - Added ImFontAtlas::RemoveCustomRect() function. + - GetCustomRect() can safely return false and not crash when passed an invalid or removed id. +- Fonts: texture is now stored in a single format CPU side (save ~25% when using RGBA). +- Fonts: changing current font to one from a different atlas is supported. (#8080) +- Fonts: automatic baking of an "..." ellipsis works better with monospace fonts. +- Fonts: each ImFontConfig font source may provide a custom backend/loader. +- Fonts: added platform_io.Renderer_TextureMaxWidth/Renderer_TextureMaxHeight fields + for Renderer Backend to specify if there is a maximum accepted texture size (not yet used). +- Fonts: added compile-time overridable '#define ImTextureID_Invalid 0' if you need 0 + to be a valid low-level texture identifier. +- Debug Tools: Fonts section: add font preview, add "Remove" button, add "Load all glyphs" + button, add selection to change font backend when both are compiled in. + - IO: variations in analog-only components of gamepad events do not interfere with trickling of mouse position events (#4921, #8508) - Windows: fixed SetNextWindowCollapsed()/SetWindowCollapsed() breaking @@ -132,39 +360,62 @@ Other changes: requires providing a window to the backend. (#8584, #6341) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] - Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). -- Backends: Win32: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) - would fail to claim it again the next subsequent click. (#8594) -- Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad - regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) -- Backends: SDL2, SDL3: don't attempt to call SDL_CaptureMouse() on drivers where we don't - call SDL_GetGlobalMouseState(). This is specifically for Wayland but we currently use - the same white-list as SDL_GetGlobalMouseState(). (#8561) [@vs49688] -- Backends: GLFW, SDL2, SDL3: include GLFW/SDL version number in io.BackendPlatformName. -- Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() - memory ownership change. (#8530, #7801) [@Green-Sky] -- Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative - way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) -- Backends: SDLGPU3: Fixed creating atlas texture earlier than other backends, preventing - to load fonts between the Init and NewFrames calls. -- Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which - were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] -- Backends: SDLGPU3: added support for ImDrawCallback_ResetRenderState. (#8599) -- Backends: OpenGL3: made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor - GL_PRIMITIVE_RESTART. (#8664) [@DyXel] -- Backends: DirectX10, DirectX11, DirectX12: Honor FramebufferScale to allow for custom - platform backends and experiments using it (consistently with other renderer backends, - even though in normal condition it is not set under Windows). (#8412) [@WSSDude] -- Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's - pColorAttachmentFormats buffer when set, in order to reduce common user-error of - specifying a pointer to data that gets out of scope. (#8282) -- Backends: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() - + try both non-KHR and KHR versions. (#8600, #8326, #8365) [@ChrisTom-94] -- Backends: Vulkan: fixed validation errors in window create/resize helpers used by examples - and by multi-viewports implementation, which would typically trigger errors while detaching - secondary viewports. (#8600, #8176) [@ChrisTom-94] -- Examples: Apple+Metal, Apple+OpenGL: add Makefile (CLion opens them nicely). (#8637) [@pthom] -- Examples: DirectX12+Win32: also test for IsIconic() for sleeping since we don't seem to - get a DXGI_STATUS_OCCLUDED signal when minimized. (#8603) [@dooann] +- Backends: + - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, Allegro5: + - Added ImGuiBackendFlags_RendererHasTextures support. (#8465, #3761, #3471) + [@ocornut, @ShironekoBen, @thedmd] + - Added ImGui_ImplXXXX_UpdateTexture(ImTextureData* tex) functions for all backend. + Available if you want to start uploading textures right after ImGui::Render() and without + waiting for the call to ImGui_ImplXXXX_RenderDrawData(). Also useful if you use a staged or + multi-threaded rendering schemes, where you might want to set ImDrawData::Textures = NULL. (#8597, #1860) + - Backends: GLFW: added ImGui_ImplGlfw_GetContentScaleForMonitor(), ImGui_ImplGlfw_GetContentScaleForWindow() + helpers. They are wrappers to glfwGetMonitorContentScale()/glfwGetWindowContentScale(), with compile-time + GLFW version checks + returning 1.0f on Apple platform. + - Backends: SDL2: added ImGui_ImplSDL2_GetDpiScaleForDisplay() and ImGui_ImplSDL2_GetContentScaleForWindow() + helpers. They are wrappers to SDL_GetDisplayDPI(), with compile-time SDL version checks + returning 1.0f + on Apple platforms. SDL3 already does this by default. + - Backends: Win32: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) + would fail to claim it again the next subsequent click. (#8594) + - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad + regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) + - Backends: SDL2, SDL3: don't attempt to call SDL_CaptureMouse() on drivers where we don't + call SDL_GetGlobalMouseState(). This is specifically for Wayland but we currently use + the same white-list as SDL_GetGlobalMouseState(). (#8561) [@vs49688] + - Backends: GLFW, SDL2, SDL3: include GLFW/SDL version number in io.BackendPlatformName. + - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() + memory ownership change. (#8530, #7801) [@Green-Sky] + - Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative + way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) + - Backends: SDLGPU3: Fixed creating atlas texture earlier than other backends, preventing + to load fonts between the Init and NewFrames calls. + - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which + were unusually slow to recreate every frame. Much faster now. (#8534) [@ocornut, @TheMode] + - Backends: SDLGPU3: added support for ImDrawCallback_ResetRenderState. (#8599) + - Backends: OpenGL3: made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor + GL_PRIMITIVE_RESTART. (#8664) [@DyXel] + - Backends: DirectX10, DirectX11, DirectX12: Honor FramebufferScale to allow for custom + platform backends and experiments using it (consistently with other renderer backends, + even though in normal condition it is not set under Windows). (#8412) [@WSSDude] + - Backends: Vulkan: Deep-copy ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo's + pColorAttachmentFormats buffer when set, in order to reduce common user-error of + specifying a pointer to data that gets out of scope. (#8282) + - Backends: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + + try both non-KHR and KHR versions. (#8600, #8326, #8365) [@ChrisTom-94] + - Backends: Vulkan: fixed validation errors in window create/resize helpers used by examples + and by multi-viewports implementation, which would typically trigger errors while detaching + secondary viewports. (#8600, #8176) [@ChrisTom-94] +- Examples: + - Examples: Made many examples DPI aware by default. + The single-viewport is basically: + - Query monitor DPI scale. Helpers are provided in some backends. + - Call style.ScaleAllSizes() and set style.FontScaleDpi with this factor. + Multi-viewport applications may set both of those flags: + - io.ConfigDpiScaleFonts = true; + - io.ConfigDpiScaleViewports = true; + Which will scale fonts but NOT style padding/spacings/thicknesses yet. + - Examples: Apple+Metal, Apple+OpenGL: add Makefile (CLion opens them nicely). (#8637) [@pthom] + - Examples: DirectX12+Win32: also test for IsIconic() for sleeping since we don't seem to + get a DXGI_STATUS_OCCLUDED signal when minimized. (#8603) [@dooann] ----------------------------------------------------------------------- diff --git a/docs/FAQ.md b/docs/FAQ.md index 8c08b4dd7..0e8ba5c77 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -24,7 +24,7 @@ or view this file with any Markdown viewer. | [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | | **Q&A: Usage** | | **[About the ID Stack system..
Why is my widget not reacting when I click on it?
Why is the wrong widget reacting when I click on one?
How can I have widgets with an empty label?
How can I have multiple widgets with the same label?
How can I have multiple windows with the same label?](#q-about-the-id-stack-system)** | -| [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| +| [How can I display an image?](#q-how-can-i-display-an-image)
[What are ImTextureID/ImTextureRef?](#q-what-are-imtextureidimtextureref)| | [How can I use maths operators with ImVec2?](#q-how-can-i-use-maths-operators-with-imvec2) | | [How can I use my own maths types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-maths-types-instead-of-imvec2imvec4) | | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | @@ -161,7 +161,8 @@ Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-lik ### Q: I integrated Dear ImGui in my engine and little squares are showing instead of text... Your renderer backend is not using the font texture correctly or it hasn't been uploaded to the GPU. -- If this happens using the standard backends: A) have you modified the font atlas after `ImGui_ImplXXX_NewFrame()`? B) maybe the texture failed to upload, which **can if your texture atlas is too big**. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). +- If this happens using standard backends (before 1.92): A) have you modified the font atlas after `ImGui_ImplXXX_NewFrame()`? B) maybe the texture failed to upload, which **can if your texture atlas is too big**. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). +- If this happens using standard backends (after 1.92): please report. - If this happens with a custom backend: make sure you have uploaded the font texture to the GPU, that all shaders are rendering states are setup properly (e.g. texture is bound). Compare your code to existing backends and use a graphics debugger such as [RenderDoc](https://renderdoc.org) to debug your rendering states. ##### [Return to Index](#index) @@ -375,23 +376,49 @@ node open/closed state differently. See what makes more sense in your situation! --- -### Q: How can I display an image? What is ImTextureID, how does it work? +### Q: How can I display an image? +### Q: What are ImTextureID/ImTextureRef? -Short explanation: +**Short explanation:** - Refer to [Image Loading and Displaying Examples](https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples) on the [Wiki](https://github.com/ocornut/imgui/wiki). - You may use functions such as `ImGui::Image()`, `ImGui::ImageButton()` or lower-level `ImDrawList::AddImage()` to emit draw calls that will use your own textures. - Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as an opaque ImTextureID value. - By default ImTextureID can store up to 64-bits. You may `#define` it to a custom type/structure if you need. - Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason), but the examples linked above may be useful references. +**Details:** + +1.92 introduced `ImTextureRef` in June 2025. +- Most drawing functions using ImTextureID were changed to use ImTextureRef. +- We intentionally do not provide an implicit ImTextureRef -> ImTextureID cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering. + +**ImTextureID = backend specific, low-level identifier for a texture uploaded in GPU/graphics system.** +- When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint`; Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.). +- User may submit their own textures to e.g. ImGui::Image() function by passing the same type. +- During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside a ImTextureRef, which is stored inside ImDrawCmd. +- Compile-time type configuration: + - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file. + - This can be whatever to you want it to be! read the FAQ entry about textures for details. + - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various constructors if you like. You will need to implement ==/!= operators. + +**ImTextureRef = higher-level identifier for a texture.** +- The identifier is valid even before the texture has been uploaded to the GPU/graphics system. +- This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`. +- This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering. + - When a texture is created by user code (e.g. custom images), we directly stores the low-level `ImTextureID`. + - When a texture is created by the backend, we stores a `ImTextureData*` which becomes an indirection to extract the `ImTextureID` value during rendering, after texture upload has happened. + - There is no constructor to create a `ImTextureID` from a `ImTextureData*` as we don't expect this to be useful to the end-user, and it would be erroneously called by many legacy code. + - If you want to bind the current atlas when using custom rectangle, you can use `io.Fonts->TexRef`. + - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g. `inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; }` + **Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.** Long explanation: - Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices. At the end of the frame, those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code to render them is generally fairly short (a few dozen lines). In the examples/ folder, we provide functions for popular graphics APIs (OpenGL, DirectX, etc.). - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API. - We carry the information to identify a "texture" in the ImTextureID type. +We carry the information to identify a "texture" in the ImTextureID type, which itself tends to be stored inside a ImTextureRef. ImTextureID default to ImU64 aka 8 bytes worth of data: just enough to store one pointer or integer of your choice. -Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely passes ImTextureID values until they reach your rendering function. +Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely passes values until they reach your rendering function. - In the [examples/](https://github.com/ocornut/imgui/tree/master/examples) backends, for each graphics API we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: ```cpp OpenGL: @@ -539,30 +566,49 @@ ImGui::End(); ### Q: How should I handle DPI in my application? -The short answer is: obtain the desired DPI scale, load your fonts resized with that scale (always round down fonts size to the nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. +Since 1.92 (June 2025) fonts may be dynamically used at any size. -Your application may want to detect DPI change and reload the fonts and reset style between frames. +**Scaling fonts** + +To change font size: +```cpp +ImGui::PushFontSize(42.0f); +``` +To change font and font size: +```cpp +ImGui::PushFont(new_font, 42.0f); +``` +To scale all fonts: +```cpp +style.FontScaleDpi = 2.0f; +``` +In `docking` branch or with multi-viewports: +```cpp +io.ConfigDpiScaleFonts = true; // [Experimental] Automatically overwrite style.FontScaleDpi in Begin() when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now. +io.ConfigDpiScaleViewports = true; // [Experimental] Scale Dear ImGui and Platform Windows when Monitor DPI changes. +``` + +**Scaling style** (paddings, spacings, thicknesses) + +This is still massively work in progress, expect turbulence. +Style values are currently not easily scalable dynamically. +For single viewport application you can call once: +```cpp +style.ScaleAllSizes(factor); // call once! +``` +If you need to change the scaling factor, it is currently most practical to reset the style and call this again with a new value. Your UI code should avoid using hardcoded constants for size and positioning. Prefer to express values as multiple of reference values such as `ImGui::GetFontSize()` or `ImGui::GetFrameHeight()`. So e.g. instead of seeing a hardcoded height of 500 for a given item/window, you may want to use `30*ImGui::GetFontSize()` instead. -Down the line Dear ImGui will provide a variety of standardized reference values to facilitate using this. +Down the line Dear ImGui will provide a variety of standardized reference values to facilitate using this. This is expected to happen during subsequent 1.92.x releases. -Applications in the `examples/` folder are not DPI aware partly because they are unable to load a custom font from the file-system (may change that in the future). +Applications in the `examples/` folder are partly DPI aware but they are unable to load a custom font from the file-system, so they look ugly (may change that in the future). -The reason DPI is not auto-magically solved in stock examples is that we don't yet have a satisfying solution for the "multi-dpi" problem (using the `docking` branch: when multiple viewport windows are over multiple monitors using different DPI scales). The current way to handle this on the application side is: -- Create and maintain one font atlas per active DPI scale (e.g. by iterating `platform_io.Monitors[]` before `NewFrame()`). -- Hook `platform_io.OnChangedViewport()` to detect when a `Begin()` call makes a Dear ImGui window change monitor (and therefore DPI). -- In the hook: swap atlas, swap style with correctly sized one, and remap the current font from one atlas to the other (you may need to maintain a remapping table of your fonts at varying DPI scales). +The reason DPI is not auto-magically solved in stock examples is that we don't yet have a satisfying solution for the "multi-dpi" problem (using the `docking` branch: when multiple viewport windows are over multiple monitors using different DPI scales) specifically for the `ImGuiStyle` structure. Fonts are however now perfectly scalable. -This approach is relatively easy and functional but comes with two issues: -- It's not possibly to reliably size or position a window ahead of `Begin()` without knowing on which monitor it'll land. -- Style override may be lost during the `Begin()` call crossing monitor boundaries. You may need to do some custom scaling mumbo-jumbo if you want your `OnChangedViewport()` handler to preserve style overrides. - -Please note that if you are not using multi-viewports with multi-monitors using different DPI scales, you can ignore that and use the simpler technique recommended at the top. - -On Windows, in addition to scaling the font size (make sure to round to an integer) and using `style.ScaleAllSizes()`, you will need to inform Windows that your application is DPI aware. If this is not done, Windows will scale the application window and the UI text will be blurry. Potential solutions to indicate DPI awareness on Windows are: - -- For SDL2: the flag `SDL_WINDOW_ALLOW_HIGHDPI` needs to be passed to `SDL_CreateWindow()`. +**On Windows, you need to inform Windows that your application is DPI aware!** +If this is not done, Windows will scale the application window and the UI text will be blurry. Potential solutions to indicate DPI awareness on Windows are: +- For SDL2: the flag `SDL_WINDOW_ALLOW_HIGHDPI` needs to be passed to `SDL_CreateWindow()` + call `::SetProcessDPIAware()`. - For SDL3: the flag `SDL_WINDOW_HIGH_PIXEL_DENSITY` needs to be passed to `SDL_CreateWindow()`. - For GLFW: this is done automatically. - For other Windows projects with other backends, or wrapper projects: @@ -615,9 +661,12 @@ Use the font atlas to pack them into a single texture. Read [docs/FONTS.md](http --- ### Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? -When loading a font, pass custom Unicode ranges to specify the glyphs to load. +Since 1.92 (June 2025) and with an updated backend, it is not necessary to specify glyph ranges at all. + +Before 1.92, when loading a font, pass custom Unicode ranges to specify the glyphs to load. ```cpp +// [BEFORE 1.92] // Add default Japanese ranges io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, nullptr, io.Fonts->GetGlyphRangesJapanese()); @@ -641,8 +690,8 @@ Text input: it is up to your application to pass the right character code by cal The applications in examples/ are doing that. Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode). You may also use `MultiByteToWideChar()` or `ToUnicode()` to retrieve Unicode codepoints from MultiByte characters or keyboard state. -Windows: if your language is relying on an Input Method Editor (IME), you can write your HWND to ImGui::GetMainViewport()->PlatformHandleRaw -for the default implementation of GetPlatformIO().Platform_SetImeDataFn() to set your Microsoft IME position correctly. +Windows: if your language is relying on an Input Method Editor (IME), you can write your HWND to `ImGui::GetMainViewport()->PlatformHandleRaw` +for the default implementation of `GetPlatformIO().Platform_SetImeDataFn()` to set your Microsoft IME position correctly. ##### [Return to Index](#index) diff --git a/docs/FONTS.md b/docs/FONTS.md index baa53adde..7ed8fe026 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -12,7 +12,7 @@ In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) fo ## Index - [Troubleshooting](#troubleshooting) -- [New! Dynamic Fonts system in 1.92 (March 2025)](#new-dynamic-fonts-system-in-192-march-2025) +- [New! Dynamic Fonts system in 1.92 (June 2025)](#new-dynamic-fonts-system-in-192-june-2025) - [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application) - [Fonts Loading Instructions](#fonts-loading-instructions) - [Loading Font Data from Memory](#loading-font-data-from-memory) @@ -72,11 +72,11 @@ Future versions of Dear ImGui should solve this problem. --------------------------------------- -## New! Dynamic Fonts system in 1.92 (March 2025+) +## New! Dynamic Fonts system in 1.92 (June 2025) -v1.92 will introduce a newer, dynamic font system. It requires backend to support the `ImGuiBackendFlags_HasTextures` feature: +v1.92 introduces a newer, dynamic font system. It requires backend to support the `ImGuiBackendFlags_HasTextures` feature: - Users of icons, Asian and non-English languages do not need to pre-build all glyphs ahead of time. Saving on loading time, memory, and also reducing issues with missing glyphs. Specifying glyph ranges is not needed anymore. -- PushFontSize() may be used anytime to change font size. +- `PushFontSize()` may be used anytime to change font size. - Packing custom rectangles is more convenient as pixels may be written to immediately. - Any update to fonts previously required backend specific calls to re-upload the texture, and said calls were not portable across backends. It is now possible to scale fonts etc. in a way that doesn't require you to make backend-specific calls. - It is possible to plug a custom loader/backend to any font source. @@ -105,6 +105,12 @@ io.Fonts->AddFontDefault(); ``` **Load .TTF/.OTF file with:** +🆕 **Since 1.92, with an up to date backend: passing a size is not necessary** +```cpp +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontFromFileTTF("font.ttf"); +``` +**Before 1.92, or without an up to date backend:** ```cpp ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); @@ -115,8 +121,8 @@ If you get an assert stating "Could not load font file!", your font filename is ```cpp // Init ImGuiIO& io = ImGui::GetIO(); -ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); -ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); +ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf",); +ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf"); ``` In your application loop, select which font to use: @@ -135,6 +141,18 @@ ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); ``` **Combine multiple fonts into one:** + +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary.** +```cpp +// Load a first font +ImFont* font = io.Fonts->AddFontDefault(); +ImFontConfig config; +config.MergeMode = true; +io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 0.0f, &config); // Merge into first font to add e.g. Asian characters +io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 0.0f, &config); // Merge into first font to add Icons +io.Fonts->Build(); +``` +**Before 1.92, or without an up to date backend:** ```cpp // Load a first font ImFont* font = io.Fonts->AddFontDefault(); @@ -152,8 +170,7 @@ io.Fonts->Build(); **Add a fourth parameter to bake specific font ranges only:** -🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary. All the GetGlyphRangesXXX() functions are marked obsolete.** - +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary. All the GetGlyphRangesXXX() functions are marked obsolete.** ```cpp // Basic Latin, Extended Latin io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesDefault()); @@ -169,14 +186,12 @@ See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create yo **Example loading and using a Japanese font:** 🆕 **Since 1.92, with an up to date backend:** - ```cpp ImGuiIO& io = ImGui::GetIO(); -io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f); +io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf"); ``` **Before 1.92, or without an up to date backend:** - ```cpp ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); @@ -248,14 +263,24 @@ To refer to the icon UTF-8 codepoints from your C++ code, you may use those head So you can use `ICON_FA_SEARCH` as a string that will render as a "Search" icon. -🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary. You can omit this parameter.** - +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary. You can omit this parameter.** Example Setup: ```cpp // Merge icons into default tool font #include "IconsFontAwesome.h" ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontDefault(); +ImFontConfig config; +config.MergeMode = true; +config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced +io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config); +``` +**Before 1.92:** +```cpp +// Merge icons into default tool font +#include "IconsFontAwesome.h" +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontDefault(); ImFontConfig config; config.MergeMode = true; @@ -275,7 +300,8 @@ See Links below for other icons fonts and related tools. **Monospace Icons?** -To make your icon look more monospace and facilitate alignment, you may want to set the ImFontConfig::GlyphMinAdvanceX value when loading an icon font. +To make your icon look more monospace and facilitate alignment, you may want to set the `ImFontConfig::GlyphMinAdvanceX` value when loading an icon font. +If you `GlyphMinAdvanceX` you need to pass a `font_size` to `AddFontXXX()` calls, as the MinAdvanceX value will be specified for the given size and scaled otherwise. **Screenshot** @@ -288,8 +314,8 @@ Here's an application using icons ("Avoyd", https://www.avoyd.com): ## Using FreeType Rasterizer (imgui_freetype) -- Dear ImGui uses imstb\_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. -- There is an implementation of the ImFontAtlas builder using FreeType that you can use in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. +- Dear ImGui uses [stb_truetype.h](https://github.com/nothings/stb/) to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. +- You can however use `imgui_freetype.cpp` from the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. - FreeType supports auto-hinting which tends to improve the readability of small fonts. - Read documentation in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. - Correct sRGB space blending will have an important effect on your font rendering quality. @@ -312,10 +338,9 @@ Here's an application using icons ("Avoyd", https://www.avoyd.com): io.Fonts->AddFontFromFileTTF("../../../imgui_dev/data/fonts/NotoSans-Regular.ttf", 16.0f); static ImWchar ranges[] = { 0x1, 0x1FFFF, 0 }; static ImFontConfig cfg; -cfg.OversampleH = cfg.OversampleV = 1; cfg.MergeMode = true; -cfg.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_LoadColor; -io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg, ranges); +cfg.FontLoaderFlags |= ImGuiFreeTypeLoaderFlags_LoadColor; +io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg); ``` ##### [Return to Index](#index) @@ -348,7 +373,7 @@ io.Fonts->Build(); // Build the atlas while 🆕 **Since 1.92, with an up to date backend: this system has been revamped.** TL;DR; With the new system, it is recommended that you create a custom `ImFontLoader` and register your fonts with it. -`AddCustomRectFontGlyph()` has been obsolete because its API does not make much sense with resizable fonts. +`AddCustomRectFontGlyph()` has been obsoleted because its API does not make much sense with resizable fonts. You can ask questions in [#8466](https://github.com/ocornut/imgui/issues/8466). diff --git a/imgui.h b/imgui.h index 1d27953f2..de0d06645 100644 --- a/imgui.h +++ b/imgui.h @@ -314,18 +314,17 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // ImTextureID = backend specific, low-level identifier for a texture uploaded in GPU/graphics system. // [Compile-time configurable type] -// Overview: // - When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value. -// (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint'; +// (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint`; // Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.). // - User may submit their own textures to e.g. ImGui::Image() function by passing the same type. -// - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside -// ImTextureRef, which is stored inside ImDrawCmd. -// Configuring the type: -// - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file. -// - This can be whatever to you want it to be! read the FAQ entry about textures for details. -// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various -// constructors if you like. You will need to implement ==/!= operators. +// - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside a +// ImTextureRef, which is stored inside a ImDrawCmd. +// - Compile-time type configuration: +// - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - This can be whatever to you want it to be! read the FAQ entry about textures for details. +// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various +// constructors if you like. You will need to implement ==/!= operators. // History: // - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requirig 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. // - In v1.92.0 (2025/XX/XX): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef @@ -340,15 +339,15 @@ typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or // ImTextureRef = higher-level identifier for a texture. // The identifier is valid even before the texture has been uploaded to the GPU/graphics system. -// This is what gets passed to functions such as ImGui::Image(), ImDrawList::AddImage(). -// This is what gets stored in draw commands (ImDrawCmd) to identify a texture during rendering. +// This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`. +// This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering. // - When a texture is created by user code (e.g. custom images), we directly stores the low-level ImTextureID. // - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection // to extract the ImTextureID value during rendering, after texture upload has happened. // - There is no constructor to create a ImTextureID from a ImTextureData* as we don't expect this // to be useful to the end-user, and it would be erroneously called by many legacy code. // - If you want to bind the current atlas when using custom rectangle, you can use io.Fonts->TexRef. -// - Binding generators for languages such as C (which don't have constructors), should provide a helper: +// - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g. // inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; } // In 1.92 we changed most drawing functions using ImTextureID to use ImTextureRef. // We intentionally do not provide an implicit ImTextureRef -> ImTextureID cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering. From df068ce11eeee0566090fcdf3fbfab807cf95808 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 18:30:18 +0200 Subject: [PATCH 1076/2359] Various/misc fixes following back-and-forth dynamic_fonts->master->docking merges. Added missing API BREAKING CHANGES section. --- backends/imgui_impl_dx12.cpp | 9 ----- backends/imgui_impl_opengl2.cpp | 2 +- backends/imgui_impl_sdlgpu3.cpp | 2 +- backends/imgui_impl_sdlgpu3.h | 2 +- backends/imgui_impl_sdlrenderer2.cpp | 2 +- backends/imgui_impl_sdlrenderer2.h | 2 +- backends/imgui_impl_sdlrenderer3.cpp | 2 +- backends/imgui_impl_sdlrenderer3.h | 2 +- backends/imgui_impl_wgpu.cpp | 4 ++- backends/imgui_impl_wgpu.h | 4 ++- docs/CHANGELOG.txt | 14 ++++---- imgui.cpp | 51 ++++++++++++++++++++++++++++ 12 files changed, 71 insertions(+), 25 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index ea7e3b881..e3bcda195 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -820,15 +820,6 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. - if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) - ImGui_ImplDX12_InitPlatformInterface(); - - // Create a dummy ImGui_ImplDX12_ViewportData holder for the main viewport, - // Since this is created and managed by the application, we will only use the ->Resources[] fields. - ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - main_viewport->RendererUserData = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight); ->>>>>>> dda12fbd9a (Backends: DirectX12: added ImGuiBackendFlags_RendererHasTextures support.) - #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (init_info->SrvDescriptorAllocFn == nullptr) { diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp index 5e9df1715..afcafe826 100644 --- a/backends/imgui_impl_opengl2.cpp +++ b/backends/imgui_impl_opengl2.cpp @@ -3,7 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! -// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // Missing features or Issues: // [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 92515602b..0ad9e2c30 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -4,7 +4,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). -// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index 380855b29..826767ac5 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -4,7 +4,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). -// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index dbdeb5c11..bcc4404ff 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -12,7 +12,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). -// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h index cf127c1f7..a62e60927 100644 --- a/backends/imgui_impl_sdlrenderer2.h +++ b/backends/imgui_impl_sdlrenderer2.h @@ -12,7 +12,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). -// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index ef6f0441c..77b5bc059 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -12,7 +12,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). -// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h index 170560fdc..618cc2430 100644 --- a/backends/imgui_impl_sdlrenderer3.h +++ b/backends/imgui_impl_sdlrenderer3.h @@ -12,7 +12,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). -// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 3187be29a..3a182ccd2 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -3,9 +3,11 @@ // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.) // Implemented features: -// [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. +// Missing features or Issues: +// [ ] Renderer: Missing texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 7efb02afe..1da208f00 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -10,9 +10,11 @@ //#define IMGUI_IMPL_WEBGPU_BACKEND_WGPU // Implemented features: -// [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. +// Missing features or Issues: +// [ ] Renderer: Missing texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2a16008f6..8a49b9a04 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,11 +63,11 @@ Breaking changes: - With a legacy backend (< 1.92): - Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. - This already worked before, but is now pretty much required. - - With a new backend (1.92+) + - With a new backend (1.92+), + - This should be all automatic. - FramebufferScale is automatically used to set current font RasterizerDensity. - FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch. - - So this should be all automatic. - Fonts: **IMPORTANT** on Font Sizing: - Before 1.92, fonts were of a single size. They can now be dynamically sized. - PushFont() API now has an optional size parameter. PushFontSize() was also added. @@ -75,9 +75,9 @@ Breaking changes: - Before 1.92: ImGui::PushFont() always used font "default" size specified in AddFont() call. - Since 1.92: ImGui::PushFont() preserve the current font size which is a shared value. - To use old behavior: - - use 'ImGui::PushFont(font, font->LegacySize)' at call site. + - use 'ImGui::PushFont(font, font->LegacySize)' at call site (preferred). - or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call - (not desirable as it requires e.g. third-party code to be aware of it). + (not desirable as it requires e.g. all third-party code to be aware of it). - ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). - Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. @@ -134,7 +134,7 @@ Breaking changes: - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size. - - Things moved from ImFont to ImFontBaked: + - Fields moved from ImFont to ImFontBaked: - ImFont::IndexAdvanceX[] -> ImFontBaked::IndexAdvanceX[] - ImFont::Glyphs[] -> ImFontBaked::Glyphs[] - ImFont::Ascent, Descent -> ImFontBaked::Ascent, Descent @@ -155,9 +155,9 @@ Breaking changes: - if you used runtime imgui_freetype selection rather than the default compile-time option provided by IMGUI_ENABLE_FREETYPE: - renamed/reworked ImFontBuilderIO into ImFontLoader, - - renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader(). + - renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader() - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() - - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader() + - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader(); - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). - Fonts: (users of custom rectangles) - Renamed AddCustomRectRegular() to AddCustomRect(). (#8466) diff --git a/imgui.cpp b/imgui.cpp index b9b5fbbc1..74c135ddf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -449,6 +449,57 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/06/11 (1.92.0) - THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, BUT INEVITABLY SOME USERS WILL BE AFFECTED. + IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/ + As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be part of subsequent releases (1.92.1+). + If you are updating from an old version, and expecting a massive or difficult update, consider first updating to 1.91.9 to reduce the amount of changes. + - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this! + - Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f): + This WILL NOT map correctly to the new system! Because font will rasterize as requested size. + - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required. + - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch. + - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized. + - PushFont() API now has an optional size parameter. PushFontSize() was also added. + - Before 1.92: ImGui::PushFont() always used font "default" size specified in AddFont() call. + - Since 1.92: ImGui::PushFont() preserve the current font size which is a shared value. + - To use old behavior: (A) use 'ImGui::PushFont(font, font->LegacySize)' at call site (preferred). (B) Set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call (not desirable as it requires e.g. third-party code to be aware of it). + - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). + - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. + - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded(). + - Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID(), IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete). + - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling. + - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese(). + - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327) + - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to set the atlas->RendererHasTextures field and call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. + - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFontSize(style.FontSizeBase * factor)' or to manipulate other scaling factors. + - Fonts: obsoleted ImFont::Scale which is not useful anymore. + - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: + - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef. + - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[] + - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. + - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size. + - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance(). + - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to access font data for current font at current font size (and you may use font->GetFontBaked(size) to access it for any other size.) + - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags. + If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader(). + - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() + - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader() + - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV(). + - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h. + - old: + const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id); + ImVec2 uv0, uv1; + atlas->GetCustomRectUV(r, &uv0, &uv1); + ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1); + - new; + ImFontAtlasRect r; + atlas->GetCustomRect(custom_rect_id, &r); + ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1); + - We added a redirecting typedef but haven't attempted to magically redirect the field names, as this API is rarely used and the fix is simple. + - Obsoleted AddCustomRectFontGlyph() as the API does not make sense for scalable fonts. Kept existing function which uses the font "default size" (Sources[0]->LegacySize). Added a helper AddCustomRectFontGlyphForSize() which is immediately marked obsolete, but can facilitate transitioning old code. + - Prefer adding a font source (ImFontConfig) using a custom/procedural loader. + - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). + - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more. - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition() - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....); - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....); From 895bff6524549ccb3fb1136aa23ad130b68d0a3e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 19:16:50 +0200 Subject: [PATCH 1077/2359] Removed unneeded check in RenderText() loop + disable static analyzer false-positive warnings. --- imgui_draw.cpp | 6 +++--- imstb_truetype.h | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 195f5bece..2e9a0b645 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2874,7 +2874,7 @@ void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data } } } - else if (data->Format == ImTextureFormat_RGBA32) + else if (data->Format == ImTextureFormat_RGBA32) //-V547 { for (int ny = data->Height; ny > 0; ny--, pixels += pitch) { @@ -5631,8 +5631,8 @@ begin: } const ImFontGlyph* glyph = baked->FindGlyph((ImWchar)c); - if (glyph == NULL) - continue; + //if (glyph == NULL) + // continue; float char_width = glyph->AdvanceX * scale; if (glyph->Visible) diff --git a/imstb_truetype.h b/imstb_truetype.h index 976f09cb9..cf33289f6 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -4516,8 +4516,8 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex q2[0] = (float)x2; q2[1] = (float)y2; if (equal(q0,q1) || equal(q1,q2)) { - x0 = (int)verts[i-1].x; - y0 = (int)verts[i-1].y; + x0 = (int)verts[i-1].x; //-V1048 + y0 = (int)verts[i-1].y; //-V1048 x1 = (int)verts[i ].x; y1 = (int)verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { From 7a42233d43dfab63de340e8b187d24c3c55e2ce7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Jun 2025 20:47:17 +0200 Subject: [PATCH 1078/2359] imgui_freetype: fixed using legacy names. --- misc/freetype/imgui_freetype.cpp | 44 ++++++++++++++++---------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 35a277f7c..ae87f63f9 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -7,7 +7,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025/XX/XX: refactored for the new ImFontLoader architecture, and ImGuiBackendFlags_RendererHasTextures support. +// 2025/06/11: refactored for the new ImFontLoader architecture, and ImGuiBackendFlags_RendererHasTextures support. // 2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927) // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics. // 2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG'. (#6591) @@ -185,26 +185,26 @@ bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfi UserFlags = (ImGuiFreeTypeLoaderFlags)(src->FontLoaderFlags | extra_font_loader_flags); LoadFlags = 0; - if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0) + if ((UserFlags & ImGuiFreeTypeLoaderFlags_Bitmap) == 0) LoadFlags |= FT_LOAD_NO_BITMAP; - if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting) + if (UserFlags & ImGuiFreeTypeLoaderFlags_NoHinting) LoadFlags |= FT_LOAD_NO_HINTING; else src->PixelSnapH = true; // FIXME: A bit weird to do this this way. - if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint) + if (UserFlags & ImGuiFreeTypeLoaderFlags_NoAutoHint) LoadFlags |= FT_LOAD_NO_AUTOHINT; - if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint) + if (UserFlags & ImGuiFreeTypeLoaderFlags_ForceAutoHint) LoadFlags |= FT_LOAD_FORCE_AUTOHINT; - if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting) + if (UserFlags & ImGuiFreeTypeLoaderFlags_LightHinting) LoadFlags |= FT_LOAD_TARGET_LIGHT; - else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting) + else if (UserFlags & ImGuiFreeTypeLoaderFlags_MonoHinting) LoadFlags |= FT_LOAD_TARGET_MONO; else LoadFlags |= FT_LOAD_TARGET_NORMAL; - if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor) + if (UserFlags & ImGuiFreeTypeLoaderFlags_LoadColor) LoadFlags |= FT_LOAD_COLOR; return true; @@ -246,9 +246,9 @@ static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_F #endif // IMGUI_ENABLE_FREETYPE_LUNASVG // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting) - if (src_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bold) + if (src_data->UserFlags & ImGuiFreeTypeLoaderFlags_Bold) FT_GlyphSlot_Embolden(slot); - if (src_data->UserFlags & ImGuiFreeTypeBuilderFlags_Oblique) + if (src_data->UserFlags & ImGuiFreeTypeLoaderFlags_Oblique) { FT_GlyphSlot_Oblique(slot); //FT_BBox bbox; @@ -442,7 +442,7 @@ bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL) const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; FT_Size_RequestRec req; - req.type = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; + req.type = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; req.width = 0; req.height = (uint32_t)(size * 64 * rasterizer_density); req.horiResolution = 0; @@ -497,7 +497,7 @@ bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src // Render glyph into a bitmap (currently held by FreeType) FT_Face face = bd_font_data->FtFace; FT_GlyphSlot slot = face->glyph; - FT_Render_Mode render_mode = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL; + FT_Render_Mode render_mode = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Monochrome) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL; FT_Error error = FT_Render_Glyph(slot, render_mode); const FT_Bitmap* ft_bitmap = &slot->bitmap; if (error != 0 || ft_bitmap == nullptr) @@ -590,16 +590,16 @@ void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* u bool ImGuiFreeType::DebugEditFontLoaderFlags(unsigned int* p_font_loader_flags) { bool edited = false; - edited |= ImGui::CheckboxFlags("NoHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_NoHinting); - edited |= ImGui::CheckboxFlags("NoAutoHint", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_NoAutoHint); - edited |= ImGui::CheckboxFlags("ForceAutoHint",p_font_loader_flags, ImGuiFreeTypeBuilderFlags_ForceAutoHint); - edited |= ImGui::CheckboxFlags("LightHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_LightHinting); - edited |= ImGui::CheckboxFlags("MonoHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_MonoHinting); - edited |= ImGui::CheckboxFlags("Bold", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Bold); - edited |= ImGui::CheckboxFlags("Oblique", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Oblique); - edited |= ImGui::CheckboxFlags("Monochrome", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Monochrome); - edited |= ImGui::CheckboxFlags("LoadColor", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_LoadColor); - edited |= ImGui::CheckboxFlags("Bitmap", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Bitmap); + edited |= ImGui::CheckboxFlags("NoHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_NoHinting); + edited |= ImGui::CheckboxFlags("NoAutoHint", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_NoAutoHint); + edited |= ImGui::CheckboxFlags("ForceAutoHint",p_font_loader_flags, ImGuiFreeTypeLoaderFlags_ForceAutoHint); + edited |= ImGui::CheckboxFlags("LightHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_LightHinting); + edited |= ImGui::CheckboxFlags("MonoHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_MonoHinting); + edited |= ImGui::CheckboxFlags("Bold", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Bold); + edited |= ImGui::CheckboxFlags("Oblique", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Oblique); + edited |= ImGui::CheckboxFlags("Monochrome", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Monochrome); + edited |= ImGui::CheckboxFlags("LoadColor", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_LoadColor); + edited |= ImGui::CheckboxFlags("Bitmap", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Bitmap); return edited; } From a0b3eceec7854be4a32e19ff21397738c06517fe Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 11:02:32 +0200 Subject: [PATCH 1079/2359] Fixed using IMGUI_DISABLE_DEMO_WINDOWS without IMGUI_DISABLE_DEBUG_TOOLS and without linking with imgui_demo.cpp --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 36 +++++++++++++++++++++++++++++++++++- imgui_demo.cpp | 39 +++------------------------------------ 3 files changed, 40 insertions(+), 37 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8a49b9a04..7cda2db6c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -290,6 +290,8 @@ Other changes: to be a valid low-level texture identifier. - Debug Tools: Fonts section: add font preview, add "Remove" button, add "Load all glyphs" button, add selection to change font backend when both are compiled in. +- Special thanks for fonts/texture related feedback to: @thedmd, @ShironekoBen, @rodrigorc, + @pathogendavid, @itamago, @rokups, @DucaRii, @Aarkham, @cyfewlp. - IO: variations in analog-only components of gamepad events do not interfere with trickling of mouse position events (#4921, #8508) diff --git a/imgui.cpp b/imgui.cpp index 74c135ddf..90f9ecd2d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15921,7 +15921,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) if (loader_current == loader_freetype) { unsigned int loader_flags = atlas->FontLoaderFlags; - Text("Shared FreeType Loader Flags: 0x%08", loader_flags); + Text("Shared FreeType Loader Flags: 0x%08X", loader_flags); if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags)) { for (ImFont* font : atlas->Fonts) @@ -17726,6 +17726,40 @@ void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {} #endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS +#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) +{ + ImGuiIO& io = GetIO(); + ImFont* font_current = GetFont(); + if (BeginCombo(label, font_current->GetDebugName())) + { + for (ImFont* font : io.Fonts->Fonts) + { + PushID((void*)font); + if (Selectable(font->GetDebugName(), font == font_current)) + io.FontDefault = font; + if (font == font_current) + SetItemDefaultFocus(); + PopID(); + } + EndCombo(); + } + SameLine(); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + MetricsHelpMarker( + "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" + "- Read FAQ and docs/FONTS.md for more details."); + else + MetricsHelpMarker( + "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" + "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" + "- Read FAQ and docs/FONTS.md for more details.\n" + "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); +} +#endif // #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) + //----------------------------------------------------------------------------- // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index cd48ee0ff..0b7c45aca 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8171,43 +8171,10 @@ void ImGui::ShowAboutWindow(bool* p_open) //----------------------------------------------------------------------------- // [SECTION] Style Editor / ShowStyleEditor() //----------------------------------------------------------------------------- -// - ShowFontSelector() // - ShowStyleSelector() // - ShowStyleEditor() //----------------------------------------------------------------------------- -// 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) -{ - ImGuiIO& io = ImGui::GetIO(); - ImFont* font_current = ImGui::GetFont(); - if (ImGui::BeginCombo(label, font_current->GetDebugName())) - { - for (ImFont* font : io.Fonts->Fonts) - { - ImGui::PushID((void*)font); - if (ImGui::Selectable(font->GetDebugName(), font == font_current)) - io.FontDefault = font; - if (font == font_current) - ImGui::SetItemDefaultFocus(); - ImGui::PopID(); - } - ImGui::EndCombo(); - } - ImGui::SameLine(); - if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) - HelpMarker( - "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" - "- Read FAQ and docs/FONTS.md for more details."); - else - HelpMarker( - "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" - "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" - "- Read FAQ and docs/FONTS.md for more details.\n" - "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); -} - // Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. // Here we use the simplified Combo() api that packs items into a single literal string. // Useful for quick combo boxes where the choices are known locally. @@ -10808,9 +10775,9 @@ void ImGui::ShowAboutWindow(bool*) {} void ImGui::ShowDemoWindow(bool*) {} void ImGui::ShowUserGuide() {} void ImGui::ShowStyleEditor(ImGuiStyle*) {} -bool ImGui::ShowStyleSelector(const char* label) { return false; } -void ImGui::ShowFontSelector(const char* label) {} +bool ImGui::ShowStyleSelector(const char*) { return false; } +void ImGui::ShowFontSelector(const char*) {} -#endif +#endif // #ifndef IMGUI_DISABLE_DEMO_WINDOWS #endif // #ifndef IMGUI_DISABLE From f6fc166584783b8a886f102ea8623a24115ca5c4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 11:07:08 +0200 Subject: [PATCH 1080/2359] TreeNode: fixed runtime asan warning (#2920) imgui_widgets.cpp:6923:52: runtime error: shift exponent -1 is negative --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index cdca228c4..ba35e531b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6914,7 +6914,7 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - if ((window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1))) == 0) + if (window->DC.TreeDepth == 0 || (window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1))) == 0) return; ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; From 1ce75e2bcad6f85efc3a91a795837ed3489ed9dc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 11:25:15 +0200 Subject: [PATCH 1081/2359] Fixed duplicate symbols in some compile-time configurations. --- imgui_demo.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0b7c45aca..899932066 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10776,7 +10776,6 @@ void ImGui::ShowDemoWindow(bool*) {} void ImGui::ShowUserGuide() {} void ImGui::ShowStyleEditor(ImGuiStyle*) {} bool ImGui::ShowStyleSelector(const char*) { return false; } -void ImGui::ShowFontSelector(const char*) {} #endif // #ifndef IMGUI_DISABLE_DEMO_WINDOWS From 41f4acfb4ff259d97eecdf031b44c4853e54e8fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 11:44:11 +0200 Subject: [PATCH 1082/2359] Fonts: add has_textures parameters to ImFontAtlasUpdateNewFrame(). --- docs/CHANGELOG.txt | 4 ++-- imgui.cpp | 7 +++---- imgui_draw.cpp | 11 ++++++----- imgui_internal.h | 2 +- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7cda2db6c..20377e2aa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -115,8 +115,8 @@ Breaking changes: to 4096 but that limit isn't necessary anymore, and Renderer_TextureMaxWidth covers this) However you may set TexMinWidth = TexMaxWidth for the same effect. - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on - ImGuiContext to create one, you'll need to set the atlas->RendererHasTextures field - and call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. + ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. + An assert will trigger if you don't. - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using PushFontSize(style.FontSizeBase * factor) or to manipulate other scaling factors. - Fonts: obsoleted ImFont::Scale which is not useful anymore. diff --git a/imgui.cpp b/imgui.cpp index 90f9ecd2d..f57c305b4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -470,7 +470,7 @@ CODE - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling. - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese(). - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327) - - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to set the atlas->RendererHasTextures field and call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. + - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFontSize(style.FontSizeBase * factor)' or to manipulate other scaling factors. - Fonts: obsoleted ImFont::Scale which is not useful anymore. - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: @@ -5286,13 +5286,12 @@ static void ImGui::UpdateTexturesNewFrame() { if (atlas->OwnerContext == &g) { - atlas->RendererHasTextures = has_textures; - ImFontAtlasUpdateNewFrame(atlas, g.FrameCount); + ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures); } else { IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1 && "If you manage font atlases yourself you need to call ImFontAtlasUpdateNewFrame() on it."); - IM_ASSERT(atlas->RendererHasTextures == has_textures && "If you manage font atlases yourself make sure atlas->RendererHasTextures is set consistently with all contexts using it."); + IM_ASSERT(atlas->RendererHasTextures == has_textures && "If you manage font atlases yourself make sure ImGuiBackendFlags_RendererHasTextures is set consistently with atlas->RendererHasTextures as specified in the ImFontAtlasUpdateNewFrame() call."); } } } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2e9a0b645..cd3d22ef9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2716,12 +2716,13 @@ static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* at } // Called by NewFrame() for atlases owned by a context. -// If you manually manage font atlases, you'll need to call this yourself + ensure atlas->RendererHasTextures is set. -// 'frame_count' needs to be provided because we can gc/prioritize baked fonts based on their age. -// 'frame_count' may not match those of imgui contexts using this atlas, as contexts may be updated as different frequencies. -void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count) +// If you manually manage font atlases, you'll need to call this yourself. +// - 'frame_count' needs to be provided because we can gc/prioritize baked fonts based on their age. +// - 'frame_count' may not match those of all imgui contexts using this atlas, as contexts may be updated as different frequencies. But generally you can use ImGui::GetFrameCount() on one of your context. +void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures) { - IM_ASSERT(atlas->Builder == NULL || atlas->Builder->FrameCount < frame_count); // Protection against being called twice? + IM_ASSERT(atlas->Builder == NULL || atlas->Builder->FrameCount < frame_count); // Protection against being called twice. + atlas->RendererHasTextures = renderer_has_textures; // Check that font atlas was built or backend support texture reload in which case we can build now if (atlas->RendererHasTextures) diff --git a/imgui_internal.h b/imgui_internal.h index b80bf50b6..1d572d5a6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3833,7 +3833,7 @@ IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtl IMGUI_API ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id); IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); -IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count); +IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures); IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex); From 115a8e74c2478d372d09b6ecc2170818fbced396 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 14:18:23 +0200 Subject: [PATCH 1083/2359] Fonts: update misc comments, docs. --- .github/ISSUE_TEMPLATE/issue_template.yml | 2 +- docs/FONTS.md | 3 +- imgui.cpp | 35 +++++++++++++++-------- 3 files changed, 26 insertions(+), 14 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/issue_template.yml b/.github/ISSUE_TEMPLATE/issue_template.yml index 46ed826d5..6ed62493a 100644 --- a/.github/ISSUE_TEMPLATE/issue_template.yml +++ b/.github/ISSUE_TEMPLATE/issue_template.yml @@ -4,7 +4,7 @@ body: - type: markdown attributes: value: | - FOR FIRST-TIME USERS ISSUES COMPILING/LINKING/RUNNING or LOADING FONTS, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions) + FOR FIRST-TIME USERS ISSUES COMPILING/LINKING/RUNNING, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions) For anything else: **we are happy to use 'GitHub Issues' for many types of open-ended questions**. We are encouraging 'Issues' becoming a large, centralized, tagged, cross-referenced database of Dear ImGui contents. Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users. diff --git a/docs/FONTS.md b/docs/FONTS.md index 7ed8fe026..95538f97d 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -105,6 +105,7 @@ io.Fonts->AddFontDefault(); ``` **Load .TTF/.OTF file with:** + 🆕 **Since 1.92, with an up to date backend: passing a size is not necessary** ```cpp ImGuiIO& io = ImGui::GetIO(); @@ -377,7 +378,7 @@ TL;DR; With the new system, it is recommended that you create a custom `ImFontLo You can ask questions in [#8466](https://github.com/ocornut/imgui/issues/8466). -🆕 **Before 1.92:** +**Before 1.92:** As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiFreeTypeBuilderFlags_LoadColor`, you may allocate your own space in the texture atlas and write yourself into it. **(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)** diff --git a/imgui.cpp b/imgui.cpp index f57c305b4..f7d2e7441 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -21,9 +21,10 @@ // - Issues & support ........... https://github.com/ocornut/imgui/issues // - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) -// For first-time users having issues compiling/linking/running/loading fonts: +// For first-time users having issues compiling/linking/running: // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. +// Since 1.92, we encourage font loading question to also be posted in 'Issues'. // Copyright (c) 2014-2025 Omar Cornut // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. @@ -347,12 +348,12 @@ CODE ImGui::Render(); // Update textures - for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + ImDrawData* draw_data = ImGui::GetDrawData(); + for (ImTextureData* tex : *draw_data->Textures) if (tex->Status != ImTextureStatus_OK) MyImGuiBackend_UpdateTexture(tex); // Render dear imgui contents, swap buffers - ImDrawData* draw_data = ImGui::GetDrawData(); MyImGuiBackend_RenderDrawData(draw_data); SwapBuffers(); } @@ -372,25 +373,32 @@ CODE { if (tex->Status == ImTextureStatus_WantCreate) { - // create texture based on tex->Width/Height/Pixels - // call tex->SetTexID() to specify backend-specific identifiers - // tex->Status = ImTextureStatus_OK; + // Width/Height/Pixels> + tex->SetTexID(xxxx); // specify backend-specific ImTextureID identifier + tex->SetStatus(ImTextureStatus_OK); + tex->BackendUserData = xxxx; // store more backend data } if (tex->Status == ImTextureStatus_WantUpdates) { - // update texture blocks based on tex->UpdateRect - // tex->Status = ImTextureStatus_OK; + // UpdateRect> + tex->SetStatus(ImTextureStatus_OK); } if (tex->Status == ImTextureStatus_WantDestroy) { - // destroy texture - // call tex->SetTexID(ImTextureID_Invalid) - // tex->Status = ImTextureStatus_Destroyed; + // + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); } } void MyImGuiBackend_RenderDrawData(ImDrawData* draw_data) { + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + MyImGuiBackend_UpdateTexture(tex); + + // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering. // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize @@ -407,7 +415,10 @@ CODE const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { - pcmd->UserCallback(cmd_list, pcmd); + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + MyEngineResetRenderState(); + else + pcmd->UserCallback(cmd_list, pcmd); } else { From b178fd42862f4314370a32c252c8fbd54eee1127 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 14:55:46 +0200 Subject: [PATCH 1084/2359] Backends: WebGPU: moved sampler creation out of ImGui_ImplWGPU_CreateFontsTexture(). --- backends/imgui_impl_wgpu.cpp | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 3a182ccd2..d5ac95d50 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -597,20 +597,6 @@ static void ImGui_ImplWGPU_CreateFontsTexture() wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size); } - // Create the associated sampler - // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - { - WGPUSamplerDescriptor sampler_desc = {}; - sampler_desc.minFilter = WGPUFilterMode_Linear; - sampler_desc.magFilter = WGPUFilterMode_Linear; - sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear; - sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge; - sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge; - sampler_desc.addressModeW = WGPUAddressMode_ClampToEdge; - sampler_desc.maxAnisotropy = 1; - bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc); - } - // Store our identifier static_assert(sizeof(ImTextureID) >= sizeof(bd->renderResources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); io.Fonts->SetTexID((ImTextureID)bd->renderResources.FontTextureView); @@ -760,13 +746,24 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() ImGui_ImplWGPU_CreateFontsTexture(); ImGui_ImplWGPU_CreateUniformBuffer(); + // Create sampler + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + WGPUSamplerDescriptor sampler_desc = {}; + sampler_desc.minFilter = WGPUFilterMode_Linear; + sampler_desc.magFilter = WGPUFilterMode_Linear; + sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear; + sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge; + sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge; + sampler_desc.addressModeW = WGPUAddressMode_ClampToEdge; + sampler_desc.maxAnisotropy = 1; + bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc); + // Create resource bind group WGPUBindGroupEntry common_bg_entries[] = { { nullptr, 0, bd->renderResources.Uniforms, 0, MEMALIGN(sizeof(Uniforms), 16), 0, 0 }, { nullptr, 1, 0, 0, 0, bd->renderResources.Sampler, 0 }, }; - WGPUBindGroupDescriptor common_bg_descriptor = {}; common_bg_descriptor.layout = bg_layouts[0]; common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry); From 571dae9664ee842d88b3139476f1cb85fdc7b48a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 15:12:07 +0200 Subject: [PATCH 1085/2359] Backends: WGPU: added ImGuiBackendFlags_RendererHasTextures support. (#8465) --- backends/imgui_impl_wgpu.cpp | 132 +++++++++++++++++++++-------------- backends/imgui_impl_wgpu.h | 6 +- docs/CHANGELOG.txt | 2 +- 3 files changed, 86 insertions(+), 54 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index d5ac95d50..09bd30ca8 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -6,8 +6,7 @@ // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. -// Missing features or Issues: -// [ ] Renderer: Missing texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -19,6 +18,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. (#8465) // 2025-02-26: Recreate image bind groups during render. (#8426, #8046, #7765, #8027) + Update for latest webgpu-native changes. // 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083) // 2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. @@ -73,11 +73,15 @@ extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed); #define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro). // WebGPU data +struct ImGui_ImplWGPU_Texture +{ + WGPUTexture Texture = nullptr; + WGPUTextureView TextureView = nullptr; +}; + struct RenderResources { - WGPUTexture FontTexture = nullptr; // Font texture - WGPUTextureView FontTextureView = nullptr; // Texture view for font texture - WGPUSampler Sampler = nullptr; // Sampler for the font texture + WGPUSampler Sampler = nullptr; // Sampler for textures WGPUBuffer Uniforms = nullptr; // Shader uniforms WGPUBindGroup CommonBindGroup = nullptr; // Resources bind-group to bind the common resources to pipeline ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map) @@ -234,23 +238,8 @@ static void SafeRelease(WGPUShaderModule& res) wgpuShaderModuleRelease(res); res = nullptr; } -static void SafeRelease(WGPUTextureView& res) -{ - if (res) - wgpuTextureViewRelease(res); - res = nullptr; -} -static void SafeRelease(WGPUTexture& res) -{ - if (res) - wgpuTextureRelease(res); - res = nullptr; -} - static void SafeRelease(RenderResources& res) { - SafeRelease(res.FontTexture); - SafeRelease(res.FontTextureView); SafeRelease(res.Sampler); SafeRelease(res.Uniforms); SafeRelease(res.CommonBindGroup); @@ -381,6 +370,13 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0) return; + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplWGPU_UpdateTexture(tex); + // FIXME: Assuming that this only gets called once per frame! // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); @@ -536,33 +532,52 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder platform_io.Renderer_RenderState = nullptr; } -static void ImGui_ImplWGPU_CreateFontsTexture() +static void ImGui_ImplWGPU_DestroyTexture(ImTextureData* tex) { - // Build texture atlas - ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); - ImGuiIO& io = ImGui::GetIO(); - unsigned char* pixels; - int width, height, size_pp; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &size_pp); + ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData; + if (backend_tex == nullptr) + return; - // Upload texture to graphics system + IM_ASSERT(backend_tex->TextureView == (WGPUTextureView)(intptr_t)tex->TexID); + wgpuTextureViewRelease(backend_tex->TextureView); + wgpuTextureRelease(backend_tex->Texture); + IM_DELETE(backend_tex); + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + tex->BackendUserData = nullptr; +} + +void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex) +{ + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); + if (tex->Status == ImTextureStatus_WantCreate) { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + ImGui_ImplWGPU_Texture* backend_tex = IM_NEW(ImGui_ImplWGPU_Texture)(); + + // Create texture WGPUTextureDescriptor tex_desc = {}; #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - tex_desc.label = { "Dear ImGui Font Texture", WGPU_STRLEN }; + tex_desc.label = { "Dear ImGui Texture", WGPU_STRLEN }; #else - tex_desc.label = "Dear ImGui Font Texture"; + tex_desc.label = "Dear ImGui Texture"; #endif tex_desc.dimension = WGPUTextureDimension_2D; - tex_desc.size.width = width; - tex_desc.size.height = height; + tex_desc.size.width = tex->Width; + tex_desc.size.height = tex->Height; tex_desc.size.depthOrArrayLayers = 1; tex_desc.sampleCount = 1; tex_desc.format = WGPUTextureFormat_RGBA8Unorm; tex_desc.mipLevelCount = 1; tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding; - bd->renderResources.FontTexture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc); + backend_tex->Texture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc); + // Create texture view WGPUTextureViewDescriptor tex_view_desc = {}; tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm; tex_view_desc.dimension = WGPUTextureViewDimension_2D; @@ -571,19 +586,35 @@ static void ImGui_ImplWGPU_CreateFontsTexture() tex_view_desc.baseArrayLayer = 0; tex_view_desc.arrayLayerCount = 1; tex_view_desc.aspect = WGPUTextureAspect_All; - bd->renderResources.FontTextureView = wgpuTextureCreateView(bd->renderResources.FontTexture, &tex_view_desc); + backend_tex->TextureView = wgpuTextureCreateView(backend_tex->Texture, &tex_view_desc); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)backend_tex->TextureView); + tex->BackendUserData = backend_tex; + // We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below. } - // Upload texture data + if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates) { + ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData; + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + + // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture. + const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x; + const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y; + const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w; + const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h; + + // Update full texture or selected blocks. We only ever write to textures regions which have never been used before! + // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions. #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) WGPUTexelCopyTextureInfo dst_view = {}; #else WGPUImageCopyTexture dst_view = {}; #endif - dst_view.texture = bd->renderResources.FontTexture; + dst_view.texture = backend_tex->Texture; dst_view.mipLevel = 0; - dst_view.origin = { 0, 0, 0 }; + dst_view.origin = { (uint32_t)upload_x, (uint32_t)upload_y, 0 }; dst_view.aspect = WGPUTextureAspect_All; #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) WGPUTexelCopyBufferLayout layout = {}; @@ -591,15 +622,14 @@ static void ImGui_ImplWGPU_CreateFontsTexture() WGPUTextureDataLayout layout = {}; #endif layout.offset = 0; - layout.bytesPerRow = width * size_pp; - layout.rowsPerImage = height; - WGPUExtent3D size = { (uint32_t)width, (uint32_t)height, 1 }; - wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size); + layout.bytesPerRow = tex->Width * tex->BytesPerPixel; + layout.rowsPerImage = upload_h; + WGPUExtent3D write_size = { (uint32_t)upload_w, (uint32_t)upload_h, 1 }; + wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, tex->GetPixelsAt(upload_x, upload_y), (uint32_t)(tex->Width * upload_h * tex->BytesPerPixel), &layout, &write_size); + tex->SetStatus(ImTextureStatus_OK); } - - // Store our identifier - static_assert(sizeof(ImTextureID) >= sizeof(bd->renderResources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); - io.Fonts->SetTexID((ImTextureID)bd->renderResources.FontTextureView); + if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + ImGui_ImplWGPU_DestroyTexture(tex); } static void ImGui_ImplWGPU_CreateUniformBuffer() @@ -743,7 +773,6 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() bd->pipelineState = wgpuDeviceCreateRenderPipeline(bd->wgpuDevice, &graphics_pipeline_desc); - ImGui_ImplWGPU_CreateFontsTexture(); ImGui_ImplWGPU_CreateUniformBuffer(); // Create sampler @@ -788,8 +817,10 @@ void ImGui_ImplWGPU_InvalidateDeviceObjects() SafeRelease(bd->pipelineState); SafeRelease(bd->renderResources); - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->SetTexID(0); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplWGPU_DestroyTexture(tex); for (unsigned int i = 0; i < bd->numFramesInFlight; i++) SafeRelease(bd->pFrameResources[i]); @@ -814,6 +845,7 @@ bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info) io.BackendRendererName = "imgui_impl_webgpu"; #endif io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. bd->initInfo = *init_info; bd->wgpuDevice = init_info->Device; @@ -823,8 +855,6 @@ bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info) bd->numFramesInFlight = init_info->NumFramesInFlight; bd->frameIndex = UINT_MAX; - bd->renderResources.FontTexture = nullptr; - bd->renderResources.FontTextureView = nullptr; bd->renderResources.Sampler = nullptr; bd->renderResources.Uniforms = nullptr; bd->renderResources.CommonBindGroup = nullptr; @@ -863,7 +893,7 @@ void ImGui_ImplWGPU_Shutdown() io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); } diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 1da208f00..61d2d23c0 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -13,8 +13,7 @@ // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID/ImTextureRef! // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. -// Missing features or Issues: -// [ ] Renderer: Missing texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). +// [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -57,6 +56,9 @@ IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURen IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex); + // [BETA] Selected render state data shared with callbacks. // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplWGPU_RenderDrawData() call. // (Please open an issue if you feel you need access to more data) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 20377e2aa..9a24bd72f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -363,7 +363,7 @@ Other changes: - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] - Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). - Backends: - - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, Allegro5: + - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, WebGPU, Allegro5: - Added ImGuiBackendFlags_RendererHasTextures support. (#8465, #3761, #3471) [@ocornut, @ShironekoBen, @thedmd] - Added ImGui_ImplXXXX_UpdateTexture(ImTextureData* tex) functions for all backend. From b7f13df130354c1cb7eba3d83aa697b8f489fa32 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 15:42:51 +0200 Subject: [PATCH 1086/2359] Docs: reformat Changelog. --- docs/CHANGELOG.txt | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9a24bd72f..1cb16ad61 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -362,7 +362,7 @@ Other changes: requires providing a window to the backend. (#8584, #6341) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] - Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). -- Backends: +- Renderer Backends: - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, WebGPU, Allegro5: - Added ImGuiBackendFlags_RendererHasTextures support. (#8465, #3761, #3471) [@ocornut, @ShironekoBen, @thedmd] @@ -370,24 +370,6 @@ Other changes: Available if you want to start uploading textures right after ImGui::Render() and without waiting for the call to ImGui_ImplXXXX_RenderDrawData(). Also useful if you use a staged or multi-threaded rendering schemes, where you might want to set ImDrawData::Textures = NULL. (#8597, #1860) - - Backends: GLFW: added ImGui_ImplGlfw_GetContentScaleForMonitor(), ImGui_ImplGlfw_GetContentScaleForWindow() - helpers. They are wrappers to glfwGetMonitorContentScale()/glfwGetWindowContentScale(), with compile-time - GLFW version checks + returning 1.0f on Apple platform. - - Backends: SDL2: added ImGui_ImplSDL2_GetDpiScaleForDisplay() and ImGui_ImplSDL2_GetContentScaleForWindow() - helpers. They are wrappers to SDL_GetDisplayDPI(), with compile-time SDL version checks + returning 1.0f - on Apple platforms. SDL3 already does this by default. - - Backends: Win32: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) - would fail to claim it again the next subsequent click. (#8594) - - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad - regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) - - Backends: SDL2, SDL3: don't attempt to call SDL_CaptureMouse() on drivers where we don't - call SDL_GetGlobalMouseState(). This is specifically for Wayland but we currently use - the same white-list as SDL_GetGlobalMouseState(). (#8561) [@vs49688] - - Backends: GLFW, SDL2, SDL3: include GLFW/SDL version number in io.BackendPlatformName. - - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() - memory ownership change. (#8530, #7801) [@Green-Sky] - - Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative - way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) - Backends: SDLGPU3: Fixed creating atlas texture earlier than other backends, preventing to load fonts between the Init and NewFrames calls. - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which @@ -406,6 +388,25 @@ Other changes: - Backends: Vulkan: fixed validation errors in window create/resize helpers used by examples and by multi-viewports implementation, which would typically trigger errors while detaching secondary viewports. (#8600, #8176) [@ChrisTom-94] +- Platform Backends: + - Backends: GLFW: added ImGui_ImplGlfw_GetContentScaleForMonitor(), ImGui_ImplGlfw_GetContentScaleForWindow() + helpers. They are wrappers to glfwGetMonitorContentScale()/glfwGetWindowContentScale(), with compile-time + GLFW version checks + returning 1.0f on Apple platform. + - Backends: SDL2: added ImGui_ImplSDL2_GetDpiScaleForDisplay() and ImGui_ImplSDL2_GetContentScaleForWindow() + helpers. They are wrappers to SDL_GetDisplayDPI(), with compile-time SDL version checks + returning 1.0f + on Apple platforms. SDL3 already does this by default. + - Backends: Win32: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) + would fail to claim it again the next subsequent click. (#8594) + - Backends: SDL2, SDL3, OSX: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad + regardless of ImGuiConfigFlags_NavEnableGamepad being set. (#8508) + - Backends: SDL2, SDL3: don't attempt to call SDL_CaptureMouse() on drivers where we don't + call SDL_GetGlobalMouseState(). This is specifically for Wayland but we currently use + the same white-list as SDL_GetGlobalMouseState(). (#8561) [@vs49688] + - Backends: GLFW, SDL2, SDL3: include GLFW/SDL version number in io.BackendPlatformName. + - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() + memory ownership change. (#8530, #7801) [@Green-Sky] + - Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative + way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) - Examples: - Examples: Made many examples DPI aware by default. The single-viewport is basically: From 7ac99a43662b9dd011610fca500665279af1fbe3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 15:43:12 +0200 Subject: [PATCH 1087/2359] Backends: OSX: ImGui_ImplOSX_HandleEvent() only process event for window containing our view. (#8644) --- backends/imgui_impl_osx.mm | 4 ++++ docs/CHANGELOG.txt | 2 ++ 2 files changed, 6 insertions(+) diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 32e562472..27567fb19 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -31,6 +31,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-12: ImGui_ImplOSX_HandleEvent() only process event for window containing our view. (#8644) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-01-20: Removed notification observer when shutting down. (#8331) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: @@ -663,6 +664,9 @@ static ImGuiMouseSource GetMouseSource(NSEvent* event) static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) { + // Only process events from the window containing ImGui view + if (event.window != view.window) + return false; ImGuiIO& io = ImGui::GetIO(); if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1cb16ad61..4d73a2aa2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -407,6 +407,8 @@ Other changes: memory ownership change. (#8530, #7801) [@Green-Sky] - Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) + - Backends: OSX: ImGui_ImplOSX_HandleEvent() only process event for window containing + our view. (#8644) [@BingoXuan] - Examples: - Examples: Made many examples DPI aware by default. The single-viewport is basically: From 1ec1510ef7ac64cae4a1876fe25736d05bda02ba Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Jun 2025 16:35:51 +0200 Subject: [PATCH 1088/2359] Fonts: clarify assert. (#8680) --- docs/CHANGELOG.txt | 5 ++++- imgui.cpp | 10 +++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4d73a2aa2..87dfe5672 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,11 +41,14 @@ HOW TO UPDATE? THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, -BUT INEVITABLY SOME USERS WILL BE AFFECTED. +BUT INEVITABLY SOME USERS OR THIRD-PARTY EXTENSIONS WILL BE AFFECTED. IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/ +If you are using custom widgets, internals or third-party extension that are somehow +breaking and aren't obvious how to solve, please post in Issues so we can gather +data and share solutions that may help others. As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be diff --git a/imgui.cpp b/imgui.cpp index f7d2e7441..67e29e228 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5301,8 +5301,12 @@ static void ImGui::UpdateTexturesNewFrame() } else { - IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1 && "If you manage font atlases yourself you need to call ImFontAtlasUpdateNewFrame() on it."); - IM_ASSERT(atlas->RendererHasTextures == has_textures && "If you manage font atlases yourself make sure ImGuiBackendFlags_RendererHasTextures is set consistently with atlas->RendererHasTextures as specified in the ImFontAtlasUpdateNewFrame() call."); + // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it. + // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context. + // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that. + // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures. + IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1); + IM_ASSERT(atlas->RendererHasTextures == has_textures); } } } @@ -16967,7 +16971,7 @@ void ImGui::DebugNodeFont(ImFont* font) if (baked->ContainerFont != font) continue; PushID(baked_n); - if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.1f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) + if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) { if (SmallButton("Load all")) for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++) From ca3169310ea3e2e8c4a140fd7eaa872edcc2245e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Jun 2025 16:43:58 +0200 Subject: [PATCH 1089/2359] Fonts: fixed FontBaked=NULL in initial call to SetCurrentWindow() in Begin() using previous frame value of SkipItems. (#8465) ref 0e769c5 --- imgui.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 67e29e228..3618384fb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4475,12 +4475,15 @@ static void SetCurrentWindow(ImGuiWindow* window) g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking if (window) { + bool backup_skip_items = window->SkipItems; + window->SkipItems = false; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) { ImGuiViewport* viewport = window->Viewport; g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity() } ImGui::UpdateCurrentFontSize(0.0f); + window->SkipItems = backup_skip_items; ImGui::NavUpdateCurrentWindowIsScrollPushableX(); } } @@ -8695,6 +8698,21 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) // Most of the relevant font logic is in imgui_draw.cpp. // Those are high-level support functions. //----------------------------------------------------------------------------- +// - UpdateFontsNewFrame() [Internal] +// - UpdateFontsEndFrame() [Internal] +// - GetDefaultFont() [Internal] +// - RegisterUserTexture() [Internal] +// - UnregisterUserTexture() [Internal] +// - RegisterFontAtlas() [Internal] +// - UnregisterFontAtlas() [Internal] +// - SetCurrentFont() [Internal] +// - UpdateCurrentFontSize() [Internal] +// - SetFontRasterizerDensity() [Internal] +// - PushFont() +// - PopFont() +// - PushFontSize() +// - PopFontSize() +//----------------------------------------------------------------------------- void ImGui::UpdateFontsNewFrame() { From d8da97f756d8e69ed3ebd858c109edf608cebccc Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Jun 2025 16:47:23 +0200 Subject: [PATCH 1090/2359] Fonts: UpdateCurrentFontSize() early out doesn't need to clear FontBaked. This was meant when the code would be lower in the function (after updating e.g. g.FontSize) Amend 0e769c5. --- imgui.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3618384fb..2bd7cebc5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8825,12 +8825,10 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) // Early out to avoid hidden window keeping bakes referenced and out of GC reach. // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching, so for now we null it. + // FIXME: perhaps g.FontSize should be updated? if (window != NULL && window->SkipItems) if (g.CurrentTable == NULL || g.CurrentTable->CurrentColumn != -1) // See 8465#issuecomment-2951509561. Ideally the SkipItems=true in tables would be amended with extra data. - { - g.FontBaked = NULL; return; - } // Restoring is pretty much only used by PopFont()/PopFontSize() float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; From cfa43e721aa1300b17d633f7590516587ff23617 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Jun 2025 17:40:17 +0200 Subject: [PATCH 1091/2359] Windows: clicking on a window close button doesn't claim focus and bring to front. (#8683) Added ImGuiItemFlags_NoFocus, ImGuiButtonFlags_NoFocus. Neither are well specified so marking as experimental. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 4 ++++ imgui_internal.h | 2 ++ imgui_widgets.cpp | 6 ++++-- 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 87dfe5672..c23a2b7e2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -302,6 +302,7 @@ Other changes: codepath that preserve last contents size when collapsed, resulting in programmatically uncollapsing auto-sizing windows having them flicker size for a frame. (#7691) [@achabense] +- Windows: clicking on a window close button doesn't claim focus and bring to front. (#8683) - Windows: loosened code to allow hovering of resize grips, borders, and table borders while hovering a sibling child window, so that the code in master matches one in docking (they accidentally diverged). (#8554) diff --git a/imgui.cpp b/imgui.cpp index 2bd7cebc5..9ed61ba5d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7126,8 +7126,12 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl // Close button if (has_close_button) + { + g.CurrentItemFlags |= ImGuiItemFlags_NoFocus; if (CloseButton(window->GetID("#CLOSE"), close_button_pos)) *p_open = false; + g.CurrentItemFlags &= ~ImGuiItemFlags_NoFocus; + } window->DC.NavLayerCurrent = ImGuiNavLayer_Main; g.CurrentItemFlags = item_flags_backup; diff --git a/imgui_internal.h b/imgui_internal.h index 1d572d5a6..fe71e49b0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -946,6 +946,7 @@ enum ImGuiItemFlagsPrivate_ ImGuiItemFlags_AllowOverlap = 1 << 14, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. ImGuiItemFlags_NoNavDisableMouseHover = 1 << 15, // false // Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false). ImGuiItemFlags_NoMarkEdited = 1 << 16, // false // Skip calling MarkItemEdited() + ImGuiItemFlags_NoFocus = 1 << 17, // false // [EXPERIMENTAL: Not very well specced] Clicking doesn't take focus. Automatically sets ImGuiButtonFlags_NoFocus + ImGuiButtonFlags_NoNavFocus in ButtonBehavior(). // Controlled by widget code ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. @@ -1023,6 +1024,7 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item ImGuiButtonFlags_NoSetKeyOwner = 1 << 20, // don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) ImGuiButtonFlags_NoTestKeyOwner = 1 << 21, // don't test key/input owner when polling the key (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) + ImGuiButtonFlags_NoFocus = 1 << 22, // [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking. ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease, }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ba35e531b..2e80564ea 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -548,6 +548,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags); if (flags & ImGuiButtonFlags_AllowOverlap) item_flags |= ImGuiItemFlags_AllowOverlap; + if (item_flags & ImGuiItemFlags_NoFocus) + flags |= ImGuiButtonFlags_NoFocus | ImGuiButtonFlags_NoNavFocus; // Default only reacts to left mouse button if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0) @@ -623,7 +625,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool SetFocusID(id, window); FocusWindow(window); } - else + else if (!(flags & ImGuiButtonFlags_NoFocus)) { FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child } @@ -641,7 +643,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool SetFocusID(id, window); FocusWindow(window); } - else + else if (!(flags & ImGuiButtonFlags_NoFocus)) { FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child } From 6b3cbb10a2e73b2ce93b1f402667c7b50ddd4a60 Mon Sep 17 00:00:00 2001 From: Shawn Hatori <5499686+shawnhatori@users.noreply.github.com> Date: Mon, 16 Jun 2025 05:59:26 -0400 Subject: [PATCH 1092/2359] Backends: Vulkan: correct minimum pool size assertion (#8691) --- backends/imgui_impl_vulkan.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 74c7d791b..3e2c043de 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1043,7 +1043,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() if (v->DescriptorPoolSize != 0) { - IM_ASSERT(v->DescriptorPoolSize > IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE); + IM_ASSERT(v->DescriptorPoolSize >= IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE); VkDescriptorPoolSize pool_size = { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, v->DescriptorPoolSize }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; From 842837e35b421a4c85ca30f6840321f0a3c5a029 Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Mon, 16 Jun 2025 18:36:33 +0200 Subject: [PATCH 1093/2359] imgui_freetype: fix conversion null -> bool in FontBakedLoadGlyph (#8696) --- misc/freetype/imgui_freetype.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index ae87f63f9..d7d50db39 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -501,7 +501,7 @@ bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src FT_Error error = FT_Render_Glyph(slot, render_mode); const FT_Bitmap* ft_bitmap = &slot->bitmap; if (error != 0 || ft_bitmap == nullptr) - return NULL; + return false; const int w = (int)ft_bitmap->width; const int h = (int)ft_bitmap->rows; @@ -520,7 +520,7 @@ bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src { // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory."); - return NULL; + return false; } ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); From 24f7328e5f7939c0fa9d9dd8c6cf9fd06c38540a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Jun 2025 11:55:40 +0200 Subject: [PATCH 1094/2359] DrawList, Fonts: fixed ImFontAtlasTextureRepack() overwriting draw list shared data UV's etc. even when not bound. (#8694, #8465) ImFontAtlasUpdateDrawListsSharedData() call from ImFontAtlasTextureRepack() would trigger this. For simplicity we also track current atlas in ImDrawListSharedData, but we could probably use Font->ContainerAtlas. --- imgui.cpp | 10 ++++++---- imgui_draw.cpp | 18 ++++++++++-------- imgui_internal.h | 7 ++++--- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9ed61ba5d..4ace6433d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3932,7 +3932,7 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso ImGuiContext& g = *GImGui; if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values. mouse_cursor = ImGuiMouseCursor_Arrow; - ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas; + ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas; for (ImGuiViewportP* viewport : g.Viewports) { // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. @@ -8813,10 +8813,12 @@ void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float f #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS IM_ASSERT(font->Scale > 0.0f); #endif - g.DrawListSharedData.Font = g.Font; - ImFontAtlasUpdateDrawListsSharedData(g.Font->ContainerAtlas); + ImFontAtlas* atlas = font->ContainerAtlas; + g.DrawListSharedData.FontAtlas = atlas; + g.DrawListSharedData.Font = font; + ImFontAtlasUpdateDrawListsSharedData(atlas); if (g.CurrentWindow != NULL) - g.CurrentWindow->DrawList->_SetTexture(font->ContainerAtlas->TexRef); + g.CurrentWindow->DrawList->_SetTexture(atlas->TexRef); } } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index cd3d22ef9..3621deb46 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2694,10 +2694,11 @@ void ImFontAtlas::ClearFonts() Fonts.clear_delete(); TexIsBuilt = false; for (ImDrawListSharedData* shared_data : DrawListSharedDatas) - { - shared_data->Font = NULL; - shared_data->FontScale = shared_data->FontSize = 0.0f; - } + if (shared_data->FontAtlas == this) + { + shared_data->Font = NULL; + shared_data->FontScale = shared_data->FontSize = 0.0f; + } } static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* atlas) @@ -3914,10 +3915,11 @@ void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) { for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) - { - shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; - shared_data->TexUvLines = atlas->TexUvLines; - } + if (shared_data->FontAtlas == atlas) + { + shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; + shared_data->TexUvLines = atlas->TexUvLines; + } } // Set current texture. This is mostly called from AddTexture() + to handle a failed resize. diff --git a/imgui_internal.h b/imgui_internal.h index fe71e49b0..b3a950c7a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -838,9 +838,10 @@ struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) - ImFont* Font; // Current/default font (optional, for simplified AddText overload) - float FontSize; // Current/default font size (optional, for simplified AddText overload) - float FontScale; // Current/default font scale (== FontSize / Font->FontSize) + ImFontAtlas* FontAtlas; // Current font atlas + ImFont* Font; // Current font (used for simplified AddText overload) + float FontSize; // Current font size (used for for simplified AddText overload) + float FontScale; // Current font scale (== FontSize / Font->FontSize) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc float InitialFringeScale; // Initial scale to apply to AA fringe From fe048efeab2fe21f397579f49ea1011be6d2be4a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Jun 2025 11:56:43 +0200 Subject: [PATCH 1095/2359] DrawList, Fonts: fixed PushFont()/AddImage() not restoring correct atlas texture id when using multiple atlas (#8694) This also needs 24f7328. --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 1 + 2 files changed, 4 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c23a2b7e2..c895a0532 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -161,6 +161,9 @@ Breaking changes: - renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader() - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader(); +- DrawList: Fixed a regression from 1.91.1 where a Begin()/PushFont()/AddImage() sequence + would not restore the correct atlas Texture Identifier when the PushFont() call used + a font from a different atlas. (#8694, caused by #3224, #3875, #6398, #7903) - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). - Fonts: (users of custom rectangles) - Renamed AddCustomRectRegular() to AddCustomRect(). (#8466) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3621deb46..6ac946491 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -695,6 +695,7 @@ void ImDrawList::_SetTexture(ImTextureRef tex_ref) if (_CmdHeader.TexRef == tex_ref) return; _CmdHeader.TexRef = tex_ref; + _TextureStack.back() = tex_ref; _OnChangedTexture(); } From f2e4e8039154515b43b89b6e236504b140850c5e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Jun 2025 14:01:01 +0200 Subject: [PATCH 1096/2359] Windows: BeginChild(): fixed being unable to combine manual resize on one axis and automatic resize on the other axis. (#8690) + removed obsolete TODO entries. --- docs/CHANGELOG.txt | 4 ++++ docs/TODO.txt | 3 --- imgui.cpp | 8 +++++--- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c895a0532..dd9daeba1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -309,6 +309,10 @@ Other changes: - Windows: loosened code to allow hovering of resize grips, borders, and table borders while hovering a sibling child window, so that the code in master matches one in docking (they accidentally diverged). (#8554) +- Windows: BeginChild(): fixed being unable to combine manual resize on one axis + and automatic resize on the other axis. (#8690) + e.g. neither ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeY + or ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX worked before. - TreeNode: added experimental flags to draw tree hierarchy outlines linking parent and tree nodes: (#2920) - ImGuiTreeNodeFlags_DrawLinesNone: No lines drawn (default value in style.TreeLinesFlags). diff --git a/docs/TODO.txt b/docs/TODO.txt index aeef17592..8866d04fb 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -26,9 +26,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window/size: manually triggered auto-fit (double-click on grip) shouldn't resize window down to viewport size? - window/size: how to allow to e.g. auto-size vertically to fit contents, but be horizontally resizable? Assuming SetNextWindowSize() is modified to treat -1.0f on each axis as "keep as-is" (would be good but might break erroneous code): Problem is UpdateWindowManualResize() and lots of code treat (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) together. - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. - - window/child: background options for child windows, border option (disable rounding). - - window/child: allow resizing of child windows (possibly given min/max for each axis?.) - - window/child: allow SetNextWindowContentSize() to work on child windows. - window/clipping: some form of clipping when DisplaySize (or corresponding viewport) is zero. - window/tabbing: add a way to signify that a window or docked window requires attention (e.g. blinking title bar, trying to click behind a modal). - window/id_stack: add e.g. window->GetIDFromPath() with support for leading / and ../ (#1390, #331) -> model from test engine. diff --git a/imgui.cpp b/imgui.cpp index 4ace6433d..af22c37fa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6612,9 +6612,9 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars, // we may need to compute/store three variants of size_auto_fit, for x/y/xy. // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well: - if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY)) + if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & (ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeY))) size_auto_fit.y = window->SizeFull.y; - else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY)) + else if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && !(window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeX))) size_auto_fit.x = window->SizeFull.x; // When the window cannot fit all contents (either because of constraints, either because screen is too small), @@ -6734,7 +6734,9 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; - if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + return false; + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0) return false; if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window. return false; From 39a90ac4d63867bb9bbd3ee4012b0981c4329eaf Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Jun 2025 14:52:34 +0200 Subject: [PATCH 1097/2359] Misc: removed static linkage from operators to facilitate using in C++ modules. (#8682, #8358) [@radjkarl] --- docs/CHANGELOG.txt | 1 + imgui.h | 48 +++++++++++++++++++++++----------------------- imgui_internal.h | 4 ++-- 3 files changed, 27 insertions(+), 26 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dd9daeba1..245462463 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -372,6 +372,7 @@ Other changes: of WantVisible. This is set in the same structure because activating text input generally requires providing a window to the backend. (#8584, #6341) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] +- Misc: removed static linkage from operators to facilitate using in C++ modules. (#8682, #8358) [@johmani] - Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). - Renderer Backends: - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, WebGPU, Allegro5: diff --git a/imgui.h b/imgui.h index de0d06645..195a4ea5a 100644 --- a/imgui.h +++ b/imgui.h @@ -2827,31 +2827,31 @@ struct ImGuiListClipper #define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED IM_MSVC_RUNTIME_CHECKS_OFF // ImVec2 operators -static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } -static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } -static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } -static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } -static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } -static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } -static inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } -static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } -static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } -static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } -static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } -static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } -static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } -static inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } -static inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } +inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } +inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } +inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } +inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } +inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } +inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } +inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } +inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } +inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } +inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } // ImVec4 operators -static inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } -static inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } -static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } -static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } -static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } -static inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } -static inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } -static inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } -static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } +inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } +inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } +inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } +inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } +inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } +inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } +inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } +inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } +inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } IM_MSVC_RUNTIME_CHECKS_RESTORE #endif diff --git a/imgui_internal.h b/imgui_internal.h index b3a950c7a..7ff24d889 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3713,8 +3713,8 @@ typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are // Helpers: ImTextureRef ==/!= operators provided as convenience // (note that _TexID and _TexData are never set simultaneously) -static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } -static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } +inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } +inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } // Refer to ImFontAtlasPackGetRect() to better understand how this works. #define ImFontAtlasRectId_IndexMask_ (0x000FFFFF) // 20-bits: index to access builder->RectsIndex[]. From 041abe85224c38d4629dd1e9f9e9ab6f20837a99 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Jun 2025 14:57:39 +0200 Subject: [PATCH 1098/2359] Revert "Misc: removed static linkage from operators to facilitate using in C++ modules. (#8682, #8358) [@radjkarl]" This reverts commit 39a90ac4d63867bb9bbd3ee4012b0981c4329eaf. --- docs/CHANGELOG.txt | 1 - imgui.h | 48 +++++++++++++++++++++++----------------------- imgui_internal.h | 4 ++-- 3 files changed, 26 insertions(+), 27 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 245462463..dd9daeba1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -372,7 +372,6 @@ Other changes: of WantVisible. This is set in the same structure because activating text input generally requires providing a window to the backend. (#8584, #6341) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] -- Misc: removed static linkage from operators to facilitate using in C++ modules. (#8682, #8358) [@johmani] - Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). - Renderer Backends: - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, WebGPU, Allegro5: diff --git a/imgui.h b/imgui.h index 195a4ea5a..de0d06645 100644 --- a/imgui.h +++ b/imgui.h @@ -2827,31 +2827,31 @@ struct ImGuiListClipper #define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED IM_MSVC_RUNTIME_CHECKS_OFF // ImVec2 operators -inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } -inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } -inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } -inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } -inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } -inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } -inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } -inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } -inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } -inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } -inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } -inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } -inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } -inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } -inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } +static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } +static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } +static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } +static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } +static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } +static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } +static inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } +static inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } // ImVec4 operators -inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } -inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } -inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } -inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } -inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } -inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } -inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } -inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } -inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } +static inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } +static inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } +static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } +static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } +static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } +static inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } +static inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } +static inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } +static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } IM_MSVC_RUNTIME_CHECKS_RESTORE #endif diff --git a/imgui_internal.h b/imgui_internal.h index 7ff24d889..b3a950c7a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3713,8 +3713,8 @@ typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are // Helpers: ImTextureRef ==/!= operators provided as convenience // (note that _TexID and _TexData are never set simultaneously) -inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } -inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } +static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } +static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } // Refer to ImFontAtlasPackGetRect() to better understand how this works. #define ImFontAtlasRectId_IndexMask_ (0x000FFFFF) // 20-bits: index to access builder->RectsIndex[]. From 08bb348142386feca796cbbe51e030875a2216a0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Jun 2025 14:52:34 +0200 Subject: [PATCH 1099/2359] Misc: removed static linkage from operators to facilitate using in C++ modules. (#8682, #8358) --- docs/CHANGELOG.txt | 1 + imgui.h | 48 +++++++++++++++++++++++----------------------- imgui_internal.h | 4 ++-- 3 files changed, 27 insertions(+), 26 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dd9daeba1..245462463 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -372,6 +372,7 @@ Other changes: of WantVisible. This is set in the same structure because activating text input generally requires providing a window to the backend. (#8584, #6341) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] +- Misc: removed static linkage from operators to facilitate using in C++ modules. (#8682, #8358) [@johmani] - Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). - Renderer Backends: - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, WebGPU, Allegro5: diff --git a/imgui.h b/imgui.h index de0d06645..195a4ea5a 100644 --- a/imgui.h +++ b/imgui.h @@ -2827,31 +2827,31 @@ struct ImGuiListClipper #define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED IM_MSVC_RUNTIME_CHECKS_OFF // ImVec2 operators -static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } -static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } -static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } -static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } -static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } -static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } -static inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } -static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } -static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } -static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } -static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } -static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } -static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } -static inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } -static inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } +inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } +inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } +inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } +inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } +inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } +inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } +inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } +inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } +inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } +inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } // ImVec4 operators -static inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } -static inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } -static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } -static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } -static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } -static inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } -static inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } -static inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } -static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } +inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } +inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } +inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } +inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } +inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } +inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } +inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } +inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } +inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } IM_MSVC_RUNTIME_CHECKS_RESTORE #endif diff --git a/imgui_internal.h b/imgui_internal.h index b3a950c7a..7ff24d889 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3713,8 +3713,8 @@ typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are // Helpers: ImTextureRef ==/!= operators provided as convenience // (note that _TexID and _TexData are never set simultaneously) -static inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } -static inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } +inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } +inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } // Refer to ImFontAtlasPackGetRect() to better understand how this works. #define ImFontAtlasRectId_IndexMask_ (0x000FFFFF) // 20-bits: index to access builder->RectsIndex[]. From 12626b85c496b6d8f5995f0f77ba9a9516d0beaa Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Jun 2025 19:24:10 +0200 Subject: [PATCH 1100/2359] InputText: minor changes to match for both insert chars paths to look more similar. --- imgui_widgets.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2e80564ea..22f8b4eca 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4282,6 +4282,10 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons if (new_text == new_text_end) return; + ImGuiContext& g = *Ctx; + ImGuiInputTextState* obj = &g.InputTextState; + IM_ASSERT(obj->ID != 0 && g.ActiveId == obj->ID); + // Grow internal buffer if needed const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text); @@ -4290,15 +4294,12 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons if (!is_resizable) return; - ImGuiContext& g = *Ctx; - ImGuiInputTextState* edit_state = &g.InputTextState; - IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); - IM_ASSERT(Buf == edit_state->TextA.Data); + IM_ASSERT(Buf == obj->TextA.Data); int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; - edit_state->TextA.resize(new_buf_size + 1); - edit_state->TextSrc = edit_state->TextA.Data; - Buf = edit_state->TextA.Data; - BufSize = edit_state->BufCapacity = new_buf_size; + obj->TextA.resize(new_buf_size + 1); + obj->TextSrc = obj->TextA.Data; + Buf = obj->TextA.Data; + BufSize = obj->BufCapacity = new_buf_size; } if (BufTextLen != pos) @@ -5483,7 +5484,7 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state) Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId); DebugLocateItemOnHover(state->ID); Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->TextLen, stb_state->cursor, stb_state->select_start, stb_state->select_end); - Text("BufCapacityA: %d", state->BufCapacity); + Text("BufCapacity: %d", state->BufCapacity); Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity); Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x); Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point); From b2c73596aeaf63b46b66a615ec02fce1b87f4248 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Jun 2025 20:11:22 +0200 Subject: [PATCH 1101/2359] InputText: fixed a buffer overrun that could happen when using dynamically resizing buffers. (#8689) --- docs/CHANGELOG.txt | 3 +++ imgui.h | 2 +- imgui_widgets.cpp | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 245462463..2104b9c9c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -336,6 +336,9 @@ Other changes: - TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. - InputText: fixed cursor positioning issue using up/down keys near end of lines while editing non-ASCII text. (Regression from 1.91.2) (#8635, #7925) +- InputText: fixed a buffer overrun that could happen when using dynamically resizing + buffers (e.g. imgui_stdlib.cpp for std::string, or ImGuiInputTextFlags_CallbackRezize) + and programmatically making an insertion. (#8689) [@ocornut, @m9710797] - Tables: fixed TableHeader() eager vertical clipping of text which may be noticeable with FramePadding.y was too small. (#6236) - Tables: fixed an assert when combining Tables, Frozen Rows, Clipper and BeginMultiSelect() diff --git a/imgui.h b/imgui.h index 195a4ea5a..ae0b90e8c 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19198 +#define IMGUI_VERSION_NUM 19199 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 22f8b4eca..43d98bb88 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4289,7 +4289,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons // Grow internal buffer if needed const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text); - if (new_text_len + BufTextLen >= BufSize) + if (new_text_len + BufTextLen + 1 > obj->TextA.Size) { if (!is_resizable) return; From c56e8b496467aa573ca0f65a295b4b1235718d43 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Jun 2025 15:31:00 +0200 Subject: [PATCH 1102/2359] imgui_freetype: fixed NULL that creeped in instead of nullptr. --- misc/freetype/imgui_freetype.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index d7d50db39..e5f2818db 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -346,7 +346,7 @@ static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas) { - IM_ASSERT(atlas->FontLoaderData == NULL); + IM_ASSERT(atlas->FontLoaderData == nullptr); ImGui_ImplFreeType_Data* bd = IM_NEW(ImGui_ImplFreeType_Data)(); // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html @@ -387,23 +387,23 @@ bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas) void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas) { ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData; - IM_ASSERT(bd != NULL); + IM_ASSERT(bd != nullptr); FT_Done_Library(bd->Library); IM_DELETE(bd); - atlas->FontLoaderData = NULL; + atlas->FontLoaderData = nullptr; } bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) { ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData; ImGui_ImplFreeType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplFreeType_FontSrcData); - IM_ASSERT(src->FontLoaderData == NULL); + IM_ASSERT(src->FontLoaderData == nullptr); src->FontLoaderData = bd_font_data; if (!bd_font_data->InitFont(bd->Library, src, (ImGuiFreeTypeLoaderFlags)atlas->FontLoaderFlags)) { IM_DELETE(bd_font_data); - src->FontLoaderData = NULL; + src->FontLoaderData = nullptr; return false; } @@ -415,7 +415,7 @@ void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) IM_UNUSED(atlas); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; IM_DELETE(bd_font_data); - src->FontLoaderData = NULL; + src->FontLoaderData = nullptr; } bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) @@ -430,7 +430,7 @@ bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF // We use one FT_Size per (source + baked) combination. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; - IM_ASSERT(bd_baked_data != NULL); + IM_ASSERT(bd_baked_data != nullptr); IM_PLACEMENT_NEW(bd_baked_data) ImGui_ImplFreeType_FontSrcBakedData(); FT_New_Size(bd_font_data->FtFace, &bd_baked_data->FtSize); @@ -470,7 +470,7 @@ void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, IM_UNUSED(baked); IM_UNUSED(src); ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; - IM_ASSERT(bd_baked_data != NULL); + IM_ASSERT(bd_baked_data != nullptr); FT_Done_Size(bd_baked_data->FtSize); bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() } @@ -491,7 +491,7 @@ bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src } const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, codepoint); - if (metrics == NULL) + if (metrics == nullptr) return false; // Render glyph into a bitmap (currently held by FreeType) From d290e583c54dcb020cc96cfcab2f629441c7dad5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Jun 2025 15:50:49 +0200 Subject: [PATCH 1103/2359] Backends: GLFW: fixed WndProc relying on current context. (#8676, #8239, #8069) This makes the backend closer to support multi-context. --- backends/imgui_impl_glfw.cpp | 16 +++++++++++++--- docs/CHANGELOG.txt | 1 + 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index aac9eca2e..fb8df3e55 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -191,6 +191,10 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } +static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData(ImGuiIO& io) +{ + return (ImGui_ImplGlfw_Data*)io.BackendPlatformUserData; +} // Functions @@ -501,6 +505,7 @@ static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEven #ifdef _WIN32 // GLFW doesn't allow to distinguish Mouse vs TouchScreen vs Pen. // Add support for Win32 (based on imgui_impl_win32), because we rely on _TouchScreen info to trickle inputs differently. +namespace ImGui { extern ImGuiIO& GetIO(ImGuiContext*); } static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() { LPARAM extra_info = ::GetMessageExtraInfo(); @@ -512,7 +517,10 @@ static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() } static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + ImGuiContext* ctx = (ImGuiContext*)::GetPropA(hWnd, "IMGUI_CONTEXT"); + ImGuiIO& io = ImGui::GetIO(ctx); + + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(io); switch (msg) { case WM_MOUSEMOVE: case WM_NCMOUSEMOVE: @@ -520,7 +528,7 @@ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wPara case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_MBUTTONUP: case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: case WM_XBUTTONUP: - ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); + io.AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); break; } return ::CallWindowProcW(bd->PrevWndProc, hWnd, msg, wParam, lParam); @@ -661,6 +669,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Windows: register a WndProc hook so we can intercept some messages. #ifdef _WIN32 + ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_CONTEXT", ImGui::GetCurrentContext()); bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC); IM_ASSERT(bd->PrevWndProc != nullptr); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); @@ -672,7 +681,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817 if (emscripten::glfw3::IsRuntimePlatformApple()) { - ImGui::GetIO().ConfigMacOSXBehaviors = true; + io.ConfigMacOSXBehaviors = true; // Due to how the browser (poorly) handles the Meta Key, this line essentially disables repeats when used. // This means that Meta + V only registers a single key-press, even if the keys are held. @@ -721,6 +730,7 @@ void ImGui_ImplGlfw_Shutdown() // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_CONTEXT", nullptr); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); bd->PrevWndProc = nullptr; #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2104b9c9c..72edad331 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -407,6 +407,7 @@ Other changes: - Backends: GLFW: added ImGui_ImplGlfw_GetContentScaleForMonitor(), ImGui_ImplGlfw_GetContentScaleForWindow() helpers. They are wrappers to glfwGetMonitorContentScale()/glfwGetWindowContentScale(), with compile-time GLFW version checks + returning 1.0f on Apple platform. + - Backends: GLFW: fixed Win32 specific WndProc handler relying on current context. (#8676, #8239, #8069) - Backends: SDL2: added ImGui_ImplSDL2_GetDpiScaleForDisplay() and ImGui_ImplSDL2_GetContentScaleForWindow() helpers. They are wrappers to SDL_GetDisplayDPI(), with compile-time SDL version checks + returning 1.0f on Apple platforms. SDL3 already does this by default. From f633a60581bc7573f76c9913f66695aa02caf5d0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Jun 2025 16:40:35 +0200 Subject: [PATCH 1104/2359] Backends: GLFW: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069) --- backends/imgui_impl_glfw.cpp | 102 ++++++++++++++++++++--------------- backends/imgui_impl_glfw.h | 1 + docs/CHANGELOG.txt | 2 +- 3 files changed, 62 insertions(+), 43 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index fb8df3e55..5518a823e 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -9,6 +9,7 @@ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Multiple Dear ImGui contexts support. // Missing features or Issues: // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. // [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. @@ -28,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-18: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069) // 2025-06-11: Added ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) and ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) helper to facilitate making DPI-aware apps. // 2025-03-10: Map GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 into ImGuiKey_Oem102. // 2025-03-03: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. @@ -141,6 +143,16 @@ #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName() #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError() +// Map GLFWWindow* to ImGuiContext*. +// - Would be simpler if we could use glfwSetWindowUserPointer()/glfwGetWindowUserPointer(), but this is a single and shared resource. +// - Would be simpler if we could use e.g. std::map<> as well. But we don't. +// - This is not particularly optimized as we expect size to be small and queries to be rare. +struct ImGui_ImplGlfw_WindowToContext { GLFWwindow* Window; ImGuiContext* Context; }; +static ImVector g_ContextMap; +static void ImGui_ImplGlfw_ContextMap_Add(GLFWwindow* window, ImGuiContext* ctx) { g_ContextMap.push_back(ImGui_ImplGlfw_WindowToContext{ window, ctx }); } +static void ImGui_ImplGlfw_ContextMap_Remove(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) { g_ContextMap.erase_unsorted(&entry); return; } } +static ImGuiContext* ImGui_ImplGlfw_ContextMap_Get(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) return entry.Context; return nullptr; } + // GLFW data enum GlfwClientApi { @@ -151,6 +163,7 @@ enum GlfwClientApi struct ImGui_ImplGlfw_Data { + ImGuiContext* Context; GLFWwindow* Window; GlfwClientApi ClientApi; double Time; @@ -187,13 +200,17 @@ struct ImGui_ImplGlfw_Data // (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks. // - Otherwise we may need to store a GLFWWindow* -> ImGuiContext* map and handle this in the backend, adding a little bit of extra complexity to it. // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. +namespace ImGui { extern ImGuiIO& GetIO(ImGuiContext*); } static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() { + // Get data for current context return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } -static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData(ImGuiIO& io) +static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData(GLFWwindow* window) { - return (ImGui_ImplGlfw_Data*)io.BackendPlatformUserData; + // Get data for a given GLFW window, regardless of current context (since GLFW events are sent together) + ImGuiContext* ctx = ImGui_ImplGlfw_ContextMap_Get(window); + return (ImGui_ImplGlfw_Data*)ImGui::GetIO(ctx).BackendPlatformUserData; } // Functions @@ -330,38 +347,36 @@ ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode) // X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW // See https://github.com/ocornut/imgui/issues/6034 and https://github.com/glfw/glfw/issues/1630 -static void ImGui_ImplGlfw_UpdateKeyModifiers(GLFWwindow* window) +static void ImGui_ImplGlfw_UpdateKeyModifiers(ImGuiIO& io, GLFWwindow* window) { - ImGuiIO& io = ImGui::GetIO(); io.AddKeyEvent(ImGuiMod_Ctrl, (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)); io.AddKeyEvent(ImGuiMod_Shift, (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS)); io.AddKeyEvent(ImGuiMod_Alt, (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS)); io.AddKeyEvent(ImGuiMod_Super, (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS)); } -static bool ImGui_ImplGlfw_ShouldChainCallback(GLFWwindow* window) +static bool ImGui_ImplGlfw_ShouldChainCallback(ImGui_ImplGlfw_Data* bd, GLFWwindow* window) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); return bd->CallbacksChainForAllWindows ? true : (window == bd->Window); } void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + + if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackMousebutton(window, button, action, mods); - ImGui_ImplGlfw_UpdateKeyModifiers(window); - - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); + ImGui_ImplGlfw_UpdateKeyModifiers(io, window); if (button >= 0 && button < ImGuiMouseButton_COUNT) io.AddMouseButtonEvent(button, action == GLFW_PRESS); } void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackScroll(window, xoffset, yoffset); #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 @@ -369,7 +384,7 @@ void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yo return; #endif - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddMouseWheelEvent((float)xoffset, (float)yoffset); } @@ -409,18 +424,18 @@ static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode) void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackKey(window, keycode, scancode, action, mods); if (action != GLFW_PRESS && action != GLFW_RELEASE) return; - ImGui_ImplGlfw_UpdateKeyModifiers(window); + ImGuiIO& io = ImGui::GetIO(bd->Context); + ImGui_ImplGlfw_UpdateKeyModifiers(io, window); keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode); - ImGuiIO& io = ImGui::GetIO(); ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode, scancode); io.AddKeyEvent(imgui_key, (action == GLFW_PRESS)); io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code) @@ -428,21 +443,21 @@ void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, i void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackWindowFocus(window, focused); - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddFocusEvent(focused != 0); } void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackCursorPos(window, x, y); - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddMousePosEvent((float)x, (float)y); bd->LastValidMousePos = ImVec2((float)x, (float)y); } @@ -451,11 +466,11 @@ void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y) // so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984) void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackCursorEnter(window, entered); - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); if (entered) { bd->MouseWindow = window; @@ -471,11 +486,11 @@ void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered) void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackChar(window, c); - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddInputCharacter(c); } @@ -485,17 +500,18 @@ void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int) } #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 -static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void*) +static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void* user_data) { // Mimic Emscripten_HandleWheel() in SDL. // Corresponding equivalent in GLFW JS emulation layer has incorrect quantizing preventing small values. See #6096 + ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data; float multiplier = 0.0f; if (ev->deltaMode == DOM_DELTA_PIXEL) { multiplier = 1.0f / 100.0f; } // 100 pixels make up a step. else if (ev->deltaMode == DOM_DELTA_LINE) { multiplier = 1.0f / 3.0f; } // 3 lines make up a step. else if (ev->deltaMode == DOM_DELTA_PAGE) { multiplier = 80.0f; } // A page makes up 80 steps. float wheel_x = ev->deltaX * -multiplier; float wheel_y = ev->deltaY * -multiplier; - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddMouseWheelEvent(wheel_x, wheel_y); //IMGUI_DEBUG_LOG("[Emsc] mode %d dx: %.2f, dy: %.2f, dz: %.2f --> feed %.2f %.2f\n", (int)ev->deltaMode, ev->deltaX, ev->deltaY, ev->deltaZ, wheel_x, wheel_y); return EM_TRUE; @@ -505,7 +521,6 @@ static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEven #ifdef _WIN32 // GLFW doesn't allow to distinguish Mouse vs TouchScreen vs Pen. // Add support for Win32 (based on imgui_impl_win32), because we rely on _TouchScreen info to trickle inputs differently. -namespace ImGui { extern ImGuiIO& GetIO(ImGuiContext*); } static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() { LPARAM extra_info = ::GetMessageExtraInfo(); @@ -517,10 +532,9 @@ static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() } static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { - ImGuiContext* ctx = (ImGuiContext*)::GetPropA(hWnd, "IMGUI_CONTEXT"); - ImGuiIO& io = ImGui::GetIO(ctx); + ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)::GetPropA(hWnd, "IMGUI_BACKEND_DATA"); + ImGuiIO& io = ImGui::GetIO(bd->Context); - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(io); switch (msg) { case WM_MOUSEMOVE: case WM_NCMOUSEMOVE: @@ -537,7 +551,7 @@ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wPara void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!"); IM_ASSERT(bd->Window == window); @@ -554,7 +568,7 @@ void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window) void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!"); IM_ASSERT(bd->Window == window); @@ -610,8 +624,10 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + bd->Context = ImGui::GetCurrentContext(); bd->Window = window; bd->Time = 0.0; + ImGui_ImplGlfw_ContextMap_Add(window, bd->Context); ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); #if GLFW_VERSION_COMBINED < 3300 @@ -669,8 +685,9 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Windows: register a WndProc hook so we can intercept some messages. #ifdef _WIN32 - ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_CONTEXT", ImGui::GetCurrentContext()); - bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_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 @@ -730,7 +747,7 @@ void ImGui_ImplGlfw_Shutdown() // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_CONTEXT", 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 @@ -738,6 +755,7 @@ void ImGui_ImplGlfw_Shutdown() io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); + ImGui_ImplGlfw_ContextMap_Remove(bd->Window); IM_DELETE(bd); } @@ -961,7 +979,7 @@ void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow*, const char* canvas_s // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096) // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves. // FIXME: May break chaining in case user registered their own Emscripten callback? - emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, ImGui_ImplEmscripten_WheelCallback); + emscripten_set_wheel_callback(bd->CanvasSelector, bd, false, ImGui_ImplEmscripten_WheelCallback); } #elif defined(EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3) // When using --use-port=contrib.glfw3 for the GLFW implementation, you can override the behavior of this call diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index 1ef9ade17..80e2b55ef 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -8,6 +8,7 @@ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Multiple Dear ImGui contexts support. // Missing features or Issues: // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. // [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 72edad331..b6f5c9e6e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -407,7 +407,7 @@ Other changes: - Backends: GLFW: added ImGui_ImplGlfw_GetContentScaleForMonitor(), ImGui_ImplGlfw_GetContentScaleForWindow() helpers. They are wrappers to glfwGetMonitorContentScale()/glfwGetWindowContentScale(), with compile-time GLFW version checks + returning 1.0f on Apple platform. - - Backends: GLFW: fixed Win32 specific WndProc handler relying on current context. (#8676, #8239, #8069) + - Backends: GLFW: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069) - Backends: SDL2: added ImGui_ImplSDL2_GetDpiScaleForDisplay() and ImGui_ImplSDL2_GetContentScaleForWindow() helpers. They are wrappers to SDL_GetDisplayDPI(), with compile-time SDL version checks + returning 1.0f on Apple platforms. SDL3 already does this by default. From 725d185a31f860b74014aba167aa69003d12c01a Mon Sep 17 00:00:00 2001 From: PlayDay <18056374+playday3008@users.noreply.github.com> Date: Thu, 19 Jun 2025 05:54:54 +0200 Subject: [PATCH 1105/2359] Backends: DirectX12: fixed build on MinGW. (#8702, #4594) --- backends/imgui_impl_dx12.cpp | 6 +++++- docs/CHANGELOG.txt | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index e3bcda195..5f7eec063 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-19: Fixed build on MinGW. (#8702, #4594) // 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX12: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-02-24: DirectX12: Fixed an issue where ImGui_ImplDX12_Init() signature change from 2024-11-15 combined with change from 2025-01-15 made legacy ImGui_ImplDX12_Init() crash. (#8429) @@ -61,6 +62,9 @@ #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif +// MinGW workaround, see #4594 +typedef decltype(D3D12SerializeRootSignature) *_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE; + // DirectX12 data struct ImGui_ImplDX12_RenderBuffers; @@ -618,7 +622,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return false; } - PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)(void*)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature"); + _PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)(void*)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature"); if (D3D12SerializeRootSignatureFn == nullptr) return false; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b6f5c9e6e..71549deb5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -392,6 +392,7 @@ Other changes: - Backends: SDLGPU3: added support for ImDrawCallback_ResetRenderState. (#8599) - Backends: OpenGL3: made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664) [@DyXel] + - Backends: DirectX12: Fixed build on MinGW. (#8702, #4594) [@playday3008] - Backends: DirectX10, DirectX11, DirectX12: Honor FramebufferScale to allow for custom platform backends and experiments using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). (#8412) [@WSSDude] From f7dabede8b1bd3e439c5bff048a22c8d00cd9fcf Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Jun 2025 09:45:26 +0200 Subject: [PATCH 1106/2359] Backends: Allegro5: Fixed missing invisible mouse cursor, broken by ee8941e0d. --- backends/imgui_impl_allegro5.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index b5f8ca00a..bd7f10c64 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -647,6 +647,9 @@ void ImGui_ImplAllegro5_NewFrame() ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?"); + if (!bd->MouseCursorInvisible) + ImGui_ImplAllegro5_CreateDeviceObjects(); + // Setup display size (every frame to accommodate for window resizing) ImGuiIO& io = ImGui::GetIO(); int w, h; From 8d6e66d38cfcf7e2057a378c14b5de64a04eaac8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Jun 2025 09:49:06 +0200 Subject: [PATCH 1107/2359] Backends: DX10, DX11, DX12, OpenGL3, Vulkan, WGPU: Assert when CreateDeviceObjects() calls return false. --- backends/imgui_impl_dx10.cpp | 3 ++- backends/imgui_impl_dx11.cpp | 3 ++- backends/imgui_impl_dx12.cpp | 3 ++- backends/imgui_impl_opengl3.cpp | 12 ++++++++---- backends/imgui_impl_vulkan.cpp | 3 ++- backends/imgui_impl_wgpu.cpp | 3 ++- 6 files changed, 18 insertions(+), 9 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 4dc5f884e..b7be791c7 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -642,7 +642,8 @@ void ImGui_ImplDX10_NewFrame() IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?"); if (!bd->pVertexShader) - ImGui_ImplDX10_CreateDeviceObjects(); + if (!ImGui_ImplDX10_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplDX10_CreateDeviceObjects() failed!"); } //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index 14e74e9b2..1917f6c0f 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -662,7 +662,8 @@ void ImGui_ImplDX11_NewFrame() IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX11_Init()?"); if (!bd->pVertexShader) - ImGui_ImplDX11_CreateDeviceObjects(); + if (!ImGui_ImplDX11_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplDX11_CreateDeviceObjects() failed!"); } //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 5f7eec063..1baa3c4e8 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -914,7 +914,8 @@ void ImGui_ImplDX12_NewFrame() IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?"); if (!bd->pPipelineState) - ImGui_ImplDX12_CreateDeviceObjects(); + if (!ImGui_ImplDX12_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplDX12_CreateDeviceObjects() failed!"); } //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 3f6c08756..40b3be68b 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -431,7 +431,8 @@ void ImGui_ImplOpenGL3_NewFrame() ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries. if (!bd->ShaderHandle) - ImGui_ImplOpenGL3_CreateDeviceObjects(); + if (!ImGui_ImplOpenGL3_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplOpenGL3_CreateDeviceObjects() failed!"); } static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object) @@ -965,21 +966,24 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() GL_CALL(vert_handle = glCreateShader(GL_VERTEX_SHADER)); glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr); glCompileShader(vert_handle); - CheckShader(vert_handle, "vertex shader"); + if (!CheckShader(vert_handle, "vertex shader")) + return false; const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader }; GLuint frag_handle; GL_CALL(frag_handle = glCreateShader(GL_FRAGMENT_SHADER)); glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr); glCompileShader(frag_handle); - CheckShader(frag_handle, "fragment shader"); + if (!CheckShader(frag_handle, "fragment shader")) + return false; // Link bd->ShaderHandle = glCreateProgram(); glAttachShader(bd->ShaderHandle, vert_handle); glAttachShader(bd->ShaderHandle, frag_handle); glLinkProgram(bd->ShaderHandle); - CheckProgram(bd->ShaderHandle, "shader program"); + if (!CheckProgram(bd->ShaderHandle, "shader program")) + return false; glDetachShader(bd->ShaderHandle, vert_handle); glDetachShader(bd->ShaderHandle, frag_handle); diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 3e2c043de..a0f787e8a 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1236,7 +1236,8 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) } #endif - ImGui_ImplVulkan_CreateDeviceObjects(); + if (!ImGui_ImplVulkan_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplVulkan_CreateDeviceObjects() failed!"); // <- Can't be hit yet. return true; } diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 09bd30ca8..c0ec2e3f9 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -901,7 +901,8 @@ void ImGui_ImplWGPU_NewFrame() { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); if (!bd->pipelineState) - ImGui_ImplWGPU_CreateDeviceObjects(); + if (!ImGui_ImplWGPU_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplWGPU_CreateDeviceObjects() failed!"); } //----------------------------------------------------------------------------- From 3a964d18e0e336b626a4b2e09536e087a81d382e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Jun 2025 10:11:07 +0200 Subject: [PATCH 1108/2359] Comments on ImGuiMod_XXXX and ImGuiKey_GamepadXXXX values. --- imgui.h | 69 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 35 insertions(+), 34 deletions(-) diff --git a/imgui.h b/imgui.h index ae0b90e8c..10eac63c9 100644 --- a/imgui.h +++ b/imgui.h @@ -1530,7 +1530,7 @@ enum ImGuiKey : int ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, - ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, + ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, // Also see ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiMod_Alt, ImGuiMod_Super below! ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper, ImGuiKey_Menu, ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, @@ -1570,32 +1570,34 @@ enum ImGuiKey : int ImGuiKey_AppForward, ImGuiKey_Oem102, // Non-US backslash. - // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION + // Gamepad + // (analog values are 0.0f to 1.0f) // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) - ImGuiKey_GamepadStart, // Menu (Xbox) + (Switch) Start/Options (PS) - ImGuiKey_GamepadBack, // View (Xbox) - (Switch) Share (PS) - ImGuiKey_GamepadFaceLeft, // X (Xbox) Y (Switch) Square (PS) // Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) - ImGuiKey_GamepadFaceRight, // B (Xbox) A (Switch) Circle (PS) // Cancel / Close / Exit - ImGuiKey_GamepadFaceUp, // Y (Xbox) X (Switch) Triangle (PS) // Text Input / On-screen Keyboard - ImGuiKey_GamepadFaceDown, // A (Xbox) B (Switch) Cross (PS) // Activate / Open / Toggle / Tweak - ImGuiKey_GamepadDpadLeft, // D-pad Left // Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadRight, // D-pad Right // Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadUp, // D-pad Up // Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadDown, // D-pad Down // Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadL1, // L Bumper (Xbox) L (Switch) L1 (PS) // Tweak Slower / Focus Previous (in Windowing mode) - ImGuiKey_GamepadR1, // R Bumper (Xbox) R (Switch) R1 (PS) // Tweak Faster / Focus Next (in Windowing mode) - ImGuiKey_GamepadL2, // L Trig. (Xbox) ZL (Switch) L2 (PS) [Analog] - ImGuiKey_GamepadR2, // R Trig. (Xbox) ZR (Switch) R2 (PS) [Analog] - ImGuiKey_GamepadL3, // L Stick (Xbox) L3 (Switch) L3 (PS) - ImGuiKey_GamepadR3, // R Stick (Xbox) R3 (Switch) R3 (PS) - ImGuiKey_GamepadLStickLeft, // [Analog] // Move Window (in Windowing mode) - ImGuiKey_GamepadLStickRight, // [Analog] // Move Window (in Windowing mode) - ImGuiKey_GamepadLStickUp, // [Analog] // Move Window (in Windowing mode) - ImGuiKey_GamepadLStickDown, // [Analog] // Move Window (in Windowing mode) - ImGuiKey_GamepadRStickLeft, // [Analog] - ImGuiKey_GamepadRStickRight, // [Analog] - ImGuiKey_GamepadRStickUp, // [Analog] - ImGuiKey_GamepadRStickDown, // [Analog] + // // XBOX | SWITCH | PLAYSTA. | -> ACTION + ImGuiKey_GamepadStart, // Menu | + | Options | + ImGuiKey_GamepadBack, // View | - | Share | + ImGuiKey_GamepadFaceLeft, // X | Y | Square | Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) + ImGuiKey_GamepadFaceRight, // B | A | Circle | Cancel / Close / Exit + ImGuiKey_GamepadFaceUp, // Y | X | Triangle | Text Input / On-screen Keyboard + ImGuiKey_GamepadFaceDown, // A | B | Cross | Activate / Open / Toggle / Tweak + ImGuiKey_GamepadDpadLeft, // D-pad Left | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadRight, // D-pad Right | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadUp, // D-pad Up | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadDown, // D-pad Down | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadL1, // L Bumper | L | L1 | Tweak Slower / Focus Previous (in Windowing mode) + ImGuiKey_GamepadR1, // R Bumper | R | R1 | Tweak Faster / Focus Next (in Windowing mode) + ImGuiKey_GamepadL2, // L Trigger | ZL | L2 | [Analog] + ImGuiKey_GamepadR2, // R Trigger | ZR | R2 | [Analog] + ImGuiKey_GamepadL3, // L Stick | L3 | L3 | + ImGuiKey_GamepadR3, // R Stick | R3 | R3 | + ImGuiKey_GamepadLStickLeft, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickRight, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickUp, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickDown, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadRStickLeft, // | | | [Analog] + ImGuiKey_GamepadRStickRight, // | | | [Analog] + ImGuiKey_GamepadRStickUp, // | | | [Analog] + ImGuiKey_GamepadRStickDown, // | | | [Analog] // Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls) // - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API. @@ -1603,11 +1605,15 @@ enum ImGuiKey : int // [Internal] Reserved for mod storage ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper, + + // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END. ImGuiKey_NamedKey_END, + ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) - // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing - // them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc. + // - Any functions taking a ImGuiKeyChord parameter can binary-or those with regular keys, e.g. Shortcut(ImGuiMod_Ctrl | ImGuiKey_S). + // - Those are written back into io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper for convenience, + // but may be accessed via standard key API such as IsKeyPressed(), IsKeyReleased(), querying duration etc. // - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those // and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiMod_Ctrl). // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys. @@ -1621,11 +1627,6 @@ enum ImGuiKey : int ImGuiMod_Super = 1 << 15, // Windows/Super (non-macOS), Ctrl (macOS) ImGuiMod_Mask_ = 0xF000, // 4-bits - // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END. - ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, - //ImGuiKey_KeysData_SIZE = ImGuiKey_NamedKey_COUNT, // Size of KeysData[]: only hold named keys - //ImGuiKey_KeysData_OFFSET = ImGuiKey_NamedKey_BEGIN, // Accesses to io.KeysData[] must use (key - ImGuiKey_NamedKey_BEGIN) index. - #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was extremely misleading (since named keys don't start at 0 anymore) ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl @@ -2514,7 +2515,7 @@ struct ImGuiIO // Other state maintained from data above + IO function calls ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. Read-only, updated by NewFrame() - ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. Use IsKeyXXX() functions to access this. + ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. MUST use 'key - ImGuiKey_NamedKey_BEGIN' as index. Use IsKeyXXX() functions to access this. bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) ImVec2 MouseClickedPos[5]; // Position at time of clicking From 9a50c091722bdc57355325d4b40dea1dcdfd0075 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Jun 2025 14:30:33 +0200 Subject: [PATCH 1109/2359] Bsckends: SDL2, GLFW: fixed ImGui_ImplXXXX_GetContentScaleXXX functions never using SDL 2.0.4 & GLFW 3.3 path in master. Amend 9da3e6696a, 8269924c (was broken for master) --- backends/imgui_impl_glfw.cpp | 1 + backends/imgui_impl_sdl2.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 5518a823e..a20759747 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -134,6 +134,7 @@ // We gather version tests as define in order to easily see which features are version-dependent. #define GLFW_VERSION_COMBINED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION) +#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetMonitorContentScale #ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released? #define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR #else diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 84ecc55e0..9fa8f296b 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -123,6 +123,7 @@ #else #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 #endif +#define SDL_HAS_PER_MONITOR_DPI SDL_VERSION_ATLEAST(2,0,4) #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) #define SDL_HAS_OPEN_URL SDL_VERSION_ATLEAST(2,0,14) #if SDL_HAS_VULKAN From 2f9c518ca89f80fccb96d5d3d335546b4ede78ef Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Jun 2025 15:15:27 +0200 Subject: [PATCH 1110/2359] Textures: ImTextureData::GetPixels() returns void* for clarity. --- imgui.h | 4 ++-- imgui_draw.cpp | 8 ++++---- imgui_internal.h | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 10eac63c9..061e6a9eb 100644 --- a/imgui.h +++ b/imgui.h @@ -3440,8 +3440,8 @@ struct ImTextureData ~ImTextureData() { DestroyPixels(); } IMGUI_API void Create(ImTextureFormat format, int w, int h); IMGUI_API void DestroyPixels(); - unsigned char* GetPixels() { IM_ASSERT(Pixels != NULL); return Pixels; } - unsigned char* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } + void* GetPixels() { IM_ASSERT(Pixels != NULL); return Pixels; } + void* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } int GetPitch() const { return Width * BytesPerPixel; } ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = ImTextureID_Invalid; return tex_ref; } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6ac946491..5a67b239a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2863,7 +2863,7 @@ void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data) void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor) { - unsigned char* pixels = data->Pixels; + unsigned char* pixels = (unsigned char*)data->Pixels; int pitch = data->Pitch; if (data->Format == ImTextureFormat_Alpha8) { @@ -3448,7 +3448,7 @@ void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, in { case ImTextureFormat_Alpha8: { - ImU8* out_p = tex->GetPixelsAt(x, y); + ImU8* out_p = (ImU8*)tex->GetPixelsAt(x, y); for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w) for (int off_x = 0; off_x < w; off_x++) out_p[off_x] = (in_str[off_x] == in_marker_char) ? 0xFF : 0x00; @@ -3456,7 +3456,7 @@ void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, in } case ImTextureFormat_RGBA32: { - ImU32* out_p = (ImU32*)(void*)tex->GetPixelsAt(x, y); + ImU32* out_p = (ImU32*)tex->GetPixelsAt(x, y); for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w) for (int off_x = 0; off_x < w; off_x++) out_p[off_x] = (in_str[off_x] == in_marker_char) ? IM_COL32_WHITE : IM_COL32_BLACK_TRANS; @@ -5124,7 +5124,7 @@ void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, { ImTextureData* tex = atlas->TexData; IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); - ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h); + ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, (unsigned char*)tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h); ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, glyph, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h }; ImFontAtlasTextureBlockPostProcess(&pp_data); ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); diff --git a/imgui_internal.h b/imgui_internal.h index 7ff24d889..b2656a734 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3746,7 +3746,7 @@ struct ImFontAtlasPostProcessData ImFontGlyph* Glyph; // Pixel data - unsigned char* Pixels; + void* Pixels; ImTextureFormat Format; int Pitch; int Width; From e97e55adbc025325e16a48f5970fd1e1d85d588e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Jun 2025 14:46:32 +0200 Subject: [PATCH 1111/2359] Backends: Fixed various warnings discovered when using MinGW GCC 15/Clang on latest backends. dx12: 'ImGui_ImplDX12_Data* bd' shadowed local in spite of being in lambda. --- backends/imgui_impl_dx10.cpp | 6 ++++ backends/imgui_impl_dx11.cpp | 6 ++++ backends/imgui_impl_dx12.cpp | 47 +++++++++++++++++----------- backends/imgui_impl_dx9.cpp | 10 ++++-- backends/imgui_impl_glfw.cpp | 1 + backends/imgui_impl_sdl2.cpp | 5 ++- backends/imgui_impl_sdl3.cpp | 7 +++-- backends/imgui_impl_sdlrenderer2.cpp | 2 ++ backends/imgui_impl_sdlrenderer3.cpp | 2 ++ backends/imgui_impl_vulkan.cpp | 2 +- backends/imgui_impl_win32.cpp | 1 + imgui_demo.cpp | 2 +- 12 files changed, 66 insertions(+), 25 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index b7be791c7..6bc52156f 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -50,6 +50,12 @@ #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#endif + // DirectX10 data struct ImGui_ImplDX10_Texture { diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index 1917f6c0f..1b28745a3 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -52,6 +52,12 @@ #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#endif + // DirectX11 data struct ImGui_ImplDX11_Texture { diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 1baa3c4e8..557850979 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -62,6 +62,12 @@ #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#endif + // MinGW workaround, see #4594 typedef decltype(D3D12SerializeRootSignature) *_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE; @@ -800,6 +806,28 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() } } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +static void ImGui_ImplDX12_InitLegacySingleDescriptorMode(ImGui_ImplDX12_InitInfo* init_info) +{ + // Wrap legacy behavior of passing space for a single descriptor + IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0); + init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle) + { + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + IM_ASSERT(bd->LegacySingleDescriptorUsed == false && "Only 1 simultaneous texture allowed with legacy ImGui_ImplDX12_Init() signature!"); + *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor; + *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor; + bd->LegacySingleDescriptorUsed = true; + }; + init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE) + { + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + IM_ASSERT(bd->LegacySingleDescriptorUsed == true); + bd->LegacySingleDescriptorUsed = false; + }; +} +#endif + bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) { ImGuiIO& io = ImGui::GetIO(); @@ -826,24 +854,7 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (init_info->SrvDescriptorAllocFn == nullptr) - { - // Wrap legacy behavior of passing space for a single descriptor - IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0); - init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle) - { - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - IM_ASSERT(bd->LegacySingleDescriptorUsed == false && "Only 1 simultaneous texture allowed with legacy ImGui_ImplDX12_Init() signature!"); - *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor; - *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor; - bd->LegacySingleDescriptorUsed = true; - }; - init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE) - { - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - IM_ASSERT(bd->LegacySingleDescriptorUsed == true); - bd->LegacySingleDescriptorUsed = false; - }; - } + ImGui_ImplDX12_InitLegacySingleDescriptorMode(init_info); #endif IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr); diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 2617988e7..5f3f3bd1c 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -46,6 +46,12 @@ // DirectX #include +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#endif + // DirectX data struct ImGui_ImplDX9_Data { @@ -368,8 +374,8 @@ static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, const ImU32* sr #endif for (int y = 0; y < h; y++) { - ImU32* src_p = (ImU32*)((unsigned char*)src + src_pitch * y); - ImU32* dst_p = (ImU32*)((unsigned char*)dst + dst_pitch * y); + const ImU32* src_p = (const ImU32*)(void*)((const unsigned char*)src + src_pitch * y); + ImU32* dst_p = (ImU32*)(void*)((unsigned char*)dst + dst_pitch * y); if (convert_rgba_to_bgra) for (int x = w; x > 0; x--, src_p++, dst_p++) // Convert copy *dst_p = IMGUI_COL_TO_DX9_ARGB(*src_p); diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index a20759747..d0a75ac78 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -545,6 +545,7 @@ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wPara case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: case WM_XBUTTONUP: io.AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); break; + default: break; } return ::CallWindowProcW(bd->PrevWndProc, hWnd, msg, wParam, lParam); } diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 9fa8f296b..9f5e0374a 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -104,6 +104,7 @@ // Clang warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif @@ -434,7 +435,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) // (event->type == SDL_KEYDOWN) ? "DOWN" : "UP ", event->key.keysym.sym, SDL_GetKeyName(event->key.keysym.sym), event->key.keysym.scancode, SDL_GetScancodeName(event->key.keysym.scancode), event->key.keysym.mod); ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode); io.AddKeyEvent(key, (event->type == SDL_KEYDOWN)); - io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. + io.SetKeyEventNativeData(key, (int)event->key.keysym.sym, (int)event->key.keysym.scancode, (int)event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. return true; } case SDL_WINDOWEVENT: @@ -466,6 +467,8 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) bd->WantUpdateGamepadsList = true; return true; } + default: + break; } return false; } diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 4f099595a..68fc4d746 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -64,6 +64,7 @@ // Clang warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif @@ -409,7 +410,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) // (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP ", event->key.key, SDL_GetKeyName(event->key.key), event->key.scancode, SDL_GetScancodeName(event->key.scancode), event->key.mod); ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode); io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN)); - io.SetKeyEventNativeData(key, event->key.key, event->key.scancode, event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. + io.SetKeyEventNativeData(key, (int)event->key.key, (int)event->key.scancode, (int)event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. return true; } case SDL_EVENT_WINDOW_MOUSE_ENTER: @@ -445,6 +446,8 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) bd->WantUpdateGamepadsList = true; return true; } + default: + break; } return false; } @@ -471,7 +474,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void // Setup backend capabilities flags ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)(); - snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl3 (%u.%u.%u; %u.%u.%u)", + snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl3 (%d.%d.%d; %d.%d.%d)", SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_MICRO_VERSION, SDL_VERSIONNUM_MAJOR(ver_linked), SDL_VERSIONNUM_MINOR(ver_linked), SDL_VERSIONNUM_MICRO(ver_linked)); io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = bd->BackendPlatformName; diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index bcc4404ff..a39360f5c 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -44,6 +44,8 @@ #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe #endif // SDL diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 77b5bc059..f62949150 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -41,6 +41,8 @@ #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe #endif // SDL diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index a0f787e8a..5546a59ff 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1250,7 +1250,7 @@ void ImGui_ImplVulkan_Shutdown() ImGui_ImplVulkan_DestroyDeviceObjects(); #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - IM_FREE((void*)bd->VulkanInitInfo.PipelineRenderingCreateInfo.pColorAttachmentFormats); + IM_FREE((void*)const_cast(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pColorAttachmentFormats)); #endif io.BackendRendererName = nullptr; diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index cd5e2dbf2..d7206b970 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -571,6 +571,7 @@ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam) case 51: return ImGuiKey_Comma; case 52: return ImGuiKey_Period; case 53: return ImGuiKey_Slash; + default: break; } return ImGuiKey_None; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 899932066..a979b9e92 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8146,7 +8146,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) ImGui::Text(" RendererHasTextures"); ImGui::Separator(); ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexData->Width, io.Fonts->TexData->Height); - ImGui::Text("io.Fonts->FontLoaderName: \"%s\"", io.Fonts->FontLoaderName ? io.Fonts->FontLoaderName : "NULL"); + ImGui::Text("io.Fonts->FontLoaderName: %s", io.Fonts->FontLoaderName ? io.Fonts->FontLoaderName : "NULL"); ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); ImGui::Separator(); From afe20dc9b608e29b2e75964327287cf5588c1d2d Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Jun 2025 15:23:52 +0200 Subject: [PATCH 1112/2359] Backends: warning fix. --- backends/imgui_impl_dx9.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 5f3f3bd1c..b0159bf37 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -374,7 +374,7 @@ static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, const ImU32* sr #endif for (int y = 0; y < h; y++) { - const ImU32* src_p = (const ImU32*)(void*)((const unsigned char*)src + src_pitch * y); + const ImU32* src_p = (const ImU32*)(const void*)((const unsigned char*)src + src_pitch * y); ImU32* dst_p = (ImU32*)(void*)((unsigned char*)dst + dst_pitch * y); if (convert_rgba_to_bgra) for (int x = w; x > 0; x--, src_p++, dst_p++) // Convert copy From 0dc2885f3e0890585a0fa61a1ea041df9609b0ab Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 22 Jun 2025 13:04:06 +0200 Subject: [PATCH 1113/2359] InputText: fix for InsertChars() to work on read-only buffer. (#8714, #8689, #8242) Ill defined feature but memory editor use InsertChars etc on a read-only buffer. `if (init_state)` block of InputTextEx() intentionally does not resize TextA, as unneeded. Amend b2c73596aeaf63b46b66a615ec02fce1b87f4248 Amend e900571 --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 43d98bb88..d7214b6c2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4289,7 +4289,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons // Grow internal buffer if needed const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text); - if (new_text_len + BufTextLen + 1 > obj->TextA.Size) + if (new_text_len + BufTextLen + 1 > obj->TextA.Size && (Flags & ImGuiInputTextFlags_ReadOnly) == 0) { if (!is_resizable) return; From 613a6a964c9183c1fcdffde792ae96bc9fdfb944 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 10:27:24 +0200 Subject: [PATCH 1114/2359] Fonts: AddFontDefault() adds to GlyphOffset.y instead of overriding it. --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5a67b239a..0b4175126 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3102,7 +3102,7 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) if (font_cfg.Name[0] == '\0') ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf"); font_cfg.EllipsisChar = (ImWchar)0x0085; - font_cfg.GlyphOffset.y = 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units + font_cfg.GlyphOffset.y += 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units int ttf_compressed_size = 0; const char* ttf_compressed = GetDefaultCompressedFontDataTTF(&ttf_compressed_size); From a49ddaac897538aee7b8dffe4f7cc537ac9e8e9a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 10:50:30 +0200 Subject: [PATCH 1115/2359] Fonts: add comments and examples for GlyphExcludeRanges[]. --- docs/CHANGELOG.txt | 22 +++++++++++++++++++++- docs/FONTS.md | 39 +++++++++++++++++++++++++++++++++++++++ imgui.cpp | 19 +++++++++++++++++-- imgui.h | 2 +- 4 files changed, 78 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 71549deb5..4b879a6cb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,7 +62,7 @@ Breaking changes: - Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f): - This WILL NOT map correctly to the new system! Because font will rasterize as requested size. + - This WILL NOT map correctly to the new system! Because font will rasterize as requested size. - With a legacy backend (< 1.92): - Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. - This already worked before, but is now pretty much required. @@ -84,6 +84,26 @@ Breaking changes: - ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). - Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. +- Fonts: **IMPORTANT** on Font Merging: + - When searching for a glyph in multiple merged fonts: font inputs are now scanned in order + for the first font input which the desired glyph. This is technically a different behavior + than before! + - e.g. If you are merging fonts you may have glyphs that you expected to load from + Font Source 2 which exists in Font Source 1. After the update and when using a new backend, + those glyphs may now loaded from Font Source 1! + - You can use `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to ignore in given Input: + // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range + static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; + ImFontConfig cfg1; + cfg1.GlyphExcludeRanges = exclude_ranges; + io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1); + // Add Font Source 2, which expects to use the range above + ImFontConfig cfg2; + cfg2.MergeMode = true; + io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); + - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to + see list of glyphs available in multiple font sources. This can facilitate understanding + which font input is providing which glyph. - Textures: - All API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef': diff --git a/docs/FONTS.md b/docs/FONTS.md index 95538f97d..8edfbd33b 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -18,6 +18,7 @@ In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) fo - [Loading Font Data from Memory](#loading-font-data-from-memory) - [Loading Font Data Embedded In Source Code](#loading-font-data-embedded-in-source-code) - [Using Icon Fonts](#using-icon-fonts) + - [Excluding Overlapping Ranges](#excluding-overlapping-ranges) - [Using FreeType Rasterizer (imgui_freetype)](#using-freetype-rasterizer-imgui_freetype) - [Using Colorful Glyphs/Emojis](#using-colorful-glyphsemojis) - [Using Custom Glyph Ranges](#using-custom-glyph-ranges) @@ -313,6 +314,44 @@ Here's an application using icons ("Avoyd", https://www.avoyd.com): --------------------------------------- +### Excluding Overlapping Ranges + +🆕 **Since 1.92, with an up to date backend: glyphs ranges are ignored**: when loading a glyph, input fonts in the merge list are queried in order. The first font which has the glyph loads it. +
‼️ **If you are merging several fonts, you may have undesirable overlapping ranges.** You can use `ImFontConfig::GlyphExcludeRanges[] `to specify ranges to ignore in a given Input. + +```cpp +// Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range +static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; +ImFontConfig cfg1; +cfg1.GlyphExcludeRanges = exclude_ranges; +io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1); + +// Add Font Source 2, which expects to use the range above +ImFontConfig cfg2; +cfg2.MergeMode = true; +io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); +``` +Another (silly) example: +```cpp +// Remove 'A'-'Z' from first font +static ImWchar exclude_ranges[] = { 'A', 'Z', 0 }; +ImFontConfig cfg1; +cfg1.GlyphExcludeRanges = exclude_ranges; +io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1); + +// Load another font to fill the gaps +ImFontConfig cfg2; +cfg2.MergeMode = true; +io.Fonts->AddFontFromFileTTF("Roboto-Medium.ttf", 0.0f, &cfg2); +``` +![image](https://github.com/user-attachments/assets/f3d751d3-1aee-4698-bd9b-f511902f56bb) + +You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate understanding which font input is providing which glyph. + +##### [Return to Index](#index) + +--------------------------------------- + ## Using FreeType Rasterizer (imgui_freetype) - Dear ImGui uses [stb_truetype.h](https://github.com/nothings/stb/) to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. diff --git a/imgui.cpp b/imgui.cpp index af22c37fa..2b4a98802 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -474,6 +474,20 @@ CODE - Before 1.92: ImGui::PushFont() always used font "default" size specified in AddFont() call. - Since 1.92: ImGui::PushFont() preserve the current font size which is a shared value. - To use old behavior: (A) use 'ImGui::PushFont(font, font->LegacySize)' at call site (preferred). (B) Set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call (not desirable as it requires e.g. third-party code to be aware of it). + - Fonts: **IMPORTANT** on Font Merging: + - When searching for a glyph in multiple merged fonts: font inputs are now scanned in orderfor the first font input which the desired glyph. This is technically a different behavior than before! + - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1. After the update and when using a new backend, those glyphs may now loaded from Font Source 1! + - You can use `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to ignore in given Input: + // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range + static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; + ImFontConfig cfg1; + cfg1.GlyphExcludeRanges = exclude_ranges; + io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1); + // Add Font Source 2, which expects to use the range above + ImFontConfig cfg2; + cfg2.MergeMode = true; + io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); + - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate unde - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded(). @@ -3932,7 +3946,7 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso ImGuiContext& g = *GImGui; if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values. mouse_cursor = ImGuiMouseCursor_Arrow; - ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas; + ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas; for (ImGuiViewportP* viewport : g.Viewports) { // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. @@ -16958,7 +16972,8 @@ void ImGui::DebugNodeFont(ImFont* font) } if (font->Sources.Size > 1 && TreeNode("Input Glyphs Overlap Detection Tool")) { - TextWrapped("- First Input that contains the glyph is used.\n- Use ImFontConfig::GlyphExcludeRanges[] to specify ranges to ignore glyph in given Input.\n- This tool doesn't cache results and is slow, don't keep it open!"); + TextWrapped("- First Input that contains the glyph is used.\n" + "- Use ImFontConfig::GlyphExcludeRanges[] to specify ranges to ignore glyph in given Input.\n- Prefer using a small number of ranges as the list is scanned every time a new glyph is loaded,\n - e.g. GlyphExcludeRanges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };\n- This tool doesn't cache results and is slow, don't keep it open!"); if (BeginTable("table", 2)) { for (unsigned int c = 0; c < 0x10000; c++) diff --git a/imgui.h b/imgui.h index 061e6a9eb..ba8001d87 100644 --- a/imgui.h +++ b/imgui.h @@ -3474,7 +3474,7 @@ struct ImFontConfig ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). const ImWchar* GlyphRanges; // NULL // *LEGACY* THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). - const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a VERY SHORT user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. + const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a small user-provided list of Unicode ranges (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. From 608dd96de654b9831c9d2c7d31fd0806df4b358e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 12:21:07 +0200 Subject: [PATCH 1116/2359] Fonts: fixed RenderText() asserting when crossing VtxOffset change boundaries. (#8720, #8465) --- imgui_draw.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0b4175126..8d56c0178 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5581,7 +5581,6 @@ begin: return; // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) - const int cmd_count = draw_list->CmdBuffer.Size; const int vtx_count_max = (int)(text_end - s) * 4; const int idx_count_max = (int)(text_end - s) * 6; const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; @@ -5589,6 +5588,7 @@ begin: ImDrawVert* vtx_write = draw_list->_VtxWritePtr; ImDrawIdx* idx_write = draw_list->_IdxWritePtr; unsigned int vtx_index = draw_list->_VtxCurrentIdx; + const int cmd_count = draw_list->CmdBuffer.Size; const ImU32 col_untinted = col | ~IM_COL32_A_MASK; const char* word_wrap_eol = NULL; @@ -5711,6 +5711,8 @@ begin: draw_list->CmdBuffer.pop_back(); draw_list->PrimUnreserve(idx_count_max, vtx_count_max); draw_list->AddDrawCmd(); + //IMGUI_DEBUG_LOG("RenderText: cancel and retry to missing glyphs.\n"); // [DEBUG] + //draw_list->AddRectFilled(pos, pos + ImVec2(10, 10), IM_COL32(255, 0, 0, 255)); // [DEBUG] goto begin; //RenderText(draw_list, size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip); // FIXME-OPT: Would a 'goto begin' be better for code-gen? //return; From 6e846c56b4823110269eb6530468eaf5b106019c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 12:25:04 +0200 Subject: [PATCH 1117/2359] Demo: fixed ID conflicts. (#8723) --- imgui_demo.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a979b9e92..8a4c4584e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4444,11 +4444,11 @@ static void DemoWindowLayout() ImGui::Text("SetNextItemWidth/PushItemWidth(-Min(GetContentRegionAvail().x * 0.40f, GetFontSize() * 12))"); ImGui::PushItemWidth(-IM_MIN(ImGui::GetFontSize() * 12, ImGui::GetContentRegionAvail().x * 0.40f)); - ImGui::DragFloat("float##4a", &f); + ImGui::DragFloat("float##5a", &f); if (show_indented_items) { ImGui::Indent(); - ImGui::DragFloat("float (indented)##4b", &f); + ImGui::DragFloat("float (indented)##5b", &f); ImGui::Unindent(); } ImGui::PopItemWidth(); @@ -4458,11 +4458,11 @@ static void DemoWindowLayout() ImGui::Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)"); ImGui::SameLine(); HelpMarker("Align to right edge"); ImGui::PushItemWidth(-FLT_MIN); - ImGui::DragFloat("##float5a", &f); + ImGui::DragFloat("##float6a", &f); if (show_indented_items) { ImGui::Indent(); - ImGui::DragFloat("float (indented)##5b", &f); + ImGui::DragFloat("float (indented)##6b", &f); ImGui::Unindent(); } ImGui::PopItemWidth(); From 6722d789e91b78f8c1565dbeabfbacd8a1ce87a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 14:44:38 +0200 Subject: [PATCH 1118/2359] (Breaking) Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font". --- docs/CHANGELOG.txt | 1 + imgui.cpp | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4b879a6cb..1f166b629 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,6 +83,7 @@ Breaking changes: (not desirable as it requires e.g. all third-party code to be aware of it). - ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). + - Removed support for PushFont(NULL) which was a shortcut for "default font". - Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. - Fonts: **IMPORTANT** on Font Merging: - When searching for a glyph in multiple merged fonts: font inputs are now scanned in order diff --git a/imgui.cpp b/imgui.cpp index 2b4a98802..1234bce4d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -489,6 +489,7 @@ CODE io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate unde - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). + - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font". - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded(). - Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID(), IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete). @@ -8906,9 +8907,11 @@ void ImGui::SetFontRasterizerDensity(float rasterizer_density) void ImGui::PushFont(ImFont* font, float font_size_base) { ImGuiContext& g = *GImGui; + //if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont()) + // font = g.Font; + IM_ASSERT(font != NULL); + g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize }); - if (font == NULL) - font = GetDefaultFont(); if (font_size_base <= 0.0f) { if (font->Flags & ImFontFlags_DefaultToLegacySize) From 0218ddd5753f0b028ad65a5a1a6b4ce0fdc41168 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 15:00:42 +0200 Subject: [PATCH 1119/2359] Fonts: moved GetFont(), GetFontSize(), GetFontBaked() to higher section. --- imgui.h | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index ba8001d87..b73089d66 100644 --- a/imgui.h +++ b/imgui.h @@ -499,14 +499,16 @@ namespace ImGui // - To use old behavior (single size font, size specified in AddFontXXX() call: // - Use 'PushFont(font, font->LegacySize)' at call site // - Or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' before calling AddFont(), and then 'PushFont(font)' will use this size. - // - External scale factors are applied over the provided value. - // *IMPORTANT* If you want to scale an existing font size: - // - OK: PushFontSize(style.FontSizeBase * factor) (= value before external scale factors applied). - // - KO: PushFontSize(GetFontSize() * factor) (= value after external scale factors applied. external scale factors are style.FontScaleMain + per-viewport scales.). + // *IMPORTANT* External scale factors are applied over the provided value. If you want to scale an existing font size: + // - OK: PushFontSize(style.FontSizeBase * 2.0f) (= value before external scale factors applied). + // - NOT OK: PushFontSize(GetFontSize() * 2.0f) (= value after external scale factors applied. External scale factors are: 'style.FontScaleMain * style.FontScaleDpi * maybe more'). IMGUI_API void PushFont(ImFont* font, float font_size_base = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. IMGUI_API void PopFont(); - IMGUI_API void PushFontSize(float font_size_base); + IMGUI_API void PushFontSize(float font_size_base); // keep current font, change its size. Final 'font size = font_size_base * external scale factors'. IMGUI_API void PopFontSize(); + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) AFTER external scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()/PushFontSize()! Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. + IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) // Parameters stacks (shared) IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). @@ -530,10 +532,7 @@ namespace ImGui // Style read access // - Use the ShowStyleEditor() function to interactively see/edit the colors. - IMGUI_API ImFont* GetFont(); // get current font - IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with external scale factors applied. Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a white pixel, useful to draw custom shapes via the ImDrawList API - IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList IMGUI_API ImU32 GetColorU32(ImU32 col, float alpha_mul = 1.0f); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList From 776897d3c9ae721dcb1dfa935162a67dbac7a69d Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 15:24:09 +0200 Subject: [PATCH 1120/2359] Fonts: fixed PVS Studio false positive "expression 'cmd_count != draw_list->CmdBuffer.Size' is always false." (#8720, #8465) Amend 608dd96 --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8d56c0178..50b486cad 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5705,7 +5705,7 @@ begin: } // Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui:: calls because CalcTextSize() is always used. - if (cmd_count != draw_list->CmdBuffer.Size) + if (cmd_count != draw_list->CmdBuffer.Size) //-V547 { IM_ASSERT(draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount == 0); draw_list->CmdBuffer.pop_back(); From 04a5b9c2cf58c78b116e4dbcfe90f8cb1eec2a07 Mon Sep 17 00:00:00 2001 From: Geert Bleyen Date: Tue, 24 Jun 2025 16:13:44 +0200 Subject: [PATCH 1121/2359] Backends: SDL3: fixed pulling SDL_PROP_WINDOW_COCOA_WINDOW_POINTER into viewport->PlatformHandleRaw. (#8725, #8726) SDL_VIDEO_DRIVER_COCOA does not exist on SDL3. --- backends/imgui_impl_sdl3.cpp | 2 +- docs/CHANGELOG.txt | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 68fc4d746..9c0d6581c 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -458,7 +458,7 @@ static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Win viewport->PlatformHandleRaw = nullptr; #if defined(_WIN32) && !defined(__WINRT__) viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); -#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) +#elif defined(__APPLE__) viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr); #endif } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1f166b629..948b3d326 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -445,6 +445,8 @@ Other changes: memory ownership change. (#8530, #7801) [@Green-Sky] - Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) + - Backends: SDL3: fixed pulling SDL_PROP_WINDOW_COCOA_WINDOW_POINTER into + viewport->PlatformHandleRaw. (#8725, #8726) [@eertbleyen] - Backends: OSX: ImGui_ImplOSX_HandleEvent() only process event for window containing our view. (#8644) [@BingoXuan] - Examples: From ca72eb059648efdba4617170005206d7d44539dc Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 18:53:40 +0200 Subject: [PATCH 1122/2359] (Breaking) Fonts: obsolete PushFont() default parameter. --- docs/CHANGELOG.txt | 26 +++++++++++++++++--------- imgui.cpp | 20 ++++++++++---------- imgui.h | 30 ++++++++++++++++++------------ 3 files changed, 45 insertions(+), 31 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 948b3d326..d468b60ae 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -73,17 +73,25 @@ Breaking changes: Platform_GetWindowFramebufferScale() handler in 'docking' branch. - Fonts: **IMPORTANT** on Font Sizing: - Before 1.92, fonts were of a single size. They can now be dynamically sized. - - PushFont() API now has an optional size parameter. PushFontSize() was also added. - void PushFont(ImFont* font) --> void PushFont(ImFont* font, float size = 0.0f); - - Before 1.92: ImGui::PushFont() always used font "default" size specified in AddFont() call. - - Since 1.92: ImGui::PushFont() preserve the current font size which is a shared value. + - PushFont() API now has a REQUIRED size parameter. + void PushFont(ImFont* font) --> void PushFont(ImFont* font, float size); + - PushFont(font, 0.0f) // Change font and keep current size + - PushFont(NULL, 20.0f) // Keep font and change current size + - PushFont(font, 20.0f) // Change font and set size to 20.0f + - PushFont(font, style.FontSizeBase * 2.0f) // Change font and set size to be twice bigger than current size. + - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavor, for fixed size fonts. - To use old behavior: - use 'ImGui::PushFont(font, font->LegacySize)' at call site (preferred). - or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call (not desirable as it requires e.g. all third-party code to be aware of it). + We intentionally didn't add a default parameter because it would make the long-term + transition more difficult. + - Kept inline redirection font. Will obsolete. + - External scale factors may be applied over the provided size. + This is why it is called 'FontSizeBase' in the style structure. - ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). - - Removed support for PushFont(NULL) which was a shortcut for "default font". + - Removed support for old PushFont(NULL) which was a shortcut for "revert to default font". - Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. - Fonts: **IMPORTANT** on Font Merging: - When searching for a glyph in multiple merged fonts: font inputs are now scanned in order @@ -182,8 +190,8 @@ Breaking changes: - renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader() - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader(); -- DrawList: Fixed a regression from 1.91.1 where a Begin()/PushFont()/AddImage() sequence - would not restore the correct atlas Texture Identifier when the PushFont() call used +- DrawList: Fixed a regression from 1.91.1 where a Begin()/PushFont()/AddImage() sequence + would not restore the correct atlas Texture Identifier when the PushFont() call used a font from a different atlas. (#8694, caused by #3224, #3875, #6398, #7903) - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). - Fonts: (users of custom rectangles) @@ -332,7 +340,7 @@ Other changes: one in docking (they accidentally diverged). (#8554) - Windows: BeginChild(): fixed being unable to combine manual resize on one axis and automatic resize on the other axis. (#8690) - e.g. neither ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeY + e.g. neither ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeY or ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX worked before. - TreeNode: added experimental flags to draw tree hierarchy outlines linking parent and tree nodes: (#2920) @@ -357,7 +365,7 @@ Other changes: - TreeNode: fixed incorrect clipping of arrow/bullet when using ImGuiTreeNodeFlags_SpanAllColumns. - InputText: fixed cursor positioning issue using up/down keys near end of lines while editing non-ASCII text. (Regression from 1.91.2) (#8635, #7925) -- InputText: fixed a buffer overrun that could happen when using dynamically resizing +- InputText: fixed a buffer overrun that could happen when using dynamically resizing buffers (e.g. imgui_stdlib.cpp for std::string, or ImGuiInputTextFlags_CallbackRezize) and programmatically making an insertion. (#8689) [@ocornut, @m9710797] - Tables: fixed TableHeader() eager vertical clipping of text which may be noticeable diff --git a/imgui.cpp b/imgui.cpp index 1234bce4d..44a613ac9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -470,10 +470,11 @@ CODE - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required. - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch. - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized. - - PushFont() API now has an optional size parameter. PushFontSize() was also added. - - Before 1.92: ImGui::PushFont() always used font "default" size specified in AddFont() call. - - Since 1.92: ImGui::PushFont() preserve the current font size which is a shared value. + - PushFont() API now has a REQUIRED size parameter. PushFontSize() was also added. + - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize). + - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value. - To use old behavior: (A) use 'ImGui::PushFont(font, font->LegacySize)' at call site (preferred). (B) Set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call (not desirable as it requires e.g. third-party code to be aware of it). + - Kept inline single parameter function. Will obsolete. - Fonts: **IMPORTANT** on Font Merging: - When searching for a glyph in multiple merged fonts: font inputs are now scanned in orderfor the first font input which the desired glyph. This is technically a different behavior than before! - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1. After the update and when using a new backend, those glyphs may now loaded from Font Source 1! @@ -8901,23 +8902,22 @@ void ImGui::SetFontRasterizerDensity(float rasterizer_density) UpdateCurrentFontSize(0.0f); } -// If you want to scale an existing font size: -// - Use e.g. PushFontSize(style.FontSizeBase * factor) (= value before external scale factors applied). -// - Do NOT use PushFontSize(GetFontSize() * factor) (= value after external scale factors applied). +// If you want to scale an existing font size! Read comments in imgui.h! void ImGui::PushFont(ImFont* font, float font_size_base) { ImGuiContext& g = *GImGui; //if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont()) // font = g.Font; IM_ASSERT(font != NULL); + IM_ASSERT(font_size_base >= 0.0f); g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize }); - if (font_size_base <= 0.0f) + if (font_size_base == 0.0f) { if (font->Flags & ImFontFlags_DefaultToLegacySize) - font_size_base = font->LegacySize; // Legacy: use AddFont() specified font size. Same as doing PushFont(font, font->LegacySize) + font_size_base = font->LegacySize; // Legacy: use AddFont() specified font size. Same as doing PushFont(font, font->LegacySize) else - font_size_base = g.FontSizeBase; // Keep current font size + font_size_base = g.FontSizeBase; // Keep current font size } SetCurrentFont(font, font_size_base, 0.0f); } @@ -16909,7 +16909,7 @@ void ImGui::DebugNodeFont(ImFont* font) Indent(); if (cfg->ShowFontPreview) { - PushFont(font); + PushFont(font, 0.0f); Text("The quick brown fox jumps over the lazy dog"); PopFont(); } diff --git a/imgui.h b/imgui.h index b73089d66..2c361c4cf 100644 --- a/imgui.h +++ b/imgui.h @@ -493,21 +493,26 @@ namespace ImGui IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. // Parameters stacks (font) + // - PushFont(font, 0.0f) // Change font and keep current size + // - PushFont(NULL, 20.0f) // Keep font and change current size + // - PushFont(font, 20.0f) // Change font and set size to 20.0f + // - PushFont(font, style.FontSizeBase * 2.0f) // Change font and set size to be twice bigger than current size. + // - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavior. // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. - // - Before 1.92: PushFont() always used font default size. - // - Since 1.92: PushFont() preserve the current shared font size. - // - To use old behavior (single size font, size specified in AddFontXXX() call: - // - Use 'PushFont(font, font->LegacySize)' at call site - // - Or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' before calling AddFont(), and then 'PushFont(font)' will use this size. - // *IMPORTANT* External scale factors are applied over the provided value. If you want to scale an existing font size: - // - OK: PushFontSize(style.FontSizeBase * 2.0f) (= value before external scale factors applied). - // - NOT OK: PushFontSize(GetFontSize() * 2.0f) (= value after external scale factors applied. External scale factors are: 'style.FontScaleMain * style.FontScaleDpi * maybe more'). - IMGUI_API void PushFont(ImFont* font, float font_size_base = -1); // use NULL as a shortcut to push default font. Use <0.0f to keep current font size. + // - In 1.92 we have REMOVED the single parameter version of PushFont() because it seems like the easiest way to provide an error-proof transition. + // - PushFont(font) before 1.92 = PushFont(font, font->LegacySize) after 1.92 // Use default font size as passed to AddFontXXX() function. + // *IMPORTANT* external scale factors are applied over the provided size. If you want to scale an *existing* font size: + // - External scale factors are: 'style.FontScaleMain * style.FontScaleDpi' and maybe more. + // - CORRECT: PushFont(NULL, style.FontSizeBase) // use current unscaled size == does nothing + // - CORRECT: PushFont(NULL, style.FontSizeBase * 2.0f) // use current unscaled size x2 == make text twice bigger + // - INCORRECT: PushFont(NULL, GetFontSize()) // INCORRECT! use size after external factors applied == EXTERNAL SCALING FACTORS WILL APPLY TWICE! + // - INCORRECT: PushFont(NULL, GetFontSize() * 2.0f) // INCORRECT! use size after external factors applied == EXTERNAL SCALING FACTORS WILL APPLY TWICE! + IMGUI_API void PushFont(ImFont* font, float font_size_base_unscaled); // Use NULL as a shortcut to keep current font. Use 0.0f to keep current size. IMGUI_API void PopFont(); IMGUI_API void PushFontSize(float font_size_base); // keep current font, change its size. Final 'font size = font_size_base * external scale factors'. IMGUI_API void PopFontSize(); IMGUI_API ImFont* GetFont(); // get current font - IMGUI_API float GetFontSize(); // get current font size (= height in pixels) AFTER external scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()/PushFontSize()! Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. + IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER external scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()/PushFontSize()! Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) // Parameters stacks (shared) @@ -3756,7 +3761,7 @@ struct ImFontBaked enum ImFontFlags_ { ImFontFlags_None = 0, - ImFontFlags_DefaultToLegacySize = 1 << 0, // Legacy compatibility: make PushFont() calls without explicit size use font->LegacySize instead of current font size. + ImFontFlags_DefaultToLegacySize = 1 << 0, // Legacy compatibility: make `PushFont(font)` == `PushFont(font, font->LegacySize)`. Otherwise by default/shared current font size is used. ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. ImFontFlags_NoLoadGlyphs = 1 << 2, // [Internal] Disable loading new glyphs. ImFontFlags_LockBakedSizes = 1 << 3, // [Internal] Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. Important: if you use this to preload given sizes, consider the possibility of multiple font density used on Retina display. @@ -3949,7 +3954,8 @@ struct ImGuiPlatformImeData namespace ImGui { // OBSOLETED in 1.92.0 (from June 2025) - IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFontSize(style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. + static inline void PushFont(ImFont* font) { IM_ASSERT(font != NULL); PushFont(font, font->LegacySize); } + IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFont(NULL, style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. // OBSOLETED in 1.91.9 (from February 2025) IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) From 97e0d59619f0796f64be2a4b35383e422c93b5d6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 19:01:59 +0200 Subject: [PATCH 1123/2359] (Breaking) Fonts: removed PushFontSize(), PopFontSize(). --- docs/CHANGELOG.txt | 3 +-- docs/FAQ.md | 2 +- docs/FONTS.md | 2 +- docs/TODO.txt | 1 - imgui.cpp | 21 ++++----------------- imgui.h | 6 ++---- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- 8 files changed, 11 insertions(+), 28 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d468b60ae..7c7daf79d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -150,7 +150,7 @@ Breaking changes: ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using - PushFontSize(style.FontSizeBase * factor) or to manipulate other scaling factors. + PushFont(NULL, style.FontSizeBase * factor) or to manipulate other scaling factors. - Fonts: obsoleted ImFont::Scale which is not useful anymore. - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition(): - old: const char* CalcWordWrapPositionA(float scale, const char* text, ....); @@ -270,7 +270,6 @@ Other changes: - Fonts: ImFontAtlas::AddFontXXX() functions may be called at any time during the frame. - Fonts: ImFontAtlas::AddFontXXX() can fail more gracefully if error handling is configured to not assert (this will be better exposed via future font flags). -- Fonts: added ImGui::PushFontSize()/PopFontSize() functions. - Fonts: added style.FontScaleBase scaling factor (previously called io.FontGlobalScale). - Fonts: added style.FontScaleDpi scaling factor. This is designed to be be changed on per-monitor/per-viewport basis, which `io.ConfigDpiScaleFonts` does automatically. diff --git a/docs/FAQ.md b/docs/FAQ.md index 0e8ba5c77..ad35d5451 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -572,7 +572,7 @@ Since 1.92 (June 2025) fonts may be dynamically used at any size. To change font size: ```cpp -ImGui::PushFontSize(42.0f); +ImGui::PushFont(NULL, 42.0f); ``` To change font and font size: ```cpp diff --git a/docs/FONTS.md b/docs/FONTS.md index 8edfbd33b..5a43b4403 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -77,7 +77,7 @@ Future versions of Dear ImGui should solve this problem. v1.92 introduces a newer, dynamic font system. It requires backend to support the `ImGuiBackendFlags_HasTextures` feature: - Users of icons, Asian and non-English languages do not need to pre-build all glyphs ahead of time. Saving on loading time, memory, and also reducing issues with missing glyphs. Specifying glyph ranges is not needed anymore. -- `PushFontSize()` may be used anytime to change font size. +- `PushFont(NULL, new_size)` may be used anytime to change font size. - Packing custom rectangles is more convenient as pixels may be written to immediately. - Any update to fonts previously required backend specific calls to re-upload the texture, and said calls were not portable across backends. It is now possible to scale fonts etc. in a way that doesn't require you to make backend-specific calls. - It is possible to plug a custom loader/backend to any font source. diff --git a/docs/TODO.txt b/docs/TODO.txt index 8866d04fb..03deffb2d 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -249,7 +249,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font: finish CustomRectRegister() to allow mapping Unicode codepoint to custom texture data - font: remove ID from CustomRect registration, it seems unnecessary! - font: make it easier to submit own bitmap font (same texture, another texture?). (#2127, #2575) - - font: PushFontSize API (#1018) - font: MemoryTTF taking ownership confusing/not obvious, maybe default should be opposite? - font: storing MinAdvanceX per font would allow us to skip calculating line width (under a threshold of character count) in loops looking for block width - font/demo: add tools to show glyphs used by a text blob, display U16 value, list missing glyphs. diff --git a/imgui.cpp b/imgui.cpp index 44a613ac9..eceda68f1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -470,7 +470,7 @@ CODE - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required. - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch. - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized. - - PushFont() API now has a REQUIRED size parameter. PushFontSize() was also added. + - PushFont() API now has a REQUIRED size parameter. - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize). - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value. - To use old behavior: (A) use 'ImGui::PushFont(font, font->LegacySize)' at call site (preferred). (B) Set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call (not desirable as it requires e.g. third-party code to be aware of it). @@ -498,7 +498,7 @@ CODE - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese(). - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327) - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. - - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFontSize(style.FontSizeBase * factor)' or to manipulate other scaling factors. + - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors. - Fonts: obsoleted ImFont::Scale which is not useful anymore. - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef. @@ -8551,7 +8551,7 @@ ImVec2 ImGui::GetFontTexUvWhitePixel() return GImGui->DrawListSharedData.TexUvWhitePixel; } -// Prefer using PushFontSize(style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows. +// Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS void ImGui::SetWindowFontScale(float scale) { @@ -8732,8 +8732,6 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) // - SetFontRasterizerDensity() [Internal] // - PushFont() // - PopFont() -// - PushFontSize() -// - PopFontSize() //----------------------------------------------------------------------------- void ImGui::UpdateFontsNewFrame() @@ -8854,7 +8852,7 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) if (g.CurrentTable == NULL || g.CurrentTable->CurrentColumn != -1) // See 8465#issuecomment-2951509561. Ideally the SkipItems=true in tables would be amended with extra data. return; - // Restoring is pretty much only used by PopFont()/PopFontSize() + // Restoring is pretty much only used by PopFont() float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; if (final_size == 0.0f) { @@ -8935,17 +8933,6 @@ void ImGui::PopFont() g.FontStack.pop_back(); } -void ImGui::PushFontSize(float font_size_base) -{ - ImGuiContext& g = *GImGui; - PushFont(g.Font, font_size_base); -} - -void ImGui::PopFontSize() -{ - PopFont(); -} - //----------------------------------------------------------------------------- // [SECTION] ID STACK //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 2c361c4cf..1022ea3fa 100644 --- a/imgui.h +++ b/imgui.h @@ -509,10 +509,8 @@ namespace ImGui // - INCORRECT: PushFont(NULL, GetFontSize() * 2.0f) // INCORRECT! use size after external factors applied == EXTERNAL SCALING FACTORS WILL APPLY TWICE! IMGUI_API void PushFont(ImFont* font, float font_size_base_unscaled); // Use NULL as a shortcut to keep current font. Use 0.0f to keep current size. IMGUI_API void PopFont(); - IMGUI_API void PushFontSize(float font_size_base); // keep current font, change its size. Final 'font size = font_size_base * external scale factors'. - IMGUI_API void PopFontSize(); IMGUI_API ImFont* GetFont(); // get current font - IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER external scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()/PushFontSize()! Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. + IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER external scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()! Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) // Parameters stacks (shared) @@ -2232,7 +2230,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE struct ImGuiStyle { // ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors) - float FontSizeBase; // Current base font size before external scaling factors are applied. Use PushFont()/PushFontSize() to modify. Use ImGui::GetFontSize() to obtain scaled value. + float FontSizeBase; // Current base font size before external scaling factors are applied. Use PushFont(NULL, size) to modify. Use ImGui::GetFontSize() to obtain scaled value. float FontScaleMain; // Main scale factor. May be set by application once, or exposed to end-user. float FontScaleDpi; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 50b486cad..e540f9e6a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5227,7 +5227,7 @@ ImFontBaked* ImFont::GetFontBaked(float size, float density) ImFontBaked* baked = LastBaked; // Round font size - // - ImGui::PushFontSize() will already round, but other paths calling GetFontBaked() directly also needs it (e.g. ImFontAtlasBuildPreloadAllGlyphRanges) + // - ImGui::PushFont() will already round, but other paths calling GetFontBaked() directly also needs it (e.g. ImFontAtlasBuildPreloadAllGlyphRanges) size = ImGui::GetRoundedFontSize(size); if (density < 0.0f) diff --git a/imgui_internal.h b/imgui_internal.h index b2656a734..a01a974f5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2143,7 +2143,7 @@ struct ImGuiContext ImFont* Font; // Currently bound font. (== FontStack.back().Font) ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) float FontSize; // Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function). - float FontSizeBase; // Font size before scaling == style.FontSizeBase == value passed to PushFont() / PushFontSize() when specified. + float FontSizeBase; // Font size before scaling == style.FontSizeBase == value passed to PushFont() when specified. float FontBakedScale; // == FontBaked->Size / FontSize. Scale factor over baked size. Rarely used nowadays, very often == 1.0f. float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale From 89b5a2c3d50e4ca6a0a88378f096d7d05ff1c962 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 24 Jun 2025 19:06:46 +0200 Subject: [PATCH 1124/2359] (Breaking) Fonts: removed ImFontFlags_DefaultToLegacySize. --- docs/CHANGELOG.txt | 7 +------ imgui.cpp | 9 ++------- imgui.h | 1 - 3 files changed, 3 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7c7daf79d..01694d50a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,10 +80,7 @@ Breaking changes: - PushFont(font, 20.0f) // Change font and set size to 20.0f - PushFont(font, style.FontSizeBase * 2.0f) // Change font and set size to be twice bigger than current size. - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavor, for fixed size fonts. - - To use old behavior: - - use 'ImGui::PushFont(font, font->LegacySize)' at call site (preferred). - - or set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call - (not desirable as it requires e.g. all third-party code to be aware of it). + - To use old behavior use 'ImGui::PushFont(font, font->LegacySize)' at call site. We intentionally didn't add a default parameter because it would make the long-term transition more difficult. - Kept inline redirection font. Will obsolete. @@ -290,8 +287,6 @@ Other changes: window and other locations). - Fonts: added ImFontFlags (currently needs to be passed through ImFontConfig until we revamp font loading API): - - ImFontFlags_DefaultToLegacySize: for legacy compatibility: make PushFont() calls - without explicit size use font->LegacySize instead of current font size. - ImFontFlags_NoLoadError: disable erroring/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. - ImFontFlags_NoLoadGlyphs: disable loading new glyphs. diff --git a/imgui.cpp b/imgui.cpp index eceda68f1..e36d0a9e2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -473,7 +473,7 @@ CODE - PushFont() API now has a REQUIRED size parameter. - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize). - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value. - - To use old behavior: (A) use 'ImGui::PushFont(font, font->LegacySize)' at call site (preferred). (B) Set 'ImFontConfig::Flags |= ImFontFlags_DefaultToLegacySize' in AddFont() call (not desirable as it requires e.g. third-party code to be aware of it). + - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site. - Kept inline single parameter function. Will obsolete. - Fonts: **IMPORTANT** on Font Merging: - When searching for a glyph in multiple merged fonts: font inputs are now scanned in orderfor the first font input which the desired glyph. This is technically a different behavior than before! @@ -8911,12 +8911,7 @@ void ImGui::PushFont(ImFont* font, float font_size_base) g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize }); if (font_size_base == 0.0f) - { - if (font->Flags & ImFontFlags_DefaultToLegacySize) - font_size_base = font->LegacySize; // Legacy: use AddFont() specified font size. Same as doing PushFont(font, font->LegacySize) - else - font_size_base = g.FontSizeBase; // Keep current font size - } + font_size_base = g.FontSizeBase; // Keep current font size SetCurrentFont(font, font_size_base, 0.0f); } diff --git a/imgui.h b/imgui.h index 1022ea3fa..44ab90869 100644 --- a/imgui.h +++ b/imgui.h @@ -3759,7 +3759,6 @@ struct ImFontBaked enum ImFontFlags_ { ImFontFlags_None = 0, - ImFontFlags_DefaultToLegacySize = 1 << 0, // Legacy compatibility: make `PushFont(font)` == `PushFont(font, font->LegacySize)`. Otherwise by default/shared current font size is used. ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. ImFontFlags_NoLoadGlyphs = 1 << 2, // [Internal] Disable loading new glyphs. ImFontFlags_LockBakedSizes = 1 << 3, // [Internal] Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. Important: if you use this to preload given sizes, consider the possibility of multiple font density used on Retina display. From d8c69537103fef8c14304d003e6db9859e31b5a3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 12:08:00 +0200 Subject: [PATCH 1125/2359] Fonts: comments. --- docs/BACKENDS.md | 2 +- docs/CHANGELOG.txt | 5 +++-- docs/FONTS.md | 32 +++++++++++++++----------------- docs/TODO.txt | 10 +--------- imgui.cpp | 6 ++++-- imgui.h | 20 +++++++++++--------- 6 files changed, 35 insertions(+), 40 deletions(-) diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index de5cd6697..fcdd703f4 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -12,7 +12,7 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKE Dear ImGui is highly portable and only requires a few things to run and render, typically: - Required: providing mouse/keyboard inputs (fed into the `ImGuiIO` structure). - - Required: uploading the font atlas texture into graphics memory. + - Required: creating, updating and destroying textures. - Required: rendering indexed textured triangles with a clipping rectangle. Extra features are opt-in, our backends try to support as many as possible: diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 01694d50a..4a753127a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -79,13 +79,14 @@ Breaking changes: - PushFont(NULL, 20.0f) // Keep font and change current size - PushFont(font, 20.0f) // Change font and set size to 20.0f - PushFont(font, style.FontSizeBase * 2.0f) // Change font and set size to be twice bigger than current size. - - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavor, for fixed size fonts. + - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavior, for fixed size fonts. - To use old behavior use 'ImGui::PushFont(font, font->LegacySize)' at call site. We intentionally didn't add a default parameter because it would make the long-term transition more difficult. - Kept inline redirection font. Will obsolete. - - External scale factors may be applied over the provided size. + - Global scale factors may be applied over the provided size. This is why it is called 'FontSizeBase' in the style structure. + - Global scale factors are: 'style.FontScaleMain', 'style.FontScaleDpi' and maybe more. - ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). - Removed support for old PushFont(NULL) which was a shortcut for "revert to default font". diff --git a/docs/FONTS.md b/docs/FONTS.md index 5a43b4403..f8431507c 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -2,7 +2,7 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS ## Dear ImGui: Using Fonts -The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), +The code in imgui.cpp embeds a copy of [ProggyClean.ttf](http://proggyfonts.net) (by Tristan Grimmer), a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions. You may also load external .TTF/.OTF files. @@ -37,7 +37,7 @@ In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) fo ### (1) Invalid filename due to use of `\` or unexpected working directory. -See [About Filenames](#about-filenames). AddFontXXX functions should assert if the filename is incorrect. +See [About Filenames](#about-filenames). AddFontXXX() functions should assert if the filename is incorrect. ### (2) Invalid UTF-8 encoding of your non-ASCII strings. @@ -45,18 +45,18 @@ See [About UTF-8 Encoding](#about-utf-8-encoding). Use the encoding viewer to co ### (3) Missing glyph ranges. -🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary.** +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary.** -You need to load a font with explicit glyph ranges if you want to use non-ASCII characters. See [Fonts Loading Instructions](#fonts-loading-instructions). Use [Debug Tools](#debug-tools) confirm loaded fonts and loaded glyph ranges. +⏪ Before 1.92: you need to load a font with explicit glyph ranges if you want to use non-ASCII characters. See [Fonts Loading Instructions](#fonts-loading-instructions). Use [Debug Tools](#debug-tools) confirm loaded fonts and loaded glyph ranges. -This is a current constraint of Dear ImGui (which we will lift in the future): when loading a font you need to specify which characters glyphs to load. +This was a previous constraint of Dear ImGui (lifted in 1.92): when loading a font you need to specify which characters glyphs to load. All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of `io.Fonts->GetTexDataAsAlpha8()`, `io.Fonts->GetTexDataAsRGBA32()` or `io.Fonts->Build()` will build the atlas. This is generally called by the Renderer backend, e.g. `ImGui_ImplDX11_NewFrame()` calls it. **If you use custom glyphs ranges, make sure the array is persistent** and available during the calls to `GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build()`. ### (4) Font atlas texture fails to upload to GPU. 🆕 **Since 1.92, with an up to date backend: atlas is built incrementally and dynamically resized, this is less likely to happen** -This is often of byproduct of point 3. If you have large number of glyphs or multiple fonts, the texture may become too big for your graphics API. **The typical result of failing to upload a texture is if every glyph or everything appears as empty white rectangles.** Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. +:rewind: This is often of byproduct of point 3. If you have large number of glyphs or multiple fonts, the texture may become too big for your graphics API. **The typical result of failing to upload a texture is if every glyph or everything appears as empty white rectangles.** Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. ![empty squares](https://github.com/user-attachments/assets/68b50fb5-8b9d-4c38-baec-6ac384f06d26) @@ -67,8 +67,6 @@ Some solutions: You can use the `ImFontGlyphRangesBuilder` for this purpose and rebuilding your atlas between frames when new characters are needed. This will be the biggest win! - Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. -Future versions of Dear ImGui should solve this problem. - ##### [Return to Index](#index) --------------------------------------- @@ -112,7 +110,7 @@ io.Fonts->AddFontDefault(); ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("font.ttf"); ``` -**Before 1.92, or without an up to date backend:** +:rewind: **Before 1.92, or without an up to date backend:** ```cpp ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); @@ -130,7 +128,7 @@ ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf"); In your application loop, select which font to use: ```cpp ImGui::Text("Hello"); // use the default font (which is the first loaded font) -ImGui::PushFont(font2); +ImGui::PushFont(font2, 0.0f); // change font, keep current size ImGui::Text("Hello with another font"); ImGui::PopFont(); ``` @@ -154,7 +152,7 @@ io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 0.0f, &config); // Merge io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 0.0f, &config); // Merge into first font to add Icons io.Fonts->Build(); ``` -**Before 1.92, or without an up to date backend:** +:rewind: **Before 1.92, or without an up to date backend:** ```cpp // Load a first font ImFont* font = io.Fonts->AddFontDefault(); @@ -193,7 +191,7 @@ ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf"); ``` -**Before 1.92, or without an up to date backend:** +:rewind: **Before 1.92, or without an up to date backend:** ```cpp ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); @@ -277,7 +275,7 @@ config.MergeMode = true; config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config); ``` -**Before 1.92:** +:rewind: **Before 1.92:** ```cpp // Merge icons into default tool font #include "IconsFontAwesome.h" @@ -355,8 +353,8 @@ You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` ## Using FreeType Rasterizer (imgui_freetype) - Dear ImGui uses [stb_truetype.h](https://github.com/nothings/stb/) to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. -- You can however use `imgui_freetype.cpp` from the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. -- FreeType supports auto-hinting which tends to improve the readability of small fonts. +- You can however use `imgui_freetype.cpp` from the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. Compile with this file and add `#define IMGUI_ENABLE_FREETYPE` to your imconfig.h file or build system to automatically activate it. +- FreeType supports auto-hinting which tends to improve the readability of small fonts. It makes a big difference especially at smaller resolutions. - Read documentation in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. - Correct sRGB space blending will have an important effect on your font rendering quality. @@ -391,7 +389,7 @@ io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg); 🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary, so this is not needed.** -You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. +:rewind: You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. ```cpp ImVector ranges; ImFontGlyphRangesBuilder builder; @@ -417,7 +415,7 @@ TL;DR; With the new system, it is recommended that you create a custom `ImFontLo You can ask questions in [#8466](https://github.com/ocornut/imgui/issues/8466). -**Before 1.92:** +:rewind: **Before 1.92:** As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiFreeTypeBuilderFlags_LoadColor`, you may allocate your own space in the texture atlas and write yourself into it. **(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)** diff --git a/docs/TODO.txt b/docs/TODO.txt index 03deffb2d..90d2b35db 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -241,21 +241,14 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font: arbitrary line spacing. (#2945) - font: MergeMode: flags to select overwriting or not (this is now very easy with refactored ImFontAtlasBuildWithStbTruetype) - - font: free the Alpha buffer if user only requested RGBA. -!- font: better CalcTextSizeA() API, at least for simple use cases. current one is horrible (perhaps have simple vs extended versions). + - font: better CalcTextSizeA() API, at least for simple use cases. current one is horrible (perhaps have simple vs extended versions). - font: for the purpose of RenderTextEllipsis(), it might be useful that CalcTextSizeA() can ignore the trailing padding? - font: a CalcTextHeight() helper could run faster than CalcTextSize().y - font: enforce monospace through ImFontConfig (for icons?) + create dual ImFont output from same input, reusing rasterized data but with different glyphs/AdvanceX - - font: finish CustomRectRegister() to allow mapping Unicode codepoint to custom texture data - - font: remove ID from CustomRect registration, it seems unnecessary! - font: make it easier to submit own bitmap font (same texture, another texture?). (#2127, #2575) - font: MemoryTTF taking ownership confusing/not obvious, maybe default should be opposite? - font: storing MinAdvanceX per font would allow us to skip calculating line width (under a threshold of character count) in loops looking for block width - - font/demo: add tools to show glyphs used by a text blob, display U16 value, list missing glyphs. - font/demo: demonstrate use of ImFontGlyphRangesBuilder. - - font/atlas: add a missing Glyphs.reserve() - - font/atlas: incremental updates - - font/atlas: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. - font/draw: vertical and/or rotated text renderer (#705) - vertical is easier clipping wise - font/draw: need to be able to specify wrap start position. - font/draw: better reserve policy for large horizontal block of text (shouldn't reserve for all clipped lines). also see #3349. @@ -264,7 +257,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font: optimization: for monospace font (like the default one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance (need to make sure TAB is still correct), would save on cache line. - font: add support for kerning, probably optional. A) perhaps default to (32..128)^2 matrix ~ 9K entries = 36KB, then hash for non-ascii?. B) or sparse lookup into per-char list? - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) - - font: fix AddRemapChar() to work before atlas has been built. - font: (api breaking) remove "TTF" from symbol names. also because it now supports OTF. - font/opt: Considering storing standalone AdvanceX table as 16-bit fixed point integer? - font/opt: Glyph currently 40 bytes (2+9*4). Consider storing UV as 16-bits integer? (->32 bytes). X0/Y0/X1/Y1 as 16 fixed-point integers? Or X0/Y0 as float and X1/Y1 as fixed8_8? diff --git a/imgui.cpp b/imgui.cpp index e36d0a9e2..bed833764 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8540,7 +8540,9 @@ ImFontBaked* ImGui::GetFontBaked() return GImGui->FontBaked; } -// Get current font size (= height in pixels) of current font, with external scale factors applied. Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. +// Get current font size (= height in pixels) of current font, with global scale factors applied. +// - Use style.FontSizeBase to get value before global scale factors. +// - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors) float ImGui::GetFontSize() { return GImGui->FontSize; @@ -8858,7 +8860,7 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) { final_size = g.FontSizeBase; - // External scale factors + // Global scale factors final_size *= g.Style.FontScaleMain; // Main global scale factor final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled. diff --git a/imgui.h b/imgui.h index 44ab90869..e7f74e7da 100644 --- a/imgui.h +++ b/imgui.h @@ -501,16 +501,17 @@ namespace ImGui // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. // - In 1.92 we have REMOVED the single parameter version of PushFont() because it seems like the easiest way to provide an error-proof transition. // - PushFont(font) before 1.92 = PushFont(font, font->LegacySize) after 1.92 // Use default font size as passed to AddFontXXX() function. - // *IMPORTANT* external scale factors are applied over the provided size. If you want to scale an *existing* font size: - // - External scale factors are: 'style.FontScaleMain * style.FontScaleDpi' and maybe more. + // *IMPORTANT* global scale factors are applied over the provided size. + // - Global scale factors are: 'style.FontScaleMain', 'style.FontScaleDpi' and maybe more. + // - If you want to apply a factor to the _current_ font size: // - CORRECT: PushFont(NULL, style.FontSizeBase) // use current unscaled size == does nothing // - CORRECT: PushFont(NULL, style.FontSizeBase * 2.0f) // use current unscaled size x2 == make text twice bigger - // - INCORRECT: PushFont(NULL, GetFontSize()) // INCORRECT! use size after external factors applied == EXTERNAL SCALING FACTORS WILL APPLY TWICE! - // - INCORRECT: PushFont(NULL, GetFontSize() * 2.0f) // INCORRECT! use size after external factors applied == EXTERNAL SCALING FACTORS WILL APPLY TWICE! + // - INCORRECT: PushFont(NULL, GetFontSize()) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE! + // - INCORRECT: PushFont(NULL, GetFontSize() * 2.0f) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE! IMGUI_API void PushFont(ImFont* font, float font_size_base_unscaled); // Use NULL as a shortcut to keep current font. Use 0.0f to keep current size. IMGUI_API void PopFont(); IMGUI_API ImFont* GetFont(); // get current font - IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER external scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()! Use ImGui::GetStyle().FontSizeBase to get value before external scale factors. + IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER global scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()! Use ImGui::GetStyle().FontSizeBase to get value before global scale factors. IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) // Parameters stacks (shared) @@ -2229,10 +2230,11 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE struct ImGuiStyle { - // ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors) - float FontSizeBase; // Current base font size before external scaling factors are applied. Use PushFont(NULL, size) to modify. Use ImGui::GetFontSize() to obtain scaled value. - float FontScaleMain; // Main scale factor. May be set by application once, or exposed to end-user. - float FontScaleDpi; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. + // Font scaling + // - recap: ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors) + float FontSizeBase; // Current base font size before external global factors are applied. Use PushFont(NULL, size) to modify. Use ImGui::GetFontSize() to obtain scaled value. + float FontScaleMain; // Main global scale factor. May be set by application once, or exposed to end-user. + float FontScaleDpi; // Additional global scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. From dcf14505e27f16f6cf1933d4834705ed76302637 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 15:46:25 +0200 Subject: [PATCH 1126/2359] Backends: SDLGPU: fixes call to SDL_MapGPUTransferBuffer(). Fixes artifacts on OSX/Metal. (#8465, #8703) --- backends/imgui_impl_sdlgpu3.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 0ad9e2c30..927e511cb 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -22,6 +22,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-06-25: Mapping transfer buffer for texture update use cycle=true. Fixes artifacts e.g. on Metal backend. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture(). // 2025-04-28: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2025-03-30: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now. @@ -373,7 +374,7 @@ void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) // Copy to transfer buffer { - void* texture_ptr = SDL_MapGPUTransferBuffer(v->Device, bd->TexTransferBuffer, false); + void* texture_ptr = SDL_MapGPUTransferBuffer(v->Device, bd->TexTransferBuffer, true); for (int y = 0; y < upload_h; y++) memcpy((void*)((uintptr_t)texture_ptr + y * upload_pitch), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch); SDL_UnmapGPUTransferBuffer(v->Device, bd->TexTransferBuffer); From 5bc70c68e2dff11ad55036ddf9e5f86f7a0a1a9f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 15:55:25 +0200 Subject: [PATCH 1127/2359] Fonts: fix PushFont(NULL) to work as advertised. Didn't properly finish ca72eb0. --- imgui.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bed833764..343862b30 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8906,8 +8906,8 @@ void ImGui::SetFontRasterizerDensity(float rasterizer_density) void ImGui::PushFont(ImFont* font, float font_size_base) { ImGuiContext& g = *GImGui; - //if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont()) - // font = g.Font; + if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont()) + font = g.Font; IM_ASSERT(font != NULL); IM_ASSERT(font_size_base >= 0.0f); From 719a3fe98eb692cd35aba1d792fd6702669275f5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 16:04:51 +0200 Subject: [PATCH 1128/2359] Additional comments on ErrorCheckUsingSetCursorPosToExtendParentBoundaries(). (#5548) --- imgui.cpp | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 343862b30..aa73294fe 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10581,21 +10581,30 @@ bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, si return !error; } -// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell) -// This is causing issues and ambiguity and we need to retire that. -// See https://github.com/ocornut/imgui/issues/5548 for more details. -// [Scenario 1] +// Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos() +// to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing +// windows, table column contents size used for auto-resizing columns, group size). +// This was causing issues and ambiguities and we needed to retire that. +// From 1.89, extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED. +// // Previously this would make the window content size ~200x200: -// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK +// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE // Instead, please submit an item: // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK // Alternative: // Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK -// [Scenario 2] -// For reference this is one of the issue what we aim to fix with this change: -// BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() -// The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller! -// While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue. +// +// The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item, +// and with a position that would grow the parent contents size. +// +// Advanced: +// - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos()) +// had a side-effect on layout! In particular this caused problem to compute group boundaries. +// e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the +// group to be taller because auto-sizing generally adds padding on bottom and right side. +// - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. +// Using vertical alignment patterns would frequently trigger this sorts of issue. +// - See https://github.com/ocornut/imgui/issues/5548 for more details. void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries() { ImGuiContext& g = *GImGui; From 6f21bed66d678dc4207113ba874e1b5b96e34f92 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 16:23:06 +0200 Subject: [PATCH 1129/2359] Fonts: removing assert from legacy PushFont() to mirror new PushFont(). for consistency. --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index e7f74e7da..15acc8c0e 100644 --- a/imgui.h +++ b/imgui.h @@ -3953,7 +3953,7 @@ struct ImGuiPlatformImeData namespace ImGui { // OBSOLETED in 1.92.0 (from June 2025) - static inline void PushFont(ImFont* font) { IM_ASSERT(font != NULL); PushFont(font, font->LegacySize); } + static inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); } IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFont(NULL, style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. // OBSOLETED in 1.91.9 (from February 2025) IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. From 2819ab32f85b97d8c99a6cb0ec0f39b42bec4c92 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 16:39:23 +0200 Subject: [PATCH 1130/2359] Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback. (#5548, #4510, #3355, #1760, #1490, #4152, #150) --- docs/CHANGELOG.txt | 10 ++++++++++ imgui.cpp | 17 ++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4a753127a..8ef51cc23 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -225,6 +225,16 @@ Breaking changes: - removed ImGui_ImplSDLRenderer2_CreateFontsTexture(), ImGui_ImplSDLRenderer2_DestroyFontsTexture(). - removed ImGui_ImplSDLRenderer3_CreateFontsTexture(), ImGui_ImplSDLRenderer3_DestroyFontsTexture(). - removed ImGui_ImplVulkan_CreateFontsTexture(), ImGui_ImplVulkan_DestroyFontsTexture(). +- Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback + obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM + to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if + previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150) + - Incorrect way to make a window content size 200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); + - Correct ways to make a window content size 200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); + Begin(...) + Dummy(ImVec2(200,200)) + End(); + - TL;DR; if the assert triggers, you can add a Dummy({0,0}) call to validate extending parent boundaries. - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). (#1079, #8639) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted diff --git a/imgui.cpp b/imgui.cpp index aa73294fe..660e9da9b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -460,6 +460,14 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/06/25 (1.92.0) - layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM + to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150) + - Incorrect way to make a window content size 200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); + - Correct ways to make a window content size 200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); + Begin(...) + Dummy(ImVec2(200,200)) + End(); + - TL;DR; if the assert triggers, you can add a Dummy({0,0}) call to validate extending parent boundaries. - 2025/06/11 (1.92.0) - THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, BUT INEVITABLY SOME USERS WILL BE AFFECTED. IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/ As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be part of subsequent releases (1.92.1+). @@ -10611,15 +10619,14 @@ void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries() ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(window->DC.IsSetPos); window->DC.IsSetPos = false; -#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y) return; if (window->SkipItems) return; - IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent."); -#else - window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); -#endif + IM_ASSERT_USER_ERROR(0, "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries.\nPlease submit an item e.g. Dummy() afterwards in order to grow window/parent boundaries."); + + // For reference, the old behavior was essentially: + //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } static void ImGui::ErrorCheckNewFrameSanityChecks() From da3c86925ab90c3a998bf8d7a6084decdbe23d6a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 18:19:48 +0200 Subject: [PATCH 1131/2359] Demo: added TextLinkOpenURL() call in Widgets section. --- imgui_demo.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8a4c4584e..ccd6a11f5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -842,6 +842,9 @@ static void DemoWindowWidgetsBasic() ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); ImGui::RadioButton("radio c", &e, 2); + ImGui::AlignTextToFramePadding(); + ImGui::TextLinkOpenURL("Hyperlink", "https://github.com/ocornut/imgui/wiki/Error-Handling"); + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Colored)"); for (int i = 0; i < 7; i++) @@ -8024,6 +8027,8 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::SameLine(); ImGui::TextLinkOpenURL("Wiki", "https://github.com/ocornut/imgui/wiki"); ImGui::SameLine(); + ImGui::TextLinkOpenURL("Extensions", "https://github.com/ocornut/imgui/wiki/Useful-Extensions"); + ImGui::SameLine(); ImGui::TextLinkOpenURL("Releases", "https://github.com/ocornut/imgui/releases"); ImGui::SameLine(); ImGui::TextLinkOpenURL("Funding", "https://github.com/ocornut/imgui/wiki/Funding"); From 673eb7de9678459ccd2c340a75786d8b1434848f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 18:13:10 +0200 Subject: [PATCH 1132/2359] Version 1.92.0 --- docs/CHANGELOG.txt | 60 +++++++++++++++++++++++++--------------------- imgui.cpp | 2 +- imgui.h | 6 ++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 42 insertions(+), 36 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8ef51cc23..473c389f9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,11 +36,13 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.0 WIP (In Progress) + VERSION 1.92.0 (Released 2025-06-25) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92 + THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! -I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, +I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCE, BUT INEVITABLY SOME USERS OR THIRD-PARTY EXTENSIONS WILL BE AFFECTED. IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, @@ -88,8 +90,9 @@ Breaking changes: This is why it is called 'FontSizeBase' in the style structure. - Global scale factors are: 'style.FontScaleMain', 'style.FontScaleDpi' and maybe more. - ImFont::FontSize was removed and does not make sense anymore. - ImFont::LegacySize is the size passed to AddFont(). + - ImFont::LegacySize is the size passed to AddFont(). - Removed support for old PushFont(NULL) which was a shortcut for "revert to default font". + `PushFont(NULL, some_size)` now keeps current change and changes size. - Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. - Fonts: **IMPORTANT** on Font Merging: - When searching for a glyph in multiple merged fonts: font inputs are now scanned in order @@ -114,7 +117,7 @@ Breaking changes: - Textures: - All API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef': - - ImTextureRef a small composite structure which may be constructed from a ImTextureID. + - ImTextureRef ais small composite structure which may be constructed from a ImTextureID. (or constructed from a ImTextureData* which represent a texture which will generally be ready by the time of rendering). - Affected functions are: @@ -147,7 +150,7 @@ Breaking changes: - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. -- Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using +- Fonts: obsoleted ImGui::SetWindowFontScale() which is not useful anymore. Prefer using PushFont(NULL, style.FontSizeBase * factor) or to manipulate other scaling factors. - Fonts: obsoleted ImFont::Scale which is not useful anymore. - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition(): @@ -160,7 +163,7 @@ Breaking changes: While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef. - - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[] + - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size. @@ -188,9 +191,6 @@ Breaking changes: - renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader() - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader(); -- DrawList: Fixed a regression from 1.91.1 where a Begin()/PushFont()/AddImage() sequence - would not restore the correct atlas Texture Identifier when the PushFont() call used - a font from a different atlas. (#8694, caused by #3224, #3875, #6398, #7903) - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). - Fonts: (users of custom rectangles) - Renamed AddCustomRectRegular() to AddCustomRect(). (#8466) @@ -249,7 +249,7 @@ Breaking changes: - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387) -Other changes: +Non-breaking Fonts/Textures related changes: - Textures: added partial texture update protocol. (#8465, #3761) - The Renderer Backend needs to set io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures @@ -310,7 +310,7 @@ Other changes: - ImFontBaked structures may be cleaned up between frames when unused, pointers to them are only valid for the current frame. - Added ImFontBaked::IsGlyphLoaded() function. -- Fonts: custom rect packing has generally been reworked. (#8107, #7962, #1282) +- Fonts: Custom Rect packing has generally been reworked. (#8107, #7962, #1282) - ImFontAtlas::AddCustomRect() (previously AddCustomRectRegular()/AddCustomRectFontGlyph()) functions will immediately return a packed rectangle identifier, and you can write your pixels immediately - previously had to wait for Build() to be called. @@ -328,14 +328,29 @@ Other changes: for Renderer Backend to specify if there is a maximum accepted texture size (not yet used). - Fonts: added compile-time overridable '#define ImTextureID_Invalid 0' if you need 0 to be a valid low-level texture identifier. +- Fonts: reworked text ellipsis logic to ensure a "..." is always displayed instead + of a single character. (#7024) +- Fonts: word-wrapping code handle ideographic comma & full stop (U+3001, U+3002). (#8540) +- Fonts: fixed CalcWordWrapPosition() fallback when width is too small to wrap: + would use a +1 offset instead of advancing to the next UTF-8 codepoint. (#8540) - Debug Tools: Fonts section: add font preview, add "Remove" button, add "Load all glyphs" button, add selection to change font backend when both are compiled in. +- Renderer Backends: + - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, WebGPU, Allegro5: + - Added ImGuiBackendFlags_RendererHasTextures support for all backends. (#8465, #3761, #3471) + [@ocornut, @ShironekoBen, @thedmd] + - Added ImGui_ImplXXXX_UpdateTexture(ImTextureData* tex) functions for all backends. + Available if you want to start uploading textures right after ImGui::Render() and without + waiting for the call to ImGui_ImplXXXX_RenderDrawData(). Also useful if you use a staged or + multi-threaded rendering schemes, where you might want to set ImDrawData::Textures = NULL. (#8597, #1860) - Special thanks for fonts/texture related feedback to: @thedmd, @ShironekoBen, @rodrigorc, @pathogendavid, @itamago, @rokups, @DucaRii, @Aarkham, @cyfewlp. +Other Changes: + - IO: variations in analog-only components of gamepad events do not interfere with trickling of mouse position events (#4921, #8508) -- Windows: fixed SetNextWindowCollapsed()/SetWindowCollapsed() breaking +- Windows: fixed SetNextWindowCollapsed()/SetWindowCollapsed() bypassing the codepath that preserve last contents size when collapsed, resulting in programmatically uncollapsing auto-sizing windows having them flicker size for a frame. (#7691) [@achabense] @@ -353,10 +368,10 @@ Other changes: - ImGuiTreeNodeFlags_DrawLinesFull: Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. - ImGuiTreeNodeFlags_DrawLinesToNodes: Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. - Added style.TreeLinesFlags which stores the default setting, - which may be overriden in individual TreeNode() calls. + which may be overridden in individual TreeNode() calls. - Added style.TreeLinesSize (default to 1.0f). - Added style.TreeLinesRadius (default to 0.0f). - - Added ImGuiCol_TreeLines (in default style this is the same as ImGuiCol_Border). + - Added ImGuiCol_TreeLines (in default styles this is the same as ImGuiCol_Border). - Caveats: - Tree nodes may be used in many creative ways (manually positioning openable nodes in unusual ways, using indent to create tree-looking structures, etc.) @@ -397,28 +412,19 @@ Other changes: EndPopup() call. (#1651, #8499) - Error Handling: added better error report and recovery when calling EndFrame() or Render() without NewFrame(). Was previously only an assert. -- Fonts: reworked text ellipsis logic to ensure a "..." is always displayed instead - of a single character. (#7024) -- Fonts: word-wrapping code handle ideographic comma & full stop (U+3001, U+3002). (#8540) -- Fonts: fixed CalcWordWrapPosition() fallback when width is too small to wrap: - would use a +1 offset instead of advancing to the next UTF-8 codepoint. (#8540) - Style, InputText: added ImGuiCol_InputTextCursor to configure color of the InputText cursor/caret. (#7031) - Platform IME: added ImGuiPlatformImeData::ViewportId info (backported from Docking branch). - Platform IME: added ImGuiPlatformImeData::WantTextInput which might set independently of WantVisible. This is set in the same structure because activating text input generally requires providing a window to the backend. (#8584, #6341) +- DrawList: Fixed a regression from 1.91.1 where a Begin()/PushFont()/AddImage() sequence + would not restore the correct atlas Texture Identifier when the PushFont() call used + a font from a different atlas. (#8694, caused by #3224, #3875, #6398, #7903) - Misc: added extra operators to ImVec4 in IMGUI_DEFINE_MATH_OPERATORS block. (#8510) [@gan74] - Misc: removed static linkage from operators to facilitate using in C++ modules. (#8682, #8358) [@johmani] - Demo: changed default framed item width to use Min(GetFontSize() * 12, GetContentRegionAvail().x * 0.40f). - Renderer Backends: - - Backends: DX9/DX10/DX11/DX12, Vulkan, OpenGL2/3, Metal, SDLGPU3, SDLRenderer2/3, WebGPU, Allegro5: - - Added ImGuiBackendFlags_RendererHasTextures support. (#8465, #3761, #3471) - [@ocornut, @ShironekoBen, @thedmd] - - Added ImGui_ImplXXXX_UpdateTexture(ImTextureData* tex) functions for all backend. - Available if you want to start uploading textures right after ImGui::Render() and without - waiting for the call to ImGui_ImplXXXX_RenderDrawData(). Also useful if you use a staged or - multi-threaded rendering schemes, where you might want to set ImDrawData::Textures = NULL. (#8597, #1860) - Backends: SDLGPU3: Fixed creating atlas texture earlier than other backends, preventing to load fonts between the Init and NewFrames calls. - Backends: SDLGPU3: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which @@ -456,7 +462,7 @@ Other changes: - Backends: GLFW, SDL2, SDL3: include GLFW/SDL version number in io.BackendPlatformName. - Backends: SDL3: Update for SDL3 api changes: revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) [@Green-Sky] - - Backends: SDL3: honor ImGuiPlatformImeData->WantTextInput as an alternative + - Backends: SDL3: honor ImGuiPlatformImeData::WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. (#8584) - Backends: SDL3: fixed pulling SDL_PROP_WINDOW_COCOA_WINDOW_POINTER into viewport->PlatformHandleRaw. (#8725, #8726) [@eertbleyen] diff --git a/imgui.cpp b/imgui.cpp index 660e9da9b..21df13327 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.92.0 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 15acc8c0e..78baa1b7b 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.92.0 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.0 WIP" -#define IMGUI_VERSION_NUM 19199 +#define IMGUI_VERSION "1.92.0" +#define IMGUI_VERSION_NUM 19200 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ccd6a11f5..9b71ceae4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.92.0 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e540f9e6a..dc0944506 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.92.0 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index a01a974f5..40fe681f8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.92.0 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 61bc576ca..88b99d0a7 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.92.0 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d7214b6c2..49bee8436 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 WIP +// dear imgui, v1.92.0 // (widgets code) /* From 85b2fe8486190fa9326565a2fb5fccb6caea4396 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 25 Jun 2025 18:46:41 +0200 Subject: [PATCH 1133/2359] Docs: update binaries. --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index 701016a6a..7c62950d8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -110,7 +110,7 @@ Reading the changelogs is a good way to keep up to date with the things Dear ImG Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing a variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. [Here's how the demo looks](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png). You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: -- [imgui-demo-binaries-20241211.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20241211.zip) (Windows, 1.91.6, built 2024/11/11, master) or [older binaries](https://www.dearimgui.com/binaries). +- [imgui-demo-binaries-20250625.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20250625.zip) (Windows, 1.92.0, built 2025/06/25, master) or [older binaries](https://www.dearimgui.com/binaries). The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at a different scale and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.com/faq)). From 4f4bc7cc8fa6ba821298221a80fc6a8092a08f13 Mon Sep 17 00:00:00 2001 From: Aidan Sun Date: Thu, 26 Jun 2025 03:46:54 -0400 Subject: [PATCH 1134/2359] Replace IMGUI_API with inline for PushTextureID() and PopTextureID() (#8729) --- imgui.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 78baa1b7b..6b7dd2b64 100644 --- a/imgui.h +++ b/imgui.h @@ -3329,8 +3329,8 @@ struct ImDrawList // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - IMGUI_API void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x - IMGUI_API void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x + inline void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x + inline void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x #endif //inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) From 5ee9c2ad1ffcc105910b8f059f7d6c86b0ef30b7 Mon Sep 17 00:00:00 2001 From: Ves Georgiev <1884844+VesCodes@users.noreply.github.com> Date: Fri, 27 Jun 2025 00:06:42 +0100 Subject: [PATCH 1135/2359] Demo: Fixed font scaling warning if ImGuiBackendFlags_RendererHasTextures is set (#8736) --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 21df13327..fe9e8686a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15940,7 +15940,8 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 5.0f); //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); //EndDisabled(); - BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); + if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); BulletText("Load a nice font for better results!"); BulletText("Please submit feedback:"); SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); From f18aea52460a3cd5ad25ef07c60100b71d603c61 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 26 Jun 2025 20:35:35 +0200 Subject: [PATCH 1136/2359] Version 1.92.1 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 8 ++++---- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 19 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 473c389f9..ea760cd10 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.1 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking changes: + +Other changes: + + ----------------------------------------------------------------------- VERSION 1.92.0 (Released 2025-06-25) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index fe9e8686a..b5c534c57 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 +// dear imgui, v1.92.1 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 6b7dd2b64..ab23774d1 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 +// dear imgui, v1.92.1 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.0" -#define IMGUI_VERSION_NUM 19200 +#define IMGUI_VERSION "1.92.1 WIP" +#define IMGUI_VERSION_NUM 19201 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -327,7 +327,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // constructors if you like. You will need to implement ==/!= operators. // History: // - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requirig 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. -// - In v1.92.0 (2025/XX/XX): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef +// - In v1.92.0 (2025/06/11): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef #ifndef ImTextureID typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that. #endif diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9b71ceae4..94d39587f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 +// dear imgui, v1.92.1 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dc0944506..e835dcd75 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 +// dear imgui, v1.92.1 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 40fe681f8..eeee93778 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 +// dear imgui, v1.92.1 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 88b99d0a7..f6d516521 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 +// dear imgui, v1.92.1 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 49bee8436..afad7b6ec 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.0 +// dear imgui, v1.92.1 WIP // (widgets code) /* From 22ad62c90ca47474f7328548a7818e9955a73958 Mon Sep 17 00:00:00 2001 From: Christian Fillion Date: Thu, 26 Jun 2025 22:43:41 -0400 Subject: [PATCH 1137/2359] Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. (#8739) Yet another undocumented standard cursor. Amend 8a35386. --- backends/imgui_impl_osx.h | 2 -- backends/imgui_impl_osx.mm | 5 +++-- docs/CHANGELOG.txt | 3 +++ 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h index b4d7bf8d7..ea2b4f492 100644 --- a/backends/imgui_impl_osx.h +++ b/backends/imgui_impl_osx.h @@ -10,8 +10,6 @@ // [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. -// Missing features or Issues: -// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 27567fb19..06a6aff8b 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -10,8 +10,6 @@ // [X] Platform: Gamepad support. // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: IME support. -// Missing features or Issues: -// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -31,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-27: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-06-12: ImGui_ImplOSX_HandleEvent() only process event for window containing our view. (#8644) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-01-20: Removed notification observer when shutting down. (#8331) @@ -110,6 +109,7 @@ static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view); + (id)_windowResizeNorthEastSouthWestCursor; + (id)_windowResizeNorthSouthCursor; + (id)_windowResizeEastWestCursor; ++ (id)busyButClickableCursor; @end /** @@ -431,6 +431,7 @@ bool ImGui_ImplOSX_Init(NSView* view) bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor]; bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor]; bd->MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor]; + bd->MouseCursors[ImGuiMouseCursor_Wait] = bd->MouseCursors[ImGuiMouseCursor_Progress] = [NSCursor respondsToSelector:@selector(busyButClickableCursor)] ? [NSCursor busyButClickableCursor] : [NSCursor arrowCursor]; bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor]; // Note that imgui.cpp also include default OSX clipboard handlers which can be enabled diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ea760cd10..1b93505d1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress + mouse cursor support. (#8739) [@cfillion] + ----------------------------------------------------------------------- VERSION 1.92.0 (Released 2025-06-25) From ec13fa436b2219bbffcf7f30c5a51fc4e227bb5b Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 27 Jun 2025 13:59:51 +0200 Subject: [PATCH 1138/2359] Docs: tidying up Backends.md, add index, prepare for adding more docs. --- docs/BACKENDS.md | 88 ++++++++++++++++++++++++++++++------------------ 1 file changed, 56 insertions(+), 32 deletions(-) diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index fcdd703f4..0c5f71bc8 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -1,8 +1,19 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md or view this file with any Markdown viewer)_ -## Dear ImGui: Backends +# Dear ImGui: Backends -### Integrating backends +## Index + +- [Introduction](#introduction) +- [Using standard backends](#using-standard-backends) +- [List of third-party backends](#list-of-third-party-backends) +- [Writing your own backend](#writing-your-own-backend) + - [Using a custom engine?](#using-a-custom-engine) + - [Adding support for `ImGuiBackendFlags_RendererHasTextures` (1.92+)](#adding-support-for-imguibackendflags_rendererhastextures-192) + +## Introduction + +### Getting Started 💡 The **[Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) wiki guide** has examples of how to integrate Dear ImGui into an existing application.
The [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) documentation may also be worth a read. @@ -34,13 +45,13 @@ and the backends which we are describing here (backends/ folder). - You should be able to write backends for pretty much any platform and any 3D graphics API. e.g. you can get creative and use software rendering or render remotely on a different machine. -### Standard backends +## Using standard backends **The [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder contains backends for popular platforms/graphics API, which you can use in your application or engine to easily integrate Dear ImGui.** Each backend is typically self-contained in a pair of files: imgui_impl_XXXX.cpp + imgui_impl_XXXX.h. - The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, and windowing.
- e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), SDL2 ([imgui_impl_sdl2.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl2.cpp)), etc. + e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), SDL3 ([imgui_impl_sdl3.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl3.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), etc. - The 'Renderer' backends are in charge of: creating atlas texture, and rendering imgui draw data.
e.g. DirectX11 ([imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)), OpenGL/WebGL ([imgui_impl_opengl3.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_opengl3.cpp)), Vulkan ([imgui_impl_vulkan.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_vulkan.cpp)), etc. @@ -53,44 +64,41 @@ For example, the [example_win32_directx11](https://github.com/ocornut/imgui/tree **Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** -### List of backends +### List of standard backends In the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder: List of Platforms Backends: - imgui_impl_android.cpp ; Android native app API - imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ - imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) - imgui_impl_sdl2.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org - imgui_impl_sdl3.cpp ; SDL3 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org (*EXPERIMENTAL UNTIL SDL3 IS RELEASED*) - imgui_impl_win32.cpp ; Win32 native API (Windows) - imgui_impl_glut.cpp ; GLUT/FreeGLUT (this is prehistoric software and absolutely not recommended today!) + imgui_impl_android.cpp ; Android native app API + imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ + imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) + imgui_impl_sdl2.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org + imgui_impl_sdl3.cpp ; SDL3 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org + imgui_impl_win32.cpp ; Win32 native API (Windows) + imgui_impl_glut.cpp ; GLUT/FreeGLUT (this is prehistoric software and absolutely not recommended today!) List of Renderer Backends: - imgui_impl_dx9.cpp ; DirectX9 - imgui_impl_dx10.cpp ; DirectX10 - imgui_impl_dx11.cpp ; DirectX11 - imgui_impl_dx12.cpp ; DirectX12 - imgui_impl_metal.mm ; Metal (with ObjC) - imgui_impl_opengl2.cpp ; OpenGL 2 (legacy, fixed pipeline <- don't use with modern OpenGL context) - imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) + imgui_impl_dx9.cpp ; DirectX9 + imgui_impl_dx10.cpp ; DirectX10 + imgui_impl_dx11.cpp ; DirectX11 + imgui_impl_dx12.cpp ; DirectX12 + imgui_impl_metal.mm ; Metal (ObjC or C++) + imgui_impl_opengl2.cpp ; OpenGL 2 (legacy fixed pipeline. Don't use with modern OpenGL code!) + imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2/3, WebGL + imgui_impl_sdlgpu3.cpp ; SDL_GPU (portable 3D graphics API of SDL3) imgui_impl_sdlrenderer2.cpp ; SDL_Renderer (optional component of SDL2 available from SDL 2.0.18+) - imgui_impl_sdlrenderer3.cpp ; SDL_Renderer (optional component of SDL3 available from SDL 3.0.0+) - imgui_impl_vulkan.cpp ; Vulkan - imgui_impl_wgpu.cpp ; WebGPU (web and desktop) + imgui_impl_sdlrenderer3.cpp ; SDL_Renderer (optional component of SDL3. Prefer using SDL_GPU!). + imgui_impl_vulkan.cpp ; Vulkan + imgui_impl_wgpu.cpp ; WebGPU (web + desktop) List of high-level Frameworks Backends (combining Platform + Renderer): imgui_impl_allegro5.cpp Emscripten is also supported! -The SDL+GL, GLFW+GL and GLFW+WebGPU examples are all ready to build and run with Emscripten. - -### Backends for third-party frameworks, graphics API or other languages - -See https://github.com/ocornut/imgui/wiki/Bindings for the full list (e.g. Adventure Game Studio, Cinder, Cocos2d-x, Game Maker Studio2, Godot, LÖVE+LUA, Magnum, Monogame, Ogre, openFrameworks, OpenSceneGraph, SFML, Sokol, Unity, Unreal Engine and many others). +The SDL2+GL, SDL3+GL, GLFW+GL and GLFW+WebGPU examples are all ready to build and run with Emscripten. ### Recommended Backends @@ -98,18 +106,27 @@ If you are not sure which backend to use, the recommended platform/frameworks fo |Library |Website |Backend |Note | |--------|--------|--------|-----| -| GLFW | https://github.com/glfw/glfw | imgui_impl_glfw.cpp | | +| SDL3 | https://www.libsdl.org | imgui_impl_sdl3.cpp | Recommended | | SDL2 | https://www.libsdl.org | imgui_impl_sdl2.cpp | | +| GLFW | https://github.com/glfw/glfw | imgui_impl_glfw.cpp | | | Sokol | https://github.com/floooh/sokol | [util/sokol_imgui.h](https://github.com/floooh/sokol/blob/master/util/sokol_imgui.h) | Lower-level than GLFW/SDL | +If your application runs on Windows or if you are using multi-viewport, the win32 backend handles some details a little better than other backends. + +## List of third-party backends + +See https://github.com/ocornut/imgui/wiki/Bindings for the full list (e.g. Adventure Game Studio, Cinder, Cocos2d-x, Game Maker Studio2, Godot, LÖVE+LUA, Magnum, Monogame, Ogre, openFrameworks, OpenSceneGraph, SFML, Sokol, Unity, Unreal Engine and many others). + +## Writing your own backend ### Using a custom engine? You will likely be tempted to start by rewrite your own backend using your own custom/high-level facilities...
Think twice! -If you are new to Dear ImGui, first try using the existing backends as-is. -You will save lots of time integrating the library. +**Consider using the existing backends as-is**. +You will save lots of time integrating the library. +Standard backends are battle-tested and handle subtleties that you are likely to implement incorrectly. You can LATER decide to rewrite yourself a custom backend if you really need to. In most situations, custom backends have fewer features and more bugs than the standard backends we provide. If you want portability, you can use multiple backends and choose between them either at compile time @@ -131,8 +148,10 @@ Suggestion: try using a non-portable backend first (e.g. win32 + underlying grap your desktop builds working first. This will get you running faster and get your acquainted with how Dear ImGui works and is setup. You can then rewrite a custom backend using your own engine API... -Generally: -It is unlikely you will add value to your project by creating your own backend. +TL;DR; +- **It is unlikely you will add value to your project by creating your own backend.** +- Writing your own Renderer Backend is easier. +- Writing your own Platform Backend is harder and you are more likely to introduce bugs. Also: The [multi-viewports feature](https://github.com/ocornut/imgui/wiki/Multi-Viewports) of the 'docking' branch allows @@ -144,3 +163,8 @@ Supporting the multi-viewports feature correctly using 100% of your own abstract than supporting single-viewport. If you decide to use unmodified imgui_impl_XXXX.cpp files, you can automatically benefit from improvements and fixes related to viewports and platform windows without extra work on your side. + +### Adding support for `ImGuiBackendFlags_RendererHasTextures` (1.92+) + +Version [1.92.0](https://github.com/ocornut/imgui/releases/tag/v1.92.0), released June 2025, added texture support in Rendering Backends, which is the backbone for supporting dynamic font scaling among other things. +
**In order to move forward and take advantage of all new features, support for `ImGuiBackendFlags_RendererHasTextures` will likely be REQUIRED for all backends before June 2026.** From 47570d045db3749a97f7a632694e78ef80999f19 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 27 Jun 2025 14:51:13 +0200 Subject: [PATCH 1139/2359] Docs: update Backends with direction for implementing RenderDrawData function and supporting ImGuiBackendFlags_RendererHasTextures. (#8735, #8465) --- docs/BACKENDS.md | 189 +++++++++++++++++++++++++++++++++++++++++---- docs/CHANGELOG.txt | 3 + docs/EXAMPLES.md | 2 +- docs/FAQ.md | 13 +++- imgui.cpp | 123 +++++++---------------------- imgui.h | 2 +- imgui_demo.cpp | 5 ++ 7 files changed, 227 insertions(+), 110 deletions(-) diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 0c5f71bc8..aae663078 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -7,9 +7,10 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKE - [Introduction](#introduction) - [Using standard backends](#using-standard-backends) - [List of third-party backends](#list-of-third-party-backends) -- [Writing your own backend](#writing-your-own-backend) +- [Writing your own Backend](#writing-your-own-backend) - [Using a custom engine?](#using-a-custom-engine) - - [Adding support for `ImGuiBackendFlags_RendererHasTextures` (1.92+)](#adding-support-for-imguibackendflags_rendererhastextures-192) + - [Rendering: Implementing your RenderDrawData function](#rendering-implementing-your-renderdrawdata-function) + - [Rendering: Adding support for `ImGuiBackendFlags_RendererHasTextures` (1.92+)](#rendering-adding-support-for-imguibackendflags_rendererhastextures-192) ## Introduction @@ -117,15 +118,20 @@ If your application runs on Windows or if you are using multi-viewport, the win3 See https://github.com/ocornut/imgui/wiki/Bindings for the full list (e.g. Adventure Game Studio, Cinder, Cocos2d-x, Game Maker Studio2, Godot, LÖVE+LUA, Magnum, Monogame, Ogre, openFrameworks, OpenSceneGraph, SFML, Sokol, Unity, Unreal Engine and many others). -## Writing your own backend +## Writing your own Backend ### Using a custom engine? You will likely be tempted to start by rewrite your own backend using your own custom/high-level facilities...
Think twice! +TL;DR; +- Writing your own Renderer Backend is easy. +- Writing your own Platform Backend is harder and you are more likely to introduce bugs. +- **It is unlikely you will add value to your project by creating your own backend.** + **Consider using the existing backends as-is**. -You will save lots of time integrating the library. +You will save lots of time integrating the library. Standard backends are battle-tested and handle subtleties that you are likely to implement incorrectly. You can LATER decide to rewrite yourself a custom backend if you really need to. In most situations, custom backends have fewer features and more bugs than the standard backends we provide. @@ -148,23 +154,180 @@ Suggestion: try using a non-portable backend first (e.g. win32 + underlying grap your desktop builds working first. This will get you running faster and get your acquainted with how Dear ImGui works and is setup. You can then rewrite a custom backend using your own engine API... -TL;DR; -- **It is unlikely you will add value to your project by creating your own backend.** -- Writing your own Renderer Backend is easier. -- Writing your own Platform Backend is harder and you are more likely to introduce bugs. - Also: The [multi-viewports feature](https://github.com/ocornut/imgui/wiki/Multi-Viewports) of the 'docking' branch allows Dear ImGui windows to be seamlessly detached from the main application window. This is achieved using an extra layer to the Platform and Renderer backends, which allows Dear ImGui to communicate platform-specific requests such as: "create an additional OS window", "create a render context", "get the OS position of this -window" etc. See 'ImGuiPlatformIO' for details. +window", but some things are more difficult "find OS window under mouse position BUT with some windows marked as passthrough". See 'ImGuiPlatformIO' for details. Supporting the multi-viewports feature correctly using 100% of your own abstractions is more difficult than supporting single-viewport. If you decide to use unmodified imgui_impl_XXXX.cpp files, you can automatically benefit from improvements and fixes related to viewports and platform windows without extra work on your side. -### Adding support for `ImGuiBackendFlags_RendererHasTextures` (1.92+) +### Rendering: Implementing your RenderDrawData function -Version [1.92.0](https://github.com/ocornut/imgui/releases/tag/v1.92.0), released June 2025, added texture support in Rendering Backends, which is the backbone for supporting dynamic font scaling among other things. -
**In order to move forward and take advantage of all new features, support for `ImGuiBackendFlags_RendererHasTextures` will likely be REQUIRED for all backends before June 2026.** +Note: set `ImGuiBackendFlags_RendererHasVtxOffset` to signify your backend can handle rendering with a vertex offset (`ImDrawCmd::VtxOffset` field). +Otherwise, rendering will be limited to 64K vertices per window, which may be limiting for advanced plot. +As an alternative, you may also use `#define ImDrawIdx unsigned int` in your `imconfig.h` file to support 32-bit indices. + +```cpp +void MyImGuiBackend_RenderDrawData(ImDrawData* draw_data) +{ + // TODO: Update textures. + // - Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // - This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates. + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + MyImGuiBackend_UpdateTexture(tex); + + // TODO: Setup render state: + // - Alpha-blending enabled + // - No backface culling + // - No depth testing, no depth writing + // - Scissor enabled + MyEngineSetupenderState(); + + // TODO: Setup texture sampling state + // - Sample with bilinear filtering (NOT point/nearest filtering). + // - Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering. + + // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize + + // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize + + // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color. + + // Render command lists + ImVec2 clip_off = draw_data->DisplayPos; + ImVec2 clip_scale = draw_data->FramebufferScale; + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui + const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) + { + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + MyEngineSetupenderState(); + else + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + // - Clipping coordinates are provided in imgui coordinates space: + // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size + // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values. + // - In the interest of supporting multi-viewport applications (see 'docking' branch on github), + // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space. + // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min) + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + // We are using scissoring to clip some objects. All low-level graphics API should support it. + // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches + // (some elements visible outside their bounds) but you can fix that once everything else works! + MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y); + + // The texture for the draw call is specified by pcmd->GetTexID(). + // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization. + MyEngineBindTexture((MyTexture*)pcmd->GetTexID()); + + // Render 'pcmd->ElemCount/3' indexed triangles. + // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices. + MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset); + } + } + } +} +``` + +### Rendering: Adding support for `ImGuiBackendFlags_RendererHasTextures` (1.92+) + +Version [1.92.0](https://github.com/ocornut/imgui/releases/tag/v1.92.0) (June 2025), added texture support in Rendering Backends, which is the backbone for supporting dynamic font scaling among other things. + +**In order to move forward and take advantage of all new features, support for `ImGuiBackendFlags_RendererHasTextures` will likely be REQUIRED for all backends before June 2026.** + +**TD;DR: List of commits which added support for `ImGuiBackendFlags_RendererHasTextures` in standard backends:** + +- Allegro5: [ee8941e](https://github.com/ocornut/imgui/commit/ee8941e) (+35 lines) +- DirectX9: [75efba7](https://github.com/ocornut/imgui/commit/75efba7) (+48 lines) +- DirectX10: [2d2b1bc](https://github.com/ocornut/imgui/commit/2d2b1bc) (+40 lines) +- DirectX11: [372fd27](https://github.com/ocornut/imgui/commit/372fd27) (+40 lines) +- DirectX12: [eefe5d5](https://github.com/ocornut/imgui/commit/eefe5d5) (+87 lines) +- Metal: [26c017d](https://github.com/ocornut/imgui/commit/26c017d) (+55 lines) +- OpenGL Legacy: [0430c55](https://github.com/ocornut/imgui/commit/0430c55) (+25 lines) +- OpenGL3/WebGL/ES: [dbb91a5](https://github.com/ocornut/imgui/commit/dbb91a5) (+47 lines) +- SDL_Renderer2: [9fa65cd](https://github.com/ocornut/imgui/commit/9fa65cd) (+20 lines) +- SDL_Renderer3: [e538883](https://github.com/ocornut/imgui/commit/e538883) (+19 lines) +- SDL_GPU: [16fe666](https://github.com/ocornut/imgui/commit/16fe666) (+41 lines) +- Vulkan: [abe294b](https://github.com/ocornut/imgui/commit/abe294b) (+33 lines) +- WGPU: [571dae9](https://github.com/ocornut/imgui/commit/571dae9) (+30 lines) + +**Instructions** + +- Set `ImGuiBackendFlags_RendererHasTextures` to signify your backend can handle the feature. +- During rendering, e.g. in your RenderDrawData function, iterate `ImDrawData->Textures` array and process all textures. +- During shutdown, iterate the `ImGui::GetPlatformIO().Textures` and destroy all textures. +- (Both arrays are `ImVector`. They are only in different location because: to allow advanced users to perform multi-threaded rendering, we store a pointer to the texture list in ImDrawData, with the aim that multi-threaded rendering users replace it with their own pointer.) + +Pseudo-code for processing a texture: +```cpp +if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + MyImGuiBackend_UpdateTexture(tex); +``` +```cpp +void MyImGuiBackend_UpdateTexture(ImTextureData* tex) +{ + if (tex->Status == ImTextureStatus_WantCreate) + { + // Create texture based on tex->Width, tex->Height. + // - Most backends only support tex->Format == ImTextureFormat_RGBA32. + // - Backends for particularly memory constrainted platforms may support tex->Format == ImTextureFormat_Alpha8. + + // Upload all texture pixels + // - Read from our CPU-side copy of the texture and copy to your graphics API. + // - Use tex->Width, tex->Height, tex->GetPixels(), tex->GetPixelsAt(), tex->GetPitch() as needed. + + // Store your data, and acknowledge creation. + tex->SetTexID(xxxx); // Specify backend-specific ImTextureID identifier which will be stored in ImDrawCmd. + tex->SetStatus(ImTextureStatus_OK); + tex->BackendUserData = xxxx; // Store more backend data if needed (most backend allocate a small texture to store data in there) + } + if (tex->Status == ImTextureStatus_WantUpdates) + { + // Upload a rectangle of pixels to the existing texture + // - We only ever write to textures regions which have never been used before! + // - Use tex->TexID or tex->BackendUserData to retrieve your stored data. + // - Use tex->UpdateRect.x/y, tex->UpdateRect.w/h to obtain the block position and size. + // - Use tex->Updates[] to obtain individual sub-regions within tex->UpdateRect. Not recommended. + // - Read from our CPU-side copy of the texture and copy to your graphics API. + // - Use tex->Width, tex->Height, tex->GetPixels(), tex->GetPixelsAt(), tex->GetPitch() as needed. + + // Acknowledge update + tex->SetStatus(ImTextureStatus_OK); + } + if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + { + // If you use staged rendering and have in-flight renders, changed tex->UnusedFrames > 0 check to higher count as needed e.g. > 2 + + // Destroy texture + // - Use tex->TexID or tex->BackendUserData to retrieve your stored data. + // - Destroy texture in your graphics API. + + // Acknowledge destruction + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + } +} +``` +Refer to "List of commits which added support for `ImGuiBackendFlags_RendererHasTextures` in standard backends" above for concrete examples of this. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1b93505d1..bdd06a7c3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,6 +57,9 @@ THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCE, BUT INEVITABLY SOME USERS OR THIRD-PARTY EXTENSIONS WILL BE AFFECTED. +For instructions to upgrade your custom backend: +--> See https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md + IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/ diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index 2826a5ad7..20851c158 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -3,7 +3,7 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/EXAMP ## Dear ImGui: Examples **The [examples/](https://github.com/ocornut/imgui/blob/master/examples) folder example applications (standalone, ready-to-build) for variety of -platforms and graphics APIs.** They all use standard backends from the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder (see [BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md)). +platforms and graphics APIs.** They all use standard backends from the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder (see [docs/BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md)). The purpose of Examples is to showcase integration with backends, let you try Dear ImGui, and guide you toward integrating Dear ImGui in your own application/game/engine. diff --git a/docs/FAQ.md b/docs/FAQ.md index ad35d5451..10fb60350 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -19,6 +19,7 @@ or view this file with any Markdown viewer. | **[How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?](#q-how-can-i-tell-whether-to-dispatch-mousekeyboard-to-dear-imgui-or-my-application)** | | [How can I enable keyboard or gamepad controls?](#q-how-can-i-enable-keyboard-or-gamepad-controls) | | [How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)](#q-how-can-i-use-this-on-a-machine-without-mouse-keyboard-or-screen-input-share-remote-display) | +| [How can I create my own backend?](q-how-can-i-create-my-own-backend) | [I integrated Dear ImGui in my engine and little squares are showing instead of text...](#q-i-integrated-dear-imgui-in-my-engine-and-little-squares-are-showing-instead-of-text) | | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | | [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | @@ -92,8 +93,8 @@ Many projects are using this branch and it is kept in sync with master regularly ### Q: How to get started? Read [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started).
-Read [EXAMPLES.md](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md).
-Read [BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md).
+Read [docs/EXAMPLES.md](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md).
+Read [docs/BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md).
Read `PROGRAMMER GUIDE` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp).
The [Wiki](https://github.com/ocornut/imgui/wiki) is a hub to many resources and links. @@ -159,6 +160,14 @@ Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-lik --- +### Q: How can I create my own backend? +- See [docs/BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md). +- See Documentation at the top of imgui.cpp. + +##### [Return to Index](#index) + +--- + ### Q: I integrated Dear ImGui in my engine and little squares are showing instead of text... Your renderer backend is not using the font texture correctly or it hasn't been uploaded to the GPU. - If this happens using standard backends (before 1.92): A) have you modified the font atlas after `ImGui_ImplXXX_NewFrame()`? B) maybe the texture failed to upload, which **can if your texture atlas is too big**. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). diff --git a/imgui.cpp b/imgui.cpp index b5c534c57..b256c9ffe 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -53,7 +53,7 @@ DOCUMENTATION - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE - HOW A SIMPLE APPLICATION MAY LOOK LIKE - - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE + - USING CUSTOM BACKEND / CUSTOM ENGINE - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ) - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer) @@ -274,7 +274,8 @@ CODE HOW A SIMPLE APPLICATION MAY LOOK LIKE -------------------------------------- - EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder). + + USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder). The sub-folders in examples/ contain examples applications following this structure. // Application init: create a dear imgui context, setup some options, load fonts @@ -310,7 +311,27 @@ CODE ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); - EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE + To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application, + you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! + Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this. + + +USING CUSTOM BACKEND / CUSTOM ENGINE +------------------------------------ + +IMPLEMENTING YOUR RenderDrawData() function: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md + -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_RenderDrawData() function. + +IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md + -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_UpdateTexture() function. + +IMPLEMENTING YOUR PLATFORM BACKEND: + -> missing documentation. + -> the Platform backends in impl_impl_XXX.cpp files contain many implementations. + + Basic application/backend skeleton: // Application init: create a Dear ImGui context, setup some options, load fonts ImGui::CreateContext(); @@ -319,7 +340,7 @@ CODE io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard controls // TODO: Load TTF/OTF fonts if you don't want to use the default font. - io.Fonts->AddFontFromFileTTF("NotoSans.ttf", 18.0f); + io.Fonts->AddFontFromFileTTF("NotoSans.ttf"); // Application main loop while (true) @@ -361,95 +382,6 @@ CODE // Shutdown ImGui::DestroyContext(); - To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application, - you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! - Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this. - - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE - --------------------------------------------- - The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function. - - void MyImGuiBackend_UpdateTexture(ImTextureData* tex) - { - if (tex->Status == ImTextureStatus_WantCreate) - { - // Width/Height/Pixels> - tex->SetTexID(xxxx); // specify backend-specific ImTextureID identifier - tex->SetStatus(ImTextureStatus_OK); - tex->BackendUserData = xxxx; // store more backend data - } - if (tex->Status == ImTextureStatus_WantUpdates) - { - // UpdateRect> - tex->SetStatus(ImTextureStatus_OK); - } - if (tex->Status == ImTextureStatus_WantDestroy) - { - // - tex->SetTexID(ImTextureID_Invalid); - tex->SetStatus(ImTextureStatus_Destroyed); - } - } - - void MyImGuiBackend_RenderDrawData(ImDrawData* draw_data) - { - if (draw_data->Textures != nullptr) - for (ImTextureData* tex : *draw_data->Textures) - if (tex->Status != ImTextureStatus_OK) - MyImGuiBackend_UpdateTexture(tex); - - - // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled - // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering. - // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize - // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize - // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color. - ImVec2 clip_off = draw_data->DisplayPos; - for (int n = 0; n < draw_data->CmdListsCount; n++) - { - const ImDrawList* cmd_list = draw_data->CmdLists[n]; - const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui - const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui - for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) - { - const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) - { - if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) - MyEngineResetRenderState(); - else - pcmd->UserCallback(cmd_list, pcmd); - } - else - { - // Project scissor/clipping rectangles into framebuffer space - ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); - ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); - if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) - continue; - - // We are using scissoring to clip some objects. All low-level graphics API should support it. - // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches - // (some elements visible outside their bounds) but you can fix that once everything else works! - // - Clipping coordinates are provided in imgui coordinates space: - // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size - // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values. - // - In the interest of supporting multi-viewport applications (see 'docking' branch on github), - // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space. - // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min) - MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y); - - // The texture for the draw call is specified by pcmd->GetTexID(). - // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization. - MyEngineBindTexture((MyTexture*)pcmd->GetTexID()); - - // Render 'pcmd->ElemCount/3' indexed triangles. - // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices. - MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset); - } - } - } - } API BREAKING CHANGES @@ -15941,7 +15873,12 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); //EndDisabled(); if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + { BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); + BulletText("For instructions, see:"); + SameLine(); + TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md"); + } BulletText("Load a nice font for better results!"); BulletText("Please submit feedback:"); SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); diff --git a/imgui.h b/imgui.h index ab23774d1..e417731d0 100644 --- a/imgui.h +++ b/imgui.h @@ -1691,7 +1691,7 @@ enum ImGuiBackendFlags_ ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. - ImGuiBackendFlags_RendererHasTextures = 1 << 4, // Backend Renderer supports ImTextureData requests to create/update/destroy textures. This enables incremental texture updates and texture reloads. + ImGuiBackendFlags_RendererHasTextures = 1 << 4, // Backend Renderer supports ImTextureData requests to create/update/destroy textures. This enables incremental texture updates and texture reloads. See https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for instructions on how to upgrade your custom backend. }; // Enumeration for PushStyleColor() / PopStyleColor() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 94d39587f..c743667c1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8230,7 +8230,12 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) // General SeparatorText("General"); if ((GetIO().BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + { BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); + BulletText("For instructions, see:"); + SameLine(); + TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md"); + } if (ShowStyleSelector("Colors##Selector")) ref_saved_style = style; From 68046106ddf02b2c518977814b78b47cb27d792b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 27 Jun 2025 15:15:34 +0200 Subject: [PATCH 1140/2359] Docs: update Backends with basic Platform backend instructions. --- docs/BACKENDS.md | 57 ++++++++++++++++++++++++++++++++++++++++++------ imgui.cpp | 8 +++---- 2 files changed, 54 insertions(+), 11 deletions(-) diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index aae663078..ae5e91b0e 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -5,10 +5,13 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKE ## Index - [Introduction](#introduction) -- [Using standard backends](#using-standard-backends) -- [List of third-party backends](#list-of-third-party-backends) + - [Getting Started](#getting-started) + - [What are Backends?](#what-are-backends) +- [Using standard Backends](#using-standard-backends) +- [Using third-party Backends](#using-third-party-backends) - [Writing your own Backend](#writing-your-own-backend) - [Using a custom engine?](#using-a-custom-engine) + - [Platform: Implementing your Platform Backend](#platform-implementing-your-platform-backend) - [Rendering: Implementing your RenderDrawData function](#rendering-implementing-your-renderdrawdata-function) - [Rendering: Adding support for `ImGuiBackendFlags_RendererHasTextures` (1.92+)](#rendering-adding-support-for-imguibackendflags_rendererhastextures-192) @@ -19,7 +22,7 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKE 💡 The **[Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) wiki guide** has examples of how to integrate Dear ImGui into an existing application.
The [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) documentation may also be worth a read. -### What are backends? +### What are Backends? Dear ImGui is highly portable and only requires a few things to run and render, typically: @@ -46,7 +49,7 @@ and the backends which we are describing here (backends/ folder). - You should be able to write backends for pretty much any platform and any 3D graphics API. e.g. you can get creative and use software rendering or render remotely on a different machine. -## Using standard backends +## Using standard Backends **The [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder contains backends for popular platforms/graphics API, which you can use in your application or engine to easily integrate Dear ImGui.** Each backend is typically self-contained in a pair of files: imgui_impl_XXXX.cpp + imgui_impl_XXXX.h. @@ -65,7 +68,7 @@ For example, the [example_win32_directx11](https://github.com/ocornut/imgui/tree **Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** -### List of standard backends +### List of standard Backends In the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder: @@ -114,7 +117,7 @@ If you are not sure which backend to use, the recommended platform/frameworks fo If your application runs on Windows or if you are using multi-viewport, the win32 backend handles some details a little better than other backends. -## List of third-party backends +## Using third-party Backends See https://github.com/ocornut/imgui/wiki/Bindings for the full list (e.g. Adventure Game Studio, Cinder, Cocos2d-x, Game Maker Studio2, Godot, LÖVE+LUA, Magnum, Monogame, Ogre, openFrameworks, OpenSceneGraph, SFML, Sokol, Unity, Unreal Engine and many others). @@ -165,6 +168,46 @@ than supporting single-viewport. If you decide to use unmodified imgui_impl_XXXX.cpp files, you can automatically benefit from improvements and fixes related to viewports and platform windows without extra work on your side. +### Platform: Implementing your Platform Backend + +The Platform backends in impl_impl_XXX.cpp files contain many implementations. + +**In your `ImGui_ImplXXX_Init()` function:** +- You can allocate your backend data and use `io.BackendPlatformUserData` to store/retrieve it later. +- Set `io.BackendPlatformName` to a name `"imgui_impl_xxxx"` which will be available in e.g. About box. +- Set `io.BackendPlatformUserData` to your backend data. +- Set `io.BackendFlags` with supported optional features: + - `ImGuiBackendFlags_HasGamepad`: supports gamepad and currently has one connected. + - `ImGuiBackendFlags_HasMouseCursors`: supports honoring GetMouseCursor() value to change the OS cursor shape. + - `ImGuiBackendFlags_HasSetMousePos`: supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). + - `ImGuiBackendFlags_PlatformHasViewports` supports multiple viewports. (multi-viewports only) + - `ImGuiBackendFlags_HasMouseHoveredViewport` supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the ImGuiViewportFlags_NoInputs flag. If this cannot be done, Dear ImGui needs to use a flawed heuristic to find the viewport under mouse position, as it doesn't know about foreign windows. (multi-viewports only) + +**In your `ImGui_ImplXXX_NewFrame()` function:** +- Set `io.DeltaTime` to the time elapsed (in seconds) since last frame. +- Set `io.DisplaySize` to your window size. +- Set `io.DisplayFrameBufferSize` to your window pixel density (macOS/iOS only). +- Update mouse cursor shape is supported. + +**In your `ImGui_ImplXXX_NewFrame()` function or event handlers:** +- **Mouse Support** + - Use `io.AddMousePosEvent()`, `io.AddMouseButtonEvent()`, `io.AddMouseWheelEvent()` to pass mouse events. + - Use `io.AddMouseSourceEvent()` if you are able to distinguish Mouse from TouchScreen from Pen inputs. TouchScreen and Pen inputs requires different logic for some Dear ImGui features. + - Use `io.AddMouseViewportEvent()` to specify which viewport/OS window is being hovered by the mouse. Read instructions carefully as this is not as simple as it seems! (multi-viewports only) +- **Keyboard Support** + - Use `io.AddKeyEvent()` to pass key events. + - Use `io.AddInputCharacter()` to pass text/character events. +- **Gamepad Support** + - Use `io.AddKeyEvent()` and `io.AddKeyAnalogEvent()` to pass gamepad events, using `ImGuiKey_GamepadXXX` values. +- **Miscellaneous** + - Clipboard Support: setup `Platform_GetClipboardTextFn()`, `Platform_SetClipboardTextFn()` handlers in `ImGuiPlatformIO`. + - Open in Shell support: setup `Platform_OpenInShellFn()` handler in `ImGuiPlatformIO`. + - IME Support: setup `Platform_SetImeDataFn()` handler in `ImGuiPlatformIO`. + - Use `io.AddFocusEvent()` to notify when application window gets focused/unfocused. +- **Multi-viewport Support** + - Update monitor list if supported. + - Setup all required handlers in `ImGuiPlatformIO` to create/destroy/move/resize/title/focus/etc. windows. + ### Rendering: Implementing your RenderDrawData function Note: set `ImGuiBackendFlags_RendererHasVtxOffset` to signify your backend can handle rendering with a vertex offset (`ImDrawCmd::VtxOffset` field). @@ -271,7 +314,7 @@ Version [1.92.0](https://github.com/ocornut/imgui/releases/tag/v1.92.0) (June 20 - Vulkan: [abe294b](https://github.com/ocornut/imgui/commit/abe294b) (+33 lines) - WGPU: [571dae9](https://github.com/ocornut/imgui/commit/571dae9) (+30 lines) -**Instructions** +**Instructions:** - Set `ImGuiBackendFlags_RendererHasTextures` to signify your backend can handle the feature. - During rendering, e.g. in your RenderDrawData function, iterate `ImDrawData->Textures` array and process all textures. diff --git a/imgui.cpp b/imgui.cpp index b256c9ffe..acdbf33e4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -319,6 +319,10 @@ CODE USING CUSTOM BACKEND / CUSTOM ENGINE ------------------------------------ +IMPLEMENTING YOUR PLATFORM BACKEND: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. + -> the Platform backends in impl_impl_XXX.cpp files contain many implementations. + IMPLEMENTING YOUR RenderDrawData() function: -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_RenderDrawData() function. @@ -327,10 +331,6 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_UpdateTexture() function. -IMPLEMENTING YOUR PLATFORM BACKEND: - -> missing documentation. - -> the Platform backends in impl_impl_XXX.cpp files contain many implementations. - Basic application/backend skeleton: // Application init: create a Dear ImGui context, setup some options, load fonts From 8e3aac57449b9ab73dabef187807528a597e837a Mon Sep 17 00:00:00 2001 From: Thomas Quante Date: Fri, 27 Jun 2025 15:52:39 +0200 Subject: [PATCH 1141/2359] Backends: Vulkan: use nonCoherentAtomSize to align upload_size, fixing validation error on some setups. (#8743, #8744) --- backends/imgui_impl_vulkan.cpp | 10 +++++++++- docs/CHANGELOG.txt | 2 ++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 5546a59ff..059e8c9ed 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-27: Vulkan: Fixed validation errors during texture upload/update by aligning upload size to 'nonCoherentAtomSize'. (#8743, #8744) // 2025-06-11: Vulkan: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_DestroyFontsTexture(). // 2025-05-07: Vulkan: Fixed validation errors during window detach in multi-viewport mode. (#8600, #8176) // 2025-05-07: Vulkan: Load dynamic rendering functions using vkGetDeviceProcAddr() + try both non-KHR and KHR versions. (#8600, #8326, #8365) @@ -244,6 +245,7 @@ struct ImGui_ImplVulkan_Data { ImGui_ImplVulkan_InitInfo VulkanInitInfo; VkDeviceSize BufferMemoryAlignment; + VkDeviceSize NonCoherentAtomSize; VkPipelineCreateFlags PipelineCreateFlags; VkDescriptorSetLayout DescriptorSetLayout; VkPipelineLayout PipelineLayout; @@ -264,6 +266,7 @@ struct ImGui_ImplVulkan_Data { memset((void*)this, 0, sizeof(*this)); BufferMemoryAlignment = 256; + NonCoherentAtomSize = 64; } }; @@ -751,7 +754,7 @@ void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) VkBuffer upload_buffer; VkDeviceSize upload_pitch = upload_w * tex->BytesPerPixel; - VkDeviceSize upload_size = upload_h * upload_pitch; + VkDeviceSize upload_size = AlignBufferSize(upload_h * upload_pitch, bd->NonCoherentAtomSize); { VkBufferCreateInfo buffer_info = {}; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; @@ -1225,6 +1228,11 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); bd->VulkanInitInfo = *info; + + VkPhysicalDeviceProperties properties; + vkGetPhysicalDeviceProperties(info->PhysicalDevice, &properties); + bd->NonCoherentAtomSize = properties.limits.nonCoherentAtomSize; + #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; if (v->PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bdd06a7c3..5666a03cc 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,8 @@ Other changes: - Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. (#8739) [@cfillion] +- Backends: Vulkan: use nonCoherentAtomSize to align upload_size, fixing + validation error on some setups. (#8743, #8744) [@tquante] ----------------------------------------------------------------------- From fff47f111985ee755256dce0f19e0aaee6e2eb7f Mon Sep 17 00:00:00 2001 From: morrazzzz <123486080+morrazzzz@users.noreply.github.com> Date: Tue, 24 Jun 2025 23:30:38 +0300 Subject: [PATCH 1142/2359] Backends: SDL3: avoid calling SDL_StartTextInput() again if already active. (#8727) --- backends/imgui_impl_sdl3.cpp | 3 ++- docs/CHANGELOG.txt | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 9c0d6581c..48e766bcd 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-06-27: IME: avoid calling SDL_StartTextInput() again if already active. (#8727) // 2025-04-22: IME: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. // 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) // 2025-03-30: Update for SDL3 api changes: Revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) @@ -169,7 +170,7 @@ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view SDL_SetTextInputArea(window, &r, 0); bd->ImeWindow = window; } - if (data->WantVisible || data->WantTextInput) + if (!SDL_TextInputActive(window) && (data->WantVisible || data->WantTextInput)) SDL_StartTextInput(window); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5666a03cc..fd705f1c8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking changes: Other changes: +- Backends: SDL3: avoid calling SDL_StartTextInput() again if already active. + (#8727) [@morrazzzz] - Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. (#8739) [@cfillion] - Backends: Vulkan: use nonCoherentAtomSize to align upload_size, fixing From 9fbe56021865d6961859dc40a93bc5dba11e7401 Mon Sep 17 00:00:00 2001 From: Demonese Date: Fri, 27 Jun 2025 10:33:25 +0800 Subject: [PATCH 1143/2359] Demo: Added "Widgets/Text/Different Size Text" section to show font system changes in v1.92. (#8738) --- imgui_demo.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c743667c1..8acbfcb39 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3548,6 +3548,35 @@ static void DemoWindowWidgetsText() ImGui::TreePop(); } + IMGUI_DEMO_MARKER("Widgets/Text/Different Size Text"); + if (ImGui::TreeNode("Different Size Text")) + { + const ImGuiStyle& style = ImGui::GetStyle(); + + for (float scaling = 0.5f; scaling < 4.01f; scaling += 0.5f) + { + ImGui::PushFont(nullptr, style.FontSizeBase * scaling); + ImGui::Text("Text size is %.1f (style.FontSizeBase * %.1f)", style.FontSizeBase * scaling, scaling); + ImGui::PopFont(); + } + + static float custom_scaling{ 1.0f }; + ImGui::SliderFloat("Custom Scaling##Different Size Text", &custom_scaling, 0.5f, 4.0f, "%.1f"); + ImGui::SameLine(); HelpMarker("ImGui::PushFont(nullptr, style.FontSizeBase * custom_scaling);"); + ImGui::PushFont(nullptr, style.FontSizeBase * custom_scaling); + ImGui::Text("Text size is %.1f (style.FontSizeBase * %.1f)", style.FontSizeBase * custom_scaling, custom_scaling); + ImGui::PopFont(); + + static float custom_font_size{ 16.0f }; + ImGui::SliderFloat("Custom Font Size##Different Size Text", &custom_font_size, 10.0f, 100.0f, "%.1f"); + ImGui::SameLine(); HelpMarker("ImGui::PushFont(nullptr, custom_font_size);"); + ImGui::PushFont(nullptr, custom_font_size); + ImGui::Text("Text size is %.1f", custom_font_size); + ImGui::PopFont(); + + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping"); if (ImGui::TreeNode("Word Wrapping")) { From 0fe51665313b627957cb11ed177e09ee9ccf9364 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 27 Jun 2025 16:54:16 +0200 Subject: [PATCH 1144/2359] Demo: amend "Font Size" demo. (#8738) --- imgui_demo.cpp | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8acbfcb39..692eb2992 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3548,32 +3548,40 @@ static void DemoWindowWidgetsText() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text/Different Size Text"); - if (ImGui::TreeNode("Different Size Text")) + IMGUI_DEMO_MARKER("Widgets/Text/Font Size"); + if (ImGui::TreeNode("Font Size")) { - const ImGuiStyle& style = ImGui::GetStyle(); + ImGuiStyle& style = ImGui::GetStyle(); + const float global_scale = style.FontScaleMain * style.FontScaleDpi; + ImGui::Text("style.FontScaleMain = %0.2f", style.FontScaleMain); + ImGui::Text("style.FontScaleDpi = %0.2f", style.FontScaleDpi); + ImGui::Text("global_scale = ~%0.2f", global_scale); // This is not technically accurate as internal scales may apply, but conceptually let's pretend it is. + ImGui::Text("FontSize = %0.2f", ImGui::GetFontSize()); - for (float scaling = 0.5f; scaling < 4.01f; scaling += 0.5f) + ImGui::SeparatorText(""); + static float custom_size = 16.0f; + ImGui::SliderFloat("custom_size", &custom_size, 10.0f, 100.0f, "%.0f"); + ImGui::Text("ImGui::PushFont(nullptr, custom_size);"); + ImGui::PushFont(NULL, custom_size); + ImGui::Text("FontSize = %.2f (== %.2f * global_scale)", ImGui::GetFontSize(), custom_size); + ImGui::PopFont(); + + ImGui::SeparatorText(""); + static float custom_scale = 1.0f; + ImGui::SliderFloat("custom_scale", &custom_scale, 0.5f, 4.0f, "%.2f"); + ImGui::Text("ImGui::PushFont(nullptr, style.FontSizeBase * custom_scale);"); + ImGui::PushFont(NULL, style.FontSizeBase * custom_scale); + ImGui::Text("FontSize = %.2f (== style.FontSizeBase * %.2f * global_scale)", ImGui::GetFontSize(), custom_scale); + ImGui::PopFont(); + + ImGui::SeparatorText(""); + for (float scaling = 0.5f; scaling <= 4.0f; scaling += 0.5f) { - ImGui::PushFont(nullptr, style.FontSizeBase * scaling); - ImGui::Text("Text size is %.1f (style.FontSizeBase * %.1f)", style.FontSizeBase * scaling, scaling); + ImGui::PushFont(NULL, style.FontSizeBase * scaling); + ImGui::Text("FontSize = %.2f (== style.FontSizeBase * %.2f * global_scale)", ImGui::GetFontSize(), scaling); ImGui::PopFont(); } - static float custom_scaling{ 1.0f }; - ImGui::SliderFloat("Custom Scaling##Different Size Text", &custom_scaling, 0.5f, 4.0f, "%.1f"); - ImGui::SameLine(); HelpMarker("ImGui::PushFont(nullptr, style.FontSizeBase * custom_scaling);"); - ImGui::PushFont(nullptr, style.FontSizeBase * custom_scaling); - ImGui::Text("Text size is %.1f (style.FontSizeBase * %.1f)", style.FontSizeBase * custom_scaling, custom_scaling); - ImGui::PopFont(); - - static float custom_font_size{ 16.0f }; - ImGui::SliderFloat("Custom Font Size##Different Size Text", &custom_font_size, 10.0f, 100.0f, "%.1f"); - ImGui::SameLine(); HelpMarker("ImGui::PushFont(nullptr, custom_font_size);"); - ImGui::PushFont(nullptr, custom_font_size); - ImGui::Text("Text size is %.1f", custom_font_size); - ImGui::PopFont(); - ImGui::TreePop(); } From bc051dcf91cb0e3c61ce20e582c91654d0049003 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 27 Jun 2025 17:03:13 +0200 Subject: [PATCH 1145/2359] Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value. --- docs/CHANGELOG.txt | 3 +++ imgui.h | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fd705f1c8..3bf28c689 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking changes: Other changes: +- Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value: + ImTextureData() was incorrectly cleared with zeroes. (#8745) [@rachit7645] +- Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] - Backends: SDL3: avoid calling SDL_StartTextInput() again if already active. (#8727) [@morrazzzz] - Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress diff --git a/imgui.h b/imgui.h index e417731d0..b09d7ee82 100644 --- a/imgui.h +++ b/imgui.h @@ -3440,7 +3440,7 @@ struct ImTextureData bool WantDestroyNextFrame; // rw - // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. // Functions - ImTextureData() { memset(this, 0, sizeof(*this)); } + ImTextureData() { memset(this, 0, sizeof(*this)); TexID = ImTextureID_Invalid; } ~ImTextureData() { DestroyPixels(); } IMGUI_API void Create(ImTextureFormat format, int w, int h); IMGUI_API void DestroyPixels(); From de7625b8c25b07214a7ed6540d2225a1547c2231 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 28 Jun 2025 16:45:58 +0200 Subject: [PATCH 1146/2359] Docs: tweak/fixed comments. (#8750, #8749) --- docs/CHANGELOG.txt | 12 +++++------- docs/FONTS.md | 2 +- imgui.cpp | 9 ++++++--- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3bf28c689..b548fb657 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -117,13 +117,11 @@ Breaking changes: `PushFont(NULL, some_size)` now keeps current change and changes size. - Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. - Fonts: **IMPORTANT** on Font Merging: - - When searching for a glyph in multiple merged fonts: font inputs are now scanned in order - for the first font input which the desired glyph. This is technically a different behavior - than before! - - e.g. If you are merging fonts you may have glyphs that you expected to load from - Font Source 2 which exists in Font Source 1. After the update and when using a new backend, - those glyphs may now loaded from Font Source 1! - - You can use `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to ignore in given Input: + - When searching for a glyph in multiple merged fonts: we search for the FIRST font source + which contains the desired glyph. Because the user doesn't need to provide glyph ranges + any more, it is possible that a glyph that you expected to fetch from a secondary/merged + icon font may be erroneously fetched from the primary font. + - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source: // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; ImFontConfig cfg1; diff --git a/docs/FONTS.md b/docs/FONTS.md index f8431507c..ce08f176d 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -387,7 +387,7 @@ io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg); ## Using Custom Glyph Ranges -🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is necessary, so this is not needed.** +🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary. Therefore this is not really useful any more.** :rewind: You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. ```cpp diff --git a/imgui.cpp b/imgui.cpp index acdbf33e4..8aaa901fc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -416,9 +416,12 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site. - Kept inline single parameter function. Will obsolete. - Fonts: **IMPORTANT** on Font Merging: - - When searching for a glyph in multiple merged fonts: font inputs are now scanned in orderfor the first font input which the desired glyph. This is technically a different behavior than before! - - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1. After the update and when using a new backend, those glyphs may now loaded from Font Source 1! - - You can use `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to ignore in given Input: + - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph. + Because the user doesn't need to provide glyph ranges any more, it is possible that a glyph that you expected to fetch from a secondary/merged icon font may be erroneously fetched from the primary font. + - When searching for a glyph in multiple merged fonts: we now search for the FIRST font source which contains the desired glyph. This is technically a different behavior than before! + - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1. + After the update and when using a new backend, those glyphs may now loaded from Font Source 1! + - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source: // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; ImFontConfig cfg1; From d99ab9f90355adb3197f81eef9060b44d1076ae0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 28 Jun 2025 17:15:18 +0200 Subject: [PATCH 1147/2359] Backends: SDL2: undef Status for X11. (#8751) --- backends/imgui_impl_sdl2.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 9f5e0374a..18035d24f 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -118,6 +118,9 @@ #ifdef __EMSCRIPTEN__ #include #endif +#ifdef Status // X11 headers +#undef Status +#endif #if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 From 8c61ee5498f1761c057f6aa8f87222c11b4c8eff Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 29 Jun 2025 18:05:28 +0200 Subject: [PATCH 1148/2359] Tables: fixed comments about DisableDefaultContextMenu. (#8746) --- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index eeee93778..22fbef4f2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2982,7 +2982,7 @@ struct IMGUI_API ImGuiTable bool IsSortSpecsDirty; bool IsUsingHeaders; // Set when the first row had the ImGuiTableRowFlags_Headers flag. bool IsContextPopupOpen; // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted). - bool DisableDefaultContextMenu; // Disable default context menu contents. You may submit your own using TableBeginContextMenuPopup()/EndPopup() + bool DisableDefaultContextMenu; // Disable default context menu. You may submit your own using TableBeginContextMenuPopup()/EndPopup() bool IsSettingsRequestLoad; bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data. bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f6d516521..069c72995 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1251,7 +1251,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // [Part 11] Default context menu // - To append to this menu: you can call TableBeginContextMenuPopup()/.../EndPopup(). - // - To modify or replace this: set table->IsContextPopupNoDefaultContents = true, then call TableBeginContextMenuPopup()/.../EndPopup(). + // - To modify or replace this: set table->DisableDefaultContextMenu = true, then call TableBeginContextMenuPopup()/.../EndPopup(). // - You may call TableDrawDefaultContextMenu() with selected flags to display specific sections of the default menu, // e.g. TableDrawDefaultContextMenu(table, table->Flags & ~ImGuiTableFlags_Hideable) will display everything EXCEPT columns visibility options. if (table->DisableDefaultContextMenu == false && TableBeginContextMenuPopup(table)) From 8ccfdf7ba05b74b9d80d8fad728c5510c5634c2c Mon Sep 17 00:00:00 2001 From: Aidan Sun Date: Sun, 29 Jun 2025 17:32:48 -0400 Subject: [PATCH 1149/2359] CI: Fixed dllimport/dllexport tests. (#8757) --- .github/workflows/build.yml | 20 ++++++-------------- docs/CHANGELOG.txt | 1 + 2 files changed, 7 insertions(+), 14 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 86872d21c..bc58e25bb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -51,15 +51,11 @@ jobs: - name: Build example_null (mingw 64-bit, as DLL) shell: bash run: | - echo '#ifdef _EXPORT' > example_single_file.cpp - echo '# define IMGUI_API __declspec(dllexport)' >> example_single_file.cpp - echo '#else' >> example_single_file.cpp - echo '# define IMGUI_API __declspec(dllimport)' >> example_single_file.cpp - echo '#endif' >> example_single_file.cpp + echo '#define IMGUI_API __declspec(dllexport)' > example_single_file.cpp echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -D_EXPORT -shared -o libimgui.dll -Wl,--out-implib,libimgui.a example_single_file.cpp -limm32 - g++ -I. -Wall -Wformat -o example_null.exe examples/example_null/main.cpp -L. -limgui + g++ -I. -Wall -Wformat -shared -o libimgui.dll -Wl,--out-implib,libimgui.a example_single_file.cpp -limm32 + g++ -I. -Wall -Wformat -DIMGUI_API='__declspec(dllimport)' -o example_null.exe examples/example_null/main.cpp -L. -limgui rm -f example_null.exe libimgui.* example_single_file.* - name: Build example_null (extra warnings, msvc 64-bit) @@ -99,16 +95,12 @@ jobs: run: | call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" - echo #ifdef _EXPORT > example_single_file.cpp - echo # define IMGUI_API __declspec(dllexport) >> example_single_file.cpp - echo #else >> example_single_file.cpp - echo # define IMGUI_API __declspec(dllimport) >> example_single_file.cpp - echo #endif >> example_single_file.cpp + echo #define IMGUI_API __declspec(dllexport) > example_single_file.cpp echo #define IMGUI_IMPLEMENTATION >> example_single_file.cpp echo #include "misc/single_file/imgui_single_file.h" >> example_single_file.cpp - cl.exe /D_USRDLL /D_WINDLL /D_EXPORT /I. example_single_file.cpp /LD /FeImGui.dll /link - cl.exe /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp + cl.exe /D_USRDLL /D_WINDLL /I. example_single_file.cpp /LD /FeImGui.dll /link + cl.exe /DIMGUI_API=__declspec(dllimport) /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp - name: Build Win32 example_glfw_opengl2 shell: cmd diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b548fb657..216b61524 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,7 @@ Other changes: - Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value: ImTextureData() was incorrectly cleared with zeroes. (#8745) [@rachit7645] - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] +- CI: Fixed dllimport/dllexport tests. (#8757) [@AidanSun05] - Backends: SDL3: avoid calling SDL_StartTextInput() again if already active. (#8727) [@morrazzzz] - Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress From b7e5d76c7928d66ace9116a9f180153a7c260b59 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 30 Jun 2025 20:01:02 +0200 Subject: [PATCH 1150/2359] Fonts: added ImFontAtlas::SetFontLoader() to dynamically change font loader at runtime without using internal API. (#8752, #8465) --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 7 ++++--- imgui.h | 5 +++-- imgui_draw.cpp | 9 +++++++-- misc/freetype/imgui_freetype.h | 6 +++--- 5 files changed, 20 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 216b61524..0b9d1d9a1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking changes: Other changes: +- Fonts: added ImFontAtlas::SetFontLoader() to dynamically change font + loader at runtime without using internal API. (#8752, #8465) - Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value: ImTextureData() was incorrectly cleared with zeroes. (#8745) [@rachit7645] - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] @@ -211,7 +213,7 @@ Breaking changes: - renamed/reworked ImFontBuilderIO into ImFontLoader, - renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader() - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() - - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader(); + - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader() - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). - Fonts: (users of custom rectangles) - Renamed AddCustomRectRegular() to AddCustomRect(). (#8466) diff --git a/imgui.cpp b/imgui.cpp index 8aaa901fc..ddc20991e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -453,7 +453,8 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags. If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader(). - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() - - new: io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader() + - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader() + - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1] - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV(). - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h. - old: @@ -15902,7 +15903,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) #ifdef IMGUI_ENABLE_STB_TRUETYPE const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype(); if (RadioButton("stb_truetype", loader_current == loader_stbtruetype)) - ImFontAtlasBuildSetupFontLoader(atlas, loader_stbtruetype); + atlas->SetFontLoader(loader_stbtruetype); #else BeginDisabled(); RadioButton("stb_truetype", false); @@ -15913,7 +15914,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) #ifdef IMGUI_ENABLE_FREETYPE const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader(); if (RadioButton("FreeType", loader_current == loader_freetype)) - ImFontAtlasBuildSetupFontLoader(atlas, loader_freetype); + atlas->SetFontLoader(loader_freetype); if (loader_current == loader_freetype) { unsigned int loader_flags = atlas->FontLoaderFlags; diff --git a/imgui.h b/imgui.h index b09d7ee82..153ce5cad 100644 --- a/imgui.h +++ b/imgui.h @@ -3493,7 +3493,7 @@ struct ImFontConfig // [Internal] ImFontFlags Flags; // Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) ImFont* DstFont; // Target font (as we merging fonts, multiple ImFontConfig may target the same font) - const ImFontLoader* FontLoader; // Custom font backend for this source (other use one stored in ImFontAtlas) + const ImFontLoader* FontLoader; // Custom font backend for this source (default source is the one stored in ImFontAtlas) void* FontLoaderData; // Font loader opaque storage (per font config) IMGUI_API ImFontConfig(); @@ -3590,6 +3590,7 @@ struct ImFontAtlas IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) IMGUI_API void CompactCache(); // Compact cached glyphs and texture. + IMGUI_API void SetFontLoader(const ImFontLoader* font_loader); // Change font loader at runtime. // As we are transitioning toward a new font system, we expect to obsolete those soon: 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. @@ -3698,7 +3699,7 @@ struct ImFontAtlas int FontNextUniqueID; // Next value to be stored in ImFont->FontID ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. - const ImFontLoader* FontLoader; // Font loader opaque interface (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). Don't set directly! + const ImFontLoader* FontLoader; // Font loader opaque interface (default to use FreeType when IMGUI_ENABLE_FREETYPE is defined, otherwise default to use stb_truetype). Use SetFontLoader() to change this at runtime. const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name void* FontLoaderData; // Font backend opaque storage unsigned int FontLoaderFlags; // Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig). diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e835dcd75..704cc6d2f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2659,6 +2659,11 @@ void ImFontAtlas::CompactCache() ImFontAtlasTextureCompact(this); } +void ImFontAtlas::SetFontLoader(const ImFontLoader* font_loader) +{ + ImFontAtlasBuildSetupFontLoader(this, font_loader); +} + void ImFontAtlas::ClearInputData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); @@ -4178,9 +4183,9 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (atlas->FontLoader == NULL) { #ifdef IMGUI_ENABLE_FREETYPE - ImFontAtlasBuildSetupFontLoader(atlas, ImGuiFreeType::GetFontLoader()); + atlas->SetFontLoader(ImGuiFreeType::GetFontLoader()); #elif defined(IMGUI_ENABLE_STB_TRUETYPE) - ImFontAtlasBuildSetupFontLoader(atlas, ImFontAtlasGetFontLoaderForStbTruetype()); + atlas->SetFontLoader(ImFontAtlasGetFontLoaderForStbTruetype()); #else IM_ASSERT(0); // Invalid Build function #endif diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index 4f7306790..85313699d 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -8,7 +8,7 @@ // Usage: // - Add '#define IMGUI_ENABLE_FREETYPE' in your imconfig to automatically enable support // for imgui_freetype in imgui. It is equivalent to selecting the default loader with: -// io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader() +// io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) // Optional support for OpenType SVG fonts: // - Add '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG' to use plutosvg (not provided). See #7927. @@ -62,7 +62,7 @@ namespace ImGuiFreeType { // This is automatically assigned when using '#define IMGUI_ENABLE_FREETYPE'. // If you need to dynamically select between multiple builders: - // - you can manually assign this builder with 'atlas->FontLoader = ImGuiFreeType::GetFontLoader()' + // - you can manually assign this builder with 'atlas->SetFontLoader(ImGuiFreeType::GetFontLoader())' // - prefer deep-copying this into your own ImFontLoader instance if you use hot-reloading that messes up static data. IMGUI_API const ImFontLoader* GetFontLoader(); @@ -75,7 +75,7 @@ namespace ImGuiFreeType // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - //IMGUI_API const ImFontBuilderIO* GetBuilderForFreeType(); // Renamed/changed in 1.92. Change 'io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()' to 'io.Fonts.FontLoader = ImGuiFreeType::GetFontLoader()' if you need runtime selection. + //IMGUI_API const ImFontBuilderIO* GetBuilderForFreeType(); // Renamed/changed in 1.92. Change 'io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()' to 'io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader())' if you need runtime selection. //static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontLoaderFlags = flags; return atlas->Build(); } // Prefer using '#define IMGUI_ENABLE_FREETYPE' #endif } From 51b3495ad8f7f4a3a4341bf0f9da87fd092a4efd Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 30 Jun 2025 20:59:08 +0200 Subject: [PATCH 1151/2359] Fonts: set a maximum font size of 512.0f at ImGui:: API level to reduce edge cases. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 6 +++--- imgui_demo.cpp | 2 +- imgui_internal.h | 2 ++ 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0b9d1d9a1..99246de8f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,9 @@ Other changes: - Fonts: added ImFontAtlas::SetFontLoader() to dynamically change font loader at runtime without using internal API. (#8752, #8465) +- Fonts: set a maximum font size of 512.0f at ImGui:: API level to reduce + edge cases (e.g. out of memory errors). ImDrawList:: API doesn't have the + constraint. (#8758) - Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value: ImTextureData() was incorrectly cleared with zeroes. (#8745) [@rachit7645] - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] diff --git a/imgui.cpp b/imgui.cpp index ddc20991e..f34ad7969 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8824,7 +8824,7 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. // - We may support it better later and remove this rounding. final_size = GetRoundedFontSize(final_size); - final_size = ImMax(1.0f, final_size); + final_size = ImClamp(final_size, 1.0f, IMGUI_FONT_SIZE_MAX); if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity; g.FontSize = final_size; @@ -15871,9 +15871,9 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later."); - DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 5.0f); + DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); //BeginDisabled(io.ConfigDpiScaleFonts); - DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 5.0f); + DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f); //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); //EndDisabled(); if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 692eb2992..05f5e45f1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8282,7 +8282,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); //BeginDisabled(GetIO().ConfigDpiScaleFonts); - DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 5.0f); + DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f); //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); //EndDisabled(); diff --git a/imgui_internal.h b/imgui_internal.h index 22fbef4f2..7ac0c2079 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3711,6 +3711,8 @@ typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- +#define IMGUI_FONT_SIZE_MAX (512.0f) + // Helpers: ImTextureRef ==/!= operators provided as convenience // (note that _TexID and _TexData are never set simultaneously) inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } From fd75bdccb033e74afeba44f500edc8fcef7eb023 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 30 Jun 2025 21:16:20 +0200 Subject: [PATCH 1152/2359] Fonts: for large size fonts, layout/size calculation only load glyphs metrics. Actual glyphs are renderer+packed when used by drawing functions. (#8758, #8465) (Breaking) breaks signature of ImFontLoader::FontBakedLoadGlyph, sorry. --- docs/CHANGELOG.txt | 2 + imgui_draw.cpp | 90 ++++++++++++++++++++++++++------ imgui_internal.h | 6 ++- misc/freetype/imgui_freetype.cpp | 18 +++++-- 4 files changed, 93 insertions(+), 23 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 99246de8f..625a5b927 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,8 @@ Other changes: - Fonts: added ImFontAtlas::SetFontLoader() to dynamically change font loader at runtime without using internal API. (#8752, #8465) +- Fonts: for large size fonts, layout/size calculation only load glyphs metrics. + Actual glyphs are renderer+packed when used by drawing functions. (#8758, #8465) - Fonts: set a maximum font size of 512.0f at ImGui:: API level to reduce edge cases (e.g. out of memory errors). ImDrawList:: API doesn't have the constraint. (#8758) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 704cc6d2f..374088573 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2560,6 +2560,7 @@ void ImTextureData::DestroyPixels() //----------------------------------------------------------------------------- // - ImFontBaked_BuildGrowIndex() // - ImFontBaked_BuildLoadGlyph() +// - ImFontBaked_BuildLoadGlyphAdvanceX() // - ImFontAtlasDebugLogTextureRequests() //----------------------------------------------------------------------------- // - ImFontAtlasGetFontLoaderForStbTruetype() @@ -4409,7 +4410,7 @@ static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, *c = (ImWchar)font->RemapPairs.GetInt((ImGuiID)*c, (int)*c); } -static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint) +static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint, float* only_load_advance_x) { ImFont* font = baked->ContainerFont; ImFontAtlas* atlas = font->ContainerAtlas; @@ -4442,13 +4443,25 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) { - ImFontGlyph glyph_buf; - if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf)) + if (only_load_advance_x == NULL) { - // FIXME: Add hooks for e.g. #7962 - glyph_buf.Codepoint = src_codepoint; - glyph_buf.SourceIdx = src_n; - return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); + ImFontGlyph glyph_buf; + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf, NULL)) + { + // FIXME: Add hooks for e.g. #7962 + glyph_buf.Codepoint = src_codepoint; + glyph_buf.SourceIdx = src_n; + return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); + } + } + else + { + // Special mode but only loading glyphs metrics. Will rasterize and pack later. + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, NULL, only_load_advance_x)) + { + ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x); + return NULL; + } } } loader_user_data_p += loader->FontBakedSrcLoaderDataSize; @@ -4468,12 +4481,27 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep return NULL; } +static float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint) +{ + if (baked->Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE) + { + // First load AdvanceX value used by CalcTextSize() API then load the rest when loaded by drawing API. + float only_advance_x = 0.0f; + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint, &only_advance_x); + return glyph ? glyph->AdvanceX : only_advance_x; + } + else + { + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint, NULL); + return glyph ? glyph->AdvanceX : baked->FallbackAdvanceX; + } +} + // The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b IM_MSVC_RUNTIME_CHECKS_OFF static float BuildLoadGlyphGetAdvanceOrFallback(ImFontBaked* baked, unsigned int codepoint) { - ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint); - return glyph ? glyph->AdvanceX : baked->FallbackAdvanceX; + return ImFontBaked_BuildLoadGlyphAdvanceX(baked, (ImWchar)codepoint); } IM_MSVC_RUNTIME_CHECKS_RESTORE @@ -4594,7 +4622,7 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig return true; } -static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph) +static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) { // Search for first font which has the glyph ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; @@ -4616,7 +4644,14 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC int advance, lsb; stbtt_GetGlyphBitmapBoxSubpixel(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0, &x0, &y0, &x1, &y1); stbtt_GetGlyphHMetrics(&bd_font_data->FontInfo, glyph_index, &advance, &lsb); - const bool is_visible = (x0 != x1 && y0 != y1); + + // Load metrics only mode + if (out_advance_x != NULL) + { + IM_ASSERT(out_glyph == NULL); + *out_advance_x = advance * scale_for_layout; + return true; + } // Prepare glyph out_glyph->Codepoint = codepoint; @@ -4624,6 +4659,7 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC // Pack and retrieve position inside texture atlas // (generally based on stbtt_PackFontRangesRenderIntoRects) + const bool is_visible = (x0 != x1 && y0 != y1); if (is_visible) { const int w = (x1 - x0 + oversample_h - 1); @@ -5124,6 +5160,29 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked return glyph; } +// FIXME: Code is duplicated with code above. +void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x) +{ + IM_UNUSED(atlas); + if (src != NULL) + { + // Clamp & recenter if needed + const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; + advance_x = ImClamp(advance_x, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); + + // Snap to pixel + if (src->PixelSnapH) + advance_x = IM_ROUND(advance_x); + + // Bake spacing + advance_x += src->GlyphExtraAdvanceX; + } + + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); + baked->IndexAdvanceX[codepoint] = advance_x; +} + // Copy to texture, post-process and queue update for backend void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch) { @@ -5151,7 +5210,7 @@ ImFontGlyph* ImFontBaked::FindGlyph(ImWchar c) if (i != IM_FONTGLYPH_INDEX_UNUSED) return &Glyphs.Data[i]; } - ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c); + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL); return glyph ? glyph : &Glyphs.Data[FallbackGlyphIndex]; } @@ -5167,7 +5226,7 @@ ImFontGlyph* ImFontBaked::FindGlyphNoFallback(ImWchar c) return &Glyphs.Data[i]; } LockLoadingFallback = true; // This is actually a rare call, not done in hot-loop, so we prioritize not adding extra cruft to ImFontBaked_BuildLoadGlyph() call sites. - ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c); + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL); LockLoadingFallback = false; return glyph; } @@ -5210,10 +5269,7 @@ float ImFontBaked::GetCharAdvance(ImWchar c) if (x >= 0.0f) return x; } - - // Same as BuildLoadGlyphGetAdvanceOrFallback(): - const ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c); - return glyph ? glyph->AdvanceX : FallbackAdvanceX; + return ImFontBaked_BuildLoadGlyphAdvanceX(this, c); } IM_MSVC_RUNTIME_CHECKS_RESTORE diff --git a/imgui_internal.h b/imgui_internal.h index 7ac0c2079..12fdac568 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3691,7 +3691,7 @@ struct ImFontLoader bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); - bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph); + bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x); // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. // FIXME: At this point the two other types of buffers may be managed by core to be consistent? @@ -3711,7 +3711,8 @@ typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- -#define IMGUI_FONT_SIZE_MAX (512.0f) +#define IMGUI_FONT_SIZE_MAX (512.0f) +#define IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE (128.0f) // Helpers: ImTextureRef ==/!= operators provided as convenience // (note that _TexID and _TexData are never set simultaneously) @@ -3829,6 +3830,7 @@ IMGUI_API ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, IMGUI_API ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id); IMGUI_API void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); +IMGUI_API void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x); IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index e5f2818db..33f259365 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -475,7 +475,7 @@ void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() } -bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph) +bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) { ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); @@ -494,9 +494,20 @@ bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src if (metrics == nullptr) return false; - // Render glyph into a bitmap (currently held by FreeType) FT_Face face = bd_font_data->FtFace; FT_GlyphSlot slot = face->glyph; + const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; + + // Load metrics only mode + const float advance_x = (slot->advance.x / FT_SCALEFACTOR) / rasterizer_density; + if (out_advance_x != NULL) + { + IM_ASSERT(out_glyph == NULL); + *out_advance_x = advance_x; + return true; + } + + // Render glyph into a bitmap (currently held by FreeType) FT_Render_Mode render_mode = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Monochrome) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL; FT_Error error = FT_Render_Glyph(slot, render_mode); const FT_Bitmap* ft_bitmap = &slot->bitmap; @@ -506,11 +517,10 @@ bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src const int w = (int)ft_bitmap->width; const int h = (int)ft_bitmap->rows; const bool is_visible = (w != 0 && h != 0); - const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; // Prepare glyph out_glyph->Codepoint = codepoint; - out_glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) / rasterizer_density; + out_glyph->AdvanceX = advance_x; // Pack and retrieve position inside texture atlas if (is_visible) From 0448428322780d34599e30e5267b4a063374d691 Mon Sep 17 00:00:00 2001 From: Matthew Pohlmann Date: Sat, 5 Jul 2025 08:51:58 -0700 Subject: [PATCH 1153/2359] Fonts: Change ImFontConfig::FontNo back to int from S8 (#8775) When used with FreeType this value is passed as `face_index` which needs to be 32-bits. # Conflicts: # docs/CHANGELOG.txt --- docs/CHANGELOG.txt | 4 ++++ imgui.h | 4 ++-- misc/freetype/imgui_freetype.cpp | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 625a5b927..00c66b8d5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,10 @@ Other changes: - Fonts: set a maximum font size of 512.0f at ImGui:: API level to reduce edge cases (e.g. out of memory errors). ImDrawList:: API doesn't have the constraint. (#8758) +- Fonts: Restore ImFontConfig::FontNo being a 32-bits value as this is needed + to pass full range of information into e.g. FreeType's face_index, as higher + bits are used from FreeType 2.6.1. (#8775) [@Valakor] + (the field has been erroneously reduced from 32-bits to 8-bit in 1.92.0) - Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value: ImTextureData() was incorrectly cleared with zeroes. (#8745) [@rachit7645] - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] diff --git a/imgui.h b/imgui.h index 153ce5cad..e605cb676 100644 --- a/imgui.h +++ b/imgui.h @@ -3473,9 +3473,9 @@ struct ImFontConfig bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. bool PixelSnapV; // true // Align Scaled GlyphOffset.y to pixel boundaries. - ImS8 FontNo; // 0 // Index of font within TTF/OTF file ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. + ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). const ImWchar* GlyphRanges; // NULL // *LEGACY* THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a small user-provided list of Unicode ranges (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. @@ -3484,11 +3484,11 @@ struct ImFontConfig float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. // FIXME-NEWATLAS: Intentionally unscaled + ImU32 FontNo; // 0 // Index of font within TTF/OTF file unsigned int FontLoaderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. //unsigned int FontBuilderFlags; // -- // [Renamed in 1.92] Ue FontLoaderFlags. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. float RasterizerDensity; // 1.0f // [LEGACY: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported] DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. - ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. // [Internal] ImFontFlags Flags; // Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 33f259365..7a9468375 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -174,7 +174,7 @@ struct ImGui_ImplFreeType_FontSrcBakedData bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_font_loader_flags) { - FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (uint32_t)src->FontDataSize, (uint32_t)src->FontNo, &FtFace); + FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (FT_Long)src->FontDataSize, (FT_Long)src->FontNo, &FtFace); if (error != 0) return false; error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE); From be6303765425ac3fd3b0ab59b673d90200f87a8f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 10:34:59 +0200 Subject: [PATCH 1154/2359] CI: Updated to use latest Windows image + VS2022. (Untested) --- .github/workflows/build.yml | 10 +++++----- docs/CHANGELOG.txt | 1 + 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bc58e25bb..edf37ef9e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,10 +17,10 @@ on: jobs: Windows: - runs-on: windows-2019 + runs-on: windows-2025 env: - VS_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\ - MSBUILD_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\ + VS_PATH: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\ + MSBUILD_PATH: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\ steps: - uses: actions/checkout@v4 @@ -40,8 +40,8 @@ jobs: run: | # CI workers do not supporter older Visual Studio versions. Fix projects to target newer available version. gci -recurse -filter "*.vcxproj" | ForEach-Object { - (Get-Content $_.FullName) -Replace "v\d{3}","v142" | Set-Content -Path $_.FullName - (Get-Content $_.FullName) -Replace "[\d\.]+","10.0.18362.0" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "v\d{3}","v143" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "[\d\.]+","$(LatestTargetPlatformVersion)" | Set-Content -Path $_.FullName } # Not using matrix here because it would inflate job count too much. Check out and setup is done for every job and that makes build times way too long. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 00c66b8d5..cdb7da4e6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,7 @@ Other changes: ImTextureData() was incorrectly cleared with zeroes. (#8745) [@rachit7645] - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] - CI: Fixed dllimport/dllexport tests. (#8757) [@AidanSun05] +- CI: Updated to use latest Windows image + VS2022. - Backends: SDL3: avoid calling SDL_StartTextInput() again if already active. (#8727) [@morrazzzz] - Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress From 497ebec01dba0d981f99fa4c6a7c43c72e7d8bd1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 10:36:49 +0200 Subject: [PATCH 1155/2359] CI: Fix/amend be63037. --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index edf37ef9e..5efd6f389 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -41,7 +41,7 @@ jobs: # CI workers do not supporter older Visual Studio versions. Fix projects to target newer available version. gci -recurse -filter "*.vcxproj" | ForEach-Object { (Get-Content $_.FullName) -Replace "v\d{3}","v143" | Set-Content -Path $_.FullName - (Get-Content $_.FullName) -Replace "[\d\.]+","$(LatestTargetPlatformVersion)" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "[\d\.]+","\$(LatestTargetPlatformVersion)" | Set-Content -Path $_.FullName } # Not using matrix here because it would inflate job count too much. Check out and setup is done for every job and that makes build times way too long. From 4441aa8b605524bb0806d39a22a251491bc18535 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 10:41:01 +0200 Subject: [PATCH 1156/2359] CI: Fix/amend be63037. --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5efd6f389..21d059913 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -41,7 +41,7 @@ jobs: # CI workers do not supporter older Visual Studio versions. Fix projects to target newer available version. gci -recurse -filter "*.vcxproj" | ForEach-Object { (Get-Content $_.FullName) -Replace "v\d{3}","v143" | Set-Content -Path $_.FullName - (Get-Content $_.FullName) -Replace "[\d\.]+","\$(LatestTargetPlatformVersion)" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "[\d\.]+","\\$(LatestTargetPlatformVersion)" | Set-Content -Path $_.FullName } # Not using matrix here because it would inflate job count too much. Check out and setup is done for every job and that makes build times way too long. From 68971223aa47a5a62dc7ff783c826315276a45dc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 10:42:45 +0200 Subject: [PATCH 1157/2359] CI: Fix/amend be63037. --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 21d059913..95bcf3e76 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -41,7 +41,7 @@ jobs: # CI workers do not supporter older Visual Studio versions. Fix projects to target newer available version. gci -recurse -filter "*.vcxproj" | ForEach-Object { (Get-Content $_.FullName) -Replace "v\d{3}","v143" | Set-Content -Path $_.FullName - (Get-Content $_.FullName) -Replace "[\d\.]+","\\$(LatestTargetPlatformVersion)" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "[\d\.]+",'$(LatestTargetPlatformVersion)' | Set-Content -Path $_.FullName } # Not using matrix here because it would inflate job count too much. Check out and setup is done for every job and that makes build times way too long. From 495d6f1e39acf46b6ee4b1d6d16912940d1a8d58 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 14:51:42 +0200 Subject: [PATCH 1158/2359] Undef 'Status' in main header file. (#8751, #8765) --- backends/imgui_impl_sdl2.cpp | 4 +--- backends/imgui_impl_vulkan.cpp | 1 + imgui.h | 2 ++ 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 18035d24f..4dc2dea6e 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -118,9 +118,7 @@ #ifdef __EMSCRIPTEN__ #include #endif -#ifdef Status // X11 headers -#undef Status -#endif +#undef Status // X11 headers are leaking this. #if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 059e8c9ed..52ad716b7 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -97,6 +97,7 @@ #ifndef IM_MAX #define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) #endif +#undef Status // X11 headers are leaking this. // Visual Studio warnings #ifdef _MSC_VER diff --git a/imgui.h b/imgui.h index e605cb676..0833e1c82 100644 --- a/imgui.h +++ b/imgui.h @@ -3385,6 +3385,8 @@ struct ImDrawData // FOR ALL OTHER ImTextureXXXX TYPES: ONLY CORE LIBRARY AND RENDERER BACKENDS NEED TO KNOW AND CARE ABOUT THEM. //----------------------------------------------------------------------------- +#undef Status // X11 headers are leaking this. + // We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension. // Most standard backends only support RGBA32 but we provide a single channel option for low-resource/embedded systems. enum ImTextureFormat From 94c888ebda6f0123dbf89b27f109298d0818d757 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 15:27:47 +0200 Subject: [PATCH 1159/2359] Docs: update 1.92.0 changelogs to cover more internal fields. (#8764) --- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 2 ++ 2 files changed, 8 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cdb7da4e6..d53af355d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -196,6 +196,7 @@ Breaking changes: While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef. + - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef. - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[]. - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. - Each ImFont has a number of ImFontBaked instances corresponding to actively used @@ -213,6 +214,11 @@ Breaking changes: g.Font == ImGui::GetFont() g.FontSize == ImGui::GetFontSize() g.FontBaked == ImGui::GetFontBaked() == ImGui::GetFont()->GetFontBaked(ImGui::GetFontSize()) + - Fields moved from ImFontAtlas to ImTextureData + - ImFontAtlas->TexWidth -> ImFontAtlas->TexData->Width + - ImFontAtlas->TexHeight -> ImFontAtlas->TexData->Height + - ImFontAtlas->TexPixelsAlpha8 -> ImFontAtlas->TexData->GetPixels() (when ImFontAtlas::TexDesiredFormat == ImTextureFormat_Alpha8) + - ImFontAtlas->TexPixelsRGBA32 -> ImFontAtlas->TexData->GetPixels() (when ImFontAtlas::TexDesiredFormat == ImTextureFormat_RGBA32) Please report if you are affected! - Fonts: (users of imgui_freetype) - renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. diff --git a/imgui.cpp b/imgui.cpp index f34ad7969..0a8582686 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -445,10 +445,12 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - Fonts: obsoleted ImFont::Scale which is not useful anymore. - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef. + - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef. - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[] - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size. - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance(). + - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels(). - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to access font data for current font at current font size (and you may use font->GetFontBaked(size) to access it for any other size.) - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags. If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader(). From 57a93e1a19892ae194351766b59b0992ba55c7e5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 15:36:24 +0200 Subject: [PATCH 1160/2359] Backends: Allegro5: fixed texture update broken on some platforms where ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten. (#8770) --- backends/imgui_impl_allegro5.cpp | 11 +++++------ docs/CHANGELOG.txt | 2 ++ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index bd7f10c64..5cbb89365 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-07-07: Fixed texture update broken on some platforms where ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture(). // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-01-06: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256). @@ -291,14 +292,12 @@ void ImGui_ImplAllegro5_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. - ImTextureRect r_bb = tex->UpdateRect; // Bounding box encompassing all individual updates + ImTextureRect r = tex->UpdateRect; // Bounding box encompassing all individual updates ALLEGRO_BITMAP* gpu_bitmap = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID; - ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap_region(gpu_bitmap, r_bb.x, r_bb.y, r_bb.w, r_bb.h, al_get_bitmap_format(gpu_bitmap), ALLEGRO_LOCK_WRITEONLY); + ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap_region(gpu_bitmap, r.x, r.y, r.w, r.h, al_get_bitmap_format(gpu_bitmap), ALLEGRO_LOCK_WRITEONLY); IM_ASSERT(locked_region && "Backend failed to update texture!"); - for (ImTextureRect& r : tex->Updates) - for (int y = 0; y < r.h; y++) - memcpy((unsigned char*)locked_region->data + locked_region->pitch * (r.y - r_bb.y + y) + (r.x - r_bb.x) * tex->BytesPerPixel, // dst - tex->GetPixelsAt(r.x, r.y + y), r.w * tex->BytesPerPixel); // src, block pitch + for (int y = 0; y < r.h; y++) + memcpy((unsigned char*)locked_region->data + locked_region->pitch * y, tex->GetPixelsAt(r.x, r.y + y), r.w * tex->BytesPerPixel); // dst, src, block pitch al_unlock_bitmap(gpu_bitmap); tex->SetStatus(ImTextureStatus_OK); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d53af355d..6e9c71f8d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,6 +63,8 @@ Other changes: (#8727) [@morrazzzz] - Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. (#8739) [@cfillion] +- Backends: Allegro5: fixed texture update broken on some platforms where + ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten. (#8770) - Backends: Vulkan: use nonCoherentAtomSize to align upload_size, fixing validation error on some setups. (#8743, #8744) [@tquante] From 4ef11452416b1b99179b2d3076ef451484de078e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 16:50:50 +0200 Subject: [PATCH 1161/2359] Fonts: fixed dynamically changing font loader from losing Fallback and Ellipsis glyphs. (#8763) Only the call to ImFontAtlasBuildSetupFontLoader() is the notable change. The change in ImFontAtlasFontInitOutput() is merely to use an existing helper function. --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 8 ++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6e9c71f8d..0cf39ca51 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,8 @@ Other changes: - Fonts: added ImFontAtlas::SetFontLoader() to dynamically change font loader at runtime without using internal API. (#8752, #8465) +- Fonts: fixed a bug where dynamically changing font loader would lose + the Fallback and Ellipsis glyphs under some circumstance. (#8763) - Fonts: for large size fonts, layout/size calculation only load glyphs metrics. Actual glyphs are renderer+packed when used by drawing functions. (#8758, #8465) - Fonts: set a maximum font size of 512.0f at ImGui:: API level to reduce diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 374088573..bce905420 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3410,6 +3410,9 @@ void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* fon atlas->FontLoader->LoaderInit(atlas); for (ImFont* font : atlas->Fonts) ImFontAtlasFontInitOutput(atlas, font); + for (ImFont* font : atlas->Fonts) + for (ImFontConfig* src : font->Sources) + ImFontAtlasFontSourceAddToFont(atlas, font, src); } // Preload all glyph ranges for legacy backends. @@ -3576,11 +3579,8 @@ bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font) { bool ret = true; for (ImFontConfig* src : font->Sources) - { - const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - if (loader && loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src)) + if (!ImFontAtlasFontSourceInit(atlas, src)) ret = false; - } IM_ASSERT(ret); // Unclear how to react to this meaningfully. Assume that result will be same as initial AddFont() call. return ret; } From c2d9b075339346881b92c3ddb614f9305e93194b Mon Sep 17 00:00:00 2001 From: Moses Miller Date: Fri, 4 Jul 2025 02:33:55 -0700 Subject: [PATCH 1162/2359] Backends: Vulkan: fixed texture synchronization. (#8772) --- backends/imgui_impl_vulkan.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 52ad716b7..38eaabe90 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-07-07: Vulkan: Fixed texture synchronization issue introduced on 2025-06-11. (#8772) // 2025-06-27: Vulkan: Fixed validation errors during texture upload/update by aligning upload size to 'nonCoherentAtomSize'. (#8743, #8744) // 2025-06-11: Vulkan: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_DestroyFontsTexture(). // 2025-05-07: Vulkan: Fixed validation errors during window detach in multi-viewport mode. (#8600, #8176) @@ -808,6 +809,7 @@ void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) { VkImageMemoryBarrier copy_barrier[1] = {}; copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + copy_barrier[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; @@ -817,7 +819,7 @@ void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_barrier[0].subresourceRange.levelCount = 1; copy_barrier[0].subresourceRange.layerCount = 1; - vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); + vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); VkBufferImageCopy region = {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; From 032e1397d9e728106e6e03e819419e29370b2106 Mon Sep 17 00:00:00 2001 From: Moses Miller Date: Fri, 4 Jul 2025 03:21:54 -0700 Subject: [PATCH 1163/2359] Backends: Vulkan: use separate barrier for buffer. (#8772) --- backends/imgui_impl_vulkan.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 38eaabe90..a5dd75c8e 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -807,9 +807,18 @@ void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) // Copy to Image: { + VkBufferMemoryBarrier upload_barrier[1] = {}; + upload_barrier[0].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + upload_barrier[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + upload_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + upload_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + upload_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + upload_barrier[0].buffer = upload_buffer; + upload_barrier[0].offset = 0; + upload_barrier[0].size = upload_size; + VkImageMemoryBarrier copy_barrier[1] = {}; copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - copy_barrier[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; @@ -819,7 +828,7 @@ void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_barrier[0].subresourceRange.levelCount = 1; copy_barrier[0].subresourceRange.layerCount = 1; - vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); + vkCmdPipelineBarrier(bd->TexCommandBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, upload_barrier, 1, copy_barrier); VkBufferImageCopy region = {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; From c0d02e5ae42d26dbe9b31f76233f1c96c3407162 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 7 Jul 2025 17:02:07 +0200 Subject: [PATCH 1164/2359] Backends: Vulkan: forgot to update Changelog. (#8772) --- docs/CHANGELOG.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0cf39ca51..b70e47a73 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,8 @@ Other changes: ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten. (#8770) - Backends: Vulkan: use nonCoherentAtomSize to align upload_size, fixing validation error on some setups. (#8743, #8744) [@tquante] +- Backends: Vulkan: fixed texture synchronization issue introduced in 1.92.0, + leading to validation layers reacting. (#8772) [@Majora320] ----------------------------------------------------------------------- From 7c51c0e3de2b04216b9562f5e5d55de943650388 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 8 Jul 2025 11:58:50 +0200 Subject: [PATCH 1165/2359] Docs: misc update. (#8727, #8764) --- docs/BACKENDS.md | 2 ++ docs/CHANGELOG.txt | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index ae5e91b0e..fa05d55ea 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -298,6 +298,8 @@ Version [1.92.0](https://github.com/ocornut/imgui/releases/tag/v1.92.0) (June 20 **In order to move forward and take advantage of all new features, support for `ImGuiBackendFlags_RendererHasTextures` will likely be REQUIRED for all backends before June 2026.** +`ImFontAtlas` functions such as `Build()`, `GetTexDataAsRGBA32()`, `GetTexDataAsAlpha8()`, `SetTexID()`, `IsBuilt()` were obsoleted in favor if iterating a `Textures[]` array and updating their state when requested by Dear ImGui. + **TD;DR: List of commits which added support for `ImGuiBackendFlags_RendererHasTextures` in standard backends:** - Allegro5: [ee8941e](https://github.com/ocornut/imgui/commit/ee8941e) (+35 lines) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b70e47a73..0a3523621 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,7 +62,8 @@ Other changes: - CI: Fixed dllimport/dllexport tests. (#8757) [@AidanSun05] - CI: Updated to use latest Windows image + VS2022. - Backends: SDL3: avoid calling SDL_StartTextInput() again if already active. - (#8727) [@morrazzzz] + (fixes e.g.: an issue on iOS where the keyboard animation will popup every + time the user types a key + probably other things) (#8727) [@morrazzzz] - Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. (#8739) [@cfillion] - Backends: Allegro5: fixed texture update broken on some platforms where @@ -168,6 +169,8 @@ Breaking changes: and IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete). - A majority of old backends should still work with new code (behaving like they did before). + - For instructions to upgrade your custom backend: + https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md - Calling ImFontAtlas::Build() before initializing new backends will erroneously trigger preloading all glyphs. Will be detected with an assertion after the backend is initialized. - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) From 18dca11dd0428dc1de424bc5b71a4cecaf1d889f Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Fri, 27 Jun 2025 13:40:48 +0200 Subject: [PATCH 1166/2359] Backends: GLFW, SDL2: ImplXXX_GetContentScaleXXX() helpers return 1.0f on emscripten / apple / android (#8742, #8733) We can divide platforms into two cases based on how they report screen geometry: - Case 1: Platforms which report screen size in "physical pixels": Windows (for "Dpi aware" apps), Linux (with Wayland) - Case 2: Platforms which report screen size in "density-independent pixels": macOS, iOS, Android, emscripten As a consequence, there are two important things we need to know: - FramebufferScale: The scaling factor FrameBufferSize / ScreenSize - In case 1, the framebuffer size is equal to the screen size and DisplayFramebufferScale=1. - In case 2, the framebuffer size is equal to the screen size multiplied by a factor, for example DisplayFramebufferScale=2. - ContentScale The scaling factor for the content that we will display - In case 1, the content scale will often need to be > 1 (e.g., 2), because we will need to display bigger elements so that they show with a correct physical size on the screen. - In case 2, the content scale is equal to 1 This commit fixes ContentScale for platforms in case 2. --- backends/imgui_impl_glfw.cpp | 5 +++-- backends/imgui_impl_sdl2.cpp | 3 ++- docs/CHANGELOG.txt | 3 +++ imgui.h | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index d0a75ac78..98e07ce5c 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-07-08: Made ImGui_ImplGlfw_GetContentScaleForWindow(), ImGui_ImplGlfw_GetContentScaleForMonitor() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) // 2025-06-18: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069) // 2025-06-11: Added ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) and ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) helper to facilitate making DPI-aware apps. // 2025-03-10: Map GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 into ImGuiKey_Oem102. @@ -876,7 +877,7 @@ static void ImGui_ImplGlfw_UpdateGamepads() // - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle. float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) { -#if GLFW_HAS_PER_MONITOR_DPI && !defined(__APPLE__) +#if GLFW_HAS_PER_MONITOR_DPI && !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(__ANDROID__)) float x_scale, y_scale; glfwGetWindowContentScale(window, &x_scale, &y_scale); return x_scale; @@ -888,7 +889,7 @@ float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) { -#if GLFW_HAS_PER_MONITOR_DPI && !defined(__APPLE__) +#if GLFW_HAS_PER_MONITOR_DPI && !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(__ANDROID__)) float x_scale, y_scale; glfwGetMonitorContentScale(monitor, &x_scale, &y_scale); return x_scale; diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 4dc2dea6e..291edb811 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-07-08: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) // 2025-06-11: Added ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) and ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) helper to facilitate making DPI-aware apps. // 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. @@ -719,7 +720,7 @@ float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) { #if SDL_HAS_PER_MONITOR_DPI -#ifndef __APPLE__ +#if !defined(__APPLE__) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) float dpi = 0.0f; if (SDL_GetDisplayDPI(display_index, &dpi, nullptr, nullptr) == 0) return dpi / 96.0f; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0a3523621..d412df107 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,9 @@ Other changes: - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] - CI: Fixed dllimport/dllexport tests. (#8757) [@AidanSun05] - CI: Updated to use latest Windows image + VS2022. +- Backends: GLFW, SDL2 made ImGui_ImplGLFW_GetContentScaleXXX() and + ImGui_ImplSDL2_GetContentScaleXXXX() helpers return 1.0f on Emscripten + and Android platforms, matching macOS logic. (#8742, #8733) [@pthom] - Backends: SDL3: avoid calling SDL_StartTextInput() again if already active. (fixes e.g.: an issue on iOS where the keyboard animation will popup every time the user types a key + probably other things) (#8727) [@morrazzzz] diff --git a/imgui.h b/imgui.h index 0833e1c82..89c2c2e5d 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.1 WIP" -#define IMGUI_VERSION_NUM 19201 +#define IMGUI_VERSION_NUM 19202 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From ed7d965818f9a7d04de0d5ec76ea9809b49a78e7 Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Fri, 27 Jun 2025 16:36:43 +0200 Subject: [PATCH 1167/2359] Examples: GLFW+OpenGL3, GLFW+WGPU: Emscripten Makefiles uses port contrib.glfw3 (#8742) This unofficial port offers a better support for HighDPI. See - https://emscripten.org/docs/compiling/Contrib-Ports.html - https://github.com/pongasoft/emscripten-glfw --- docs/CHANGELOG.txt | 2 ++ examples/example_glfw_opengl3/Makefile.emscripten | 5 +++-- examples/example_glfw_wgpu/Makefile.emscripten | 5 +++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d412df107..2cab3f6c5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,8 @@ Other changes: - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] - CI: Fixed dllimport/dllexport tests. (#8757) [@AidanSun05] - CI: Updated to use latest Windows image + VS2022. +- Examples: GLFW+OpenGL3, GLFW+WGPU: Emscripten Makefiles uses GLFW port + 'contrib.glfw3' which offers better HiDPI support. (#8742) [@pthom] - Backends: GLFW, SDL2 made ImGui_ImplGLFW_GetContentScaleXXX() and ImGui_ImplSDL2_GetContentScaleXXXX() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) [@pthom] diff --git a/examples/example_glfw_opengl3/Makefile.emscripten b/examples/example_glfw_opengl3/Makefile.emscripten index bba4ac9dc..8d2f6e7bd 100644 --- a/examples/example_glfw_opengl3/Makefile.emscripten +++ b/examples/example_glfw_opengl3/Makefile.emscripten @@ -32,8 +32,9 @@ EMS = ##--------------------------------------------------------------------- # ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) -EMS += -s DISABLE_EXCEPTION_CATCHING=1 -LDFLAGS += -s USE_GLFW=3 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1 +# Note: For glfw, we use emscripten-glfw port (contrib.glfw3) instead of ('-s USE_GLFW=3' in LDFLAGS) to get a better support for High DPI displays. +EMS += -s DISABLE_EXCEPTION_CATCHING=1 --use-port=contrib.glfw3 +LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1 # Build as single file (binary text encoded in .html file) #LDFLAGS += -sSINGLE_FILE diff --git a/examples/example_glfw_wgpu/Makefile.emscripten b/examples/example_glfw_wgpu/Makefile.emscripten index 78d64b4d3..8ee398bc8 100644 --- a/examples/example_glfw_wgpu/Makefile.emscripten +++ b/examples/example_glfw_wgpu/Makefile.emscripten @@ -32,8 +32,9 @@ EMS = ##--------------------------------------------------------------------- # ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) -EMS += -s DISABLE_EXCEPTION_CATCHING=1 -LDFLAGS += -s USE_GLFW=3 -s USE_WEBGPU=1 +# Note: For glfw, we use emscripten-glfw port (contrib.glfw3) instead of (-s USE_GLFW=3) to get a better support for High DPI displays. +EMS += -s DISABLE_EXCEPTION_CATCHING=1 --use-port=contrib.glfw3 +LDFLAGS += -s USE_WEBGPU=1 LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1 # Build as single file (binary text encoded in .html file) From d9b758661f79a484255de00a9dbf310beec8bfc1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Jul 2025 15:05:10 +0200 Subject: [PATCH 1168/2359] Misc comments to facilitate update for people who nilly-willy copied entire chunks of internal widgets to create their own. --- imgui.cpp | 4 +++- imgui_internal.h | 11 ++++++++--- imgui_widgets.cpp | 3 ++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0a8582686..84ac433b0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4730,7 +4730,8 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) return true; } -// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). +// Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK. +// Returns whether the item was hovered, logic differs slightly from IsItemHovered(). // (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call) // FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28. // If you used this in your legacy/custom widgets code: @@ -4742,6 +4743,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag ImGuiWindow* window = g.CurrentWindow; // Detect ID conflicts + // (this is specifically done here by comparing on hover because it allows us a detection of duplicates that is algorithmically extra cheap, 1 u32 compare per item. No O(log N) lookup whatsoever) #ifndef IMGUI_DISABLE_DEBUG_TOOLS if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0) { diff --git a/imgui_internal.h b/imgui_internal.h index 12fdac568..fecb7b4dd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -976,6 +976,7 @@ enum ImGuiItemStatusFlags_ ImGuiItemStatusFlags_Visible = 1 << 8, // [WIP] Set when item is overlapping the current clipping rectangle (Used internally. Please don't use yet: API/system will change as we refactor Itemadd()). ImGuiItemStatusFlags_HasClipRect = 1 << 9, // g.LastItemData.ClipRect is valid. ImGuiItemStatusFlags_HasShortcut = 1 << 10, // g.LastItemData.Shortcut valid. Set by SetNextItemShortcut() -> ItemAdd(). + //ImGuiItemStatusFlags_FocusedByTabbing = 1 << 8, // Removed IN 1.90.1 (Dec 2023). The trigger is part of g.NavActivateId. See commit 54c1bdeceb. // Additional status + semantic for ImGuiTestEngine #ifdef IMGUI_ENABLE_TEST_ENGINE @@ -1028,6 +1029,7 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_NoFocus = 1 << 22, // [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking. ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease, + //ImGuiButtonFlags_NoKeyModifiers = ImGuiButtonFlags_NoKeyModsAllowed, // Renamed in 1.91.4 }; // Extend ImGuiComboFlags_ @@ -1678,6 +1680,7 @@ enum ImGuiNavRenderCursorFlags_ ImGuiNavHighlightFlags_Compact = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.91.4 ImGuiNavHighlightFlags_AlwaysDraw = ImGuiNavRenderCursorFlags_AlwaysDraw, // Renamed in 1.91.4 ImGuiNavHighlightFlags_NoRounding = ImGuiNavRenderCursorFlags_NoRounding, // Renamed in 1.91.4 + //ImGuiNavHighlightFlags_TypeThin = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.90.2 #endif }; @@ -2269,18 +2272,19 @@ struct ImGuiContext ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusedWindow' ImGuiID NavFocusScopeId; // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope) ImGuiNavLayer NavLayer; // Focused layer (main scrolling layer, or menu/title bar layer) - ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItem() + ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItemByID() ImGuiID NavActivateDownId; // ~~ IsKeyDown(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyDown(ImGuiKey_NavGamepadActivate) ? NavId : 0 ImGuiID NavActivatePressedId; // ~~ IsKeyPressed(ImGuiKey_Space) || IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate) ? NavId : 0 (no repeat) ImGuiActivateFlags NavActivateFlags; ImVector NavFocusRoute; // Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window->ParentWindowForFocusRoute chain. ImGuiID NavHighlightActivatedId; float NavHighlightActivatedTimer; - ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame. + ImGuiID NavNextActivateId; // Set by ActivateItemByID(), queued until next frame. ImGuiActivateFlags NavNextActivateFlags; ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse ImGuiSelectionUserData NavLastValidSelectionUserData; // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data. ImS8 NavCursorHideFrames; + //ImGuiID NavActivateInputId; // Removed in 1.89.4 (July 2023). This is now part of g.NavActivateId and sets g.NavActivateFlags |= ImGuiActivateFlags_PreferInput. See commit c9a53aa74, issue #5606. // Navigation: Init & Move Requests bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() @@ -3281,7 +3285,7 @@ namespace ImGui // This should be part of a larger set of API: FocusItem(offset = -1), FocusItemByID(id), ActivateItem(offset = -1), ActivateItemByID(id) etc. which are // much harder to design and implement than expected. I have a couple of private branches on this matter but it's not simple. For now implementing the easy ones. IMGUI_API void FocusItem(); // Focus last item (no selection/activation). - IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again. + IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again. Was called 'ActivateItem()' before 1.89.7. // Inputs // FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. @@ -3663,6 +3667,7 @@ namespace ImGui //inline bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0) { return TreeNodeUpdateNextOpen(id, flags); } // Renamed in 1.89 //inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { IM_ASSERT(IsNamedKey(key)); return IsKeyPressed(key, repeat); } // Removed in 1.87: Mapping from named key is always identity! + // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): // (Old) IMGUI_VERSION_NUM < 18209: using 'ItemAdd(....)' and 'bool tab_focused = FocusableItemRegister(...)' // (Old) IMGUI_VERSION_NUM >= 18209: using 'ItemAdd(..., ImGuiItemAddFlags_Focusable)' and 'bool tab_focused = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Focused) != 0' diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index afad7b6ec..9aa94c799 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -573,7 +573,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool bool pressed = false; bool hovered = ItemHoverable(bb, id, item_flags); - // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button + // Special mode for Drag and Drop used by openables (tree nodes, tabs etc.) + // where holding the button pressed for a long time while drag a payload item triggers the button. if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers)) if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { From f39b13848734faf9acc3cf9d2313e2f01032af12 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Jul 2025 18:24:14 +0200 Subject: [PATCH 1169/2359] Internals: rename DebugDrawIdConflicts -> DebugDrawIdConflictsId. --- imgui.cpp | 12 ++++++------ imgui_internal.h | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 84ac433b0..da7f39e24 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4032,7 +4032,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1; WheelingWindowReleaseTimer = 0.0f; - DebugDrawIdConflicts = 0; + DebugDrawIdConflictsId = 0; DebugHookIdInfo = 0; HoveredId = HoveredIdPreviousFrame = 0; HoveredIdPreviousFrameItemCount = 0; @@ -4748,7 +4748,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0) { g.HoveredIdPreviousFrameItemCount++; - if (g.DebugDrawIdConflicts == id) + if (g.DebugDrawIdConflictsId == id) window->DrawList->AddRect(bb.Min - ImVec2(1,1), bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f); } #endif @@ -5376,9 +5376,9 @@ void ImGui::NewFrame() // [DEBUG] if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL - g.DebugDrawIdConflicts = 0; + g.DebugDrawIdConflictsId = 0; if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1) - g.DebugDrawIdConflicts = g.HoveredIdPreviousFrame; + g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame; // Update HoveredId data if (!g.HoveredIdPreviousFrame) @@ -10841,9 +10841,9 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() { #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *GImGui; - if (g.DebugDrawIdConflicts != 0 && g.IO.KeyCtrl == false) + if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false) g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount; - if (g.DebugDrawIdConflicts != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip()) + if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip()) { Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount); BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!"); diff --git a/imgui_internal.h b/imgui_internal.h index fecb7b4dd..978a51020 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2192,7 +2192,7 @@ struct ImGuiContext ImVec2 WheelingAxisAvg; // Item/widgets state and tracking information - ImGuiID DebugDrawIdConflicts; // Set when we detect multiple items with the same identifier + ImGuiID DebugDrawIdConflictsId; // Set when we detect multiple items with the same identifier ImGuiID DebugHookIdInfo; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line] ImGuiID HoveredId; // Hovered widget, filled during the frame ImGuiID HoveredIdPreviousFrame; From 0ba02a4ed67b4c8985007f109b413edb21898f41 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Jul 2025 18:43:25 +0200 Subject: [PATCH 1170/2359] Debug Tools: added IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS. (#8651, #7961, #7669) --- docs/CHANGELOG.txt | 3 +++ imconfig.h | 4 ++++ imgui.cpp | 25 +++++++++++++++++++++++++ imgui_internal.h | 4 ++++ 4 files changed, 36 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2cab3f6c5..4bf17e785 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,9 @@ Other changes: - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] - CI: Fixed dllimport/dllexport tests. (#8757) [@AidanSun05] - CI: Updated to use latest Windows image + VS2022. +- Debug Tools: added IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS to detect + id conflicts _before_ hovering. This is very slow and should only be used + temporarily. (#8651, #7961, #7669) - Examples: GLFW+OpenGL3, GLFW+WGPU: Emscripten Makefiles uses GLFW port 'contrib.glfw3' which offers better HiDPI support. (#8742) [@pthom] - Backends: GLFW, SDL2 made ImGui_ImplGLFW_GetContentScaleXXX() and diff --git a/imconfig.h b/imconfig.h index a1e29e849..4dab1b604 100644 --- a/imconfig.h +++ b/imconfig.h @@ -129,6 +129,10 @@ //#define IM_DEBUG_BREAK IM_ASSERT(0) //#define IM_DEBUG_BREAK __debugbreak() +//---- Debug Tools: Enable highlight ID conflicts _before_ hovering items. When io.ConfigDebugHighlightIdConflicts is set. +// (THIS WILL SLOW DOWN DEAR IMGUI. Only use occasionally and disable after use) +//#define IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + //---- Debug Tools: Enable slower asserts //#define IMGUI_DEBUG_PARANOID diff --git a/imgui.cpp b/imgui.cpp index da7f39e24..153ae5c03 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4263,6 +4263,12 @@ void ImGui::Initialize() #ifdef IMGUI_HAS_DOCK #endif + // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow. + // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED. +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n"); +#endif + // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context. // But this link allows us to facilitate/handle a few edge cases better. ImFontAtlas* atlas = g.IO.Fonts; @@ -11012,6 +11018,21 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something". // READ THE FAQ: https://dearimgui.com/faq IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!"); + + // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED. + // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd(). +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0) + { + int* p_alive = g.DebugDrawIdConflictsAliveCount.GetIntRef(id, -1); // Could halve lookups if we knew ImGuiStorage can store 64-bit, or by storing FrameCount as 30-bits + highlight as 2-bits. But the point is that we should not pretend that this is fast. + int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1); + if (*p_alive == g.FrameCount) + *p_highlight = g.FrameCount; + *p_alive = g.FrameCount; + if (*p_highlight >= g.FrameCount - 1) + window->DrawList->AddRect(bb.Min - ImVec2(1, 1), bb.Max + ImVec2(1, 1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f); + } +#endif } //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG] //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0) @@ -16126,6 +16147,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) } }; +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n"); +#endif + // Tools if (TreeNode("Tools")) { diff --git a/imgui_internal.h b/imgui_internal.h index 978a51020..54daf89c4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2495,6 +2495,10 @@ struct ImGuiContext ImGuiMetricsConfig DebugMetricsConfig; ImGuiIDStackTool DebugIDStackTool; ImGuiDebugAllocInfo DebugAllocInfo; +#if defined(IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS) + ImGuiStorage DebugDrawIdConflictsAliveCount; + ImGuiStorage DebugDrawIdConflictsHighlightSet; +#endif // Misc float FramerateSecPerFrame[60]; // Calculate estimate of framerate for user over the last 60 frames.. From 5d4126876bc10396d4c6511853ff10964414c776 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 9 Jul 2025 18:53:58 +0200 Subject: [PATCH 1171/2359] Version 1.92.1 --- docs/CHANGELOG.txt | 8 ++++---- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 4 ++-- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4bf17e785..7f12f6a5b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,12 +36,12 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.1 WIP (In Progress) + VERSION 1.92.1 (Released 2025-07-09) ----------------------------------------------------------------------- -Breaking changes: +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92.1 -Other changes: +Changes: - Fonts: added ImFontAtlas::SetFontLoader() to dynamically change font loader at runtime without using internal API. (#8752, #8465) @@ -86,7 +86,7 @@ Other changes: VERSION 1.92.0 (Released 2025-06-25) ----------------------------------------------------------------------- -Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92.0 THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCE, diff --git a/imgui.cpp b/imgui.cpp index 153ae5c03..99819ffe4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 WIP +// dear imgui, v1.92.1 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 89c2c2e5d..a2b2a1fae 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 WIP +// dear imgui, v1.92.1 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.1 WIP" -#define IMGUI_VERSION_NUM 19202 +#define IMGUI_VERSION "1.92.1" +#define IMGUI_VERSION_NUM 19210 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 05f5e45f1..991676f78 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 WIP +// dear imgui, v1.92.1 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bce905420..401282678 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 WIP +// dear imgui, v1.92.1 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 54daf89c4..ccb979b8c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 WIP +// dear imgui, v1.92.1 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. @@ -2507,7 +2507,7 @@ struct ImGuiContext float FramerateSecPerFrameAccum; int WantCaptureMouseNextFrame; // Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. int WantCaptureKeyboardNextFrame; // " - int WantTextInputNextFrame; // Copied in EndFrame() from g.PlatformImeData.WanttextInput. Needs to be set for some backends (SDL3) to emit character inputs. + int WantTextInputNextFrame; // Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. ImVector TempBuffer; // Temporary text buffer char TempKeychordName[64]; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 069c72995..119fe7bcc 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 WIP +// dear imgui, v1.92.1 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9aa94c799..a0c4f14f5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 WIP +// dear imgui, v1.92.1 // (widgets code) /* From 4d745bc602d40b242504c15f03fb0322dedb74b3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Jul 2025 18:41:05 +0200 Subject: [PATCH 1172/2359] Version 1.92.2 WIP --- docs/CHANGELOG.txt | 17 +++++++++++++---- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 22 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7f12f6a5b..f19d5f246 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.2 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.92.1 (Released 2025-07-09) ----------------------------------------------------------------------- @@ -64,13 +73,13 @@ Changes: - Debug Tools: added IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS to detect id conflicts _before_ hovering. This is very slow and should only be used temporarily. (#8651, #7961, #7669) -- Examples: GLFW+OpenGL3, GLFW+WGPU: Emscripten Makefiles uses GLFW port +- Examples: GLFW+OpenGL3, GLFW+WGPU: Emscripten Makefiles uses GLFW port 'contrib.glfw3' which offers better HiDPI support. (#8742) [@pthom] -- Backends: GLFW, SDL2 made ImGui_ImplGLFW_GetContentScaleXXX() and - ImGui_ImplSDL2_GetContentScaleXXXX() helpers return 1.0f on Emscripten +- Backends: GLFW, SDL2 made ImGui_ImplGLFW_GetContentScaleXXX() and + ImGui_ImplSDL2_GetContentScaleXXXX() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) [@pthom] - Backends: SDL3: avoid calling SDL_StartTextInput() again if already active. - (fixes e.g.: an issue on iOS where the keyboard animation will popup every + (fixes e.g.: an issue on iOS where the keyboard animation will popup every time the user types a key + probably other things) (#8727) [@morrazzzz] - Backends: OSX: added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. (#8739) [@cfillion] diff --git a/imgui.cpp b/imgui.cpp index 99819ffe4..94d94ff85 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 +// dear imgui, v1.92.2 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index a2b2a1fae..f474876f1 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 +// dear imgui, v1.92.2 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.1" -#define IMGUI_VERSION_NUM 19210 +#define IMGUI_VERSION "1.92.2 WIP" +#define IMGUI_VERSION_NUM 19211 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 991676f78..6bc8968a4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 +// dear imgui, v1.92.2 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 401282678..93fa8c344 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 +// dear imgui, v1.92.2 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index ccb979b8c..c5a664010 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 +// dear imgui, v1.92.2 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 119fe7bcc..f2fa47d78 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 +// dear imgui, v1.92.2 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a0c4f14f5..63dd9dc21 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.1 +// dear imgui, v1.92.2 WIP // (widgets code) /* From c680f54e6c56952885c8f3aebc7eb09d2934e212 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Jul 2025 18:42:39 +0200 Subject: [PATCH 1173/2359] FIxed IsWindowFocused() using wrong flag types (harmless as values were identical). (#8786) --- imgui.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 94d94ff85..0ba16fb31 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12501,10 +12501,10 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) IM_ASSERT(cur_window); // Not inside a Begin()/End() const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0; - if (flags & ImGuiHoveredFlags_RootWindow) + if (flags & ImGuiFocusedFlags_RootWindow) cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy); - if (flags & ImGuiHoveredFlags_ChildWindows) + if (flags & ImGuiFocusedFlags_ChildWindows) return IsWindowChildOf(ref_window, cur_window, popup_hierarchy); else return (ref_window == cur_window); From 0e6e876f237921b7d73bd201f0fc63953fed95d6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Jul 2025 19:04:43 +0200 Subject: [PATCH 1174/2359] Docs: update docs/comments about ImTextureRef, ImTextureID. (#8783) --- docs/FAQ.md | 38 ++++++++++++++++++++++++++++++-------- imgui.h | 5 +++-- imgui_internal.h | 1 - 3 files changed, 33 insertions(+), 11 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 10fb60350..286127cb9 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -389,8 +389,8 @@ node open/closed state differently. See what makes more sense in your situation! ### Q: What are ImTextureID/ImTextureRef? **Short explanation:** -- Refer to [Image Loading and Displaying Examples](https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples) on the [Wiki](https://github.com/ocornut/imgui/wiki). - You may use functions such as `ImGui::Image()`, `ImGui::ImageButton()` or lower-level `ImDrawList::AddImage()` to emit draw calls that will use your own textures. +- To load and display your own textures, refer to [Image Loading and Displaying Examples](https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples) on the [Wiki](https://github.com/ocornut/imgui/wiki). - Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as an opaque ImTextureID value. - By default ImTextureID can store up to 64-bits. You may `#define` it to a custom type/structure if you need. - Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason), but the examples linked above may be useful references. @@ -398,12 +398,20 @@ node open/closed state differently. See what makes more sense in your situation! **Details:** 1.92 introduced `ImTextureRef` in June 2025. -- Most drawing functions using ImTextureID were changed to use ImTextureRef. -- We intentionally do not provide an implicit ImTextureRef -> ImTextureID cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering. +- All drawing functions using `ImTextureID` were changed to use `ImTextureRef`. +- You can trivially create a `ImTextureRef` from a `ImTextureID`. +- **If you use Image functions with textures that you have loaded/created yourself, you will mostly likely only ever store/manipulate `ImTextureID` and then pass them as `ImTextureRef`.** +- You only NEED to manipulate `ImTextureRef` when dealing with textures managed by the backend itself, aka mainly the atlas texture for now. +- We intentionally do not provide an implicit `ImTextureRef` -> `ImTextureID` cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering. **ImTextureID = backend specific, low-level identifier for a texture uploaded in GPU/graphics system.** +```cpp +#ifndef ImTextureID +typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that. +#endif +``` - When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint`; Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.). -- User may submit their own textures to e.g. ImGui::Image() function by passing the same type. +- User may submit their own textures to e.g. `ImGui::Image()` function by passing this value. - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside a ImTextureRef, which is stored inside ImDrawCmd. - Compile-time type configuration: - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file. @@ -411,13 +419,27 @@ node open/closed state differently. See what makes more sense in your situation! - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various constructors if you like. You will need to implement ==/!= operators. **ImTextureRef = higher-level identifier for a texture.** +```cpp +// Store a ImTextureID _or_ a ImTextureData*. +struct ImTextureRef +{ + ImTextureRef() { _TexData = NULL; _TexID = ImTextureID_Invalid; } + ImTextureRef(ImTextureID tex_id) { _TexData = NULL; _TexID = tex_id; } + inline ImTextureID GetTexID() const { return _TexData ? _TexData->TexID : _TexID; } + + // Members (either are set, never both!) + ImTextureData* _TexData; // A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. + ImTextureID _TexID; // _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui::Image() calls. +}; +``` - The identifier is valid even before the texture has been uploaded to the GPU/graphics system. - This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`. - This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering. - - When a texture is created by user code (e.g. custom images), we directly stores the low-level `ImTextureID`. - - When a texture is created by the backend, we stores a `ImTextureData*` which becomes an indirection to extract the `ImTextureID` value during rendering, after texture upload has happened. - - There is no constructor to create a `ImTextureID` from a `ImTextureData*` as we don't expect this to be useful to the end-user, and it would be erroneously called by many legacy code. - - If you want to bind the current atlas when using custom rectangle, you can use `io.Fonts->TexRef`. + - When a texture is created by user code (e.g. custom images), we directly store the low-level `ImTextureID`. + - Because of this, when displaying your own texture you are likely to ever only manage ImTextureID values on your side. + - When a texture is created by the backend, we store a `ImTextureData*` which becomes an indirection to extract the `ImTextureID` value during rendering, after texture upload has happened. + - There is no constructor to create a `ImTextureRef` from a `ImTextureData*` as we don't expect this to be useful to the end-user, and it would be erroneously called by many legacy code. + - If you want to bind the current atlas when using custom rectangles, you can use `io.Fonts->TexRef`. - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g. `inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; }` **Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.** diff --git a/imgui.h b/imgui.h index f474876f1..cef7d7b87 100644 --- a/imgui.h +++ b/imgui.h @@ -317,7 +317,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // - When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value. // (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint`; // Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.). -// - User may submit their own textures to e.g. ImGui::Image() function by passing the same type. +// - User may submit their own textures to e.g. ImGui::Image() function by passing this value. // - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside a // ImTextureRef, which is stored inside a ImDrawCmd. // - Compile-time type configuration: @@ -337,11 +337,12 @@ typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or #define ImTextureID_Invalid ((ImTextureID)0) #endif -// ImTextureRef = higher-level identifier for a texture. +// ImTextureRef = higher-level identifier for a texture. Store a ImTextureID _or_ a ImTextureData*. // The identifier is valid even before the texture has been uploaded to the GPU/graphics system. // This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`. // This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering. // - When a texture is created by user code (e.g. custom images), we directly stores the low-level ImTextureID. +// Because of this, when displaying your own texture you are likely to ever only manage ImTextureID values on your side. // - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection // to extract the ImTextureID value during rendering, after texture upload has happened. // - There is no constructor to create a ImTextureID from a ImTextureData* as we don't expect this diff --git a/imgui_internal.h b/imgui_internal.h index c5a664010..bf744d4b1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3671,7 +3671,6 @@ namespace ImGui //inline bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0) { return TreeNodeUpdateNextOpen(id, flags); } // Renamed in 1.89 //inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { IM_ASSERT(IsNamedKey(key)); return IsKeyPressed(key, repeat); } // Removed in 1.87: Mapping from named key is always identity! - // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): // (Old) IMGUI_VERSION_NUM < 18209: using 'ItemAdd(....)' and 'bool tab_focused = FocusableItemRegister(...)' // (Old) IMGUI_VERSION_NUM >= 18209: using 'ItemAdd(..., ImGuiItemAddFlags_Focusable)' and 'bool tab_focused = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Focused) != 0' From a0d3e405a343677cd326ed704b1b27c000c05d17 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 11 Jul 2025 16:40:35 +0200 Subject: [PATCH 1175/2359] Textures: ImTextureData::Create() sets status. RegisterUserTexture() increases RefCount. Added comments about ImTextureData::GetTexRef(). (#8789) --- docs/FAQ.md | 2 ++ imgui.cpp | 5 ++++- imgui.h | 9 +++++---- imgui_draw.cpp | 3 ++- imgui_internal.h | 2 +- 5 files changed, 14 insertions(+), 7 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 286127cb9..fb693c7e3 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -438,6 +438,8 @@ struct ImTextureRef - When a texture is created by user code (e.g. custom images), we directly store the low-level `ImTextureID`. - Because of this, when displaying your own texture you are likely to ever only manage ImTextureID values on your side. - When a texture is created by the backend, we store a `ImTextureData*` which becomes an indirection to extract the `ImTextureID` value during rendering, after texture upload has happened. + - To create a `ImTextureRef` from a `ImTextureData*` you can use `ImTextureData::GetTexRef()`. + We intentionally do not provide an `ImTextureRef` constructor for this: we don't expect this to be frequently useful to the end-user, and it would be erroneously called by many legacy code. - There is no constructor to create a `ImTextureRef` from a `ImTextureData*` as we don't expect this to be useful to the end-user, and it would be erroneously called by many legacy code. - If you want to bind the current atlas when using custom rectangles, you can use `io.Fonts->TexRef`. - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g. `inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; }` diff --git a/imgui.cpp b/imgui.cpp index 0ba16fb31..31a95716b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8732,16 +8732,19 @@ ImFont* ImGui::GetDefaultFont() return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0]; } +// EXPERIMENTAL: DO NOT USE YET. void ImGui::RegisterUserTexture(ImTextureData* tex) { ImGuiContext& g = *GImGui; - IM_ASSERT(tex->RefCount > 0); + tex->RefCount++; g.UserTextures.push_back(tex); } void ImGui::UnregisterUserTexture(ImTextureData* tex) { ImGuiContext& g = *GImGui; + IM_ASSERT(tex->RefCount > 0); + tex->RefCount--; g.UserTextures.find_erase(tex); } diff --git a/imgui.h b/imgui.h index cef7d7b87..ee4e976ae 100644 --- a/imgui.h +++ b/imgui.h @@ -345,8 +345,9 @@ typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or // Because of this, when displaying your own texture you are likely to ever only manage ImTextureID values on your side. // - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection // to extract the ImTextureID value during rendering, after texture upload has happened. -// - There is no constructor to create a ImTextureID from a ImTextureData* as we don't expect this -// to be useful to the end-user, and it would be erroneously called by many legacy code. +// - To create a ImTextureRef from a ImTextureData you can use ImTextureData::GetTexRef(). +// We intentionally do not provide an ImTextureRef constructor for this: we don't expect this +// to be frequently useful to the end-user, and it would be erroneously called by many legacy code. // - If you want to bind the current atlas when using custom rectangle, you can use io.Fonts->TexRef. // - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g. // inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; } @@ -3425,7 +3426,7 @@ struct ImTextureRect struct ImTextureData { //------------------------------------------ core / backend --------------------------------------- - int UniqueID; // w - // Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. + int UniqueID; // w - // [DEBUG] Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. ImTextureStatus Status; // rw rw // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! void* BackendUserData; // - rw // Convenience storage for backend. Some backends may have enough with TexID. ImTextureID TexID; // r w // Backend-specific texture identifier. Always use SetTexID() to modify! The identifier will stored in ImDrawCmd::GetTexID() and passed to backend's RenderDrawData function. @@ -3443,7 +3444,7 @@ struct ImTextureData bool WantDestroyNextFrame; // rw - // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. // Functions - ImTextureData() { memset(this, 0, sizeof(*this)); TexID = ImTextureID_Invalid; } + ImTextureData() { memset(this, 0, sizeof(*this)); Status = ImTextureStatus_Destroyed; TexID = ImTextureID_Invalid; } ~ImTextureData() { DestroyPixels(); } IMGUI_API void Create(ImTextureFormat format, int w, int h); IMGUI_API void DestroyPixels(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 93fa8c344..d12b8b55d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2457,8 +2457,10 @@ const char* ImTextureDataGetFormatName(ImTextureFormat format) void ImTextureData::Create(ImTextureFormat format, int w, int h) { + IM_ASSERT(Status == ImTextureStatus_Destroyed); DestroyPixels(); Format = format; + Status = ImTextureStatus_WantCreate; Width = w; Height = h; BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format); @@ -3971,7 +3973,6 @@ ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h) } new_tex->Create(atlas->TexDesiredFormat, w, h); - new_tex->Status = ImTextureStatus_WantCreate; atlas->TexIsBuilt = false; ImFontAtlasBuildSetTexture(atlas, new_tex); diff --git a/imgui_internal.h b/imgui_internal.h index bf744d4b1..f5f324c6e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3124,7 +3124,7 @@ namespace ImGui IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); // Fonts, drawing - IMGUI_API void RegisterUserTexture(ImTextureData* tex); // Register external texture + IMGUI_API void RegisterUserTexture(ImTextureData* tex); // Register external texture. EXPERIMENTAL: DO NOT USE YET. IMGUI_API void UnregisterUserTexture(ImTextureData* tex); IMGUI_API void RegisterFontAtlas(ImFontAtlas* atlas); IMGUI_API void UnregisterFontAtlas(ImFontAtlas* atlas); From 79d88e2d0b1c915a9ea3d1a4215cf2a4dded3fab Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 11 Jul 2025 16:57:43 +0200 Subject: [PATCH 1176/2359] Error Handling, Tables: TableGetSortSpecs() silently return NULL when no table (matching most other table getters). TableSetBgColor() uses IM_ASSERT_USER_ERROR. --- docs/CHANGELOG.txt | 3 +++ imgui_tables.cpp | 9 ++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f19d5f246..70d3c37a3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking Changes: Other Changes: +- Error Handling: minor improvements to error handling for TableGetSortSpecs() + and TableSetBgColor() calls. (#1651, #8499) + ----------------------------------------------------------------------- VERSION 1.92.1 (Released 2025-07-09) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f2fa47d78..a1504853b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1825,6 +1825,11 @@ void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; IM_ASSERT(target != ImGuiTableBgTarget_None); + if (table == NULL) + { + IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); + return; + } if (color == IM_COL32_DISABLE) color = 0; @@ -2876,9 +2881,7 @@ ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL); - - if (!(table->Flags & ImGuiTableFlags_Sortable)) + if (table == NULL || !(table->Flags & ImGuiTableFlags_Sortable)) return NULL; // Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths. From 336d9212fc25055a52107c70441c11acd12e8bb9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 11 Jul 2025 17:41:52 +0200 Subject: [PATCH 1177/2359] Backends: using range-for to iterate draw_data->CmdLists[]. --- backends/imgui_impl_allegro5.cpp | 4 +--- backends/imgui_impl_dx10.cpp | 6 ++---- backends/imgui_impl_dx11.cpp | 6 ++---- backends/imgui_impl_dx12.cpp | 6 ++---- backends/imgui_impl_dx9.cpp | 6 ++---- backends/imgui_impl_metal.mm | 6 ++---- backends/imgui_impl_opengl2.cpp | 3 +-- backends/imgui_impl_opengl3.cpp | 4 +--- backends/imgui_impl_sdlgpu3.cpp | 6 ++---- backends/imgui_impl_sdlrenderer2.cpp | 3 +-- backends/imgui_impl_sdlrenderer3.cpp | 3 +-- backends/imgui_impl_vulkan.cpp | 6 ++---- backends/imgui_impl_wgpu.cpp | 8 +++----- docs/BACKENDS.md | 3 +-- imgui.h | 2 +- imgui_draw.cpp | 17 ++++++++--------- 16 files changed, 32 insertions(+), 57 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 5cbb89365..40417fc63 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -160,10 +160,8 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) ImGui_ImplAllegro5_SetupRenderState(draw_data); // Render command lists - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; - ImVector& vertices = bd->BufVertices; #if ALLEGRO_HAS_DRAW_INDEXED_PRIM vertices.resize(draw_list->VtxBuffer.Size); diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 6bc52156f..3781a0974 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -200,9 +200,8 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ImDrawIdx* idx_dst = nullptr; bd->pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst); bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst); - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += draw_list->VtxBuffer.Size; @@ -268,9 +267,8 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; ImVec2 clip_scale = draw_data->FramebufferScale; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index 1b28745a3..08bf7998f 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -208,9 +208,8 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += draw_list->VtxBuffer.Size; @@ -282,9 +281,8 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) int global_vtx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; ImVec2 clip_scale = draw_data->FramebufferScale; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 557850979..2932855ed 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -262,9 +262,8 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += draw_list->VtxBuffer.Size; @@ -295,9 +294,8 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; ImVec2 clip_scale = draw_data->FramebufferScale; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index b0159bf37..94411fabe 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -228,9 +228,8 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) // 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 (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_src = draw_list->VtxBuffer.Data; for (int i = 0; i < draw_list->VtxBuffer.Size; i++) { @@ -260,9 +259,8 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) int global_vtx_offset = 0; int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index b1decb2bb..a1adc6c9a 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -223,7 +223,7 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id // 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); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); - if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0) + if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdLists.Size == 0) return; // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. @@ -259,10 +259,8 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id // Render command lists size_t vertexBufferOffset = 0; size_t indexBufferOffset = 0; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; - memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp index afcafe826..7f760cca5 100644 --- a/backends/imgui_impl_opengl2.cpp +++ b/backends/imgui_impl_opengl2.cpp @@ -208,9 +208,8 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data; const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data; glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, pos))); diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 40b3be68b..7e8853017 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -584,10 +584,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; - // Upload vertex/index buffers // - OpenGL drivers are in a very sorry state nowadays.... // During 2021 we attempted to switch from glBufferData() to orphaning+glBufferSubData() following reports diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 927e511cb..f58324a89 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -180,9 +180,8 @@ void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuff ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->Device, fd->VertexTransferBuffer, true); ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->Device, fd->IndexTransferBuffer, true); - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += draw_list->VtxBuffer.Size; @@ -238,9 +237,8 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index a39360f5c..3a47f80bf 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -169,9 +169,8 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* ImVec2 clip_scale = render_scale; // Render command lists - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data; const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data; diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index f62949150..42c173888 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -189,9 +189,8 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* ImVec2 clip_scale = render_scale; // Render command lists - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data; const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data; diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index a5dd75c8e..1120b4b5e 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -550,9 +550,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm check_vk_result(err); err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)&idx_dst); check_vk_result(err); - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += draw_list->VtxBuffer.Size; @@ -590,9 +589,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index c0ec2e3f9..d20028d55 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -367,7 +367,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder // Avoid rendering when minimized int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); - if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0) + if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdLists.Size == 0) return; // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. @@ -442,9 +442,8 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder // Upload vertex/index data into a single contiguous GPU buffer ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost; ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += draw_list->VtxBuffer.Size; @@ -471,9 +470,8 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder int global_idx_offset = 0; ImVec2 clip_scale = draw_data->FramebufferScale; ImVec2 clip_off = draw_data->DisplayPos; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* draw_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index fa05d55ea..629f8d83f 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -245,9 +245,8 @@ void MyImGuiBackend_RenderDrawData(ImDrawData* draw_data) // Render command lists ImVec2 clip_off = draw_data->DisplayPos; ImVec2 clip_scale = draw_data->FramebufferScale; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (const ImDrawList* draw_list : draw_data->CmdLists) { - const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) diff --git a/imgui.h b/imgui.h index ee4e976ae..5d947b23d 100644 --- a/imgui.h +++ b/imgui.h @@ -3361,7 +3361,7 @@ struct ImDrawList struct ImDrawData { bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. - int CmdListsCount; // Number of ImDrawList* to render. (== CmdLists.Size). Exists for legacy reason. + int CmdListsCount; // == CmdLists.Size. (OBSOLETE: exists for legacy reasons). Number of ImDrawList* to render. int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size ImVector CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d12b8b55d..f42f96639 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2312,17 +2312,16 @@ void ImDrawData::DeIndexAllBuffers() { ImVector new_vtx_buffer; TotalVtxCount = TotalIdxCount = 0; - for (int i = 0; i < CmdListsCount; i++) + for (ImDrawList* draw_list : CmdLists) { - ImDrawList* cmd_list = CmdLists[i]; - if (cmd_list->IdxBuffer.empty()) + if (draw_list->IdxBuffer.empty()) continue; - new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); - for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) - new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; - cmd_list->VtxBuffer.swap(new_vtx_buffer); - cmd_list->IdxBuffer.resize(0); - TotalVtxCount += cmd_list->VtxBuffer.Size; + new_vtx_buffer.resize(draw_list->IdxBuffer.Size); + for (int j = 0; j < draw_list->IdxBuffer.Size; j++) + new_vtx_buffer[j] = draw_list->VtxBuffer[draw_list->IdxBuffer[j]]; + draw_list->VtxBuffer.swap(new_vtx_buffer); + draw_list->IdxBuffer.resize(0); + TotalVtxCount += draw_list->VtxBuffer.Size; } } From 8744d10235e58536c5237a2ead3af53b700f40c4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 15 Jul 2025 14:30:50 +0200 Subject: [PATCH 1178/2359] Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) --- backends/imgui_impl_opengl2.cpp | 3 +++ backends/imgui_impl_opengl3.cpp | 15 ++++++++++++--- backends/imgui_impl_opengl3_loader.h | 1 + docs/CHANGELOG.txt | 2 ++ 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp index 7f760cca5..477e3a043 100644 --- a/backends/imgui_impl_opengl2.cpp +++ b/backends/imgui_impl_opengl2.cpp @@ -25,6 +25,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) // 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL2_CreateFontsTexture() and ImGui_ImplOpenGL2_DestroyFontsTexture(). // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-06-28: OpenGL: ImGui_ImplOpenGL2_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL2_DestroyFontsTexture(). (#7748) @@ -285,6 +286,7 @@ void ImGui_ImplOpenGL2_UpdateTexture(ImTextureData* tex) GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)); GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); + GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->Width, tex->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); // Store identifiers @@ -304,6 +306,7 @@ void ImGui_ImplOpenGL2_UpdateTexture(ImTextureData* tex) GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_tex_id)); GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->Width)); + GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); for (ImTextureRect& r : tex->Updates) GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, tex->GetPixelsAt(r.x, r.y))); GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 7e8853017..e9660295e 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -23,6 +23,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) // 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture(). // 2025-06-04: OpenGL: Made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664) // 2025-02-18: OpenGL: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) @@ -709,6 +710,17 @@ static void ImGui_ImplOpenGL3_DestroyTexture(ImTextureData* tex) void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex) { + // FIXME: Consider backing up and restoring + if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates) + { +#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); +#endif +#ifdef GL_UNPACK_ALIGNMENT + GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); +#endif + } + if (tex->Status == ImTextureStatus_WantCreate) { // Create and upload new texture to graphics system @@ -728,9 +740,6 @@ void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex) GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); -#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES - GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); -#endif GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->Width, tex->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); // Store identifiers diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index 4ca053603..aa8fdc27e 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -166,6 +166,7 @@ typedef khronos_uint8_t GLubyte; #define GL_SCISSOR_BOX 0x0C10 #define GL_SCISSOR_TEST 0x0C11 #define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_ALIGNMENT 0x0CF5 #define GL_PACK_ALIGNMENT 0x0D05 #define GL_MAX_TEXTURE_SIZE 0x0D33 #define GL_TEXTURE_2D 0x0DE1 diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 70d3c37a3..17cf659ba 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,8 @@ Other Changes: - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) +- Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating + textures. (#8802) [@Daandelange] ----------------------------------------------------------------------- From 643f0e3abf6f84c210ea717f62c02bf411fc2e8c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 15 Jul 2025 14:34:04 +0200 Subject: [PATCH 1179/2359] Backends: OpenGL3: restore update path on non-WebGL non-ES targets that doesn't require a CPU copy. (#8802, #8465) Amend/fix dbb91a5 --- backends/imgui_impl_opengl3.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index e9660295e..00d1d94c3 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -23,7 +23,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) +// 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures (#8802) + restore non-WebGL/ES update path that doesn't require a CPU-side copy. // 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture(). // 2025-06-04: OpenGL: Made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664) // 2025-02-18: OpenGL: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) @@ -758,7 +758,7 @@ void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex) GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_tex_id)); -#if 0// GL_UNPACK_ROW_LENGTH // Not on WebGL/ES +#if GL_UNPACK_ROW_LENGTH // Not on WebGL/ES GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->Width)); for (ImTextureRect& r : tex->Updates) GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, tex->GetPixelsAt(r.x, r.y))); From 57a816ae609b09c384be938d4a1036483fe71f83 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Jul 2025 15:27:17 +0900 Subject: [PATCH 1180/2359] Texutres: minor comments, tweaks. --- imgui_draw.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f42f96639..5cb0ef8b5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2740,10 +2740,9 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool rendere if (atlas->Builder == NULL) // This will only happen if fonts were not already loaded. ImFontAtlasBuildMain(atlas); } - else // Legacy backend - { + // Legacy backend + if (!atlas->RendererHasTextures) IM_ASSERT_USER_ERROR(atlas->TexIsBuilt, "Backend does not support ImGuiBackendFlags_RendererHasTextures, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()."); - } if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges) IM_ASSERT_USER_ERROR(atlas->RendererHasTextures == false, "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build()."); @@ -2798,8 +2797,9 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool rendere } else if (tex->WantDestroyNextFrame && tex->Status != ImTextureStatus_WantDestroy) { - // Request destroy. Keep bool as it allows us to keep track of things. - // We don't destroy pixels right away, as backend may have an in-flight copy from RAM. + // Request destroy. + // - Keep bool to true in order to differentiate a planned destroy vs a destroy decided by the backend. + // - We don't destroy pixels right away, as backend may have an in-flight copy from RAM. IM_ASSERT(tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates); tex->Status = ImTextureStatus_WantDestroy; } @@ -2955,7 +2955,7 @@ void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, tex->UsedRect.h = (unsigned short)(ImMax(tex->UsedRect.y + tex->UsedRect.h, req.y + req.h) - tex->UsedRect.y); atlas->TexIsBuilt = false; - // No need to queue if status is _WantCreate + // No need to queue if status is == ImTextureStatus_WantCreate if (tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantUpdates) { tex->Status = ImTextureStatus_WantUpdates; From c9e0208de4512ba2c9d93da76d8a71ed5de092d5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Jul 2025 15:35:53 +0900 Subject: [PATCH 1181/2359] Textures: moved UpdateTexturesNewFrame(), UpdateTexturesEndFrame() to a more suitable location in the file. --- imgui.cpp | 86 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 44 insertions(+), 42 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 31a95716b..02080d14b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -78,7 +78,7 @@ CODE // [SECTION] RENDER HELPERS // [SECTION] INITIALIZATION, SHUTDOWN // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) -// [SECTION] FONTS +// [SECTION] FONTS, TEXTURES // [SECTION] ID STACK // [SECTION] INPUTS // [SECTION] ERROR CHECKING, STATE RECOVERY @@ -5261,46 +5261,6 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; } -static void ImGui::UpdateTexturesNewFrame() -{ - // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count. - ImGuiContext& g = *GImGui; - const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; - for (ImFontAtlas* atlas : g.FontAtlases) - { - if (atlas->OwnerContext == &g) - { - ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures); - } - else - { - // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it. - // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context. - // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that. - // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures. - IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1); - IM_ASSERT(atlas->RendererHasTextures == has_textures); - } - } -} - -// Build a single texture list -static void ImGui::UpdateTexturesEndFrame() -{ - ImGuiContext& g = *GImGui; - g.PlatformIO.Textures.resize(0); - for (ImFontAtlas* atlas : g.FontAtlases) - for (ImTextureData* tex : atlas->TexList) - { - // We provide this information so backends can decide whether to destroy textures. - // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized. - tex->RefCount = (unsigned short)atlas->RefCount; - g.PlatformIO.Textures.push_back(tex); - } - for (ImTextureData* tex : g.UserTextures) - g.PlatformIO.Textures.push_back(tex); -} - // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! static void SetupDrawListSharedData() @@ -8671,11 +8631,13 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) } //----------------------------------------------------------------------------- -// [SECTION] FONTS +// [SECTION] FONTS, TEXTURES //----------------------------------------------------------------------------- // Most of the relevant font logic is in imgui_draw.cpp. // Those are high-level support functions. //----------------------------------------------------------------------------- +// - UpdateTexturesNewFrame() [Internal] +// - UpdateTexturesEndFrame() [Internal] // - UpdateFontsNewFrame() [Internal] // - UpdateFontsEndFrame() [Internal] // - GetDefaultFont() [Internal] @@ -8690,6 +8652,46 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) // - PopFont() //----------------------------------------------------------------------------- +static void ImGui::UpdateTexturesNewFrame() +{ + // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count. + ImGuiContext& g = *GImGui; + const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + for (ImFontAtlas* atlas : g.FontAtlases) + { + if (atlas->OwnerContext == &g) + { + ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures); + } + else + { + // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it. + // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context. + // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that. + // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures. + IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1); + IM_ASSERT(atlas->RendererHasTextures == has_textures); + } + } +} + +// Build a single texture list +static void ImGui::UpdateTexturesEndFrame() +{ + ImGuiContext& g = *GImGui; + g.PlatformIO.Textures.resize(0); + for (ImFontAtlas* atlas : g.FontAtlases) + for (ImTextureData* tex : atlas->TexList) + { + // We provide this information so backends can decide whether to destroy textures. + // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized. + tex->RefCount = (unsigned short)atlas->RefCount; + g.PlatformIO.Textures.push_back(tex); + } + for (ImTextureData* tex : g.UserTextures) + g.PlatformIO.Textures.push_back(tex); +} + void ImGui::UpdateFontsNewFrame() { ImGuiContext& g = *GImGui; From 3401dbde92cab3691fa04ea3d773f051d9fa7307 Mon Sep 17 00:00:00 2001 From: Rhys Pounder <60443928+Rhys-Pounder@users.noreply.github.com> Date: Mon, 21 Jul 2025 07:42:16 +0100 Subject: [PATCH 1182/2359] Docs: Fixed typo. (#8817) --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index 7c62950d8..0cd64fa82 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,7 +16,7 @@ Businesses: support continued development and maintenance via invoiced sponsorin | [The Pitch](#the-pitch) - [Usage](#usage) - [How it works](#how-it-works) - [Releases & Changelogs](#releases--changelogs) - [Demo](#demo) - [Getting Started & Integration](#getting-started--integration) | :----------------------------------------------------------: | | [Gallery](#gallery) - [Support, FAQ](#support-frequently-asked-questions-faq) - [How to help](#how-to-help) - **[Funding & Sponsors](https://github.com/ocornut/imgui/wiki/Funding)** - [Credits](#credits) - [License](#license) | -| [Wiki](https://github.com/ocornut/imgui/wiki) - [Extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions) - [Languages bindings & frameworks backends](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | +| [Wiki](https://github.com/ocornut/imgui/wiki) - [Extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions) - [Language bindings & framework backends](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | ### The Pitch From ed5bd1f9ef951628491b7d2355410a703fa2046f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Jul 2025 14:06:44 +0900 Subject: [PATCH 1183/2359] Changed ImTextCharToUtf8() to return bytes count rather than original pointer. (#8820) Amend c2bf4abfa12 --- imgui.cpp | 15 ++++++++++----- imgui.h | 2 +- imgui_internal.h | 2 +- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 02080d14b..dc29cdb32 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2582,11 +2582,11 @@ static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int return 0; } -const char* ImTextCharToUtf8(char out_buf[5], unsigned int c) +int ImTextCharToUtf8(char out_buf[5], unsigned int c) { int count = ImTextCharToUtf8_inline(out_buf, 5, c); out_buf[count] = 0; - return out_buf; + return count; } // Not optimal but we very rarely use this function. @@ -16922,8 +16922,10 @@ void ImGui::DebugNodeFont(ImFont* font) #endif char c_str[5]; - Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar); - Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar); + ImTextCharToUtf8(c_str, font->FallbackChar); + Text("Fallback character: '%s' (U+%04X)", c_str, font->FallbackChar); + ImTextCharToUtf8(c_str, font->EllipsisChar); + Text("Ellipsis character: '%s' (U+%04X)", c_str, font->EllipsisChar); for (int src_n = 0; src_n < font->Sources.Size; src_n++) { @@ -16965,7 +16967,10 @@ void ImGui::DebugNodeFont(ImFont* font) { char utf8_buf[5]; for (unsigned int n = c; n < c_end; n++) - BulletText("Codepoint U+%04X (%s)", n, ImTextCharToUtf8(utf8_buf, n)); + { + ImTextCharToUtf8(utf8_buf, n); + BulletText("Codepoint U+%04X (%s)", n, utf8_buf); + } TreePop(); } TableNextColumn(); diff --git a/imgui.h b/imgui.h index 5d947b23d..4caa4e134 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.2 WIP" -#define IMGUI_VERSION_NUM 19211 +#define IMGUI_VERSION_NUM 19212 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_internal.h b/imgui_internal.h index f5f324c6e..f0e6b4175 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -417,7 +417,7 @@ IMGUI_API const char* ImParseFormatSanitizeForScanning(const char* fmt_in, cha IMGUI_API int ImParseFormatPrecision(const char* format, int default_value); // Helpers: UTF-8 <> wchar conversions -IMGUI_API const char* ImTextCharToUtf8(char out_buf[5], unsigned int c); // return out_buf +IMGUI_API int ImTextCharToUtf8(char out_buf[5], unsigned int c); // return output UTF-8 bytes count IMGUI_API int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count IMGUI_API int ImTextStrFromUtf8(ImWchar* out_buf, int out_buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count From ea613e181c95de2765e92e7b52ba1a849070df8a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Jul 2025 16:22:53 +0900 Subject: [PATCH 1184/2359] Windows: fixed an issue where resizable child windows would emit border logic when hidden/non-visible. (#8815) This makes more sense in docking branch but may be merged in master right away. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 10 ++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 17cf659ba..f58f01a50 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking Changes: Other Changes: +- Windows: fixed an issue where resizable child windows would emit border + logic when hidden/non-visible (e.g. when in a docked window that is not + selected), impacting code not checking for BeginChild() return value. (#8815) - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating diff --git a/imgui.cpp b/imgui.cpp index dc29cdb32..769fd44df 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7578,12 +7578,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } #endif + // Decide if we are going to handle borders and resize grips + // 'window->SkipItems' is not updated yet so for child windows we rely on ParentWindow to avoid submitting decorations. (#8815) + // Whenever we add support for full decorated child windows we will likely make this logic more general. + bool handle_borders_and_resize_grips = true; + if ((flags & ImGuiWindowFlags_ChildWindow) && window->ParentWindow->SkipItems) + handle_borders_and_resize_grips = false; + // Handle manual resize: Resize Grips, Borders, Gamepad int border_hovered = -1, border_held = -1; ImU32 resize_grip_col[4] = {}; const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); - if (!window->Collapsed) + if (handle_borders_and_resize_grips && !window->Collapsed) if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) { if (auto_fit_mask & (1 << ImGuiAxis_X)) @@ -7720,7 +7727,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Handle title bar, scrollbar, resize grips and resize borders const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); - const bool handle_borders_and_resize_grips = true; // This exists to facilitate merge with 'docking' branch. RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size); if (render_decorations_in_parent) From 9c392896b750c056e952bc84e6036c0d6bc1acaa Mon Sep 17 00:00:00 2001 From: gomkyung2 Date: Thu, 17 Jul 2025 18:56:12 +0900 Subject: [PATCH 1185/2359] Misc: removed more redundant inline static linkage from imgui_internal.h. (#8813, #8682, #8358) --- docs/CHANGELOG.txt | 2 + imgui_internal.h | 114 ++++++++++++++++++++++----------------------- 2 files changed, 59 insertions(+), 57 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f58f01a50..da2162b9f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,8 @@ Other Changes: selected), impacting code not checking for BeginChild() return value. (#8815) - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) +- Misc: removed more redundant inline static linkage from imgui_internal.h to + facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) [@Daandelange] diff --git a/imgui_internal.h b/imgui_internal.h index f0e6b4175..e92ab7b5c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -369,17 +369,17 @@ IMGUI_API ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImGuiI // Helpers: Sorting #ifndef ImQsort -static inline void ImQsort(void* base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const*, void const*)) { if (count > 1) qsort(base, count, size_of_element, compare_func); } +inline void ImQsort(void* base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const*, void const*)) { if (count > 1) qsort(base, count, size_of_element, compare_func); } #endif // Helpers: Color Blending IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); // Helpers: Bit manipulation -static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } -static inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } -static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } -static inline unsigned int ImCountSetBits(unsigned int v) { unsigned int count = 0; while (v > 0) { v = v & (v - 1); count++; } return count; } +inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } +inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } +inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } +inline unsigned int ImCountSetBits(unsigned int v) { unsigned int count = 0; while (v > 0) { v = v & (v - 1); count++; } return count; } // Helpers: String #define ImStrlen strlen @@ -398,10 +398,10 @@ IMGUI_API const char* ImStrSkipBlank(const char* str); 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 -static inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; } -static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } -static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } -static inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } +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; } +inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } IM_MSVC_RUNTIME_CHECKS_RESTORE // Helpers: Formatting @@ -431,11 +431,11 @@ IMGUI_API int ImTextCountLines(const char* in_text, const char* in_tex #ifdef IMGUI_DISABLE_FILE_FUNCTIONS #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS typedef void* ImFileHandle; -static inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; } -static inline bool ImFileClose(ImFileHandle) { return false; } -static inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; } -static inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; } -static inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; } +inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; } +inline bool ImFileClose(ImFileHandle) { return false; } +inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; } +inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; } +inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; } #endif #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS typedef FILE* ImFileHandle; @@ -462,56 +462,56 @@ IM_MSVC_RUNTIME_CHECKS_OFF #define ImAtan2(Y, X) atan2f((Y), (X)) #define ImAtof(STR) atof(STR) #define ImCeil(X) ceilf(X) -static inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision -static inline double ImPow(double x, double y) { return pow(x, y); } -static inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision -static inline double ImLog(double x) { return log(x); } -static inline int ImAbs(int x) { return x < 0 ? -x : x; } -static inline float ImAbs(float x) { return fabsf(x); } -static inline double ImAbs(double x) { return fabs(x); } -static inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f) ? 1.0f : 0.0f; } // Sign operator - returns -1, 0 or 1 based on sign of argument -static inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; } +inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision +inline double ImPow(double x, double y) { return pow(x, y); } +inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision +inline double ImLog(double x) { return log(x); } +inline int ImAbs(int x) { return x < 0 ? -x : x; } +inline float ImAbs(float x) { return fabsf(x); } +inline double ImAbs(double x) { return fabs(x); } +inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f) ? 1.0f : 0.0f; } // Sign operator - returns -1, 0 or 1 based on sign of argument +inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; } #ifdef IMGUI_ENABLE_SSE -static inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); } +inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); } #else -static inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } +inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } #endif -static inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } +inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } #endif // - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double // (Exceptionally using templates here but we could also redefine them for those types) -template static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } -template static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } -template static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } -template static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } -template static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } -template static inline 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 static inline 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; } +template T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } +template T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } +template T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +template T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } +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; } // - Misc maths helpers -static 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); } -static 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); } -static inline ImVec2 ImClamp(const ImVec2& v, const ImVec2&mn, const ImVec2&mx) { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); } -static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); } -static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } -static inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } -static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } -static inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } -static inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } -static 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; } -static inline float ImTrunc(float f) { return (float)(int)(f); } -static inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } -static inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() -static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } -static inline float ImTrunc64(float f) { return (float)(ImS64)(f); } -static inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } -static inline int ImModPositive(int a, int b) { return (a + b) % b; } -static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } -static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } -static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; } -static inline float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x) { return ImSaturate((x - s0) / (s1 - s0)) * (d1 - d0) + d0; } -static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } -static inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } -static inline float ImExponentialMovingAverage(float avg, float sample, int n) { avg -= avg / n; avg += sample / n; return avg; } +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); } +inline ImVec2 ImClamp(const ImVec2& v, const ImVec2&mn, const ImVec2&mx){ return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); } +inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); } +inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } +inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } +inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } +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); } +inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } +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 ImTrunc64(float f) { return (float)(ImS64)(f); } +inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } +inline int ImModPositive(int a, int b) { return (a + b) % b; } +inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } +inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } +inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; } +inline float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x) { return ImSaturate((x - s0) / (s1 - s0)) * (d1 - d0) + d0; } +inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } +inline float ImExponentialMovingAverage(float avg, float sample, int n){ avg -= avg / n; avg += sample / n; return avg; } IM_MSVC_RUNTIME_CHECKS_RESTORE // Helpers: Geometry From 4a51295c9e72b7339657c7e3baa40a66bc359caa Mon Sep 17 00:00:00 2001 From: Tim-Rex Date: Sat, 12 Jul 2025 16:47:45 +1000 Subject: [PATCH 1186/2359] Backends: OpenGL3: add and call embedded loader shutdown in ImGui_ImplOpenGL3_Shutdown(). (#8792) Include update of imgui_impl_opengl3_loader.h as submitted to gl3w_stripped repository, which adds imgl3wShutdown(). --- backends/imgui_impl_opengl3.cpp | 5 +++++ backends/imgui_impl_opengl3_loader.h | 14 ++++++++++---- docs/CHANGELOG.txt | 2 ++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 00d1d94c3..607d24371 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -23,6 +23,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-07-22: OpenGL: Add and call embedded loader shutdown during ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) // 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures (#8802) + restore non-WebGL/ES update path that doesn't require a CPU-side copy. // 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture(). // 2025-06-04: OpenGL: Made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664) @@ -422,6 +423,10 @@ void ImGui_ImplOpenGL3_Shutdown() io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); IM_DELETE(bd); + +#ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W + imgl3wShutdown(); +#endif } void ImGui_ImplOpenGL3_NewFrame() diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index aa8fdc27e..c3f5a93f5 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -477,6 +477,7 @@ typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc); /* gl3w api */ GL3W_API int imgl3wInit(void); GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc); +GL3W_API void imgl3wShutdown(void); GL3W_API int imgl3wIsSupported(int major, int minor); GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc); @@ -632,7 +633,7 @@ extern "C" { #endif #include -static HMODULE libgl; +static HMODULE libgl = NULL; typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR); static GL3WglGetProcAddr wgl_get_proc_address; @@ -645,7 +646,7 @@ static int open_libgl(void) return GL3W_OK; } -static void close_libgl(void) { FreeLibrary(libgl); } +static void close_libgl(void) { FreeLibrary(libgl); libgl = NULL; } static GL3WglProc get_proc(const char *proc) { GL3WglProc res; @@ -657,7 +658,7 @@ static GL3WglProc get_proc(const char *proc) #elif defined(__APPLE__) #include -static void *libgl; +static void *libgl = NULL; static int open_libgl(void) { libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL); @@ -666,7 +667,7 @@ static int open_libgl(void) return GL3W_OK; } -static void close_libgl(void) { dlclose(libgl); } +static void close_libgl(void) { dlclose(libgl); libgl = NULL; } static GL3WglProc get_proc(const char *proc) { @@ -834,6 +835,11 @@ int imgl3wInit2(GL3WGetProcAddressProc proc) return parse_version(); } +void imgl3wShutdown(void) +{ + close_libgl(); +} + int imgl3wIsSupported(int major, int minor) { if (major < 2) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index da2162b9f..edc43247a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Other Changes: and TableSetBgColor() calls. (#1651, #8499) - Misc: removed more redundant inline static linkage from imgui_internal.h to facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] +- Backends: OpenGL3: add and call embedded loader shutdown in ImGui_ImplOpenGL3_Shutdown() + to facilitate multiple init/shutdown cycles in same process. (#8792) [@tim-rex] - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) [@Daandelange] From c96e9c82739944ac38e2efbc056697d24c18e2e2 Mon Sep 17 00:00:00 2001 From: scribam Date: Sun, 20 Jul 2025 18:04:57 +0200 Subject: [PATCH 1187/2359] CI: Update Windows CI to use a more recent SDL2. (#8819, #8778) --- .github/workflows/build.yml | 6 +++--- docs/CHANGELOG.txt | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 95bcf3e76..13cc0b88b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,9 +27,9 @@ jobs: - name: Install Dependencies shell: powershell run: | - Invoke-WebRequest -Uri "https://www.libsdl.org/release/SDL2-devel-2.26.3-VC.zip" -OutFile "SDL2-devel-2.26.3-VC.zip" - Expand-Archive -Path SDL2-devel-2.26.3-VC.zip - echo "SDL2_DIR=$(pwd)\SDL2-devel-2.26.3-VC\SDL2-2.26.3\" >>${env:GITHUB_ENV} + Invoke-WebRequest -Uri "https://www.libsdl.org/release/SDL2-devel-2.32.8-VC.zip" -OutFile "SDL2-devel-2.32.8-VC.zip" + Expand-Archive -Path SDL2-devel-2.32.8-VC.zip + echo "SDL2_DIR=$(pwd)\SDL2-devel-2.32.8-VC\SDL2-2.32.8\" >>${env:GITHUB_ENV} Invoke-WebRequest -Uri "https://github.com/ocornut/imgui/files/3789205/vulkan-sdk-1.1.121.2.zip" -OutFile vulkan-sdk-1.1.121.2.zip Expand-Archive -Path vulkan-sdk-1.1.121.2.zip diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index edc43247a..a2b749e72 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,7 @@ Other Changes: and TableSetBgColor() calls. (#1651, #8499) - Misc: removed more redundant inline static linkage from imgui_internal.h to facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] +- CI: Update Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] - Backends: OpenGL3: add and call embedded loader shutdown in ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) [@tim-rex] - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating From 7babc24ad4ef7091b76fa94ef91277bc5154d3a6 Mon Sep 17 00:00:00 2001 From: scribam Date: Sun, 20 Jul 2025 18:08:11 +0200 Subject: [PATCH 1188/2359] CI: Add SDL3 builds to MacOS and Windows. (#8819, #8778) --- .github/workflows/build.yml | 48 ++++++++++++++++++++++++++++++++++++- docs/CHANGELOG.txt | 3 ++- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 13cc0b88b..0eb409247 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -30,6 +30,10 @@ jobs: Invoke-WebRequest -Uri "https://www.libsdl.org/release/SDL2-devel-2.32.8-VC.zip" -OutFile "SDL2-devel-2.32.8-VC.zip" Expand-Archive -Path SDL2-devel-2.32.8-VC.zip echo "SDL2_DIR=$(pwd)\SDL2-devel-2.32.8-VC\SDL2-2.32.8\" >>${env:GITHUB_ENV} + + Invoke-WebRequest -Uri "https://www.libsdl.org/release/SDL3-devel-3.2.18-VC.zip" -OutFile "SDL3-devel-3.2.18-VC.zip" + Expand-Archive -Path SDL3-devel-3.2.18-VC.zip + echo "SDL3_DIR=$(pwd)\SDL3-devel-3.2.18-VC\SDL3-3.2.18\" >>${env:GITHUB_ENV} Invoke-WebRequest -Uri "https://github.com/ocornut/imgui/files/3789205/vulkan-sdk-1.1.121.2.zip" -OutFile vulkan-sdk-1.1.121.2.zip Expand-Archive -Path vulkan-sdk-1.1.121.2.zip @@ -140,6 +144,25 @@ jobs: run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj /p:Platform=Win32 /p:Configuration=Release' if: github.event_name == 'workflow_run' + - name: Build Win32 example_sdl3_opengl3 + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj /p:Platform=Win32 /p:Configuration=Release' + + - name: Build Win32 example_sdl3_sdlgpu3 + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + + - name: Build Win32 example_sdl3_sdlrenderer3 + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + + - name: Build Win32 example_sdl3_vulkan + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + - name: Build Win32 example_win32_directx9 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx9/example_win32_directx9.vcxproj /p:Platform=Win32 /p:Configuration=Release' @@ -190,6 +213,26 @@ jobs: shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj /p:Platform=x64 /p:Configuration=Release' + - name: Build x64 example_sdl3_opengl3 + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj /p:Platform=x64 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + + - name: Build x64 example_sdl3_sdlgpu3 + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj /p:Platform=x64 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + + - name: Build x64 example_sdl3_sdlrenderer3 + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj /p:Platform=x64 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + + - name: Build x64 example_sdl3_vulkan + shell: cmd + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' + if: github.event_name == 'workflow_run' + - name: Build x64 example_win32_directx9 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx9/example_win32_directx9.vcxproj /p:Platform=x64 /p:Configuration=Release' @@ -433,7 +476,7 @@ jobs: - name: Install Dependencies run: | - brew install glfw3 sdl2 + brew install glfw3 sdl2 sdl3 - name: Build example_null (extra warnings, clang 64-bit) run: make -C examples/example_null WITH_EXTRA_WARNINGS=1 @@ -491,6 +534,9 @@ jobs: - name: Build example_sdl2_opengl3 run: make -C examples/example_sdl2_opengl3 + - name: Build example_sdl3_opengl3 + run: make -C examples/example_sdl3_opengl3 + - name: Build example_apple_metal run: xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_macos diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a2b749e72..5626bb3e5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,7 +50,8 @@ Other Changes: and TableSetBgColor() calls. (#1651, #8499) - Misc: removed more redundant inline static linkage from imgui_internal.h to facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] -- CI: Update Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] +- CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] +- CI: Updated Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] - Backends: OpenGL3: add and call embedded loader shutdown in ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) [@tim-rex] - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating From 06ab541e2fc182c35b59cd4b011f2afdc7924b7f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Jul 2025 17:01:26 +0900 Subject: [PATCH 1189/2359] CI: Adjust policies to more frequently build Win64 SDL3+SDL_Renderer, SDL3+SDL_GPU, and tweak others. --- .github/workflows/build.yml | 41 ++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0eb409247..bb2e502a2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -106,9 +106,12 @@ jobs: cl.exe /D_USRDLL /D_WINDLL /I. example_single_file.cpp /LD /FeImGui.dll /link cl.exe /DIMGUI_API=__declspec(dllimport) /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp + # Win64 examples are more frequently compilted than the Win32 examples. + # More of the Win32 examples requires 'workflow_run' to reduce waste. - name: Build Win32 example_glfw_opengl2 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - name: Build Win32 example_glfw_opengl3 shell: cmd @@ -166,89 +169,89 @@ jobs: - name: Build Win32 example_win32_directx9 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx9/example_win32_directx9.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - name: Build Win32 example_win32_directx10 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx10/example_win32_directx10.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - name: Build Win32 example_win32_directx11 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx11/example_win32_directx11.vcxproj /p:Platform=Win32 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_glfw_opengl2 + # Windows 64-bits + - name: Build Win64 example_glfw_opengl2 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_glfw_opengl3 + - name: Build Win64 example_glfw_opengl3 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj /p:Platform=x64 /p:Configuration=Release' - - name: Build x64 example_glfw_vulkan + - name: Build Win64 example_glfw_vulkan shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' - - name: Build x64 example_sdl2_sdlrenderer2 + - name: Build Win64 example_sdl2_sdlrenderer2 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl2_vulkan + - name: Build Win64 example_sdl2_vulkan shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl2_opengl2 + - name: Build Win64 example_sdl2_opengl2 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl2_opengl3 + - name: Build Win64 example_sdl2_opengl3 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl2_directx11 + - name: Build Win64 example_sdl2_directx11 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj /p:Platform=x64 /p:Configuration=Release' - - name: Build x64 example_sdl3_opengl3 + - name: Build Win64 example_sdl3_opengl3 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl3_sdlgpu3 + - name: Build Win64 example_sdl3_sdlgpu3 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl3_sdlrenderer3 + - name: Build Win64 example_sdl3_sdlrenderer3 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl3_vulkan + - name: Build Win64 example_sdl3_vulkan shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl3_vulkan/example_sdl3_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_win32_directx9 + - name: Build Win64 example_win32_directx9 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx9/example_win32_directx9.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_win32_directx10 + - name: Build Win64 example_win32_directx10 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx10/example_win32_directx10.vcxproj /p:Platform=x64 /p:Configuration=Release' if: github.event_name == 'workflow_run' - - name: Build x64 example_win32_directx11 + - name: Build Win64 example_win32_directx11 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx11/example_win32_directx11.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'workflow_run' - - name: Build x64 example_win32_directx12 + - name: Build Win64 example_win32_directx12 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' From 8403c49484d7962fdd7395de090716a6f2dd9cef Mon Sep 17 00:00:00 2001 From: Shi Yan Date: Tue, 22 Jul 2025 18:28:12 -0500 Subject: [PATCH 1190/2359] Examples: SDL3+Metal: Added example. (#8827, #8825) --- examples/example_sdl3_metal/Makefile | 48 +++++++ examples/example_sdl3_metal/main.mm | 188 +++++++++++++++++++++++++++ 2 files changed, 236 insertions(+) create mode 100644 examples/example_sdl3_metal/Makefile create mode 100644 examples/example_sdl3_metal/main.mm diff --git a/examples/example_sdl3_metal/Makefile b/examples/example_sdl3_metal/Makefile new file mode 100644 index 000000000..9093ae133 --- /dev/null +++ b/examples/example_sdl3_metal/Makefile @@ -0,0 +1,48 @@ +# +# You will need SDL3 (http://www.libsdl.org): +# brew install sdl3 +# + +#CXX = g++ +#CXX = clang++ + +EXE = example_sdl3_metal +IMGUI_DIR = ../.. +SOURCES = main.mm +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl3.cpp $(IMGUI_DIR)/backends/imgui_impl_metal.mm +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) + +LIBS = -framework Metal -framework MetalKit -framework Cocoa -framework IOKit -framework CoreVideo -framework QuartzCore +LIBS += `pkg-config --libs sdl3` +LIBS += -L/usr/local/lib -L/opt/local/lib + +CXXFLAGS += `pkg-config --cflags sdl3` +CXXFLAGS += -I/usr/local/include -I/opt/local/include +CXXFLAGS += -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS += -Wall -Wformat +CFLAGS = $(CXXFLAGS) + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:%.mm + $(CXX) $(CXXFLAGS) -ObjC++ -fobjc-weak -fobjc-arc -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.mm + $(CXX) $(CXXFLAGS) -ObjC++ -fobjc-weak -fobjc-arc -c -o $@ $< + +all: $(EXE) + @echo Build complete + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm new file mode 100644 index 000000000..b847cbed4 --- /dev/null +++ b/examples/example_sdl3_metal/main.mm @@ -0,0 +1,188 @@ +// Dear ImGui: standalone example application for SDL3 + Metal +// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#include "imgui.h" +#include "imgui_impl_sdl3.h" +#include "imgui_impl_metal.h" +#include +#include + +#import +#import + +int main(int, char**) +{ + // Setup SDL + // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function] + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) + { + printf("Error: SDL_Init(): %s\n", SDL_GetError()); + return -1; + } + + float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); + SDL_WindowFlags window_flags = SDL_WINDOW_METAL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; + SDL_Window *window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + SDL_ShowWindow(window); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + + // Setup Platform/Renderer backends + // Create Metal device BEFORE creating the view/layer + id metalDevice = MTLCreateSystemDefaultDevice(); + if (!metalDevice) + { + printf("Error: failed to create Metal device.\n"); + SDL_DestroyWindow(window); + SDL_Quit(); + return -1; + } + + SDL_MetalView view = SDL_Metal_CreateView(window); + CAMetalLayer* layer = (__bridge CAMetalLayer*)SDL_Metal_GetLayer(view); + layer.device = metalDevice; + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + ImGui_ImplMetal_Init(layer.device); + + ImGui_ImplSDL3_InitForMetal(window); + + id commandQueue = [layer.device newCommandQueue]; + MTLRenderPassDescriptor* renderPassDescriptor = [MTLRenderPassDescriptor new]; + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + float clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f}; + + // Main loop + bool done = false; + while (!done) + { + @autoreleasepool + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL3_ProcessEvent(&event); + if (event.type == SDL_EVENT_QUIT) + done = true; + if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) + done = true; + } + + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function] + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } + + int width, height; + SDL_GetWindowSizeInPixels(window, &width, &height); + + layer.drawableSize = CGSizeMake(width, height); + id drawable = [layer nextDrawable]; + + id commandBuffer = [commandQueue commandBuffer]; + renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color[0] * clear_color[3], clear_color[1] * clear_color[3], clear_color[2] * clear_color[3], clear_color[3]); + renderPassDescriptor.colorAttachments[0].texture = drawable.texture; + renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear; + renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore; + id renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor]; + [renderEncoder pushDebugGroup:@"ImGui demo"]; + + // Start the Dear ImGui frame + ImGui_ImplMetal_NewFrame(renderPassDescriptor); + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + ImGui_ImplMetal_RenderDrawData(ImGui::GetDrawData(), commandBuffer, renderEncoder); + + [renderEncoder popDebugGroup]; + [renderEncoder endEncoding]; + + [commandBuffer presentDrawable:drawable]; + [commandBuffer commit]; + } + } + + // Cleanup + ImGui_ImplMetal_Shutdown(); + ImGui_ImplSDL3_Shutdown(); + ImGui::DestroyContext(); + + SDL_DestroyWindow(window); + SDL_Quit(); + + return 0; +} From 4f007740065ca53e9da6a7c8fc970b180fe84d9f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Jul 2025 16:11:44 +0900 Subject: [PATCH 1191/2359] Examples: SDL3+Metal: Amend example. (#8827, #8825) Amend 8403c49 --- .gitignore | 1 + docs/CHANGELOG.txt | 1 + docs/EXAMPLES.md | 4 ++ examples/example_sdl3_metal/main.mm | 62 +++++++++++++++++--------- examples/example_sdl3_sdlgpu3/main.cpp | 3 +- 5 files changed, 49 insertions(+), 22 deletions(-) diff --git a/.gitignore b/.gitignore index 6f6c50cb4..a3faf78bb 100644 --- a/.gitignore +++ b/.gitignore @@ -68,6 +68,7 @@ examples/example_sdl2_opengl2/example_sdl2_opengl2 examples/example_sdl2_opengl3/example_sdl2_opengl3 examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2 examples/example_sdl2_vulkan/example_sdl2_vulkan +examples/example_sdl3_metal/example_sdl3_metal examples/example_sdl3_opengl3/example_sdl3_opengl3 examples/example_sdl3_sdlgpu3/example_sdl3_sdlgpu3 examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3 diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5626bb3e5..586cd831b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,7 @@ Other Changes: facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] - CI: Updated Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] +- Examples: SDL3+Metal: added SDL3+Metal example. (#8827, #8825) [@shi-yan] - Backends: OpenGL3: add and call embedded loader shutdown in ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) [@tim-rex] - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index 20851c158..038bd5858 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -149,6 +149,10 @@ SDL2 (Win32, Mac, Linux, etc.) + Vulkan example.
This is quite long and tedious, because: Vulkan.
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. +[example_sdl3_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_metal/)
+SDL3 + Metal example (Mac).
+= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_metal.mm
+ [example_sdl3_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_opengl3/)
SDL3 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example.
= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_opengl3.cpp
diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index b847cbed4..50c33c82d 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -10,12 +10,13 @@ #include "imgui.h" #include "imgui_impl_sdl3.h" #include "imgui_impl_metal.h" -#include +#include // printf, fprintf #include #import #import +// Main code int main(int, char**) { // Setup SDL @@ -26,9 +27,10 @@ int main(int, char**) return -1; } + // Create SDL window graphics context float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_METAL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window *window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Metal example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -37,6 +39,23 @@ int main(int, char**) SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_ShowWindow(window); + // Create Metal device _before_ creating the view/layer + id metalDevice = MTLCreateSystemDefaultDevice(); + if (!metalDevice) + { + printf("Error: failed to create Metal device.\n"); + SDL_DestroyWindow(window); + SDL_Quit(); + return -1; + } + SDL_MetalView view = SDL_Metal_CreateView(window); + CAMetalLayer* layer = (__bridge CAMetalLayer*)SDL_Metal_GetLayer(view); + layer.device = metalDevice; + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + + id commandQueue = [layer.device newCommandQueue]; + MTLRenderPassDescriptor* renderPassDescriptor = [MTLRenderPassDescriptor new]; + // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); @@ -54,31 +73,29 @@ int main(int, char**) style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) // Setup Platform/Renderer backends - // Create Metal device BEFORE creating the view/layer - id metalDevice = MTLCreateSystemDefaultDevice(); - if (!metalDevice) - { - printf("Error: failed to create Metal device.\n"); - SDL_DestroyWindow(window); - SDL_Quit(); - return -1; - } - - SDL_MetalView view = SDL_Metal_CreateView(window); - CAMetalLayer* layer = (__bridge CAMetalLayer*)SDL_Metal_GetLayer(view); - layer.device = metalDevice; - layer.pixelFormat = MTLPixelFormatBGRA8Unorm; ImGui_ImplMetal_Init(layer.device); - ImGui_ImplSDL3_InitForMetal(window); - id commandQueue = [layer.device newCommandQueue]; - MTLRenderPassDescriptor* renderPassDescriptor = [MTLRenderPassDescriptor new]; + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; bool show_another_window = false; - float clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f}; + float clear_color[4] = { 0.45f, 0.55f, 0.60f, 1.00f }; // Main loop bool done = false; @@ -91,6 +108,7 @@ int main(int, char**) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function] SDL_Event event; while (SDL_PollEvent(&event)) { @@ -166,7 +184,8 @@ int main(int, char**) // Rendering ImGui::Render(); - ImGui_ImplMetal_RenderDrawData(ImGui::GetDrawData(), commandBuffer, renderEncoder); + ImDrawData* draw_data = ImGui::GetDrawData(); + ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder); [renderEncoder popDebugGroup]; [renderEncoder endEncoding]; @@ -177,6 +196,7 @@ int main(int, char**) } // Cleanup + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function] ImGui_ImplMetal_Shutdown(); ImGui_ImplSDL3_Shutdown(); ImGui::DestroyContext(); diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 581b11c11..649fde9f5 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -1,4 +1,5 @@ // Dear ImGui: standalone example application for SDL3 + SDL_GPU +// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq @@ -154,7 +155,7 @@ int main(int, char**) ImGui::Checkbox("Another Window", &show_another_window); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit4("clear color", (float*)&clear_color); // Edit 3 floats representing a color + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) counter++; From 174f37bdaf87aff066f0332778dcfee016b44073 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Jul 2025 16:17:35 +0900 Subject: [PATCH 1192/2359] Fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 34 ++++++++++++++++++++-------------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 586cd831b..3c2e13300 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,7 @@ Other Changes: selected), impacting code not checking for BeginChild() return value. (#8815) - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) +- Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) - Misc: removed more redundant inline static linkage from imgui_internal.h to facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] diff --git a/imgui.cpp b/imgui.cpp index 769fd44df..918105f26 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15665,10 +15665,14 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImG //----------------------------------------------------------------------------- // [SECTION] METRICS/DEBUGGER WINDOW //----------------------------------------------------------------------------- +// - MetricsHelpMarker() [Internal] // - DebugRenderViewportThumbnail() [Internal] // - RenderViewportsThumbnails() [Internal] +// - DebugRenderKeyboardPreview() [Internal] // - DebugTextEncoding() -// - MetricsHelpMarker() [Internal] +// - DebugFlashStyleColorStop() [Internal] +// - DebugFlashStyleColor() +// - UpdateDebugToolFlashStyleColor() [Internal] // - ShowFontAtlas() [Internal but called by Demo!] // - DebugNodeTexture() [Internal] // - ShowMetricsWindow() @@ -15686,6 +15690,21 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImG // - DebugNodeWindowsListByBeginStackParent() [Internal] //----------------------------------------------------------------------------- +#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) +// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. +static void MetricsHelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::BeginItemTooltip()) + { + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} +#endif + #ifndef IMGUI_DISABLE_DEBUG_TOOLS void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb) @@ -15874,19 +15893,6 @@ static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, const return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), cmd->TexRef.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID() } -// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. -static void MetricsHelpMarker(const char* desc) -{ - ImGui::TextDisabled("(?)"); - if (ImGui::BeginItemTooltip()) - { - ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); - ImGui::TextUnformatted(desc); - ImGui::PopTextWrapPos(); - ImGui::EndTooltip(); - } -} - #ifdef IMGUI_ENABLE_FREETYPE namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); } #endif From b88453395741a4debdc5960c129ef49db188dd01 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Jul 2025 16:30:30 +0900 Subject: [PATCH 1193/2359] Document/workaround an issue using IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION since 1.92.0. (#8794) --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 9 +++++++++ imstb_truetype.h | 9 ++++++--- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3c2e13300..cb733b594 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) +- Misc: document/workaround an issue using IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION + since 1.92.0. (#8794) [@tim-rex] - Misc: removed more redundant inline static linkage from imgui_internal.h to facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5cb0ef8b5..93008fde9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4622,6 +4622,15 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig return true; } +// Since 1.92.0 (June 2025) we rely on those 3 functions which are implemented inside stb_truetype.h and require STB_TRUETYPE_IMPLEMENTATION. +// Using IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION became broken, see https://github.com/ocornut/imgui/issues/8794 +// One way to fix is to remove the 'static' keywords for those 3 functions in your copy of stb_truetype.h +#ifdef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +extern void stbtt__h_prefilter(unsigned char* pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width); +extern void stbtt__v_prefilter(unsigned char* pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width); +extern float stbtt__oversample_shift(int oversample); +#endif + static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) { // Search for first font which has the glyph diff --git a/imstb_truetype.h b/imstb_truetype.h index cf33289f6..1a2778773 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -4017,7 +4017,8 @@ STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int s #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) -static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +/*static*/ +void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; @@ -4079,7 +4080,8 @@ static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_i } } -static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +/*static*/ +void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; @@ -4141,7 +4143,8 @@ static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_i } } -static float stbtt__oversample_shift(int oversample) +/*static*/ +float stbtt__oversample_shift(int oversample) { if (!oversample) return 0.0f; From 19d1ad04f4b4b0be10656eb654a43f5201511869 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Jul 2025 16:42:00 +0900 Subject: [PATCH 1194/2359] Fonts: stop using stb_truetype.h implementation functions. Fix using IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION. (#8794) --- docs/CHANGELOG.txt | 3 +-- imgui_draw.cpp | 24 ++++++------------------ 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cb733b594..543f784ae 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,8 +49,7 @@ Other Changes: - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) -- Misc: document/workaround an issue using IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION - since 1.92.0. (#8794) [@tim-rex] +- Misc: fixed building with IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION. (#8794) - Misc: removed more redundant inline static linkage from imgui_internal.h to facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 93008fde9..ed6a91ab3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4622,15 +4622,6 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig return true; } -// Since 1.92.0 (June 2025) we rely on those 3 functions which are implemented inside stb_truetype.h and require STB_TRUETYPE_IMPLEMENTATION. -// Using IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION became broken, see https://github.com/ocornut/imgui/issues/8794 -// One way to fix is to remove the 'static' keywords for those 3 functions in your copy of stb_truetype.h -#ifdef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION -extern void stbtt__h_prefilter(unsigned char* pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width); -extern void stbtt__v_prefilter(unsigned char* pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width); -extern float stbtt__oversample_shift(int oversample); -#endif - static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) { // Search for first font which has the glyph @@ -4688,15 +4679,12 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC builder->TempBuffer.resize(w * h * 1); unsigned char* bitmap_pixels = builder->TempBuffer.Data; memset(bitmap_pixels, 0, w * h * 1); - stbtt_MakeGlyphBitmapSubpixel(&bd_font_data->FontInfo, bitmap_pixels, r->w - oversample_h + 1, r->h - oversample_v + 1, w, - scale_for_raster_x, scale_for_raster_y, 0, 0, glyph_index); - // Oversampling + // Render with oversampling // (those functions conveniently assert if pixels are not cleared, which is another safety layer) - if (oversample_h > 1) - stbtt__h_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_h); - if (oversample_v > 1) - stbtt__v_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_v); + float sub_x, sub_y; + stbtt_MakeGlyphBitmapSubpixelPrefilter(&bd_font_data->FontInfo, bitmap_pixels, w, h, w, + scale_for_raster_x, scale_for_raster_y, 0, 0, oversample_h, oversample_v, &sub_x, &sub_y, glyph_index); const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; @@ -4706,8 +4694,8 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC font_off_x = IM_ROUND(font_off_x); if (src->PixelSnapV) font_off_y = IM_ROUND(font_off_y); - font_off_x += stbtt__oversample_shift(oversample_h); - font_off_y += stbtt__oversample_shift(oversample_v) + IM_ROUND(baked->Ascent); + font_off_x += sub_x; + font_off_y += sub_y + IM_ROUND(baked->Ascent); float recip_h = 1.0f / (oversample_h * rasterizer_density); float recip_v = 1.0f / (oversample_v * rasterizer_density); From 075ad676aadc8ad70b6ffa949408dd093d6f213d Mon Sep 17 00:00:00 2001 From: Ori Avtalion Date: Fri, 25 Jul 2025 11:36:23 +0300 Subject: [PATCH 1195/2359] Demo: Fix '= =' typo in text (#8836) --- imgui_demo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6bc8968a4..6063a3c6c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2170,7 +2170,7 @@ static void DemoWindowWidgetsQueryingStatuses() ); ImGui::BulletText( "with Hovering Delay or Stationary test:\n" - "IsItemHovered() = = %d\n" + "IsItemHovered() = %d\n" "IsItemHovered(_Stationary) = %d\n" "IsItemHovered(_DelayShort) = %d\n" "IsItemHovered(_DelayNormal) = %d\n" From 853a46e021dfd58a7945b0b7561d658963be776f Mon Sep 17 00:00:00 2001 From: Miolith Date: Sat, 26 Jul 2025 15:54:56 +0200 Subject: [PATCH 1196/2359] Backends: Vulkan: fixed texture update corruption introduced in 1.92.0. (#8801, #8755, #8840, #8465) Fix abe294bfd0bf --- backends/imgui_impl_vulkan.cpp | 3 ++- docs/CHANGELOG.txt | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 1120b4b5e..f89ff5176 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-07-27: Vulkan: Fixed texture update corruption introduced on 2025-06-11. (#8801, #8755, #8840) // 2025-07-07: Vulkan: Fixed texture synchronization issue introduced on 2025-06-11. (#8772) // 2025-06-27: Vulkan: Fixed validation errors during texture upload/update by aligning upload size to 'nonCoherentAtomSize'. (#8743, #8744) // 2025-06-11: Vulkan: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_DestroyFontsTexture(). @@ -818,7 +819,7 @@ void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) VkImageMemoryBarrier copy_barrier[1] = {}; copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + copy_barrier[0].oldLayout = (tex->Status == ImTextureStatus_WantCreate) ? VK_IMAGE_LAYOUT_UNDEFINED : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 543f784ae..38d1dc985 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,8 @@ Other Changes: to facilitate multiple init/shutdown cycles in same process. (#8792) [@tim-rex] - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) [@Daandelange] +- Backends: Vulkan: Fixed texture update corruption introduced in 1.92.0, + affecting some drivers/setups. (#8801, #8755, #8840) [@Retro52, @Miolith] ----------------------------------------------------------------------- From da6c97203e4f80a5ff93197709b504ec9d4a4116 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 27 Jul 2025 19:37:30 +0900 Subject: [PATCH 1197/2359] Fixed comments for io.KeyCtrl / io.KeySuper to match the one for ImGuiMod_Ctrl, ImGuiMod_Super. (#8839) --- imgui.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 4caa4e134..7108f636b 100644 --- a/imgui.h +++ b/imgui.h @@ -2514,10 +2514,10 @@ struct ImGuiIO float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold SHIFT to turn vertical scroll into horizontal scroll. float MouseWheelH; // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends. ImGuiMouseSource MouseSource; // Mouse actual input peripheral (Mouse/TouchScreen/Pen). - bool KeyCtrl; // Keyboard modifier down: Control + bool KeyCtrl; // Keyboard modifier down: Ctrl (non-macOS), Cmd (macOS) bool KeyShift; // Keyboard modifier down: Shift bool KeyAlt; // Keyboard modifier down: Alt - bool KeySuper; // Keyboard modifier down: Cmd/Super/Windows + bool KeySuper; // Keyboard modifier down: Windows/Super (non-macOS), Ctrl (macOS) // Other state maintained from data above + IO function calls ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. Read-only, updated by NewFrame() From c6c0c3be08007217a9dccc5e33aecc3cd9f4c042 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 27 Jul 2025 20:15:21 +0900 Subject: [PATCH 1198/2359] Docs: amend 1.92.0 logs on the fact that font->CalcTextSizeA() used to be thread-safe. --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 2 ++ 2 files changed, 6 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 38d1dc985..8d4dc5cf7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -190,6 +190,10 @@ Breaking changes: - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate understanding which font input is providing which glyph. +- Fonts: **IMPORTANT** on Thread Safety: + - A few functions such as font->CalcTextSizeA() were by sheer luck (== accidentally) + thread-safe even thou we had never provided that guarantee before. They are + definitively not thread-safe anymore as new glyphs may be loaded. - Textures: - All API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef': diff --git a/imgui.cpp b/imgui.cpp index 918105f26..87e6cbd79 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -432,6 +432,8 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: cfg2.MergeMode = true; io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate unde + - Fonts: **IMPORTANT** on Thread Safety: + - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded. - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font". - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. From 10dc1882c85390be1d5185cf18e4082a2f02f6ea Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 27 Jul 2025 20:23:36 +0900 Subject: [PATCH 1199/2359] Fonts: (Internal) rename ImFontBaked::LockLoadingFallback to ImFontBaked::LoadNoFallback. --- imgui.h | 6 +++--- imgui_draw.cpp | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 7108f636b..f060277d3 100644 --- a/imgui.h +++ b/imgui.h @@ -3745,10 +3745,10 @@ struct ImFontBaked // [Internal] Members: Cold float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) unsigned int MetricsTotalSurface:26;// 3 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) - unsigned int WantDestroy:1; // 0 // // Queued for destroy - unsigned int LockLoadingFallback:1; // 0 // // + unsigned int WantDestroy:1; // 0 // // Queued for destroy + unsigned int LoadNoFallback:1; // 0 // // Disable loading fallback in lower-level calls. int LastUsedFrame; // 4 // // Record of that time this was bounds - ImGuiID BakedId; // 4 // + ImGuiID BakedId; // 4 // // Unique ID for this baked storage ImFont* ContainerFont; // 4-8 // in // Parent font void* FontLoaderDatas; // 4-8 // // Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ed6a91ab3..bd7455d78 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4417,7 +4417,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep if (atlas->Locked || (font->Flags & ImFontFlags_NoLoadGlyphs)) { // Lazily load fallback glyph - if (baked->FallbackGlyphIndex == -1 && baked->LockLoadingFallback == 0) + if (baked->FallbackGlyphIndex == -1 && baked->LoadNoFallback == 0) ImFontAtlasBuildSetupFontBakedFallback(baked); return NULL; } @@ -4469,7 +4469,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep } // Lazily load fallback glyph - if (baked->LockLoadingFallback) + if (baked->LoadNoFallback) return NULL; if (baked->FallbackGlyphIndex == -1) ImFontAtlasBuildSetupFontBakedFallback(baked); @@ -5222,9 +5222,9 @@ ImFontGlyph* ImFontBaked::FindGlyphNoFallback(ImWchar c) if (i != IM_FONTGLYPH_INDEX_UNUSED) return &Glyphs.Data[i]; } - LockLoadingFallback = true; // This is actually a rare call, not done in hot-loop, so we prioritize not adding extra cruft to ImFontBaked_BuildLoadGlyph() call sites. + LoadNoFallback = true; // This is actually a rare call, not done in hot-loop, so we prioritize not adding extra cruft to ImFontBaked_BuildLoadGlyph() call sites. ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL); - LockLoadingFallback = false; + LoadNoFallback = false; return glyph; } From 87d7f7744efe63e77f4d0e00ccb5f6affd12aca7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 27 Jul 2025 20:33:57 +0900 Subject: [PATCH 1200/2359] Fonts: (Internal) Added undocumented ImFontBaked::LoadNoRenderOnLayout. (#8758, #8465) Amend fd75bdccb0. --- imgui.h | 7 ++++--- imgui_draw.cpp | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui.h b/imgui.h index f060277d3..62a3a309b 100644 --- a/imgui.h +++ b/imgui.h @@ -3745,9 +3745,10 @@ struct ImFontBaked // [Internal] Members: Cold float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) unsigned int MetricsTotalSurface:26;// 3 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) - unsigned int WantDestroy:1; // 0 // // Queued for destroy - unsigned int LoadNoFallback:1; // 0 // // Disable loading fallback in lower-level calls. - int LastUsedFrame; // 4 // // Record of that time this was bounds + unsigned int WantDestroy:1; // 0 // // Queued for destroy + unsigned int LoadNoFallback:1; // 0 // // Disable loading fallback in lower-level calls. + unsigned int LoadNoRenderOnLayout:1;// 0 // // Enable a two-steps mode where CalcTextSize() calls will load AdvanceX *without* rendering/packing glyphs. Only advantagous if you know that the glyph is unlikely to actually be rendered, otherwise it is slower because we'd do one query on the first CalcTextSize and one query on the first Draw. + int LastUsedFrame; // 4 // // Record of that time this was bounds ImGuiID BakedId; // 4 // // Unique ID for this baked storage ImFont* ContainerFont; // 4-8 // in // Parent font void* FontLoaderDatas; // 4-8 // // Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bd7455d78..64f9a9f7a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4483,7 +4483,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep static float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint) { - if (baked->Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE) + if (baked->Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE || baked->LoadNoRenderOnLayout) { // First load AdvanceX value used by CalcTextSize() API then load the rest when loaded by drawing API. float only_advance_x = 0.0f; From 2ab3946ecb12962eff96c9bc13ef83d403c84dd8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Jul 2025 18:39:15 +0900 Subject: [PATCH 1201/2359] Windows: add StopMouseMovingWindow(), partial merge 80d78fa from docking. --- imgui.cpp | 36 ++++++++++++++++++++++++++---------- imgui_internal.h | 1 + 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 87e6cbd79..6c1e688e2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4503,15 +4503,6 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) // Clear previous active id if (g.ActiveId != 0) { - // While most behaved code would make an effort to not steal active id during window move/drag operations, - // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch - // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that. - if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId) - { - IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n"); - g.MovingWindow = NULL; - } - // Store deactivate data ImGuiDeactivatedItemData* deactivated_data = &g.DeactivatedItemData; deactivated_data->ID = g.ActiveId; @@ -4524,6 +4515,15 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveID() if (g.InputTextState.ID == g.ActiveId) InputTextDeactivateHook(g.ActiveId); + + // While most behaved code would make an effort to not steal active id during window move/drag operations, + // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch + // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that. + if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId) + { + IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n"); + StopMouseMovingWindow(); + } } // Set active id @@ -5077,6 +5077,19 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) g.MovingWindow = window; } +// This is not 100% symetric with StartMouseMovingWindow(). +// We do NOT clear ActiveID, because: +// - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired. +// - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item). +void ImGui::StopMouseMovingWindow() +{ + ImGuiContext& g = *GImGui; + + // [nb: docking branch has more stuff in this function] + + g.MovingWindow = NULL; +} + // Handle mouse moving window // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() // FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId. @@ -5100,7 +5113,7 @@ void ImGui::UpdateMouseMovingWindowNewFrame() } else { - g.MovingWindow = NULL; + StopMouseMovingWindow(); ClearActiveID(); } } @@ -5142,6 +5155,9 @@ void ImGui::UpdateMouseMovingWindowEndFrame() { StartMouseMovingWindow(g.HoveredWindow); //-V595 + // FIXME: In principal we might be able to call StopMouseMovingWindow() below. + // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId. + // Cancel moving if clicked outside of title bar if (g.IO.ConfigWindowsMoveFromTitleBarOnly) if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) diff --git a/imgui_internal.h b/imgui_internal.h index e92ab7b5c..35ffb0d5d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3150,6 +3150,7 @@ namespace ImGui IMGUI_API void UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos); IMGUI_API void FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window); IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); + IMGUI_API void StopMouseMovingWindow(); IMGUI_API void UpdateMouseMovingWindowNewFrame(); IMGUI_API void UpdateMouseMovingWindowEndFrame(); From a0cdac48e00159d5494183d2fd0177889a35d40c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Jul 2025 13:16:51 +0900 Subject: [PATCH 1202/2359] Tables: fixed TableGetHoveredRow() (#7350, #6588, #6250) + TableGetRowIndex() which never correctly worked when using a clipper. Amend e09454aec. Can't understand the comment nor why code was commented. Code looks alright. Compared TableEndRow() between 1.80 and current as well. --- docs/CHANGELOG.txt | 5 +++++ imgui.cpp | 2 +- imgui.h | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8d4dc5cf7..9381e0185 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,11 @@ Other Changes: - Windows: fixed an issue where resizable child windows would emit border logic when hidden/non-visible (e.g. when in a docked window that is not selected), impacting code not checking for BeginChild() return value. (#8815) +- Tables: fixed TableGetRowIndex() which never correctly worked when using + a clipper (it exists for consistency but is almost never used, as it is + often more convenient to use index in caller-code, whereas TableGetRowIndex() + includes header rows). +- Tables: fixed imgui_internal.h's TableGetHoveredRow() the same way. (#7350, #6588, #6250) - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) diff --git a/imgui.cpp b/imgui.cpp index 6c1e688e2..792fb7d99 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3125,7 +3125,7 @@ static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_ ImGui::TableEndRow(table); table->RowPosY2 = window->DC.CursorPos.y; const int row_increase = (int)((off_y / line_height) + 0.5f); - //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow() + table->CurrentRow += row_increase; table->RowBgColorCounter += row_increase; } } diff --git a/imgui.h b/imgui.h index 62a3a309b..5c45b6486 100644 --- a/imgui.h +++ b/imgui.h @@ -916,7 +916,7 @@ namespace ImGui IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable) IMGUI_API int TableGetColumnIndex(); // return current column index. - IMGUI_API int TableGetRowIndex(); // return current row index. + IMGUI_API int TableGetRowIndex(); // return current row index (header rows are accounted for) IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. IMGUI_API void TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) From 046a8eae0ff0854864760b99e0776c904d80b74d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Jul 2025 22:04:01 +0900 Subject: [PATCH 1203/2359] Tabs: fixed tab bar underline not drawing below scroll buttons. (#6820, #4859, #5022, #5239) Fix ef8ff1b5d8 which accidentally meant we are using BarRect after it may have been modified by TabBarScrollingButtons(). --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9381e0185..d3c5d6609 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,8 @@ Other Changes: often more convenient to use index in caller-code, whereas TableGetRowIndex() includes header rows). - Tables: fixed imgui_internal.h's TableGetHoveredRow() the same way. (#7350, #6588, #6250) +- Tabs: fixed tab bar underline not drawing below scroll buttons, when + they are enabled (minor regression from 1.90). (#6820, #4859, #5022, #5239) - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 63dd9dc21..b4d5bc1d7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9429,8 +9429,8 @@ bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id); ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); tab_bar->ID = id; - tab_bar->SeparatorMinX = tab_bar->BarRect.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f); - tab_bar->SeparatorMaxX = tab_bar->BarRect.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f); + tab_bar->SeparatorMinX = tab_bar_bb.x - IM_TRUNC(window->WindowPadding.x * 0.5f); + tab_bar->SeparatorMaxX = tab_bar_bb.x + IM_TRUNC(window->WindowPadding.x * 0.5f); //if (g.NavWindow && IsWindowChildOf(g.NavWindow, window, false, false)) flags |= ImGuiTabBarFlags_IsFocused; return BeginTabBarEx(tab_bar, tab_bar_bb, flags); @@ -9668,7 +9668,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing; // Horizontal scrolling buttons - // (note that TabBarScrollButtons() will alter BarRect.Max.x) + // Important: note that TabBarScrollButtons() will alter BarRect.Max.x. if ((tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll)) if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar)) { From 7bb9db501cfc4a181cc1f54824517ad28b0941b0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Jul 2025 22:05:19 +0900 Subject: [PATCH 1204/2359] Tabs: fixed 046a8ea (commited a modified file). --- imgui_widgets.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b4d5bc1d7..13aad7459 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9429,8 +9429,8 @@ bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id); ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); tab_bar->ID = id; - tab_bar->SeparatorMinX = tab_bar_bb.x - IM_TRUNC(window->WindowPadding.x * 0.5f); - tab_bar->SeparatorMaxX = tab_bar_bb.x + IM_TRUNC(window->WindowPadding.x * 0.5f); + tab_bar->SeparatorMinX = tab_bar_bb.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f); + tab_bar->SeparatorMaxX = tab_bar_bb.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f); //if (g.NavWindow && IsWindowChildOf(g.NavWindow, window, false, false)) flags |= ImGuiTabBarFlags_IsFocused; return BeginTabBarEx(tab_bar, tab_bar_bb, flags); From 7278cda039b67602905683f2d6add8e0d5abd395 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Jul 2025 22:27:24 +0900 Subject: [PATCH 1205/2359] Tabs: added TabMinWidthBase, ImGuiStyleVar_TabMinWidthBase. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 +++ imgui.h | 2 ++ imgui_demo.cpp | 5 +++-- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 ++ 6 files changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d3c5d6609..a70d9fe56 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,9 @@ Other Changes: - Tables: fixed imgui_internal.h's TableGetHoveredRow() the same way. (#7350, #6588, #6250) - Tabs: fixed tab bar underline not drawing below scroll buttons, when they are enabled (minor regression from 1.90). (#6820, #4859, #5022, #5239) +- Tabs: added style.TabMinWidthBase, ImGuiStyleVar_TabMinWidthBase to control + the base minimum width of a tab (default to 1.0f). This is the size before + any potential shrinking is applied. - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) diff --git a/imgui.cpp b/imgui.cpp index 792fb7d99..bfbf6fe1e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1417,6 +1417,7 @@ ImGuiStyle::ImGuiStyle() ImageBorderSize = 0.0f; // Thickness of border around tabs. TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. + TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. TabCloseButtonMinWidthUnselected = 0.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. @@ -1483,6 +1484,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); + TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor); TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected; TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); @@ -3502,6 +3504,7 @@ static const ImGuiStyleVarInfo GStyleVarsInfo[] = { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle diff --git a/imgui.h b/imgui.h index 5c45b6486..ddce1e2a6 100644 --- a/imgui.h +++ b/imgui.h @@ -1803,6 +1803,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_ImageBorderSize, // float ImageBorderSize ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_TabBorderSize, // float TabBorderSize + ImGuiStyleVar_TabMinWidthBase, // float TabMinWidthBase ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle @@ -2268,6 +2269,7 @@ struct ImGuiStyle float ImageBorderSize; // Thickness of border around Image() calls. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. + float TabMinWidthBase; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. float TabCloseButtonMinWidthSelected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. float TabCloseButtonMinWidthUnselected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. float TabBarBorderSize; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6063a3c6c..c50d3400f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8341,8 +8341,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); - DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); - DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); + DragFloat("TabMinWidthBase", &style.TabMinWidthBase, 0.5f, 1.0f, 500.0f, "%.0f"); + DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.5f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); + DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.5f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); SeparatorText("Tables"); diff --git a/imgui_internal.h b/imgui_internal.h index 35ffb0d5d..ea6bd0c1d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2735,7 +2735,7 @@ struct ImGuiTabItem 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 float Width; // Width currently displayed - float ContentWidth; // Width of label, stored during BeginTabItem() call + float ContentWidth; // Width of label + padding, stored during BeginTabItem() call (misnamed as "Content" would normally imply width of label only) float RequestedWidth; // Width optionally requested by caller, -1.0f is unused ImS32 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 13aad7459..75b4aa633 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9648,6 +9648,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) const char* tab_name = TabBarGetTabName(tab_bar, tab); const bool has_close_button_or_unsaved_marker = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0 || (tab->Flags & ImGuiTabItemFlags_UnsavedDocument); tab->ContentWidth = (tab->RequestedWidth >= 0.0f) ? tab->RequestedWidth : TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x; + if ((tab->Flags & ImGuiTabItemFlags_Button) == 0) + tab->ContentWidth = ImMax(tab->ContentWidth, g.Style.TabMinWidthBase); int section_n = TabItemGetSectionIdx(tab); ImGuiTabBarSection* section = §ions[section_n]; From 78d11cd78117e71bd4f2aec9d2dccd612f48a3f1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Jul 2025 22:41:00 +0900 Subject: [PATCH 1206/2359] Tabs: (Breaking) renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. (#261, #351) Amend 54a60aaa40 --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 ++- imgui.h | 14 ++++++++++---- imgui_demo.cpp | 25 +++++++++++++------------ imgui_widgets.cpp | 2 +- 5 files changed, 29 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a70d9fe56..57ae8d067 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ HOW TO UPDATE? Breaking Changes: +- Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. + Kept inline redirection enum (will obsolete). (#261, #351) + Other Changes: - Windows: fixed an issue where resizable child windows would emit border diff --git a/imgui.cpp b/imgui.cpp index bfbf6fe1e..e4e893041 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -392,7 +392,8 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - - 2025/06/25 (1.92.0) - layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM + - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete). + - 2025/06/25 (1.92.0) - Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150) - Incorrect way to make a window content size 200x200: Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); diff --git a/imgui.h b/imgui.h index ddce1e2a6..ffef8e90a 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.2 WIP" -#define IMGUI_VERSION_NUM 19212 +#define IMGUI_VERSION_NUM 19213 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -1370,10 +1370,16 @@ enum ImGuiTabBarFlags_ ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab ImGuiTabBarFlags_DrawSelectedOverline = 1 << 6, // Draw selected overline markers over selected tab - ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 7, // Resize tabs when they don't fit + + // Fitting/Resize policy + ImGuiTabBarFlags_FittingPolicyShrink = 1 << 7, // Shrink down tabs when they don't fit ImGuiTabBarFlags_FittingPolicyScroll = 1 << 8, // Add scroll buttons when tabs don't fit - ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, - ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown, + ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyShrink | ImGuiTabBarFlags_FittingPolicyScroll, + ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyShrink, + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiTabBarFlags_FittingPolicyResizeDown = ImGuiTabBarFlags_FittingPolicyShrink, // Renamed in 1.92.2 +#endif }; // Flags for ImGui::BeginTabItem() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c50d3400f..e0a9ffc61 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3379,6 +3379,16 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // [SECTION] DemoWindowWidgetsTabs() //----------------------------------------------------------------------------- +static void EditTabBarFittingPolicyFlags(ImGuiTabBarFlags* p_flags) +{ + if ((*p_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) + *p_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyShrink", p_flags, ImGuiTabBarFlags_FittingPolicyShrink)) + *p_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyShrink); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", p_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + *p_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); +} + static void DemoWindowWidgetsTabs() { IMGUI_DEMO_MARKER("Widgets/Tabs"); @@ -3421,12 +3431,7 @@ static void DemoWindowWidgetsTabs() ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); ImGui::CheckboxFlags("ImGuiTabBarFlags_DrawSelectedOverline", &tab_bar_flags, ImGuiTabBarFlags_DrawSelectedOverline); - if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) - tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) - tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) - tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); + EditTabBarFittingPolicyFlags(&tab_bar_flags); // Tab Bar ImGui::AlignTextToFramePadding(); @@ -3475,12 +3480,8 @@ static void DemoWindowWidgetsTabs() ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs - static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; - ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) - tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) - tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyShrink; + EditTabBarFittingPolicyFlags(&tab_bar_flags); if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 75b4aa633..1821b5f3b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9691,7 +9691,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore - if (width_excess >= 1.0f && ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || !central_section_is_visible)) + if (width_excess >= 1.0f && ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyShrink) || !central_section_is_visible)) { int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount); int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0); From cc1fbcc9a95c13e4d9622486da9451da797c193c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Jul 2025 23:04:35 +0900 Subject: [PATCH 1207/2359] Fonts: undo change done in b884533 since 19d1ad0 made them unnecessary. (#8794, #8850) --- imstb_truetype.h | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/imstb_truetype.h b/imstb_truetype.h index 1a2778773..cf33289f6 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -4017,8 +4017,7 @@ STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int s #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) -/*static*/ -void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; @@ -4080,8 +4079,7 @@ void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes } } -/*static*/ -void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; @@ -4143,8 +4141,7 @@ void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes } } -/*static*/ -float stbtt__oversample_shift(int oversample) +static float stbtt__oversample_shift(int oversample) { if (!oversample) return 0.0f; From 3ef6c8410a763b8137928d191aed72188ce8770b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Jul 2025 23:20:47 +0900 Subject: [PATCH 1208/2359] Tabs: added new fitting policy ImGuiTabBarFlags_FittingPolicyMixed, new default. (#3421, #8800) --- docs/CHANGELOG.txt | 10 ++++++++-- imgui.cpp | 3 +++ imgui.h | 11 +++++++---- imgui_demo.cpp | 3 +++ imgui_internal.h | 3 ++- imgui_widgets.cpp | 36 ++++++++++++++++++++++++++---------- 6 files changed, 49 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 57ae8d067..808007d6f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,11 +54,17 @@ Other Changes: often more convenient to use index in caller-code, whereas TableGetRowIndex() includes header rows). - Tables: fixed imgui_internal.h's TableGetHoveredRow() the same way. (#7350, #6588, #6250) -- Tabs: fixed tab bar underline not drawing below scroll buttons, when - they are enabled (minor regression from 1.90). (#6820, #4859, #5022, #5239) +- Tabs: added new fitting policy ImGuiTabBarFlags_FittingPolicyMixed + and made it the default. This policy shrink tab width down to a given amount, + and then beyond that it enable scrolling buttons. (#3421, #8800) +- Tabs: added style.TabMinWidthShrink, ImGuiStyleVar_TabMinWidthShrink to + control the width to shrink to in ImGuiTabBarFlags_FittingPolicyMixed mode. + (#3421, #8800). - Tabs: added style.TabMinWidthBase, ImGuiStyleVar_TabMinWidthBase to control the base minimum width of a tab (default to 1.0f). This is the size before any potential shrinking is applied. +- Tabs: fixed tab bar underline not drawing below scroll buttons, when + they are enabled (minor regression from 1.90). (#6820, #4859, #5022, #5239) - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) diff --git a/imgui.cpp b/imgui.cpp index e4e893041..1cc310c57 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1419,6 +1419,7 @@ ImGuiStyle::ImGuiStyle() TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. TabMinWidthBase = 1.0f; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. + TabMinWidthShrink = 80.0f; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy. TabCloseButtonMinWidthSelected = -1.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. TabCloseButtonMinWidthUnselected = 0.0f; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. @@ -1486,6 +1487,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor); + TabMinWidthShrink = ImTrunc(TabMinWidthShrink * scale_factor); TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected; TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); @@ -3506,6 +3508,7 @@ static const ImGuiStyleVarInfo GStyleVarsInfo[] = { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthBase) }, // ImGuiStyleVar_TabMinWidthBase + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabMinWidthShrink) }, // ImGuiStyleVar_TabMinWidthShrink { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle diff --git a/imgui.h b/imgui.h index ffef8e90a..1624384c2 100644 --- a/imgui.h +++ b/imgui.h @@ -1372,10 +1372,11 @@ enum ImGuiTabBarFlags_ ImGuiTabBarFlags_DrawSelectedOverline = 1 << 6, // Draw selected overline markers over selected tab // Fitting/Resize policy - ImGuiTabBarFlags_FittingPolicyShrink = 1 << 7, // Shrink down tabs when they don't fit - ImGuiTabBarFlags_FittingPolicyScroll = 1 << 8, // Add scroll buttons when tabs don't fit - ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyShrink | ImGuiTabBarFlags_FittingPolicyScroll, - ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyShrink, + ImGuiTabBarFlags_FittingPolicyMixed = 1 << 7, // Shrink down tabs when they don't fit, until width is style.TabMinWidthShrink, then enable scrolling buttons. + ImGuiTabBarFlags_FittingPolicyShrink = 1 << 8, // Shrink down tabs when they don't fit + ImGuiTabBarFlags_FittingPolicyScroll = 1 << 9, // Enable scrolling buttons when tabs don't fit + ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyMixed | ImGuiTabBarFlags_FittingPolicyShrink | ImGuiTabBarFlags_FittingPolicyScroll, + ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyMixed, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiTabBarFlags_FittingPolicyResizeDown = ImGuiTabBarFlags_FittingPolicyShrink, // Renamed in 1.92.2 @@ -1810,6 +1811,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_TabBorderSize, // float TabBorderSize ImGuiStyleVar_TabMinWidthBase, // float TabMinWidthBase + ImGuiStyleVar_TabMinWidthShrink, // float TabMinWidthShrink ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle @@ -2276,6 +2278,7 @@ struct ImGuiStyle float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. float TabMinWidthBase; // Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. + float TabMinWidthShrink; // Minimum tab width after shrinking, when using ImGuiTabBarFlags_FittingPolicyMixed policy. float TabCloseButtonMinWidthSelected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. float TabCloseButtonMinWidthUnselected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. float TabBarBorderSize; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e0a9ffc61..eb15dcd1e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3383,6 +3383,8 @@ static void EditTabBarFittingPolicyFlags(ImGuiTabBarFlags* p_flags) { if ((*p_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) *p_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyMixed", p_flags, ImGuiTabBarFlags_FittingPolicyMixed)) + *p_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyMixed); if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyShrink", p_flags, ImGuiTabBarFlags_FittingPolicyShrink)) *p_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyShrink); if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", p_flags, ImGuiTabBarFlags_FittingPolicyScroll)) @@ -8343,6 +8345,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); DragFloat("TabMinWidthBase", &style.TabMinWidthBase, 0.5f, 1.0f, 500.0f, "%.0f"); + DragFloat("TabMinWidthShrink", &style.TabMinWidthShrink, 0.5f, 1.0f, 500.0f, "%0.f"); DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.5f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.5f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); diff --git a/imgui_internal.h b/imgui_internal.h index ea6bd0c1d..553c314d3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2776,6 +2776,7 @@ struct IMGUI_API ImGuiTabBar bool WantLayout; bool VisibleTabWasSubmitted; 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. ImS16 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() float ItemSpacingY; @@ -3222,7 +3223,7 @@ namespace ImGui IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); IMGUI_API void PushMultiItemsWidths(int components, float width_full); - IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); + IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min); // Parameter stacks (shared) IMGUI_API const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1821b5f3b..f96a61a0b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1830,27 +1830,31 @@ static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs) // Shrink excess width from a set of item, by removing width from the larger items first. // Set items Width to -1.0f to disable shrinking this item. -void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess) +void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min) { if (count == 1) { if (items[0].Width >= 0.0f) - items[0].Width = ImMax(items[0].Width - width_excess, 1.0f); + items[0].Width = ImMax(items[0].Width - width_excess, width_min); return; } - ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); + ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); // Sort largest first, smallest last. int count_same_width = 1; while (width_excess > 0.0f && count_same_width < count) { while (count_same_width < count && items[0].Width <= items[count_same_width].Width) count_same_width++; float max_width_to_remove_per_item = (count_same_width < count && items[count_same_width].Width >= 0.0f) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); + max_width_to_remove_per_item = ImMin(items[0].Width - width_min, max_width_to_remove_per_item); if (max_width_to_remove_per_item <= 0.0f) break; - float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item); + float base_width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item); for (int item_n = 0; item_n < count_same_width; item_n++) - items[item_n].Width -= width_to_remove_per_item; - width_excess -= width_to_remove_per_item * count_same_width; + { + float width_to_remove_for_this_item = ImMin(base_width_to_remove_per_item, items[item_n].Width - width_min); + items[item_n].Width -= width_to_remove_for_this_item; + width_excess -= width_to_remove_for_this_item; + } } // Round width and redistribute remainder @@ -9358,6 +9362,7 @@ struct ImGuiTabBarSection { int TabCount; // Number of tabs in this section. float Width; // Sum of width of tabs in this section (after shrinking down) + float WidthAfterShrinkMinWidth; float Spacing; // Horizontal spacing at the end of the section. ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); } @@ -9626,6 +9631,9 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount }; g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); + // Minimum shrink width + const float shrink_min_width = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed) ? g.Style.TabMinWidthShrink : 1.0f; + // Compute ideal tabs widths + store them into shrink buffer ImGuiTabItem* most_recently_selected_tab = NULL; int curr_section_n = -1; @@ -9654,6 +9662,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) int section_n = TabItemGetSectionIdx(tab); ImGuiTabBarSection* section = §ions[section_n]; section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f); + section->WidthAfterShrinkMinWidth += ImMin(tab->ContentWidth, shrink_min_width) + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f); curr_section_n = section_n; // Store data so we can build an array sorted by width if we need to shrink tabs down @@ -9665,13 +9674,19 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) } // Compute total ideal width (used for e.g. auto-resizing a window) + float width_all_tabs_after_min_width_shrink = 0.0f; tab_bar->WidthAllTabsIdeal = 0.0f; for (int section_n = 0; section_n < 3; section_n++) + { tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing; + width_all_tabs_after_min_width_shrink += sections[section_n].WidthAfterShrinkMinWidth + sections[section_n].Spacing; + } // Horizontal scrolling buttons // Important: note that TabBarScrollButtons() will alter BarRect.Max.x. - if ((tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll)) + const bool can_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed); + tab_bar->ScrollButtonEnabled = ((width_all_tabs_after_min_width_shrink > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && can_scroll); + if (tab_bar->ScrollButtonEnabled) if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar)) { scroll_to_tab_id = scroll_and_select_tab->ID; @@ -9691,11 +9706,12 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore - if (width_excess >= 1.0f && ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyShrink) || !central_section_is_visible)) + const bool can_shrink = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyShrink) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed); + if (width_excess >= 1.0f && (can_shrink || !central_section_is_visible)) { int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount); int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0); - ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess); + ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess, shrink_min_width); // Apply shrunk values into tabs and sections for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++) @@ -9750,7 +9766,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Apply request requests if (scroll_to_tab_id != 0) TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections); - else if ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) && IsMouseHoveringRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, true) && IsWindowContentHoverable(g.CurrentWindow)) + else if (tab_bar->ScrollButtonEnabled && IsMouseHoveringRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, true) && IsWindowContentHoverable(g.CurrentWindow)) { const float wheel = g.IO.MouseWheelRequestAxisSwap ? g.IO.MouseWheel : g.IO.MouseWheelH; const ImGuiKey wheel_key = g.IO.MouseWheelRequestAxisSwap ? ImGuiKey_MouseWheelY : ImGuiKey_MouseWheelX; From 320c94bfaa475fae8e2c3ec2c52cbd48fcbd567a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 31 Jul 2025 23:39:44 +0900 Subject: [PATCH 1209/2359] Tabs: when scrolling is enabled, track selected tabs when resizing down parent container. (#3421, #8800) --- docs/CHANGELOG.txt | 3 +++ imgui_internal.h | 1 + imgui_widgets.cpp | 6 ++++++ 3 files changed, 10 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 808007d6f..89e8b34eb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,9 @@ Other Changes: - Tabs: added style.TabMinWidthShrink, ImGuiStyleVar_TabMinWidthShrink to control the width to shrink to in ImGuiTabBarFlags_FittingPolicyMixed mode. (#3421, #8800). +- Tabs: when scrolling is enabled, track selected tabs when resizing down + parent container. This does not prevent to horizontally scroll it out of + view during normal operations. (#3421, #8800) - Tabs: added style.TabMinWidthBase, ImGuiStyleVar_TabMinWidthBase to control the base minimum width of a tab (default to 1.0f). This is the size before any potential shrinking is applied. diff --git a/imgui_internal.h b/imgui_internal.h index 553c314d3..87472b1fb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2758,6 +2758,7 @@ struct IMGUI_API ImGuiTabBar int CurrFrameVisible; int PrevFrameVisible; ImRect BarRect; + float BarRectPrevWidth; // Backup of previous width. When width change we enforce keep horizontal scroll on focused tab. float CurrTabsContentsHeight; float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar float WidthAllTabs; // Actual width of all tabs (locked during layout) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f96a61a0b..3210140c9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9555,6 +9555,10 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImGuiContext& g = *GImGui; tab_bar->WantLayout = false; + // Track selected tab when resizing our parent down + const bool scroll_to_selected_tab = (tab_bar->BarRectPrevWidth > tab_bar->BarRect.GetWidth()); + tab_bar->BarRectPrevWidth = tab_bar->BarRect.GetWidth(); + // Garbage collect by compacting list // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section) int tab_dst_n = 0; @@ -9693,6 +9697,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if ((scroll_and_select_tab->Flags & ImGuiTabItemFlags_Button) == 0) tab_bar->SelectedTabId = scroll_to_tab_id; } + if (scroll_to_tab_id == 0 && scroll_to_selected_tab) + scroll_to_tab_id = tab_bar->SelectedTabId; // Shrink widths if full tabs don't fit in their allocated space float section_0_w = sections[0].Width + sections[0].Spacing; From 22fe9fce4cd6d6ba5d484d0936218a98948812c5 Mon Sep 17 00:00:00 2001 From: Christian Fillion Date: Mon, 4 Aug 2025 00:57:44 -0400 Subject: [PATCH 1210/2359] Textures: fixed assertion in DebugNodeTexture() when ImTextureID_Invalid is non-zero. (#8860, #8745) ImFontAtlas's constructor resets ImTextureRef::_TexID to 0 instead of ImTextureID_Invalid. Amend bc051dc --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 1 + 2 files changed, 3 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 89e8b34eb..8119ffd16 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: - Windows: fixed an issue where resizable child windows would emit border logic when hidden/non-visible (e.g. when in a docked window that is not selected), impacting code not checking for BeginChild() return value. (#8815) +- Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value: + ImFontAtlas() was incorrectly cleared with zeroes. (#8860, #8745) [@cfillion] - Tables: fixed TableGetRowIndex() which never correctly worked when using a clipper (it exists for consistency but is almost never used, as it is often more convenient to use index in caller-code, whereas TableGetRowIndex() diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 64f9a9f7a..399fc4822 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2631,6 +2631,7 @@ ImFontAtlas::ImFontAtlas() TexMinHeight = 128; TexMaxWidth = 8192; TexMaxHeight = 8192; + TexRef._TexID = ImTextureID_Invalid; RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. TexNextUniqueID = 1; FontNextUniqueID = 1; From 7d5fef8642ab457ec76501f4601b0aecc8896ec4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 4 Aug 2025 15:06:14 +0900 Subject: [PATCH 1211/2359] Nav: fixed a bug where GamepadMenu couldn't toggle between main and menu layer while navigating a Modal window. (#8834) Amend 901d432cb but for Gamepad. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 10 ++++++++-- imgui_internal.h | 4 ++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8119ffd16..78fa81869 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,8 @@ Other Changes: any potential shrinking is applied. - Tabs: fixed tab bar underline not drawing below scroll buttons, when they are enabled (minor regression from 1.90). (#6820, #4859, #5022, #5239) +- Nav: fixed a bug where GamepadMenu button couldn't toggle between main and + menu layers while navigating a Modal window. (#8834) - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) diff --git a/imgui.cpp b/imgui.cpp index 1cc310c57..621653748 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14200,9 +14200,16 @@ static void ImGui::NavUpdateWindowing() const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); - const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id); + const bool start_toggling_with_gamepad = nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id); + const bool start_windowing_with_gamepad = allow_windowing && start_toggling_with_gamepad; const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard! bool just_started_windowing_from_null_focus = false; + if (start_toggling_with_gamepad) + { + g.NavWindowingToggleLayer = true; // Gamepad starts toggling layer + g.NavWindowingToggleKey = ImGuiKey_NavGamepadMenu; + g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad; + } if (start_windowing_with_gamepad || start_windowing_with_keyboard) if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) { @@ -14210,7 +14217,6 @@ static void ImGui::NavUpdateWindowing() g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f); - g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad; if (g.NavWindow == NULL) just_started_windowing_from_null_focus = true; diff --git a/imgui_internal.h b/imgui_internal.h index 87472b1fb..e4354c375 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2328,8 +2328,8 @@ struct ImGuiContext float NavWindowingTimer; float NavWindowingHighlightAlpha; ImGuiInputSource NavWindowingInputSource; - bool NavWindowingToggleLayer; - ImGuiKey NavWindowingToggleKey; + bool NavWindowingToggleLayer; // Set while Alt or GamepadMenu is held, may be cleared by other operations, and processed when releasing the key. + ImGuiKey NavWindowingToggleKey; // Keyboard/gamepad key used when toggling to menu layer. ImVec2 NavWindowingAccumDeltaPos; ImVec2 NavWindowingAccumDeltaSize; From c14d83d4e0c5f9e42a88e69563bd77973646fd9a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 4 Aug 2025 15:12:23 +0900 Subject: [PATCH 1212/2359] Tabs: made scrolling buttons never keyboard/gamepad navigation candidates. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 78fa81869..170be06e9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,7 @@ Other Changes: any potential shrinking is applied. - Tabs: fixed tab bar underline not drawing below scroll buttons, when they are enabled (minor regression from 1.90). (#6820, #4859, #5022, #5239) +- Tabs: made scrolling buttons never keyboard/gamepad navigation candidates. - Nav: fixed a bug where GamepadMenu button couldn't toggle between main and menu layers while navigating a Modal window. (#8834) - Error Handling: minor improvements to error handling for TableGetSortSpecs() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3210140c9..88d255ffb 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10046,7 +10046,7 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) PushStyleColor(ImGuiCol_Text, arrow_col); PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); - PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); + PushItemFlag(ImGuiItemFlags_ButtonRepeat | ImGuiItemFlags_NoNav, true); const float backup_repeat_delay = g.IO.KeyRepeatDelay; const float backup_repeat_rate = g.IO.KeyRepeatRate; g.IO.KeyRepeatDelay = 0.250f; From 250bd66b76f627af3ceafc4f2e27ef3e91783a48 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 4 Aug 2025 15:19:16 +0900 Subject: [PATCH 1213/2359] Tabs: fixed ImGuiTabBarFlags_FittingPolicyScroll not triggering (regression in 3ef6c84). (#3421, #8800) --- imgui_widgets.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 88d255ffb..5f595e788 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9689,7 +9689,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Horizontal scrolling buttons // Important: note that TabBarScrollButtons() will alter BarRect.Max.x. const bool can_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed); - tab_bar->ScrollButtonEnabled = ((width_all_tabs_after_min_width_shrink > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && can_scroll); + const float width_all_tabs_to_use_for_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) ? tab_bar->WidthAllTabs : width_all_tabs_after_min_width_shrink; + tab_bar->ScrollButtonEnabled = ((width_all_tabs_to_use_for_scroll > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && can_scroll); if (tab_bar->ScrollButtonEnabled) if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar)) { From 70cfc028114524d2951d3be1a6546fc1847f1ae5 Mon Sep 17 00:00:00 2001 From: "o:tone" <33697887+itsdanott@users.noreply.github.com> Date: Wed, 23 Jul 2025 12:36:34 +0200 Subject: [PATCH 1214/2359] Examples: SDL3+SDL_GPU: use SDL_WaitAndAcquireGPUSwapchainTexture() instead of SDL_AcquireGPUSwapchainTexture(). (#8830) --- docs/CHANGELOG.txt | 2 ++ examples/example_sdl3_sdlgpu3/main.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 170be06e9..85b52db3b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -82,6 +82,8 @@ Other Changes: - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] - CI: Updated Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] - Examples: SDL3+Metal: added SDL3+Metal example. (#8827, #8825) [@shi-yan] +- Examples: SDL3+SDL_GPU: use SDL_WaitAndAcquireGPUSwapchainTexture() instead + of SDL_AcquireGPUSwapchainTexture(). (#8830) [@itsdanott] - Backends: OpenGL3: add and call embedded loader shutdown in ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) [@tim-rex] - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 649fde9f5..5945d9af8 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -184,7 +184,7 @@ int main(int, char**) SDL_GPUCommandBuffer* command_buffer = SDL_AcquireGPUCommandBuffer(gpu_device); // Acquire a GPU command buffer SDL_GPUTexture* swapchain_texture; - SDL_AcquireGPUSwapchainTexture(command_buffer, window, &swapchain_texture, nullptr, nullptr); // Acquire a swapchain texture + SDL_WaitAndAcquireGPUSwapchainTexture(command_buffer, window, &swapchain_texture, nullptr, nullptr); // Acquire a swapchain texture if (swapchain_texture != nullptr && !is_minimized) { From 902b8cc39a7f15fdacb85ac69346238d0a889ec6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 4 Aug 2025 15:30:25 +0900 Subject: [PATCH 1215/2359] Examples: SDL3+SDL_GPU: use SDL_GPU_PRESENTMODE_VSYNC present mode. (#8830) --- examples/example_sdl3_sdlgpu3/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 5945d9af8..380b8c574 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -60,7 +60,7 @@ int main(int, char**) printf("Error: SDL_ClaimWindowForGPUDevice(): %s\n", SDL_GetError()); return -1; } - SDL_SetGPUSwapchainParameters(gpu_device, window, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, SDL_GPU_PRESENTMODE_MAILBOX); + SDL_SetGPUSwapchainParameters(gpu_device, window, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, SDL_GPU_PRESENTMODE_VSYNC); // Setup Dear ImGui context IMGUI_CHECKVERSION(); From 90025a62c7739b8e4d7c931dc75a77308e4723a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20B=C3=B6hme?= Date: Fri, 6 Jun 2025 16:27:57 +0200 Subject: [PATCH 1216/2359] Backends: Vulkan: Avoid calling vkCmdBindDescriptorSets() when texture has not changed. (#8666) --- backends/imgui_impl_vulkan.cpp | 6 +++++- docs/CHANGELOG.txt | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index f89ff5176..263c2c73b 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -588,6 +588,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) + VkDescriptorSet last_desc_set = VK_NULL_HANDLE; int global_vtx_offset = 0; int global_idx_offset = 0; for (const ImDrawList* draw_list : draw_data->CmdLists) @@ -603,6 +604,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height); else pcmd->UserCallback(draw_list, pcmd); + last_desc_set = VK_NULL_HANDLE; } else { @@ -628,7 +630,9 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Bind DescriptorSet with font or user texture VkDescriptorSet desc_set = (VkDescriptorSet)pcmd->GetTexID(); - vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, &desc_set, 0, nullptr); + if (desc_set != last_desc_set) + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, &desc_set, 0, nullptr); + last_desc_set = desc_set; // Draw vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 85b52db3b..686ca2fad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -90,6 +90,8 @@ Other Changes: textures. (#8802) [@Daandelange] - Backends: Vulkan: Fixed texture update corruption introduced in 1.92.0, affecting some drivers/setups. (#8801, #8755, #8840) [@Retro52, @Miolith] +- Backends: Vulkan: Avoid calling vkCmdBindDescriptorSets() when texture + has not changed. (#8666) [@micb25] ----------------------------------------------------------------------- From 7e701c18c819bf953aafe60c19ff00116c46befc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 4 Aug 2025 18:21:38 +0900 Subject: [PATCH 1217/2359] Fonts: fixed an issue when a font using MergeMode has a reference size specified but the target font doesn't. --- docs/CHANGELOG.txt | 4 ++++ imgui_draw.cpp | 7 ++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 686ca2fad..21008e01d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,10 @@ Breaking Changes: Other Changes: +- Fonts: fixed an issue when a font using MergeMode has a reference size + specified but the target font doesn't. Usually either all fonts should + have a reference size (only required when specifying e.g. GlyphOffset), + or none should have a reference size. - Windows: fixed an issue where resizable child windows would emit border logic when hidden/non-visible (e.g. when in a docked window that is not selected), impacting code not checking for BeginChild() return value. (#8815) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 399fc4822..ca1f912a4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4573,15 +4573,16 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* } src->FontLoaderData = bd_font_data; + const float ref_size = src->DstFont->Sources[0]->SizePixels; if (src->MergeMode && src->SizePixels == 0.0f) - src->SizePixels = src->DstFont->Sources[0]->SizePixels; + src->SizePixels = ref_size; if (src->SizePixels >= 0.0f) bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); else bd_font_data->ScaleFactor = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); - if (src->MergeMode && src->SizePixels != 0.0f) - bd_font_data->ScaleFactor *= src->SizePixels / src->DstFont->Sources[0]->SizePixels; // FIXME-NEWATLAS: Should tidy up that a bit + if (src->MergeMode && src->SizePixels != 0.0f && ref_size != 0.0f) + bd_font_data->ScaleFactor *= src->SizePixels / ref_size; // FIXME-NEWATLAS: Should tidy up that a bit return true; } From ff2dfc84226aaeab4200aa2334c4715590e9dc9e Mon Sep 17 00:00:00 2001 From: Elliot Prior <1709938+Quogu@users.noreply.github.com> Date: Tue, 22 Jul 2025 18:21:43 +0100 Subject: [PATCH 1218/2359] Fonts: fixed a crash when modifying different texture format with a legacy backend. (#8824) --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 6 +----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 21008e01d..049007155 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,9 @@ Other Changes: specified but the target font doesn't. Usually either all fonts should have a reference size (only required when specifying e.g. GlyphOffset), or none should have a reference size. +- Fonts: fixed a crash when changing texture format when using a legacy + backend. Most commonly would happen when calling GetTexDataAsRGBA32() + then immediately GetTexDataAsAlpha8(). (#8824) - Windows: fixed an issue where resizable child windows would emit border logic when hidden/non-visible (e.g. when in a docked window that is not selected), impacting code not checking for BeginChild() return value. (#8815) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ca1f912a4..8109ca6e0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3363,11 +3363,7 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) { IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); if (atlas->TexData && atlas->TexData->Format != atlas->TexDesiredFormat) - { - ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); - ImFontAtlasBuildDestroy(atlas); - ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y); - } + ImFontAtlasBuildClear(atlas); if (atlas->Builder == NULL) ImFontAtlasBuildInit(atlas); From f7eae45ae94c32ce2ff9038a689646813fd539a2 Mon Sep 17 00:00:00 2001 From: Christian Fillion Date: Tue, 5 Aug 2025 21:42:34 -0400 Subject: [PATCH 1219/2359] Fonts: show ImFontConfig::FontNo in DebugNodeFont(). (#8863) Thanks! --- imgui.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 621653748..308733d17 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16973,8 +16973,8 @@ void ImGui::DebugNodeFont(ImFont* font) for (int src_n = 0; src_n < font->Sources.Size; src_n++) { ImFontConfig* src = font->Sources[src_n]; - if (TreeNode(src, "Input %d: \'%s\', Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", - src_n, src->Name, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y)) + if (TreeNode(src, "Input %d: \'%s\' [%d], Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->FontNo, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y)) { const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; Text("Loader: '%s'", loader->Name ? loader->Name : "N/A"); From d163e20f63ce0620ad91a290f136d7405e0556e5 Mon Sep 17 00:00:00 2001 From: Adem Budak Date: Wed, 6 Aug 2025 04:43:57 +0300 Subject: [PATCH 1220/2359] Examples: Win32+OpenGL3: Replace legacy 'GL/GL.h' with 'GL/gl.h' (#8861) --- examples/example_win32_opengl3/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 820248c64..6b88497c0 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -15,7 +15,7 @@ #define WIN32_LEAN_AND_MEAN #endif #include -#include +#include #include // Data stored per platform window From 284283615b2fcf9d7d7d8608fdd990fc767b1791 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 6 Aug 2025 10:47:43 +0900 Subject: [PATCH 1221/2359] InputText: minor tweak to an expression. Primarily to make PVS Studio static analysis go silent but it is a perfectly valid suggestion. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5f595e788..cb5dade87 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4944,7 +4944,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Determine if we turn Enter into a \n character bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; - if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) + if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line != io.KeyCtrl)) { validated = true; if (io.ConfigInputTextEnterKeepActive && !is_multiline) From 1bf41a076229739ac845b7ffc613511f0208398a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 7 Aug 2025 16:16:12 +0200 Subject: [PATCH 1222/2359] Fonts, Tables: fixed PushFont() having no effect when called after submitting a hidden column. (#8865) Amend 0e769c5 --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 049007155..88dbf2fc7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -122,6 +122,8 @@ Changes: to pass full range of information into e.g. FreeType's face_index, as higher bits are used from FreeType 2.6.1. (#8775) [@Valakor] (the field has been erroneously reduced from 32-bits to 8-bit in 1.92.0) +- Fonts, Tables: fixed PushFont() having no effect when called after submitting + a hidden column. (#8865) - Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value: ImTextureData() was incorrectly cleared with zeroes. (#8745) [@rachit7645] - Demo: Added "Text -> Font Size" demo section. (#8738) [@Demonese] diff --git a/imgui.cpp b/imgui.cpp index 308733d17..d2b600595 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8841,8 +8841,11 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching, so for now we null it. // FIXME: perhaps g.FontSize should be updated? if (window != NULL && window->SkipItems) - if (g.CurrentTable == NULL || g.CurrentTable->CurrentColumn != -1) // See 8465#issuecomment-2951509561. Ideally the SkipItems=true in tables would be amended with extra data. + { + ImGuiTable* table = g.CurrentTable; + if (table == NULL || (table->CurrentColumn != -1 && table->Columns[table->CurrentColumn].IsSkipItems == false)) // See 8465#issuecomment-2951509561 and #8865. Ideally the SkipItems=true in tables would be amended with extra data. return; + } // Restoring is pretty much only used by PopFont() float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; From c22af8c346e9d7527ef0f5edf89ba2b56e47f0a9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 7 Aug 2025 16:19:07 +0200 Subject: [PATCH 1223/2359] Fonts: fixes comment (amend d8da97f7). --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index d2b600595..e3c89879f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8838,7 +8838,7 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) g.Style.FontSizeBase = g.FontSizeBase; // Early out to avoid hidden window keeping bakes referenced and out of GC reach. - // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching, so for now we null it. + // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching. // FIXME: perhaps g.FontSize should be updated? if (window != NULL && window->SkipItems) { From 412daf7362b40869e38c0ee57f07127eed04bdde Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 7 Aug 2025 16:41:21 +0200 Subject: [PATCH 1224/2359] Tabs: attempt to fix infinite loop in tab-bar ShrinkWidth() by using an epsilon. (#5652, #3421, #8800) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index cb5dade87..946ac74e2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1840,7 +1840,7 @@ void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_exc } ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); // Sort largest first, smallest last. int count_same_width = 1; - while (width_excess > 0.0f && count_same_width < count) + while (width_excess > 0.001f && count_same_width < count) { while (count_same_width < count && items[0].Width <= items[count_same_width].Width) count_same_width++; From e7d0ad092cad0807de8f0f9c05911a4d8b4e88dc Mon Sep 17 00:00:00 2001 From: LEE KYOUNGHEON Date: Fri, 8 Aug 2025 00:01:23 +0900 Subject: [PATCH 1225/2359] Removed static inline usages from free functions. (#8867, #8813) For C++20 module compatibility. See https://github.com/stripe2933/imgui-module/ --- imgui.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index 1624384c2..5a05d3bb9 100644 --- a/imgui.h +++ b/imgui.h @@ -3970,24 +3970,24 @@ struct ImGuiPlatformImeData namespace ImGui { // OBSOLETED in 1.92.0 (from June 2025) - static inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); } + inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); } IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFont(NULL, style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. // OBSOLETED in 1.91.9 (from February 2025) IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) - static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } - static inline void PopButtonRepeat() { PopItemFlag(); } - static inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } - static inline void PopTabStop() { PopItemFlag(); } + inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } + inline void PopButtonRepeat() { PopItemFlag(); } + inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + inline void PopTabStop() { PopItemFlag(); } IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! // OBSOLETED in 1.90.0 (from September 2023) - static inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } - static inline void EndChildFrame() { EndChild(); } + inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } + inline void EndChildFrame() { EndChild(); } //static 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 //static 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 - static inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } + inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } 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); 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); // OBSOLETED in 1.89.7 (from June 2023) From 9ee3d731b5934b92da9ebe8ae2442015eac600ac Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 8 Aug 2025 15:25:19 +0200 Subject: [PATCH 1226/2359] Backends: SDL_GPU3: changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*. Added ImGui_ImplSDLGPU3_RenderState. (#8866, #8163, #7998, #7988) --- backends/imgui_impl_sdlgpu3.cpp | 36 ++++++++++++++++++++++----------- backends/imgui_impl_sdlgpu3.h | 12 ++++++++++- docs/CHANGELOG.txt | 5 +++++ imgui.cpp | 1 + imgui.h | 2 +- 5 files changed, 42 insertions(+), 14 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index f58324a89..7bca619b5 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -2,7 +2,7 @@ // This needs to be used along with the SDL3 Platform Backend // Implemented features: -// [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID. +// [X] Renderer: User texture binding. Use 'SDL_GPUTexture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! **IMPORTANT** Before 2025/08/08, ImTextureID was a reference to a SDL_GPUTextureSamplerBinding struct. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). // [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). @@ -22,6 +22,8 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-08-08: *BREAKING* Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) +// 2025-08-08: Expose SamplerDefault and SamplerCurrent in ImGui_ImplSDLGPU3_RenderState. Allow callback to change sampler. // 2025-06-25: Mapping transfer buffer for texture update use cycle=true. Fixes artifacts e.g. on Metal backend. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture(). // 2025-04-28: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. @@ -39,7 +41,6 @@ struct ImGui_ImplSDLGPU3_Texture { SDL_GPUTexture* Texture = nullptr; - SDL_GPUTextureSamplerBinding TextureSamplerBinding = { nullptr, nullptr }; }; // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData() @@ -84,12 +85,13 @@ static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass * render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height) +static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, ImGui_ImplSDLGPU3_RenderState* render_state, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height) { - //ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); + render_state->SamplerCurrent = render_state->SamplerCurrent = bd->TexSampler; // Bind graphics pipeline - SDL_BindGPUGraphicsPipeline(render_pass,pipeline); + SDL_BindGPUGraphicsPipeline(render_pass, pipeline); // Bind Vertex And Index Buffers if (draw_data->TotalVtxCount > 0) @@ -227,12 +229,19 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe if (pipeline == nullptr) pipeline = bd->Pipeline; - ImGui_ImplSDLGPU3_SetupRenderState(draw_data, pipeline, command_buffer, render_pass, fd, fb_width, fb_height); - // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + // Setup render state structure (for callbacks and custom texture bindings) + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + ImGui_ImplSDLGPU3_RenderState render_state; + render_state.Device = bd->InitInfo.Device; + render_state.SamplerDefault = render_state.SamplerCurrent = bd->TexSampler; + platform_io.Renderer_RenderState = &render_state; + + ImGui_ImplSDLGPU3_SetupRenderState(draw_data, &render_state, pipeline, command_buffer, render_pass, fd, fb_width, fb_height); + // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; @@ -247,7 +256,7 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) - ImGui_ImplSDLGPU3_SetupRenderState(draw_data, pipeline, command_buffer, render_pass, fd, fb_width, fb_height); + ImGui_ImplSDLGPU3_SetupRenderState(draw_data, &render_state, pipeline, command_buffer, render_pass, fd, fb_width, fb_height); else pcmd->UserCallback(draw_list, pcmd); } @@ -274,9 +283,14 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe SDL_SetGPUScissor(render_pass,&scissor_rect); // Bind DescriptorSet with font or user texture - SDL_BindGPUFragmentSamplers(render_pass, 0, (SDL_GPUTextureSamplerBinding*)pcmd->GetTexID(), 1); + SDL_GPUTextureSamplerBinding texture_sampler_binding; + texture_sampler_binding.texture = (SDL_GPUTexture*)(intptr_t)pcmd->GetTexID(); + texture_sampler_binding.sampler = render_state.SamplerCurrent; + SDL_BindGPUFragmentSamplers(render_pass, 0, &texture_sampler_binding, 1); // Draw + // **IF YOU GET A CRASH HERE** In 1.92.2 on 2025/08/08 we have changed ImTextureID to store 'SDL_GPUTexture*' instead of storing 'SDL_GPUTextureSamplerBinding'. + // Any code loading custom texture using this backend needs to be updated. SDL_DrawGPUIndexedPrimitives(render_pass, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } } @@ -334,12 +348,10 @@ void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1; backend_tex->Texture = SDL_CreateGPUTexture(v->Device, &texture_info); - backend_tex->TextureSamplerBinding.texture = backend_tex->Texture; - backend_tex->TextureSamplerBinding.sampler = bd->TexSampler; IM_ASSERT(backend_tex->Texture && "Failed to create font texture, call SDL_GetError() for more info"); // Store identifiers - tex->SetTexID((ImTextureID)(intptr_t)&backend_tex->TextureSamplerBinding); + tex->SetTexID((ImTextureID)(intptr_t)backend_tex->Texture); tex->BackendUserData = backend_tex; } diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index 826767ac5..1ab3a5a84 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -2,7 +2,7 @@ // This needs to be used along with the SDL3 Platform Backend // Implemented features: -// [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID. +// [X] Renderer: User texture binding. Use 'SDL_GPUTexture*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! **IMPORTANT** Before 2025/08/08, ImTextureID was a reference to a SDL_GPUTextureSamplerBinding struct. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). // [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). @@ -49,4 +49,14 @@ IMGUI_IMPL_API void ImGui_ImplSDLGPU3_DestroyDeviceObjects(); // (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. IMGUI_IMPL_API void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex); +// [BETA] Selected render state data shared with callbacks. +// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLGPU3_RenderDrawData() call. +// (Please open an issue if you feel you need access to more data) +struct ImGui_ImplSDLGPU3_RenderState +{ + SDL_GPUDevice* Device; + SDL_GPUSampler* SamplerDefault; // Default sampler (bilinear filtering) + SDL_GPUSampler* SamplerCurrent; // Current sampler (may be changed by callback) +}; + #endif // #ifndef IMGUI_DISABLE diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 88dbf2fc7..def674c2c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking Changes: - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete). (#261, #351) +- Backends: SDL_GPU3: changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, + which is more natural and easier for user to manage. If you need to change the current sampler, + you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) Other Changes: @@ -95,6 +98,8 @@ Other Changes: to facilitate multiple init/shutdown cycles in same process. (#8792) [@tim-rex] - Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) [@Daandelange] +- Backends: SDL_GPU3: expose current SDL_GPUSampler* in the ImGui_ImplSDLGPU3_RenderState + struct. (#8866, #8163, #7998, #7988) - Backends: Vulkan: Fixed texture update corruption introduced in 1.92.0, affecting some drivers/setups. (#8801, #8755, #8840) [@Retro52, @Miolith] - Backends: Vulkan: Avoid calling vkCmdBindDescriptorSets() when texture diff --git a/imgui.cpp b/imgui.cpp index e3c89879f..4b2936d9c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -392,6 +392,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/08/08 (1.92.2) - Backends: SDL_GPU3: Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete). - 2025/06/25 (1.92.0) - Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150) diff --git a/imgui.h b/imgui.h index 5a05d3bb9..e490658f1 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.2 WIP" -#define IMGUI_VERSION_NUM 19213 +#define IMGUI_VERSION_NUM 19214 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From b6614f6c7cdf0a0e6ef64e8c00489d6040689f45 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 8 Aug 2025 15:48:40 +0200 Subject: [PATCH 1227/2359] Backends: SDL_GPU3: removed ImGui_ImplSDLGPU3_Texture struct extraneous indirection now that we only need to store SDL_GPUTexture*. (#8866, #8163, #7998, #7988, #8465) --- backends/imgui_impl_sdlgpu3.cpp | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 7bca619b5..c2f465136 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -38,10 +38,6 @@ #include "imgui_impl_sdlgpu3_shaders.h" // SDL_GPU Data -struct ImGui_ImplSDLGPU3_Texture -{ - SDL_GPUTexture* Texture = nullptr; -}; // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData() struct ImGui_ImplSDLGPU3_FrameData @@ -309,18 +305,13 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe static void ImGui_ImplSDLGPU3_DestroyTexture(ImTextureData* tex) { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - ImGui_ImplSDLGPU3_Texture* backend_tex = (ImGui_ImplSDLGPU3_Texture*)tex->BackendUserData; - if (backend_tex == nullptr) - return; - SDL_GPUTextureSamplerBinding* binding = (SDL_GPUTextureSamplerBinding*)(intptr_t)tex->BackendUserData; - IM_ASSERT(backend_tex->Texture == binding->texture); - SDL_ReleaseGPUTexture(bd->InitInfo.Device, backend_tex->Texture); - IM_DELETE(backend_tex); + SDL_GPUTexture* raw_tex = (SDL_GPUTexture*)(intptr_t)tex->GetTexID(); + if (raw_tex != nullptr) + SDL_ReleaseGPUTexture(bd->InitInfo.Device, raw_tex); // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) tex->SetTexID(ImTextureID_Invalid); tex->SetStatus(ImTextureStatus_Destroyed); - tex->BackendUserData = nullptr; } void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) @@ -334,7 +325,6 @@ void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); - ImGui_ImplSDLGPU3_Texture* backend_tex = IM_NEW(ImGui_ImplSDLGPU3_Texture)(); // Create texture SDL_GPUTextureCreateInfo texture_info = {}; @@ -347,17 +337,16 @@ void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) texture_info.num_levels = 1; texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1; - backend_tex->Texture = SDL_CreateGPUTexture(v->Device, &texture_info); - IM_ASSERT(backend_tex->Texture && "Failed to create font texture, call SDL_GetError() for more info"); + SDL_GPUTexture* raw_tex = SDL_CreateGPUTexture(v->Device, &texture_info); + IM_ASSERT(raw_tex != nullptr && "Failed to create font texture, call SDL_GetError() for more info"); // Store identifiers - tex->SetTexID((ImTextureID)(intptr_t)backend_tex->Texture); - tex->BackendUserData = backend_tex; + tex->SetTexID((ImTextureID)(intptr_t)raw_tex); } if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates) { - ImGui_ImplSDLGPU3_Texture* backend_tex = (ImGui_ImplSDLGPU3_Texture*)tex->BackendUserData; + SDL_GPUTexture* raw_tex = (SDL_GPUTexture*)(intptr_t)tex->GetTexID(); IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); // Update full texture or selected blocks. We only ever write to textures regions which have never been used before! @@ -395,7 +384,7 @@ void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) transfer_info.transfer_buffer = bd->TexTransferBuffer; SDL_GPUTextureRegion texture_region = {}; - texture_region.texture = backend_tex->Texture; + texture_region.texture = raw_tex; texture_region.x = (Uint32)upload_x; texture_region.y = (Uint32)upload_y; texture_region.w = (Uint32)upload_w; From ea075ed973edb7b40d3eeadb6a0360599104169c Mon Sep 17 00:00:00 2001 From: Ian Date: Sun, 10 Aug 2025 14:10:42 -0400 Subject: [PATCH 1228/2359] ImVector: skip memcpy in operator= if Data isn't initialized to play nice with -fsanitize=undefined. (#8874) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index def674c2c..42b36e269 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -89,6 +89,8 @@ Other Changes: - Misc: fixed building with IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION. (#8794) - Misc: removed more redundant inline static linkage from imgui_internal.h to facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] +- Misc: ImVector: skip memcpy in operator= if `Data` isn't initialized in order + to play nice with -fsanitize=undefined. (#8874) [@i25e] - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] - CI: Updated Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] - Examples: SDL3+Metal: added SDL3+Metal example. (#8827, #8825) [@shi-yan] diff --git a/imgui.h b/imgui.h index e490658f1..3112184fc 100644 --- a/imgui.h +++ b/imgui.h @@ -2181,7 +2181,7 @@ struct ImVector // Constructors, destructor inline ImVector() { Size = Capacity = 0; Data = NULL; } inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } - inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); if (src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } + inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); if (Data && src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } inline ~ImVector() { if (Data) IM_FREE(Data); } // Important: does not destruct anything inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } // Important: does not destruct anything From 47c41483bd8936e7a58db25ebd5671ff98b3c32d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2025 10:47:55 +0200 Subject: [PATCH 1229/2359] Tables, Nav: fixed navigation within scrolling tables when item boundaries goes beyond columns limits. (#8816, #2221) Amend 00d3f9295e5caf417886572266bebb490ad3577b. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 ++- imgui_tables.cpp | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 42b36e269..aa0b1db9e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,9 @@ Other Changes: - Tabs: fixed tab bar underline not drawing below scroll buttons, when they are enabled (minor regression from 1.90). (#6820, #4859, #5022, #5239) - Tabs: made scrolling buttons never keyboard/gamepad navigation candidates. +- Nav, Tables: fixed navigation within scrolling tables when item boundaries + goes beyond columns limits. The fix done in 1.89.6 didn't work correctly + on scrolling windows. (#8816, #2221) - Nav: fixed a bug where GamepadMenu button couldn't toggle between main and menu layers while navigating a Modal window. (#8834) - Error Handling: minor improvements to error handling for TableGetSortSpecs() diff --git a/imgui.cpp b/imgui.cpp index 4b2936d9c..6f9a77497 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -24,7 +24,7 @@ // For first-time users having issues compiling/linking/running: // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. -// Since 1.92, we encourage font loading question to also be posted in 'Issues'. +// Since 1.92, we encourage font loading questions to also be posted in 'Issues'. // Copyright (c) 2014-2025 Omar Cornut // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. @@ -13746,6 +13746,7 @@ void ImGui::NavUpdateCreateMoveRequest() } } + // Prepare scoring rectangle. // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) ImRect scoring_rect; if (window != NULL) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index a1504853b..2816707cf 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -542,7 +542,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Make table current g.CurrentTable = table; - outer_window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX(); + inner_window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX(); outer_window->DC.CurrentTableIdx = table_idx; if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly. inner_window->DC.CurrentTableIdx = table_idx; From 1c57dc21c26bc6e4b57715d32f50650b305dc02c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2025 11:01:13 +0200 Subject: [PATCH 1230/2359] Misc: fixes zealous MSVC static analyzer warnings + make GetInputSourceName(), GetMouseSourceName() a little more tolerant. (#8876) --- imgui.cpp | 9 +++++++-- imgui_draw.cpp | 3 ++- imgui_widgets.cpp | 1 + 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6f9a77497..cc5abfc3d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10175,13 +10175,17 @@ void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse) static const char* GetInputSourceName(ImGuiInputSource source) { const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" }; - IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT); + IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); + if (source < 0 || source >= ImGuiInputSource_COUNT) + return "Unknown"; return input_source_names[source]; } static const char* GetMouseSourceName(ImGuiMouseSource source) { const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" }; - IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT); + IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT); + if (source < 0 || source >= ImGuiMouseSource_COUNT) + return "Unknown"; return mouse_source_names[source]; } static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e) @@ -14157,6 +14161,7 @@ static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window) SetNavCursorVisibleAfterMove(); ClosePopupsOverWindow(apply_focus_window, false); FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild); + IM_ASSERT(g.NavWindow != NULL); apply_focus_window = g.NavWindow; if (apply_focus_window->NavLastIds[0] == 0) NavInitWindow(apply_focus_window, false); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8109ca6e0..a0afce188 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3363,7 +3363,7 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) { IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); if (atlas->TexData && atlas->TexData->Format != atlas->TexDesiredFormat) - ImFontAtlasBuildClear(atlas); + ImFontAtlasBuildClear(atlas); if (atlas->Builder == NULL) ImFontAtlasBuildInit(atlas); @@ -4372,6 +4372,7 @@ ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId if (atlas->Builder == NULL) ImFontAtlasBuildInit(atlas); ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + IM_MSVC_WARNING_SUPPRESS(28182); // Static Analysis false positive "warning C28182: Dereferencing NULL pointer 'builder'" if (index_idx >= builder->RectsIndex.Size) return NULL; ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 946ac74e2..12ff71385 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8883,6 +8883,7 @@ void ImGui::EndMenuBar() PopClipRect(); PopID(); + IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'" window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->Pos.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos. // FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here. From 50115596dccd152309079359339088cfbd4c4cef Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2025 12:29:13 +0200 Subject: [PATCH 1231/2359] Demo: About Box: include IMGUI_ENABLE_TEST_ENGINE in Config/Build info. --- imgui_demo.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index eb15dcd1e..3fd05ba0e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8099,6 +8099,9 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::Separator(); ImGui::Text("sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert)); ImGui::Text("define: __cplusplus=%d", (int)__cplusplus); +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGui::Text("define: IMGUI_ENABLE_TEST_ENGINE"); +#endif #ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS"); #endif From 8239a0e0c4c7f670f38a87ad2649222571d6e5b3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2025 15:17:02 +0200 Subject: [PATCH 1232/2359] Nav, Tables: fix NavIsScrollPushableX logic clamping value stored in NavApplyItemToResult(), which would break scrolling. (#8816, #2221) Amend 47c4148. --- imgui.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cc5abfc3d..c67340edd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1291,7 +1291,7 @@ static float NavUpdatePageUpPageDown(); static inline void NavUpdateAnyRequestFlag(); static void NavUpdateCreateWrappingRequest(); static void NavEndFrame(); -static bool NavScoreItem(ImGuiNavItemData* result); +static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb); static void NavApplyItemToResult(ImGuiNavItemData* result); static void NavProcessItem(); static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags); @@ -12870,7 +12870,7 @@ static float inline NavScoreItemDistInterval(float cand_min, float cand_max, flo } // Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057 -static bool ImGui::NavScoreItem(ImGuiNavItemData* result) +static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -12878,7 +12878,7 @@ static bool ImGui::NavScoreItem(ImGuiNavItemData* result) return false; // FIXME: Those are not good variables names - ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle + ImRect cand = nav_bb; // Current item nav rectangle const ImRect curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width) g.NavScoringDebugCount++; @@ -13045,13 +13045,13 @@ static void ImGui::NavProcessItem() const ImGuiID id = g.LastItemData.ID; const ImGuiItemFlags item_flags = g.LastItemData.ItemFlags; - // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221) + // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816) + ImRect nav_bb = g.LastItemData.NavRect; if (window->DC.NavIsScrollPushableX == false) { - g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x); - g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x); + nav_bb.Min.x = ImClamp(nav_bb.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x); + nav_bb.Max.x = ImClamp(nav_bb.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x); } - const ImRect nav_bb = g.LastItemData.NavRect; // Process Init Request if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0) @@ -13083,14 +13083,14 @@ static void ImGui::NavProcessItem() else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) { ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; - if (NavScoreItem(result)) + if (NavScoreItem(result, nav_bb)) NavApplyItemToResult(result); // Features like PageUp/PageDown need to maintain a separate score for the visible set of items. const float VISIBLE_RATIO = 0.70f; if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb)) if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) - if (NavScoreItem(&g.NavMoveResultLocalVisible)) + if (NavScoreItem(&g.NavMoveResultLocalVisible, nav_bb)) NavApplyItemToResult(&g.NavMoveResultLocalVisible); } } From 5a6fa33b882c1c88c6cd91356ae740640ceaef88 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2025 15:36:54 +0200 Subject: [PATCH 1233/2359] Fixed an inconsistency between IsItemHovered() and internal hovering check, where IsItemHovered() would return true if mouse was first clicked on the background of a non-moveable window. (#8877) --- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 4 +--- imgui.h | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index aa0b1db9e..cd78ff878 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,12 @@ Breaking Changes: Other Changes: +- Fixed an inconsistency between IsItemHovered() and internal hovering check, + where IsItemHovered() would return true to mouse was first clicked on the + background of a non-moveable window then moved over the item or button. + Note that while it is consistent with other logic, there is a possibility + that some third-party code may accidentally relied on this. + (#8877) [@achabense, @ocornut] - Fonts: fixed an issue when a font using MergeMode has a reference size specified but the target font doesn't. Usually either all fonts should have a reference size (only required when specifying e.g. GlyphOffset), diff --git a/imgui.cpp b/imgui.cpp index c67340edd..cef058b45 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4656,7 +4656,6 @@ static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, } // This is roughly matching the behavior of internal-facing ItemHoverable() -// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) { @@ -4698,8 +4697,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) const ImGuiID id = g.LastItemData.ID; if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0) if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) - if (g.ActiveId != window->MoveId) - return false; + return false; // Test if interactions on this window are blocked by an active popup or modal. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. diff --git a/imgui.h b/imgui.h index 3112184fc..95a8001d5 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.2 WIP" -#define IMGUI_VERSION_NUM 19214 +#define IMGUI_VERSION_NUM 19215 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From e10300ed3cec48494d21bc487e45ded6c379b8f6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2025 16:26:10 +0200 Subject: [PATCH 1234/2359] Docs: Special thanks. --- docs/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/README.md b/docs/README.md index 0cd64fa82..6a873a4fd 100644 --- a/docs/README.md +++ b/docs/README.md @@ -184,7 +184,7 @@ How to help - See [GitHub Forum/Issues](https://github.com/ocornut/imgui/issues). - You may help with development and submit pull requests! Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance forever. PR should be crafted both in the interest of the end-users and also to ease the maintainer into understanding and accepting it. - See [Help wanted](https://github.com/ocornut/imgui/wiki/Help-Wanted) on the [Wiki](https://github.com/ocornut/imgui/wiki/) for some more ideas. -- Be a [Funding Supporter](https://github.com/ocornut/imgui/wiki/Funding)! Have your company financially support this project via invoiced sponsors/maintenance or by buying a license for [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine) (please reach out: omar AT dearimgui DOT com). +- Be a [Funding Supporter](https://github.com/ocornut/imgui/wiki/Funding)! Have your company financially support this project via invoiced sponsors/maintenance or by buying a license for [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine) (please reach out: contact AT dearimgui DOT com). Sponsors -------- @@ -214,7 +214,7 @@ Omar: "I first discovered the IMGUI paradigm at [Q-Games](https://www.q-games.co Embeds [ProggyClean.ttf](https://www.proggyfonts.net) font by Tristan Grimmer (MIT license).
Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). -Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Also thank you to everyone posting feedback, questions and patches on GitHub. +Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Special thanks to Alex Evans, Patrick Doane, Marco Koegler to pulling nice strings at the right moment. Also thank you to everyone posting feedback, questions and patches on GitHub. License ------- From 2b24f5fa71d124de108da54d9da49ea3049dc91e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 11 Aug 2025 16:27:27 +0200 Subject: [PATCH 1235/2359] Version 1.92.2 --- docs/CHANGELOG.txt | 35 ++++++++++++++++++++--------------- docs/README.md | 2 +- imgui.cpp | 2 +- imgui.h | 26 +++++++++++++------------- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 9 files changed, 40 insertions(+), 35 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cd78ff878..50b9193b8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.2 WIP (In Progress) + VERSION 1.92.2 (Released 2025-08-11) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92.2 + Breaking Changes: - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. @@ -49,35 +51,36 @@ Breaking Changes: Other Changes: -- Fixed an inconsistency between IsItemHovered() and internal hovering check, +- Fixed an old inconsistency between IsItemHovered() and internal hovering check, where IsItemHovered() would return true to mouse was first clicked on the background of a non-moveable window then moved over the item or button. Note that while it is consistent with other logic, there is a possibility - that some third-party code may accidentally relied on this. + that some third-party code may accidentally relied on this. One can always use + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem to bypass the active id check. (#8877) [@achabense, @ocornut] - Fonts: fixed an issue when a font using MergeMode has a reference size specified but the target font doesn't. Usually either all fonts should have a reference size (only required when specifying e.g. GlyphOffset), - or none should have a reference size. + or none should have a reference size. - Fonts: fixed a crash when changing texture format when using a legacy backend. Most commonly would happen when calling GetTexDataAsRGBA32() - then immediately GetTexDataAsAlpha8(). (#8824) + then immediately calling GetTexDataAsAlpha8(). (#8824) - Windows: fixed an issue where resizable child windows would emit border logic when hidden/non-visible (e.g. when in a docked window that is not selected), impacting code not checking for BeginChild() return value. (#8815) - Textures: Fixed support for `#define ImTextureID_Invalid` to non-zero value: ImFontAtlas() was incorrectly cleared with zeroes. (#8860, #8745) [@cfillion] - Tables: fixed TableGetRowIndex() which never correctly worked when using - a clipper (it exists for consistency but is almost never used, as it is + a clipper (it exists for consistency but is almost never used, as it is often more convenient to use index in caller-code, whereas TableGetRowIndex() - includes header rows). + includes header rows). - Tables: fixed imgui_internal.h's TableGetHoveredRow() the same way. (#7350, #6588, #6250) - Tabs: added new fitting policy ImGuiTabBarFlags_FittingPolicyMixed and made it the default. This policy shrink tab width down to a given amount, and then beyond that it enable scrolling buttons. (#3421, #8800) - Tabs: added style.TabMinWidthShrink, ImGuiStyleVar_TabMinWidthShrink to control the width to shrink to in ImGuiTabBarFlags_FittingPolicyMixed mode. - (#3421, #8800). + (#3421, #8800). - Tabs: when scrolling is enabled, track selected tabs when resizing down parent container. This does not prevent to horizontally scroll it out of view during normal operations. (#3421, #8800) @@ -90,24 +93,26 @@ Other Changes: - Nav, Tables: fixed navigation within scrolling tables when item boundaries goes beyond columns limits. The fix done in 1.89.6 didn't work correctly on scrolling windows. (#8816, #2221) -- Nav: fixed a bug where GamepadMenu button couldn't toggle between main and - menu layers while navigating a Modal window. (#8834) +- Nav: fixed a bug where ImGuiKey_NavGamepadMenu (==ImGuiKey_GamepadFaceLeft) + button couldn't toggle between main and menu layers while navigating a Modal + window. (#8834) - Error Handling: minor improvements to error handling for TableGetSortSpecs() and TableSetBgColor() calls. (#1651, #8499) - Misc: fixed building with IMGUI_DISABLE_DEBUG_TOOLS only. (#8796) - Misc: fixed building with IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION. (#8794) -- Misc: removed more redundant inline static linkage from imgui_internal.h to +- Misc: removed more redundant inline static linkage from imgui_internal.h to facilitate using in C++ modules. (#8813, #8682, #8358) [@stripe2933] - Misc: ImVector: skip memcpy in operator= if `Data` isn't initialized in order to play nice with -fsanitize=undefined. (#8874) [@i25e] - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] - CI: Updated Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] - Examples: SDL3+Metal: added SDL3+Metal example. (#8827, #8825) [@shi-yan] -- Examples: SDL3+SDL_GPU: use SDL_WaitAndAcquireGPUSwapchainTexture() instead +- Examples: SDL3+SDL_GPU: use SDL_WaitAndAcquireGPUSwapchainTexture() instead of SDL_AcquireGPUSwapchainTexture(). (#8830) [@itsdanott] -- Backends: OpenGL3: add and call embedded loader shutdown in ImGui_ImplOpenGL3_Shutdown() +- Examples: SDL3+SDL_GPU: use SDL_GPU_PRESENTMODE_VSYNC present mode. +- Backends: OpenGL3: add and call embedded loader shutdown in ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) [@tim-rex] -- Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating +- Backends: OpenGL2, OpenGL3: set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) [@Daandelange] - Backends: SDL_GPU3: expose current SDL_GPUSampler* in the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) @@ -247,7 +252,7 @@ Breaking changes: see list of glyphs available in multiple font sources. This can facilitate understanding which font input is providing which glyph. - Fonts: **IMPORTANT** on Thread Safety: - - A few functions such as font->CalcTextSizeA() were by sheer luck (== accidentally) + - A few functions such as font->CalcTextSizeA() were by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee before. They are definitively not thread-safe anymore as new glyphs may be loaded. diff --git a/docs/README.md b/docs/README.md index 6a873a4fd..90a66119d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -214,7 +214,7 @@ Omar: "I first discovered the IMGUI paradigm at [Q-Games](https://www.q-games.co Embeds [ProggyClean.ttf](https://www.proggyfonts.net) font by Tristan Grimmer (MIT license).
Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). -Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Special thanks to Alex Evans, Patrick Doane, Marco Koegler to pulling nice strings at the right moment. Also thank you to everyone posting feedback, questions and patches on GitHub. +Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Special thanks to Alex Evans, Patrick Doane, Marco Koegler for kindly helping. Also thank you to everyone posting feedback, questions and patches on GitHub. License ------- diff --git a/imgui.cpp b/imgui.cpp index cef058b45..9ebe39c2e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 WIP +// dear imgui, v1.92.2 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 95a8001d5..37d65b8e1 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 WIP +// dear imgui, v1.92.2 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.2 WIP" -#define IMGUI_VERSION_NUM 19215 +#define IMGUI_VERSION "1.92.2" +#define IMGUI_VERSION_NUM 19220 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -3970,24 +3970,24 @@ struct ImGuiPlatformImeData namespace ImGui { // OBSOLETED in 1.92.0 (from June 2025) - inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); } + inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); } IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFont(NULL, style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. // OBSOLETED in 1.91.9 (from February 2025) IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) - inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } - inline void PopButtonRepeat() { PopItemFlag(); } - inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } - inline void PopTabStop() { PopItemFlag(); } + inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } + inline void PopButtonRepeat() { PopItemFlag(); } + inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + inline void PopTabStop() { PopItemFlag(); } IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! // OBSOLETED in 1.90.0 (from September 2023) - inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } - inline void EndChildFrame() { EndChild(); } - //static 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 - //static 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 void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } + inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } + inline void EndChildFrame() { EndChild(); } + //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 void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } 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); 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); // OBSOLETED in 1.89.7 (from June 2023) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3fd05ba0e..2c82f57c7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 WIP +// dear imgui, v1.92.2 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a0afce188..2dba0c1b9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 WIP +// dear imgui, v1.92.2 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index e4354c375..a8bd72f78 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 WIP +// dear imgui, v1.92.2 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2816707cf..4f06f454b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 WIP +// dear imgui, v1.92.2 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 12ff71385..8bd0923bb 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 WIP +// dear imgui, v1.92.2 // (widgets code) /* From 863e989c25a9d0169b8a5c9692c4fcd8f94b12c7 Mon Sep 17 00:00:00 2001 From: Wouter Vermaelen Date: Mon, 11 Aug 2025 19:39:26 +0200 Subject: [PATCH 1236/2359] imgui_freetype.cpp: fix gcc -Wmissing-declarations (#8879) --- misc/freetype/imgui_freetype.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 7a9468375..cbbde767c 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -344,7 +344,7 @@ static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size return block; } -bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas) +static bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas) { IM_ASSERT(atlas->FontLoaderData == nullptr); ImGui_ImplFreeType_Data* bd = IM_NEW(ImGui_ImplFreeType_Data)(); @@ -384,7 +384,7 @@ bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas) return true; } -void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas) +static void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas) { ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData; IM_ASSERT(bd != nullptr); @@ -393,7 +393,7 @@ void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas) atlas->FontLoaderData = nullptr; } -bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) +static bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) { ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData; ImGui_ImplFreeType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplFreeType_FontSrcData); @@ -410,7 +410,7 @@ bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) return true; } -void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) +static void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) { IM_UNUSED(atlas); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; @@ -418,7 +418,7 @@ void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) src->FontLoaderData = nullptr; } -bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { IM_UNUSED(atlas); float size = baked->Size; @@ -464,7 +464,7 @@ bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImF return true; } -void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +static void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { IM_UNUSED(atlas); IM_UNUSED(baked); @@ -475,7 +475,7 @@ void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() } -bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) +static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) { ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); @@ -566,7 +566,7 @@ bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src return true; } -bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) +static bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) { IM_UNUSED(atlas); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; From af920e1e6f70269788f4e77d4ee9831daf31977b Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2025 11:30:41 +0200 Subject: [PATCH 1237/2359] Version 1.92.3 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 50b9193b8..f73d18190 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.3 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.92.2 (Released 2025-08-11) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 9ebe39c2e..2e3086582 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 +// dear imgui, v1.92.3 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 37d65b8e1..08927acd6 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 +// dear imgui, v1.92.3 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.2" -#define IMGUI_VERSION_NUM 19220 +#define IMGUI_VERSION "1.92.3 WIP" +#define IMGUI_VERSION_NUM 19221 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2c82f57c7..68f8eec9c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 +// dear imgui, v1.92.3 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2dba0c1b9..0941783a8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 +// dear imgui, v1.92.3 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index a8bd72f78..dd2049569 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 +// dear imgui, v1.92.3 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 4f06f454b..8824534e7 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 +// dear imgui, v1.92.3 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8bd0923bb..ce9ccd9f8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2 +// dear imgui, v1.92.3 WIP // (widgets code) /* From e1a93805db15fea76d4fc0e6545416c3be7e6f80 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2025 11:33:10 +0200 Subject: [PATCH 1238/2359] Backends: Allegro5: Added ImGui_ImplAllegro5_SetDisplay(). --- backends/imgui_impl_allegro5.cpp | 43 ++++++++++++++++++++++---------- backends/imgui_impl_allegro5.h | 1 + docs/CHANGELOG.txt | 3 +++ 3 files changed, 34 insertions(+), 13 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 40417fc63..e3245d666 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -8,7 +8,7 @@ // [X] Platform: Clipboard support (from Allegro 5.1.12). // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Missing features or Issues: -// [ ] Renderer: The renderer is suboptimal as we need to convert vertices manually. +// [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. // [ ] Platform: Missing gamepad support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-08-12: Added ImGui_ImplAllegro5_SetDisplay() function to change current ALLEGRO_DISPLAY, as Allegro applications often need to do that. // 2025-07-07: Fixed texture update broken on some platforms where ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture(). // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. @@ -476,20 +477,9 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. - bd->Display = display; bd->LastCursor = ALLEGRO_SYSTEM_MOUSE_CURSOR_NONE; - // Create custom vertex declaration. - // Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 floats. - // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion. - ALLEGRO_VERTEX_ELEMENT elems[] = - { - { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, pos) }, - { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, uv) }, - { ALLEGRO_PRIM_COLOR_ATTR, 0, offsetof(ImDrawVertAllegro, col) }, - { 0, 0, 0 } - }; - bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro)); + ImGui_ImplAllegro5_SetDisplay(display); #if ALLEGRO_HAS_CLIPBOARD ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); @@ -518,6 +508,33 @@ void ImGui_ImplAllegro5_Shutdown() IM_DELETE(bd); } +void ImGui_ImplAllegro5_SetDisplay(ALLEGRO_DISPLAY* display) +{ + ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); + bd->Display = display; + + if (bd->VertexDecl) + { + al_destroy_vertex_decl(bd->VertexDecl); + bd->VertexDecl = NULL; + } + + if (bd->Display && !bd->VertexDecl) + { + // Create custom vertex declaration. + // Unfortunately Allegro doesn't support 32-bits packed colors so we have to convert them to 4 floats. + // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion. + ALLEGRO_VERTEX_ELEMENT elems[] = + { + { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, pos) }, + { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, uv) }, + { ALLEGRO_PRIM_COLOR_ATTR, 0, IM_OFFSETOF(ImDrawVertAllegro, col) }, + { 0, 0, 0 } + }; + bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro)); + } +} + // ev->keyboard.modifiers seems always zero so using that... static void ImGui_ImplAllegro5_UpdateKeyModifiers() { diff --git a/backends/imgui_impl_allegro5.h b/backends/imgui_impl_allegro5.h index 421bbf129..622430432 100644 --- a/backends/imgui_impl_allegro5.h +++ b/backends/imgui_impl_allegro5.h @@ -32,6 +32,7 @@ IMGUI_IMPL_API void ImGui_ImplAllegro5_Shutdown(); IMGUI_IMPL_API void ImGui_ImplAllegro5_NewFrame(); IMGUI_IMPL_API void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event); +IMGUI_IMPL_API void ImGui_ImplAllegro5_SetDisplay(ALLEGRO_DISPLAY* display); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects(); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f73d18190..0477f3491 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking Changes: Other Changes: +- Backends: Allegro5: Added ImGui_ImplAllegro5_SetDisplay() function to + change current ALLEGRO_DISPLAY, as Allegro applications often need to do that. + ----------------------------------------------------------------------- VERSION 1.92.2 (Released 2025-08-11) From e2a662eed8d7396f323704b258111847ed93b1f9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2025 11:41:11 +0200 Subject: [PATCH 1239/2359] Backends: Allegro5: fixed use of obsolete IM_OFFSETOF(). --- backends/imgui_impl_allegro5.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index e3245d666..554588a4b 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -526,9 +526,9 @@ void ImGui_ImplAllegro5_SetDisplay(ALLEGRO_DISPLAY* display) // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion. ALLEGRO_VERTEX_ELEMENT elems[] = { - { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, pos) }, - { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, uv) }, - { ALLEGRO_PRIM_COLOR_ATTR, 0, IM_OFFSETOF(ImDrawVertAllegro, col) }, + { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, pos) }, + { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, uv) }, + { ALLEGRO_PRIM_COLOR_ATTR, 0, offsetof(ImDrawVertAllegro, col) }, { 0, 0, 0 } }; bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro)); From e1baadba8498e4e0159145cf2f0d63de32a4544d Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2025 15:02:58 +0200 Subject: [PATCH 1240/2359] Backends: Allegro5: Fixed texture format setup. (#8770, #8465) Amend/fix ee8941e. --- backends/imgui_impl_allegro5.cpp | 9 ++++++--- docs/CHANGELOG.txt | 2 ++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 554588a4b..7b92ab54b 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -268,8 +268,6 @@ void ImGui_ImplAllegro5_UpdateTexture(ImTextureData* tex) al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE); ALLEGRO_BITMAP* cpu_bitmap = al_create_bitmap(tex->Width, tex->Height); - al_set_new_bitmap_flags(new_bitmap_flags); - al_set_new_bitmap_format(new_bitmap_format); IM_ASSERT(cpu_bitmap != nullptr && "Backend failed to create texture!"); // Upload pixels @@ -279,10 +277,15 @@ void ImGui_ImplAllegro5_UpdateTexture(ImTextureData* tex) al_unlock_bitmap(cpu_bitmap); // Convert software texture to hardware texture. + al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP); + al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_32_WITH_ALPHA); ALLEGRO_BITMAP* gpu_bitmap = al_clone_bitmap(cpu_bitmap); al_destroy_bitmap(cpu_bitmap); IM_ASSERT(gpu_bitmap != nullptr && "Backend failed to create texture!"); + al_set_new_bitmap_flags(new_bitmap_flags); + al_set_new_bitmap_format(new_bitmap_format); + // Store identifiers tex->SetTexID((ImTextureID)(intptr_t)gpu_bitmap); tex->SetStatus(ImTextureStatus_OK); @@ -521,7 +524,7 @@ void ImGui_ImplAllegro5_SetDisplay(ALLEGRO_DISPLAY* display) if (bd->Display && !bd->VertexDecl) { - // Create custom vertex declaration. + // Create custom vertex declaration. // Unfortunately Allegro doesn't support 32-bits packed colors so we have to convert them to 4 floats. // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion. ALLEGRO_VERTEX_ELEMENT elems[] = diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0477f3491..c0e2b8414 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking Changes: Other Changes: +- Backends: Allegro5: Fixed texture format setup which didn't work on all + setups/drivers. (#8770, #8465) - Backends: Allegro5: Added ImGui_ImplAllegro5_SetDisplay() function to change current ALLEGRO_DISPLAY, as Allegro applications often need to do that. From 02f654cbce819ccef85eca3c79b7fc8d7a668a68 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 12 Aug 2025 20:02:08 +0200 Subject: [PATCH 1241/2359] Backends: Allegro5: fixed missing support for ImGuiKey_PrintScreen under Windows. --- backends/imgui_impl_allegro5.cpp | 6 ++++++ docs/CHANGELOG.txt | 2 ++ 2 files changed, 8 insertions(+) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 7b92ab54b..6c5df4b1f 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-08-12: Inputs: fixed missing support for ImGuiKey_PrintScreen under Windows, as raw Allegro 5 does not receive it. // 2025-08-12: Added ImGui_ImplAllegro5_SetDisplay() function to change current ALLEGRO_DISPLAY, as Allegro applications often need to do that. // 2025-07-07: Fixed texture update broken on some platforms where ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture(). @@ -679,6 +680,11 @@ void ImGui_ImplAllegro5_NewFrame() io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f); bd->Time = current_time; + // Allegro 5 doesn't receive PrintScreen under Windows +#ifdef _WIN32 + io.AddKeyEvent(ImGuiKey_PrintScreen, (::GetAsyncKeyState(VK_SNAPSHOT) & 0x8000) != 0); +#endif + // Setup mouse cursor shape ImGui_ImplAllegro5_UpdateMouseCursor(); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c0e2b8414..d1b421594 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Other Changes: setups/drivers. (#8770, #8465) - Backends: Allegro5: Added ImGui_ImplAllegro5_SetDisplay() function to change current ALLEGRO_DISPLAY, as Allegro applications often need to do that. +- Backends: Allegro5: Fixed missing support for ImGuiKey_PrintScreen + under Windows, as raw Allegro 5 does not receive it. ----------------------------------------------------------------------- From 43e3ac0dc69f3ba0cf7f3b3a41ef634c8dd570a9 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 Aug 2025 15:17:53 +0200 Subject: [PATCH 1242/2359] Docs: fixed unneeded usage of Build(). (#8883) --- docs/FONTS.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index ce08f176d..3fa7fd19c 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -150,7 +150,6 @@ ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 0.0f, &config); // Merge into first font to add e.g. Asian characters io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 0.0f, &config); // Merge into first font to add Icons -io.Fonts->Build(); ``` :rewind: **Before 1.92, or without an up to date backend:** ```cpp From 4dee11a089412a4ead7c84b0832b47a8ea5e2008 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2025 17:01:57 +0200 Subject: [PATCH 1243/2359] Make ImGuiInputSource int. (primarily to avoid "result of comparison 'ImGuiInputSource' < 0 is always false" in GetInputSourceName(). --- imgui_internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index dd2049569..ec6be29d8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1487,7 +1487,7 @@ enum ImGuiInputEventType ImGuiInputEventType_COUNT }; -enum ImGuiInputSource +enum ImGuiInputSource : int { ImGuiInputSource_None = 0, ImGuiInputSource_Mouse, // Note: may be Mouse or TouchScreen or Pen. See io.MouseSource to distinguish them. From 774ddb58bd5c4f2c5ce93b1ec447bcc2df6d3bec Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2025 17:06:05 +0200 Subject: [PATCH 1244/2359] Fixed IsItemHovered() failing on disabled items and items that have no identifier. Made holding on disabled items not leak IsItemDisabled() between disabled items when window has _NoMove. (#8877, #8883) See amends to "widgets_status_common", "widgets_disabled_2" tests. --- docs/CHANGELOG.txt | 5 +++++ imgui.cpp | 22 +++++++++++++++++++--- imgui.h | 2 +- imgui_internal.h | 1 + 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d1b421594..01fa71f57 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,11 @@ Breaking Changes: Other Changes: +- Fixed IsItemHovered() failing on disabled items and items that have no + identifier (e.g. Text() calls) when holding mouse button. (#8877, #8883) + [Regression in 1.92.2]. +- Made IsItemHovered() on holding mouse button down on disabled items not + leak between items when the window cannot be moved. - Backends: Allegro5: Fixed texture format setup which didn't work on all setups/drivers. (#8770, #8465) - Backends: Allegro5: Added ImGui_ImplAllegro5_SetDisplay() function to diff --git a/imgui.cpp b/imgui.cpp index 2e3086582..2705d8b70 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4063,6 +4063,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) ActiveIdClickOffset = ImVec2(-1, -1); ActiveIdWindow = NULL; ActiveIdSource = ImGuiInputSource_None; + ActiveIdDisabledId = 0; ActiveIdMouseButton = -1; ActiveIdPreviousFrame = 0; memset(&DeactivatedItemData, 0, sizeof(DeactivatedItemData)); @@ -4555,6 +4556,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) g.ActiveIdWindow = window; g.ActiveIdHasBeenEditedThisFrame = false; g.ActiveIdFromShortcut = false; + g.ActiveIdDisabledId = 0; if (id) { g.ActiveIdIsAlive = id; @@ -4656,6 +4658,7 @@ static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, } // This is roughly matching the behavior of internal-facing ItemHoverable() +// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) { @@ -4697,7 +4700,17 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) const ImGuiID id = g.LastItemData.ID; if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0) if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) - return false; + { + // When ActiveId == MoveId it means that either: + // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag) + // - the (id == 0) test handles it, however, IsItemHovered() will leak between id==0 items (mostly visible when using _NoMove). // FIXME: May be fixed. + // - (2) user clicked a disabled item. UpdateMouseMovingWindowEndFrame() uses ActiveId == MoveId to avoid interference with item logic + sets ActiveIdDisabledId. + bool cancel_is_hovered = true; + if (g.ActiveId == window->MoveId && (id == 0 || g.ActiveIdDisabledId == id)) + cancel_is_hovered = false; + if (cancel_is_hovered) + return false; + } // Test if interactions on this window are blocked by an active popup or modal. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. @@ -4778,7 +4791,7 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag if (!g.ActiveIdFromShortcut) return false; - // Done with rectangle culling so we can perform heavier checks now. + // We are done with rectangle culling so we can perform heavier checks now. if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) { g.HoveredIdIsDisabled = true; @@ -5171,9 +5184,12 @@ void ImGui::UpdateMouseMovingWindowEndFrame() g.MovingWindow = NULL; // Cancel moving if clicked over an item which was disabled or inhibited by popups - // (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item)0 already) + // (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item) if (g.HoveredIdIsDisabled) + { g.MovingWindow = NULL; + g.ActiveIdDisabledId = g.HoveredId; + } } else if (root_window == NULL && g.NavWindow != NULL) { diff --git a/imgui.h b/imgui.h index 08927acd6..6069dbdd6 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.3 WIP" -#define IMGUI_VERSION_NUM 19221 +#define IMGUI_VERSION_NUM 19222 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_internal.h b/imgui_internal.h index ec6be29d8..d7d17cd45 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2212,6 +2212,7 @@ struct ImGuiContext bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. bool ActiveIdHasBeenEditedThisFrame; bool ActiveIdFromShortcut; + ImGuiID ActiveIdDisabledId; // When clicking a disabled item we set ActiveId=window->MoveId to avoid interference with widget code. Actual item ID is stored here. int ActiveIdMouseButton : 8; ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) ImGuiWindow* ActiveIdWindow; From 45acd5e0e82f4c954432533ae9985ff0e1aad6d5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 13 Aug 2025 17:31:01 +0200 Subject: [PATCH 1245/2359] Version 1.92.2b --- docs/CHANGELOG.txt | 6 +++--- imgui.cpp | 2 +- imgui.h | 4 ++-- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 01fa71f57..257071ae0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,12 +36,12 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.3 WIP (In Progress) + VERSION 1.92.2b (Released 2025-08-13) ----------------------------------------------------------------------- -Breaking Changes: +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92.2b -Other Changes: +Changes: - Fixed IsItemHovered() failing on disabled items and items that have no identifier (e.g. Text() calls) when holding mouse button. (#8877, #8883) diff --git a/imgui.cpp b/imgui.cpp index 2705d8b70..286171463 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.2b // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 6069dbdd6..81fb65819 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.2b // (headers) // Help: @@ -28,7 +28,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.3 WIP" +#define IMGUI_VERSION "1.92.2b" #define IMGUI_VERSION_NUM 19222 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 68f8eec9c..a8c2536f8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.2b // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0941783a8..34a967a99 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.2b // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index d7d17cd45..a11d4e409 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.2b // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 8824534e7..370d8f6ad 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.2b // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ce9ccd9f8..23ebf5dcd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.2b // (widgets code) /* From 86ec5c83429887bc700a7e4fbf54023d65d4e12c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 19 Aug 2025 15:15:41 +0200 Subject: [PATCH 1246/2359] Version 1.92.3 WIP --- docs/CHANGELOG.txt | 11 ++++++++++- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 19 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 257071ae0..e009fd5d4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.3 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.92.2b (Released 2025-08-13) ----------------------------------------------------------------------- @@ -50,7 +59,7 @@ Changes: leak between items when the window cannot be moved. - Backends: Allegro5: Fixed texture format setup which didn't work on all setups/drivers. (#8770, #8465) -- Backends: Allegro5: Added ImGui_ImplAllegro5_SetDisplay() function to +- Backends: Allegro5: Added ImGui_ImplAllegro5_SetDisplay() function to change current ALLEGRO_DISPLAY, as Allegro applications often need to do that. - Backends: Allegro5: Fixed missing support for ImGuiKey_PrintScreen under Windows, as raw Allegro 5 does not receive it. diff --git a/imgui.cpp b/imgui.cpp index 286171463..2705d8b70 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2b +// dear imgui, v1.92.3 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 81fb65819..0df769352 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2b +// dear imgui, v1.92.3 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.2b" -#define IMGUI_VERSION_NUM 19222 +#define IMGUI_VERSION "1.92.3 WIP" +#define IMGUI_VERSION_NUM 19223 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a8c2536f8..68f8eec9c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2b +// dear imgui, v1.92.3 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 34a967a99..0941783a8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2b +// dear imgui, v1.92.3 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index a11d4e409..d7d17cd45 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2b +// dear imgui, v1.92.3 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 370d8f6ad..8824534e7 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2b +// dear imgui, v1.92.3 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 23ebf5dcd..ce9ccd9f8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.2b +// dear imgui, v1.92.3 WIP // (widgets code) /* From 361e370fe02fe2e42550f896571b90e823c37d0d Mon Sep 17 00:00:00 2001 From: scribam Date: Sat, 16 Aug 2025 18:34:02 +0200 Subject: [PATCH 1247/2359] Examples: Android+OpenGL3: update Gradle project (#8888, #8878) --- docs/CHANGELOG.txt | 2 ++ .../android/.gitignore | 10 ++++--- .../android/app/build.gradle | 29 +++++++------------ .../android/app/src/main/AndroidManifest.xml | 3 +- .../android/build.gradle | 27 +++-------------- .../android/settings.gradle | 21 ++++++++++++++ 6 files changed, 45 insertions(+), 47 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e009fd5d4..e1aaef37a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking Changes: Other Changes: +- Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] + ----------------------------------------------------------------------- VERSION 1.92.2b (Released 2025-08-13) diff --git a/examples/example_android_opengl3/android/.gitignore b/examples/example_android_opengl3/android/.gitignore index 3c7a61910..41afcd57c 100644 --- a/examples/example_android_opengl3/android/.gitignore +++ b/examples/example_android_opengl3/android/.gitignore @@ -1,12 +1,14 @@ -.cxx -.externalNativeBuild build/ *.iml - -.idea .gradle +.idea +.DS_Store +/captures +.externalNativeBuild +.cxx local.properties # Android Studio puts a Gradle wrapper here, that we don't want: gradle/ +!gradle/libs.versions.toml gradlew* diff --git a/examples/example_android_opengl3/android/app/build.gradle b/examples/example_android_opengl3/android/app/build.gradle index 3a68c8371..e142f1917 100644 --- a/examples/example_android_opengl3/android/app/build.gradle +++ b/examples/example_android_opengl3/android/app/build.gradle @@ -1,16 +1,16 @@ -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) +} android { - compileSdkVersion 33 - buildToolsVersion "33.0.2" - ndkVersion "25.2.9519653" + namespace 'imgui.example.android' + compileSdk 36 defaultConfig { applicationId "imgui.example.android" - namespace "imgui.example.android" - minSdkVersion 24 - targetSdkVersion 33 + minSdk 24 + targetSdk 36 versionCode 1 versionName "1.0" } @@ -21,26 +21,17 @@ android { proguardFiles getDefaultProguardFile('proguard-android-optimize.txt') } } - compileOptions { sourceCompatibility JavaVersion.VERSION_11 targetCompatibility JavaVersion.VERSION_11 } - kotlinOptions { - jvmTarget="11" + jvmTarget = '11' } - externalNativeBuild { cmake { - path "../../CMakeLists.txt" + path file('../../CMakeLists.txt') version '3.22.1' } } } -repositories { - mavenCentral() -} -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" -} diff --git a/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml b/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml index 5a1e2d9e5..6410b5a13 100644 --- a/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml +++ b/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml @@ -1,5 +1,6 @@ - + Date: Sat, 16 Aug 2025 18:34:02 +0200 Subject: [PATCH 1248/2359] Examples: Android+OpenGL3: update Gradle project, amend. (#8888, #8878) --- .../android/gradle/libs.versions.toml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 examples/example_android_opengl3/android/gradle/libs.versions.toml diff --git a/examples/example_android_opengl3/android/gradle/libs.versions.toml b/examples/example_android_opengl3/android/gradle/libs.versions.toml new file mode 100644 index 000000000..82971810b --- /dev/null +++ b/examples/example_android_opengl3/android/gradle/libs.versions.toml @@ -0,0 +1,8 @@ +[versions] +agp = "8.12.0" +kotlin = "2.0.21" + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } +kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } + From 321e9eb919685bf589a301ed566bf69e948959d0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 19 Aug 2025 15:32:12 +0200 Subject: [PATCH 1249/2359] Fixes for printing out ImTextureID value when it is typedef to other types. (#8889) --- imgui_draw.cpp | 6 +++--- imgui_internal.h | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0941783a8..4b089286f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4516,16 +4516,16 @@ void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) if (tex->Status == ImTextureStatus_WantCreate) IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: create %dx%d\n", tex->UniqueID, tex->Width, tex->Height); else if (tex->Status == ImTextureStatus_WantDestroy) - IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: destroy %dx%d, texid=0x%" IM_PRIX64 ", backend_data=%p\n", tex->UniqueID, tex->Width, tex->Height, tex->TexID, tex->BackendUserData); + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: destroy %dx%d, texid=0x%" IM_PRIX64 ", backend_data=%p\n", tex->UniqueID, tex->Width, tex->Height, IM_TEXTUREID_TO_U64(tex->TexID), tex->BackendUserData); else if (tex->Status == ImTextureStatus_WantUpdates) { - IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, IM_TEXTUREID_TO_U64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData); for (const ImTextureRect& r : tex->Updates) { IM_UNUSED(r); IM_ASSERT(r.x >= 0 && r.y >= 0); IM_ASSERT(r.x + r.w <= tex->Width && r.y + r.h <= tex->Height); // In theory should subtract PackPadding but it's currently part of atlas and mid-frame change would wreck assert. - //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); + //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, IM_TEXTUREID_TO_U64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData); } } } diff --git a/imgui_internal.h b/imgui_internal.h index d7d17cd45..b2a675e8d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -335,6 +335,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IM_PRIu64 "llu" #define IM_PRIX64 "llX" #endif +#define IM_TEXTUREID_TO_U64(_TEXID) ((ImU64)(intptr_t)(_TEXID)) //----------------------------------------------------------------------------- // [SECTION] Generic helpers From 720e94f3daae98094196e8f27701ac8285469376 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 19 Aug 2025 15:32:38 +0200 Subject: [PATCH 1250/2359] Rework FormatTextureIDForDebugDisplay() ImDrawCmd version as FormatTextureRefForDebugDisplay(). --- imgui.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2705d8b70..bc19d1aeb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15940,12 +15940,12 @@ static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTex return buf; } -static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, const ImDrawCmd* cmd) +static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTextureRef tex_ref) { char* buf_end = buf + buf_size; - if (cmd->TexRef._TexData != NULL) - buf += ImFormatString(buf, buf_end - buf, "#%03d: ", cmd->TexRef._TexData->UniqueID); - return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), cmd->TexRef.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID() + if (tex_ref._TexData != NULL) + buf += ImFormatString(buf, buf_end - buf, "#%03d: ", tex_ref._TexData->UniqueID); + return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), tex_ref.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID() } #ifdef IMGUI_ENABLE_FREETYPE @@ -16133,7 +16133,7 @@ void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRe char texid_desc[30]; Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors); - Text("TexID = %s, BackendUserData = %p", FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->TexID), tex->BackendUserData); + Text("TexID = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->GetTexRef()), tex->BackendUserData); TreePop(); } PopID(); @@ -16834,7 +16834,7 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con } char texid_desc[30]; - FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd); + FormatTextureRefForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TexRef); char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); From 0c4f50090aa9ec3d9ea7d0159a801dd2cea5df83 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Aug 2025 17:48:03 +0200 Subject: [PATCH 1251/2359] DrawList: fixed CloneOutput() taking a copy of the ImDrawListSharedData pointer. (#8894, #1860) Amend b82e99c032 --- imgui.h | 2 +- imgui_draw.cpp | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 0df769352..95c70c71b 100644 --- a/imgui.h +++ b/imgui.h @@ -3316,7 +3316,7 @@ struct ImDrawList // Advanced: Miscellaneous IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible - IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. + IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. For multi-threaded rendering, consider using `imgui_threaded_rendering` from https://github.com/ocornut/imgui_club instead. // Advanced: Channels // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4b089286f..0426d4a2e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -478,9 +478,10 @@ void ImDrawList::_ClearFreeMemory() _Splitter.ClearFreeMemory(); } +// Note: For multi-threaded rendering, consider using `imgui_threaded_rendering` from https://github.com/ocornut/imgui_club ImDrawList* ImDrawList::CloneOutput() const { - ImDrawList* dst = IM_NEW(ImDrawList(_Data)); + ImDrawList* dst = IM_NEW(ImDrawList(NULL)); dst->CmdBuffer = CmdBuffer; dst->IdxBuffer = IdxBuffer; dst->VtxBuffer = VtxBuffer; From 89b7fc906a993228edc120fc13092c016663794c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Aug 2025 17:57:06 +0200 Subject: [PATCH 1252/2359] DrawList: fixed CloneOutput() taking a copy of the ImDrawListSharedData pointer. Missing Changelog. (#8894, #1860) --- docs/CHANGELOG.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e1aaef37a..02858c4c6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking Changes: Other Changes: +- DrawList: Fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData + pointer, which could to issue when deleting the cloned list. (#8894, #1860) - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] From 42656b3aa197f57e32b94ceb00cf6bf309992436 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Aug 2025 18:27:35 +0200 Subject: [PATCH 1253/2359] Scrollbar, Style: added style.ScrollbarPadding, ImGuiStyleVar_ScrollbarPadding. (#8895) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 3 +++ imgui.h | 2 ++ imgui_demo.cpp | 7 +++++-- imgui_widgets.cpp | 3 ++- 5 files changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 02858c4c6..b126e5f15 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking Changes: Other Changes: +- Scrollbar, Style: added configurable style.ScrollbarPadding value and corresponding + ImGuiStyleVar_ScrollbarPadding enum, instead of hardcoded computed default. (#8895) - DrawList: Fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] diff --git a/imgui.cpp b/imgui.cpp index bc19d1aeb..8b201ee76 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1413,6 +1413,7 @@ ImGuiStyle::ImGuiStyle() ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar + ScrollbarPadding = 2.0f; // Padding of scrollbar grab within its frame (same for both axises) GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. @@ -1482,6 +1483,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor); ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor); ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor); + ScrollbarPadding = ImTrunc(ScrollbarPadding * scale_factor); GrabMinSize = ImTrunc(GrabMinSize * scale_factor); GrabRounding = ImTrunc(GrabRounding * scale_factor); LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); @@ -3503,6 +3505,7 @@ static const ImGuiStyleVarInfo GStyleVarsInfo[] = { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarPadding) }, // ImGuiStyleVar_ScrollbarPadding { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize diff --git a/imgui.h b/imgui.h index 95c70c71b..6b35f8403 100644 --- a/imgui.h +++ b/imgui.h @@ -1805,6 +1805,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_CellPadding, // ImVec2 CellPadding ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding + ImGuiStyleVar_ScrollbarPadding, // float ScrollbarPadding ImGuiStyleVar_GrabMinSize, // float GrabMinSize ImGuiStyleVar_GrabRounding, // float GrabRounding ImGuiStyleVar_ImageBorderSize, // float ImageBorderSize @@ -2271,6 +2272,7 @@ struct ImGuiStyle float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. float ScrollbarRounding; // Radius of grab corners for scrollbar. + float ScrollbarPadding; // Padding of scrollbar grab within its frame (same for both axises). float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 68f8eec9c..be1698bdd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8325,7 +8325,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); - SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); SeparatorText("Borders"); @@ -8339,9 +8338,13 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); - SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); + SeparatorText("Scrollbar"); + SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("ScrollbarPadding", &style.ScrollbarPadding, 0.0f, 10.0f, "%.0f"); + SeparatorText("Tabs"); SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ce9ccd9f8..4a64b2c21 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1026,7 +1026,8 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 const bool allow_interaction = (alpha >= 1.0f); ImRect bb = bb_frame; - bb.Expand(ImVec2(-ImClamp(IM_TRUNC((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_TRUNC((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f))); + float padding = IM_TRUNC(ImMin(style.ScrollbarPadding, ImMin(bb_frame_width, bb_frame_height) * 0.5f)); + bb.Expand(-padding); // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight(); From 7c6fa8f8f71007d2dfed4e2be66af9ff9c7edcec Mon Sep 17 00:00:00 2001 From: PTSVU Date: Tue, 19 Aug 2025 12:48:59 +0300 Subject: [PATCH 1254/2359] Backends: SDL_GPU: add swapchain parameters to ImGui_ImplSDLGPU3_InitInfo. (#8892) (master branch commit, values are not used) --- backends/imgui_impl_sdlgpu3.cpp | 1 + backends/imgui_impl_sdlgpu3.h | 10 ++++++---- examples/example_sdl3_sdlgpu3/main.cpp | 4 +++- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index c2f465136..61056718d 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -22,6 +22,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-08-20: Added SwapchainComposition::SwapchainComposition and SwapchainComposition::PresentMode to configure how secondary viewports are created. // 2025-08-08: *BREAKING* Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) // 2025-08-08: Expose SamplerDefault and SamplerCurrent in ImGui_ImplSDLGPU3_RenderState. Allow callback to change sampler. // 2025-06-25: Mapping transfer buffer for texture update use cycle=true. Fixes artifacts e.g. on Metal backend. diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index 1ab3a5a84..cde9c5fe7 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -27,12 +27,14 @@ #include // Initialization data, for ImGui_ImplSDLGPU_Init() -// - Remember to set ColorTargetFormat to the correct format. If you're rendering to the swapchain, call SDL_GetGPUSwapchainTextureFormat to query the right value +// - Remember to set ColorTargetFormat to the correct format. If you're rendering to the swapchain, call SDL_GetGPUSwapchainTextureFormat() to query the right value struct ImGui_ImplSDLGPU3_InitInfo { - SDL_GPUDevice* Device = nullptr; - SDL_GPUTextureFormat ColorTargetFormat = SDL_GPU_TEXTUREFORMAT_INVALID; - SDL_GPUSampleCount MSAASamples = SDL_GPU_SAMPLECOUNT_1; + SDL_GPUDevice* Device = nullptr; + SDL_GPUTextureFormat ColorTargetFormat = SDL_GPU_TEXTUREFORMAT_INVALID; + SDL_GPUSampleCount MSAASamples = SDL_GPU_SAMPLECOUNT_1; + SDL_GPUSwapchainComposition SwapchainComposition = SDL_GPU_SWAPCHAINCOMPOSITION_SDR; // Only used in multi-viewports mode. + SDL_GPUPresentMode PresentMode = SDL_GPU_PRESENTMODE_VSYNC; // Only used in multi-viewports mode. }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 380b8c574..1566cf368 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -83,7 +83,9 @@ int main(int, char**) ImGui_ImplSDLGPU3_InitInfo init_info = {}; init_info.Device = gpu_device; init_info.ColorTargetFormat = SDL_GetGPUSwapchainTextureFormat(gpu_device, window); - init_info.MSAASamples = SDL_GPU_SAMPLECOUNT_1; + init_info.MSAASamples = SDL_GPU_SAMPLECOUNT_1; // Only used in multi-viewports mode. + init_info.SwapchainComposition = SDL_GPU_SWAPCHAINCOMPOSITION_SDR; // Only used in multi-viewports mode. + init_info.PresentMode = SDL_GPU_PRESENTMODE_VSYNC; ImGui_ImplSDLGPU3_Init(&init_info); // Load Fonts From 515c0b526f144f72d00e60a3c1decb7912b226a6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Aug 2025 18:53:25 +0200 Subject: [PATCH 1255/2359] Backends: SDL_GPU: typo + changelog. (#8892) --- backends/imgui_impl_sdlgpu3.cpp | 2 +- docs/CHANGELOG.txt | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 61056718d..8420da4c5 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -22,7 +22,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG -// 2025-08-20: Added SwapchainComposition::SwapchainComposition and SwapchainComposition::PresentMode to configure how secondary viewports are created. +// 2025-08-20: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and ImGui_ImplSDLGPU3_InitInfo::PresentMode to configure how secondary viewports are created. // 2025-08-08: *BREAKING* Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) // 2025-08-08: Expose SamplerDefault and SamplerCurrent in ImGui_ImplSDLGPU3_RenderState. Allow callback to change sampler. // 2025-06-25: Mapping transfer buffer for texture update use cycle=true. Fixes artifacts e.g. on Metal backend. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b126e5f15..073a37b6b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,9 @@ Other Changes: - DrawList: Fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] +- Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and + PresentMode to configure how secondary viewports are created. Currently only used + in multi-viewport mode. (#8892) ----------------------------------------------------------------------- From fe0303511292491e9ec1802b7eadfc5f805c9d86 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Aug 2025 19:58:19 +0200 Subject: [PATCH 1256/2359] Docs: advertise ProggyVector font as an alternative. --- docs/FONTS.md | 11 +++++++---- examples/example_allegro5/main.cpp | 2 +- examples/example_android_opengl3/main.cpp | 2 +- examples/example_apple_metal/main.mm | 2 +- examples/example_apple_opengl2/main.mm | 2 +- examples/example_glfw_metal/main.mm | 2 +- examples/example_glfw_opengl2/main.cpp | 2 +- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_glfw_vulkan/main.cpp | 2 +- examples/example_glfw_wgpu/main.cpp | 2 +- examples/example_glut_opengl2/main.cpp | 2 +- examples/example_sdl2_directx11/main.cpp | 2 +- examples/example_sdl2_metal/main.mm | 2 +- examples/example_sdl2_opengl2/main.cpp | 2 +- examples/example_sdl2_opengl3/main.cpp | 2 +- examples/example_sdl2_sdlrenderer2/main.cpp | 2 +- examples/example_sdl2_vulkan/main.cpp | 2 +- examples/example_sdl3_metal/main.mm | 2 +- examples/example_sdl3_opengl3/main.cpp | 2 +- examples/example_sdl3_sdlgpu3/main.cpp | 2 +- examples/example_sdl3_sdlrenderer3/main.cpp | 2 +- examples/example_sdl3_vulkan/main.cpp | 2 +- examples/example_win32_directx10/main.cpp | 2 +- examples/example_win32_directx11/main.cpp | 2 +- examples/example_win32_directx12/main.cpp | 2 +- examples/example_win32_directx9/main.cpp | 2 +- examples/example_win32_opengl3/main.cpp | 2 +- examples/example_win32_vulkan/main.cpp | 2 +- imgui_draw.cpp | 2 ++ 29 files changed, 36 insertions(+), 31 deletions(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index 3fa7fd19c..072ca9762 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -587,15 +587,18 @@ Some fonts files are available in the `misc/fonts/` folder: #### MONOSPACE FONTS +image + Pixel Perfect: - Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php - Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font (also include an .inl file to use directly in dear imgui.) Regular: -- Google Noto Mono Fonts https://www.google.com/get/noto/ -- Typefaces for source code beautification https://github.com/chrissimpkins/codeface -- Programmation fonts http://s9w.github.io/font_compare/ -- Inconsolata http://www.levien.com/type/myfonts/inconsolata.html +- ProggyVector if you want the old school Dear ImGui font to scale: https://github.com/bluescan/proggyfonts +- Google Noto Mono Fonts: https://www.google.com/get/noto/ +- Typefaces for source code beautification: https://github.com/chrissimpkins/codeface +- Programmation fonts: http://s9w.github.io/font_compare/ +- Inconsolata: http://www.levien.com/type/myfonts/inconsolata.html - Adobe Source Code Pro: Monospaced font family for ui & coding environments https://github.com/adobe-fonts/source-code-pro - Monospace/Fixed Width Programmer's Fonts http://www.lowing.org/fonts/ diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 02db84a48..cde2c676a 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -53,7 +53,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_android_opengl3/main.cpp b/examples/example_android_opengl3/main.cpp index 452cb77d9..568d6f02b 100644 --- a/examples/example_android_opengl3/main.cpp +++ b/examples/example_android_opengl3/main.cpp @@ -154,7 +154,7 @@ void Init(struct android_app* app) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them. diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 301a2b4ad..0349dfbdc 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -73,7 +73,7 @@ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index c3f0c313b..9b4fa1860 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -61,7 +61,7 @@ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index ef314702a..9f4b82c4f 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -43,7 +43,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 83fcab65f..411a5891d 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -66,7 +66,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 4bd7bc591..6dfeacb96 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -106,7 +106,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 19766b9f3..7ad9778f1 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -418,7 +418,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index c150b5961..e30df5662 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -115,7 +115,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details. //io.Fonts->AddFontDefault(); diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 69f85a245..e72b94830 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -84,7 +84,7 @@ int main(int argc, char** argv) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index 194dd0e03..2e347752f 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -94,7 +94,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index c1750b16b..97a643759 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -34,7 +34,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index c8363fece..7385f4cd1 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -83,7 +83,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index 16a73deb6..c59836f6e 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -123,7 +123,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index e456b2e9e..76f17d3f6 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -85,7 +85,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 300543fba..de6745623 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -430,7 +430,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index 50c33c82d..98c4a9490 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -81,7 +81,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index cfd6f6a1a..25b6b1937 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -113,7 +113,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 1566cf368..bef16fe5b 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -93,7 +93,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 6e39429d2..f98986943 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -75,7 +75,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index df7f5efbd..743e68dba 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -429,7 +429,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 23033d6c1..12f10ab4d 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -76,7 +76,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index c80114cfb..2b85895f7 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -76,7 +76,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 3a9ba4fb4..4ff7c54e5 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -170,7 +170,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 430a2b448..66369d242 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -74,7 +74,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 6b88497c0..8748ab777 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -76,7 +76,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index a98f16fe2..aa80e8696 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -409,7 +409,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefault(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0426d4a2e..3ef76efec 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3097,6 +3097,7 @@ static const char* GetDefaultCompressedFontDataTTF(int* out_size); #endif // Load embedded ProggyClean.ttf at size 13, disable oversampling +// If you want a similar font which may be better scaled, consider using ProggyVector from the same author! ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) { #ifndef IMGUI_DISABLE_DEFAULT_FONT @@ -6118,6 +6119,7 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i // Copyright (c) 2004, 2005 Tristan Grimmer // MIT license (see License.txt in http://www.proggyfonts.net/index.php?menu=download) // Download and more information at http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php +// If you want a similar font which may be better scaled, consider using ProggyVector from the same author! //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_DEFAULT_FONT From e728b966003104c7fc21a007237bca10abf39b19 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 Aug 2025 20:22:31 +0200 Subject: [PATCH 1257/2359] Fixed Bullet() fixed tesselation amount which looked out of place in very large sizes. --- docs/CHANGELOG.txt | 3 ++- imgui_draw.cpp | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 073a37b6b..e053076f8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,12 +45,13 @@ Other Changes: - Scrollbar, Style: added configurable style.ScrollbarPadding value and corresponding ImGuiStyleVar_ScrollbarPadding enum, instead of hardcoded computed default. (#8895) +- Fixed Bullet() fixed tesselation amount which looked out of place in very large sizes. - DrawList: Fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used - in multi-viewport mode. (#8892) + multi-viewport mode. (#8892) [@PTSVU] ----------------------------------------------------------------------- diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3ef76efec..31beb4133 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5835,8 +5835,9 @@ void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir d void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col) { - // FIXME-OPT: This should be baked in font. - draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8); + // FIXME-OPT: This should be baked in font now that it's easier. + float font_size = draw_list->_Data->FontSize; + draw_list->AddCircleFilled(pos, font_size * 0.20f, col, (font_size < 22) ? 8 : (font_size < 40) ? 12 : 0); // Hardcode optimal/nice tessellation threshold } void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz) From 783f1e62cc122f8bc5a76b068e366c38b9dca71c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Aug 2025 15:36:56 +0200 Subject: [PATCH 1258/2359] Debug Tools: ID Stack Tool: fixed using fixed-size buffers preventing long identifiers from being displayed in the tool. (#8905, #4631) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 59 ++++++++++++++++++++++++++-------------------- imgui_internal.h | 9 +++---- 3 files changed, 40 insertions(+), 30 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e053076f8..1e52af5fd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,8 @@ Other Changes: - Fixed Bullet() fixed tesselation amount which looked out of place in very large sizes. - DrawList: Fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) +- Debug Tools: ID Stack Tool: fixed using fixed-size buffers preventing long identifiers + from being displayed in the tool. (#8905, #4631) - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used diff --git a/imgui.cpp b/imgui.cpp index 8b201ee76..5a16e5d08 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17645,6 +17645,7 @@ void ImGui::UpdateDebugToolStackQueries() tool->QueryId = query_id; tool->StackLevel = -1; tool->Results.resize(0); + tool->ResultPathsBuf.resize(0); } if (query_id == 0) return; @@ -17691,37 +17692,43 @@ void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* dat ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel]; IM_ASSERT(info->ID == id && info->QueryFrameCount > 0); - switch (data_type) + if (info->DescOffset == -1) { - case ImGuiDataType_S32: - ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id); - break; - case ImGuiDataType_String: - ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*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: - ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id); - break; - case ImGuiDataType_ID: - if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one. - return; - ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id); - break; - default: - IM_ASSERT(0); + const char* result = NULL; + const char* result_end = NULL; + switch (data_type) + { + case ImGuiDataType_S32: + ImFormatStringToTempBuffer(&result, &result_end, "%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); + break; + case ImGuiDataType_Pointer: + ImFormatStringToTempBuffer(&result, &result_end, "(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); + break; + default: + IM_ASSERT(0); + } + info->DescOffset = tool->ResultPathsBuf.size(); + tool->ResultPathsBuf.append(result, result_end + 1); // Include zero terminator } info->QuerySuccess = true; - info->DataType = data_type; + info->DataType = (ImS8)data_type; } static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size) { ImGuiStackLevelInfo* info = &tool->Results[n]; - ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL; + ImGuiWindow* window = (info->DescOffset == -1 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL; if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked) return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name); if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) - return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc); + return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", &tool->ResultPathsBuf.Buf[info->DescOffset]); if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. return (*buf = 0); #ifdef IMGUI_ENABLE_TEST_ENGINE @@ -17747,17 +17754,17 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) ImGuiIDStackTool* tool = &g.DebugIDStackTool; // Build and display path - tool->ResultPathBuf.resize(0); + tool->ResultTempBuf.resize(0); for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++) { char level_desc[256]; StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); - tool->ResultPathBuf.append(stack_n == 0 ? "//" : "/"); + tool->ResultTempBuf.append(stack_n == 0 ? "//" : "/"); for (int n = 0; level_desc[n]; n++) { if (level_desc[n] == '/') - tool->ResultPathBuf.append("\\"); - tool->ResultPathBuf.append(level_desc + n, level_desc + n + 1); + tool->ResultTempBuf.append("\\"); + tool->ResultTempBuf.append(level_desc + n, level_desc + n + 1); } } Text("0x%08X", tool->QueryId); @@ -17773,10 +17780,10 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused)) { tool->CopyToClipboardLastTime = (float)g.Time; - SetClipboardText(tool->ResultPathBuf.c_str()); + SetClipboardText(tool->ResultTempBuf.c_str()); } - Text("- Path \"%s\"", tool->ResultPathBuf.c_str()); + Text("- Path \"%s\"", tool->ResultTempBuf.c_str()); #ifdef IMGUI_ENABLE_TEST_ENGINE Text("- Label \"%s\"", tool->QueryId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryId) : ""); #endif diff --git a/imgui_internal.h b/imgui_internal.h index b2a675e8d..ee4c75d18 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2095,10 +2095,10 @@ struct ImGuiStackLevelInfo ImGuiID ID; ImS8 QueryFrameCount; // >= 1: Query in progress bool QuerySuccess; // Obtained result from DebugHookIdInfo() - ImGuiDataType DataType : 8; - char Desc[57]; // Arbitrarily sized buffer to hold a result (FIXME: could replace Results[] with a chunk stream?) FIXME: Now that we added CTRL+C this should be fixed. + ImS8 DataType; // ImGuiDataType + int DescOffset; // -1 or offset into parent's ResultPathsBuf - ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); } + ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); DescOffset = -1; } }; // State for ID Stack tool queries @@ -2110,7 +2110,8 @@ struct ImGuiIDStackTool ImVector Results; bool CopyToClipboardOnCtrlC; float CopyToClipboardLastTime; - ImGuiTextBuffer ResultPathBuf; + ImGuiTextBuffer ResultPathsBuf; + ImGuiTextBuffer ResultTempBuf; ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); CopyToClipboardLastTime = -FLT_MAX; } }; From 9e864012ae15568877f7157da2be552fb26ed7c8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Aug 2025 15:58:59 +0200 Subject: [PATCH 1259/2359] Debug Tools: ID Stack Tool: added option to hex-encode non-ASCII characters in output path. (#8904, #4631) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 19 ++++++++++++++----- imgui_internal.h | 5 +++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1e52af5fd..28e4ab272 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Other Changes: pointer, which could to issue when deleting the cloned list. (#8894, #1860) - Debug Tools: ID Stack Tool: fixed using fixed-size buffers preventing long identifiers from being displayed in the tool. (#8905, #4631) +- Debug Tools: ID Stack Tool: added option to hex-encode non-ASCII characters in + output path. (#8904, #4631) - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used diff --git a/imgui.cpp b/imgui.cpp index 5a16e5d08..0d4bd99a9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17760,11 +17760,17 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) char level_desc[256]; StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); tool->ResultTempBuf.append(stack_n == 0 ? "//" : "/"); - for (int n = 0; level_desc[n]; n++) + for (const char* p = level_desc; *p != 0; ) { - if (level_desc[n] == '/') + unsigned int c; + const char* p_next = p + ImTextCharFromUtf8(&c, p, NULL); + if (c == '/') tool->ResultTempBuf.append("\\"); - tool->ResultTempBuf.append(level_desc + n, level_desc + n + 1); + if (c < 256 || !tool->OptHexEncodeNonAsciiChars) + tool->ResultTempBuf.append(p, p_next); + else for (; p < p_next; p++) + tool->ResultTempBuf.appendf("\\x%02x", (unsigned char)*p); + p = p_next; } } Text("0x%08X", tool->QueryId); @@ -17773,11 +17779,14 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) // CTRL+C to copy path const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime; + PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f); + Checkbox("Hex-encode non-ASCII", &tool->OptHexEncodeNonAsciiChars); SameLine(); - PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f); Checkbox("Ctrl+C: copy path", &tool->CopyToClipboardOnCtrlC); PopStyleVar(); + Checkbox("Ctrl+C: copy path", &tool->OptCopyToClipboardOnCtrlC); + PopStyleVar(); SameLine(); TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*"); - if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused)) + if (tool->OptCopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused)) { tool->CopyToClipboardLastTime = (float)g.Time; SetClipboardText(tool->ResultTempBuf.c_str()); diff --git a/imgui_internal.h b/imgui_internal.h index ee4c75d18..1b21a8fcd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2108,12 +2108,13 @@ struct ImGuiIDStackTool int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level ImGuiID QueryId; // ID to query details for ImVector Results; - bool CopyToClipboardOnCtrlC; + bool OptHexEncodeNonAsciiChars; + bool OptCopyToClipboardOnCtrlC; float CopyToClipboardLastTime; ImGuiTextBuffer ResultPathsBuf; ImGuiTextBuffer ResultTempBuf; - ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); CopyToClipboardLastTime = -FLT_MAX; } + ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; } }; //----------------------------------------------------------------------------- From 75a4a48d1fdb5fb80045b4be6ea81a505e02af84 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Aug 2025 16:19:08 +0200 Subject: [PATCH 1260/2359] Internals: extracted ImHashSkipUncontributingPrefix() out of CreateNewWindowSettings() and added note about it. --- imgui.cpp | 16 ++++++++++------ imgui_internal.h | 1 + 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0d4bd99a9..4207012ed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2387,6 +2387,14 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed) return ~crc; } +// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() +const char* ImHashSkipUncontributingPrefix(const char* label) +{ + if (const char* p = strstr(label, "###")) // FIXME: Should loop. + label = p; + return label; +} + //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (File functions) //----------------------------------------------------------------------------- @@ -15259,13 +15267,9 @@ ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) { ImGuiContext& g = *GImGui; + // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. if (g.IO.ConfigDebugIniSettings == false) - { - // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() - // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. - if (const char* p = strstr(name, "###")) - name = p; - } + name = ImHashSkipUncontributingPrefix(name); const size_t name_len = ImStrlen(name); // Allocate chunk diff --git a/imgui_internal.h b/imgui_internal.h index 1b21a8fcd..3085648dd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -367,6 +367,7 @@ 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); // Helpers: Sorting #ifndef ImQsort From 7d230594decfb434624c3d466acc95f96132ed5e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Aug 2025 16:25:33 +0200 Subject: [PATCH 1261/2359] Fixed ImHashSkipUncontributingPrefix() not looping in case of multiple ### elements. --- imgui.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4207012ed..57ea52195 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2388,11 +2388,14 @@ 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) { - if (const char* p = strstr(label, "###")) // FIXME: Should loop. - label = p; - return label; + const char* result = label; + while (unsigned char c = *label++) + if (c == '#' && label[0] == '#' && label[1] == '#') + result = label - 1; + return result; } //----------------------------------------------------------------------------- From 229d56e37a5d6e5f3cf8dee284754c2c8f3f5ca9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Aug 2025 16:30:13 +0200 Subject: [PATCH 1262/2359] Debug Tools: ID Stack Tool: when ### is used, uncontributing prefix before the ### is now skipped. (#8904, #4631) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 28e4ab272..435057852 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Other Changes: pointer, which could to issue when deleting the cloned list. (#8894, #1860) - Debug Tools: ID Stack Tool: fixed using fixed-size buffers preventing long identifiers from being displayed in the tool. (#8905, #4631) +- Debug Tools: ID Stack Tool: when ### is used, uncontributing prefix before the ### + is now skipped. (#8904, #4631) - Debug Tools: ID Stack Tool: added option to hex-encode non-ASCII characters in output path. (#8904, #4631) - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] diff --git a/imgui.cpp b/imgui.cpp index 57ea52195..16ae8d123 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17733,14 +17733,14 @@ static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_f ImGuiStackLevelInfo* info = &tool->Results[n]; ImGuiWindow* window = (info->DescOffset == -1 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL; if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked) - return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name); + return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", ImHashSkipUncontributingPrefix(window->Name)); if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) - return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", &tool->ResultPathsBuf.Buf[info->DescOffset]); + return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", ImHashSkipUncontributingPrefix(&tool->ResultPathsBuf.Buf[info->DescOffset])); if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. return (*buf = 0); #ifdef IMGUI_ENABLE_TEST_ENGINE if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo() - return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label); + return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", ImHashSkipUncontributingPrefix(label)); #endif return ImFormatString(buf, buf_size, "???"); } From 319c481abb380fcc0c37d6310f3f083ecff22c63 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Aug 2025 17:57:51 +0200 Subject: [PATCH 1263/2359] AddFontDefault(): shallow simplification. --- imgui.cpp | 2 +- imgui_draw.cpp | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 16ae8d123..18e67eab2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17160,7 +17160,7 @@ void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) if (glyph->PackId >= 0) { ImTextureRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId); - Text("PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y); + Text("PackId: 0x%X (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y); } Text("SourceIdx: %d", glyph->SourceIdx); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 31beb4133..c4dd43a52 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3116,9 +3116,7 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) int ttf_compressed_size = 0; const char* ttf_compressed = GetDefaultCompressedFontDataTTF(&ttf_compressed_size); - const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault(); - ImFont* font = AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg, glyph_ranges); - return font; + return AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg); #else IM_ASSERT(0 && "AddFontDefault() disabled in this build."); IM_UNUSED(font_cfg_template); From 87c1ab79883b90b5c8fc9698a8bff0bfb7f1b5c8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Aug 2025 18:48:08 +0200 Subject: [PATCH 1264/2359] Windows: changed how g.CurrentItemFlags is modified before windows' CloseButton() submission to be less misleading. (#8903) I don't think anyone would have `ImGuiItemFlags_NoFocus` set globally but technically it might. --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 18e67eab2..bc4da78ee 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7113,10 +7113,11 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl // Close button if (has_close_button) { + ImGuiItemFlags backup_item_flags = g.CurrentItemFlags; g.CurrentItemFlags |= ImGuiItemFlags_NoFocus; if (CloseButton(window->GetID("#CLOSE"), close_button_pos)) *p_open = false; - g.CurrentItemFlags &= ~ImGuiItemFlags_NoFocus; + g.CurrentItemFlags = backup_item_flags; } window->DC.NavLayerCurrent = ImGuiNavLayer_Main; From a309d2dcac2c0941a6a04ef1e4d07b7d9c5b9485 Mon Sep 17 00:00:00 2001 From: Christian Fillion Date: Wed, 27 Aug 2025 00:05:30 -0400 Subject: [PATCH 1265/2359] Fonts: fixed assertion failure when ImFontAtlasRectEntry::Generation overflows. (#8906) --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 2 ++ imgui_internal.h | 10 +++++----- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 435057852..619e0c42e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,8 @@ Other Changes: - Scrollbar, Style: added configurable style.ScrollbarPadding value and corresponding ImGuiStyleVar_ScrollbarPadding enum, instead of hardcoded computed default. (#8895) +- Fonts: fixed an assertion failure when a rectangle entry has been reused + 1024 times (e.g. due to constant change of font types). (#8906) [@cfillion] - Fixed Bullet() fixed tesselation amount which looked out of place in very large sizes. - DrawList: Fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c4dd43a52..76d8474bf 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4293,6 +4293,8 @@ void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) index_entry->IsUsed = false; index_entry->TargetIndex = builder->RectsIndexFreeListStart; index_entry->Generation++; + if (index_entry->Generation == 0) + index_entry->Generation++; // Keep non-zero on overflow const int pack_padding = atlas->TexGlyphPadding; builder->RectsIndexFreeListStart = index_idx; diff --git a/imgui_internal.h b/imgui_internal.h index 3085648dd..873e7881e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3736,12 +3736,12 @@ inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { re inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } // Refer to ImFontAtlasPackGetRect() to better understand how this works. -#define ImFontAtlasRectId_IndexMask_ (0x000FFFFF) // 20-bits: index to access builder->RectsIndex[]. +#define ImFontAtlasRectId_IndexMask_ (0x0007FFFF) // 20-bits signed: index to access builder->RectsIndex[]. #define ImFontAtlasRectId_GenerationMask_ (0x3FF00000) // 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. #define ImFontAtlasRectId_GenerationShift_ (20) -inline int ImFontAtlasRectId_GetIndex(ImFontAtlasRectId id) { return id & ImFontAtlasRectId_IndexMask_; } -inline int ImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id) { return (id & ImFontAtlasRectId_GenerationMask_) >> ImFontAtlasRectId_GenerationShift_; } -inline ImFontAtlasRectId ImFontAtlasRectId_Make(int index_idx, int gen_idx) { IM_ASSERT(index_idx < ImFontAtlasRectId_IndexMask_ && gen_idx < (ImFontAtlasRectId_GenerationMask_ >> ImFontAtlasRectId_GenerationShift_)); return (ImFontAtlasRectId)(index_idx | (gen_idx << ImFontAtlasRectId_GenerationShift_)); } +inline int ImFontAtlasRectId_GetIndex(ImFontAtlasRectId id) { return (id & ImFontAtlasRectId_IndexMask_); } +inline unsigned int ImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id) { return (unsigned int)(id & ImFontAtlasRectId_GenerationMask_) >> ImFontAtlasRectId_GenerationShift_; } +inline ImFontAtlasRectId ImFontAtlasRectId_Make(int index_idx, int gen_idx) { IM_ASSERT(index_idx >= 0 && index_idx <= ImFontAtlasRectId_IndexMask_ && gen_idx <= (ImFontAtlasRectId_GenerationMask_ >> ImFontAtlasRectId_GenerationShift_)); return (ImFontAtlasRectId)(index_idx | (gen_idx << ImFontAtlasRectId_GenerationShift_)); } // Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) // User are returned ImFontAtlasRectId values which are meant to be persistent. @@ -3751,7 +3751,7 @@ inline ImFontAtlasRectId ImFontAtlasRectId_Make(int index_idx, int gen_idx) struct ImFontAtlasRectEntry { int TargetIndex : 20; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. - int Generation : 10; // Increased each time the entry is reused for a new rectangle. + unsigned int Generation : 10; // Increased each time the entry is reused for a new rectangle. unsigned int IsUsed : 1; }; From aa2f40c3bbd7963fa908877cece04ab56f8329db Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Aug 2025 18:34:10 +0200 Subject: [PATCH 1266/2359] Clipper, Tables: added ImGuiListClipperFlags, ImGuiListClipperFlags_NoSetTableRowCounters. (#8886) a0cdac48e0 revealed the issue but technically the core issue is that clipper assume 1 item = 1 table row. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 16 ++++++++++------ imgui.h | 11 ++++++++++- imgui_tables.cpp | 5 +++-- 4 files changed, 26 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 619e0c42e..38b9898e9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,9 @@ Other Changes: ImGuiStyleVar_ScrollbarPadding enum, instead of hardcoded computed default. (#8895) - Fonts: fixed an assertion failure when a rectangle entry has been reused 1024 times (e.g. due to constant change of font types). (#8906) [@cfillion] +- Clipper, Tables: added ImGuiListClipperFlags_NoSetTableRowCounters as a way to + disable the assumption that 1 clipper item == 1 table row, which breaks when + e.g. using clipper with ItemsHeight=1 in order to clip in pixel units. (#8886) - Fixed Bullet() fixed tesselation amount which looked out of place in very large sizes. - DrawList: Fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) diff --git a/imgui.cpp b/imgui.cpp index bc4da78ee..085575bbd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3124,7 +3124,7 @@ static void ImGuiListClipper_SortAndFuseRanges(ImVector& } } -static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height) +static void ImGuiListClipper_SeekCursorAndSetupPrevLine(ImGuiListClipper* clipper, float pos_y, float line_height) { // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. @@ -3142,10 +3142,14 @@ static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_ { if (table->IsInsideRow) ImGui::TableEndRow(table); + if ((clipper->Flags & ImGuiListClipperFlags_NoSetTableRowCounters) == 0) + { + const int row_increase = (int)((off_y / line_height) + 0.5f); + IM_ASSERT(row_increase >= 0); // If your clipper item height is != from actual table row height, consider using ImGuiListClipperFlags_NoSetTableRowCounters. See #8886. + table->CurrentRow += row_increase; + table->RowBgColorCounter += row_increase; + } table->RowPosY2 = window->DC.CursorPos.y; - const int row_increase = (int)((off_y / line_height) + 0.5f); - table->CurrentRow += row_increase; - table->RowBgColorCounter += row_increase; } } @@ -3228,7 +3232,7 @@ void ImGuiListClipper::SeekCursorForItem(int item_n) // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight). // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done. float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight); - ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, ItemsHeight); + ImGuiListClipper_SeekCursorAndSetupPrevLine(this, pos_y, ItemsHeight); } static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) @@ -3327,7 +3331,6 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) if (g.NavId != 0 && window->NavLastIds[0] == g.NavId) data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0)); - // Add visible range float min_y = window->ClipRect.Min.y; float max_y = window->ClipRect.Max.y; @@ -3346,6 +3349,7 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0)); } + // Add main visible range const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0; data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max)); diff --git a/imgui.h b/imgui.h index 6b35f8403..f0163f9f1 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.3 WIP" -#define IMGUI_VERSION_NUM 19223 +#define IMGUI_VERSION_NUM 19224 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -246,6 +246,7 @@ typedef int ImGuiInputFlags; // -> enum ImGuiInputFlags_ // Flags: f typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag(), shared by all items typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. +typedef int ImGuiListClipperFlags; // -> enum ImGuiListClipperFlags_// Flags: for ImGuiListClipper typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiMultiSelectFlags; // -> enum ImGuiMultiSelectFlags_// Flags: for BeginMultiSelect() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() @@ -2782,6 +2783,13 @@ struct ImGuiStorage #endif }; +// Flags for ImGuiListClipper (currently not fully exposed in function calls: a future refactor will likely add this to ImGuiListClipper::Begin function equivalent) +enum ImGuiListClipperFlags_ +{ + ImGuiListClipperFlags_None = 0, + ImGuiListClipperFlags_NoSetTableRowCounters = 1 << 0, // [Internal] Disabled modifying table row counters. Avoid assumption that 1 clipper item == 1 table row. +}; + // Helper: Manually clip large list of items. // If you have lots evenly spaced items and you have random access to the list, you can perform coarse // clipping based on visibility to only submit items that are in view. @@ -2812,6 +2820,7 @@ struct ImGuiListClipper double StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed double StartSeekOffsetY; // [Internal] Account for frozen rows in a table and initial loss of precision in very large windows. void* TempData; // [Internal] Internal data + ImGuiListClipperFlags Flags; // [Internal] Flags, currently not yet well exposed. // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step, and you can call SeekCursorForItem() manually if you need) // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 8824534e7..c2b7548c9 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2054,10 +2054,11 @@ void ImGui::TableEndRow(ImGuiTable* table) } // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) - // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and - // get the new cursor position. + // - We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark + // end of row and get the new cursor position. if (unfreeze_rows_request) { + IM_ASSERT(table->FreezeRowsRequest > 0); for (int column_n = 0; column_n < table->ColumnsCount; column_n++) table->Columns[column_n].NavLayerCurrent = table->NavLayer; const float y0 = ImMax(table->RowPosY2 + 1, table->InnerClipRect.Min.y); From 9f969944d5c995cefa2c7069f7967f3a30d93e44 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 Aug 2025 17:37:40 +0200 Subject: [PATCH 1267/2359] stb_textedit: fixed misleading cursor-1 in STB_TEXTEDIT_K_LINESTART handlers. (#7925) `state->cursor - 1` in STB_TEXTEDIT_K_LINESTART handlers was technically misleadingly not UTF-8 compliant but things would naturally work anyhow. --- imstb_textedit.h | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/imstb_textedit.h b/imstb_textedit.h index 33eef7095..1a9975f3b 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -1100,8 +1100,12 @@ retry: stb_textedit_move_to_first(state); if (state->single_line) state->cursor = 0; - else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) - state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); + else while (state->cursor > 0) { + int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); + if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) + break; + state->cursor = prev; + } state->has_preferred_x = 0; break; @@ -1128,8 +1132,12 @@ retry: stb_textedit_prep_selection_at_cursor(state); if (state->single_line) state->cursor = 0; - else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) - state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); + else while (state->cursor > 0) { + int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); + if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) + break; + state->cursor = prev; + } state->select_end = state->cursor; state->has_preferred_x = 0; break; From 55cbc665081d31108420532bdf4435b9397a383f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Aug 2025 20:21:31 +0200 Subject: [PATCH 1268/2359] InputText: allow passing an empty string with buf_size==0. (#8907) --- docs/CHANGELOG.txt | 6 +++++- imgui_widgets.cpp | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 38b9898e9..b25af3124 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,7 +51,11 @@ Other Changes: disable the assumption that 1 clipper item == 1 table row, which breaks when e.g. using clipper with ItemsHeight=1 in order to clip in pixel units. (#8886) - Fixed Bullet() fixed tesselation amount which looked out of place in very large sizes. -- DrawList: Fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData +- InputText: allow passing an empty string with buf_size==0. (#8907) + In theory the buffer size should always account for a zero-terminator, but idioms + such as using InputTextMultiline() with ImGuiInputTextFlags_ReadOnly to display + a text blob are facilitated by allowing this. +- DrawList: fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) - Debug Tools: ID Stack Tool: fixed using fixed-size buffers preventing long identifiers from being displayed in the tool. (#8905, #4631) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4a64b2c21..e701e0293 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4653,7 +4653,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Take a copy of the initial buffer value. // From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode) const int buf_len = (int)ImStrlen(buf); - IM_ASSERT(buf_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?"); + IM_ASSERT(((buf_len + 1 <= buf_size) || (buf_len == 0 && buf_size == 0)) && "Is your input buffer properly zero-terminated?"); state->TextToRevertTo.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. memcpy(state->TextToRevertTo.Data, buf, buf_len + 1); From 6351f00ff11cf926262200b9e9f2f9e13be79710 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Aug 2025 20:31:05 +0200 Subject: [PATCH 1269/2359] Clipper, Tables: removed `row_increase >= 0` assert. (#8886) Seeing cases in my own tests that are not obvious so it seems like too much of a burden for the user to assert/crash, as the row count is not always useful anyhow. --- imgui.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 085575bbd..07537df87 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3142,10 +3142,9 @@ static void ImGuiListClipper_SeekCursorAndSetupPrevLine(ImGuiListClipper* clippe { if (table->IsInsideRow) ImGui::TableEndRow(table); - if ((clipper->Flags & ImGuiListClipperFlags_NoSetTableRowCounters) == 0) + const int row_increase = (int)((off_y / line_height) + 0.5f); + if (row_increase > 0 && (clipper->Flags & ImGuiListClipperFlags_NoSetTableRowCounters) == 0) // If your clipper item height is != from actual table row height, consider using ImGuiListClipperFlags_NoSetTableRowCounters. See #8886. { - const int row_increase = (int)((off_y / line_height) + 0.5f); - IM_ASSERT(row_increase >= 0); // If your clipper item height is != from actual table row height, consider using ImGuiListClipperFlags_NoSetTableRowCounters. See #8886. table->CurrentRow += row_increase; table->RowBgColorCounter += row_increase; } From 771fae623d747cfac490c738c16bb288a9b45e82 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Aug 2025 20:06:18 +0200 Subject: [PATCH 1270/2359] ImRect: added AsVec4() helper. Using ImRect in InputTextEx(). --- imgui_internal.h | 1 + imgui_widgets.cpp | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 873e7881e..739ae692c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -592,6 +592,7 @@ struct IMGUI_API ImRect void Floor() { Min.x = IM_TRUNC(Min.x); Min.y = IM_TRUNC(Min.y); Max.x = IM_TRUNC(Max.x); Max.y = IM_TRUNC(Max.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; } }; // Helper: ImBitArray diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e701e0293..5178d5448 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5230,7 +5230,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); } - const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size + const ImRect clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.0f, 0.0f); @@ -5362,9 +5362,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll; for (const char* p = text_selected_begin; p < text_selected_end; ) { - if (rect_pos.y > clip_rect.w + g.FontSize) + if (rect_pos.y > clip_rect.Max.y + g.FontSize) break; - if (rect_pos.y < clip_rect.y) + if (rect_pos.y < clip_rect.Min.y) { p = (const char*)ImMemchr((void*)p, '\n', text_selected_end - p); p = p ? p + 1 : text_selected_end; @@ -5388,7 +5388,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) { ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect.AsVec4()); } // Draw blinking cursor @@ -5433,7 +5433,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const ImVec2 draw_scroll = /*state ? ImVec2(state->Scroll.x, 0.0f) :*/ ImVec2(0.0f, 0.0f); // Preserve scroll when inactive? ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect.AsVec4()); } } From 5c92699f5f7a1295c8d5e1d578695f00dc329ce0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 28 Aug 2025 18:43:41 +0200 Subject: [PATCH 1271/2359] stb_textedit: trim trailing blanks for simplicity. In theory your editorconfig has this disabled for this file but MSVC plugin doesn't seem to handle this properly. --- imstb_textedit.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/imstb_textedit.h b/imstb_textedit.h index 1a9975f3b..5049715af 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -181,10 +181,10 @@ // // To support UTF-8: // -// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character -// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character +// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character +// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character // Do NOT define STB_TEXTEDIT_KEYTOTEXT. -// Instead, call stb_textedit_text() directly for text contents. +// 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 @@ -260,7 +260,7 @@ // // 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() +// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() // cannot infer text length. // // From 0ef9610e701ad8ca37928768dc54374a067eecf2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Aug 2025 17:55:45 +0200 Subject: [PATCH 1272/2359] InputText, stb_textedit: Revert special handling when pressing Down/PageDown on last line of a buffer without a trailing carriage return. Revert fbf70070bb. --- docs/CHANGELOG.txt | 3 +++ imstb_textedit.h | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b25af3124..9d1710a6d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,9 @@ Other Changes: In theory the buffer size should always account for a zero-terminator, but idioms such as using InputTextMultiline() with ImGuiInputTextFlags_ReadOnly to display a text blob are facilitated by allowing this. +- InputText: revert a change in 1.79 where pressing Down or PageDown on the last line + of a multi-line buffer without a trailing carriage return would keep the cursor + unmoved. We revert back to move to the end of line in this situation. - DrawList: fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) - Debug Tools: ID Stack Tool: fixed using fixed-size buffers preventing long identifiers diff --git a/imstb_textedit.h b/imstb_textedit.h index 5049715af..ac4db0fb9 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -921,8 +921,8 @@ retry: // [DEAR IMGUI] // going down while being on the last line shouldn't bring us to that line end - if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE) - break; + //if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE) + // break; // now find character position down a row state->cursor = start; From 8dc457fda24806d69a1b291f6fa03b9924c41fdd Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 Aug 2025 16:43:44 +0200 Subject: [PATCH 1273/2359] Internals: added indent, shallow tweaks + unused context pointer to InputTextCalcTextLenAndLineCount() to reduce noise in wip patch. Visualize this commit with white-space changes disabled. --- imgui.h | 2 +- imgui_draw.cpp | 6 +++--- imgui_widgets.cpp | 38 ++++++++++++++++++++++---------------- 3 files changed, 26 insertions(+), 20 deletions(-) diff --git a/imgui.h b/imgui.h index f0163f9f1..12f01f43f 100644 --- a/imgui.h +++ b/imgui.h @@ -3832,7 +3832,7 @@ 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** remaining = NULL); // utf8 + 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 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, bool cpu_fine_clip = false); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 76d8474bf..e0d56612a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5458,7 +5458,7 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha return s; } -ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining) { if (!text_end) text_end = text_begin + ImStrlen(text_begin); // FIXME-OPT: Need to avoid this. @@ -5536,8 +5536,8 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons if (line_width > 0 || text_size.y == 0.0f) text_size.y += line_height; - if (remaining) - *remaining = s; + if (out_remaining != NULL) + *out_remaining = s; return text_size; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5178d5448..3012404e0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -135,7 +135,7 @@ static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); // For InputTextEx() static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false); -static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); +static int InputTextCalcTextLenAndLineCount(ImGuiContext* ctx, const char* text_begin, const char** out_text_end); static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); //------------------------------------------------------------------------- @@ -3941,20 +3941,22 @@ bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, si } // This is only used in the path where the multiline widget is inactive. -static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) +static int InputTextCalcTextLenAndLineCount(ImGuiContext*, const char* text_begin, const char** out_text_end) { int line_count = 0; const char* s = text_begin; - while (true) { - const char* s_eol = strchr(s, '\n'); - line_count++; - if (s_eol == NULL) + while (true) { - s = s + ImStrlen(s); - break; + const char* s_eol = strchr(s, '\n'); + line_count++; + if (s_eol == NULL) + { + s = s + ImStrlen(s); + break; + } + s = s_eol + 1; } - s = s_eol + 1; } *out_text_end = s; return line_count; @@ -5259,7 +5261,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } // Render text. We currently only render selection when the widget is active or while scrolling. - // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. + // FIXME: This is one of the messiest piece of the whole codebase. if (render_cursor || render_selection) { IM_ASSERT(state != NULL); @@ -5285,14 +5287,17 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const char* selmin_ptr = render_selection ? text_begin + ImMin(state->Stb->select_start, state->Stb->select_end) : NULL; // Count lines and find line number for cursor and selection ends + // FIXME: Switch to zero-based index to reduce confusion. int line_count = 1; if (is_multiline) { - for (const char* s = text_begin; (s = (const char*)ImMemchr(s, '\n', (size_t)(text_end - s))) != NULL; s++) { - if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_no = line_count; } - if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_no = line_count; } - line_count++; + for (const char* s = text_begin; (s = (const char*)ImMemchr(s, '\n', (size_t)(text_end - s))) != NULL; s++) + { + if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_no = line_count; } + if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_no = line_count; } + line_count++; + } } } if (cursor_line_no == -1) @@ -5372,7 +5377,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else { ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, &p, NULL, true); - if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines + if (rect_size.x <= 0.0f) + rect_size.x = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn)); rect.ClipWith(clip_rect); if (rect.Overlaps(clip_rect)) @@ -5419,7 +5425,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Render text only (no selection, no cursor) if (is_multiline) - text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width + text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(&g, buf_display, &buf_display_end) * g.FontSize); // We don't need width else if (!is_displaying_hint && g.ActiveId == id) buf_display_end = buf_display + state->TextLen; else if (!is_displaying_hint) From 0dd3c845ebf4e4a08b88f40d34efc9b3605ae80b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=AF=D0=BD=20=D0=9B=D0=B8?= <184278878+vxbo@users.noreply.github.com> Date: Wed, 3 Sep 2025 10:17:23 +0300 Subject: [PATCH 1274/2359] Docs: add missing anchor in FAQ.md (#8913) --- docs/FAQ.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index fb693c7e3..519a0e8a9 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -19,7 +19,7 @@ or view this file with any Markdown viewer. | **[How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?](#q-how-can-i-tell-whether-to-dispatch-mousekeyboard-to-dear-imgui-or-my-application)** | | [How can I enable keyboard or gamepad controls?](#q-how-can-i-enable-keyboard-or-gamepad-controls) | | [How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)](#q-how-can-i-use-this-on-a-machine-without-mouse-keyboard-or-screen-input-share-remote-display) | -| [How can I create my own backend?](q-how-can-i-create-my-own-backend) +| [How can I create my own backend?](#q-how-can-i-create-my-own-backend) | [I integrated Dear ImGui in my engine and little squares are showing instead of text...](#q-i-integrated-dear-imgui-in-my-engine-and-little-squares-are-showing-instead-of-text) | | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | | [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | From 3766d40394a9f4b66a919085ae25db89cb16d7b1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Sep 2025 17:50:10 +0200 Subject: [PATCH 1275/2359] Nav: fixed Ctrl+Tab window appearing as empty when the sole active and focused window has the ImGuiWindowFlags_NoNavFocus flag. (#8914) --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9d1710a6d..4a28876bc 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,7 +50,9 @@ Other Changes: - Clipper, Tables: added ImGuiListClipperFlags_NoSetTableRowCounters as a way to disable the assumption that 1 clipper item == 1 table row, which breaks when e.g. using clipper with ItemsHeight=1 in order to clip in pixel units. (#8886) -- Fixed Bullet() fixed tesselation amount which looked out of place in very large sizes. +- Nav: fixed Ctrl+Tab window appearing as empty when the sole active and focused + window has the ImGuiWindowFlags_NoNavFocus flag. (#8914) +- Bullet: fixed tesselation amount which looked out of place in very large sizes. - InputText: allow passing an empty string with buf_size==0. (#8907) In theory the buffer size should always account for a zero-terminator, but idioms such as using InputTextMultiline() with ImGuiInputTextFlags_ReadOnly to display diff --git a/imgui.cpp b/imgui.cpp index 07537df87..a4128f2dc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14253,7 +14253,7 @@ static void ImGui::NavUpdateWindowing() g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Gamepad; } if (start_windowing_with_gamepad || start_windowing_with_keyboard) - if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) + if (ImGuiWindow* window = (g.NavWindow && IsWindowNavFocusable(g.NavWindow)) ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) { if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad) g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location From 20160ff1d5ec8c2fc4f3e18a50f4e4dc902418b8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Sep 2025 19:36:02 +0200 Subject: [PATCH 1276/2359] Fonts: fixed merging a font and specifying a font target in DstFont that's not the last added font (regression in 1.92). (#8912) --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4a28876bc..479115613 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Other Changes: ImGuiStyleVar_ScrollbarPadding enum, instead of hardcoded computed default. (#8895) - Fonts: fixed an assertion failure when a rectangle entry has been reused 1024 times (e.g. due to constant change of font types). (#8906) [@cfillion] +- Fonts: fixed merging a font and specifying a font target in DstFont + that's not the last added font (regression in 1.92). (#8912) - Clipper, Tables: added ImGuiListClipperFlags_NoSetTableRowCounters as a way to disable the assumption that 1 clipper item == 1 table row, which breaks when e.g. using clipper with ItemsHeight=1 in order to clip in pixel units. (#8886) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e0d56612a..ee7f55efa 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3026,7 +3026,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) else { IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. - font = Fonts.back(); + font = font_cfg_in->DstFont ? font_cfg_in->DstFont : Fonts.back(); } // Add to list From b7cb3d93a419ffa9c37c2150eda695f3f43c221f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Sep 2025 19:39:55 +0200 Subject: [PATCH 1277/2359] Comments about using MSVC SAL for printf annotation. (#8871) --- imgui.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 12f01f43f..859cb0318 100644 --- a/imgui.h +++ b/imgui.h @@ -100,8 +100,10 @@ Index of this file: #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions. -// (MSVC provides an equivalent mechanism via SAL Annotations but it would require the macros in a different -// location. e.g. #include + void myprintf(_Printf_format_string_ const char* format, ...)) +// (MSVC provides an equivalent mechanism via SAL Annotations but it requires the macros in a different +// location. e.g. #include + void myprintf(_Printf_format_string_ const char* format, ...), +// and only works when using Code Analysis, rather than just normal compiling). +// (see https://github.com/ocornut/imgui/issues/8871 for a patch to enable this for MSVC's Code Analysis) #if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__) #define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) #define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) From 605a751571530693cc2d36bd41e4a3c11109678c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Sep 2025 13:13:58 +0200 Subject: [PATCH 1278/2359] InputText, InputInt, InputFloat: fixed an issue where using Escape to revert would not write back the reverted value. (#8915, #8273) Revealed by 00f12b9a0 Regression test: "widgets_inputtext_temp_buffer_2" --- docs/CHANGELOG.txt | 4 ++++ imgui.h | 2 +- imgui_widgets.cpp | 4 ++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 479115613..172e2f5cc 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,10 @@ Other Changes: - Nav: fixed Ctrl+Tab window appearing as empty when the sole active and focused window has the ImGuiWindowFlags_NoNavFocus flag. (#8914) - Bullet: fixed tesselation amount which looked out of place in very large sizes. +- InputText, InputInt, InputFloat: fixed an issue where using Escape to revert + would not write back the reverted value during the IsItemDeactivatedAfterEdit() + frame if the provided input buffer doesn't store temporary edits. + (regression in 1.91.7) (#8915, #8273) - InputText: allow passing an empty string with buf_size==0. (#8907) In theory the buffer size should always account for a zero-terminator, but idioms such as using InputTextMultiline() with ImGuiInputTextFlags_ReadOnly to display diff --git a/imgui.h b/imgui.h index 859cb0318..cee72416c 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.3 WIP" -#define IMGUI_VERSION_NUM 19224 +#define IMGUI_VERSION_NUM 19225 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3012404e0..1d6fc9a83 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5058,14 +5058,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (flags & ImGuiInputTextFlags_EscapeClearsAll) { // Clear input - IM_ASSERT(buf[0] != 0); + IM_ASSERT(buf[0] != 0); // FIXME: use TextA here? apply_new_text = ""; apply_new_text_length = 0; value_changed = true; IMSTB_TEXTEDIT_CHARTYPE empty_string; stb_textedit_replace(state, state->Stb, &empty_string, 0); } - else if (strcmp(buf, state->TextToRevertTo.Data) != 0) + else if (strcmp(state->TextA.Data, state->TextToRevertTo.Data) != 0) { apply_new_text = state->TextToRevertTo.Data; apply_new_text_length = state->TextToRevertTo.Size - 1; From 7d33524042fe6781dad8bbf9de66cc726a10b1cf Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Sep 2025 13:15:18 +0200 Subject: [PATCH 1279/2359] InputText: fixed an issue where using Escape with ImGuiInputTextFlags_EscapeClearsAll. (#8915, #8273) Regression test: "widgets_inputtext_temp_buffer_2" --- docs/CHANGELOG.txt | 3 +++ imgui_widgets.cpp | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 172e2f5cc..da1fd9b0d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,9 @@ Other Changes: would not write back the reverted value during the IsItemDeactivatedAfterEdit() frame if the provided input buffer doesn't store temporary edits. (regression in 1.91.7) (#8915, #8273) +- InputText: fixed an issue where using Escape with ImGuiInputTextFlags_EscapeClearsAll + would not write back the cleared value during the IsItemDeactivatedAfterEdit() + frame if the provided input buffer doesn't store temporary edits. (#8915, #8273) - InputText: allow passing an empty string with buf_size==0. (#8907) In theory the buffer size should always account for a zero-terminator, but idioms such as using InputTextMultiline() with ImGuiInputTextFlags_ReadOnly to display diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1d6fc9a83..f66baf767 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4966,7 +4966,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { if (flags & ImGuiInputTextFlags_EscapeClearsAll) { - if (buf[0] != 0) + if (state->TextA.Data[0] != 0) { revert_edit = true; } @@ -5058,7 +5058,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (flags & ImGuiInputTextFlags_EscapeClearsAll) { // Clear input - IM_ASSERT(buf[0] != 0); // FIXME: use TextA here? + IM_ASSERT(state->TextA.Data[0] != 0); apply_new_text = ""; apply_new_text_length = 0; value_changed = true; From e51d93e2f523b3209065bc556becc0269506113b Mon Sep 17 00:00:00 2001 From: Ronan Cailleau Date: Tue, 29 Oct 2024 13:58:08 +0100 Subject: [PATCH 1280/2359] Backends: Vulkan: added ImGui_ImplVulkan_CreateMainPipeline(). (#8110, #8111, #8053) - Added ImGui_ImplVulkan_CreateMainPipeline(...) to explicitly re-create the main window pipeline (when some of its properties are changed). - Does not implicitly use ImGui_ImplVulkan_InitInfo::PipelineRenderingCreateInfo, but a function parameter. - The main window pipeline is created only if possible during ImGui_ImplVulkan_Init(...) (if a render pass or rendering info are given), else it should be created with ImGui_ImplVulkan_ReCreateMainPipeline(...) - ImGui_ImplVulkan_CreatePipeline now takes a struct rather than (too) many parameters (and returns the created pipeline). --- backends/imgui_impl_vulkan.cpp | 102 ++++++++++++++++++++++++++++----- backends/imgui_impl_vulkan.h | 19 +++++- 2 files changed, 105 insertions(+), 16 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 263c2c73b..e011f6ff1 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -906,10 +906,21 @@ static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAlloca } } -static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline, uint32_t subpass) +struct ImGui_ImplVulkan_PipelineCreateInfo +{ + VkDevice Device = VK_NULL_HANDLE; + const VkAllocationCallbacks* Allocator = nullptr; + VkPipelineCache PipelineCache = VK_NULL_HANDLE; + VkRenderPass RenderPass = VK_NULL_HANDLE; + uint32_t Subpass = 0; + VkSampleCountFlagBits MSAASamples = {}; + const ImGui_ImplVulkan_PipelineRenderingCreateInfo* pRenderingInfo = nullptr; +}; + +static VkPipeline ImGui_ImplVulkan_CreatePipeline(ImGui_ImplVulkan_PipelineCreateInfo const& pci) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - ImGui_ImplVulkan_CreateShaderModules(device, allocator); + ImGui_ImplVulkan_CreateShaderModules(pci.Device, pci.Allocator); VkPipelineShaderStageCreateInfo stage[2] = {}; stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; @@ -964,7 +975,7 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC VkPipelineMultisampleStateCreateInfo ms_info = {}; ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - ms_info.rasterizationSamples = (MSAASamples != 0) ? MSAASamples : VK_SAMPLE_COUNT_1_BIT; + ms_info.rasterizationSamples = (pci.MSAASamples != 0) ? pci.MSAASamples : VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState color_attachment[1] = {}; color_attachment[0].blendEnable = VK_TRUE; @@ -1004,21 +1015,23 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC info.pColorBlendState = &blend_info; info.pDynamicState = &dynamic_state; info.layout = bd->PipelineLayout; - info.renderPass = renderPass; - info.subpass = subpass; + info.renderPass = pci.RenderPass; + info.subpass = pci.Subpass; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING if (bd->VulkanInitInfo.UseDynamicRendering) { - IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); - IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo pNext must be nullptr"); - info.pNext = &bd->VulkanInitInfo.PipelineRenderingCreateInfo; + IM_ASSERT(pci.pRenderingInfo && "PipelineRenderingCreateInfo must not be nullptr when using dynamic rendering"); + IM_ASSERT(pci.pRenderingInfo->sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo::sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); + IM_ASSERT(pci.pRenderingInfo->pNext == nullptr && "PipelineRenderingCreateInfo::pNext must be nullptr"); + info.pNext = pci.pRenderingInfo; info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. } #endif - - VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, pipeline); + VkPipeline res; + VkResult err = vkCreateGraphicsPipelines(pci.Device, pci.PipelineCache, 1, &info, pci.Allocator, &res); check_vk_result(err); + return res; } bool ImGui_ImplVulkan_CreateDeviceObjects() @@ -1092,7 +1105,34 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() check_vk_result(err); } - ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, &bd->Pipeline, v->Subpass); + { + bool create_pipeline = false; + const ImGui_ImplVulkan_PipelineRenderingCreateInfo* p_dynamic_rendering = nullptr; + if (v->RenderPass) + { + create_pipeline = true; + } + else + { +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + if (v->UseDynamicRendering && v->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR) + { + p_dynamic_rendering = &v->PipelineRenderingCreateInfo; + create_pipeline = true; + } +#endif + } + if (create_pipeline) + { + ImGui_ImplVulkan_MainPipelineCreateInfo mp_info = {}; + mp_info.RenderPass = v->RenderPass; + mp_info.Subpass = v->Subpass; + mp_info.MSAASamples = v->MSAASamples; + mp_info.pDynamicRendering = p_dynamic_rendering; + + ImGui_ImplVulkan_ReCreateMainPipeline(mp_info); + } + } // Create command pool/buffer for texture upload if (!bd->TexCommandPool) @@ -1117,6 +1157,40 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() return true; } +void ImGui_ImplVulkan_ReCreateMainPipeline(ImGui_ImplVulkan_MainPipelineCreateInfo const& info) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + if (bd->Pipeline) + { + vkDestroyPipeline(v->Device, bd->Pipeline, v->Allocator); + bd->Pipeline = VK_NULL_HANDLE; + } + v->RenderPass = info.RenderPass; + v->MSAASamples = info.MSAASamples; + v->Subpass = info.Subpass; + +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + if (info.pDynamicRendering) + { + v->PipelineRenderingCreateInfo = *info.pDynamicRendering; + } +#else + IM_ASSERT(info.pDynamicRendering == nullptr); +#endif + + ImGui_ImplVulkan_PipelineCreateInfo pci; + pci.Device = v->Device; + pci.Allocator = v->Allocator; + pci.PipelineCache = v->PipelineCache; + pci.RenderPass = v->RenderPass; + pci.Subpass = v->Subpass; + pci.MSAASamples = v->MSAASamples; + pci.pRenderingInfo = info.pDynamicRendering; + + bd->Pipeline = ImGui_ImplVulkan_CreatePipeline(pci); +} + void ImGui_ImplVulkan_DestroyDeviceObjects() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); @@ -1239,17 +1313,15 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) IM_ASSERT(info->DescriptorPoolSize > 0); IM_ASSERT(info->MinImageCount >= 2); IM_ASSERT(info->ImageCount >= info->MinImageCount); - if (info->UseDynamicRendering == false) - IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); - bd->VulkanInitInfo = *info; + ImGui_ImplVulkan_InitInfo * v = &bd->VulkanInitInfo; + *v = *info; VkPhysicalDeviceProperties properties; vkGetPhysicalDeviceProperties(info->PhysicalDevice, &properties); bd->NonCoherentAtomSize = properties.limits.nonCoherentAtomSize; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; if (v->PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) { // Deep copy buffer to reduce error-rate for end user (#8282) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 4baa98335..d4f897961 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -65,6 +65,12 @@ // Backend uses a small number of descriptors per font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture(). #define IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE (8) // Minimum per atlas +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING +typedef VkPipelineRenderingCreateInfoKHR ImGui_ImplVulkan_PipelineRenderingCreateInfo; +#else +typedef void ImGui_ImplVulkan_PipelineRenderingCreateInfo; +#endif + // Initialization data, for ImGui_ImplVulkan_Init() // [Please zero-clear before use!] // - About descriptor pool: @@ -98,6 +104,7 @@ struct ImGui_ImplVulkan_InitInfo // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. bool UseDynamicRendering; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + // (Optional, valid iif .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR) VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; #endif @@ -108,12 +115,22 @@ struct ImGui_ImplVulkan_InitInfo }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! -IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); +IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); // The main pipeline will be created if possible (RenderPass xor (UseDynamicRendering && PipelineRenderingCreateInfo->sType is correct)) +#define IMGUI_IMPL_VULKAN_HAS_MAIN_PIPELINE_RE_CREATION 1 +struct ImGui_ImplVulkan_MainPipelineCreateInfo +{ + VkRenderPass RenderPass = VK_NULL_HANDLE; + uint32_t Subpass = 0; + VkSampleCountFlagBits MSAASamples = {}; + const ImGui_ImplVulkan_PipelineRenderingCreateInfo* pDynamicRendering = nullptr; +}; +IMGUI_IMPL_API void ImGui_ImplVulkan_ReCreateMainPipeline(ImGui_ImplVulkan_MainPipelineCreateInfo const& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext)) IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) + // (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. IMGUI_IMPL_API void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex); From ee03cef14fbc2e49c8236423a2d6b53f031e2093 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Sep 2025 14:37:14 +0200 Subject: [PATCH 1281/2359] Backends: Vulkan: revert using a struct for ImGui_ImplVulkan_CreatePipeline() for now. (#8110, #8111, #8053) --- backends/imgui_impl_vulkan.cpp | 51 ++++++++++++---------------------- 1 file changed, 17 insertions(+), 34 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index e011f6ff1..69e3430e0 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -906,21 +906,10 @@ static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAlloca } } -struct ImGui_ImplVulkan_PipelineCreateInfo -{ - VkDevice Device = VK_NULL_HANDLE; - const VkAllocationCallbacks* Allocator = nullptr; - VkPipelineCache PipelineCache = VK_NULL_HANDLE; - VkRenderPass RenderPass = VK_NULL_HANDLE; - uint32_t Subpass = 0; - VkSampleCountFlagBits MSAASamples = {}; - const ImGui_ImplVulkan_PipelineRenderingCreateInfo* pRenderingInfo = nullptr; -}; - -static VkPipeline ImGui_ImplVulkan_CreatePipeline(ImGui_ImplVulkan_PipelineCreateInfo const& pci) +static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, uint32_t subpass, const ImGui_ImplVulkan_PipelineRenderingCreateInfo* pipeline_rendering_create_info) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - ImGui_ImplVulkan_CreateShaderModules(pci.Device, pci.Allocator); + ImGui_ImplVulkan_CreateShaderModules(device, allocator); VkPipelineShaderStageCreateInfo stage[2] = {}; stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; @@ -975,7 +964,7 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(ImGui_ImplVulkan_PipelineCreat VkPipelineMultisampleStateCreateInfo ms_info = {}; ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - ms_info.rasterizationSamples = (pci.MSAASamples != 0) ? pci.MSAASamples : VK_SAMPLE_COUNT_1_BIT; + ms_info.rasterizationSamples = (MSAASamples != 0) ? MSAASamples : VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState color_attachment[1] = {}; color_attachment[0].blendEnable = VK_TRUE; @@ -1015,23 +1004,25 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(ImGui_ImplVulkan_PipelineCreat info.pColorBlendState = &blend_info; info.pDynamicState = &dynamic_state; info.layout = bd->PipelineLayout; - info.renderPass = pci.RenderPass; - info.subpass = pci.Subpass; + info.renderPass = renderPass; + info.subpass = subpass; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING if (bd->VulkanInitInfo.UseDynamicRendering) { - IM_ASSERT(pci.pRenderingInfo && "PipelineRenderingCreateInfo must not be nullptr when using dynamic rendering"); - IM_ASSERT(pci.pRenderingInfo->sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo::sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); - IM_ASSERT(pci.pRenderingInfo->pNext == nullptr && "PipelineRenderingCreateInfo::pNext must be nullptr"); - info.pNext = pci.pRenderingInfo; + IM_ASSERT(pipeline_rendering_create_info && "PipelineRenderingCreateInfo must not be nullptr when using dynamic rendering"); + IM_ASSERT(pipeline_rendering_create_info->sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo::sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); + IM_ASSERT(pipeline_rendering_create_info->pNext == nullptr && "PipelineRenderingCreateInfo::pNext must be nullptr"); + info.pNext = pipeline_rendering_create_info; info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. } +#else + IM_ASSERT(pipeline_rendering_create_info == nullptr); #endif - VkPipeline res; - VkResult err = vkCreateGraphicsPipelines(pci.Device, pci.PipelineCache, 1, &info, pci.Allocator, &res); + VkPipeline pipeline; + VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, &pipeline); check_vk_result(err); - return res; + return pipeline; } bool ImGui_ImplVulkan_CreateDeviceObjects() @@ -1170,25 +1161,17 @@ void ImGui_ImplVulkan_ReCreateMainPipeline(ImGui_ImplVulkan_MainPipelineCreateIn v->MSAASamples = info.MSAASamples; v->Subpass = info.Subpass; + ImGui_ImplVulkan_PipelineRenderingCreateInfo * pipeline_rendering_create_info = nullptr; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING if (info.pDynamicRendering) { v->PipelineRenderingCreateInfo = *info.pDynamicRendering; + pipeline_rendering_create_info = &v->PipelineRenderingCreateInfo; } #else IM_ASSERT(info.pDynamicRendering == nullptr); #endif - - ImGui_ImplVulkan_PipelineCreateInfo pci; - pci.Device = v->Device; - pci.Allocator = v->Allocator; - pci.PipelineCache = v->PipelineCache; - pci.RenderPass = v->RenderPass; - pci.Subpass = v->Subpass; - pci.MSAASamples = v->MSAASamples; - pci.pRenderingInfo = info.pDynamicRendering; - - bd->Pipeline = ImGui_ImplVulkan_CreatePipeline(pci); + bd->Pipeline = ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, v->Subpass, pipeline_rendering_create_info); } void ImGui_ImplVulkan_DestroyDeviceObjects() From 1ecc34a0b1096e61b5585025525392886bfebc34 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Sep 2025 14:24:06 +0200 Subject: [PATCH 1282/2359] Backends: Vulkan: misc amends (e.g. changelog, coding style). (8110, 8111, 8053) # Conflicts: # backends/imgui_impl_vulkan.cpp --- backends/imgui_impl_vulkan.cpp | 56 +++++++++++++++------------------- backends/imgui_impl_vulkan.h | 33 +++++++++----------- docs/CHANGELOG.txt | 2 ++ 3 files changed, 41 insertions(+), 50 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 69e3430e0..23bf7b8ce 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-04: Vulkan: Added ImGui_ImplVulkan_CreateMainPipeline(). (#8110, #8111) // 2025-07-27: Vulkan: Fixed texture update corruption introduced on 2025-06-11. (#8801, #8755, #8840) // 2025-07-07: Vulkan: Fixed texture synchronization issue introduced on 2025-06-11. (#8772) // 2025-06-27: Vulkan: Fixed validation errors during texture upload/update by aligning upload size to 'nonCoherentAtomSize'. (#8743, #8744) @@ -906,7 +907,11 @@ static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAlloca } } -static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, uint32_t subpass, const ImGui_ImplVulkan_PipelineRenderingCreateInfo* pipeline_rendering_create_info) +#if !defined(IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING) && !(defined(VK_VERSION_1_3) || defined(VK_KHR_dynamic_rendering)) +typedef void VkPipelineRenderingCreateInfoKHR; +#endif + +static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, uint32_t subpass, const VkPipelineRenderingCreateInfoKHR* pipeline_rendering_create_info) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_CreateShaderModules(device, allocator); @@ -1096,33 +1101,22 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() check_vk_result(err); } - { - bool create_pipeline = false; - const ImGui_ImplVulkan_PipelineRenderingCreateInfo* p_dynamic_rendering = nullptr; - if (v->RenderPass) - { - create_pipeline = true; - } - else - { + // Create pipeline + const VkPipelineRenderingCreateInfoKHR* p_dynamic_rendering_create_info = nullptr; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - if (v->UseDynamicRendering && v->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR) - { - p_dynamic_rendering = &v->PipelineRenderingCreateInfo; - create_pipeline = true; - } + if (v->UseDynamicRendering && v->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR) + p_dynamic_rendering_create_info = &v->PipelineRenderingCreateInfo; #endif - } - if (create_pipeline) - { - ImGui_ImplVulkan_MainPipelineCreateInfo mp_info = {}; - mp_info.RenderPass = v->RenderPass; - mp_info.Subpass = v->Subpass; - mp_info.MSAASamples = v->MSAASamples; - mp_info.pDynamicRendering = p_dynamic_rendering; - - ImGui_ImplVulkan_ReCreateMainPipeline(mp_info); - } + if (v->RenderPass || p_dynamic_rendering_create_info != nullptr) + { + ImGui_ImplVulkan_MainPipelineCreateInfo mp_info = {}; + mp_info.RenderPass = v->RenderPass; + mp_info.Subpass = v->Subpass; + mp_info.MSAASamples = v->MSAASamples; +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + mp_info.pDynamicRendering = p_dynamic_rendering_create_info; +#endif + ImGui_ImplVulkan_CreateMainPipeline(mp_info); } // Create command pool/buffer for texture upload @@ -1148,7 +1142,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() return true; } -void ImGui_ImplVulkan_ReCreateMainPipeline(ImGui_ImplVulkan_MainPipelineCreateInfo const& info) +void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCreateInfo& info) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; @@ -1161,15 +1155,13 @@ void ImGui_ImplVulkan_ReCreateMainPipeline(ImGui_ImplVulkan_MainPipelineCreateIn v->MSAASamples = info.MSAASamples; v->Subpass = info.Subpass; - ImGui_ImplVulkan_PipelineRenderingCreateInfo * pipeline_rendering_create_info = nullptr; + VkPipelineRenderingCreateInfoKHR* pipeline_rendering_create_info = nullptr; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING if (info.pDynamicRendering) { v->PipelineRenderingCreateInfo = *info.pDynamicRendering; pipeline_rendering_create_info = &v->PipelineRenderingCreateInfo; } -#else - IM_ASSERT(info.pDynamicRendering == nullptr); #endif bd->Pipeline = ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, v->Subpass, pipeline_rendering_create_info); } @@ -1297,14 +1289,14 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) IM_ASSERT(info->MinImageCount >= 2); IM_ASSERT(info->ImageCount >= info->MinImageCount); - ImGui_ImplVulkan_InitInfo * v = &bd->VulkanInitInfo; - *v = *info; + bd->VulkanInitInfo = *info; VkPhysicalDeviceProperties properties; vkGetPhysicalDeviceProperties(info->PhysicalDevice, &properties); bd->NonCoherentAtomSize = properties.limits.nonCoherentAtomSize; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; if (v->PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) { // Deep copy buffer to reduce error-rate for end user (#8282) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index d4f897961..e4503261e 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -65,12 +65,6 @@ // Backend uses a small number of descriptors per font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture(). #define IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE (8) // Minimum per atlas -#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING -typedef VkPipelineRenderingCreateInfoKHR ImGui_ImplVulkan_PipelineRenderingCreateInfo; -#else -typedef void ImGui_ImplVulkan_PipelineRenderingCreateInfo; -#endif - // Initialization data, for ImGui_ImplVulkan_Init() // [Please zero-clear before use!] // - About descriptor pool: @@ -104,8 +98,7 @@ struct ImGui_ImplVulkan_InitInfo // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. bool UseDynamicRendering; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - // (Optional, valid iif .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR) - VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; + VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR #endif // (Optional) Allocation, Debugging @@ -115,21 +108,25 @@ struct ImGui_ImplVulkan_InitInfo }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! -IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); // The main pipeline will be created if possible (RenderPass xor (UseDynamicRendering && PipelineRenderingCreateInfo->sType is correct)) -#define IMGUI_IMPL_VULKAN_HAS_MAIN_PIPELINE_RE_CREATION 1 -struct ImGui_ImplVulkan_MainPipelineCreateInfo -{ - VkRenderPass RenderPass = VK_NULL_HANDLE; - uint32_t Subpass = 0; - VkSampleCountFlagBits MSAASamples = {}; - const ImGui_ImplVulkan_PipelineRenderingCreateInfo* pDynamicRendering = nullptr; -}; -IMGUI_IMPL_API void ImGui_ImplVulkan_ReCreateMainPipeline(ImGui_ImplVulkan_MainPipelineCreateInfo const& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext)) +IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) +// (Advanced) Use e.g. if you need to recreate pipeline without reinitializing the backend (see #8110, #8111) +// The main window pipeline will be created by ImGui_ImplVulkan_Init() if possible (== RenderPass xor (UseDynamicRendering && PipelineRenderingCreateInfo->sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR)) +// Else, the pipeline can be created, or re-created, using ImGui_ImplVulkan_CreateMainPipeline() before rendering. +struct ImGui_ImplVulkan_MainPipelineCreateInfo +{ + VkRenderPass RenderPass = VK_NULL_HANDLE; + uint32_t Subpass = 0; + VkSampleCountFlagBits MSAASamples = {}; +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + const VkPipelineRenderingCreateInfoKHR* pDynamicRendering = nullptr; +#endif +}; +IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCreateInfo& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext)) // (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. IMGUI_IMPL_API void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index da1fd9b0d..afdcbfc6c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,8 @@ Other Changes: - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used multi-viewport mode. (#8892) [@PTSVU] +- Backends: Vulkan: added ImGui_ImplVulkan_CreateMainPipeline() to recreate pipeline + without reinitializing backend. (#8110, #8111) [@SuperRonan] ----------------------------------------------------------------------- From 26aa81a8b1546ab5805602dde49a29c06699c6d5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Sep 2025 16:39:16 +0200 Subject: [PATCH 1283/2359] Backends: Vulkan: misc amends (makes ImGui_ImplVulkan_MainPipelineCreateInfo::PipelineRenderingCreateInfo consistent with InitInfo). (#8110, #8111, #8053) --- backends/imgui_impl_vulkan.cpp | 15 +++++++-------- backends/imgui_impl_vulkan.h | 6 +++--- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 23bf7b8ce..db23aad49 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1102,19 +1102,18 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() } // Create pipeline - const VkPipelineRenderingCreateInfoKHR* p_dynamic_rendering_create_info = nullptr; + if (v->RenderPass #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - if (v->UseDynamicRendering && v->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR) - p_dynamic_rendering_create_info = &v->PipelineRenderingCreateInfo; + || (v->UseDynamicRendering && v->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR) #endif - if (v->RenderPass || p_dynamic_rendering_create_info != nullptr) + ) { ImGui_ImplVulkan_MainPipelineCreateInfo mp_info = {}; mp_info.RenderPass = v->RenderPass; mp_info.Subpass = v->Subpass; mp_info.MSAASamples = v->MSAASamples; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - mp_info.pDynamicRendering = p_dynamic_rendering_create_info; + mp_info.PipelineRenderingCreateInfo = v->PipelineRenderingCreateInfo; #endif ImGui_ImplVulkan_CreateMainPipeline(mp_info); } @@ -1155,11 +1154,11 @@ void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCrea v->MSAASamples = info.MSAASamples; v->Subpass = info.Subpass; - VkPipelineRenderingCreateInfoKHR* pipeline_rendering_create_info = nullptr; + const VkPipelineRenderingCreateInfoKHR* pipeline_rendering_create_info = nullptr; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - if (info.pDynamicRendering) + if (v->UseDynamicRendering) { - v->PipelineRenderingCreateInfo = *info.pDynamicRendering; + v->PipelineRenderingCreateInfo = info.PipelineRenderingCreateInfo; pipeline_rendering_create_info = &v->PipelineRenderingCreateInfo; } #endif diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index e4503261e..fbbd9e2bd 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -98,13 +98,13 @@ struct ImGui_ImplVulkan_InitInfo // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. bool UseDynamicRendering; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR + VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR #endif // (Optional) Allocation, Debugging const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); - VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. + VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! @@ -123,7 +123,7 @@ struct ImGui_ImplVulkan_MainPipelineCreateInfo uint32_t Subpass = 0; VkSampleCountFlagBits MSAASamples = {}; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - const VkPipelineRenderingCreateInfoKHR* pDynamicRendering = nullptr; + VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR #endif }; IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCreateInfo& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext)) From c63714822f3e7cad9c6f6cebfcbe91e74c93b5ee Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Sep 2025 16:41:20 +0200 Subject: [PATCH 1284/2359] Backends: Vulkan: reorder InitInfo fields. --- backends/imgui_impl_vulkan.h | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index fbbd9e2bd..c7f3007dc 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -82,20 +82,18 @@ struct ImGui_ImplVulkan_InitInfo uint32_t QueueFamily; VkQueue Queue; VkDescriptorPool DescriptorPool; // See requirements in note above; ignored if using DescriptorPoolSize > 0 - VkRenderPass RenderPass; // Ignored if using dynamic rendering + uint32_t DescriptorPoolSize; // Optional: set to create internal descriptor pool automatically instead of using DescriptorPool. uint32_t MinImageCount; // >= 2 uint32_t ImageCount; // >= MinImageCount + VkPipelineCache PipelineCache; // Optional + + // Pipeline + VkRenderPass RenderPass; // Ignored if using dynamic rendering + uint32_t Subpass; VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT - // (Optional) - VkPipelineCache PipelineCache; - uint32_t Subpass; - - // (Optional) Set to create internal descriptor pool instead of using DescriptorPool - uint32_t DescriptorPoolSize; - // (Optional) Dynamic Rendering - // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. + // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3 + setup PipelineRenderingCreateInfo. bool UseDynamicRendering; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR From 026d47cd35ca2b2088266950127b5074a0cf852a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Sep 2025 17:47:36 +0200 Subject: [PATCH 1285/2359] Backends: Vulkan: store pColorAttachmentFormats deep-copy into an ImVector. (#8282, #8110) --- backends/imgui_impl_vulkan.cpp | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index db23aad49..65fecb41e 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -257,6 +257,7 @@ struct ImGui_ImplVulkan_Data VkShaderModule ShaderModuleVert; VkShaderModule ShaderModuleFrag; VkDescriptorPool DescriptorPool; + ImVector PipelineRenderingCreateInfoColorAttachmentFormats; // Deep copy of format array // Texture management VkSampler TexSampler; @@ -1160,6 +1161,13 @@ void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCrea { v->PipelineRenderingCreateInfo = info.PipelineRenderingCreateInfo; pipeline_rendering_create_info = &v->PipelineRenderingCreateInfo; + if (v->PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) + { + // Deep copy buffer to reduce error-rate for end user (#8282) + bd->PipelineRenderingCreateInfoColorAttachmentFormats.resize((int)v->PipelineRenderingCreateInfo.colorAttachmentCount); + memcpy(bd->PipelineRenderingCreateInfoColorAttachmentFormats.Data, v->PipelineRenderingCreateInfo.pColorAttachmentFormats, (size_t)bd->PipelineRenderingCreateInfoColorAttachmentFormats.size_in_bytes()); + v->PipelineRenderingCreateInfo.pColorAttachmentFormats = bd->PipelineRenderingCreateInfoColorAttachmentFormats.Data; + } } #endif bd->Pipeline = ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, v->Subpass, pipeline_rendering_create_info); @@ -1294,17 +1302,6 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) vkGetPhysicalDeviceProperties(info->PhysicalDevice, &properties); bd->NonCoherentAtomSize = properties.limits.nonCoherentAtomSize; -#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; - if (v->PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) - { - // Deep copy buffer to reduce error-rate for end user (#8282) - VkFormat* formats_copy = (VkFormat*)IM_ALLOC(sizeof(VkFormat) * v->PipelineRenderingCreateInfo.colorAttachmentCount); - memcpy(formats_copy, v->PipelineRenderingCreateInfo.pColorAttachmentFormats, sizeof(VkFormat) * v->PipelineRenderingCreateInfo.colorAttachmentCount); - v->PipelineRenderingCreateInfo.pColorAttachmentFormats = formats_copy; - } -#endif - if (!ImGui_ImplVulkan_CreateDeviceObjects()) IM_ASSERT(0 && "ImGui_ImplVulkan_CreateDeviceObjects() failed!"); // <- Can't be hit yet. @@ -1318,9 +1315,6 @@ void ImGui_ImplVulkan_Shutdown() ImGuiIO& io = ImGui::GetIO(); ImGui_ImplVulkan_DestroyDeviceObjects(); -#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - IM_FREE((void*)const_cast(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pColorAttachmentFormats)); -#endif io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; From 02af06ea5f57696b93f0dfe77a9e2525522ba76e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Sep 2025 18:13:49 +0200 Subject: [PATCH 1286/2359] Backends: Vulkan: rewrite pColorAttachmentFormats deep-copy to avoid issues when calling multiple times. (#8282, #8110) --- backends/imgui_impl_vulkan.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 65fecb41e..ad520f6b8 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1164,8 +1164,10 @@ void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCrea if (v->PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) { // Deep copy buffer to reduce error-rate for end user (#8282) - bd->PipelineRenderingCreateInfoColorAttachmentFormats.resize((int)v->PipelineRenderingCreateInfo.colorAttachmentCount); - memcpy(bd->PipelineRenderingCreateInfoColorAttachmentFormats.Data, v->PipelineRenderingCreateInfo.pColorAttachmentFormats, (size_t)bd->PipelineRenderingCreateInfoColorAttachmentFormats.size_in_bytes()); + ImVector formats; + formats.resize((int)v->PipelineRenderingCreateInfo.colorAttachmentCount); + memcpy(formats.Data, v->PipelineRenderingCreateInfo.pColorAttachmentFormats, (size_t)formats.size_in_bytes()); + formats.swap(bd->PipelineRenderingCreateInfoColorAttachmentFormats); v->PipelineRenderingCreateInfo.pColorAttachmentFormats = bd->PipelineRenderingCreateInfoColorAttachmentFormats.Data; } } From 09ebcf1779d77153cfb8e5b17ae316f578760e97 Mon Sep 17 00:00:00 2001 From: fdsa <14tanks999@gmail.com> Date: Sat, 6 Sep 2025 01:18:35 -0700 Subject: [PATCH 1287/2359] Docs: fixed mismatched parentheses & other small changes. (#8922) --- backends/imgui_impl_glfw.cpp | 2 +- backends/imgui_impl_vulkan.cpp | 6 +++--- backends/imgui_impl_vulkan.h | 6 +++--- docs/CHANGELOG.txt | 6 +++--- imgui.cpp | 12 ++++++------ imgui.h | 20 ++++++++++---------- imgui_demo.cpp | 10 +++++----- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 8 ++++---- 11 files changed, 38 insertions(+), 38 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 98e07ce5c..0cb49fda2 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -594,7 +594,7 @@ void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window) bd->PrevUserCallbackMonitor = nullptr; } -// Set to 'true' to enable chaining installed callbacks for all windows (including secondary viewports created by backends or by user. +// Set to 'true' to enable chaining installed callbacks for all windows (including secondary viewports created by backends or by user). // This is 'false' by default meaning we only chain callbacks for the main viewport. // We cannot set this to 'true' by default because user callbacks code may be not testing the 'window' parameter of their callback. // If you set this to 'true' your user callback code will need to make sure you are testing the 'window' parameter. diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index ad520f6b8..aa8d3092c 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -120,7 +120,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); // Vulkan prototypes for use with custom loaders -// (see description of IMGUI_IMPL_VULKAN_NO_PROTOTYPES in imgui_impl_vulkan.h +// (see description of IMGUI_IMPL_VULKAN_NO_PROTOTYPES in imgui_impl_vulkan.h) #if defined(VK_NO_PROTOTYPES) && !defined(VOLK_H_) #define IMGUI_IMPL_VULKAN_USE_LOADER static bool g_FunctionsLoaded = false; @@ -1411,7 +1411,7 @@ void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulk //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers -// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.) +// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.) //------------------------------------------------------------------------- // You probably do NOT need to use or care about those functions. // Those functions only exist because: @@ -1421,7 +1421,7 @@ void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulk // but it is too much code to duplicate everywhere so we exceptionally expose them. // // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). -// You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. +// You may read this code to learn about Vulkan, but it is recommended you use your own custom tailored code to do equivalent work. // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index c7f3007dc..a24cb2cdb 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -124,7 +124,7 @@ struct ImGui_ImplVulkan_MainPipelineCreateInfo VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR #endif }; -IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCreateInfo& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext)) +IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCreateInfo& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext))) // (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. IMGUI_IMPL_API void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex); @@ -163,12 +163,12 @@ struct ImGui_ImplVulkan_RenderState // // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, // render pass, frame buffers, etc.). You may read this code if you are curious, but -// it is recommended you use you own custom tailored code to do equivalent work. +// it is recommended you use your own custom tailored code to do equivalent work. // // We don't provide a strong guarantee that we won't change those functions API. // // The ImGui_ImplVulkanH_XXX functions should NOT interact with any of the state used -// by the regular ImGui_ImplVulkan_XXX functions). +// by the regular ImGui_ImplVulkan_XXX functions. //------------------------------------------------------------------------- struct ImGui_ImplVulkanH_Frame; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index afdcbfc6c..cdc51372c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -362,7 +362,7 @@ Breaking changes: to 4096 but that limit isn't necessary anymore, and Renderer_TextureMaxWidth covers this) However you may set TexMinWidth = TexMaxWidth for the same effect. - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on - ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. + ImGuiContext to create one), you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. - Fonts: obsoleted ImGui::SetWindowFontScale() which is not useful anymore. Prefer using PushFont(NULL, style.FontSizeBase * factor) or to manipulate other scaling factors. @@ -1144,7 +1144,7 @@ Breaking changes: allows casting any pointer/integer type without warning: - May warn: ImGui::Image((void*)MyTextureData, ...); - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...); - - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...); + - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData, ...); - Note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors and extra render parameters) if you like. - IO: moved ImGuiConfigFlags_NavEnableSetMousePos to standalone io.ConfigNavMoveSetMousePos bool. @@ -4514,7 +4514,7 @@ Breaking Changes: - ShowTestWindow() -> use ShowDemoWindow() - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow) - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) - - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f) + - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)) - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing() - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding diff --git a/imgui.cpp b/imgui.cpp index a4128f2dc..466f7390d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -444,7 +444,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling. - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese(). - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327) - - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. + - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one), you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors. - Fonts: obsoleted ImFont::Scale which is not useful anymore. - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: @@ -526,7 +526,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: in doubt it is almost always better to do an intermediate intptr_t cast, since it allows casting any pointer/integer type without warning: - May warn: ImGui::Image((void*)MyTextureData, ...); - May warn: ImGui::Image((void*)(intptr_t)MyTextureData, ...); - - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData), ...); + - Won't warn: ImGui::Image((ImTextureID)(intptr_t)MyTextureData, ...); - note that you can always define ImTextureID to be your own high-level structures (with dedicated constructors) if you like. - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76) - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed). @@ -813,7 +813,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - ShowTestWindow() -> use ShowDemoWindow() - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow) - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) - - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f) + - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)) - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing() - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding @@ -7329,7 +7329,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } // Process SetNextWindow***() calls - // (FIXME: Consider splitting the HasXXX flags into X/Y components + // (FIXME: Consider splitting the HasXXX flags into X/Y components) bool window_pos_set_by_api = false; bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) @@ -8463,7 +8463,7 @@ void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& s } // Content size = inner scrollable rectangle, padded with WindowPadding. -// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item. +// SetNextWindowContentSize(ImVec2(100,100)) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item. void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; @@ -17298,7 +17298,7 @@ void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) } const ImVec2* pr = window->NavPreferredScoringPosRel; for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++) - BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater. + BulletText("NavPreferredScoringPosRel[%d] = (%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater. BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); } if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); } diff --git a/imgui.h b/imgui.h index cee72416c..befb2d15d 100644 --- a/imgui.h +++ b/imgui.h @@ -1056,8 +1056,8 @@ namespace ImGui // Inputs Utilities: Shortcut Testing & Routing [BETA] // - ImGuiKeyChord = a ImGuiKey + optional ImGuiMod_Alt/ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Super. - // ImGuiKey_C // Accepted by functions taking ImGuiKey or ImGuiKeyChord arguments) - // ImGuiMod_Ctrl | ImGuiKey_C // Accepted by functions taking ImGuiKeyChord arguments) + // ImGuiKey_C // Accepted by functions taking ImGuiKey or ImGuiKeyChord arguments + // ImGuiMod_Ctrl | ImGuiKey_C // Accepted by functions taking ImGuiKeyChord arguments // only ImGuiMod_XXX values are legal to combine with an ImGuiKey. You CANNOT combine two ImGuiKey values. // - The general idea is that several callers may register interest in a shortcut, and only one owner gets it. // Parent -> call Shortcut(Ctrl+S) // When Parent is focused, Parent gets the shortcut. @@ -1185,7 +1185,7 @@ enum ImGuiWindowFlags_ }; // Flags for ImGui::BeginChild() -// (Legacy: bit 0 must always correspond to ImGuiChildFlags_Borders to be backward compatible with old API using 'bool border = false'. +// (Legacy: bit 0 must always correspond to ImGuiChildFlags_Borders to be backward compatible with old API using 'bool border = false'.) // About using AutoResizeX/AutoResizeY flags: // - May be combined with SetNextWindowSizeConstraints() to set a min/max size for each axis (see "Demo->Child->Auto-resize with Constraints"). // - Size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing. @@ -2433,7 +2433,7 @@ struct ImGuiIO // Option to enable various debug tools showing buttons that will call the IM_DEBUG_BREAK() macro. // - The Item Picker tool will be available regardless of this being enabled, in order to maximize its discoverability. // - Requires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application. - // e.g. io.ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent() on Win32, or refer to ImOsIsDebuggerPresent() imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version). + // e.g. io.ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent() on Win32, or refer to ImOsIsDebuggerPresent() imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version. bool ConfigDebugIsDebuggerPresent; // = false // Enable various tools calling IM_DEBUG_BREAK(). // Tools to detect code submitting items with conflicting/duplicate IDs @@ -2536,7 +2536,7 @@ struct ImGuiIO bool KeySuper; // Keyboard modifier down: Windows/Super (non-macOS), Ctrl (macOS) // Other state maintained from data above + IO function calls - ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. Read-only, updated by NewFrame() + ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags). Read-only, updated by NewFrame() ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. MUST use 'key - ImGuiKey_NamedKey_BEGIN' as index. Use IsKeyXXX() functions to access this. bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) @@ -2613,10 +2613,10 @@ struct ImGuiInputTextCallbackData ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() - int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 + int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land: == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] int CursorPos; // // Read-write // [Completion,History,Always] - int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection) + int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection int SelectionEnd; // // Read-write // [Completion,History,Always] // Helper functions for text manipulation. @@ -3133,7 +3133,7 @@ struct ImDrawCmd // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! - inline ImTextureID GetTexID() const; // == (TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID + inline ImTextureID GetTexID() const; // == (TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID) }; // Vertex layout @@ -3630,7 +3630,7 @@ struct ImFontAtlas // - User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). // - The pitch is always = Width * BytesPerPixels (1 or 4) // - Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into - // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. + // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste). // - From 1.92 with backends supporting ImGuiBackendFlags_RendererHasTextures: // - Calling Build(), GetTexDataAsAlpha8(), GetTexDataAsRGBA32() is not needed. // - In backend: replace calls to ImFontAtlas::SetTexID() with calls to ImTextureData::SetTexID() after honoring texture creation. @@ -3745,7 +3745,7 @@ struct ImFontAtlas IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X #endif //unsigned int FontBuilderFlags; // OBSOLETED in 1.92.X: Renamed to FontLoaderFlags. - //int TexDesiredWidth; // OBSOLETED in 1.92.X: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) + //int TexDesiredWidth; // OBSOLETED in 1.92.X: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index be1698bdd..2a7b9ac39 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3229,7 +3229,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX); ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f); ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f); - //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacingY, 0.0f); + //ImGui::PushStyleVarY(ImGuiStyleVar_ItemSpacing, 0.0f); } ImGuiListClipper clipper; @@ -5182,7 +5182,7 @@ static void DemoWindowPopups() // Typical use for regular windows: // bool my_tool_is_active = false; if (ImGui::Button("Open")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin("My Tool", &my_tool_is_active) { [...] } End(); // Typical use for popups: - // if (ImGui::Button("Open")) ImGui::OpenPopup("MyPopup"); if (ImGui::BeginPopup("MyPopup") { [...] EndPopup(); } + // if (ImGui::Button("Open")) ImGui::OpenPopup("MyPopup"); if (ImGui::BeginPopup("MyPopup")) { [...] EndPopup(); } // With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state. // This may be a bit confusing at first but it should quickly make sense. Follow on the examples below. @@ -5768,7 +5768,7 @@ static void DemoWindowTables() 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_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers)"); PopStyleCompact(); if (ImGui::BeginTable("table1", 3, flags)) @@ -7261,7 +7261,7 @@ static void DemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH); - ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers)"); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers)"); ImGui::TreePop(); } @@ -9643,7 +9643,7 @@ static void ShowExampleAppConstrainedResize(bool* p_open) IMGUI_DEMO_MARKER("Examples/Constrained Resizing window"); if (ImGui::GetIO().KeyShift) { - // Display a dummy viewport (in your real app you would likely use ImageButton() to display a texture. + // Display a dummy viewport (in your real app you would likely use ImageButton() to display a texture) ImVec2 avail_size = ImGui::GetContentRegionAvail(); ImVec2 pos = ImGui::GetCursorScreenPos(); ImGui::ColorButton("viewport", ImVec4(0.5f, 0.2f, 0.5f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, avail_size); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ee7f55efa..1eb5b90fe 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -48,7 +48,7 @@ Index of this file: #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 #pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). -#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer) +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). #endif // Clang/GCC warnings with -Weverything diff --git a/imgui_internal.h b/imgui_internal.h index 739ae692c..3c792a866 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -77,8 +77,8 @@ Index of this file: #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) -#pragma warning (disable: 26812) // The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer) #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types #endif diff --git a/imgui_tables.cpp b/imgui_tables.cpp index c2b7548c9..ba8f0034f 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -437,7 +437,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (table->InnerWindow->SkipItems && outer_window_is_measuring_size) table->InnerWindow->SkipItems = false; - // When using multiple instances, ensure they have the same amount of horizontal decorations (aka vertical scrollbar) so stretched columns can be aligned) + // When using multiple instances, ensure they have the same amount of horizontal decorations (aka vertical scrollbar) so stretched columns can be aligned if (instance_no == 0) { table->HasScrollbarYPrev = table->HasScrollbarYCurr; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f66baf767..31088b7c1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4403,7 +4403,7 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im if (c == '.' || c == ',') c = c_decimal_point; - // Full-width -> half-width conversion for numeric fields (https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block) + // Full-width -> half-width conversion for numeric fields: https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block) // While this is mostly convenient, this has the side-effect for uninformed users accidentally inputting full-width characters that they may // scratch their head as to why it works in numerical fields vs in generic text fields it would require support in the font. if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | ImGuiInputTextFlags_CharsHexadecimal)) @@ -8370,7 +8370,7 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) // - Optimized select can append unsorted, then sort in a second pass. Optimized unselect can clear in-place then compact in a second pass. // - A more optimal version wouldn't even use ImGuiStorage but directly a ImVector to reduce bandwidth, but this is a reasonable trade off to reuse code. // - There are many ways this could be better optimized. The worse case scenario being: using BoxSelect2d in a grid, box-select scrolling down while wiggling - // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each.) + // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each. // FIXME-OPT: For each block of consecutive SetRange request: // - add all requests to a sorted list, store ID, selected, offset in ImGuiStorage. // - rewrite sorted storage a single time. @@ -9085,7 +9085,7 @@ 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. + // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.) popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f; float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); @@ -9292,7 +9292,7 @@ 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. + // 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 checkmark_w = IM_TRUNC(g.FontSize * 1.20f); From bed08daede8b54ca279e9c95235735d26056be8f Mon Sep 17 00:00:00 2001 From: fgungor Date: Mon, 8 Sep 2025 11:32:38 +0200 Subject: [PATCH 1288/2359] Backends: SDLGPU3: fixed double assignment. (#8924) --- backends/imgui_impl_sdlgpu3.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 8420da4c5..3b6db79e8 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -85,7 +85,7 @@ static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData() static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, ImGui_ImplSDLGPU3_RenderState* render_state, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height) { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - render_state->SamplerCurrent = render_state->SamplerCurrent = bd->TexSampler; + render_state->SamplerCurrent = bd->TexSampler; // Bind graphics pipeline SDL_BindGPUGraphicsPipeline(render_pass, pipeline); From f77f68a5ede94d2113f87713450b936555aa2e7f Mon Sep 17 00:00:00 2001 From: yaz0r <363511+yaz0r@users.noreply.github.com> Date: Sun, 7 Sep 2025 20:27:00 -0700 Subject: [PATCH 1289/2359] CI: Windows: update to 1.4.326 + pull Vulkan from KhronosGroup's Vulkan-Headers and Vulkan-Loader. (#8925, #8778) --- .github/workflows/build.yml | 19 +++++++++++++++---- docs/CHANGELOG.txt | 1 + 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bb2e502a2..4ff14341e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -30,14 +30,25 @@ jobs: Invoke-WebRequest -Uri "https://www.libsdl.org/release/SDL2-devel-2.32.8-VC.zip" -OutFile "SDL2-devel-2.32.8-VC.zip" Expand-Archive -Path SDL2-devel-2.32.8-VC.zip echo "SDL2_DIR=$(pwd)\SDL2-devel-2.32.8-VC\SDL2-2.32.8\" >>${env:GITHUB_ENV} - + Invoke-WebRequest -Uri "https://www.libsdl.org/release/SDL3-devel-3.2.18-VC.zip" -OutFile "SDL3-devel-3.2.18-VC.zip" Expand-Archive -Path SDL3-devel-3.2.18-VC.zip echo "SDL3_DIR=$(pwd)\SDL3-devel-3.2.18-VC\SDL3-3.2.18\" >>${env:GITHUB_ENV} - Invoke-WebRequest -Uri "https://github.com/ocornut/imgui/files/3789205/vulkan-sdk-1.1.121.2.zip" -OutFile vulkan-sdk-1.1.121.2.zip - Expand-Archive -Path vulkan-sdk-1.1.121.2.zip - echo "VULKAN_SDK=$(pwd)\vulkan-sdk-1.1.121.2\" >>${env:GITHUB_ENV} + # VulkanSDK (retrieve minimal bits of the SDK from git) + $vulkanVersion = "1.4.326" + # 1. Get the vulkan headers, we will treat that folder as the sdk folder to avoid having to copy headers around + Invoke-WebRequest -Uri "https://github.com/KhronosGroup/Vulkan-Headers/archive/refs/tags/v$($vulkanVersion).zip" -OutFile Vulkan-Headers-$($vulkanVersion).zip + Expand-Archive -Path Vulkan-Headers-$($vulkanVersion).zip + echo "VULKAN_SDK=$(pwd)\Vulkan-Headers-$($vulkanVersion)\Vulkan-Headers-$($vulkanVersion)" >>${env:GITHUB_ENV} + # 2. Get and build the vulkan loader source code (UPDATE_DEPS=On will make it automatically fetch its dependencies) + Invoke-WebRequest -Uri "https://github.com/KhronosGroup/Vulkan-Loader/archive/refs/tags/v$($vulkanVersion).zip" -OutFile Vulkan-Loader-$($vulkanVersion).zip + Expand-Archive -Path Vulkan-Loader-$($vulkanVersion).zip + cmake -S Vulkan-Loader-$($vulkanVersion)\Vulkan-Loader-$($vulkanVersion) -B VulkanLoader-build -D UPDATE_DEPS=On + cmake --build VulkanLoader-build + # 3. Copy the built lib/dll to the expected place + mkdir Vulkan-Headers-$($vulkanVersion)\Vulkan-Headers-$($vulkanVersion)\Lib + copy VulkanLoader-build\loader\Debug\vulkan-1.* Vulkan-Headers-$($vulkanVersion)\Vulkan-Headers-$($vulkanVersion)\Lib\ - name: Fix Projects shell: powershell diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cdc51372c..836c57a5f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -177,6 +177,7 @@ Other Changes: to play nice with -fsanitize=undefined. (#8874) [@i25e] - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] - CI: Updated Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] +- CI: Updates Windows CI to use a more recent VulkanSDK. (#8925, #8778) [@yaz0r] - Examples: SDL3+Metal: added SDL3+Metal example. (#8827, #8825) [@shi-yan] - Examples: SDL3+SDL_GPU: use SDL_WaitAndAcquireGPUSwapchainTexture() instead of SDL_AcquireGPUSwapchainTexture(). (#8830) [@itsdanott] From 8a35ce0e982039a9b7399a55792f5737bd1447e3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 Aug 2025 14:27:15 +0200 Subject: [PATCH 1290/2359] CalcWordWrapPosition() breaks on \n instead of relying on caller to do it + expose ImTextCalcWordWrapNextLineStart(). (#3237, #952, #1062, #7363) Should be functional no-op, fingers crossed. Breaking on \n allows caller to count lines reliably. --- imgui.h | 2 +- imgui_draw.cpp | 15 +++++---------- imgui_internal.h | 1 + imgui_widgets.cpp | 5 +---- 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/imgui.h b/imgui.h index befb2d15d..f8db83d4b 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.3 WIP" -#define IMGUI_VERSION_NUM 19225 +#define IMGUI_VERSION_NUM 19226 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1eb5b90fe..5eed9bb2e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5340,7 +5340,7 @@ ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float fo } // Trim trailing space and find beginning of next line -static inline const char* CalcWordWrapNextLineStartA(const char* text, const char* text_end) +const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end) { while (text < text_end && ImCharIsBlankA(*text)) text++; @@ -5392,12 +5392,7 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha if (c < 32) { if (c == '\n') - { - line_width = word_width = blank_width = 0.0f; - inside_word = true; - s = next_s; - continue; - } + return s; // Direct return, skip "Wrap_width is too small to fit anything" path. if (c == '\r') { s = next_s; @@ -5489,7 +5484,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons text_size.y += line_height; line_width = 0.0f; word_wrap_eol = NULL; - s = CalcWordWrapNextLineStartA(s, text_end); // Wrapping skips upcoming blanks + s = ImTextCalcWordWrapNextLineStart(s, text_end); // Wrapping skips upcoming blanks continue; } } @@ -5613,7 +5608,7 @@ begin: // If the specs for CalcWordWrapPosition() were reworked to optionally return on \n we could combine both. // However it is still better than nothing performing the fast-forward! s = CalcWordWrapPosition(size, s, line_end ? line_end : text_end, wrap_width); - s = CalcWordWrapNextLineStartA(s, text_end); + s = ImTextCalcWordWrapNextLineStart(s, text_end); } else { @@ -5667,7 +5662,7 @@ begin: if (y > clip_rect.w) break; // break out of main loop word_wrap_eol = NULL; - s = CalcWordWrapNextLineStartA(s, text_end); // Wrapping skips upcoming blanks + s = ImTextCalcWordWrapNextLineStart(s, text_end); // Wrapping skips upcoming blanks continue; } } diff --git a/imgui_internal.h b/imgui_internal.h index 3c792a866..4d6d13efe 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -428,6 +428,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_text_curr); // return previous UTF-8 code-point. 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 const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end); // trim trailing space and find beginning of next line // Helpers: File System #ifdef IMGUI_DISABLE_FILE_FUNCTIONS diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 31088b7c1..81b3271a4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3911,9 +3911,6 @@ bool ImGui::InputDouble(const char* label, double* v, double step, double step_f // - InputText() // - InputTextWithHint() // - InputTextMultiline() -// - InputTextGetCharInfo() [Internal] -// - InputTextReindexLines() [Internal] -// - InputTextReindexLinesRange() [Internal] // - InputTextEx() [Internal] // - DebugNodeInputTextState() [Internal] //------------------------------------------------------------------------- @@ -4525,7 +4522,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(buf != NULL && buf_size >= 0); IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) - IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline will not work with left-trimming + IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not not work with left-trimming ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; From c63b5bd8fb965977784cf7ad13d4c0cf5f81790e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 Aug 2025 16:11:46 +0200 Subject: [PATCH 1291/2359] Internals: extracted ImFont::CalcWordWrapPosition() into ImFontCalcWordWrapPositionEx() so we can make change to its signature. (for #3237, #952, #1062, #7363) --- imgui_draw.cpp | 16 +++++++++++----- imgui_internal.h | 3 +++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5eed9bb2e..51633c69a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5352,7 +5352,8 @@ const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_e // 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. // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) -const char* ImFont::CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width) +const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width) +//, ImDrawTextFlags flags) { // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" @@ -5366,7 +5367,7 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha // Cut words that cannot possibly fit within one line. // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" - ImFontBaked* baked = GetFontBaked(size); + ImFontBaked* baked = font->GetFontBaked(size); const float scale = size / baked->Size; float line_width = 0.0f; @@ -5453,6 +5454,11 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha return s; } +const char* ImFont::CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width) +{ + return ImFontCalcWordWrapPositionEx(this, size, text, text_end, wrap_width); +} + ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining) { if (!text_end) @@ -5475,7 +5481,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = CalcWordWrapPosition(size, s, text_end, wrap_width - line_width); + word_wrap_eol = ImFontCalcWordWrapPositionEx(this, size, s, text_end, wrap_width - line_width); if (s >= word_wrap_eol) { @@ -5607,7 +5613,7 @@ begin: // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPosition(). // If the specs for CalcWordWrapPosition() were reworked to optionally return on \n we could combine both. // However it is still better than nothing performing the fast-forward! - s = CalcWordWrapPosition(size, s, line_end ? line_end : text_end, wrap_width); + s = ImFontCalcWordWrapPositionEx(this, size, s, line_end ? line_end : text_end, wrap_width); s = ImTextCalcWordWrapNextLineStart(s, text_end); } else @@ -5653,7 +5659,7 @@ begin: { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = CalcWordWrapPosition(size, s, text_end, wrap_width - (x - origin_x)); + word_wrap_eol = ImFontCalcWordWrapPositionEx(this, size, s, text_end, wrap_width - (x - origin_x)); if (s >= word_wrap_eol) { diff --git a/imgui_internal.h b/imgui_internal.h index 4d6d13efe..cd4fa4694 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -428,6 +428,9 @@ 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_text_curr); // return previous UTF-8 code-point. 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. + +// Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) +IMGUI_API const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width); IMGUI_API const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end); // trim trailing space and find beginning of next line // Helpers: File System From 34ab6c8a89fa42463f47a2363335d3d29c57ec7e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Aug 2025 21:43:07 +0200 Subject: [PATCH 1292/2359] Internals: extracted ImFont::CalcTextSizeA() into ImFontCalcTextSizeEx() so we can make change to its signature. (for #3237, #952, #1062, #7363) --- imgui_draw.cpp | 29 ++++++++++++++++------------- imgui_internal.h | 1 + 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 51633c69a..a7c5fcba3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5459,13 +5459,13 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha return ImFontCalcWordWrapPositionEx(this, size, text, text_end, wrap_width); } -ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining) +ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining) { if (!text_end) text_end = text_begin + ImStrlen(text_begin); // FIXME-OPT: Need to avoid this. const float line_height = size; - ImFontBaked* baked = GetFontBaked(size); + ImFontBaked* baked = font->GetFontBaked(size); const float scale = size / baked->Size; ImVec2 text_size = ImVec2(0, 0); @@ -5477,11 +5477,12 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons const char* s = text_begin; while (s < text_end) { + // Word-wrapping if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = ImFontCalcWordWrapPositionEx(this, size, s, text_end, wrap_width - line_width); + word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, s, text_end, wrap_width - line_width); if (s >= word_wrap_eol) { @@ -5503,18 +5504,15 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons else s += ImTextCharFromUtf8(&c, s, text_end); - if (c < 32) + if (c == '\n') { - if (c == '\n') - { - text_size.x = ImMax(text_size.x, line_width); - text_size.y += line_height; - line_width = 0.0f; - continue; - } - if (c == '\r') - continue; + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + continue; } + if (c == '\r') + continue; // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f; @@ -5543,6 +5541,11 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons 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) +{ + return ImFontCalcTextSizeEx(this, size, max_width, wrap_width, text_begin, text_end, out_remaining); +} + // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip) { diff --git a/imgui_internal.h b/imgui_internal.h index cd4fa4694..efb947a62 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -430,6 +430,7 @@ IMGUI_API const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_star 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. // Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) +IMGUI_API ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining); IMGUI_API const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width); IMGUI_API const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end); // trim trailing space and find beginning of next line From bc6478f6518510bd7d8740f867ed781b41c7ea84 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 Aug 2025 16:38:31 +0200 Subject: [PATCH 1293/2359] Internals: added ImDrawTextFlags_WrapKeepTrailingBlanks required for text-edit style word-wrapping. (for #3237, #952, #1062, #7363) --- imgui_draw.cpp | 7 ++++--- imgui_internal.h | 8 +++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a7c5fcba3..82f740682 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5352,8 +5352,7 @@ const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_e // 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. // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) -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, const char* text_end, float wrap_width, ImDrawTextFlags flags) { // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" @@ -5428,6 +5427,8 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t { prev_word_end = word_end; line_width += word_width + blank_width; + if ((flags & ImDrawTextFlags_WrapKeepBlanks) && line_width <= wrap_width) + prev_word_end = s; word_width = blank_width = 0.0f; } @@ -5456,7 +5457,7 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t const char* ImFont::CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width) { - return ImFontCalcWordWrapPositionEx(this, size, text, text_end, wrap_width); + return ImFontCalcWordWrapPositionEx(this, size, text, 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, const char** out_remaining) diff --git a/imgui_internal.h b/imgui_internal.h index efb947a62..2efed6846 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -193,6 +193,7 @@ enum ImGuiLocKey : int; // -> enum ImGuiLocKey // E typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical // Flags +typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Flags: for ImTextCalcWordWrapPositionEx() typedef int ImGuiActivateFlags; // -> enum ImGuiActivateFlags_ // Flags: for navigation/focus function (will be for ActivateItem() later) typedef int ImGuiDebugLogFlags; // -> enum ImGuiDebugLogFlags_ // Flags: for ShowDebugLogWindow(), g.DebugLogFlags typedef int ImGuiFocusRequestFlags; // -> enum ImGuiFocusRequestFlags_ // Flags: for FocusWindow() @@ -430,8 +431,13 @@ IMGUI_API const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_star 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. // Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) +enum ImDrawTextFlags_ +{ + ImDrawTextFlags_None = 0, + ImDrawTextFlags_WrapKeepBlanks = 1 << 1, +}; IMGUI_API ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining); -IMGUI_API const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width); +IMGUI_API const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width, ImDrawTextFlags flags = 0); IMGUI_API const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end); // trim trailing space and find beginning of next line // Helpers: File System From a9945899c615c914fc1eb2c8a679226847ddfbf2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 Aug 2025 17:40:39 +0200 Subject: [PATCH 1294/2359] stb_textedit: extracted stb_textedit_move_line_start()/stb_textedit_move_line_end(), adding STB_TEXTEDIT_MOVELINESTART,STB_TEXTEDIT_MOVELINEEND support. (#3237, #952, #1062, #7363) --- imstb_textedit.h | 61 +++++++++++++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 27 deletions(-) diff --git a/imstb_textedit.h b/imstb_textedit.h index ac4db0fb9..605e44adb 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -668,6 +668,35 @@ static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditSt } } +// [DEAR IMGUI] Extracted this function so we can more easily add support for word-wrapping. +#ifndef STB_TEXTEDIT_MOVELINESTART +static int stb_textedit_move_line_start(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int cursor) +{ + if (state->single_line) + return 0; + while (cursor > 0) { + int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, cursor); + if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) + break; + cursor = prev; + } + return cursor; +} +#define STB_TEXTEDIT_MOVELINESTART stb_textedit_move_line_start +#endif +#ifndef STB_TEXTEDIT_MOVELINEEND +static int stb_textedit_move_line_end(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int cursor) +{ + int n = STB_TEXTEDIT_STRINGLEN(str); + if (state->single_line) + return n; + while (cursor < n && STB_TEXTEDIT_GETCHAR(str, cursor) != STB_TEXTEDIT_NEWLINE) + cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, cursor); + return cursor; +} +#define STB_TEXTEDIT_MOVELINEEND stb_textedit_move_line_end +#endif + #ifdef STB_TEXTEDIT_IS_SPACE static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx ) { @@ -1024,7 +1053,7 @@ retry: prev_scan = prev; } find.first_char = find.prev_first; - find.prev_first = prev_scan; + find.prev_first = STB_TEXTEDIT_MOVELINESTART(str, state, prev_scan); } break; } @@ -1098,14 +1127,7 @@ retry: case STB_TEXTEDIT_K_LINESTART: stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); - if (state->single_line) - state->cursor = 0; - else while (state->cursor > 0) { - int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); - if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) - break; - state->cursor = prev; - } + state->cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state->cursor); state->has_preferred_x = 0; break; @@ -1113,13 +1135,9 @@ retry: case STB_TEXTEDIT_K_LINEEND2: #endif case STB_TEXTEDIT_K_LINEEND: { - int n = STB_TEXTEDIT_STRINGLEN(str); stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); - if (state->single_line) - state->cursor = n; - else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor); state->has_preferred_x = 0; break; } @@ -1130,14 +1148,7 @@ retry: case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); - if (state->single_line) - state->cursor = 0; - else while (state->cursor > 0) { - int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); - if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) - break; - state->cursor = prev; - } + state->cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state->cursor); state->select_end = state->cursor; state->has_preferred_x = 0; break; @@ -1146,13 +1157,9 @@ retry: case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: #endif case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { - int n = STB_TEXTEDIT_STRINGLEN(str); stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); - if (state->single_line) - state->cursor = n; - else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor); state->select_end = state->cursor; state->has_preferred_x = 0; break; From 56189cd814d28819bdb132aac173be2a1efe2e93 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Aug 2025 21:55:40 +0200 Subject: [PATCH 1295/2359] Internals: added ImDrawTextFlags_StopOnNewLine support to ImFontCalcTextSizeEx(), ImDrawTextFlags_WrapKeepTrailingBlanks to ImTextCalcWordWrapNextLineStart(). (for #3237, #952, #1062, #7363) --- imgui_draw.cpp | 32 +++++++++++++++++++++----------- imgui_internal.h | 5 +++-- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 82f740682..0477ea8a4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5340,10 +5340,11 @@ ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float fo } // Trim trailing space and find beginning of next line -const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end) +const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end, ImDrawTextFlags flags) { - while (text < text_end && ImCharIsBlankA(*text)) - text++; + if ((flags & ImDrawTextFlags_WrapKeepBlanks) == 0) + while (text < text_end && ImCharIsBlankA(*text)) + text++; if (*text == '\n') text++; return text; @@ -5460,14 +5461,16 @@ const char* ImFont::CalcWordWrapPosition(float size, const char* text, const cha return ImFontCalcWordWrapPositionEx(this, size, text, 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, const char** out_remaining) +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; - const float line_height = size; ImFontBaked* baked = font->GetFontBaked(size); - const float scale = size / baked->Size; + const float line_height = size; + const float scale = line_height / baked->Size; ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; @@ -5476,14 +5479,14 @@ ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wra const char* word_wrap_eol = NULL; const char* s = text_begin; - while (s < text_end) + while (s < text_end_display) { // Word-wrapping if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, s, text_end, wrap_width - line_width); + word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, s, text_end, wrap_width - line_width, flags); if (s >= word_wrap_eol) { @@ -5491,8 +5494,10 @@ ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wra text_size.x = line_width; text_size.y += line_height; line_width = 0.0f; + s = ImTextCalcWordWrapNextLineStart(s, text_end, flags); // Wrapping skips upcoming blanks + if (flags & ImDrawTextFlags_StopOnNewLine) + break; word_wrap_eol = NULL; - s = ImTextCalcWordWrapNextLineStart(s, text_end); // Wrapping skips upcoming blanks continue; } } @@ -5510,6 +5515,8 @@ ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wra text_size.x = ImMax(text_size.x, line_width); text_size.y += line_height; line_width = 0.0f; + if (flags & ImDrawTextFlags_StopOnNewLine) + break; continue; } if (c == '\r') @@ -5533,7 +5540,10 @@ ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wra if (text_size.x < line_width) text_size.x = line_width; - if (line_width > 0 || text_size.y == 0.0f) + if (out_offset != NULL) + *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n + + if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n text_size.y += line_height; if (out_remaining != NULL) @@ -5544,7 +5554,7 @@ ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wra ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining) { - return ImFontCalcTextSizeEx(this, size, max_width, wrap_width, text_begin, text_end, out_remaining); + return ImFontCalcTextSizeEx(this, size, max_width, wrap_width, text_begin, NULL, text_end, out_remaining, NULL, ImDrawTextFlags_None); } // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. diff --git a/imgui_internal.h b/imgui_internal.h index 2efed6846..e473c7302 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -435,10 +435,11 @@ enum ImDrawTextFlags_ { ImDrawTextFlags_None = 0, ImDrawTextFlags_WrapKeepBlanks = 1 << 1, + ImDrawTextFlags_StopOnNewLine = 1 << 2, }; -IMGUI_API ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining); +IMGUI_API 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); IMGUI_API const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width, ImDrawTextFlags flags = 0); -IMGUI_API const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end); // trim trailing space and find beginning of next line +IMGUI_API const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end, ImDrawTextFlags flags = 0); // trim trailing space and find beginning of next line // Helpers: File System #ifdef IMGUI_DISABLE_FILE_FUNCTIONS From 3cc7d1c81a3bdac2f376e1aa8023f85736971312 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Aug 2025 21:59:25 +0200 Subject: [PATCH 1296/2359] InputText: InputTextCalcTextSize() uses ImFontCalcTextSizeEx(). (for #3237, #952, #1062, #7363) --- imgui_draw.cpp | 2 +- imgui_widgets.cpp | 59 ++++++----------------------------------------- 2 files changed, 8 insertions(+), 53 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0477ea8a4..2408d0c9b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5554,7 +5554,7 @@ ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wra ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining) { - return ImFontCalcTextSizeEx(this, size, max_width, wrap_width, text_begin, NULL, 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. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 81b3271a4..31c07f32e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -136,7 +136,7 @@ static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); // For InputTextEx() static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false); static int InputTextCalcTextLenAndLineCount(ImGuiContext* ctx, const char* text_begin, const char** out_text_end); -static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); +static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining = NULL, ImVec2* out_offset = NULL, ImDrawTextFlags flags = 0); //------------------------------------------------------------------------- // [SECTION] Widgets: Text, etc. @@ -3959,55 +3959,10 @@ static int InputTextCalcTextLenAndLineCount(ImGuiContext*, const char* text_begi return line_count; } -// FIXME: Ideally we'd share code with ImFont::CalcTextSizeA() -static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining, ImVec2* out_offset, bool stop_on_new_line) +static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags) { ImGuiContext& g = *ctx; - //ImFont* font = g.Font; - ImFontBaked* baked = g.FontBaked; - const float line_height = g.FontSize; - const float scale = line_height / baked->Size; - - ImVec2 text_size = ImVec2(0, 0); - float line_width = 0.0f; - - const char* s = text_begin; - while (s < text_end) - { - unsigned int c = (unsigned int)*s; - if (c < 0x80) - s += 1; - else - s += ImTextCharFromUtf8(&c, s, text_end); - - if (c == '\n') - { - text_size.x = ImMax(text_size.x, line_width); - text_size.y += line_height; - line_width = 0.0f; - if (stop_on_new_line) - break; - continue; - } - if (c == '\r') - continue; - - line_width += baked->GetCharAdvance((ImWchar)c) * scale; - } - - if (text_size.x < line_width) - text_size.x = line_width; - - if (out_offset) - *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n - - if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n - text_size.y += line_height; - - if (remaining) - *remaining = s; - - return text_size; + return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, 0.0f, text_begin, text_end_display, text_end, out_remaining, out_offset, flags); } // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) @@ -4025,7 +3980,7 @@ static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* ob { const char* text = obj->TextSrc; const char* text_remaining = NULL; - const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, &text_remaining, NULL, true); + const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, text + obj->TextLen, &text_remaining, NULL, ImDrawTextFlags_StopOnNewLine | ImDrawTextFlags_WrapKeepTrailingBlanks); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; @@ -5303,11 +5258,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ selmin_line_no = line_count; // Calculate 2d position by finding the beginning of the line and measuring distance - cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(cursor_ptr, text_begin), cursor_ptr).x; + cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(cursor_ptr, text_begin), cursor_ptr, cursor_ptr, NULL, NULL, ImDrawTextFlags_WrapKeepTrailingBlanks).x; cursor_offset.y = cursor_line_no * g.FontSize; if (selmin_line_no >= 0) { - select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(selmin_ptr, text_begin), selmin_ptr).x; + select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(selmin_ptr, text_begin), selmin_ptr, selmin_ptr, NULL, NULL, ImDrawTextFlags_WrapKeepTrailingBlanks).x; select_start_offset.y = selmin_line_no * g.FontSize; } @@ -5373,7 +5328,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } else { - ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, &p, NULL, true); + ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, text_selected_end, &p, NULL, ImDrawTextFlags_StopOnNewLine); if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn)); From 11fff1ccf5b14c1d3785d42ef5b4655be7b002bb Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 27 Aug 2025 22:17:28 +0200 Subject: [PATCH 1297/2359] ImFont::RenderText() takes ImDrawTextFlags_CpuFineClip instead of bool cpu_fine_clip + forward ImDrawTextFlags to word-wrap code. (for #3237, #952, #1062, #7363) --- imgui.h | 3 ++- imgui_draw.cpp | 14 ++++++++------ imgui_internal.h | 1 + 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index f8db83d4b..b45e585a8 100644 --- a/imgui.h +++ b/imgui.h @@ -233,6 +233,7 @@ typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A // - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance +typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Internal, do not use! typedef int ImFontFlags; // -> enum ImFontFlags_ // Flags: for ImFont typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags @@ -3837,7 +3838,7 @@ struct ImFont 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 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, bool cpu_fine_clip = false); + 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); #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); } #endif diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2408d0c9b..9f2867859 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1718,7 +1718,7 @@ 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); + font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, 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) @@ -5597,7 +5597,8 @@ 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. -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, bool cpu_fine_clip) +// DO NOT CALL DIRECTLY THIS WILL CHANGE WIDLY IN 2025-2025. 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) { // Align to be pixel perfect begin: @@ -5627,8 +5628,8 @@ begin: // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPosition(). // If the specs for CalcWordWrapPosition() were reworked to optionally return on \n we could combine both. // However it is still better than nothing performing the fast-forward! - s = ImFontCalcWordWrapPositionEx(this, size, s, line_end ? line_end : text_end, wrap_width); - s = ImTextCalcWordWrapNextLineStart(s, text_end); + s = ImFontCalcWordWrapPositionEx(this, size, s, line_end ? line_end : text_end, wrap_width, flags); + s = ImTextCalcWordWrapNextLineStart(s, text_end, flags); } else { @@ -5663,6 +5664,7 @@ begin: ImDrawIdx* idx_write = draw_list->_IdxWritePtr; unsigned int vtx_index = draw_list->_VtxCurrentIdx; const int cmd_count = draw_list->CmdBuffer.Size; + const bool cpu_fine_clip = (flags & ImDrawTextFlags_CpuFineClip) != 0; const ImU32 col_untinted = col | ~IM_COL32_A_MASK; const char* word_wrap_eol = NULL; @@ -5673,7 +5675,7 @@ begin: { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = ImFontCalcWordWrapPositionEx(this, size, s, text_end, wrap_width - (x - origin_x)); + word_wrap_eol = ImFontCalcWordWrapPositionEx(this, size, s, text_end, wrap_width - (x - origin_x), flags); if (s >= word_wrap_eol) { @@ -5682,7 +5684,7 @@ begin: if (y > clip_rect.w) break; // break out of main loop word_wrap_eol = NULL; - s = ImTextCalcWordWrapNextLineStart(s, text_end); // Wrapping skips upcoming blanks + s = ImTextCalcWordWrapNextLineStart(s, text_end, flags); // Wrapping skips upcoming blanks continue; } } diff --git a/imgui_internal.h b/imgui_internal.h index e473c7302..d6f385aae 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -434,6 +434,7 @@ IMGUI_API int ImTextCountLines(const char* in_text, const char* in_tex enum ImDrawTextFlags_ { ImDrawTextFlags_None = 0, + ImDrawTextFlags_CpuFineClip = 1 << 0, // Must be == 1/true for legacy with 'bool cpu_fine_clip' arg to RenderText() ImDrawTextFlags_WrapKeepBlanks = 1 << 1, ImDrawTextFlags_StopOnNewLine = 1 << 2, }; From e422a38e4cef48136980262c56fa81c95dcf9eff Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Aug 2025 18:15:43 +0200 Subject: [PATCH 1298/2359] InputText: internals: expose LineCount, GetPreferredOffsetX(). --- imgui_internal.h | 2 ++ imgui_widgets.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/imgui_internal.h b/imgui_internal.h index d6f385aae..5eef3f95a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1234,6 +1234,7 @@ struct IMGUI_API ImGuiInputTextState ImVector CallbackTextBackup; // temporary storage for callback to support automatic reconcile of undo-stack int BufCapacity; // end-user buffer capacity (include zero terminator) ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) + int LineCount; // last line count (solely for debugging) float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection @@ -1248,6 +1249,7 @@ struct IMGUI_API ImGuiInputTextState void ClearFreeMemory() { TextA.clear(); TextToRevertTo.clear(); } void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation void OnCharPressed(unsigned int c); + float GetPreferredOffsetX() const; // Cursor & Selection void CursorAnimReset(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 31c07f32e..a708b27c5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4206,6 +4206,7 @@ void ImGuiInputTextState::ClearSelection() { Stb->select_start int ImGuiInputTextState::GetCursorPos() const { return Stb->cursor; } int ImGuiInputTextState::GetSelectionStart() const { return Stb->select_start; } int ImGuiInputTextState::GetSelectionEnd() const { return Stb->select_end; } +float ImGuiInputTextState::GetPreferredOffsetX() const { return Stb->has_preferred_x ? Stb->preferred_x : -1; } void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; } void ImGuiInputTextState::ReloadUserBufAndSelectAll() { WantReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; } void ImGuiInputTextState::ReloadUserBufAndKeepSelection() { WantReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; } @@ -5269,6 +5270,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) if (is_multiline) text_size = ImVec2(inner_size.x, line_count * g.FontSize); + state->LineCount = line_count; } // Scroll From a82f66a9b0c07da86afeeddc7ccdfb805f031309 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Aug 2025 18:17:46 +0200 Subject: [PATCH 1299/2359] InputText: Word-Wrap: added ImGuiInputTextFlags_WordWrap support. (#3237, #952, #1062, #7363) --- imgui_internal.h | 11 ++++ imgui_widgets.cpp | 150 +++++++++++++++++++++++++++++++++++----------- imstb_textedit.h | 8 +++ 3 files changed, 135 insertions(+), 34 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5eef3f95a..faeef64e0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1015,6 +1015,15 @@ enum ImGuiHoveredFlagsPrivate_ // Extend ImGuiInputTextFlags_ enum ImGuiInputTextFlagsPrivate_ { + // [Experimental] + // Word-wrapping caveats: + // - Not well tested yet. Please report any incorrect cursor movement, selection behavior etc. bug to https://github.com/ocornut/imgui/issues/3237. + // - With our current design it is _much_ slower than a regular text field. Editing a <50K buffer will generally be ok, but editing a 1MB buffer will waste meaningful amount of CPU. + // We are likely to not make the feature public until this is fixed (which requires bigger changes to InputText will be be generally desirable for this and other features) + // - Wrapping of long words/sections (e.g. words that are larger than available width) is currently visually not pleasing. + // - Vertical scrollbar is currently always visible. + ImGuiInputTextFlags_WordWrap = 1 << 24, // InputTextMultine(): wrap lines that are too long. (Ref #3237, #952, #1062) + // [Internal] ImGuiInputTextFlags_Multiline = 1 << 26, // For internal use by InputTextMultiline() ImGuiInputTextFlags_MergedItem = 1 << 27, // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. @@ -1235,11 +1244,13 @@ struct IMGUI_API ImGuiInputTextState int BufCapacity; // end-user buffer capacity (include zero terminator) ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) int LineCount; // last line count (solely for debugging) + float WrapWidth; // word-wrapping width float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection bool Edited; // edited this frame bool WantReloadUserBuf; // force a reload of user buf so it may be modified externally. may be automatic in future version. + ImS8 LastMoveDirectionLR; // ImGuiDir_Left or ImGuiDir_Right. track last movement direction so when cursor cross over a word-wrapping boundaries we can display it on either line depending on last move.s int ReloadSelectionStart; int ReloadSelectionEnd; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a708b27c5..17ac3c1db 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -135,7 +135,7 @@ static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); // For InputTextEx() static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false); -static int InputTextCalcTextLenAndLineCount(ImGuiContext* ctx, const char* text_begin, const char** out_text_end); +static int InputTextCalcTextLenAndLineCount(ImGuiContext* ctx, const char* text_begin, const char** out_text_end, float wrap_width); static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining = NULL, ImVec2* out_offset = NULL, ImDrawTextFlags flags = 0); //------------------------------------------------------------------------- @@ -3938,10 +3938,11 @@ bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, si } // This is only used in the path where the multiline widget is inactive. -static int InputTextCalcTextLenAndLineCount(ImGuiContext*, const char* text_begin, const char** out_text_end) +static int InputTextCalcTextLenAndLineCount(ImGuiContext* ctx, const char* text_begin, const char** out_text_end, float wrap_width) { int line_count = 0; const char* s = text_begin; + if (wrap_width == 0.0f) { while (true) { @@ -3955,6 +3956,23 @@ static int InputTextCalcTextLenAndLineCount(ImGuiContext*, const char* text_begi s = s_eol + 1; } } + else + { + // FIXME-WORDWRAP, FIXME-OPT: This is very suboptimal. + // We basically want both text_end and text_size, they could more optimally be emitted from a RenderText call that uses word-wrapping. + ImGuiContext& g = *ctx; + ImFont* font = g.Font; + const char* text_end = text_begin + strlen(text_begin); + while (s < text_end) + { + s = ImFontCalcWordWrapPositionEx(font, g.FontSize, s, text_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); + s = (*s == '\n') ? s + 1 : s; + line_count++; + } + if (text_end > text_begin && text_end[-1] == '\n') + line_count++; + IM_ASSERT(s == text_end); + } *out_text_end = s; return line_count; } @@ -3962,7 +3980,8 @@ static int InputTextCalcTextLenAndLineCount(ImGuiContext*, const char* text_begi static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags) { ImGuiContext& g = *ctx; - return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, 0.0f, text_begin, text_end_display, text_end, out_remaining, out_offset, flags); + ImGuiInputTextState* obj = &g.InputTextState; + return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj->WrapWidth, text_begin, text_end_display, text_end, out_remaining, out_offset, flags); } // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) @@ -3980,7 +3999,7 @@ static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* ob { const char* text = obj->TextSrc; const char* text_remaining = NULL; - const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, text + obj->TextLen, &text_remaining, NULL, ImDrawTextFlags_StopOnNewLine | ImDrawTextFlags_WrapKeepTrailingBlanks); + const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, text + obj->TextLen, &text_remaining, NULL, ImDrawTextFlags_StopOnNewLine | ImDrawTextFlags_WrapKeepBlanks); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; @@ -4185,6 +4204,11 @@ void ImGuiInputTextState::OnKeyPressed(int key) stb_textedit_key(this, Stb, key); CursorFollow = true; CursorAnimReset(); + const int key_u = (key & ~STB_TEXTEDIT_K_SHIFT); + if (key_u == STB_TEXTEDIT_K_LEFT || key_u == STB_TEXTEDIT_K_LINESTART || key_u == STB_TEXTEDIT_K_TEXTSTART || key_u == STB_TEXTEDIT_K_BACKSPACE || key_u == STB_TEXTEDIT_K_WORDLEFT) + LastMoveDirectionLR = ImGuiDir_Left; + else if (key_u == STB_TEXTEDIT_K_RIGHT || key_u == STB_TEXTEDIT_K_LINEEND || key_u == STB_TEXTEDIT_K_TEXTEND || key_u == STB_TEXTEDIT_K_DELETE || key_u == STB_TEXTEDIT_K_WORDRIGHT) + LastMoveDirectionLR = ImGuiDir_Right; } void ImGuiInputTextState::OnCharPressed(unsigned int c) @@ -4479,6 +4503,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not not work with left-trimming + IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Password) == 0); // WordWrap does not work with Password mode. + IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Multiline) != 0); // WordWrap does not work in single-line mode. ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; @@ -4526,7 +4552,10 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges - bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoMove; + if (flags & ImGuiInputTextFlags_WordWrap) + window_flags |= ImGuiWindowFlags_AlwaysVerticalScrollbar; // FIXME-WORDWRAP: Makes things much simpler. Otherwise requires more work to track cursor reliably and avoid one-frame glitch. + bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, window_flags); g.NavActivateId = backup_activate_id; PopStyleVar(3); PopStyleColor(); @@ -4566,6 +4595,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0; const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0; + const bool is_wordwrap = (flags & ImGuiInputTextFlags_WordWrap) != 0; + const float wrap_width = is_wordwrap ? GetContentRegionAvail().x : 0.0f; if (is_resizable) IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag! @@ -4728,6 +4759,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ state->Edited = false; state->BufCapacity = buf_size; state->Flags = flags; + state->WrapWidth = wrap_width; // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. // Down the line we should have a cleaner library-wide concept of Selected vs Active. @@ -4765,9 +4797,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Triple-click: Select line const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor) == '\n'; + state->WrapWidth = 0.0f; // Temporarily disable wrapping so we use real line start. state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART); state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT); state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT); + state->WrapWidth = wrap_width; if (!is_eol && is_multiline) { ImSwap(state->Stb->select_start, state->Stb->select_end); @@ -5185,9 +5219,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); } - const ImRect clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.0f, 0.0f); + ImRect clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size + if (is_multiline) + clip_rect.ClipWith(draw_window->ClipRect); // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. @@ -5230,7 +5266,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. const char* text_begin = buf_display; const char* text_end = text_begin + state->TextLen; - ImVec2 cursor_offset, select_start_offset; + ImVec2 cursor_offset; + float select_start_offset_y = 0.0f; // Offset of beginning of non-wrapped line for selection. { // Find lines numbers straddling cursor and selection min position @@ -5238,12 +5275,16 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ int selmin_line_no = render_selection ? -1 : -1000; const char* cursor_ptr = render_cursor ? text_begin + state->Stb->cursor : NULL; const char* selmin_ptr = render_selection ? text_begin + ImMin(state->Stb->select_start, state->Stb->select_end) : NULL; + const char* cursor_line_start = NULL; + const char* selmin_line_start = NULL; + bool cursor_straddle_word_wrap = false; // Count lines and find line number for cursor and selection ends // FIXME: Switch to zero-based index to reduce confusion. int line_count = 1; if (is_multiline) { + if (!is_wordwrap) { for (const char* s = text_begin; (s = (const char*)ImMemchr(s, '\n', (size_t)(text_end - s))) != NULL; s++) { @@ -5252,24 +5293,54 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ line_count++; } } + else + { + bool is_start_of_non_wrapped_line = true; + int line_count_for_non_wrapped_line = 1; + for (const char* s = text_begin; s < text_end; s = (*s == '\n') ? s + 1 : s) + { + const char* s_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, s, text_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); + const char* s_prev = s; + s = s_eol; + if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_start = s_prev; cursor_line_no = line_count; } + if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_start = s_prev; selmin_line_no = line_count_for_non_wrapped_line; } + if (s == cursor_ptr && *cursor_ptr != '\n' && *cursor_ptr != 0) + cursor_straddle_word_wrap = true; + is_start_of_non_wrapped_line = (*s == '\n'); + line_count++; + if (is_start_of_non_wrapped_line) + line_count_for_non_wrapped_line = line_count; + } + } + //IMGUI_DEBUG_LOG("%d\n", selmin_line_no); } if (cursor_line_no == -1) cursor_line_no = line_count; + if (cursor_line_start == NULL) + cursor_line_start = ImStrbol(cursor_ptr, text_begin); if (selmin_line_no == -1) selmin_line_no = line_count; + if (selmin_line_start == NULL) + selmin_line_start = ImStrbol(cursor_ptr, text_begin); // Calculate 2d position by finding the beginning of the line and measuring distance - cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(cursor_ptr, text_begin), cursor_ptr, cursor_ptr, NULL, NULL, ImDrawTextFlags_WrapKeepTrailingBlanks).x; - cursor_offset.y = cursor_line_no * g.FontSize; - if (selmin_line_no >= 0) + if (render_cursor) { - select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(selmin_ptr, text_begin), selmin_ptr, selmin_ptr, NULL, NULL, ImDrawTextFlags_WrapKeepTrailingBlanks).x; - select_start_offset.y = selmin_line_no * g.FontSize; + cursor_offset.x = InputTextCalcTextSize(&g, cursor_line_start, cursor_ptr, text_end, NULL, NULL, ImDrawTextFlags_WrapKeepBlanks).x; + cursor_offset.y = cursor_line_no * g.FontSize; + if (is_multiline && cursor_straddle_word_wrap && state->LastMoveDirectionLR == ImGuiDir_Left) + cursor_offset = ImVec2(0.0f, cursor_offset.y + g.FontSize); } + if (selmin_line_no >= 0) + select_start_offset_y = selmin_line_no * g.FontSize; // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) if (is_multiline) + { + if (is_wordwrap && text_end > text_begin && text_end[-1] != '\n') + line_count--; text_size = ImVec2(inner_size.x, line_count * g.FontSize); + } state->LineCount = line_count; } @@ -5318,28 +5389,33 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. float bg_offy_dn = is_multiline ? 0.0f : 2.0f; - ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll; - for (const char* p = text_selected_begin; p < text_selected_end; ) + float bg_min_width = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines + ImVec2 rect_pos = draw_pos - draw_scroll; + rect_pos.y += select_start_offset_y; + for (const char* p = ImStrbol(text_selected_begin, text_begin); p < text_selected_end; rect_pos.y += g.FontSize) { if (rect_pos.y > clip_rect.Max.y + g.FontSize) break; - if (rect_pos.y < clip_rect.Min.y) + const char* p_eol = is_wordwrap ? ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks) : (const char*)ImMemchr((void*)p, '\n', text_selected_end - p); + if (p_eol == NULL) + p_eol = text_selected_end; + const char* p_next = is_wordwrap ? (*p_eol == '\n' ? p_eol + 1 : p_eol) : (p_eol + 1); + if (rect_pos.y >= clip_rect.Min.y) { - p = (const char*)ImMemchr((void*)p, '\n', text_selected_end - p); - p = p ? p + 1 : text_selected_end; + const char* line_selected_begin = (text_selected_begin > p) ? text_selected_begin : p; + const char* line_selected_end = (text_selected_end < p_eol) ? text_selected_end : p_eol; + if ((*p_eol == '\n' && text_selected_begin <= p_eol) || (text_selected_begin < p_eol)) + { + ImVec2 rect_offset = CalcTextSize(p, line_selected_begin); + ImVec2 rect_size = CalcTextSize(line_selected_begin, line_selected_end); + rect_size.x = ImMax(rect_size.x, bg_min_width); // So we can see selected empty lines + ImRect rect(rect_pos + ImVec2(rect_offset.x, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_offset.x + rect_size.x, bg_offy_dn)); + rect.ClipWith(clip_rect); + if (rect.Overlaps(clip_rect)) + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); + } } - else - { - ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, text_selected_end, &p, NULL, ImDrawTextFlags_StopOnNewLine); - if (rect_size.x <= 0.0f) - rect_size.x = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines - ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn)); - rect.ClipWith(clip_rect); - if (rect.Overlaps(clip_rect)) - draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); - rect_pos.x = draw_pos.x - draw_scroll.x; - } - rect_pos.y += g.FontSize; + p = p_next; } } @@ -5348,7 +5424,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) { ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect.AsVec4()); + if (col & IM_COL32_A_MASK) + g.Font->RenderText(draw_window->DrawList, g.FontSize, draw_pos - draw_scroll, col, clip_rect.AsVec4(), buf_display, buf_display_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); + //draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, wrap_width, is_multiline ? NULL : &clip_rect.AsVec4()); } // Draw blinking cursor @@ -5379,7 +5457,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Render text only (no selection, no cursor) if (is_multiline) - text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(&g, buf_display, &buf_display_end) * g.FontSize); // We don't need width + text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(&g, buf_display, &buf_display_end, wrap_width) * g.FontSize); // We don't need width else if (!is_displaying_hint && g.ActiveId == id) buf_display_end = buf_display + state->TextLen; else if (!is_displaying_hint) @@ -5393,7 +5471,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const ImVec2 draw_scroll = /*state ? ImVec2(state->Scroll.x, 0.0f) :*/ ImVec2(0.0f, 0.0f); // Preserve scroll when inactive? ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect.AsVec4()); + if (col & IM_COL32_A_MASK) + g.Font->RenderText(draw_window->DrawList, g.FontSize, draw_pos - draw_scroll, col, clip_rect.AsVec4(), buf_display, buf_display_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); + //draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, wrap_width, is_multiline ? NULL : &clip_rect.AsVec4()); } } @@ -5449,8 +5529,10 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state) ImStb::StbUndoState* undo_state = &stb_state->undostate; Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId); DebugLocateItemOnHover(state->ID); - Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->TextLen, stb_state->cursor, stb_state->select_start, stb_state->select_end); - Text("BufCapacity: %d", state->BufCapacity); + Text("TextLen: %d, Cursor: %d%s, Selection: %d..%d", state->TextLen, stb_state->cursor, + (state->Flags & ImGuiInputTextFlags_WordWrap) ? (state->LastMoveDirectionLR == ImGuiDir_Left ? " (L)" : " (R)") : "", + stb_state->select_start, stb_state->select_end); + Text("BufCapacity: %d, LineCount: %d", state->BufCapacity, state->LineCount); Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity); Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x); Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point); diff --git a/imstb_textedit.h b/imstb_textedit.h index 605e44adb..c4f5cd64f 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -572,6 +572,8 @@ static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING STB_TEXTEDIT_LAYOUTROW(&r, str, i); if (n < i + r.num_chars) break; + if (str->LastMoveDirectionLR == ImGuiDir_Right && 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; @@ -972,6 +974,8 @@ retry: } stb_textedit_clamp(str, state); + if (state->cursor == find.first_char + find.length) + str->LastMoveDirectionLR = ImGuiDir_Left; state->has_preferred_x = 1; state->preferred_x = goal_x; @@ -1036,6 +1040,10 @@ retry: } stb_textedit_clamp(str, state); + if (state->cursor == find.first_char) + str->LastMoveDirectionLR = ImGuiDir_Right; + else if (state->cursor == find.prev_first) + str->LastMoveDirectionLR = ImGuiDir_Left; state->has_preferred_x = 1; state->preferred_x = goal_x; From 985723ed94c64934740215075df7a50500bbe568 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 28 Aug 2025 19:37:52 +0200 Subject: [PATCH 1300/2359] InputText: Word-Wrap: mouse clicks on word-wrapping points set cursor side correctly. (#3237, #952, #1062, #7363) --- imstb_textedit.h | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/imstb_textedit.h b/imstb_textedit.h index c4f5cd64f..49c8933e2 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -427,7 +427,7 @@ typedef struct // // traverse the layout to locate the nearest character to a display position -static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y) +static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y, int* out_side_on_line) { StbTexteditRow r; int n = STB_TEXTEDIT_STRINGLEN(str); @@ -437,6 +437,7 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y) r.x0 = r.x1 = 0; r.ymin = r.ymax = 0; r.num_chars = 0; + *out_side_on_line = 0; // search rows to find one that straddles 'y' while (i < n) { @@ -456,7 +457,10 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y) // below all text, return 'after' last character if (i >= n) + { + *out_side_on_line = 1; return n; + } // check if it's before the beginning of the line if (x < r.x0) @@ -469,6 +473,7 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y) for (k=0; k < r.num_chars; k = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k) - i) { float w = STB_TEXTEDIT_GETWIDTH(str, i, k); if (x < prev_x+w) { + *out_side_on_line = (k == 0) ? 0 : 1; if (x < prev_x+w/2) return k+i; else @@ -480,6 +485,7 @@ static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y) } // if the last character is a newline, return that. otherwise return 'after' the last character + *out_side_on_line = 1; if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) return i+r.num_chars-1; else @@ -491,6 +497,7 @@ static void stb_textedit_click(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *st { // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse // goes off the top or bottom of the text + int side_on_line; if( state->single_line ) { StbTexteditRow r; @@ -498,16 +505,18 @@ static void stb_textedit_click(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *st y = r.ymin; } - state->cursor = stb_text_locate_coord(str, x, y); + state->cursor = stb_text_locate_coord(str, x, y, &side_on_line); state->select_start = state->cursor; state->select_end = state->cursor; state->has_preferred_x = 0; + str->LastMoveDirectionLR = (ImS8)(side_on_line ? ImGuiDir_Right : ImGuiDir_Left); } // API drag: on mouse drag, move the cursor and selection endpoint to the clicked location static void stb_textedit_drag(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) { int p = 0; + int side_on_line; // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse // goes off the top or bottom of the text @@ -521,8 +530,9 @@ static void stb_textedit_drag(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *sta if (state->select_start == state->select_end) state->select_start = state->cursor; - p = stb_text_locate_coord(str, x, y); + p = stb_text_locate_coord(str, x, y, &side_on_line); state->cursor = state->select_end = p; + str->LastMoveDirectionLR = (ImS8)(side_on_line ? ImGuiDir_Right : ImGuiDir_Left); } ///////////////////////////////////////////////////////////////////////////// From 16415aa39f50c7ea2015dba65058024328b47a8c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 29 Aug 2025 18:18:18 +0200 Subject: [PATCH 1301/2359] InputText: Word-Wrap: added custom implementation for Home/End that is word-wrap friendly. (#3237, #952, #1062, #7363) --- imgui_widgets.cpp | 69 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 17ac3c1db..35dec8113 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4101,6 +4101,75 @@ static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx) #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL +// Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping. +static int STB_TEXTEDIT_MOVELINESTART_IMPL(ImGuiInputTextState* obj, ImStb::STB_TexteditState* state, int cursor) +{ + if (state->single_line) + return 0; + + if (obj->WrapWidth > 0.0f) + { + ImGuiContext& g = *obj->Ctx; + const char* p_cursor = obj->TextSrc + cursor; + const char* p_bol = ImStrbol(p_cursor, obj->TextSrc); + const char* p = p_bol; + const char* text_end = obj->TextSrc + obj->TextLen; // End of line would be enough + while (p >= p_bol) + { + const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks); + if (p == p_cursor) // If we are already on a visible beginning-of-line, return real beginning-of-line (would be same as regular handler below) + return (int)(p_bol - obj->TextSrc); + if (p_eol == p_cursor && obj->TextA[cursor] != '\n' && obj->LastMoveDirectionLR == ImGuiDir_Left) + return (int)(p_bol - obj->TextSrc); + if (p_eol >= p_cursor) + return (int)(p - obj->TextSrc); + p = (*p_eol == '\n') ? p_eol + 1 : p_eol; + } + } + + // Regular handler, same as stb_textedit_move_line_start() + while (cursor > 0) + { + int prev_cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, cursor); + if (STB_TEXTEDIT_GETCHAR(obj, prev_cursor) == STB_TEXTEDIT_NEWLINE) + break; + cursor = prev_cursor; + } + return cursor; +} + +static int STB_TEXTEDIT_MOVELINEEND_IMPL(ImGuiInputTextState* obj, ImStb::STB_TexteditState* state, int cursor) +{ + int n = STB_TEXTEDIT_STRINGLEN(obj); + if (state->single_line) + return n; + + if (obj->WrapWidth > 0.0f) + { + ImGuiContext& g = *obj->Ctx; + const char* p_cursor = obj->TextSrc + cursor; + const char* p = ImStrbol(p_cursor, obj->TextSrc); + const char* text_end = obj->TextSrc + obj->TextLen; // End of line would be enough + while (p < text_end) + { + const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks); + cursor = (int)(p_eol - obj->TextSrc); + if (p_eol == p_cursor && obj->LastMoveDirectionLR != ImGuiDir_Left) // If we are already on a visible end-of-line, switch to regular handle + break; + if (p_eol > p_cursor) + return cursor; + p = (*p_eol == '\n') ? p_eol + 1 : p_eol; + } + } + // Regular handler, same as stb_textedit_move_line_end() + while (cursor < n && STB_TEXTEDIT_GETCHAR(obj, cursor) != STB_TEXTEDIT_NEWLINE) + cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, cursor); + return cursor; +} + +#define STB_TEXTEDIT_MOVELINESTART STB_TEXTEDIT_MOVELINESTART_IMPL +#define STB_TEXTEDIT_MOVELINEEND STB_TEXTEDIT_MOVELINEEND_IMPL + static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n) { // Offset remaining text (+ copy zero terminator) From 230418a75d56ddb5ba51e0b196332b94d74867f2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Sep 2025 15:37:27 +0200 Subject: [PATCH 1302/2359] InputText: Word-Wrap: attempt to track cursor while resizing frame/parent. (#3237, #952, #1062, #7363) --- imgui_internal.h | 1 + imgui_widgets.cpp | 33 ++++++++++++++++++++++++++------- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index faeef64e0..901c61f06 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1247,6 +1247,7 @@ struct IMGUI_API ImGuiInputTextState float WrapWidth; // word-wrapping width float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) + bool CursorCenterY; // set when we want scrolling to be centered over the cursor position (while resizing a word-wrapping field) bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection bool Edited; // edited this frame bool WantReloadUserBuf; // force a reload of user buf so it may be modified externally. may be automatic in future version. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 35dec8113..4c4ef5dff 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4821,6 +4821,15 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_password && !is_displaying_hint) PushPasswordFont(); + // Word-wrapping: attempt to keep cursor in view while resizing frame/parent + // FIXME-WORDWRAP: It would be better to preserve same relative offset. + if (is_wordwrap && state != NULL && state->ID == id && state->WrapWidth != wrap_width) + { + state->CursorCenterY = true; + state->WrapWidth = wrap_width; + render_cursor = true; + } + // Process mouse inputs and character inputs if (g.ActiveId == id) { @@ -5414,6 +5423,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } // Scroll + float new_scroll_y = scroll_y; if (render_cursor && state->CursorFollow) { // Horizontal scroll in chunks of quarter width @@ -5436,17 +5446,26 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Test if cursor is vertically visible if (cursor_offset.y - g.FontSize < scroll_y) - scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + new_scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y) - scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f; - const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); - scroll_y = ImClamp(scroll_y, 0.0f, scroll_max_y); - draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag - draw_window->Scroll.y = scroll_y; + new_scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f; } - state->CursorFollow = false; } + if (state->CursorCenterY) + { + if (is_multiline) + new_scroll_y = cursor_offset.y - g.FontSize - (inner_size.y * 0.5f - style.FramePadding.y); + state->CursorCenterY = false; + render_cursor = false; + } + if (new_scroll_y != scroll_y) + { + const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); + scroll_y = ImClamp(new_scroll_y, 0.0f, scroll_max_y); + draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag + draw_window->Scroll.y = scroll_y; + } // Draw selection const ImVec2 draw_scroll = ImVec2(state->Scroll.x, 0.0f); From ea8a5a9e1717db57ed426ae9934a939cdcde7aa3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Sep 2025 15:20:18 +0200 Subject: [PATCH 1303/2359] DrawList: made AddCallback() assert when passing a null callback. --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 836c57a5f..1ec9ff645 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,7 @@ Other Changes: unmoved. We revert back to move to the end of line in this situation. - DrawList: fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) +- DrawList: made AddCallback() assert when passing a null callback. - Debug Tools: ID Stack Tool: fixed using fixed-size buffers preventing long identifiers from being displayed in the tool. (#8905, #4631) - Debug Tools: ID Stack Tool: when ### is used, uncontributing prefix before the ### diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 9f2867859..9b01047f0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -518,6 +518,7 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* userdata, size_t use { IM_ASSERT_PARANOID(CmdBuffer.Size > 0); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + IM_ASSERT(callback != NULL); IM_ASSERT(curr_cmd->UserCallback == NULL); if (curr_cmd->ElemCount != 0) { From 14e076c5bb3c2d6898eb483ddece7014c6292ccd Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Sep 2025 15:56:42 +0200 Subject: [PATCH 1304/2359] Backends: Internal renaming of samplers. --- backends/imgui_impl_dx10.cpp | 10 +++++----- backends/imgui_impl_dx11.cpp | 12 ++++++------ backends/imgui_impl_dx12.cpp | 31 +++++++++++++++---------------- backends/imgui_impl_sdlgpu3.cpp | 20 ++++++++++---------- backends/imgui_impl_vulkan.cpp | 10 +++++----- 5 files changed, 41 insertions(+), 42 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 3781a0974..5515f780c 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -73,7 +73,7 @@ struct ImGui_ImplDX10_Data ID3D10InputLayout* pInputLayout; ID3D10Buffer* pVertexConstantBuffer; ID3D10PixelShader* pPixelShader; - ID3D10SamplerState* pFontSampler; + ID3D10SamplerState* pTexSamplerLinear; ID3D10RasterizerState* pRasterizerState; ID3D10BlendState* pBlendState; ID3D10DepthStencilState* pDepthStencilState; @@ -140,7 +140,7 @@ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device->VSSetShader(bd->pVertexShader); device->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer); device->PSSetShader(bd->pPixelShader); - device->PSSetSamplers(0, 1, &bd->pFontSampler); + device->PSSetSamplers(0, 1, &bd->pTexSamplerLinear); device->GSSetShader(nullptr); // Setup render state @@ -257,7 +257,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplDX10_RenderState render_state; render_state.Device = bd->pd3dDevice; - render_state.SamplerDefault = bd->pFontSampler; + render_state.SamplerDefault = bd->pTexSamplerLinear; render_state.VertexConstantBuffer = bd->pVertexConstantBuffer; platform_io.Renderer_RenderState = &render_state; @@ -563,7 +563,7 @@ bool ImGui_ImplDX10_CreateDeviceObjects() desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; - bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler); + bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerLinear); } return true; @@ -579,7 +579,7 @@ void ImGui_ImplDX10_InvalidateDeviceObjects() for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) if (tex->RefCount == 1) ImGui_ImplDX10_DestroyTexture(tex); - if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } + if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index 08bf7998f..c71e44d06 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -76,7 +76,7 @@ struct ImGui_ImplDX11_Data ID3D11InputLayout* pInputLayout; ID3D11Buffer* pVertexConstantBuffer; ID3D11PixelShader* pPixelShader; - ID3D11SamplerState* pFontSampler; + ID3D11SamplerState* pTexSamplerLinear; ID3D11RasterizerState* pRasterizerState; ID3D11BlendState* pBlendState; ID3D11DepthStencilState* pDepthStencilState; @@ -99,7 +99,7 @@ static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData() } // Functions -static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* device_ctx) +static void ImGui_ImplDX11_SetupRenderState(const ImDrawData* draw_data, ID3D11DeviceContext* device_ctx) { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); @@ -143,7 +143,7 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC device_ctx->VSSetShader(bd->pVertexShader, nullptr, 0); device_ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer); device_ctx->PSSetShader(bd->pPixelShader, nullptr, 0); - device_ctx->PSSetSamplers(0, 1, &bd->pFontSampler); + device_ctx->PSSetSamplers(0, 1, &bd->pTexSamplerLinear); device_ctx->GSSetShader(nullptr, nullptr, 0); device_ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. device_ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. @@ -271,7 +271,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX11_RenderState render_state; render_state.Device = bd->pd3dDevice; render_state.DeviceContext = bd->pd3dDeviceContext; - render_state.SamplerDefault = bd->pFontSampler; + render_state.SamplerDefault = bd->pTexSamplerLinear; render_state.VertexConstantBuffer = bd->pVertexConstantBuffer; platform_io.Renderer_RenderState = &render_state; @@ -578,7 +578,7 @@ bool ImGui_ImplDX11_CreateDeviceObjects() desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; - bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler); + bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerLinear); } return true; @@ -595,7 +595,7 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() if (tex->RefCount == 1) ImGui_ImplDX11_DestroyTexture(tex); - if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } + if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 2932855ed..c84c21971 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -99,7 +99,6 @@ struct ImGui_ImplDX12_Data ImGui_ImplDX12_RenderBuffers* pFrameResources; UINT frameIndex; - ImGui_ImplDX12_Texture FontTexture; bool LegacySingleDescriptorUsed; ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; } @@ -578,26 +577,26 @@ bool ImGui_ImplDX12_CreateDeviceObjects() param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. - D3D12_STATIC_SAMPLER_DESC staticSampler = {}; - staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; - staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; - staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; - staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; - staticSampler.MipLODBias = 0.f; - staticSampler.MaxAnisotropy = 0; - staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; - staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; - staticSampler.MinLOD = 0.f; - staticSampler.MaxLOD = D3D12_FLOAT32_MAX; - staticSampler.ShaderRegister = 0; - staticSampler.RegisterSpace = 0; - staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + D3D12_STATIC_SAMPLER_DESC staticSampler[1] = {}; + staticSampler[0].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + staticSampler[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + staticSampler[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + staticSampler[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + staticSampler[0].MipLODBias = 0.f; + staticSampler[0].MaxAnisotropy = 0; + staticSampler[0].ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; + staticSampler[0].BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; + staticSampler[0].MinLOD = 0.f; + staticSampler[0].MaxLOD = D3D12_FLOAT32_MAX; + staticSampler[0].ShaderRegister = 0; + staticSampler[0].RegisterSpace = 0; + staticSampler[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; D3D12_ROOT_SIGNATURE_DESC desc = {}; desc.NumParameters = _countof(param); desc.pParameters = param; desc.NumStaticSamplers = 1; - desc.pStaticSamplers = &staticSampler; + desc.pStaticSamplers = &staticSampler[0]; desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 3b6db79e8..0f8d5fa1a 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -59,7 +59,7 @@ struct ImGui_ImplSDLGPU3_Data SDL_GPUShader* VertexShader = nullptr; SDL_GPUShader* FragmentShader = nullptr; SDL_GPUGraphicsPipeline* Pipeline = nullptr; - SDL_GPUSampler* TexSampler = nullptr; + SDL_GPUSampler* TexSamplerLinear = nullptr; SDL_GPUTransferBuffer* TexTransferBuffer = nullptr; uint32_t TexTransferBufferSize = 0; @@ -85,7 +85,7 @@ static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData() static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, ImGui_ImplSDLGPU3_RenderState* render_state, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height) { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - render_state->SamplerCurrent = bd->TexSampler; + render_state->SamplerCurrent = bd->TexSamplerLinear; // Bind graphics pipeline SDL_BindGPUGraphicsPipeline(render_pass, pipeline); @@ -234,7 +234,7 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplSDLGPU3_RenderState render_state; render_state.Device = bd->InitInfo.Device; - render_state.SamplerDefault = render_state.SamplerCurrent = bd->TexSampler; + render_state.SamplerDefault = render_state.SamplerCurrent = bd->TexSamplerLinear; platform_io.Renderer_RenderState = &render_state; ImGui_ImplSDLGPU3_SetupRenderState(draw_data, &render_state, pipeline, command_buffer, render_pass, fd, fb_width, fb_height); @@ -339,7 +339,7 @@ void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1; SDL_GPUTexture* raw_tex = SDL_CreateGPUTexture(v->Device, &texture_info); - IM_ASSERT(raw_tex != nullptr && "Failed to create font texture, call SDL_GetError() for more info"); + IM_ASSERT(raw_tex != nullptr && "Failed to create texture, call SDL_GetError() for more info"); // Store identifiers tex->SetTexID((ImTextureID)(intptr_t)raw_tex); @@ -369,7 +369,7 @@ void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex) transferbuffer_info.size = upload_size + 1024; bd->TexTransferBufferSize = upload_size + 1024; bd->TexTransferBuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info); - IM_ASSERT(bd->TexTransferBuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information"); + IM_ASSERT(bd->TexTransferBuffer != nullptr && "Failed to create transfer buffer, call SDL_GetError() for more information"); } // Copy to transfer buffer @@ -558,7 +558,7 @@ void ImGui_ImplSDLGPU3_CreateDeviceObjects() ImGui_ImplSDLGPU3_DestroyDeviceObjects(); - if (bd->TexSampler == nullptr) + if (bd->TexSamplerLinear == nullptr) { // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. SDL_GPUSamplerCreateInfo sampler_info = {}; @@ -575,8 +575,8 @@ void ImGui_ImplSDLGPU3_CreateDeviceObjects() sampler_info.max_anisotropy = 1.0f; sampler_info.enable_compare = false; - bd->TexSampler = SDL_CreateGPUSampler(v->Device, &sampler_info); - IM_ASSERT(bd->TexSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information"); + bd->TexSamplerLinear = SDL_CreateGPUSampler(v->Device, &sampler_info); + IM_ASSERT(bd->TexSamplerLinear != nullptr && "Failed to create sampler, call SDL_GetError() for more information"); } ImGui_ImplSDLGPU3_CreateGraphicsPipeline(); @@ -611,7 +611,7 @@ void ImGui_ImplSDLGPU3_DestroyDeviceObjects() if (bd->TexTransferBuffer) { SDL_ReleaseGPUTransferBuffer(v->Device, bd->TexTransferBuffer); bd->TexTransferBuffer = nullptr; } if (bd->VertexShader) { SDL_ReleaseGPUShader(v->Device, bd->VertexShader); bd->VertexShader = nullptr; } if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->Device, bd->FragmentShader); bd->FragmentShader = nullptr; } - if (bd->TexSampler) { SDL_ReleaseGPUSampler(v->Device, bd->TexSampler); bd->TexSampler = nullptr; } + if (bd->TexSamplerLinear) { SDL_ReleaseGPUSampler(v->Device, bd->TexSamplerLinear); bd->TexSamplerLinear = nullptr; } if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->Device, bd->Pipeline); bd->Pipeline = nullptr; } } @@ -654,7 +654,7 @@ void ImGui_ImplSDLGPU3_NewFrame() ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLGPU3_Init()?"); - if (!bd->TexSampler) + if (!bd->TexSamplerLinear) ImGui_ImplSDLGPU3_CreateDeviceObjects(); } diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index aa8d3092c..e56902254 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -260,7 +260,7 @@ struct ImGui_ImplVulkan_Data ImVector PipelineRenderingCreateInfoColorAttachmentFormats; // Deep copy of format array // Texture management - VkSampler TexSampler; + VkSampler TexSamplerLinear; VkCommandPool TexCommandPool; VkCommandBuffer TexCommandBuffer; @@ -737,7 +737,7 @@ void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) } // Create the Descriptor Set - backend_tex->DescriptorSet = ImGui_ImplVulkan_AddTexture(bd->TexSampler, backend_tex->ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + backend_tex->DescriptorSet = ImGui_ImplVulkan_AddTexture(bd->TexSamplerLinear, backend_tex->ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // Store identifiers tex->SetTexID((ImTextureID)backend_tex->DescriptorSet); @@ -1037,7 +1037,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; VkResult err; - if (!bd->TexSampler) + if (!bd->TexSamplerLinear) { // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. VkSamplerCreateInfo info = {}; @@ -1051,7 +1051,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() info.minLod = -1000; info.maxLod = 1000; info.maxAnisotropy = 1.0f; - err = vkCreateSampler(v->Device, &info, v->Allocator, &bd->TexSampler); + err = vkCreateSampler(v->Device, &info, v->Allocator, &bd->TexSamplerLinear); check_vk_result(err); } @@ -1188,7 +1188,7 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() if (bd->TexCommandBuffer) { vkFreeCommandBuffers(v->Device, bd->TexCommandPool, 1, &bd->TexCommandBuffer); bd->TexCommandBuffer = VK_NULL_HANDLE; } if (bd->TexCommandPool) { vkDestroyCommandPool(v->Device, bd->TexCommandPool, v->Allocator); bd->TexCommandPool = VK_NULL_HANDLE; } - if (bd->TexSampler) { vkDestroySampler(v->Device, bd->TexSampler, v->Allocator); bd->TexSampler = VK_NULL_HANDLE; } + if (bd->TexSamplerLinear) { vkDestroySampler(v->Device, bd->TexSamplerLinear, v->Allocator); bd->TexSamplerLinear = VK_NULL_HANDLE; } if (bd->ShaderModuleVert) { vkDestroyShaderModule(v->Device, bd->ShaderModuleVert, v->Allocator); bd->ShaderModuleVert = VK_NULL_HANDLE; } if (bd->ShaderModuleFrag) { vkDestroyShaderModule(v->Device, bd->ShaderModuleFrag, v->Allocator); bd->ShaderModuleFrag = VK_NULL_HANDLE; } if (bd->DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; } From bf52f4a83c556a2a3cf431c20ace5ca1b1aee514 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Sep 2025 17:03:23 +0200 Subject: [PATCH 1305/2359] Backends: OpenGL3: added HasBindSampler storage for readability and consistency. --- backends/imgui_impl_opengl3.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 607d24371..5ab43a406 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -246,6 +246,7 @@ struct ImGui_ImplOpenGL3_Data GLsizeiptr VertexBufferSize; GLsizeiptr IndexBufferSize; bool HasPolygonMode; + bool HasBindSampler; bool HasClipOrigin; bool UseBufferSubData; ImVector TempBuffer; @@ -396,6 +397,9 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) // Detect extensions we support #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE bd->HasPolygonMode = (!bd->GlProfileIsES2 && !bd->GlProfileIsES3); +#endif +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER + bd->HasBindSampler = (bd->GlVersion >= 330 || bd->GlProfileIsES3); #endif bd->HasClipOrigin = (bd->GlVersion >= 450); #ifdef IMGUI_IMPL_OPENGL_HAS_EXTENSIONS @@ -495,7 +499,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER - if (bd->GlVersion >= 330 || bd->GlProfileIsES3) + if (bd->HasBindSampler) glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise. #endif @@ -543,7 +547,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER - GLuint last_sampler; if (bd->GlVersion >= 330 || bd->GlProfileIsES3) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; } + GLuint last_sampler; if (bd->HasBindSampler) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; } #endif GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY @@ -668,7 +672,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (last_program == 0 || glIsProgram(last_program)) glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER - if (bd->GlVersion >= 330 || bd->GlProfileIsES3) + if (bd->HasBindSampler) glBindSampler(0, last_sampler); #endif glActiveTexture(last_active_texture); From 2841c5135d6bb77bc23be4253ec2c6dfd86facbd Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Sep 2025 16:56:37 +0200 Subject: [PATCH 1306/2359] Backends: OpenGL3: add GL_NEAREST and samplers functions in loader. --- backends/imgui_impl_opengl3_loader.h | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index c3f5a93f5..a69ac89d7 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -180,6 +180,7 @@ typedef khronos_uint8_t GLubyte; #define GL_RENDERER 0x1F01 #define GL_VERSION 0x1F02 #define GL_EXTENSIONS 0x1F03 +#define GL_NEAREST 0x2600 #define GL_LINEAR 0x2601 #define GL_TEXTURE_MAG_FILTER 0x2800 #define GL_TEXTURE_MIN_FILTER 0x2801 @@ -400,9 +401,15 @@ GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum #ifndef GL_VERSION_3_3 #define GL_VERSION_3_3 1 #define GL_SAMPLER_BINDING 0x8919 +typedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers); +typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers); typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param); #ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers); +GLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers); GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler); +GLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param); #endif #endif /* GL_VERSION_3_3 */ #ifndef GL_VERSION_4_1 @@ -483,7 +490,7 @@ GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc); /* gl3w internal state */ union ImGL3WProcs { - GL3WglProc ptr[60]; + GL3WglProc ptr[63]; struct { PFNGLACTIVETEXTUREPROC ActiveTexture; PFNGLATTACHSHADERPROC AttachShader; @@ -503,6 +510,7 @@ union ImGL3WProcs { PFNGLCREATESHADERPROC CreateShader; PFNGLDELETEBUFFERSPROC DeleteBuffers; PFNGLDELETEPROGRAMPROC DeleteProgram; + PFNGLDELETESAMPLERSPROC DeleteSamplers; PFNGLDELETESHADERPROC DeleteShader; PFNGLDELETETEXTURESPROC DeleteTextures; PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays; @@ -515,6 +523,7 @@ union ImGL3WProcs { PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray; PFNGLFLUSHPROC Flush; PFNGLGENBUFFERSPROC GenBuffers; + PFNGLGENSAMPLERSPROC GenSamplers; PFNGLGENTEXTURESPROC GenTextures; PFNGLGENVERTEXARRAYSPROC GenVertexArrays; PFNGLGETATTRIBLOCATIONPROC GetAttribLocation; @@ -535,6 +544,7 @@ union ImGL3WProcs { PFNGLPIXELSTOREIPROC PixelStorei; PFNGLPOLYGONMODEPROC PolygonMode; PFNGLREADPIXELSPROC ReadPixels; + PFNGLSAMPLERPARAMETERIPROC SamplerParameteri; PFNGLSCISSORPROC Scissor; PFNGLSHADERSOURCEPROC ShaderSource; PFNGLTEXIMAGE2DPROC TexImage2D; @@ -569,6 +579,7 @@ GL3W_API extern union ImGL3WProcs imgl3wProcs; #define glCreateShader imgl3wProcs.gl.CreateShader #define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers #define glDeleteProgram imgl3wProcs.gl.DeleteProgram +#define glDeleteSamplers imgl3wProcs.gl.DeleteSamplers #define glDeleteShader imgl3wProcs.gl.DeleteShader #define glDeleteTextures imgl3wProcs.gl.DeleteTextures #define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays @@ -581,6 +592,7 @@ GL3W_API extern union ImGL3WProcs imgl3wProcs; #define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray #define glFlush imgl3wProcs.gl.Flush #define glGenBuffers imgl3wProcs.gl.GenBuffers +#define glGenSamplers imgl3wProcs.gl.GenSamplers #define glGenTextures imgl3wProcs.gl.GenTextures #define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays #define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation @@ -601,6 +613,7 @@ GL3W_API extern union ImGL3WProcs imgl3wProcs; #define glPixelStorei imgl3wProcs.gl.PixelStorei #define glPolygonMode imgl3wProcs.gl.PolygonMode #define glReadPixels imgl3wProcs.gl.ReadPixels +#define glSamplerParameteri imgl3wProcs.gl.SamplerParameteri #define glScissor imgl3wProcs.gl.Scissor #define glShaderSource imgl3wProcs.gl.ShaderSource #define glTexImage2D imgl3wProcs.gl.TexImage2D @@ -870,6 +883,7 @@ static const char *proc_names[] = { "glCreateShader", "glDeleteBuffers", "glDeleteProgram", + "glDeleteSamplers", "glDeleteShader", "glDeleteTextures", "glDeleteVertexArrays", @@ -882,6 +896,7 @@ static const char *proc_names[] = { "glEnableVertexAttribArray", "glFlush", "glGenBuffers", + "glGenSamplers", "glGenTextures", "glGenVertexArrays", "glGetAttribLocation", @@ -902,6 +917,7 @@ static const char *proc_names[] = { "glPixelStorei", "glPolygonMode", "glReadPixels", + "glSamplerParameteri", "glScissor", "glShaderSource", "glTexImage2D", From e66afbbbe0c96ab47aee40098727e693a05cd931 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 9 Sep 2025 17:18:26 +0200 Subject: [PATCH 1307/2359] Selectable: ImGuiSelectableFlags_SelectOnNav doesn't close popups. --- imgui_widgets.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4c4ef5dff..a0e1af4ac 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7348,6 +7348,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + bool auto_selected = false; // Multi-selection support (footer) if (is_multi_select) @@ -7365,7 +7366,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API. if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId) if (g.NavJustMovedToId == id) - selected = pressed = true; + selected = pressed = auto_selected = true; } // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad @@ -7416,8 +7417,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb); // Automatically close popups - if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups)) - CloseCurrentPopup(); + if (pressed && !auto_selected && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups)) + if (!(flags & ImGuiSelectableFlags_SelectOnNav) || g.NavJustMovedToId != id) + CloseCurrentPopup(); if (disabled_item && !disabled_global) EndDisabled(); From 8e4955bb23a07549e025e52e5ad618daa12f8555 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 9 Sep 2025 17:37:20 +0200 Subject: [PATCH 1308/2359] Selectable: moved ImGuiSelectableFlags_SelectOnNav to public API. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui.h | 1 + imgui_demo.cpp | 3 +-- imgui_internal.h | 1 - 5 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1ec9ff645..34a16a3f8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,8 @@ Other Changes: - InputText: revert a change in 1.79 where pressing Down or PageDown on the last line of a multi-line buffer without a trailing carriage return would keep the cursor unmoved. We revert back to move to the end of line in this situation. +- Selectable: added ImGuiSelectableFlags_SelectOnNav to auto-select an item when + moved into (automatic when in a BeginMultiSelect() block). - DrawList: fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) - DrawList: made AddCallback() assert when passing a null callback. diff --git a/imgui.cpp b/imgui.cpp index 466f7390d..744273e5d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15757,6 +15757,7 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImG // - DebugNodeWindowSettings() [Internal] // - DebugNodeWindowsList() [Internal] // - DebugNodeWindowsListByBeginStackParent() [Internal] +// - ShowFontSelector() //----------------------------------------------------------------------------- #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) diff --git a/imgui.h b/imgui.h index b45e585a8..a9aea86ed 100644 --- a/imgui.h +++ b/imgui.h @@ -1341,6 +1341,7 @@ enum ImGuiSelectableFlags_ ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text ImGuiSelectableFlags_AllowOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one ImGuiSelectableFlags_Highlight = 1 << 5, // Make the item be displayed as if it is hovered + ImGuiSelectableFlags_SelectOnNav = 1 << 6, // Auto-select when moved into. Automatic when in a BeginMultiSelect() block. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2a7b9ac39..6e0e1c5c4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -9288,10 +9288,9 @@ static void ShowExampleAppLayout(bool* p_open) ImGui::BeginChild("left pane", ImVec2(150, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX); for (int i = 0; i < 100; i++) { - // FIXME: Good candidate to use ImGuiSelectableFlags_SelectOnNav char label[128]; sprintf(label, "MyObject %d", i); - if (ImGui::Selectable(label, selected == i)) + if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SelectOnNav)) selected = i; } ImGui::EndChild(); diff --git a/imgui_internal.h b/imgui_internal.h index 901c61f06..0a5018bdf 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1075,7 +1075,6 @@ enum ImGuiSelectableFlagsPrivate_ { // NB: need to be in sync with last value of ImGuiSelectableFlags_ ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, - ImGuiSelectableFlags_SelectOnNav = 1 << 21, // (WIP) Auto-select when moved into. This is not exposed in public API as to handle multi-select and modifiers we will need user to explicitly control focus scope. May be replaced with a BeginSelection() API. ImGuiSelectableFlags_SelectOnClick = 1 << 22, // Override button behavior to react on Click (default is Click+Release) ImGuiSelectableFlags_SelectOnRelease = 1 << 23, // Override button behavior to react on Release (default is Click+Release) ImGuiSelectableFlags_SpanAvailWidth = 1 << 24, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) From 045645e5f160803004371128e8d83fd5ae102c80 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 9 Sep 2025 17:50:40 +0200 Subject: [PATCH 1309/2359] Demo: tweaked ShowFontSelector() and ShowStyleSelector() to update selection while navigating and to not close popup automatically. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- imgui_demo.cpp | 26 +++++++++++++++++--------- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 34a16a3f8..fe785c9fc 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,6 +80,8 @@ Other Changes: is now skipped. (#8904, #4631) - Debug Tools: ID Stack Tool: added option to hex-encode non-ASCII characters in output path. (#8904, #4631) +- Demo: tweaked ShowFontSelector() and ShowStyleSelector() to update selection + while navigating and to not close popup automatically. - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used diff --git a/imgui.cpp b/imgui.cpp index 744273e5d..c655c3146 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17873,7 +17873,7 @@ void ImGui::ShowFontSelector(const char* label) for (ImFont* font : io.Fonts->Fonts) { PushID((void*)font); - if (Selectable(font->GetDebugName(), font == font_current)) + if (Selectable(font->GetDebugName(), font == font_current, ImGuiSelectableFlags_SelectOnNav | ImGuiSelectableFlags_NoAutoClosePopups)) io.FontDefault = font; if (font == font_current) SetItemDefaultFocus(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6e0e1c5c4..8950e814e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8229,17 +8229,25 @@ void ImGui::ShowAboutWindow(bool* p_open) bool ImGui::ShowStyleSelector(const char* label) { static int style_idx = -1; - if (ImGui::Combo(label, &style_idx, "Dark\0Light\0Classic\0")) + const char* style_names[] = { "Dark", "Light", "Classic" }; + bool ret = false; + if (ImGui::BeginCombo(label, (style_idx >= 0 && style_idx < IM_ARRAYSIZE(style_names)) ? style_names[style_idx] : "")) { - switch (style_idx) - { - case 0: ImGui::StyleColorsDark(); break; - case 1: ImGui::StyleColorsLight(); break; - case 2: ImGui::StyleColorsClassic(); break; - } - return true; + for (int n = 0; n < IM_ARRAYSIZE(style_names); n++) + if (ImGui::Selectable(style_names[n], style_idx == n, ImGuiSelectableFlags_SelectOnNav | ImGuiSelectableFlags_NoAutoClosePopups)) + { + style_idx = n; + ret = true; + switch (style_idx) + { + case 0: ImGui::StyleColorsDark(); break; + case 1: ImGui::StyleColorsLight(); break; + case 2: ImGui::StyleColorsClassic(); break; + } + } + ImGui::EndCombo(); } - return false; + return ret; } static const char* GetTreeLinesFlagsName(ImGuiTreeNodeFlags flags) From 4e98fb20e2e0453f5e886e268877a4841eb3778d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Sep 2025 17:59:26 +0200 Subject: [PATCH 1310/2359] TabBar: Internals: added TabBarFindByID(), TabBarRemove() helpers. Currently only for the benefit of TestEngine. --- imgui_internal.h | 2 ++ imgui_tables.cpp | 2 +- imgui_widgets.cpp | 13 +++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 0a5018bdf..6b5b4ca25 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3522,6 +3522,8 @@ namespace ImGui // Tab Bars inline ImGuiTabBar* GetCurrentTabBar() { ImGuiContext& g = *GImGui; return g.CurrentTabBar; } + IMGUI_API ImGuiTabBar* TabBarFindByID(ImGuiID id); + IMGUI_API void TabBarRemove(ImGuiTabBar* tab_bar); IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id); IMGUI_API ImGuiTabItem* TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ba8f0034f..5b4e3e07d 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3943,7 +3943,7 @@ void ImGui::TableSettingsAddSettingsHandler() // - TableGcCompactSettings() [Internal] //------------------------------------------------------------------------- -// Remove Table (currently only used by TestEngine) +// Remove Table data (currently only used by TestEngine) void ImGui::TableRemove(ImGuiTable* table) { //IMGUI_DEBUG_PRINT("TableRemove() id=0x%08X\n", table->ID); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a0e1af4ac..c405d2f2d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9557,6 +9557,19 @@ static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) return ImGuiPtrOrIndex(tab_bar); } +ImGuiTabBar* ImGui::TabBarFindByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.TabBars.GetByKey(id); +} + +// Remove TabBar data (currently only used by TestEngine) +void ImGui::TabBarRemove(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + g.TabBars.Remove(tab_bar->ID, tab_bar); +} + bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) { ImGuiContext& g = *GImGui; From 1cd08b883c842713a0ab4bb2d5ee5868f3932b87 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Sep 2025 18:03:34 +0200 Subject: [PATCH 1311/2359] TabBar: fixed calling TabBarQueueFocus() before submitting tabs. (#8929, #6681) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- imgui_widgets.cpp | 3 ++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fe785c9fc..aab1c1f69 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,8 @@ Other Changes: unmoved. We revert back to move to the end of line in this situation. - Selectable: added ImGuiSelectableFlags_SelectOnNav to auto-select an item when moved into (automatic when in a BeginMultiSelect() block). +- TabBar: fixed an issue were forcefully selecting a tab using internal API would + be ignored on first/appearing frame before tabs are submitted (#8929, #6681) - DrawList: fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData pointer, which could to issue when deleting the cloned list. (#8894, #1860) - DrawList: made AddCallback() assert when passing a null callback. diff --git a/imgui.h b/imgui.h index a9aea86ed..a087c9e4d 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.3 WIP" -#define IMGUI_VERSION_NUM 19226 +#define IMGUI_VERSION_NUM 19227 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c405d2f2d..53167ea69 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9908,7 +9908,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->TabsNames.Buf.resize(0); // If we have lost the selected tab, select the next most recently active one - if (found_selected_tab_id == false) + const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); + if (found_selected_tab_id == false && !tab_bar_appearing) tab_bar->SelectedTabId = 0; if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL) scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID; From 2f1d1c8b2f56082588ad05f3fd98f865c1359a73 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Sep 2025 18:31:34 +0200 Subject: [PATCH 1312/2359] Focus, InputText: fixed an issue where SetKeyboardFocusHere() did not work on InputTextMultiline() with ImGuiInputTextFlags_AllowTabInput. (#8928) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 ++ imgui_internal.h | 3 ++- imgui_widgets.cpp | 4 ++-- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index aab1c1f69..6ac099fcf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,9 @@ Other Changes: - InputText: revert a change in 1.79 where pressing Down or PageDown on the last line of a multi-line buffer without a trailing carriage return would keep the cursor unmoved. We revert back to move to the end of line in this situation. +- Focus, InputText: fixed an issue where SetKeyboardFocusHere() did not work + on InputTextMultiline() fields with ImGuiInputTextFlags_AllowTabInput, since + they normally inhibit activation to allow tabbing through multiple items. (#8928) - Selectable: added ImGuiSelectableFlags_SelectOnNav to auto-select an item when moved into (automatic when in a BeginMultiSelect() block). - TabBar: fixed an issue were forcefully selecting a tab using internal API would diff --git a/imgui.cpp b/imgui.cpp index c655c3146..f5f018c84 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13932,6 +13932,8 @@ void ImGui::NavMoveRequestApplyResult() { g.NavNextActivateId = result->ID; g.NavNextActivateFlags = ImGuiActivateFlags_None; + if (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) + g.NavNextActivateFlags |= ImGuiActivateFlags_FromFocusApi; if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing; } diff --git a/imgui_internal.h b/imgui_internal.h index 6b5b4ca25..4d54789f5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1679,8 +1679,9 @@ enum ImGuiActivateFlags_ ImGuiActivateFlags_PreferInput = 1 << 0, // Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key. ImGuiActivateFlags_PreferTweak = 1 << 1, // Favor activation for tweaking with arrows or gamepad (e.g. for Slider/Drag). Default for Space key and if keyboard is not used. ImGuiActivateFlags_TryToPreserveState = 1 << 2, // Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) - ImGuiActivateFlags_FromTabbing = 1 << 3, // Activation requested by a tabbing request + ImGuiActivateFlags_FromTabbing = 1 << 3, // Activation requested by a tabbing request (ImGuiNavMoveFlags_IsTabbing) ImGuiActivateFlags_FromShortcut = 1 << 4, // Activation requested by an item shortcut via SetNextItemShortcut() function. + ImGuiActivateFlags_FromFocusApi = 1 << 5, // Activation requested by an api request (ImGuiNavMoveFlags_FocusApi) }; // Early work-in-progress API for ScrollToItem() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 53167ea69..421f33601 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4607,8 +4607,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ item_data_backup = g.LastItemData; window->DC.CursorPos = backup_pos; - // Prevent NavActivation from Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping. - if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && (flags & ImGuiInputTextFlags_AllowTabInput)) + // Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping. + if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && !(g.NavActivateFlags & ImGuiActivateFlags_FromFocusApi) && (flags & ImGuiInputTextFlags_AllowTabInput)) g.NavActivateId = 0; // Prevent NavActivate reactivating in BeginChild() when we are already active. From 013c4ed4763ddab12436c4437e60020a848642a6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Sep 2025 19:00:05 +0200 Subject: [PATCH 1313/2359] InputText: fixed gross buffer underflow introduced by a82f66a. (#3237, #952, #1062, #7363) Would typically not crash by detected by sanitinizers. --- imgui_widgets.cpp | 2 +- imstb_textedit.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 421f33601..783c49fe2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3992,7 +3992,7 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c namespace ImStb { static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; } -static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx <= obj->TextLen); return obj->TextSrc[idx]; } +static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx >= 0 && idx <= obj->TextLen); return obj->TextSrc[idx]; } static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.FontBaked->GetCharAdvance((ImWchar)c) * g.FontBakedScale; } static char STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx) diff --git a/imstb_textedit.h b/imstb_textedit.h index 49c8933e2..844be3b2b 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -582,7 +582,7 @@ static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING STB_TEXTEDIT_LAYOUTROW(&r, str, i); if (n < i + r.num_chars) break; - if (str->LastMoveDirectionLR == ImGuiDir_Right && str->Stb->cursor == i + r.num_chars && STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] Wrapping point handling + 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] From 5e5658e68fae85dde414327eb7e462a4f6a23388 Mon Sep 17 00:00:00 2001 From: Harry Mander Date: Wed, 10 Sep 2025 16:38:10 +1200 Subject: [PATCH 1314/2359] Debug Tools: fixed assertion failure when opening a combo box while using io.ConfigDebugBeginReturnValueOnce/ConfigDebugBeginReturnValueLoop. (#8931) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ac099fcf..7994e79e1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,8 @@ Other Changes: is now skipped. (#8904, #4631) - Debug Tools: ID Stack Tool: added option to hex-encode non-ASCII characters in output path. (#8904, #4631) +- Debug Tools: Fixed assertion failure when opening a combo box while using + io.ConfigDebugBeginReturnValueOnce/ConfigDebugBeginReturnValueLoop. (#8931) [@harrymander] - Demo: tweaked ShowFontSelector() and ShowStyleSelector() to update selection while navigating and to not close popup automatically. - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 783c49fe2..dd24b74a6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2032,7 +2032,8 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags if (!ret) { EndPopup(); - IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above + if (!g.IO.ConfigDebugBeginReturnValueOnce && !g.IO.ConfigDebugBeginReturnValueLoop) // Begin may only return false with those debug tools activated. + IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above return false; } g.BeginComboDepth++; From 55f590c1d17cf8bf1130e7c87c62eeface9001ac Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Sep 2025 22:29:42 +0200 Subject: [PATCH 1315/2359] Selectable: ImGuiSelectableFlags_SelectOnNav doesn't select when holding Ctrl, to be consistent with multi-select. Amend e66afbb + remove needless line in CloseCurrentPopup() block --- docs/CHANGELOG.txt | 2 +- imgui.h | 2 +- imgui_widgets.cpp | 5 ++--- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7994e79e1..2658bdb69 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -73,7 +73,7 @@ Other Changes: on InputTextMultiline() fields with ImGuiInputTextFlags_AllowTabInput, since they normally inhibit activation to allow tabbing through multiple items. (#8928) - Selectable: added ImGuiSelectableFlags_SelectOnNav to auto-select an item when - moved into (automatic when in a BeginMultiSelect() block). + moved into, unless Ctrl is held. (automatic when in a BeginMultiSelect() block). - TabBar: fixed an issue were forcefully selecting a tab using internal API would be ignored on first/appearing frame before tabs are submitted (#8929, #6681) - DrawList: fixed CloneOutput() unnecessarily taking a copy of the ImDrawListSharedData diff --git a/imgui.h b/imgui.h index a087c9e4d..e50ab814f 100644 --- a/imgui.h +++ b/imgui.h @@ -1341,7 +1341,7 @@ enum ImGuiSelectableFlags_ ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text ImGuiSelectableFlags_AllowOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one ImGuiSelectableFlags_Highlight = 1 << 5, // Make the item be displayed as if it is hovered - ImGuiSelectableFlags_SelectOnNav = 1 << 6, // Auto-select when moved into. Automatic when in a BeginMultiSelect() block. + ImGuiSelectableFlags_SelectOnNav = 1 << 6, // Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index dd24b74a6..55410b1f3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7366,7 +7366,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // - (2) usage will fail with clipped items // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API. if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId) - if (g.NavJustMovedToId == id) + if (g.NavJustMovedToId == id && (g.NavJustMovedToKeyMods & ImGuiMod_Ctrl) == 0) selected = pressed = auto_selected = true; } @@ -7419,8 +7419,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Automatically close popups if (pressed && !auto_selected && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups)) - if (!(flags & ImGuiSelectableFlags_SelectOnNav) || g.NavJustMovedToId != id) - CloseCurrentPopup(); + CloseCurrentPopup(); if (disabled_item && !disabled_global) EndDisabled(); From 8eb22ea6203f2653c317670277d4b9604cbae068 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Sep 2025 22:39:17 +0200 Subject: [PATCH 1316/2359] Demo: ShowStyleSelector(), ShowFontSelector(): remove ImGuiSelectableFlags_NoAutoClosePopups for now. In this situation we kinda want keyboard Enter to select and close but ideally not click. We don't have separate options yet. --- imgui.cpp | 2 +- imgui_demo.cpp | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f5f018c84..13c011ca9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17875,7 +17875,7 @@ void ImGui::ShowFontSelector(const char* label) for (ImFont* font : io.Fonts->Fonts) { PushID((void*)font); - if (Selectable(font->GetDebugName(), font == font_current, ImGuiSelectableFlags_SelectOnNav | ImGuiSelectableFlags_NoAutoClosePopups)) + if (Selectable(font->GetDebugName(), font == font_current, ImGuiSelectableFlags_SelectOnNav)) io.FontDefault = font; if (font == font_current) SetItemDefaultFocus(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8950e814e..26641f6b5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8224,17 +8224,18 @@ void ImGui::ShowAboutWindow(bool* p_open) //----------------------------------------------------------------------------- // Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. -// Here we use the simplified Combo() api that packs items into a single literal string. -// Useful for quick combo boxes where the choices are known locally. bool ImGui::ShowStyleSelector(const char* 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. static int style_idx = -1; const char* style_names[] = { "Dark", "Light", "Classic" }; bool ret = false; if (ImGui::BeginCombo(label, (style_idx >= 0 && style_idx < IM_ARRAYSIZE(style_names)) ? style_names[style_idx] : "")) { for (int n = 0; n < IM_ARRAYSIZE(style_names); n++) - if (ImGui::Selectable(style_names[n], style_idx == n, ImGuiSelectableFlags_SelectOnNav | ImGuiSelectableFlags_NoAutoClosePopups)) + { + if (ImGui::Selectable(style_names[n], style_idx == n, ImGuiSelectableFlags_SelectOnNav)) { style_idx = n; ret = true; @@ -8245,6 +8246,9 @@ bool ImGui::ShowStyleSelector(const char* label) case 2: ImGui::StyleColorsClassic(); break; } } + else if (style_idx == n) + ImGui::SetItemDefaultFocus(); + } ImGui::EndCombo(); } return ret; From e2f314d613b416a5126fb1385b2af67f9b74cf14 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Sep 2025 15:05:53 +0200 Subject: [PATCH 1317/2359] InputText: fixed misassignment to unused Scroll.y variable when using ImGuiInputTextFlags_NoHorizontalScroll. Amend d474ed7f7 (#7913, #383) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 55410b1f3..ebdee29b1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5439,7 +5439,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } else { - state->Scroll.y = 0.0f; + state->Scroll.x = 0.0f; } // Vertical scroll From 271f476d08320aae06d9d67e610f55c5e0608440 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Sep 2025 15:12:33 +0200 Subject: [PATCH 1318/2359] CI: disable pvs-studio 28 days warning. --- .github/workflows/static-analysis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 53db04764..a9e8bedf0 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -41,6 +41,6 @@ jobs: exit 0 fi cd examples/example_null - pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 - pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log + pvs-studio-analyzer trace --disableLicenseExpirationCheck -- make WITH_EXTRA_WARNINGS=1 + pvs-studio-analyzer analyze --disableLicenseExpirationCheck -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log plog-converter -a 'GA:1,2;OP:1' -d V1071 -t errorfile -w pvs-studio.log From e2b7d84e96d6578b41dc5f4ffe66cdb5b7f9a645 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Sep 2025 15:15:48 +0200 Subject: [PATCH 1319/2359] CI: disable pvs-studio 28 days warning (amend). --- .github/workflows/static-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index a9e8bedf0..a69c5110c 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -41,6 +41,6 @@ jobs: exit 0 fi cd examples/example_null - pvs-studio-analyzer trace --disableLicenseExpirationCheck -- make WITH_EXTRA_WARNINGS=1 + pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 pvs-studio-analyzer analyze --disableLicenseExpirationCheck -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log plog-converter -a 'GA:1,2;OP:1' -d V1071 -t errorfile -w pvs-studio.log From f36c65661c5534e215120eb96b7a2455ef1efc82 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Sep 2025 18:44:50 +0200 Subject: [PATCH 1320/2359] InputText: fixed pressing End (without Shift) in a multi-line selection from mistakenly moving cursor based on selection start. --- docs/CHANGELOG.txt | 2 ++ imstb_textedit.h | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2658bdb69..c195ed1eb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,8 @@ Other Changes: - InputText: revert a change in 1.79 where pressing Down or PageDown on the last line of a multi-line buffer without a trailing carriage return would keep the cursor unmoved. We revert back to move to the end of line in this situation. +- InputText: fixed pressing End (without Shift) in a multi-line selection from + mistakenly moving cursor based on selection start. - Focus, InputText: fixed an issue where SetKeyboardFocusHere() did not work on InputTextMultiline() fields with ImGuiInputTextFlags_AllowTabInput, since they normally inhibit activation to allow tabbing through multiple items. (#8928) diff --git a/imstb_textedit.h b/imstb_textedit.h index 844be3b2b..c41078c8a 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -1154,7 +1154,7 @@ retry: #endif case STB_TEXTEDIT_K_LINEEND: { stb_textedit_clamp(str, state); - stb_textedit_move_to_first(state); + stb_textedit_move_to_last(str, state); state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor); state->has_preferred_x = 0; break; From 67085d732aa06547800ec3c2c43ecf9bbfe76115 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Sep 2025 15:17:22 +0200 Subject: [PATCH 1321/2359] ImGuiTextIndex: rename member. --- imgui.cpp | 4 ++-- imgui_internal.h | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 13c011ca9..b66474b0a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3080,11 +3080,11 @@ void ImGuiTextIndex::append(const char* base, int old_size, int new_size) if (old_size == new_size) return; if (EndOffset == 0 || base[EndOffset - 1] == '\n') - LineOffsets.push_back(EndOffset); + Offsets.push_back(EndOffset); const char* base_end = base + new_size; for (const char* p = base + old_size; (p = (const char*)ImMemchr(p, '\n', base_end - p)) != 0; ) if (++p < base_end) // Don't push a trailing offset on last \n - LineOffsets.push_back((int)(intptr_t)(p - base)); + Offsets.push_back((int)(intptr_t)(p - base)); EndOffset = ImMax(EndOffset, new_size); } diff --git a/imgui_internal.h b/imgui_internal.h index 4d54789f5..a206357b2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -804,13 +804,13 @@ struct ImChunkStream // Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API. struct ImGuiTextIndex { - ImVector LineOffsets; + ImVector Offsets; int EndOffset = 0; // Because we don't own text buffer we need to maintain EndOffset (may bake in LineOffsets?) - void clear() { LineOffsets.clear(); EndOffset = 0; } - int size() { return LineOffsets.Size; } - const char* get_line_begin(const char* base, int n) { return base + LineOffsets[n]; } - const char* get_line_end(const char* base, int n) { return base + (n + 1 < LineOffsets.Size ? (LineOffsets[n + 1] - 1) : EndOffset); } + void clear() { Offsets.clear(); EndOffset = 0; } + int size() { return Offsets.Size; } + const char* get_line_begin(const char* base, int n) { return base + Offsets[n]; } + const char* get_line_end(const char* base, int n) { return base + (n + 1 < Offsets.Size ? (Offsets[n + 1] - 1) : EndOffset); } void append(const char* base, int old_size, int new_size); }; From 1e52e7b90c07d347cd41822aeb0b2a96f51027e9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Sep 2025 19:05:26 +0200 Subject: [PATCH 1322/2359] InputText: Added a line index. Refactored cursor and selection rendering, now simpler, easier to reason about, and faster. (#3237, #952, #1062, #7363) --- docs/CHANGELOG.txt | 2 + imgui.cpp | 11 ++ imgui_internal.h | 4 +- imgui_widgets.cpp | 348 +++++++++++++++++++++------------------------ 4 files changed, 180 insertions(+), 185 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c195ed1eb..b589eeb2f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,8 @@ Other Changes: In theory the buffer size should always account for a zero-terminator, but idioms such as using InputTextMultiline() with ImGuiInputTextFlags_ReadOnly to display a text blob are facilitated by allowing this. +- InputText: refactored internals to simplify and optimizing rendering of selection. + Very large selection (e.g. 1 MB) now take less overhead. - InputText: revert a change in 1.79 where pressing Down or PageDown on the last line of a multi-line buffer without a trailing carriage return would keep the cursor unmoved. We revert back to move to the end of line in this situation. diff --git a/imgui.cpp b/imgui.cpp index b66474b0a..5c0b11014 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3074,6 +3074,7 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) va_end(args_copy); } +IM_MSVC_RUNTIME_CHECKS_OFF void ImGuiTextIndex::append(const char* base, int old_size, int new_size) { IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset); @@ -3087,6 +3088,7 @@ void ImGuiTextIndex::append(const char* base, int old_size, int new_size) Offsets.push_back((int)(intptr_t)(p - base)); EndOffset = ImMax(EndOffset, new_size); } +IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- // [SECTION] ImGuiListClipper @@ -3414,6 +3416,13 @@ bool ImGuiListClipper::Step() return ret; } +// Generic helper, equivalent to old ImGui::CalcListClipping() but statelesss +void ImGui::CalcClipRectVisibleItemsY(const ImRect& clip_rect, const ImVec2& pos, float items_height, int* out_visible_start, int* out_visible_end) +{ + *out_visible_start = ImMax((int)((clip_rect.Min.y - pos.y) / items_height), 0); + *out_visible_end = ImMax((int)ImCeil((clip_rect.Max.y - pos.y) / items_height), *out_visible_start); +} + //----------------------------------------------------------------------------- // [SECTION] STYLING //----------------------------------------------------------------------------- @@ -4374,6 +4383,7 @@ void ImGui::Shutdown() g.ClipboardHandlerData.clear(); g.MenusIdSubmittedThisFrame.clear(); g.InputTextState.ClearFreeMemory(); + g.InputTextLineIndex.clear(); g.InputTextDeactivatedState.ClearFreeMemory(); g.SettingsWindows.clear(); @@ -4489,6 +4499,7 @@ void ImGui::GcCompactTransientMiscBuffers() ImGuiContext& g = *GImGui; g.ItemFlagsStack.clear(); g.GroupStack.clear(); + g.InputTextLineIndex.clear(); g.MultiSelectTempDataStacked = 0; g.MultiSelectTempData.clear_destruct(); TableGcCompactSettings(); diff --git a/imgui_internal.h b/imgui_internal.h index a206357b2..021a24d98 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -809,7 +809,7 @@ struct ImGuiTextIndex void clear() { Offsets.clear(); EndOffset = 0; } int size() { return Offsets.Size; } - const char* get_line_begin(const char* base, int n) { return base + Offsets[n]; } + const char* get_line_begin(const char* base, int n) { return base + (Offsets.Size != 0 ? Offsets[n] : 0); } const char* get_line_end(const char* base, int n) { return base + (n + 1 < Offsets.Size ? (Offsets[n + 1] - 1) : EndOffset); } void append(const char* base, int old_size, int new_size); }; @@ -2430,6 +2430,7 @@ struct ImGuiContext // Widget state ImGuiInputTextState InputTextState; + ImGuiTextIndex InputTextLineIndex; // Temporary storage ImGuiInputTextDeactivatedState InputTextDeactivatedState; ImFontBaked InputTextPasswordFontBackupBaked; ImFontFlags InputTextPasswordFontBackupFlags; @@ -3258,6 +3259,7 @@ namespace ImGui IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); IMGUI_API void PushMultiItemsWidths(int components, float width_full); IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min); + IMGUI_API void CalcClipRectVisibleItemsY(const ImRect& clip_rect, const ImVec2& pos, float items_height, int* out_visible_start, int* out_visible_end); // Parameter stacks (shared) IMGUI_API const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ebdee29b1..f506b111e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -135,7 +135,6 @@ static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); // For InputTextEx() static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false); -static int InputTextCalcTextLenAndLineCount(ImGuiContext* ctx, const char* text_begin, const char** out_text_end, float wrap_width); static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining = NULL, ImVec2* out_offset = NULL, ImDrawTextFlags flags = 0); //------------------------------------------------------------------------- @@ -3938,46 +3937,6 @@ bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, si return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); } -// This is only used in the path where the multiline widget is inactive. -static int InputTextCalcTextLenAndLineCount(ImGuiContext* ctx, const char* text_begin, const char** out_text_end, float wrap_width) -{ - int line_count = 0; - const char* s = text_begin; - if (wrap_width == 0.0f) - { - while (true) - { - const char* s_eol = strchr(s, '\n'); - line_count++; - if (s_eol == NULL) - { - s = s + ImStrlen(s); - break; - } - s = s_eol + 1; - } - } - else - { - // FIXME-WORDWRAP, FIXME-OPT: This is very suboptimal. - // We basically want both text_end and text_size, they could more optimally be emitted from a RenderText call that uses word-wrapping. - ImGuiContext& g = *ctx; - ImFont* font = g.Font; - const char* text_end = text_begin + strlen(text_begin); - while (s < text_end) - { - s = ImFontCalcWordWrapPositionEx(font, g.FontSize, s, text_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); - s = (*s == '\n') ? s + 1 : s; - line_count++; - } - if (text_end > text_begin && text_end[-1] == '\n') - line_count++; - IM_ASSERT(s == text_end); - } - *out_text_end = s; - return line_count; -} - static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags) { ImGuiContext& g = *ctx; @@ -4555,6 +4514,83 @@ void ImGui::InputTextDeactivateHook(ImGuiID id) } } +static int* ImLowerBound(int* in_begin, int* in_end, int v) +{ + int* in_p = in_begin; + for (size_t count = (size_t)(in_end - in_p); count > 0; ) + { + size_t count2 = count >> 1; + int* mid = in_p + count2; + if (*mid < v) + { + in_p = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } + } + return in_p; +} + +// FIXME-WORDWRAP: Bundle some of this into ImGuiTextIndex and/or extract as a different tool? +// 'max_output_buffer_size' happens to be a meaningful optimization to avoid writing the full line_index when not necessarily needed (e.g. very large buffer, scrolled up, inactive) +static int InputTextLineIndexBuild(ImGuiInputTextFlags flags, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, float wrap_width, int max_output_buffer_size) +{ + ImGuiContext& g = *GImGui; + int size = 0; + if (flags & ImGuiInputTextFlags_WordWrap) + { + for (const char* s = buf; s < buf_end; ) + { + if (size++ <= max_output_buffer_size) + line_index->Offsets.push_back((int)(s - buf)); + s = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, s, buf_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); + s = (*s == '\n') ? s + 1 : s; + } + } + else + { + for (const char* s = buf; s < buf_end; ) + { + if (size++ <= max_output_buffer_size) + line_index->Offsets.push_back((int)(s - buf)); + s = (const char*)ImMemchr(s, '\n', buf_end - s); + s = s ? s + 1 : buf_end; + } + } + if (size == 0) + { + line_index->Offsets.push_back(0); + size++; + } + if (buf_end > buf && buf_end[-1] == '\n' && size <= max_output_buffer_size) + { + line_index->Offsets.push_back((int)(buf_end - buf)); + size++; + } + return size; +} + +static ImVec2 InputTextLineIndexGetPosOffset(ImGuiContext& g, ImGuiInputTextState* state, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, int cursor_n) +{ + const char* cursor_ptr = buf + cursor_n; + int* it_begin = line_index->Offsets.begin(); + int* it_end = line_index->Offsets.end(); + const int* it = ImLowerBound(it_begin, it_end, cursor_n); + if (it > it_begin) + if (it == it_end || *it != cursor_n || (cursor_ptr[-1] != '\n' && cursor_ptr[-1] != 0 && state != NULL && state->LastMoveDirectionLR == ImGuiDir_Right)) + it--; + + const int line_no = (it == it_begin) ? 0 : line_index->Offsets.index_from_ptr(it); + const char* line_start = line_index->get_line_begin(buf, line_no); + ImVec2 offset; + offset.x = InputTextCalcTextSize(&g, line_start, cursor_ptr, buf_end, NULL, NULL, ImDrawTextFlags_WrapKeepBlanks).x; + offset.y = (line_no + 1) * g.FontSize; + return offset; +} + // Edit a string of text // - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!". // This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match @@ -5327,15 +5363,40 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ buf_display = hint; buf_display_end = hint + ImStrlen(hint); } + else + { + if (render_cursor || render_selection || g.ActiveId == id) + buf_display_end = buf_display + state->TextLen; //-V595 + else + buf_display_end = buf_display + ImStrlen(buf_display); // FIXME-OPT: For multi-line path this would optimally be folded into the InputTextLineIndex build below. + } + + // Calculate visibility + int line_visible_n0 = 0, line_visible_n1 = 1; + if (is_multiline) + CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize, &line_visible_n0, &line_visible_n1); + + // Build line index for easy data access (makes code below simpler and faster) + ImGuiTextIndex* line_index = &g.InputTextLineIndex; + line_index->Offsets.resize(0); + line_index->EndOffset = (int)(buf_display_end - buf_display); + int line_count = 1; + if (is_multiline) + line_count = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, (render_cursor && state && state->CursorFollow) ? INT_MAX : line_visible_n1 + 1); + line_visible_n1 = ImMin(line_visible_n1, line_count); + + // Store text height (we don't need width) + text_size = ImVec2(inner_size.x, line_count * g.FontSize); + //GetForegroundDrawList()->AddRect(draw_pos + ImVec2(0, line_visible_n0 * g.FontSize), draw_pos + ImVec2(frame_size.x, line_visible_n1 * g.FontSize), IM_COL32(255, 0, 0, 255)); + + // Calculate blinking cursor position + const ImVec2 cursor_offset = render_cursor && state ? InputTextLineIndexGetPosOffset(g, state, line_index, buf_display, buf_display_end, state->Stb->cursor) : ImVec2(0.0f, 0.0f); + ImVec2 draw_scroll; // Render text. We currently only render selection when the widget is active or while scrolling. - // FIXME: This is one of the messiest piece of the whole codebase. + const ImU32 text_col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); if (render_cursor || render_selection) { - IM_ASSERT(state != NULL); - if (!is_displaying_hint) - buf_display_end = buf_display + state->TextLen; - // Render text (with cursor and selection) // This is going to be messy. We need to: // - Display the text (this alone can be more easily clipped) @@ -5343,85 +5404,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // - Measure text height (for scrollbar) // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. - const char* text_begin = buf_display; - const char* text_end = text_begin + state->TextLen; - ImVec2 cursor_offset; - float select_start_offset_y = 0.0f; // Offset of beginning of non-wrapped line for selection. - - { - // Find lines numbers straddling cursor and selection min position - int cursor_line_no = render_cursor ? -1 : -1000; - int selmin_line_no = render_selection ? -1 : -1000; - const char* cursor_ptr = render_cursor ? text_begin + state->Stb->cursor : NULL; - const char* selmin_ptr = render_selection ? text_begin + ImMin(state->Stb->select_start, state->Stb->select_end) : NULL; - const char* cursor_line_start = NULL; - const char* selmin_line_start = NULL; - bool cursor_straddle_word_wrap = false; - - // Count lines and find line number for cursor and selection ends - // FIXME: Switch to zero-based index to reduce confusion. - int line_count = 1; - if (is_multiline) - { - if (!is_wordwrap) - { - for (const char* s = text_begin; (s = (const char*)ImMemchr(s, '\n', (size_t)(text_end - s))) != NULL; s++) - { - if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_no = line_count; } - if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_no = line_count; } - line_count++; - } - } - else - { - bool is_start_of_non_wrapped_line = true; - int line_count_for_non_wrapped_line = 1; - for (const char* s = text_begin; s < text_end; s = (*s == '\n') ? s + 1 : s) - { - const char* s_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, s, text_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); - const char* s_prev = s; - s = s_eol; - if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_start = s_prev; cursor_line_no = line_count; } - if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_start = s_prev; selmin_line_no = line_count_for_non_wrapped_line; } - if (s == cursor_ptr && *cursor_ptr != '\n' && *cursor_ptr != 0) - cursor_straddle_word_wrap = true; - is_start_of_non_wrapped_line = (*s == '\n'); - line_count++; - if (is_start_of_non_wrapped_line) - line_count_for_non_wrapped_line = line_count; - } - } - //IMGUI_DEBUG_LOG("%d\n", selmin_line_no); - } - if (cursor_line_no == -1) - cursor_line_no = line_count; - if (cursor_line_start == NULL) - cursor_line_start = ImStrbol(cursor_ptr, text_begin); - if (selmin_line_no == -1) - selmin_line_no = line_count; - if (selmin_line_start == NULL) - selmin_line_start = ImStrbol(cursor_ptr, text_begin); - - // Calculate 2d position by finding the beginning of the line and measuring distance - if (render_cursor) - { - cursor_offset.x = InputTextCalcTextSize(&g, cursor_line_start, cursor_ptr, text_end, NULL, NULL, ImDrawTextFlags_WrapKeepBlanks).x; - cursor_offset.y = cursor_line_no * g.FontSize; - if (is_multiline && cursor_straddle_word_wrap && state->LastMoveDirectionLR == ImGuiDir_Left) - cursor_offset = ImVec2(0.0f, cursor_offset.y + g.FontSize); - } - if (selmin_line_no >= 0) - select_start_offset_y = selmin_line_no * g.FontSize; - - // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) - if (is_multiline) - { - if (is_wordwrap && text_end > text_begin && text_end[-1] != '\n') - line_count--; - text_size = ImVec2(inner_size.x, line_count * g.FontSize); - } - state->LineCount = line_count; - } + IM_ASSERT(state != NULL); + state->LineCount = line_count; // Scroll float new_scroll_y = scroll_y; @@ -5447,7 +5431,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Test if cursor is vertically visible if (cursor_offset.y - g.FontSize < scroll_y) - new_scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + new_scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y) new_scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f; } @@ -5466,57 +5450,60 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ scroll_y = ImClamp(new_scroll_y, 0.0f, scroll_max_y); draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag draw_window->Scroll.y = scroll_y; + CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize, &line_visible_n0, &line_visible_n1); + line_visible_n1 = ImMin(line_visible_n1, line_count); } // Draw selection - const ImVec2 draw_scroll = ImVec2(state->Scroll.x, 0.0f); + draw_scroll.x = state->Scroll.x; if (render_selection) { - const char* text_selected_begin = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end); - const char* text_selected_end = text_begin + ImMax(state->Stb->select_start, state->Stb->select_end); + const ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. + const float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + const float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + const float bg_eol_width = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines - ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. - float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. - float bg_offy_dn = is_multiline ? 0.0f : 2.0f; - float bg_min_width = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines - ImVec2 rect_pos = draw_pos - draw_scroll; - rect_pos.y += select_start_offset_y; - for (const char* p = ImStrbol(text_selected_begin, text_begin); p < text_selected_end; rect_pos.y += g.FontSize) + const char* text_selected_begin = buf_display + ImMin(state->Stb->select_start, state->Stb->select_end); + const char* text_selected_end = buf_display + ImMax(state->Stb->select_start, state->Stb->select_end); + for (int line_n = line_visible_n0; line_n < line_visible_n1; line_n++) { - if (rect_pos.y > clip_rect.Max.y + g.FontSize) - break; - const char* p_eol = is_wordwrap ? ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks) : (const char*)ImMemchr((void*)p, '\n', text_selected_end - p); - if (p_eol == NULL) - p_eol = text_selected_end; - const char* p_next = is_wordwrap ? (*p_eol == '\n' ? p_eol + 1 : p_eol) : (p_eol + 1); - if (rect_pos.y >= clip_rect.Min.y) - { - const char* line_selected_begin = (text_selected_begin > p) ? text_selected_begin : p; - const char* line_selected_end = (text_selected_end < p_eol) ? text_selected_end : p_eol; - if ((*p_eol == '\n' && text_selected_begin <= p_eol) || (text_selected_begin < p_eol)) - { - ImVec2 rect_offset = CalcTextSize(p, line_selected_begin); - ImVec2 rect_size = CalcTextSize(line_selected_begin, line_selected_end); - rect_size.x = ImMax(rect_size.x, bg_min_width); // So we can see selected empty lines - ImRect rect(rect_pos + ImVec2(rect_offset.x, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_offset.x + rect_size.x, bg_offy_dn)); - rect.ClipWith(clip_rect); - if (rect.Overlaps(clip_rect)) - draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); - } - } - p = p_next; + const char* p = line_index->get_line_begin(buf_display, line_n); + const char* p_eol = line_index->get_line_end(buf_display, line_n); + const bool p_eol_is_wrap = (p_eol < buf_display_end && *p_eol != '\n'); + if (p_eol_is_wrap) + p_eol++; + const char* line_selected_begin = (text_selected_begin > p) ? text_selected_begin : p; + const char* line_selected_end = (text_selected_end < p_eol) ? text_selected_end : p_eol; + + float rect_width = 0.0f; + if (line_selected_begin < line_selected_end) + rect_width += CalcTextSize(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.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; + rect.Min.y -= bg_offy_up; + rect.ClipWith(clip_rect); + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); } } + // Render text // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. // FIXME-OPT: Multiline could submit a smaller amount of contents to AddText() since we already iterated through it. - if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) - { - ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); - if (col & IM_COL32_A_MASK) - g.Font->RenderText(draw_window->DrawList, g.FontSize, draw_pos - draw_scroll, col, clip_rect.AsVec4(), buf_display, buf_display_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); - //draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, wrap_width, is_multiline ? NULL : &clip_rect.AsVec4()); - } + if ((is_multiline || (buf_display_end - buf_display) < buf_display_max_length) && (text_col & IM_COL32_A_MASK) && (line_visible_n0 < line_visible_n1)) + 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), + wrap_width, ImDrawTextFlags_WrapKeepBlanks); // Draw blinking cursor if (render_cursor) @@ -5544,26 +5531,19 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } else { + // Find render position for right alignment (single-line only) + if (flags & ImGuiInputTextFlags_ElideLeft) + draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x); + // Render text only (no selection, no cursor) - if (is_multiline) - text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(&g, buf_display, &buf_display_end, wrap_width) * g.FontSize); // We don't need width - else if (!is_displaying_hint && g.ActiveId == id) - buf_display_end = buf_display + state->TextLen; - else if (!is_displaying_hint) - buf_display_end = buf_display + ImStrlen(buf_display); - - if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) - { - // Find render position for right alignment - if (flags & ImGuiInputTextFlags_ElideLeft) - draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x); - - const ImVec2 draw_scroll = /*state ? ImVec2(state->Scroll.x, 0.0f) :*/ ImVec2(0.0f, 0.0f); // Preserve scroll when inactive? - ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); - if (col & IM_COL32_A_MASK) - g.Font->RenderText(draw_window->DrawList, g.FontSize, draw_pos - draw_scroll, col, clip_rect.AsVec4(), buf_display, buf_display_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); - //draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, wrap_width, is_multiline ? NULL : &clip_rect.AsVec4()); - } + //draw_scroll.x = state->Scroll.x; // Preserve scroll when inactive? + if ((is_multiline || (buf_display_end - buf_display) < buf_display_max_length) && (text_col & IM_COL32_A_MASK) && (line_visible_n0 < line_visible_n1)) + 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), + wrap_width, ImDrawTextFlags_WrapKeepBlanks); } if (is_password && !is_displaying_hint) From ae832ce532046a1953023af34e9041b77f84369c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Sep 2025 20:19:17 +0200 Subject: [PATCH 1323/2359] InputText: moved blocks so same text rendering code is now used for active and inactive states. (ignore whitespace to visualize this change easily) --- imgui_widgets.cpp | 85 ++++++++++++++++++++--------------------------- 1 file changed, 36 insertions(+), 49 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f506b111e..b5980761a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5493,57 +5493,44 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); } } - - // Render text - // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. - // FIXME-OPT: Multiline could submit a smaller amount of contents to AddText() since we already iterated through it. - if ((is_multiline || (buf_display_end - buf_display) < buf_display_max_length) && (text_col & IM_COL32_A_MASK) && (line_visible_n0 < line_visible_n1)) - 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), - wrap_width, ImDrawTextFlags_WrapKeepBlanks); - - // Draw blinking cursor - if (render_cursor) - { - state->CursorAnim += io.DeltaTime; - bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f; - ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); - ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); - if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) - draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031) - - // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) - // This is required for some backends (SDL3) to start emitting character/text inputs. - // As per #6341, make sure we don't set that on the deactivating frame. - if (!is_readonly && g.ActiveId == id) - { - ImGuiPlatformImeData* ime_data = &g.PlatformImeData; // (this is a public struct, passed to io.Platform_SetImeDataFn() handler) - ime_data->WantVisible = true; - ime_data->WantTextInput = true; - ime_data->InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); - ime_data->InputLineHeight = g.FontSize; - ime_data->ViewportId = window->Viewport->ID; - } - } } - else - { - // Find render position for right alignment (single-line only) - if (flags & ImGuiInputTextFlags_ElideLeft) - draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x); - // Render text only (no selection, no cursor) - //draw_scroll.x = state->Scroll.x; // Preserve scroll when inactive? - if ((is_multiline || (buf_display_end - buf_display) < buf_display_max_length) && (text_col & IM_COL32_A_MASK) && (line_visible_n0 < line_visible_n1)) - 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), - wrap_width, ImDrawTextFlags_WrapKeepBlanks); + // Find render position for right alignment (single-line only) + if (g.ActiveId != id && flags & ImGuiInputTextFlags_ElideLeft) + draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x); + //draw_scroll.x = state->Scroll.x; // Preserve scroll when inactive? + + // Render text + if ((is_multiline || (buf_display_end - buf_display) < buf_display_max_length) && (text_col & IM_COL32_A_MASK) && (line_visible_n0 < line_visible_n1)) + 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), + wrap_width, ImDrawTextFlags_WrapKeepBlanks); + + // Render blinking cursor + if (render_cursor) + { + state->CursorAnim += io.DeltaTime; + bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f; + ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031) + + // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) + // This is required for some backends (SDL3) to start emitting character/text inputs. + // As per #6341, make sure we don't set that on the deactivating frame. + if (!is_readonly && g.ActiveId == id) + { + ImGuiPlatformImeData* ime_data = &g.PlatformImeData; // (this is a public struct, passed to io.Platform_SetImeDataFn() handler) + ime_data->WantVisible = true; + ime_data->WantTextInput = true; + ime_data->InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); + ime_data->InputLineHeight = g.FontSize; + ime_data->ViewportId = window->Viewport->ID; + } } if (is_password && !is_displaying_hint) From 8a944222469ab23559bc01a563f4e9b516e4e701 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Sep 2025 21:18:52 +0200 Subject: [PATCH 1324/2359] InputText: optimize inactive path by avoiding an early ImStrlen(). --- imgui_widgets.cpp | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b5980761a..c5359044e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4536,30 +4536,44 @@ static int* ImLowerBound(int* in_begin, int* in_end, int v) // FIXME-WORDWRAP: Bundle some of this into ImGuiTextIndex and/or extract as a different tool? // 'max_output_buffer_size' happens to be a meaningful optimization to avoid writing the full line_index when not necessarily needed (e.g. very large buffer, scrolled up, inactive) -static int InputTextLineIndexBuild(ImGuiInputTextFlags flags, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, float wrap_width, int max_output_buffer_size) +static int InputTextLineIndexBuild(ImGuiInputTextFlags flags, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, float wrap_width, int max_output_buffer_size, const char** out_buf_end) { ImGuiContext& g = *GImGui; int size = 0; + const char* s; if (flags & ImGuiInputTextFlags_WordWrap) { - for (const char* s = buf; s < buf_end; ) + for (s = buf; s < buf_end; s = (*s == '\n') ? s + 1 : s) { if (size++ <= max_output_buffer_size) line_index->Offsets.push_back((int)(s - buf)); s = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, s, buf_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks); - s = (*s == '\n') ? s + 1 : s; } } - else + else if (buf_end != NULL) { - for (const char* s = buf; s < buf_end; ) + for (s = buf; s < buf_end; s = s ? s + 1 : buf_end) { if (size++ <= max_output_buffer_size) line_index->Offsets.push_back((int)(s - buf)); s = (const char*)ImMemchr(s, '\n', buf_end - s); - s = s ? s + 1 : buf_end; } } + else + { + const char* s_eol; + for (s = buf; ; s = s_eol + 1) + { + if (size++ <= max_output_buffer_size) + line_index->Offsets.push_back((int)(s - buf)); + if ((s_eol = strchr(s, '\n')) != NULL) + continue; + s += strlen(s); + break; + } + } + if (out_buf_end != NULL) + *out_buf_end = buf_end = s; if (size == 0) { line_index->Offsets.push_back(0); @@ -5367,8 +5381,10 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { if (render_cursor || render_selection || g.ActiveId == id) buf_display_end = buf_display + state->TextLen; //-V595 + else if (is_multiline && !is_wordwrap) + buf_display_end = NULL; // Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path. else - buf_display_end = buf_display + ImStrlen(buf_display); // FIXME-OPT: For multi-line path this would optimally be folded into the InputTextLineIndex build below. + buf_display_end = buf_display + ImStrlen(buf_display); } // Calculate visibility @@ -5379,10 +5395,10 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Build line index for easy data access (makes code below simpler and faster) ImGuiTextIndex* line_index = &g.InputTextLineIndex; line_index->Offsets.resize(0); - line_index->EndOffset = (int)(buf_display_end - buf_display); int line_count = 1; if (is_multiline) - line_count = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, (render_cursor && state && state->CursorFollow) ? INT_MAX : line_visible_n1 + 1); + line_count = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, (render_cursor && state && state->CursorFollow) ? INT_MAX : line_visible_n1 + 1, buf_display_end ? NULL : &buf_display_end); + line_index->EndOffset = (int)(buf_display_end - buf_display); line_visible_n1 = ImMin(line_visible_n1, line_count); // Store text height (we don't need width) From 2f3e85bc3788c05079b7509817f46dba7db9786a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Sep 2025 14:35:39 +0200 Subject: [PATCH 1325/2359] Comments --- docs/CHANGELOG.txt | 2 +- imgui.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b589eeb2f..f8105a49a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -93,6 +93,7 @@ Other Changes: io.ConfigDebugBeginReturnValueOnce/ConfigDebugBeginReturnValueLoop. (#8931) [@harrymander] - Demo: tweaked ShowFontSelector() and ShowStyleSelector() to update selection while navigating and to not close popup automatically. +- CI: Updates Windows CI to use a more recent VulkanSDK. (#8925, #8778) [@yaz0r] - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used @@ -193,7 +194,6 @@ Other Changes: to play nice with -fsanitize=undefined. (#8874) [@i25e] - CI: Added SDL3 builds to MacOS and Windows. (#8819, #8778) [@scribam] - CI: Updated Windows CI to use a more recent SDL2. (#8819, #8778) [@scribam] -- CI: Updates Windows CI to use a more recent VulkanSDK. (#8925, #8778) [@yaz0r] - Examples: SDL3+Metal: added SDL3+Metal example. (#8827, #8825) [@shi-yan] - Examples: SDL3+SDL_GPU: use SDL_WaitAndAcquireGPUSwapchainTexture() instead of SDL_AcquireGPUSwapchainTexture(). (#8830) [@itsdanott] diff --git a/imgui.cpp b/imgui.cpp index 5c0b11014..eb84cdd4c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2066,7 +2066,7 @@ void ImStrncpy(char* dst, const char* src, size_t count) if (count < 1) return; if (count > 1) - strncpy(dst, src, count - 1); + strncpy(dst, src, count - 1); // FIXME-OPT: strncpy not only doesn't guarantee 0-termination, it also always writes the whole array dst[count - 1] = 0; } From 7f1e2bb8ddf72a16a89f62fb60d0bd0b93c13c44 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Sep 2025 14:34:43 +0200 Subject: [PATCH 1326/2359] InputText: Word-Wrap: avoid word-wrap specific path InputTextLineIndexGetPosOffset() when word-wrap is disabled. (#3237, #952, #1062, #7363) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c5359044e..5ba4293a7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4594,7 +4594,7 @@ static ImVec2 InputTextLineIndexGetPosOffset(ImGuiContext& g, ImGuiInputTextStat int* it_end = line_index->Offsets.end(); const int* it = ImLowerBound(it_begin, it_end, cursor_n); if (it > it_begin) - if (it == it_end || *it != cursor_n || (cursor_ptr[-1] != '\n' && cursor_ptr[-1] != 0 && state != NULL && state->LastMoveDirectionLR == ImGuiDir_Right)) + if (it == it_end || *it != cursor_n || (state->WrapWidth > 0.0f && cursor_ptr[-1] != '\n' && cursor_ptr[-1] != 0 && state != NULL && state->LastMoveDirectionLR == ImGuiDir_Right)) it--; const int line_no = (it == it_begin) ? 0 : line_index->Offsets.index_from_ptr(it); From 78c1d4a92c42a5f8a327934a05543d984c9acff5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Sep 2025 15:02:09 +0200 Subject: [PATCH 1327/2359] InputText: Word-Wrap: moving ImGuiInputTextFlags_WordWrap to public API. Added in demo. (#3237, #952, #1062, #7363) --- docs/CHANGELOG.txt | 12 ++++++++++++ docs/TODO.txt | 1 - imgui.h | 9 +++++++++ imgui_demo.cpp | 7 ++++++- imgui_internal.h | 9 --------- 5 files changed, 27 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f8105a49a..b50ad6816 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,18 @@ Other Changes: - Nav: fixed Ctrl+Tab window appearing as empty when the sole active and focused window has the ImGuiWindowFlags_NoNavFocus flag. (#8914) - Bullet: fixed tesselation amount which looked out of place in very large sizes. +- InputText: added ImGuiInputTextFlags_WordWrap flag to word-wrap multi-line buffers. + (#3237, #952, #1062, #7363) + - This is marked as beta because not being tested enough. + Please report any incorrect cursor movement, selection behavior etc. bug to #3237. + - Vertical scrollbar is made always visible. + - Wrapping points are not ideal. Wrapping of long words/sections (e.g. words + larger than total available width) may be particularly unpleasing. + - It is currently much slower than regular text fields. + - Ballpark estimate of cost on my 2019 desktop PC: + For a 100 KB text buffer: +~0.3 ms/+~1.0 ms (Optimized vs Debug builds). + - The CPU cost is very roughly proportional to text length, so a 10 KB buffer + should cost about ten times less. - InputText, InputInt, InputFloat: fixed an issue where using Escape to revert would not write back the reverted value during the IsItemDeactivatedAfterEdit() frame if the provided input buffer doesn't store temporary edits. diff --git a/docs/TODO.txt b/docs/TODO.txt index 90d2b35db..111852b43 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -87,7 +87,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input text multi-line: line numbers? status bar? (follow up on #200) - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725) - input text multi-line: better horizontal scrolling support (#383, #1224) - - input text multi-line: single call to AddText() should be coarse clipped on InputTextEx() end. - input number: optional range min/max for Input*() functions - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) - input number: use mouse wheel to step up/down diff --git a/imgui.h b/imgui.h index e50ab814f..58c63f44a 100644 --- a/imgui.h +++ b/imgui.h @@ -1265,6 +1265,15 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_CallbackResize = 1 << 22, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) ImGuiInputTextFlags_CallbackEdit = 1 << 23, // Callback on any edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. + // Multi-line Word-Wrapping [BETA] + // - Not well tested yet. Please report any incorrect cursor movement, selection behavior etc. bug to https://github.com/ocornut/imgui/issues/3237. + // - Vertical scrollbar is made always visible. + // - Wrapping points are not ideal. Wrapping of long words/sections (e.g. words larger than total available width) may be particularly unpleasing. + // - It is much slower than regular text fields. + // Ballpark estimate of cost on my 2019 desktop PC: for a 100 KB text buffer: +~0.3 ms (Optimized) / +~1.0 ms (Debug build). + // The CPU cost is very roughly proportional to text length, so a 10 KB buffer should cost about ten times less. + ImGuiInputTextFlags_WordWrap = 1 << 24, // InputTextMultine(): word-wrap lines that are too long. + // Obsolete names //ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 26641f6b5..d667c8b70 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3708,6 +3708,8 @@ static void DemoWindowWidgetsTextInput() static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include in here)"); ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_WordWrap", &flags, ImGuiInputTextFlags_WordWrap); + ImGui::SameLine(); HelpMarker("Feature is currently in Beta. Please read comments in imgui.h"); ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput); ImGui::SameLine(); HelpMarker("When _AllowTabInput is set, passing through the widget with Tabbing doesn't automatically activate it, in order to also cycling through subsequent widgets."); ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine); @@ -3855,10 +3857,13 @@ static void DemoWindowWidgetsTextInput() // For this demo we are using ImVector as a string container. // Note that because we need to store a terminating zero character, our size/capacity are 1 more // than usually reported by a typical string class. + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_None; + ImGui::CheckboxFlags("ImGuiInputTextFlags_WordWrap", &flags, ImGuiInputTextFlags_WordWrap); + static ImVector my_str; if (my_str.empty()) my_str.push_back(0); - Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16)); + Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity()); ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index 021a24d98..8bd05c326 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1015,15 +1015,6 @@ enum ImGuiHoveredFlagsPrivate_ // Extend ImGuiInputTextFlags_ enum ImGuiInputTextFlagsPrivate_ { - // [Experimental] - // Word-wrapping caveats: - // - Not well tested yet. Please report any incorrect cursor movement, selection behavior etc. bug to https://github.com/ocornut/imgui/issues/3237. - // - With our current design it is _much_ slower than a regular text field. Editing a <50K buffer will generally be ok, but editing a 1MB buffer will waste meaningful amount of CPU. - // We are likely to not make the feature public until this is fixed (which requires bigger changes to InputText will be be generally desirable for this and other features) - // - Wrapping of long words/sections (e.g. words that are larger than available width) is currently visually not pleasing. - // - Vertical scrollbar is currently always visible. - ImGuiInputTextFlags_WordWrap = 1 << 24, // InputTextMultine(): wrap lines that are too long. (Ref #3237, #952, #1062) - // [Internal] ImGuiInputTextFlags_Multiline = 1 << 26, // For internal use by InputTextMultiline() ImGuiInputTextFlags_MergedItem = 1 << 27, // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. From b6a33f8ce15fa8c7ad0d04b189f93cc1321ef51a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Sep 2025 15:05:23 +0200 Subject: [PATCH 1328/2359] InputText: Word-Wrap: amend 7f1e2bb to avoid triggering static analyzer. (#3237, #952, #1062, #7363) And generally more logical this way anyhow. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5ba4293a7..4b680622f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4594,7 +4594,7 @@ static ImVec2 InputTextLineIndexGetPosOffset(ImGuiContext& g, ImGuiInputTextStat int* it_end = line_index->Offsets.end(); const int* it = ImLowerBound(it_begin, it_end, cursor_n); if (it > it_begin) - if (it == it_end || *it != cursor_n || (state->WrapWidth > 0.0f && cursor_ptr[-1] != '\n' && cursor_ptr[-1] != 0 && state != NULL && state->LastMoveDirectionLR == ImGuiDir_Right)) + if (it == it_end || *it != cursor_n || (state != NULL && state->WrapWidth > 0.0f && state->LastMoveDirectionLR == ImGuiDir_Right && cursor_ptr[-1] != '\n' && cursor_ptr[-1] != 0)) it--; const int line_no = (it == it_begin) ? 0 : line_index->Offsets.index_from_ptr(it); From 36133d8ac490bf8bae3390a398420ea948fd7ad9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Sep 2025 16:03:18 +0200 Subject: [PATCH 1329/2359] InputText: Word-Wrap: hide vertical scrollbar but takes its width into account. (#3237, #952, #1062, #7363) Also increase IMGUI_VERSION_NUM for good measure, forgot to increase it when moving to public api. --- docs/CHANGELOG.txt | 6 +++--- imgui.h | 6 +++--- imgui_widgets.cpp | 14 ++++++++------ 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b50ad6816..bff030352 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,12 +56,12 @@ Other Changes: window has the ImGuiWindowFlags_NoNavFocus flag. (#8914) - Bullet: fixed tesselation amount which looked out of place in very large sizes. - InputText: added ImGuiInputTextFlags_WordWrap flag to word-wrap multi-line buffers. - (#3237, #952, #1062, #7363) + (#3237, #952, #1062, #7363). Current caveats: - This is marked as beta because not being tested enough. Please report any incorrect cursor movement, selection behavior etc. bug to #3237. - - Vertical scrollbar is made always visible. - - Wrapping points are not ideal. Wrapping of long words/sections (e.g. words + - Wrapping style is not ideal. Wrapping of long words/sections (e.g. words larger than total available width) may be particularly unpleasing. + - Wrapping width needs to always account for the possibility of a vertical scrollbar. - It is currently much slower than regular text fields. - Ballpark estimate of cost on my 2019 desktop PC: For a 100 KB text buffer: +~0.3 ms/+~1.0 ms (Optimized vs Debug builds). diff --git a/imgui.h b/imgui.h index 58c63f44a..8af72e2fc 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.3 WIP" -#define IMGUI_VERSION_NUM 19227 +#define IMGUI_VERSION_NUM 19228 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -1267,8 +1267,8 @@ enum ImGuiInputTextFlags_ // Multi-line Word-Wrapping [BETA] // - Not well tested yet. Please report any incorrect cursor movement, selection behavior etc. bug to https://github.com/ocornut/imgui/issues/3237. - // - Vertical scrollbar is made always visible. - // - Wrapping points are not ideal. Wrapping of long words/sections (e.g. words larger than total available width) may be particularly unpleasing. + // - Wrapping style is not ideal. Wrapping of long words/sections (e.g. words larger than total available width) may be particularly unpleasing. + // - Wrapping width needs to always account for the possibility of a vertical scrollbar. // - It is much slower than regular text fields. // Ballpark estimate of cost on my 2019 desktop PC: for a 100 KB text buffer: +~0.3 ms (Optimized) / +~1.0 ms (Debug build). // The CPU cost is very roughly proportional to text length, so a 10 KB buffer should cost about ten times less. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4b680622f..50a2c896d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4672,10 +4672,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges - ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoMove; - if (flags & ImGuiInputTextFlags_WordWrap) - window_flags |= ImGuiWindowFlags_AlwaysVerticalScrollbar; // FIXME-WORDWRAP: Makes things much simpler. Otherwise requires more work to track cursor reliably and avoid one-frame glitch. - bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, window_flags); + bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove); g.NavActivateId = backup_activate_id; PopStyleVar(3); PopStyleColor(); @@ -4715,11 +4712,16 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0; const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0; - const bool is_wordwrap = (flags & ImGuiInputTextFlags_WordWrap) != 0; - const float wrap_width = is_wordwrap ? GetContentRegionAvail().x : 0.0f; if (is_resizable) IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag! + // Word-wrapping: enforcing a fixed width not altered by vertical scrollbar makes things easier, notably to track cursor reliably and avoid one-frame glitches. + // Instead of using ImGuiWindowFlags_AlwaysVerticalScrollbar we account for that space if the scrollbar is not visible. + const bool is_wordwrap = (flags & ImGuiInputTextFlags_WordWrap) != 0; + float wrap_width = 0.0f; + if (is_wordwrap) + wrap_width = ImMax(1.0f, GetContentRegionAvail().x + (draw_window->ScrollbarY ? 0.0f : -g.Style.ScrollbarSize)); + const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateId == id) && ((g.NavActivateFlags & ImGuiActivateFlags_PreferInput) || (g.NavInputSource == ImGuiInputSource_Keyboard))); const bool user_clicked = hovered && io.MouseClicked[0]; From 6d25cb844b1f828bc310f174d67b0fb1961701a5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Sep 2025 16:41:05 +0200 Subject: [PATCH 1330/2359] CI: switch iOS build to macos-14 runner as macos-latest currently fails. --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4ff14341e..783615aec 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -558,7 +558,7 @@ jobs: run: xcodebuild -project examples/example_apple_opengl2/example_apple_opengl2.xcodeproj -target example_osx_opengl2 iOS: - runs-on: macos-latest + runs-on: macos-14 steps: - uses: actions/checkout@v4 From 9f13684d706e7c717a208835955f13d19e0c23cc Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Sep 2025 20:57:04 +0200 Subject: [PATCH 1331/2359] Examples: GLFW+OpenGL2: Fixed not applying content scale. (#8921) Note that this requires GLFW 3.3. --- docs/CHANGELOG.txt | 1 + examples/example_glfw_opengl2/main.cpp | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bff030352..d4523f7da 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -107,6 +107,7 @@ Other Changes: while navigating and to not close popup automatically. - CI: Updates Windows CI to use a more recent VulkanSDK. (#8925, #8778) [@yaz0r] - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] +- Examples: GLFW+OpenGL2: Fixed not applying content scale. (#8921) - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used multi-viewport mode. (#8892) [@PTSVU] diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 411a5891d..4c19ffcc3 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -40,7 +40,8 @@ int main(int, char**) return 1; // Create window with graphics context - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL2 example", nullptr, nullptr); + float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); // Valid on GLFW 3.3+ only + GLFWwindow* window = glfwCreateWindow((int)(1280 * main_scale), (int)(800 * main_scale), "Dear ImGui GLFW+OpenGL2 example", nullptr, nullptr); if (window == nullptr) return 1; glfwMakeContextCurrent(window); @@ -57,6 +58,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL2_Init(); From cd476b27f8885ff7d81de032f26973131fa78ecb Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 12 Sep 2025 21:32:46 +0200 Subject: [PATCH 1332/2359] Examples: GLFW+Vulkan: Fixed not applying content scale. (#8921, #8756) --- docs/CHANGELOG.txt | 2 +- examples/example_glfw_vulkan/main.cpp | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d4523f7da..0a0acde7c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -107,7 +107,7 @@ Other Changes: while navigating and to not close popup automatically. - CI: Updates Windows CI to use a more recent VulkanSDK. (#8925, #8778) [@yaz0r] - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] -- Examples: GLFW+OpenGL2: Fixed not applying content scale. (#8921) +- Examples: GLFW+OpenGL2, GLFW+Vulkan: Fixed not applying content scale. (#8921, #8756) - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used multi-viewport mode. (#8892) [@PTSVU] diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 7ad9778f1..ebc78bdd5 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -357,7 +357,8 @@ int main(int, char**) // Create window with Vulkan context glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Vulkan example", nullptr, nullptr); + float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); // Valid on GLFW 3.3+ only + GLFWwindow* window = glfwCreateWindow((int)(1280 * main_scale), (int)(800 * main_scale), "Dear ImGui GLFW+Vulkan example", nullptr, nullptr); if (!glfwVulkanSupported()) { printf("GLFW: Vulkan Not Supported\n"); @@ -393,6 +394,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForVulkan(window, true); ImGui_ImplVulkan_InitInfo init_info = {}; From 22a6a83c5467ca6b15c9bda4203b82afeca8fa5e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 15:16:42 +0200 Subject: [PATCH 1333/2359] Backends: SDL3: use SDL_GetWindowDisplayScale() on Mac to output DisplayFrameBufferScale. The function is more reliable during resolution changes e.g. going fullscreen. (#8703, #4414) --- backends/imgui_impl_sdl3.cpp | 14 ++++++++++++-- docs/CHANGELOG.txt | 3 +++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 48e766bcd..17613d30a 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-15: Use SDL_GetWindowDisplayScale() on Mac to output DisplayFrameBufferScale. The function is more reliable during resolution changes e.g. going fullscreen. (#8703, #4414) // 2025-06-27: IME: avoid calling SDL_StartTextInput() again if already active. (#8727) // 2025-04-22: IME: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. // 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) @@ -778,15 +779,24 @@ static void ImGui_ImplSDL3_UpdateGamepads() static void ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(SDL_Window* window, ImVec2* out_size, ImVec2* out_framebuffer_scale) { int w, h; - int display_w, display_h; SDL_GetWindowSize(window, &w, &h); if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) w = h = 0; + +#if defined(__APPLE__) + float fb_scale_x = SDL_GetWindowDisplayScale(window); // Seems more reliable during resolution change (#8703) + float fb_scale_y = fb_scale_x; +#else + int display_w, display_h; SDL_GetWindowSizeInPixels(window, &display_w, &display_h); + float fb_scale_x = (w > 0) ? (float)display_w / w : 1.0f; + float fb_scale_y = (h > 0) ? (float)display_h / h : 1.0f; +#endif + if (out_size != nullptr) *out_size = ImVec2((float)w, (float)h); if (out_framebuffer_scale != nullptr) - *out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / w, (float)display_h / h) : ImVec2(1.0f, 1.0f); + *out_framebuffer_scale = ImVec2(fb_scale_x, fb_scale_y); } void ImGui_ImplSDL3_NewFrame() diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0a0acde7c..db4587e69 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -108,6 +108,9 @@ Other Changes: - CI: Updates Windows CI to use a more recent VulkanSDK. (#8925, #8778) [@yaz0r] - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] - Examples: GLFW+OpenGL2, GLFW+Vulkan: Fixed not applying content scale. (#8921, #8756) +- Backends: SDL3: use SDL_GetWindowDisplayScale() on Mac to obtain DisplayFrameBufferScale, + fixing incorrect values during resolution changes e.g. going fullscreen. + (#8703, #4414) [@jclounge] - Backends: SDL_GPU: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and PresentMode to configure how secondary viewports are created. Currently only used multi-viewport mode. (#8892) [@PTSVU] From e044d99710cc1d7c451259cfeb440d5f84701466 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 16:33:56 +0200 Subject: [PATCH 1334/2359] Examples: standardized all examples to have a base window size of 1280x800. --- examples/example_allegro5/main.cpp | 2 +- examples/example_apple_metal/main.mm | 2 +- examples/example_apple_opengl2/main.mm | 2 +- examples/example_glfw_metal/main.mm | 2 +- examples/example_glfw_wgpu/main.cpp | 2 +- examples/example_glut_opengl2/main.cpp | 2 +- examples/example_sdl2_directx11/main.cpp | 2 +- examples/example_sdl2_metal/main.mm | 2 +- examples/example_sdl2_opengl2/main.cpp | 2 +- examples/example_sdl2_opengl3/main.cpp | 2 +- examples/example_sdl2_sdlrenderer2/main.cpp | 2 +- examples/example_sdl2_vulkan/main.cpp | 2 +- examples/example_sdl3_metal/main.mm | 2 +- examples/example_sdl3_opengl3/main.cpp | 2 +- examples/example_sdl3_sdlgpu3/main.cpp | 2 +- examples/example_sdl3_sdlrenderer3/main.cpp | 2 +- examples/example_sdl3_vulkan/main.cpp | 2 +- 17 files changed, 17 insertions(+), 17 deletions(-) diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index cde2c676a..08b809e35 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -28,7 +28,7 @@ int main(int, char**) al_install_mouse(); al_init_primitives_addon(); al_set_new_display_flags(ALLEGRO_RESIZABLE); - ALLEGRO_DISPLAY* display = al_create_display(1280, 720); + ALLEGRO_DISPLAY* display = al_create_display(1280, 800); al_set_window_title(display, "Dear ImGui Allegro 5 example"); ALLEGRO_EVENT_QUEUE* queue = al_create_event_queue(); al_register_event_source(queue, al_get_display_event_source(display)); diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 0349dfbdc..4904973ac 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -94,7 +94,7 @@ -(void)loadView { - self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 720)]; + self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 800)]; } -(void)viewDidLoad diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 9b4fa1860..d7aa7eb5b 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -171,7 +171,7 @@ if (_window != nil) return (_window); - NSRect viewRect = NSMakeRect(100.0, 100.0, 100.0 + 1280.0, 100 + 720.0); + NSRect viewRect = NSMakeRect(100.0, 100.0, 100.0 + 1280.0, 100 + 800.0); _window = [[NSWindow alloc] initWithContentRect:viewRect styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable|NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:YES]; [_window setTitle:@"Dear ImGui OSX+OpenGL2 Example"]; diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index 9f4b82c4f..4ec8b5927 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -61,7 +61,7 @@ int main(int, char**) // Create window with graphics context glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Metal example", nullptr, nullptr); + GLFWwindow* window = glfwCreateWindow(1280, 800, "Dear ImGui GLFW+Metal example", nullptr, nullptr); if (window == nullptr) return 1; diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index e30df5662..670dd08c2 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -37,7 +37,7 @@ static WGPUSurface wgpu_surface = nullptr; static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm; static WGPUSwapChain wgpu_swap_chain = nullptr; static int wgpu_swap_chain_width = 1280; -static int wgpu_swap_chain_height = 720; +static int wgpu_swap_chain_height = 800; // Forward declarations static bool InitWGPU(GLFWwindow* window); diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index e72b94830..72da416f9 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -48,7 +48,7 @@ int main(int argc, char** argv) glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE); - glutInitWindowSize(1280, 720); + glutInitWindowSize(1280, 800); glutCreateWindow("Dear ImGui GLUT+OpenGL2 Example"); // Setup GLUT display function diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index 2e347752f..a2b39f362 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -50,7 +50,7 @@ int main(int, char**) // Setup window float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index 97a643759..80c7e7b1a 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -60,7 +60,7 @@ int main(int, char**) // Enable native IME. SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL+Metal example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL+Metal example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 800, SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); if (window == nullptr) { printf("Error creating window: %s\n", SDL_GetError()); diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index 7385f4cd1..a06b58c8c 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -47,7 +47,7 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index c59836f6e..96631271b 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -81,7 +81,7 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 76f17d3f6..60b365e6e 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -44,7 +44,7 @@ int main(int, char**) // Create window with SDL_Renderer graphics context float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+SDL_Renderer example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+SDL_Renderer example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index de6745623..4a1228058 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -360,7 +360,7 @@ int main(int, char**) // Create window with Vulkan graphics context float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index 98c4a9490..022e0f432 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -30,7 +30,7 @@ int main(int, char**) // Create SDL window graphics context float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_METAL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Metal example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Metal example", (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 25b6b1937..36b5e2eba 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -70,7 +70,7 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index bef16fe5b..3f797ecd6 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -37,7 +37,7 @@ int main(int, char**) // Create SDL window graphics context float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_GPU example", (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index f98986943..2256b7da7 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -34,7 +34,7 @@ int main(int, char**) // Create window with SDL_Renderer graphics context float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 743e68dba..dd9a460c9 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -355,7 +355,7 @@ int main(int, char**) // Create window with Vulkan graphics context float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Vulkan example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Vulkan example", (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); From 3c6c5692b894252cdf3c5e6dae7cc5405b1f07b2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 16:40:10 +0200 Subject: [PATCH 1335/2359] Examples: Win32+Vulkan, GLFW+Metal: Fixed not applying content scale. (#8921, #8756) Somehow it breaks in Win32+OpenGL3 example: when enabled Win32 applies some extra scale. --- docs/CHANGELOG.txt | 3 +- examples/example_glfw_metal/main.mm | 47 ++++++++++++++----------- examples/example_win32_opengl3/main.cpp | 12 +++++-- examples/example_win32_vulkan/main.cpp | 14 ++++++-- 4 files changed, 49 insertions(+), 27 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index db4587e69..766473516 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -107,7 +107,8 @@ Other Changes: while navigating and to not close popup automatically. - CI: Updates Windows CI to use a more recent VulkanSDK. (#8925, #8778) [@yaz0r] - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] -- Examples: GLFW+OpenGL2, GLFW+Vulkan: Fixed not applying content scale. (#8921, #8756) +- Examples: GLFW+OpenGL2, GLFW+Vulkan, GLFW+Metal, Win32+Vulkan: Fixed not applying + content scale consistently with other examples. (#8921, #8756) - Backends: SDL3: use SDL_GetWindowDisplayScale() on Mac to obtain DisplayFrameBufferScale, fixing incorrect values during resolution changes e.g. going fullscreen. (#8703, #4414) [@jclounge] diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index 4ec8b5927..cc86d655c 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -27,17 +27,40 @@ static void glfw_error_callback(int error, const char* description) int main(int, char**) { + glfwSetErrorCallback(glfw_error_callback); + if (!glfwInit()) + return 1; + + // Create window with graphics context + float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); // Valid on GLFW 3.3+ only + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + GLFWwindow* window = glfwCreateWindow((int)(1280 * main_scale), (int)(800 * main_scale), "Dear ImGui GLFW+Metal example", nullptr, nullptr); + if (window == nullptr) + return 1; + // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls - // Setup style + // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + + id device = MTLCreateSystemDefaultDevice(); + id commandQueue = [device newCommandQueue]; + + // Setup Platform/Renderer backends + ImGui_ImplGlfw_InitForOpenGL(window, true); + ImGui_ImplMetal_Init(device); + // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. @@ -54,24 +77,6 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); //IM_ASSERT(font != nullptr); - // Setup window - glfwSetErrorCallback(glfw_error_callback); - if (!glfwInit()) - return 1; - - // Create window with graphics context - glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - GLFWwindow* window = glfwCreateWindow(1280, 800, "Dear ImGui GLFW+Metal example", nullptr, nullptr); - if (window == nullptr) - return 1; - - id device = MTLCreateSystemDefaultDevice(); - id commandQueue = [device newCommandQueue]; - - // Setup Platform/Renderer backends - ImGui_ImplGlfw_InitForOpenGL(window, true); - ImGui_ImplMetal_Init(device); - NSWindow *nswin = glfwGetCocoaWindow(window); CAMetalLayer *layer = [CAMetalLayer layer]; layer.device = device; diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 8748ab777..648d0d969 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -36,11 +36,14 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Main code int main(int, char**) { + // Make process DPI aware and obtain main monitor scale + //ImGui_ImplWin32_EnableDpiAwareness(); // FIXME: This somehow doesn't work in the Win32+OpenGL example. Why? + float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); + // Create application window - //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEXW wc = { sizeof(wc), CS_OWNDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; ::RegisterClassExW(&wc); - HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+OpenGL3 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+OpenGL3 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr); // Initialize OpenGL if (!CreateDeviceWGL(hwnd, &g_MainWindow)) @@ -67,6 +70,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplWin32_InitForOpenGL(hwnd); ImGui_ImplOpenGL3_Init(); diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index aa80e8696..b4b3a0860 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -342,11 +342,14 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Main code int main(int, char**) { + // Make process DPI aware and obtain main monitor scale + ImGui_ImplWin32_EnableDpiAwareness(); + float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); + // Create application window - //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; ::RegisterClassExW(&wc); - HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+Vulkan Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+Vulkan Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr); ImVector extensions; extensions.push_back("VK_KHR_surface"); @@ -369,7 +372,7 @@ int main(int, char**) // Show the window // FIXME: Retrieve client size from window itself. ImGui_ImplVulkanH_Window* wd = &g_MainWindowData; - SetupVulkanWindow(wd, surface, 1280, 800); + SetupVulkanWindow(wd, surface, (int)(1280 * main_scale), (int)(800 * main_scale)); ::ShowWindow(hwnd, SW_SHOWDEFAULT); ::UpdateWindow(hwnd); @@ -384,6 +387,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplVulkan_InitInfo init_info = {}; From 10d0162378261ef3cbc92fb684236d7a0a5ac83a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 18:20:07 +0200 Subject: [PATCH 1336/2359] Backends: GLFW: added ImGui_ImplGlfw_IsWayland(). (#8921, #8920) (technically presently untested but we've researched this) --- backends/imgui_impl_glfw.cpp | 51 ++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 0cb49fda2..a8696ade2 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -104,20 +104,25 @@ // GLFW #include - #ifdef _WIN32 #undef APIENTRY -#ifndef GLFW_EXPOSE_NATIVE_WIN32 +#ifndef GLFW_EXPOSE_NATIVE_WIN32 // for glfwGetWin32Window() #define GLFW_EXPOSE_NATIVE_WIN32 #endif -#include // for glfwGetWin32Window() -#endif -#ifdef __APPLE__ -#ifndef GLFW_EXPOSE_NATIVE_COCOA +#elif defined(__APPLE__) +#ifndef GLFW_EXPOSE_NATIVE_COCOA // for glfwGetCocoaWindow() #define GLFW_EXPOSE_NATIVE_COCOA #endif -#include // for glfwGetCocoaWindow() +#elif !defined(__EMSCRIPTEN__) +#ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) +#define GLFW_EXPOSE_NATIVE_X11 #endif +#ifndef GLFW_EXPOSE_NATIVE_WAYLAND +#define GLFW_EXPOSE_NATIVE_WAYLAND +#endif +#endif +#include +#undef Status // X11 headers are leaking this. #ifndef _WIN32 #include // for usleep() #endif @@ -144,8 +149,14 @@ #define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName() #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError() +#define GLFW_HAS_GETPLATFORM (GLFW_VERSION_COMBINED >= 3400) // 3.4+ glfwGetPlatform() +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) +#define GLFW_HAS_X11_OR_WAYLAND 1 +#else +#define GLFW_HAS_X11_OR_WAYLAND 0 +#endif -// Map GLFWWindow* to ImGuiContext*. +// Map GLFWWindow* to ImGuiContext*. // - Would be simpler if we could use glfwSetWindowUserPointer()/glfwGetWindowUserPointer(), but this is a single and shared resource. // - Would be simpler if we could use e.g. std::map<> as well. But we don't. // - This is not particularly optimized as we expect size to be small and queries to be rare. @@ -155,14 +166,14 @@ static void ImGui_ImplGlfw_ContextMap_Add(GLFWwindow* window, ImGuiContext* ctx) static void ImGui_ImplGlfw_ContextMap_Remove(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) { g_ContextMap.erase_unsorted(&entry); return; } } static ImGuiContext* ImGui_ImplGlfw_ContextMap_Get(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) return entry.Context; return nullptr; } -// GLFW data enum GlfwClientApi { - GlfwClientApi_Unknown, GlfwClientApi_OpenGL, GlfwClientApi_Vulkan, + GlfwClientApi_Unknown, // Anything else fits here. }; +// GLFW data struct ImGui_ImplGlfw_Data { ImGuiContext* Context; @@ -172,6 +183,7 @@ struct ImGui_ImplGlfw_Data GLFWwindow* MouseWindow; GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT]; ImVec2 LastValidMousePos; + bool IsWayland; bool InstalledCallbacks; bool CallbacksChainForAllWindows; char BackendPlatformName[32]; @@ -216,6 +228,23 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData(GLFWwindow* window) } // Functions +static bool ImGui_ImplGlfw_IsWayland() +{ +#if GLFW_HAS_X11_OR_WAYLAND + return false; +#elif GLFW_HAS_GETPLATFORM + return glfwGetPlatform() == GLFW_PLATFORM_WAYLAND; +#else + const char* version = glfwGetVersionString(); + if (strstr(version, "Wayland") == NULL) // e.g. Ubuntu 22.04 ships with GLFW 3.3.6 compiled without Wayland + return false; +#ifdef GLFW_EXPOSE_NATIVE_X11 + if (glfwGetX11Display() != NULL) + return false; +#endif + return true; +#endif +} // Not static to allow third-party code to use that if they want to (but undocumented) ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode); @@ -365,7 +394,6 @@ static bool ImGui_ImplGlfw_ShouldChainCallback(ImGui_ImplGlfw_Data* bd, GLFWwind void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); - if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackMousebutton(window, button, action, mods); @@ -630,6 +658,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw bd->Context = ImGui::GetCurrentContext(); bd->Window = window; bd->Time = 0.0; + bd->IsWayland = ImGui_ImplGlfw_IsWayland(); ImGui_ImplGlfw_ContextMap_Add(window, bd->Context); ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); From 2675b7ca26978e76f6ee4fbba19cf3b9a2034661 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 18:49:05 +0200 Subject: [PATCH 1337/2359] Backends: GLFW: Content Scales always reported as 1.0 on Wayland, FramebufferScale always reported as 1.0 on X11. (#8920, #8921) --- backends/imgui_impl_glfw.cpp | 19 ++++++++++++++++++- docs/CHANGELOG.txt | 6 ++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index a8696ade2..8e391b44a 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-15: Content Scales always reported as 1.0 on Wayland. FramebufferScale are always reported as 1.0 on X11. (#8920, #8921) // 2025-07-08: Made ImGui_ImplGlfw_GetContentScaleForWindow(), ImGui_ImplGlfw_GetContentScaleForMonitor() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) // 2025-06-18: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069) // 2025-06-11: Added ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) and ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) helper to facilitate making DPI-aware apps. @@ -906,6 +907,11 @@ static void ImGui_ImplGlfw_UpdateGamepads() // - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle. float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) { +#if GLFW_HAS_X11_OR_WAYLAND + if (ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window)) + if (bd->IsWayland) + return 1.0f; +#endif #if GLFW_HAS_PER_MONITOR_DPI && !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(__ANDROID__)) float x_scale, y_scale; glfwGetWindowContentScale(window, &x_scale, &y_scale); @@ -918,6 +924,10 @@ float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) { +#if GLFW_HAS_X11_OR_WAYLAND + if (ImGui_ImplGlfw_IsWayland()) // We can't access our bd->IsWayland cache for a monitor. + return 1.0f; +#endif #if GLFW_HAS_PER_MONITOR_DPI && !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(__ANDROID__)) float x_scale, y_scale; glfwGetMonitorContentScale(monitor, &x_scale, &y_scale); @@ -934,10 +944,17 @@ static void ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(GLFWwindow* window, int display_w, display_h; glfwGetWindowSize(window, &w, &h); glfwGetFramebufferSize(window, &display_w, &display_h); + float fb_scale_x = (w > 0) ? (float)display_w / w : 1.0f; + float fb_scale_y = (h > 0) ? (float)display_h / h : 1.0f; +#if GLFW_HAS_X11_OR_WAYLAND + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (!bd->IsWayland) + fb_scale_x = fb_scale_y = 1.0f; +#endif if (out_size != nullptr) *out_size = ImVec2((float)w, (float)h); if (out_framebuffer_scale != nullptr) - *out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / (float)w, (float)display_h / (float)h) : ImVec2(1.0f, 1.0f); + *out_framebuffer_scale = ImVec2(fb_scale_x, fb_scale_y); } void ImGui_ImplGlfw_NewFrame() diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 766473516..5cd953ea3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -109,6 +109,12 @@ Other Changes: - Examples: Android: Android+OpenGL3: update Gradle project (#8888, #8878) [@scribam] - Examples: GLFW+OpenGL2, GLFW+Vulkan, GLFW+Metal, Win32+Vulkan: Fixed not applying content scale consistently with other examples. (#8921, #8756) +- Backends: GLFW: distinguish X11 vs Wayland to fix various scaling issues. + (#8920, #8921) [@TheBrokenRail, @pthom, @ocornut] + - window/monitor content scales are always reported as 1.0 on Wayland. + - framebuffer scales are always reported as 1.0 on X11. (#8920, #8921) +- Backends: GLFW: + [@TheBrokenRail, @pthom, @ocornut] - Backends: SDL3: use SDL_GetWindowDisplayScale() on Mac to obtain DisplayFrameBufferScale, fixing incorrect values during resolution changes e.g. going fullscreen. (#8703, #4414) [@jclounge] From 72c00f39c14806fe1bc60219886c867c4c518e9f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 19:16:05 +0200 Subject: [PATCH 1338/2359] Backends: GLFW: fix ImGui_ImplGlfw_IsWayland() amend broken 10d0162. (#8921, #8920) Accidentally broke this while shuffling code... --- backends/imgui_impl_glfw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 8e391b44a..5a897eed8 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -231,7 +231,7 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData(GLFWwindow* window) // Functions static bool ImGui_ImplGlfw_IsWayland() { -#if GLFW_HAS_X11_OR_WAYLAND +#if !GLFW_HAS_X11_OR_WAYLAND return false; #elif GLFW_HAS_GETPLATFORM return glfwGetPlatform() == GLFW_PLATFORM_WAYLAND; From d92c8c6aff0fd11f28a542160c821218a63d43d9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 19:20:56 +0200 Subject: [PATCH 1339/2359] Backends: SDL2: Content Scales are always reported as 1.0 on Wayland. (#8921) SDL_GetDisplayDPI() seems generally broken on X11/Wayland, but our logs shows that on Wayland we get both a content scale from SDL_GetDisplayDPI() and a framebuffer scale. --- backends/imgui_impl_glfw.cpp | 2 +- backends/imgui_impl_sdl2.cpp | 4 ++++ docs/CHANGELOG.txt | 6 +++--- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 5a897eed8..42e02ccc8 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -29,7 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-09-15: Content Scales always reported as 1.0 on Wayland. FramebufferScale are always reported as 1.0 on X11. (#8920, #8921) +// 2025-09-15: Content Scales are always reported as 1.0 on Wayland. FramebufferScale are always reported as 1.0 on X11. (#8920, #8921) // 2025-07-08: Made ImGui_ImplGlfw_GetContentScaleForWindow(), ImGui_ImplGlfw_GetContentScaleForMonitor() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) // 2025-06-18: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069) // 2025-06-11: Added ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) and ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) helper to facilitate making DPI-aware apps. diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 291edb811..08e7988e2 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-15: Content Scales are always reported as 1.0 on Wayland. (#8921) // 2025-07-08: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) // 2025-06-11: Added ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) and ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) helper to facilitate making DPI-aware apps. // 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) @@ -719,6 +720,9 @@ float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) { + const char* sdl_driver = SDL_GetCurrentVideoDriver(); + if (sdl_driver && strcmp(sdl_driver, "wayland") == 0) + return 1.0f; #if SDL_HAS_PER_MONITOR_DPI #if !defined(__APPLE__) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) float dpi = 0.0f; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5cd953ea3..9495d5af1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -112,9 +112,9 @@ Other Changes: - Backends: GLFW: distinguish X11 vs Wayland to fix various scaling issues. (#8920, #8921) [@TheBrokenRail, @pthom, @ocornut] - window/monitor content scales are always reported as 1.0 on Wayland. - - framebuffer scales are always reported as 1.0 on X11. (#8920, #8921) -- Backends: GLFW: - [@TheBrokenRail, @pthom, @ocornut] + - framebuffer scales are always reported as 1.0 on X11. +- Backends: SDL2: window/monitor content scales are always reported as 1.0 on Wayland. + (#8920, #8921) [@TheBrokenRail, @pthom, @ocornut] - Backends: SDL3: use SDL_GetWindowDisplayScale() on Mac to obtain DisplayFrameBufferScale, fixing incorrect values during resolution changes e.g. going fullscreen. (#8703, #4414) [@jclounge] From 6274ca4266670fc4297b0377579978157098bbe9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 19:28:01 +0200 Subject: [PATCH 1340/2359] Backends: GLFW: fixed build for Emscripten which doesn't expose glfw3native.h. Amend 10d0162 --- backends/imgui_impl_glfw.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 42e02ccc8..8a646b5dd 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -110,10 +110,12 @@ #ifndef GLFW_EXPOSE_NATIVE_WIN32 // for glfwGetWin32Window() #define GLFW_EXPOSE_NATIVE_WIN32 #endif +#include #elif defined(__APPLE__) #ifndef GLFW_EXPOSE_NATIVE_COCOA // for glfwGetCocoaWindow() #define GLFW_EXPOSE_NATIVE_COCOA #endif +#include #elif !defined(__EMSCRIPTEN__) #ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) #define GLFW_EXPOSE_NATIVE_X11 @@ -121,8 +123,8 @@ #ifndef GLFW_EXPOSE_NATIVE_WAYLAND #define GLFW_EXPOSE_NATIVE_WAYLAND #endif -#endif #include +#endif #undef Status // X11 headers are leaking this. #ifndef _WIN32 #include // for usleep() From 431f2c5abd2065be04772fedfe02120805305a97 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Sep 2025 19:32:03 +0200 Subject: [PATCH 1341/2359] InputText: fixed dubious code handling ImGuiInputTextFlags_EscapeClearsAll. Specifically the missing = 0. Somehow only now got reported by Emscripten CI. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 50a2c896d..412835892 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5180,7 +5180,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ apply_new_text = ""; apply_new_text_length = 0; value_changed = true; - IMSTB_TEXTEDIT_CHARTYPE empty_string; + char empty_string = 0; stb_textedit_replace(state, state->Stb, &empty_string, 0); } else if (strcmp(state->TextA.Data, state->TextToRevertTo.Data) != 0) From f6890ed007da2efee80a91f140bcb57a68811c22 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Sep 2025 16:34:33 +0200 Subject: [PATCH 1342/2359] Nav, Inputs: fixed a crash that could occur when opening a popup following the processing of a global shortcut while no windows were focused. Regression test: "window_popup_from_shortcut" --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9495d5af1..b1575131c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,8 @@ Other Changes: e.g. using clipper with ItemsHeight=1 in order to clip in pixel units. (#8886) - Nav: fixed Ctrl+Tab window appearing as empty when the sole active and focused window has the ImGuiWindowFlags_NoNavFocus flag. (#8914) +- Nav: fixed a crash that could occur when opening a popup following the processing + of a global shortcut while no windows were focused. - Bullet: fixed tesselation amount which looked out of place in very large sizes. - InputText: added ImGuiInputTextFlags_WordWrap flag to word-wrap multi-line buffers. (#3237, #952, #1062, #7363). Current caveats: diff --git a/imgui.cpp b/imgui.cpp index eb84cdd4c..514f1ecdc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13413,6 +13413,9 @@ static ImVec2 ImGui::NavCalcPreferredRefPos() const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; + if (source != ImGuiInputSource_Mouse && !activated_shortcut && window == NULL) + source = ImGuiInputSource_Mouse; + // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag. if (source == ImGuiInputSource_Mouse) { @@ -13432,7 +13435,7 @@ static ImVec2 ImGui::NavCalcPreferredRefPos() ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]); // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?) - if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX)) + if (window != NULL && window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX)) { ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window); ref_rect.Translate(window->Scroll - next_scroll); From 6d834d325e3ccba9a972f974d281dbe5c17a31da Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Sep 2025 17:36:47 +0200 Subject: [PATCH 1343/2359] Debug Tools: ID Stack Tool: fixed misleading/unnecessary run of UpdateDebugToolStackQueries() on first frame. (#4631) `if (g.FrameCount != tool->LastActiveFrame + 1)` test failing on first frame. Was not harmful but probably confusing in a debugger. --- imgui_internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 8bd05c326..29cfda0e7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2134,7 +2134,7 @@ struct ImGuiIDStackTool ImGuiTextBuffer ResultPathsBuf; ImGuiTextBuffer ResultTempBuf; - ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; } + ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); LastActiveFrame = -1; OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; } }; //----------------------------------------------------------------------------- From 7e473d38d31c6944c9039976947ef16b796dce7c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Sep 2025 17:52:50 +0200 Subject: [PATCH 1344/2359] Debug Tools: ID Stack Tool: internal renaming (should be no-op). --- imgui.cpp | 32 ++++++++++++++++---------------- imgui_internal.h | 4 ++-- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 514f1ecdc..94092c3e4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4069,7 +4069,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) WheelingWindowReleaseTimer = 0.0f; DebugDrawIdConflictsId = 0; - DebugHookIdInfo = 0; + DebugHookIdInfoId = 0; HoveredId = HoveredIdPreviousFrame = 0; HoveredIdPreviousFrameItemCount = 0; HoveredIdAllowOverlap = false; @@ -8980,7 +8980,7 @@ ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *Ctx; - if (g.DebugHookIdInfo == id) + if (g.DebugHookIdInfoId == id) ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end); #endif return id; @@ -8992,7 +8992,7 @@ ImGuiID ImGuiWindow::GetID(const void* ptr) ImGuiID id = ImHashData(&ptr, sizeof(void*), seed); #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *Ctx; - if (g.DebugHookIdInfo == id) + if (g.DebugHookIdInfoId == id) ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL); #endif return id; @@ -9004,7 +9004,7 @@ ImGuiID ImGuiWindow::GetID(int n) ImGuiID id = ImHashData(&n, sizeof(n), seed); #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *Ctx; - if (g.DebugHookIdInfo == id) + if (g.DebugHookIdInfoId == id) ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL); #endif return id; @@ -9067,7 +9067,7 @@ void ImGui::PushOverrideID(ImGuiID id) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; #ifndef IMGUI_DISABLE_DEBUG_TOOLS - if (g.DebugHookIdInfo == id) + if (g.DebugHookIdInfoId == id) DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL); #endif window->IDStack.push_back(id); @@ -9081,7 +9081,7 @@ ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed) ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *GImGui; - if (g.DebugHookIdInfo == id) + if (g.DebugHookIdInfoId == id) DebugHookIdInfo(id, ImGuiDataType_String, str, str_end); #endif return id; @@ -9092,7 +9092,7 @@ ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed) ImGuiID id = ImHashData(&n, sizeof(n), seed); #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *GImGui; - if (g.DebugHookIdInfo == id) + if (g.DebugHookIdInfoId == id) DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL); #endif return id; @@ -17661,21 +17661,21 @@ void ImGui::UpdateDebugToolStackQueries() ImGuiIDStackTool* tool = &g.DebugIDStackTool; // Clear hook when id stack tool is not visible - g.DebugHookIdInfo = 0; + g.DebugHookIdInfoId = 0; if (g.FrameCount != tool->LastActiveFrame + 1) return; // Update queries. The steps are: -1: query Stack, >= 0: query each stack item // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time - const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId; - if (tool->QueryId != query_id) + const ImGuiID query_main_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId; + if (tool->QueryMainId != query_main_id) { - tool->QueryId = query_id; + tool->QueryMainId = query_main_id; tool->StackLevel = -1; tool->Results.resize(0); tool->ResultPathsBuf.resize(0); } - if (query_id == 0) + if (query_main_id == 0) return; // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result) @@ -17687,10 +17687,10 @@ void ImGui::UpdateDebugToolStackQueries() // Update hook stack_level = tool->StackLevel; if (stack_level == -1) - g.DebugHookIdInfo = query_id; - if (stack_level >= 0 && stack_level < tool->Results.Size) + g.DebugHookIdInfoId = query_main_id; + else if (stack_level >= 0 && stack_level < tool->Results.Size) { - g.DebugHookIdInfo = tool->Results[stack_level].ID; + g.DebugHookIdInfoId = tool->Results[stack_level].ID; tool->Results[stack_level].QueryFrameCount++; } } @@ -17801,7 +17801,7 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) p = p_next; } } - Text("0x%08X", tool->QueryId); + Text("0x%08X", tool->QueryMainId); 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."); diff --git a/imgui_internal.h b/imgui_internal.h index 29cfda0e7..32d04df4e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2126,7 +2126,7 @@ struct ImGuiIDStackTool { int LastActiveFrame; int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level - ImGuiID QueryId; // ID to query details for + ImGuiID QueryMainId; // ID to query details for ImVector Results; bool OptHexEncodeNonAsciiChars; bool OptCopyToClipboardOnCtrlC; @@ -2216,7 +2216,7 @@ struct ImGuiContext // Item/widgets state and tracking information ImGuiID DebugDrawIdConflictsId; // Set when we detect multiple items with the same identifier - ImGuiID DebugHookIdInfo; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line] + ImGuiID DebugHookIdInfoId; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line] ImGuiID HoveredId; // Hovered widget, filled during the frame ImGuiID HoveredIdPreviousFrame; int HoveredIdPreviousFrameItemCount; // Count numbers of items using the same ID as last frame's hovered id From 9cf9d2be8366a0b4193cfb31da911184b0db6898 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Sep 2025 18:06:03 +0200 Subject: [PATCH 1345/2359] Debug Tools: ID Stack Tool: fixed a crash when using PushOverrideID(0) during a query. (#8937, #4631) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 11 +++++++++++ imgui_internal.h | 1 + 3 files changed, 14 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b1575131c..48de7e881 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -103,6 +103,8 @@ Other Changes: is now skipped. (#8904, #4631) - Debug Tools: ID Stack Tool: added option to hex-encode non-ASCII characters in output path. (#8904, #4631) +- Debug Tools: ID Stack Tool: fixed a crash when using PushOverrideID(0) during + a query. (#8937, #4631) - Debug Tools: Fixed assertion failure when opening a combo box while using io.ConfigDebugBeginReturnValueOnce/ConfigDebugBeginReturnValueLoop. (#8931) [@harrymander] - Demo: tweaked ShowFontSelector() and ShowStyleSelector() to update selection diff --git a/imgui.cpp b/imgui.cpp index 94092c3e4..88ceb1f6c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17662,6 +17662,7 @@ void ImGui::UpdateDebugToolStackQueries() // Clear hook when id stack tool is not visible g.DebugHookIdInfoId = 0; + tool->QueryHookActive = false; if (g.FrameCount != tool->LastActiveFrame + 1) return; @@ -17687,11 +17688,15 @@ void ImGui::UpdateDebugToolStackQueries() // Update hook stack_level = tool->StackLevel; if (stack_level == -1) + { g.DebugHookIdInfoId = query_main_id; + tool->QueryHookActive = true; + } else if (stack_level >= 0 && stack_level < tool->Results.Size) { g.DebugHookIdInfoId = tool->Results[stack_level].ID; tool->Results[stack_level].QueryFrameCount++; + tool->QueryHookActive = true; } } @@ -17701,11 +17706,17 @@ void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* dat ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiIDStackTool* tool = &g.DebugIDStackTool; + if (tool->QueryHookActive == false) + { + IM_ASSERT(id == 0); + return; + } // Step 0: stack query // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget. if (tool->StackLevel == -1) { + IM_ASSERT(tool->Results.Size == 0); tool->StackLevel++; tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo()); for (int n = 0; n < window->IDStack.Size + 1; n++) diff --git a/imgui_internal.h b/imgui_internal.h index 32d04df4e..d2a3f4d8b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2128,6 +2128,7 @@ struct ImGuiIDStackTool int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level ImGuiID QueryMainId; // ID to query details for ImVector Results; + bool QueryHookActive; // Used to disambiguate the case where DebugHookIdInfoId == 0 which is valid. bool OptHexEncodeNonAsciiChars; bool OptCopyToClipboardOnCtrlC; float CopyToClipboardLastTime; From 70a43f30886f73d4119785a9615bb7233c92d690 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Sep 2025 18:12:32 +0200 Subject: [PATCH 1346/2359] Fixed build with IMGUI_ENABLE_TEST_ENGINE. --- imgui.cpp | 2 +- imgui.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 88ceb1f6c..aff0f7b32 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17833,7 +17833,7 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) Text("- Path \"%s\"", tool->ResultTempBuf.c_str()); #ifdef IMGUI_ENABLE_TEST_ENGINE - Text("- Label \"%s\"", tool->QueryId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryId) : ""); + Text("- Label \"%s\"", tool->QueryMainId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryMainId) : ""); #endif Separator(); diff --git a/imgui.h b/imgui.h index 8af72e2fc..47fe424c5 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.3 WIP" -#define IMGUI_VERSION_NUM 19228 +#define IMGUI_VERSION_NUM 19229 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From 1c544ee9416ec98e545e73636ba98dec5c2e18fa Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Sep 2025 18:15:01 +0200 Subject: [PATCH 1347/2359] Version 1.92.3 --- docs/CHANGELOG.txt | 16 ++++++++-------- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 48de7e881..01df5a742 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,27 +36,27 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.3 WIP (In Progress) + VERSION 1.92.3 (Released 2025-09-17) ----------------------------------------------------------------------- -Breaking Changes: +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92.3 Other Changes: -- Scrollbar, Style: added configurable style.ScrollbarPadding value and corresponding - ImGuiStyleVar_ScrollbarPadding enum, instead of hardcoded computed default. (#8895) -- Fonts: fixed an assertion failure when a rectangle entry has been reused - 1024 times (e.g. due to constant change of font types). (#8906) [@cfillion] - Fonts: fixed merging a font and specifying a font target in DstFont that's not the last added font (regression in 1.92). (#8912) +- Fonts: fixed an assertion failure when a rectangle entry has been reused + 1024 times (e.g. due to constant change of font size). (#8906) [@cfillion] - Clipper, Tables: added ImGuiListClipperFlags_NoSetTableRowCounters as a way to disable the assumption that 1 clipper item == 1 table row, which breaks when e.g. using clipper with ItemsHeight=1 in order to clip in pixel units. (#8886) +- Scrollbar, Style: added configurable style.ScrollbarPadding value and corresponding + ImGuiStyleVar_ScrollbarPadding enum, instead of an hard-coded computed default. (#8895) - Nav: fixed Ctrl+Tab window appearing as empty when the sole active and focused window has the ImGuiWindowFlags_NoNavFocus flag. (#8914) - Nav: fixed a crash that could occur when opening a popup following the processing of a global shortcut while no windows were focused. -- Bullet: fixed tesselation amount which looked out of place in very large sizes. +- Bullet: fixed tessellation which looked out of place in very large sizes. - InputText: added ImGuiInputTextFlags_WordWrap flag to word-wrap multi-line buffers. (#3237, #952, #1062, #7363). Current caveats: - This is marked as beta because not being tested enough. @@ -64,7 +64,7 @@ Other Changes: - Wrapping style is not ideal. Wrapping of long words/sections (e.g. words larger than total available width) may be particularly unpleasing. - Wrapping width needs to always account for the possibility of a vertical scrollbar. - - It is currently much slower than regular text fields. + - It is currently much slower than regular text fields: - Ballpark estimate of cost on my 2019 desktop PC: For a 100 KB text buffer: +~0.3 ms/+~1.0 ms (Optimized vs Debug builds). - The CPU cost is very roughly proportional to text length, so a 10 KB buffer diff --git a/imgui.cpp b/imgui.cpp index aff0f7b32..22d371ad8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.3 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 47fe424c5..aa44a51f3 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.3 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.3 WIP" -#define IMGUI_VERSION_NUM 19229 +#define IMGUI_VERSION "1.92.3" +#define IMGUI_VERSION_NUM 19230 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d667c8b70..27d3300b9 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.3 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 9b01047f0..8a629b44d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.3 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index d2a3f4d8b..ece4afbd9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.3 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 5b4e3e07d..f5c4c25aa 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.3 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 412835892..776a7135c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 WIP +// dear imgui, v1.92.3 // (widgets code) /* From bf75bfec48fc00f532af8926130b70c0e26eb099 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Sep 2025 19:05:22 +0200 Subject: [PATCH 1348/2359] Amend f6890ed mostly to please static analyzers. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 22d371ad8..45c913a0a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13431,7 +13431,7 @@ static ImVec2 ImGui::NavCalcPreferredRefPos() ImRect ref_rect; if (activated_shortcut) ref_rect = g.LastItemData.NavRect; - else + else if (window != NULL) ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]); // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?) From 0e7cd694ebd5472c718e818344c35346661aeb18 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 18 Sep 2025 15:38:46 +0200 Subject: [PATCH 1349/2359] Version 1.92.4 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 01df5a742..f7ae7c991 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.4 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.92.3 (Released 2025-09-17) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 45c913a0a..29774fe37 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 +// dear imgui, v1.92.4 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index aa44a51f3..d79a912bf 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 +// dear imgui, v1.92.4 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.3" -#define IMGUI_VERSION_NUM 19230 +#define IMGUI_VERSION "1.92.4 WIP" +#define IMGUI_VERSION_NUM 19231 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 27d3300b9..e3991a60e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 +// dear imgui, v1.92.4 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8a629b44d..3beb3aa80 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 +// dear imgui, v1.92.4 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index ece4afbd9..f66b91f7d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 +// dear imgui, v1.92.4 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f5c4c25aa..21d5335c6 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 +// dear imgui, v1.92.4 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 776a7135c..4709af05b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.3 +// dear imgui, v1.92.4 WIP // (widgets code) /* From d4f722d5b289d4d75b775acfb0a4b41e7df472a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 18 Sep 2025 16:22:24 +0200 Subject: [PATCH 1350/2359] IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers(). Backends: call those on Shutdown(). (#8945, #2769) --- backends/imgui_impl_allegro5.cpp | 4 ++++ backends/imgui_impl_dx10.cpp | 4 ++++ backends/imgui_impl_dx11.cpp | 4 ++++ backends/imgui_impl_dx12.cpp | 4 +++- backends/imgui_impl_dx9.cpp | 4 ++++ backends/imgui_impl_glfw.cpp | 4 ++++ backends/imgui_impl_metal.mm | 6 +++++- backends/imgui_impl_opengl2.cpp | 4 ++++ backends/imgui_impl_opengl3.cpp | 4 ++++ backends/imgui_impl_osx.mm | 4 ++++ backends/imgui_impl_sdl2.cpp | 3 +++ backends/imgui_impl_sdl3.cpp | 3 +++ backends/imgui_impl_sdlgpu3.cpp | 4 ++++ backends/imgui_impl_sdlrenderer2.cpp | 3 +++ backends/imgui_impl_sdlrenderer3.cpp | 3 +++ backends/imgui_impl_vulkan.cpp | 3 +++ backends/imgui_impl_wgpu.cpp | 3 +++ backends/imgui_impl_win32.cpp | 3 +++ docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 17 +++++++++++++++++ imgui.h | 7 +++++++ 21 files changed, 95 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 6c5df4b1f..bb6660d88 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() and platform_io.ClearPlatformHandlers() on shutdown. // 2025-08-12: Inputs: fixed missing support for ImGuiKey_PrintScreen under Windows, as raw Allegro 5 does not receive it. // 2025-08-12: Added ImGui_ImplAllegro5_SetDisplay() function to change current ALLEGRO_DISPLAY, as Allegro applications often need to do that. // 2025-07-07: Fixed texture update broken on some platforms where ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten. @@ -499,6 +500,7 @@ void ImGui_ImplAllegro5_Shutdown() ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplAllegro5_InvalidateDeviceObjects(); if (bd->VertexDecl) @@ -509,6 +511,8 @@ void ImGui_ImplAllegro5_Shutdown() io.BackendPlatformName = io.BackendRendererName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); + platform_io.ClearPlatformHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 5515f780c..ae6510db2 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -16,6 +16,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: DirectX10: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX10: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-01-06: DirectX10: Expose selected render state in ImGui_ImplDX10_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. @@ -630,13 +631,16 @@ void ImGui_ImplDX10_Shutdown() ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplDX10_InvalidateDeviceObjects(); if (bd->pFactory) { bd->pFactory->Release(); } if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } + io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index c71e44d06..1b3423654 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: DirectX11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX11: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). // 2025-01-06: DirectX11: Expose VertexConstantBuffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handler. @@ -649,14 +650,17 @@ void ImGui_ImplDX11_Shutdown() ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplDX11_InvalidateDeviceObjects(); if (bd->pFactory) { bd->pFactory->Release(); } if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); } + io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index c84c21971..86f1180ab 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-19: Fixed build on MinGW. (#8702, #4594) // 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX12: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). @@ -905,14 +906,15 @@ void ImGui_ImplDX12_Shutdown() ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - // Clean up windows and device objects ImGui_ImplDX12_InvalidateDeviceObjects(); delete[] bd->pFrameResources; io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 94411fabe..4a8899a62 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: DirectX9: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2024-10-07: DirectX9: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575) @@ -351,12 +352,15 @@ void ImGui_ImplDX9_Shutdown() ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplDX9_InvalidateDeviceObjects(); if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } + io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 8a646b5dd..cfe5dc6d3 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Content Scales are always reported as 1.0 on Wayland. FramebufferScale are always reported as 1.0 on X11. (#8920, #8921) // 2025-07-08: Made ImGui_ImplGlfw_GetContentScaleForWindow(), ImGui_ImplGlfw_GetContentScaleForMonitor() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) // 2025-06-18: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069) @@ -767,7 +768,9 @@ void ImGui_ImplGlfw_Shutdown() { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); if (bd->InstalledCallbacks) ImGui_ImplGlfw_RestoreCallbacks(bd->Window); @@ -790,6 +793,7 @@ void ImGui_ImplGlfw_Shutdown() io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); + platform_io.ClearPlatformHandlers(); ImGui_ImplGlfw_ContextMap_Remove(bd->Window); IM_DELETE(bd); } diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index a1adc6c9a..81e8be6c4 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -16,6 +16,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplMetal_CreateFontsTexture() and ImGui_ImplMetal_DestroyFontsTexture(). // 2025-02-03: Metal: Crash fix. (#8367) // 2024-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419). @@ -148,13 +149,16 @@ void ImGui_ImplMetal_Shutdown() ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); IM_UNUSED(bd); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + ImGui_ImplMetal_DestroyDeviceObjects(); ImGui_ImplMetal_DestroyBackendData(); - ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); } void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor) diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp index 477e3a043..af5618fb6 100644 --- a/backends/imgui_impl_opengl2.cpp +++ b/backends/imgui_impl_opengl2.cpp @@ -25,6 +25,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures. (#8802) // 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL2_CreateFontsTexture() and ImGui_ImplOpenGL2_DestroyFontsTexture(). // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap. @@ -115,11 +116,14 @@ void ImGui_ImplOpenGL2_Shutdown() ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplOpenGL2_DestroyDeviceObjects(); + io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 5ab43a406..3e0e265b1 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -23,6 +23,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-07-22: OpenGL: Add and call embedded loader shutdown during ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) // 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures (#8802) + restore non-WebGL/ES update path that doesn't require a CPU-side copy. // 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture(). @@ -421,11 +422,14 @@ void ImGui_ImplOpenGL3_Shutdown() ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplOpenGL3_DestroyDeviceObjects(); + io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); #ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 06a6aff8b..189dd53e6 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-06-27: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-06-12: ImGui_ImplOSX_HandleEvent() only process event for window containing our view. (#8644) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. @@ -514,9 +515,12 @@ void ImGui_ImplOSX_Shutdown() ImGui_ImplOSX_DestroyBackendData(); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasGamepad); + platform_io.ClearPlatformHandlers(); } static void ImGui_ImplOSX_UpdateMouseCursor() diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 08e7988e2..acd98f641 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Content Scales are always reported as 1.0 on Wayland. (#8921) // 2025-07-08: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) // 2025-06-11: Added ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) and ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) helper to facilitate making DPI-aware apps. @@ -629,6 +630,7 @@ void ImGui_ImplSDL2_Shutdown() ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); @@ -639,6 +641,7 @@ void ImGui_ImplSDL2_Shutdown() io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); + platform_io.ClearPlatformHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 17613d30a..83dc93282 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Use SDL_GetWindowDisplayScale() on Mac to output DisplayFrameBufferScale. The function is more reliable during resolution changes e.g. going fullscreen. (#8703, #4414) // 2025-06-27: IME: avoid calling SDL_StartTextInput() again if already active. (#8727) // 2025-04-22: IME: honor ImGuiPlatformImeData->WantTextInput as an alternative way to call SDL_StartTextInput(), without IME being necessarily visible. @@ -590,6 +591,7 @@ void ImGui_ImplSDL3_Shutdown() ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); @@ -600,6 +602,7 @@ void ImGui_ImplSDL3_Shutdown() io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); + platform_io.ClearPlatformHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 0f8d5fa1a..3afbf3db6 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -22,6 +22,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-08-20: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and ImGui_ImplSDLGPU3_InitInfo::PresentMode to configure how secondary viewports are created. // 2025-08-08: *BREAKING* Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) // 2025-08-08: Expose SamplerDefault and SamplerCurrent in ImGui_ImplSDLGPU3_RenderState. Allow callback to change sampler. @@ -641,11 +642,14 @@ void ImGui_ImplSDLGPU3_Shutdown() ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplSDLGPU3_DestroyDeviceObjects(); + io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index 3a47f80bf..fa1e802b1 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -24,6 +24,7 @@ // - Introduction, links and more at the top of imgui.cpp // CHANGELOG +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLRenderer2_CreateFontsTexture() and ImGui_ImplSDLRenderer2_DestroyFontsTexture(). // 2025-01-18: Use endian-dependent RGBA32 texture format, to match SDL_Color. // 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer2_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. @@ -94,12 +95,14 @@ void ImGui_ImplSDLRenderer2_Shutdown() ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 42c173888..abf636b8d 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -24,6 +24,7 @@ // - Introduction, links and more at the top of imgui.cpp // CHANGELOG +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLRenderer3_CreateFontsTexture() and ImGui_ImplSDLRenderer3_DestroyFontsTexture(). // 2025-01-18: Use endian-dependent RGBA32 texture format, to match SDL_Color. // 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer3_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. @@ -92,12 +93,14 @@ void ImGui_ImplSDLRenderer3_Shutdown() ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index e56902254..4a0a5a947 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-09-04: Vulkan: Added ImGui_ImplVulkan_CreateMainPipeline(). (#8110, #8111) // 2025-07-27: Vulkan: Fixed texture update corruption introduced on 2025-06-11. (#8801, #8755, #8840) // 2025-07-07: Vulkan: Fixed texture synchronization issue introduced on 2025-06-11. (#8772) @@ -1315,12 +1316,14 @@ void ImGui_ImplVulkan_Shutdown() ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplVulkan_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index d20028d55..1f997a10a 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -18,6 +18,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. (#8465) // 2025-02-26: Recreate image bind groups during render. (#8426, #8046, #7765, #8027) + Update for latest webgpu-native changes. // 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083) @@ -880,6 +881,7 @@ void ImGui_ImplWGPU_Shutdown() ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplWGPU_InvalidateDeviceObjects(); delete[] bd->pFrameResources; @@ -892,6 +894,7 @@ void ImGui_ImplWGPU_Shutdown() io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); IM_DELETE(bd); } diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index d7206b970..20dce139e 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-04-30: Inputs: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) would fail to claim it again the next subsequent click. (#8594) // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. @@ -222,6 +223,7 @@ void ImGui_ImplWin32_Shutdown() ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); // Unload XInput library #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD @@ -232,6 +234,7 @@ void ImGui_ImplWin32_Shutdown() io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); + platform_io.ClearPlatformHandlers(); IM_DELETE(bd); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f7ae7c991..ebb60f9a9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,12 @@ Breaking Changes: Other Changes: +- IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() + helpers to null all handlers. (#8945, #2769) +- Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and + ClearRendererHandlers() on shutdown, so as not to leave function pointers + which may be dangling when using backend in e.g. DLL. (#8945, #2769) + ----------------------------------------------------------------------- VERSION 1.92.3 (Released 2025-09-17) diff --git a/imgui.cpp b/imgui.cpp index 29774fe37..0c61f9ee1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15453,6 +15453,23 @@ void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count) // (this section is more complete in the 'docking' branch) //----------------------------------------------------------------------------- +void ImGuiPlatformIO::ClearPlatformHandlers() +{ + Platform_GetClipboardTextFn = NULL; + Platform_SetClipboardTextFn = NULL; + Platform_ClipboardUserData = NULL; + Platform_OpenInShellFn = NULL; + Platform_OpenInShellUserData = NULL; + Platform_SetImeDataFn = NULL; + Platform_ImeUserData = NULL; +} + +void ImGuiPlatformIO::ClearRendererHandlers() +{ + Renderer_TextureMaxWidth = Renderer_TextureMaxHeight = 0; + Renderer_RenderState = NULL; +} + ImGuiViewport* ImGui::GetMainViewport() { ImGuiContext& g = *GImGui; diff --git a/imgui.h b/imgui.h index d79a912bf..682364004 100644 --- a/imgui.h +++ b/imgui.h @@ -3970,6 +3970,13 @@ struct ImGuiPlatformIO // Textures list (the list is updated by calling ImGui::EndFrame or ImGui::Render) // The ImGui_ImplXXXX_RenderDrawData() function of each backend generally access this via ImDrawData::Textures which points to this. The array is available here mostly because backends will want to destroy textures on shutdown. ImVector Textures; // List of textures used by Dear ImGui (most often 1) + contents of external texture list is automatically appended into this. + + //------------------------------------------------------------------ + // Functions + //------------------------------------------------------------------ + + void ClearPlatformHandlers(); // Clear all Platform_XXX fields. Typically called on Platform Backend shutdown. + void ClearRendererHandlers(); // Clear all Renderer_XXX fields. Typically called on Renderer Backend shutdown. }; // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). From 087fbf08f600d061de7531a14c496145262e7319 Mon Sep 17 00:00:00 2001 From: David Mentler Date: Mon, 22 Sep 2025 12:20:15 +0200 Subject: [PATCH 1351/2359] Added type formatters for the LLDB debuggers (e.g. Xcode) (#8950) --- misc/debuggers/README.txt | 4 + misc/debuggers/imgui_lldb.py | 187 +++++++++++++++++++++++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 misc/debuggers/imgui_lldb.py diff --git a/misc/debuggers/README.txt b/misc/debuggers/README.txt index 3f4ba83e3..77a78b9e5 100644 --- a/misc/debuggers/README.txt +++ b/misc/debuggers/README.txt @@ -14,3 +14,7 @@ imgui.natvis With this, types like ImVector<> will be displayed nicely in the debugger. (read comments inside file for details) +imgui_lldb.py + LLDB: synthetic children provider and summaries for Dear ImGui types. + With this, types like ImVector<> will be displayed nicely in the debugger. + (read comments inside file for details) diff --git a/misc/debuggers/imgui_lldb.py b/misc/debuggers/imgui_lldb.py new file mode 100644 index 000000000..336d3f513 --- /dev/null +++ b/misc/debuggers/imgui_lldb.py @@ -0,0 +1,187 @@ +# This file implements synthetic children providers and summaries for various ImGui types for LLDB. +# +# Useful links/documentation related to the feature: +# - https://lldb.llvm.org/use/variable.html#summary-strings +# - https://lldb.llvm.org/use/variable.html#synthetic-children +# - https://lldb.llvm.org/python_reference/lldb-module.html +# +# To use it in a debug session: +# > (lldb) command script import +# +# Alternatively you may include the above command in your ~/.lldbinit file to have the formatters +# available in all future sessions + +import lldb + +class ArraySynthBase(object): + """ + Helper baseclass aimed to reduce the boilerplate needed for "array-like" containers + """ + + def __init__(self, valobj, internal_dict): + self.valobj = valobj + + def bind_to(self, pointer, size): + array_p = pointer.GetType().GetPointeeType().GetArrayType(size).GetPointerType() + self.array = pointer.Cast(array_p).Dereference() + + def update(self): + self.array = self.valobj + + def num_children(self, max_children): + return self.array.GetNumChildren(max_children) + + def get_child_index(self, name): + return self.array.GetIndexOfChildWithName(name) + + def get_child_at_index(self, index): + return self.array.GetChildAtIndex(index) + + def has_children(self): + return self.array.MightHaveChildren() + + def get_value(self): + return self.array + +class ImVectorSynth(ArraySynthBase): + def update(self): + self.size = self.valobj.GetChildMemberWithName("Size").GetValueAsUnsigned() + self.capacity = self.valobj.GetChildMemberWithName("Capacity").GetValueAsUnsigned() + + data = self.valobj.GetChildMemberWithName("Data") + + self.bind_to(data, self.size) + + def get_summary(self): + return f"Size={self.size} Capacity={self.capacity}" + +class ImSpanSynth(ArraySynthBase): + def update(self): + data = self.valobj.GetChildMemberWithName("Data") + end = self.valobj.GetChildMemberWithName("DataEnd") + + element_size = data.GetType().GetPointeeType().GetByteSize() + array_size = end.GetValueAsUnsigned() - data.GetValueAsUnsigned() + + self.size = int(array_size / element_size) + + self.bind_to(data, self.size) + + def get_summary(self): + return f"Size={self.size}" + +class ImRectSummary(object): + def __init__(self, valobj, internal_dict): + self.valobj = valobj + + def update(self): + pass + + def get_summary(self): + min = self.valobj.GetChildMemberWithName("Min") + max = self.valobj.GetChildMemberWithName("Max") + + minX = float(min.GetChildMemberWithName("x").GetValue()) + minY = float(min.GetChildMemberWithName("y").GetValue()) + + maxX = float(max.GetChildMemberWithName("x").GetValue()) + maxY = float(max.GetChildMemberWithName("y").GetValue()) + + return f"Min=({minX}, {minY}) Max=({maxX}, {maxY}) Size=({maxX - minX}, {maxY - minY})" + +def get_active_enum_flags(valobj): + flag_set = set() + + enum_name = valobj.GetType().GetName() + "_" + enum_type = valobj.GetTarget().FindFirstType(enum_name) + + if not enum_type.IsValid(): + return flag_set + + enum_members = enum_type.GetEnumMembers() + value = valobj.GetValueAsUnsigned() + + for i in range(0, enum_members.GetSize()): + member = enum_members.GetTypeEnumMemberAtIndex(i) + + if value & member.GetValueAsUnsigned(): + flag_set.add(member.GetName().removeprefix(enum_name)) + + return flag_set + +class ImGuiWindowSummary(object): + def __init__(self, valobj, internal_dict): + self.valobj = valobj + + def update(self): + pass + + def get_summary(self): + name = self.valobj.GetChildMemberWithName("Name").GetSummary() + + active = self.valobj.GetChildMemberWithName("Active").GetValueAsUnsigned() != 0 + was_active = self.valobj.GetChildMemberWithName("WasActive").GetValueAsUnsigned() != 0 + hidden = self.valobj.GetChildMemberWithName("Hidden") != 0 + + flags = get_active_enum_flags(self.valobj.GetChildMemberWithName("Flags")) + + active = 1 if active or was_active else 0 + child = 1 if "ChildWindow" in flags else 0 + popup = 1 if "Popup" in flags else 0 + hidden = 1 if hidden else 0 + + return f"Name {name} Active {active} Child {child} Popup {popup} Hidden {hidden}" + + +def __lldb_init_module(debugger, internal_dict): + """ + This function will be automatically called by LLDB when the module is loaded, here + we register the various synthetics/summaries we have build before + """ + + category_name = "imgui" + category = debugger.GetCategory(category_name) + + # Make sure we don't accidentally keep accumulating languages or override the user's + # category enablement in Xcode, where lldb-rpc-server loads this file once for eac + # debugging session + if not category.IsValid(): + category = debugger.CreateCategory(category_name) + category.AddLanguage(lldb.eLanguageTypeC_plus_plus) + category.SetEnabled(True) + + def add_summary(typename, impl): + summary = None + + if isinstance(impl, str): + summary = lldb.SBTypeSummary.CreateWithSummaryString(impl) + summary.SetOptions(lldb.eTypeOptionCascade) + else: + # Unfortunately programmatic summary string generation is an entirely different codepath + # in LLDB. Register a convenient trampoline function which makes it look like it's part + # of the SyntheticChildrenProvider contract + summary = lldb.SBTypeSummary.CreateWithScriptCode(f''' + synth = {impl.__module__}.{impl.__qualname__}(valobj.GetNonSyntheticValue(), internal_dict) + synth.update() + + return synth.get_summary() + ''') + summary.SetOptions(lldb.eTypeOptionCascade | lldb.eTypeOptionFrontEndWantsDereference) + + category.AddTypeSummary(lldb.SBTypeNameSpecifier(typename, True), summary) + + def add_synthetic(typename, impl): + add_summary(typename, impl) + + synthetic = lldb.SBTypeSynthetic.CreateWithClassName(f"{impl.__module__}.{impl.__qualname__}") + synthetic.SetOptions(lldb.eTypeOptionCascade | lldb.eTypeOptionFrontEndWantsDereference) + + category.AddTypeSynthetic(lldb.SBTypeNameSpecifier(typename, True), synthetic) + + add_synthetic("^ImVector<.+>$", ImVectorSynth) + add_synthetic("^ImSpan<.+>$", ImSpanSynth) + + add_summary("^ImVec2$", "x=${var.x} y=${var.y}") + add_summary("^ImVec4$", "x=${var.x} y=${var.y} z=${var.z} w=${var.w}") + add_summary("^ImRect$", ImRectSummary) + add_summary("^ImGuiWindow$", ImGuiWindowSummary) From 46e6382b69e30fe85b8e77bac6c4e5604b6195d1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Sep 2025 12:26:53 +0200 Subject: [PATCH 1352/2359] Added type formatters for the LLDB debuggers (e.g. Xcode, Android Studio) (#8950) --- docs/CHANGELOG.txt | 3 +++ misc/README.txt | 4 ++-- misc/debuggers/README.txt | 3 ++- misc/debuggers/imgui_lldb.py | 4 +++- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ebb60f9a9..344d5e228 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,9 @@ Other Changes: - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() helpers to null all handlers. (#8945, #2769) +- Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, + Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. + See misc/debuggers/ for details. (#8950) [@mentlerd] - Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and ClearRendererHandlers() on shutdown, so as not to leave function pointers which may be dangling when using backend in e.g. DLL. (#8945, #2769) diff --git a/misc/README.txt b/misc/README.txt index b4ce89f03..58c00ee8c 100644 --- a/misc/README.txt +++ b/misc/README.txt @@ -4,8 +4,8 @@ misc/cpp/ This is also an example of how you may wrap your own similar types. misc/debuggers/ - Helper files for popular debuggers. - With the .natvis file, types like ImVector<> will be displayed nicely in Visual Studio debugger. + Helper files for popular debuggers (Visual Studio, GDB, LLDB). + e.g. With the .natvis file, types like ImVector<> will be displayed nicely in Visual Studio debugger. misc/fonts/ Fonts loading/merging instructions (e.g. How to handle glyph ranges, how to merge icons fonts). diff --git a/misc/debuggers/README.txt b/misc/debuggers/README.txt index 77a78b9e5..ad6f491fe 100644 --- a/misc/debuggers/README.txt +++ b/misc/debuggers/README.txt @@ -15,6 +15,7 @@ imgui.natvis (read comments inside file for details) imgui_lldb.py - LLDB: synthetic children provider and summaries for Dear ImGui types. + LLDB-based debuggers (*): synthetic children provider and summaries for Dear ImGui types. With this, types like ImVector<> will be displayed nicely in the debugger. (read comments inside file for details) + (*) Xcode, Android Studio, may be used from VS Code, C++Builder, CLion, Eclipse etc. diff --git a/misc/debuggers/imgui_lldb.py b/misc/debuggers/imgui_lldb.py index 336d3f513..7d3c6bfcb 100644 --- a/misc/debuggers/imgui_lldb.py +++ b/misc/debuggers/imgui_lldb.py @@ -1,4 +1,6 @@ -# This file implements synthetic children providers and summaries for various ImGui types for LLDB. +# This file implements synthetic children providers and summaries for various Dear ImGui types for LLDB. +# LLDB is used by Xcode, Android Studio, and may be used from VS Code, C++Builder, CLion, Eclipse etc. + # # Useful links/documentation related to the feature: # - https://lldb.llvm.org/use/variable.html#summary-strings From ef6fe2ecee61c4da1c57f31a585a8cc27909ee76 Mon Sep 17 00:00:00 2001 From: yaz0r <363511+yaz0r@users.noreply.github.com> Date: Sat, 20 Sep 2025 10:48:54 -0700 Subject: [PATCH 1353/2359] CI: update Windows Vulkan scripts. (#8925) --- .github/workflows/build.yml | 17 ++-------- .../workflows/build_windows_vulkan_libs.ps1 | 33 +++++++++++++++++++ .../workflows/build_windows_vulkan_libs.yml | 22 +++++++++++++ 3 files changed, 58 insertions(+), 14 deletions(-) create mode 100644 .github/workflows/build_windows_vulkan_libs.ps1 create mode 100644 .github/workflows/build_windows_vulkan_libs.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 783615aec..1c578b76b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -35,20 +35,9 @@ jobs: Expand-Archive -Path SDL3-devel-3.2.18-VC.zip echo "SDL3_DIR=$(pwd)\SDL3-devel-3.2.18-VC\SDL3-3.2.18\" >>${env:GITHUB_ENV} - # VulkanSDK (retrieve minimal bits of the SDK from git) - $vulkanVersion = "1.4.326" - # 1. Get the vulkan headers, we will treat that folder as the sdk folder to avoid having to copy headers around - Invoke-WebRequest -Uri "https://github.com/KhronosGroup/Vulkan-Headers/archive/refs/tags/v$($vulkanVersion).zip" -OutFile Vulkan-Headers-$($vulkanVersion).zip - Expand-Archive -Path Vulkan-Headers-$($vulkanVersion).zip - echo "VULKAN_SDK=$(pwd)\Vulkan-Headers-$($vulkanVersion)\Vulkan-Headers-$($vulkanVersion)" >>${env:GITHUB_ENV} - # 2. Get and build the vulkan loader source code (UPDATE_DEPS=On will make it automatically fetch its dependencies) - Invoke-WebRequest -Uri "https://github.com/KhronosGroup/Vulkan-Loader/archive/refs/tags/v$($vulkanVersion).zip" -OutFile Vulkan-Loader-$($vulkanVersion).zip - Expand-Archive -Path Vulkan-Loader-$($vulkanVersion).zip - cmake -S Vulkan-Loader-$($vulkanVersion)\Vulkan-Loader-$($vulkanVersion) -B VulkanLoader-build -D UPDATE_DEPS=On - cmake --build VulkanLoader-build - # 3. Copy the built lib/dll to the expected place - mkdir Vulkan-Headers-$($vulkanVersion)\Vulkan-Headers-$($vulkanVersion)\Lib - copy VulkanLoader-build\loader\Debug\vulkan-1.* Vulkan-Headers-$($vulkanVersion)\Vulkan-Headers-$($vulkanVersion)\Lib\ + Invoke-WebRequest -Uri "https://github.com/ocornut/imgui/files/3789205/vulkan-sdk-1.1.121.2.zip" -OutFile vulkan-sdk-1.1.121.2.zip + Expand-Archive -Path vulkan-sdk-1.1.121.2.zip + echo "VULKAN_SDK=$(pwd)\vulkan-sdk-1.1.121.2\" >>${env:GITHUB_ENV} - name: Fix Projects shell: powershell diff --git a/.github/workflows/build_windows_vulkan_libs.ps1 b/.github/workflows/build_windows_vulkan_libs.ps1 new file mode 100644 index 000000000..57e542372 --- /dev/null +++ b/.github/workflows/build_windows_vulkan_libs.ps1 @@ -0,0 +1,33 @@ +# Set default vulkan version if none provided +if (-not $env:VULKAN_TAG) { $env:VULKAN_TAG = "1.4.326" } + +# Create output folder +mkdir vulkanArtifact + +# Download Vulkan Headers + +Invoke-WebRequest -Uri "https://github.com/KhronosGroup/Vulkan-Headers/archive/refs/tags/v$($env:VULKAN_TAG).zip" -OutFile Vulkan-Headers-$($env:VULKAN_TAG).zip +Expand-Archive -Path Vulkan-Headers-$($env:VULKAN_TAG).zip + +# Copy Vulkan Headers to artifact folder + +cp -R Vulkan-Headers-$($env:VULKAN_TAG)\Vulkan-Headers-$($env:VULKAN_TAG)\include vulkanArtifact\Include + +# Download Vulkan Loader + +Invoke-WebRequest -Uri "https://github.com/KhronosGroup/Vulkan-Loader/archive/refs/tags/v$($env:VULKAN_TAG).zip" -OutFile Vulkan-Loader-$($env:VULKAN_TAG).zip +Expand-Archive -Path Vulkan-Loader-$($env:VULKAN_TAG).zip + +# Build Vulkan Loader x64 + +cmake -S Vulkan-Loader-$($env:VULKAN_TAG)\Vulkan-Loader-$($env:VULKAN_TAG) -B VulkanLoader-build64 -D UPDATE_DEPS=On -A x64 +cmake --build VulkanLoader-build64 +mkdir vulkanArtifact\Lib +copy VulkanLoader-build64\loader\Debug\vulkan-1.lib vulkanArtifact\Lib + +# Build Vulkan Loader win32 + +cmake -S Vulkan-Loader-$($env:VULKAN_TAG)\Vulkan-Loader-$($env:VULKAN_TAG) -B VulkanLoader-build32 -D UPDATE_DEPS=On -A Win32 +cmake --build VulkanLoader-build32 +mkdir vulkanArtifact\Lib32 +copy VulkanLoader-build32\loader\Debug\vulkan-1.lib vulkanArtifact\Lib32 diff --git a/.github/workflows/build_windows_vulkan_libs.yml b/.github/workflows/build_windows_vulkan_libs.yml new file mode 100644 index 000000000..beaa2ff0a --- /dev/null +++ b/.github/workflows/build_windows_vulkan_libs.yml @@ -0,0 +1,22 @@ +name: build-windows-vulkan-libs + +on: workflow_dispatch + +jobs: + Windows: + runs-on: windows-2025 + env: + VULKAN_TAG: 1.4.326 + steps: + - uses: actions/checkout@v4 + + - name: Build Vulkan libs + shell: powershell + run: .github/workflows/build_windows_vulkan_libs.ps1 + + - uses: actions/upload-artifact@v4 + with: + name: vulkan_windows_libs_${{ env.VULKAN_TAG }} + path: vulkanArtifact + overwrite: 'true' + From dc0198a7e475fb2c1d6a8aac386aa8b0d73794f4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Sep 2025 12:44:49 +0200 Subject: [PATCH 1354/2359] CI: update Windows Vulkan scripts. Amends. (#8925) --- .github/workflows/build.yml | 8 ++++--- .../workflows/build_windows_vulkan_libs.ps1 | 5 +++++ .../workflows/build_windows_vulkan_libs.yml | 22 ------------------- docs/CHANGELOG.txt | 1 + 4 files changed, 11 insertions(+), 25 deletions(-) delete mode 100644 .github/workflows/build_windows_vulkan_libs.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1c578b76b..92d41dac1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,6 +24,8 @@ jobs: steps: - uses: actions/checkout@v4 + # The VulkanSDK libs for Windows is manually generated using build_windows_vulkan_libs.ps1 + attached to issue #8925. + # (we have a .yml workflow in commit history if it becomes ever useful to create this on CI too) - name: Install Dependencies shell: powershell run: | @@ -35,9 +37,9 @@ jobs: Expand-Archive -Path SDL3-devel-3.2.18-VC.zip echo "SDL3_DIR=$(pwd)\SDL3-devel-3.2.18-VC\SDL3-3.2.18\" >>${env:GITHUB_ENV} - Invoke-WebRequest -Uri "https://github.com/ocornut/imgui/files/3789205/vulkan-sdk-1.1.121.2.zip" -OutFile vulkan-sdk-1.1.121.2.zip - Expand-Archive -Path vulkan-sdk-1.1.121.2.zip - echo "VULKAN_SDK=$(pwd)\vulkan-sdk-1.1.121.2\" >>${env:GITHUB_ENV} + Invoke-WebRequest -Uri "https://github.com/user-attachments/files/22464296/vulkan_windows_libs_1.4.326.zip" -OutFile vulkan_windows_libs_1.4.326.zip + Expand-Archive -Path vulkan_windows_libs_1.4.326.zip + echo "VULKAN_SDK=$(pwd)\vulkan_windows_libs_1.4.326\" >>${env:GITHUB_ENV} - name: Fix Projects shell: powershell diff --git a/.github/workflows/build_windows_vulkan_libs.ps1 b/.github/workflows/build_windows_vulkan_libs.ps1 index 57e542372..6658f5b5b 100644 --- a/.github/workflows/build_windows_vulkan_libs.ps1 +++ b/.github/workflows/build_windows_vulkan_libs.ps1 @@ -1,3 +1,8 @@ +# This is current meant to be run manually, occasionally: +# - Run then zip the contents of vulkanArtifact/ into e.g. vulkan_windows_libs_1.4.326 +# - Upload as an attachment to https://github.com/ocornut/imgui/pull/8925 then change filename in build.yml +# - There is a build_windows_vulkan_libs.yml in commit history that we removed thinking this is run so rarely we don't need to pollute CI UI with it. + # Set default vulkan version if none provided if (-not $env:VULKAN_TAG) { $env:VULKAN_TAG = "1.4.326" } diff --git a/.github/workflows/build_windows_vulkan_libs.yml b/.github/workflows/build_windows_vulkan_libs.yml deleted file mode 100644 index beaa2ff0a..000000000 --- a/.github/workflows/build_windows_vulkan_libs.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: build-windows-vulkan-libs - -on: workflow_dispatch - -jobs: - Windows: - runs-on: windows-2025 - env: - VULKAN_TAG: 1.4.326 - steps: - - uses: actions/checkout@v4 - - - name: Build Vulkan libs - shell: powershell - run: .github/workflows/build_windows_vulkan_libs.ps1 - - - uses: actions/upload-artifact@v4 - with: - name: vulkan_windows_libs_${{ env.VULKAN_TAG }} - path: vulkanArtifact - overwrite: 'true' - diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 344d5e228..636110ba2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,7 @@ Other Changes: - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. See misc/debuggers/ for details. (#8950) [@mentlerd] +- CI: Updates Windows CI scripts to generate/use VulkanSDK. (#8925, #8778) [@yaz0r] - Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and ClearRendererHandlers() on shutdown, so as not to leave function pointers which may be dangling when using backend in e.g. DLL. (#8945, #2769) From 301e652376b6bb20cfc8aedaa1e6d0ca8afe7bd9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Sep 2025 16:04:59 +0200 Subject: [PATCH 1355/2359] Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support. (#8952) --- backends/imgui_impl_opengl3_loader.h | 4 ++++ docs/CHANGELOG.txt | 2 ++ 2 files changed, 6 insertions(+) diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index a69ac89d7..2c80cc598 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -714,7 +714,11 @@ static void close_libgl(void) static int is_library_loaded(const char* name, void** lib) { +#if defined(__HAIKU__) + *lib = NULL; // no support for RTLD_NOLOAD on Haiku. +#else *lib = dlopen(name, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD); +#endif return *lib != NULL; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 636110ba2..c6b65dd2f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,8 @@ Other Changes: - Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and ClearRendererHandlers() on shutdown, so as not to leave function pointers which may be dangling when using backend in e.g. DLL. (#8945, #2769) +- Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support + `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY] ----------------------------------------------------------------------- From 8868ad67e4fa45c21c9db2e7b9abd6e5a1849b7e Mon Sep 17 00:00:00 2001 From: Brenton Bostick Date: Mon, 22 Sep 2025 10:09:44 -0400 Subject: [PATCH 1356/2359] Fixed typos. (#8955) --- imgui.cpp | 2 +- imgui_draw.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0c61f9ee1..93a77ec25 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3814,7 +3814,7 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons // 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 preceeding 'float ellipsis_max' and was the same value for 99% of users. +// (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) { ImGuiContext& g = *GImGui; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3beb3aa80..0946d7a46 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5598,7 +5598,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 WIDLY IN 2025-2025. Use ImDrawList::AddText(). +// DO NOT CALL DIRECTLY THIS WILL CHANGE WILDLY IN 2025-2025. 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) { // Align to be pixel perfect From a00e517a8109030e13fc911abc9ebeb026c3ef2c Mon Sep 17 00:00:00 2001 From: Tomas Jakobsson Date: Mon, 22 Sep 2025 18:55:35 +0200 Subject: [PATCH 1357/2359] Examples: added SDL3+DirectX11 example. (#8956, #8957) --- .../example_sdl3_directx11/build_win32.bat | 8 + .../example_sdl3_directx11.vcxproj | 187 +++++++++++++ .../example_sdl3_directx11.vcxproj.filters | 63 +++++ examples/example_sdl3_directx11/main.cpp | 253 ++++++++++++++++++ examples/imgui_examples.sln | 10 + 5 files changed, 521 insertions(+) create mode 100644 examples/example_sdl3_directx11/build_win32.bat create mode 100644 examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj create mode 100644 examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj.filters create mode 100644 examples/example_sdl3_directx11/main.cpp diff --git a/examples/example_sdl3_directx11/build_win32.bat b/examples/example_sdl3_directx11/build_win32.bat new file mode 100644 index 000000000..b84b01f1a --- /dev/null +++ b/examples/example_sdl3_directx11/build_win32.bat @@ -0,0 +1,8 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@set OUT_DIR=Debug +@set OUT_EXE=example_sdl3_directx11 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib shell32.lib +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj b/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj new file mode 100644 index 000000000..340901c3d --- /dev/null +++ b/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj @@ -0,0 +1,187 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {009DAC16-1A9C-47BE-9770-A30A046E8090} + example_sdl3_directx11 + 8.1 + example_sdl3_directx11 + + + + Application + true + MultiByte + v140 + + + Application + true + MultiByte + v140 + + + Application + false + true + MultiByte + v140 + + + Application + false + true + MultiByte + v140 + + + + + + + + + + + + + + + + + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + + Level4 + Disabled + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) + + + true + %SDL3_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + Console + msvcrt.lib + + + + + Level4 + Disabled + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) + + + true + %SDL3_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + Console + msvcrt.lib + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include;%(AdditionalIncludeDirectories) + false + /utf-8 %(AdditionalOptions) + + + true + true + true + %SDL3_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + Console + + + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include;%(AdditionalIncludeDirectories) + false + /utf-8 %(AdditionalOptions) + + + true + true + true + %SDL3_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + Console + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj.filters b/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj.filters new file mode 100644 index 000000000..0579b7a64 --- /dev/null +++ b/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj.filters @@ -0,0 +1,63 @@ + + + + + {0587d7a3-f2ce-4d56-b84f-a0005d3bfce6} + + + {08e36723-ce4f-4cff-9662-c40801cf1acf} + + + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + + + imgui + + + sources + + + imgui + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + + + + imgui + + + imgui + + + \ No newline at end of file diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp new file mode 100644 index 000000000..a604e3076 --- /dev/null +++ b/examples/example_sdl3_directx11/main.cpp @@ -0,0 +1,253 @@ +// Dear ImGui: standalone example application for SDL3 + DirectX 11 +// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#include "imgui.h" +#include "imgui_impl_sdl3.h" +#include "imgui_impl_dx11.h" +#include +#include +#include + +// Data +static ID3D11Device* g_pd3dDevice = nullptr; +static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr; +static IDXGISwapChain* g_pSwapChain = nullptr; +static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr; + +// Forward declarations of helper functions +bool CreateDeviceD3D(HWND hWnd); +void CleanupDeviceD3D(); +void CreateRenderTarget(); +void CleanupRenderTarget(); + +// Main code +int main(int, char**) +{ + // Setup SDL + // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function] + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) + { + printf("Error: SDL_Init(): %s\n", SDL_GetError()); + return -1; + } + + // Setup window + float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); + SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+DirectX11 example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } + + SDL_PropertiesID props = SDL_GetWindowProperties(window); + HWND hwnd = (HWND)SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL); + + // Initialize Direct3D + if (!CreateDeviceD3D(hwnd)) + { + CleanupDeviceD3D(); + return 1; + } + + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + SDL_ShowWindow(window); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + + // Setup Platform/Renderer backends + ImGui_ImplSDL3_InitForD3D(window); + ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); + //IM_ASSERT(font != nullptr); + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; + while (!done) + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function] + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL3_ProcessEvent(&event); + if (event.type == SDL_EVENT_QUIT) + done = true; + if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) + done = true; + if (event.type == SDL_EVENT_WINDOW_RESIZED && event.window.windowID == SDL_GetWindowID(window)) + { + // Release all outstanding references to the swap chain's buffers before resizing. + CleanupRenderTarget(); + g_pSwapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0); + CreateRenderTarget(); + } + } + + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function] + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + { + SDL_Delay(10); + continue; + } + + // Start the Dear ImGui frame + ImGui_ImplDX11_NewFrame(); + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; + g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr); + g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha); + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + + g_pSwapChain->Present(1, 0); // Present with vsync + //g_pSwapChain->Present(0, 0); // Present without vsync + } + + // Cleanup + ImGui_ImplDX11_Shutdown(); + ImGui_ImplSDL3_Shutdown(); + ImGui::DestroyContext(); + + CleanupDeviceD3D(); + SDL_DestroyWindow(window); + SDL_Quit(); + + return 0; +} + +// Helper functions to use DirectX11 +bool CreateDeviceD3D(HWND hWnd) +{ + // Setup swap chain + DXGI_SWAP_CHAIN_DESC sd; + ZeroMemory(&sd, sizeof(sd)); + sd.BufferCount = 2; + sd.BufferDesc.Width = 0; + sd.BufferDesc.Height = 0; + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.BufferDesc.RefreshRate.Numerator = 60; + sd.BufferDesc.RefreshRate.Denominator = 1; + sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.OutputWindow = hWnd; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.Windowed = TRUE; + sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + + UINT createDeviceFlags = 0; + //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + D3D_FEATURE_LEVEL featureLevel; + const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; + if (D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) + return false; + + CreateRenderTarget(); + return true; +} + +void CleanupDeviceD3D() +{ + CleanupRenderTarget(); + if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = nullptr; } + if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = nullptr; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; } +} + +void CreateRenderTarget() +{ + ID3D11Texture2D* pBackBuffer; + g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &g_mainRenderTargetView); + pBackBuffer->Release(); +} + +void CleanupRenderTarget() +{ + if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; } +} diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index cf1c5ad50..8ad1a2566 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -39,6 +39,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_vulkan", "exa EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlgpu3", "example_sdl3_sdlgpu3\example_sdl3_sdlgpu3.vcxproj", "{C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_directx11", "example_sdl3_directx11\example_sdl3_directx11.vcxproj", "{009DAC16-1A9C-47BE-9770-A30A046E8090}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -191,6 +193,14 @@ Global {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Release|Win32.Build.0 = Release|Win32 {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Release|x64.ActiveCfg = Release|x64 {C22CB6F8-39A5-4DDA-90ED-4ACA4E81E1E5}.Release|x64.Build.0 = Release|x64 + {009DAC16-1A9C-47BE-9770-A30A046E8090}.Debug|Win32.ActiveCfg = Debug|Win32 + {009DAC16-1A9C-47BE-9770-A30A046E8090}.Debug|Win32.Build.0 = Debug|Win32 + {009DAC16-1A9C-47BE-9770-A30A046E8090}.Debug|x64.ActiveCfg = Debug|x64 + {009DAC16-1A9C-47BE-9770-A30A046E8090}.Debug|x64.Build.0 = Debug|x64 + {009DAC16-1A9C-47BE-9770-A30A046E8090}.Release|Win32.ActiveCfg = Release|Win32 + {009DAC16-1A9C-47BE-9770-A30A046E8090}.Release|Win32.Build.0 = Release|Win32 + {009DAC16-1A9C-47BE-9770-A30A046E8090}.Release|x64.ActiveCfg = Release|x64 + {009DAC16-1A9C-47BE-9770-A30A046E8090}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From d701ffb4780467ca3a40e63ee7774346b9b61758 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Sep 2025 21:37:41 +0200 Subject: [PATCH 1358/2359] Examples: added SDL3+DirectX11 example. Minor amends + fix both SDL2/SDL3+DirectX11 to allow WARP driver. (#8956, #8957) --- docs/CHANGELOG.txt | 5 ++++- docs/EXAMPLES.md | 6 +++++- examples/example_sdl2_directx11/main.cpp | 5 ++++- examples/example_sdl3_directx11/main.cpp | 12 ++++++++---- examples/example_win32_directx10/main.cpp | 2 +- examples/example_win32_directx11/main.cpp | 2 +- examples/example_win32_directx12/main.cpp | 2 +- examples/example_win32_directx9/main.cpp | 2 +- examples/example_win32_opengl3/main.cpp | 2 +- examples/example_win32_vulkan/main.cpp | 2 +- 10 files changed, 27 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c6b65dd2f..87cf826c1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,7 +53,10 @@ Other Changes: ClearRendererHandlers() on shutdown, so as not to leave function pointers which may be dangling when using backend in e.g. DLL. (#8945, #2769) - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support - `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY] + `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] +- Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is + not available. (#5924, #5562) +- Examples: SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] ----------------------------------------------------------------------- diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index 038bd5858..f61297fd1 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -149,8 +149,12 @@ SDL2 (Win32, Mac, Linux, etc.) + Vulkan example.
This is quite long and tedious, because: Vulkan.
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. +[example_sdl3_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_directx11/)
+SDL3 + DirectX11 examples, Windows only.
+= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_dx11.cpp
+ [example_sdl3_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_metal/)
-SDL3 + Metal example (Mac).
+SDL3 + Metal example, Mac only.
= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_metal.mm
[example_sdl3_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_opengl3/)
diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index a2b39f362..ec6602f83 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -230,7 +230,10 @@ bool CreateDeviceD3D(HWND hWnd) //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; D3D_FEATURE_LEVEL featureLevel; const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; - if (D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) + HRESULT res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext); + if (res == DXGI_ERROR_UNSUPPORTED) // Try high-performance WARP software driver if hardware is not available. + res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext); + if (res != S_OK) return false; CreateRenderTarget(); diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index a604e3076..bc8889b8c 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -11,7 +11,7 @@ #include "imgui_impl_sdl3.h" #include "imgui_impl_dx11.h" #include -#include +#include // printf #include // Data @@ -40,7 +40,7 @@ int main(int, char**) // Setup window float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY; - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+DirectX11 example", (int)(1280 * main_scale), (int)(720 * main_scale), window_flags); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+DirectX11 example", (int)(1280 * main_scale), (int)(800 * main_scale), window_flags); if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); @@ -54,7 +54,7 @@ int main(int, char**) if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - return 1; + return -1; } SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); @@ -189,6 +189,7 @@ int main(int, char**) } // Cleanup + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function] ImGui_ImplDX11_Shutdown(); ImGui_ImplSDL3_Shutdown(); ImGui::DestroyContext(); @@ -224,7 +225,10 @@ bool CreateDeviceD3D(HWND hWnd) //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; D3D_FEATURE_LEVEL featureLevel; const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; - if (D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) + HRESULT res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext); + if (res == DXGI_ERROR_UNSUPPORTED) // Try high-performance WARP software driver if hardware is not available. + res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext); + if (res != S_OK) return false; CreateRenderTarget(); diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 12f10ab4d..6fd10f83d 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for DirectX 10 +// Dear ImGui: standalone example application for Windows API + DirectX 10 // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 2b85895f7..5b88007a9 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for DirectX 11 +// Dear ImGui: standalone example application for Windows API + DirectX 11 // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 4ff7c54e5..a5396d31b 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for DirectX 12 +// Dear ImGui: standalone example application for Windows API + DirectX 12 // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 66369d242..b330efdeb 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for DirectX 9 +// Dear ImGui: standalone example application for Windows API + DirectX 9 // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 648d0d969..9ad74d61f 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for Win32 + OpenGL 3 +// Dear ImGui: standalone example application for Windows API + OpenGL // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index b4b3a0860..6063437d8 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for Win32 + Vulkan +// Dear ImGui: standalone example application for Windows API + Vulkan // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq From 5f6eaa5278aa56075f6b001105e2e7dde9cc82ce Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 Sep 2025 16:29:30 +0200 Subject: [PATCH 1359/2359] Backends: Win32: minor optimization not submitting gamepad input if packet number has not changed. (#8556) To be honest I don't believe this is valuable as an optimization, but it makes debug stepping a little nicer. --- backends/imgui_impl_win32.cpp | 5 +++++ docs/CHANGELOG.txt | 2 ++ 2 files changed, 7 insertions(+) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 20dce139e..a8b9ff8ee 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-23: Inputs: Minor optimization not submitting gamepad input if packet number has not changed. // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-04-30: Inputs: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) would fail to claim it again the next subsequent click. (#8594) // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) @@ -124,6 +125,7 @@ struct ImGui_ImplWin32_Data HMODULE XInputDLL; PFN_XInputGetCapabilities XInputGetCapabilities; PFN_XInputGetState XInputGetState; + DWORD XInputPacketNumber; #endif ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); } @@ -355,6 +357,9 @@ static void ImGui_ImplWin32_UpdateGamepads(ImGuiIO& io) if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS) return; io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + if (bd->XInputPacketNumber != 0 && bd->XInputPacketNumber == xinput_state.dwPacketNumber) + return; + bd->XInputPacketNumber = xinput_state.dwPacketNumber; #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) #define MAP_BUTTON(KEY_NO, BUTTON_ENUM) { io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 87cf826c1..8f2aaac11 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,8 @@ Other Changes: which may be dangling when using backend in e.g. DLL. (#8945, #2769) - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] +- Backends: Win32: minor optimization not submitting gamepad io again if + XInput's dwPacketNumber has not changed. (#8556) [@MidTerm-CN] - Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is not available. (#5924, #5562) - Examples: SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] From 82e9a5e47dfbb1954e4c3293302506a0a9f7b29d Mon Sep 17 00:00:00 2001 From: Aleksi Juvani Date: Wed, 19 Mar 2025 14:11:01 +0100 Subject: [PATCH 1360/2359] Windows: add resize grips for child windows with both ResizeX+ResizeY. (#8501) --- imgui.cpp | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 93a77ec25..c3977a21e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6647,8 +6647,19 @@ static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window) return ImGuiCol_WindowBg; } -static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) +static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, ImVec2 corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) { + if (window->Flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent + { + ImGuiWindow* parent_window = window->ParentWindow; + ImGuiWindowFlags parent_flags = parent_window->Flags; + ImRect corner_limit_rect = parent_window->InnerRect; + corner_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize))); + if ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)) + corner_target.x = ImClamp(corner_target.x, corner_limit_rect.Min.x, corner_limit_rect.Max.x); + if (parent_flags & ImGuiWindowFlags_NoScrollbar) + corner_target.y = ImClamp(corner_target.y, corner_limit_rect.Min.y, corner_limit_rect.Max.y); + } ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right ImVec2 size_expected = pos_max - pos_min; @@ -6868,17 +6879,6 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX); ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX); border_target = ImClamp(border_target, clamp_min, clamp_max); - if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent - { - ImGuiWindow* parent_window = window->ParentWindow; - ImGuiWindowFlags parent_flags = parent_window->Flags; - ImRect border_limit_rect = parent_window->InnerRect; - border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize))); - if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar))) - border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x); - if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar)) - border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y); - } if (!ignore_resize) CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target); } @@ -7657,7 +7657,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Handle manual resize: Resize Grips, Borders, Gamepad int border_hovered = -1, border_held = -1; ImU32 resize_grip_col[4] = {}; - const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. + int resize_grip_count; + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) { + // Child windows can only be resized when they have the flags set. The resize grip allows resizing in both directions, so it should appear only if both flags are set. + if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY)) { + resize_grip_count = 1; // Child windows can only be resized in the layout direction, that is rightwards and downwards. + } + else { + resize_grip_count = 0; + } + } + else { + resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. + } const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); if (handle_borders_and_resize_grips && !window->Collapsed) if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) From e1aea42e45165350029d54683c363b623efd7469 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 Sep 2025 16:54:59 +0200 Subject: [PATCH 1361/2359] Windows: add resize grips for child windows with both ResizeX+ResizeY. Amends. (#8501) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 32 ++++++++++++++------------------ 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8f2aaac11..f1a9ff6da 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking Changes: Other Changes: +- Windows: added lower-right resize grip on child windows using both + ImGuiChildFlags_ResizeX and ImGuiChildFlags_ResizeY flags. (#8501) [@aleksijuvani] + The grip is not visible before hovering to reduce clutter. - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() helpers to null all handlers. (#8945, #2769) - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, diff --git a/imgui.cpp b/imgui.cpp index c3977a21e..417747bca 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6647,18 +6647,19 @@ static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window) return ImGuiCol_WindowBg; } -static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, ImVec2 corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) +static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target_arg, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) { + ImVec2 corner_target = corner_target_arg; if (window->Flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent { ImGuiWindow* parent_window = window->ParentWindow; ImGuiWindowFlags parent_flags = parent_window->Flags; - ImRect corner_limit_rect = parent_window->InnerRect; - corner_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize))); + ImRect limit_rect = parent_window->InnerRect; + limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize))); if ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)) - corner_target.x = ImClamp(corner_target.x, corner_limit_rect.Min.x, corner_limit_rect.Max.x); + corner_target.x = ImClamp(corner_target.x, limit_rect.Min.x, limit_rect.Max.x); if (parent_flags & ImGuiWindowFlags_NoScrollbar) - corner_target.y = ImClamp(corner_target.y, corner_limit_rect.Min.y, corner_limit_rect.Max.y); + corner_target.y = ImClamp(corner_target.y, limit_rect.Min.y, limit_rect.Max.y); } ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right @@ -6804,7 +6805,8 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si } // Only lower-left grip is visible before hovering/activating - if (resize_grip_n == 0 || held || hovered) + const bool resize_grip_visible = held || hovered || (resize_grip_n == 0 && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0); + if (resize_grip_visible) resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); } @@ -7655,21 +7657,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) handle_borders_and_resize_grips = false; // Handle manual resize: Resize Grips, Borders, Gamepad + // Child windows can only be resized when they have the flags set. The resize grip allows resizing in both directions, so it should appear only if both flags are set. int border_hovered = -1, border_held = -1; ImU32 resize_grip_col[4] = {}; int resize_grip_count; - if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) { - // Child windows can only be resized when they have the flags set. The resize grip allows resizing in both directions, so it should appear only if both flags are set. - if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY)) { - resize_grip_count = 1; // Child windows can only be resized in the layout direction, that is rightwards and downwards. - } - else { - resize_grip_count = 0; - } - } - else { - resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. - } + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) + resize_grip_count = ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY)) ? 1 : 0; + else + resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. + const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); if (handle_borders_and_resize_grips && !window->Collapsed) if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) From e06b5dfe129ccfc3ab6f28e68bee34cb64a72345 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Sep 2025 14:17:24 +0200 Subject: [PATCH 1362/2359] Backends: SDL2,SDL3: Shallow tweaks. Toward fallback focused mouse handler to be a closer match docking version. --- backends/imgui_impl_sdl2.cpp | 13 ++++++++----- backends/imgui_impl_sdl3.cpp | 10 ++++++---- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index acd98f641..a116063ad 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -674,15 +674,18 @@ static void ImGui_ImplSDL2_UpdateMouseData() if (io.WantSetMousePos) SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y); - // (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured) + // (Optional) Fallback to provide unclamped mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured) const bool is_relative_mouse_mode = SDL_GetRelativeMouseMode() != 0; if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) { // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) - int window_x, window_y, mouse_x_global, mouse_y_global; - SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); - SDL_GetWindowPosition(bd->Window, &window_x, &window_y); - io.AddMousePosEvent((float)(mouse_x_global - window_x), (float)(mouse_y_global - window_y)); + int mouse_x, mouse_y; + int window_x, window_y; + SDL_GetGlobalMouseState(&mouse_x, &mouse_y); + SDL_GetWindowPosition(focused_window, &window_x, &window_y); + mouse_x -= window_x; + mouse_y -= window_y; + io.AddMousePosEvent((float)mouse_x, (float)mouse_y); } } } diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 83dc93282..871e7aba4 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -636,16 +636,18 @@ static void ImGui_ImplSDL3_UpdateMouseData() if (io.WantSetMousePos) SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); - // (Optional) Fallback to provide mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) + // (Optional) Fallback to provide unclamped mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) const bool is_relative_mouse_mode = SDL_GetWindowRelativeMouseMode(bd->Window); if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) { // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) - float mouse_x_global, mouse_y_global; + float mouse_x, mouse_y; int window_x, window_y; - SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); + SDL_GetGlobalMouseState(&mouse_x, &mouse_y); SDL_GetWindowPosition(focused_window, &window_x, &window_y); - io.AddMousePosEvent(mouse_x_global - window_x, mouse_y_global - window_y); + mouse_x -= window_x; + mouse_y -= window_y; + io.AddMousePosEvent(mouse_x, mouse_y); } } } From f61a7ef222747779a81dfa6cc44c648eb944fa6a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Sep 2025 14:48:33 +0200 Subject: [PATCH 1363/2359] Backends: SDL2,SDL3: avoid using the SDL_GetGlobalMouseState() path when one of our window is hovered. Fix mouse coordinate issue in fullscreen apps with macOS notch + better X11 perfs. (#7919, #7786) --- backends/imgui_impl_sdl2.cpp | 6 ++++-- backends/imgui_impl_sdl3.cpp | 6 ++++-- docs/CHANGELOG.txt | 4 ++++ imgui.h | 2 +- 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index a116063ad..53336995e 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-24: Skip using the SDL_GetGlobalMouseState() state when one of our window is hovered, as the SDL_MOUSEMOTION data is reliable. Fix macOS notch mouse coordinates issue in fullscreen mode + better perf on X11. (#7919, #7786) // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Content Scales are always reported as 1.0 on Wayland. (#8921) // 2025-07-08: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) @@ -674,9 +675,10 @@ static void ImGui_ImplSDL2_UpdateMouseData() if (io.WantSetMousePos) SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y); - // (Optional) Fallback to provide unclamped mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured) + // (Optional) Fallback to provide unclamped mouse position when focused but not hovered (SDL_MOUSEMOTION already provides this when hovered or captured) + SDL_Window* hovered_window = SDL_GetMouseFocus(); const bool is_relative_mouse_mode = SDL_GetRelativeMouseMode() != 0; - if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) + if (hovered_window == NULL && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) { // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) int mouse_x, mouse_y; diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 871e7aba4..77e5b94a8 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-24: Skip using the SDL_GetGlobalMouseState() state when one of our window is hovered, as the SDL_EVENT_MOUSE_MOTION data is reliable. Fix macOS notch mouse coordinates issue in fullscreen mode + better perf on X11. (#7919, #7786) // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Use SDL_GetWindowDisplayScale() on Mac to output DisplayFrameBufferScale. The function is more reliable during resolution changes e.g. going fullscreen. (#8703, #4414) // 2025-06-27: IME: avoid calling SDL_StartTextInput() again if already active. (#8727) @@ -636,9 +637,10 @@ static void ImGui_ImplSDL3_UpdateMouseData() if (io.WantSetMousePos) SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); - // (Optional) Fallback to provide unclamped mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) + // (Optional) Fallback to provide unclamped mouse position when focused but not hovered (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) + SDL_Window* hovered_window = SDL_GetMouseFocus(); const bool is_relative_mouse_mode = SDL_GetWindowRelativeMouseMode(bd->Window); - if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) + if (hovered_window == NULL && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) { // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) float mouse_x, mouse_y; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f1a9ff6da..9906174a5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,6 +57,10 @@ Other Changes: which may be dangling when using backend in e.g. DLL. (#8945, #2769) - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] +- Backends: SDL2,SDL3: avoid using the SDL_GetGlobalMouseState() path when one of our + window is hovered, as the event data is reliable and enough in this case. + - Fix mouse coordinates issue in fullscreen apps with macOS notch. (#7919, #7786) + - Better perf on X11 as querying global position requires a round trip to X11 server. - Backends: Win32: minor optimization not submitting gamepad io again if XInput's dwPacketNumber has not changed. (#8556) [@MidTerm-CN] - Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is diff --git a/imgui.h b/imgui.h index 682364004..f04e8c0e4 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.4 WIP" -#define IMGUI_VERSION_NUM 19231 +#define IMGUI_VERSION_NUM 19232 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From 719ea9c2284069c52135f1400d7fb7640e3d54ad Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Sep 2025 15:00:24 +0200 Subject: [PATCH 1364/2359] Comments --- backends/imgui_impl_sdl2.cpp | 1 + backends/imgui_impl_sdl3.cpp | 1 + docs/CHANGELOG.txt | 1 + 3 files changed, 3 insertions(+) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 53336995e..12a8438b9 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -676,6 +676,7 @@ static void ImGui_ImplSDL2_UpdateMouseData() SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y); // (Optional) Fallback to provide unclamped mouse position when focused but not hovered (SDL_MOUSEMOTION already provides this when hovered or captured) + // Note that SDL_GetGlobalMouseState() is in theory slow on X11, but this only runs on rather specific cases. If a problem we may provide a way to opt-out this feature. SDL_Window* hovered_window = SDL_GetMouseFocus(); const bool is_relative_mouse_mode = SDL_GetRelativeMouseMode() != 0; if (hovered_window == NULL && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 77e5b94a8..564131a4d 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -638,6 +638,7 @@ static void ImGui_ImplSDL3_UpdateMouseData() SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); // (Optional) Fallback to provide unclamped mouse position when focused but not hovered (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) + // Note that SDL_GetGlobalMouseState() is in theory slow on X11, but this only runs on rather specific cases. If a problem we may provide a way to opt-out this feature. SDL_Window* hovered_window = SDL_GetMouseFocus(); const bool is_relative_mouse_mode = SDL_GetWindowRelativeMouseMode(bd->Window); if (hovered_window == NULL && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9906174a5..3357a1547 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,7 @@ Other Changes: - Backends: SDL2,SDL3: avoid using the SDL_GetGlobalMouseState() path when one of our window is hovered, as the event data is reliable and enough in this case. - Fix mouse coordinates issue in fullscreen apps with macOS notch. (#7919, #7786) + - Essentially a working for SDL3 bug which will be fixed in SDL 3.3.0. - Better perf on X11 as querying global position requires a round trip to X11 server. - Backends: Win32: minor optimization not submitting gamepad io again if XInput's dwPacketNumber has not changed. (#8556) [@MidTerm-CN] From 940627d008b8f0584b7f50d24574537cf24a32e1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Sep 2025 15:29:00 +0200 Subject: [PATCH 1365/2359] Backends: SDL2: Fixed build for Emscripten and SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE=0 platforms. Amend e06b5df. --- backends/imgui_impl_sdl2.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 12a8438b9..c2dae4053 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -667,6 +667,7 @@ static void ImGui_ImplSDL2_UpdateMouseData() SDL_Window* focused_window = SDL_GetKeyboardFocus(); const bool is_app_focused = (bd->Window == focused_window); #else + SDL_Window* focused_window = bd->Window; const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only #endif if (is_app_focused) From cee40f8af99eee390eb17adfe79a68a26d83c436 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 24 Sep 2025 17:48:48 +0200 Subject: [PATCH 1366/2359] Examples: made examples's main.cpp consistent with returning 1 on error. --- docs/CHANGELOG.txt | 1 + examples/example_sdl2_directx11/main.cpp | 4 ++-- examples/example_sdl2_metal/main.mm | 2 +- examples/example_sdl2_opengl2/main.cpp | 4 ++-- examples/example_sdl2_opengl3/main.cpp | 6 +++--- examples/example_sdl2_sdlrenderer2/main.cpp | 6 +++--- examples/example_sdl2_vulkan/main.cpp | 4 ++-- examples/example_sdl3_directx11/main.cpp | 6 +++--- examples/example_sdl3_metal/main.mm | 10 +++++----- examples/example_sdl3_opengl3/main.cpp | 6 +++--- examples/example_sdl3_sdlgpu3/main.cpp | 8 ++++---- examples/example_sdl3_sdlrenderer3/main.cpp | 6 +++--- examples/example_sdl3_vulkan/main.cpp | 4 ++-- 13 files changed, 34 insertions(+), 33 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3357a1547..04ca7ef1c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,7 @@ Other Changes: - Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is not available. (#5924, #5562) - Examples: SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] +- Examples: made examples's main.cpp consistent with returning 1 on error. ----------------------------------------------------------------------- diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index ec6602f83..e14085dd3 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -39,7 +39,7 @@ int main(int, char**) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); - return -1; + return 1; } // From 2.0.18: Enable native IME. @@ -54,7 +54,7 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_SysWMinfo wmInfo; diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index 80c7e7b1a..0f60d771d 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -51,7 +51,7 @@ int main(int, char**) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); - return -1; + return 1; } // Inform SDL that we will be using metal for rendering. Without this hint initialization of metal renderer may fail. diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index a06b58c8c..327780e20 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -31,7 +31,7 @@ int main(int, char**) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); - return -1; + return 1; } // From 2.0.18: Enable native IME. @@ -51,7 +51,7 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_GLContext gl_context = SDL_GL_CreateContext(window); diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index 96631271b..4a655ac61 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -36,7 +36,7 @@ int main(int, char**) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); - return -1; + return 1; } // Decide GL+GLSL versions @@ -85,14 +85,14 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_GLContext gl_context = SDL_GL_CreateContext(window); if (gl_context == nullptr) { printf("Error: SDL_GL_CreateContext(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_GL_MakeCurrent(window, gl_context); diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 60b365e6e..214f6f471 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -33,7 +33,7 @@ int main(int, char**) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); - return -1; + return 1; } // From 2.0.18: Enable native IME. @@ -48,13 +48,13 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); if (renderer == nullptr) { SDL_Log("Error creating SDL_Renderer!"); - return -1; + return 1; } //SDL_RendererInfo info; //SDL_GetRendererInfo(renderer, &info); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 4a1228058..8dd505889 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -349,7 +349,7 @@ int main(int, char**) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); - return -1; + return 1; } // From 2.0.18: Enable native IME. @@ -364,7 +364,7 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } ImVector extensions; diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index bc8889b8c..946992409 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -34,7 +34,7 @@ int main(int, char**) if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); - return -1; + return 1; } // Setup window @@ -44,7 +44,7 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_PropertiesID props = SDL_GetWindowProperties(window); @@ -54,7 +54,7 @@ int main(int, char**) if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - return -1; + return 1; } SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index 022e0f432..1dd80d010 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -24,7 +24,7 @@ int main(int, char**) if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); - return -1; + return 1; } // Create SDL window graphics context @@ -34,19 +34,19 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_ShowWindow(window); // Create Metal device _before_ creating the view/layer - id metalDevice = MTLCreateSystemDefaultDevice(); + id metalDevice = MTLCreateSystemDefaultDevice(); if (!metalDevice) { printf("Error: failed to create Metal device.\n"); SDL_DestroyWindow(window); SDL_Quit(); - return -1; + return 1; } SDL_MetalView view = SDL_Metal_CreateView(window); CAMetalLayer* layer = (__bridge CAMetalLayer*)SDL_Metal_GetLayer(view); @@ -128,7 +128,7 @@ int main(int, char**) int width, height; SDL_GetWindowSizeInPixels(window, &width, &height); - + layer.drawableSize = CGSizeMake(width, height); id drawable = [layer nextDrawable]; diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 36b5e2eba..44a6417d1 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -30,7 +30,7 @@ int main(int, char**) if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); - return -1; + return 1; } // Decide GL+GLSL versions @@ -74,13 +74,13 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_GLContext gl_context = SDL_GL_CreateContext(window); if (gl_context == nullptr) { printf("Error: SDL_GL_CreateContext(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_GL_MakeCurrent(window, gl_context); diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 3f797ecd6..84b0a254f 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -31,7 +31,7 @@ int main(int, char**) if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); - return -1; + return 1; } // Create SDL window graphics context @@ -41,7 +41,7 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_ShowWindow(window); @@ -51,14 +51,14 @@ int main(int, char**) if (gpu_device == nullptr) { printf("Error: SDL_CreateGPUDevice(): %s\n", SDL_GetError()); - return -1; + return 1; } // Claim window for GPU Device if (!SDL_ClaimWindowForGPUDevice(gpu_device, window)) { printf("Error: SDL_ClaimWindowForGPUDevice(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_SetGPUSwapchainParameters(gpu_device, window, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, SDL_GPU_PRESENTMODE_VSYNC); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 2256b7da7..39870f2c6 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -28,7 +28,7 @@ int main(int, char**) if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); - return -1; + return 1; } // Create window with SDL_Renderer graphics context @@ -38,14 +38,14 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_Renderer* renderer = SDL_CreateRenderer(window, nullptr); SDL_SetRenderVSync(renderer, 1); if (renderer == nullptr) { SDL_Log("Error: SDL_CreateRenderer(): %s\n", SDL_GetError()); - return -1; + return 1; } SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_ShowWindow(window); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index dd9a460c9..060855259 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -349,7 +349,7 @@ int main(int, char**) if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) { printf("Error: SDL_Init(): %s\n", SDL_GetError()); - return -1; + return 1; } // Create window with Vulkan graphics context @@ -359,7 +359,7 @@ int main(int, char**) if (window == nullptr) { printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; + return 1; } ImVector extensions; From bf2e0b2c6f053c5633b8288d7ffc17ab92ea923c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 25 Sep 2025 19:07:51 +0200 Subject: [PATCH 1367/2359] Tables: change ImGuiTableFlags_NoBordersInBody behavior to not draw border in body even when resizing. (#8893) --- imgui_tables.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 21d5335c6..af0e8c6cf 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2818,8 +2818,13 @@ void ImGui::TableDrawBorders(ImGuiTable* table) continue; // Draw in outer window so right-most column won't be clipped - // Always draw full height border when being resized/hovered, or on the delimitation of frozen column scrolling. - float draw_y2 = (is_hovered || is_resized || is_frozen_separator || (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) == 0) ? draw_y2_body : draw_y2_head; + float draw_y2 = draw_y2_head; + if (is_frozen_separator) + draw_y2 = draw_y2_body; + else if ((table->Flags & ImGuiTableFlags_NoBordersInBodyUntilResize) != 0 && (is_hovered || is_resized)) + draw_y2 = draw_y2_body; + else if ((table->Flags & (ImGuiTableFlags_NoBordersInBodyUntilResize | ImGuiTableFlags_NoBordersInBody)) == 0) + draw_y2 = draw_y2_body; if (draw_y2 > draw_y1) inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), TableGetColumnBorderCol(table, order_n, column_n), border_size); } From 01686c6294a778b017f63eaad4c9d391fd77495a Mon Sep 17 00:00:00 2001 From: johan0A Date: Sat, 5 Apr 2025 21:36:20 +0200 Subject: [PATCH 1368/2359] Backends: Vulkan: added a way to specify custom vertex/fragment shaders. (#8585, #8271) --- backends/imgui_impl_vulkan.cpp | 25 ++++++++++++++----------- backends/imgui_impl_vulkan.h | 8 +++++++- docs/CHANGELOG.txt | 2 ++ 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 4a0a5a947..0e0ba719b 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-26: Vulkan: Added a way to customize shaders by filling ImGui_ImplVulkan_InitInfo::CustomShaderVertCreateInfo/CustomShaderFragCreateInfo. (#8585) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-09-04: Vulkan: Added ImGui_ImplVulkan_CreateMainPipeline(). (#8110, #8111) // 2025-07-27: Vulkan: Fixed texture update corruption introduced on 2025-06-11. (#8801, #8755, #8840) @@ -887,24 +888,26 @@ void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator) { - // Create the shader modules ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; if (bd->ShaderModuleVert == VK_NULL_HANDLE) { - VkShaderModuleCreateInfo vert_info = {}; - vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - vert_info.codeSize = sizeof(__glsl_shader_vert_spv); - vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; - VkResult err = vkCreateShaderModule(device, &vert_info, allocator, &bd->ShaderModuleVert); + VkShaderModuleCreateInfo default_vert_info = {}; + default_vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + default_vert_info.codeSize = sizeof(__glsl_shader_vert_spv); + default_vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; + VkShaderModuleCreateInfo* p_vert_info = (v->CustomShaderVertCreateInfo.sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) ? &v->CustomShaderVertCreateInfo : &default_vert_info; + VkResult err = vkCreateShaderModule(device, p_vert_info, allocator, &bd->ShaderModuleVert); check_vk_result(err); } if (bd->ShaderModuleFrag == VK_NULL_HANDLE) { - VkShaderModuleCreateInfo frag_info = {}; - frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - frag_info.codeSize = sizeof(__glsl_shader_frag_spv); - frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; - VkResult err = vkCreateShaderModule(device, &frag_info, allocator, &bd->ShaderModuleFrag); + VkShaderModuleCreateInfo default_frag_info = {}; + default_frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + default_frag_info.codeSize = sizeof(__glsl_shader_frag_spv); + default_frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; + VkShaderModuleCreateInfo* p_frag_info = (v->CustomShaderFragCreateInfo.sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) ? &v->CustomShaderFragCreateInfo : &default_frag_info; + VkResult err = vkCreateShaderModule(device, p_frag_info, allocator, &bd->ShaderModuleFrag); check_vk_result(err); } } diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index a24cb2cdb..cf1a5b9a1 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -102,7 +102,13 @@ struct ImGui_ImplVulkan_InitInfo // (Optional) Allocation, Debugging const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); - VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. + VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. + + // (Optional) Customize default vertex/fragment shaders. + // - if .sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO we use specified structs, otherwise we use defaults. + // - Shader inputs/outputs need to match ours. Code/data pointed to by the structure needs to survive for whole during of backend usage. + VkShaderModuleCreateInfo CustomShaderVertCreateInfo; + VkShaderModuleCreateInfo CustomShaderFragCreateInfo; }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 04ca7ef1c..ce9a22f5a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,8 @@ Other Changes: - Better perf on X11 as querying global position requires a round trip to X11 server. - Backends: Win32: minor optimization not submitting gamepad io again if XInput's dwPacketNumber has not changed. (#8556) [@MidTerm-CN] +- Backends: Vulkan: added a way to specify custom shaders by filling init fields + CustomShaderVertCreateInfo and CustomShaderFragCreateInfo. (#8585, #8271) [@johan0A] - Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is not available. (#5924, #5562) - Examples: SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] From 5fe962216ac8af5688602ea01d51313f3b949c74 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 26 Sep 2025 17:32:39 +0200 Subject: [PATCH 1369/2359] (Breaking) Backends: Vulkan: added 'VkImageUsageFlags image_usage' parameter to ImGui_ImplVulkanH_CreateOrResizeWindow(). (#8946, #8110, #8111, #8686) Default to VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT. --- backends/imgui_impl_vulkan.cpp | 12 +++++++----- backends/imgui_impl_vulkan.h | 4 ++-- docs/CHANGELOG.txt | 6 ++++++ examples/example_glfw_vulkan/main.cpp | 5 +++-- examples/example_sdl2_vulkan/main.cpp | 5 +++-- examples/example_sdl3_vulkan/main.cpp | 5 +++-- examples/example_win32_vulkan/main.cpp | 5 +++-- 7 files changed, 27 insertions(+), 15 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 0e0ba719b..7a8d26362 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-26: *BREAKING CHANGE*: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a VkImageUsageFlags image_usage` argument, default to VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT if 0. // 2025-09-26: Vulkan: Added a way to customize shaders by filling ImGui_ImplVulkan_InitInfo::CustomShaderVertCreateInfo/CustomShaderFragCreateInfo. (#8585) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-09-04: Vulkan: Added ImGui_ImplVulkan_CreateMainPipeline(). (#8110, #8111) @@ -118,7 +119,7 @@ void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulka void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count, VkImageUsageFlags image_usage); void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); // Vulkan prototypes for use with custom loaders @@ -1605,7 +1606,7 @@ int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_m } // Also destroy old swap chain and in-flight frames data, if any. -void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) +void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count, VkImageUsageFlags image_usage) { VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; @@ -1644,7 +1645,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V info.imageFormat = wd->SurfaceFormat.format; info.imageColorSpace = wd->SurfaceFormat.colorSpace; info.imageArrayLayers = 1; - info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + info.imageUsage = (image_usage != 0) ? image_usage : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // Assume that graphics family == present family info.preTransform = (cap.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR : cap.currentTransform; info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; @@ -1772,11 +1773,12 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V } // Create or resize window -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) +// - 2025/09/26: v1.92.4 added a trailing 'VkImageUsageFlags image_usage' parameter which is usually VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT. +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!"); (void)instance; - ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); + 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 diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index cf1a5b9a1..62158b7f9 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -181,8 +181,8 @@ struct ImGui_ImplVulkanH_Frame; struct ImGui_ImplVulkanH_Window; // Helpers -IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); -IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); +IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count, VkImageUsageFlags image_usage); +IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator); IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); IMGUI_IMPL_API VkPhysicalDevice ImGui_ImplVulkanH_SelectPhysicalDevice(VkInstance instance); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ce9a22f5a..1f6e463f5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,12 @@ HOW TO UPDATE? Breaking Changes: +- Backends: Vulkan: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a + `VkImageUsageFlags image_usage` argument. + It was previously hardcoded to `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` and defaults + to that when the value is 0. In theory the function is an internal helper but + since it's used by our examples some may have used it. (#8946, #8111, #8686) + Other Changes: - Windows: added lower-right resize grip on child windows using both diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index ebc78bdd5..176c8c4d3 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -54,6 +54,7 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; +static VkImageUsageFlags g_SwapChainImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static void glfw_error_callback(int error, const char* description) { @@ -239,7 +240,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, g_SwapChainImageUsage); } static void CleanupVulkan() @@ -456,7 +457,7 @@ int main(int, char**) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, g_SwapChainImageUsage); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 8dd505889..21e892779 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -49,6 +49,7 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; +static VkImageUsageFlags g_SwapChainImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static void check_vk_result(VkResult err) { @@ -230,7 +231,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, g_SwapChainImageUsage); } static void CleanupVulkan() @@ -476,7 +477,7 @@ int main(int, char**) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, g_SwapChainImageUsage); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 060855259..e4cecf210 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -51,6 +51,7 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; +static VkImageUsageFlags g_SwapChainImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static void check_vk_result(VkResult err) { @@ -232,7 +233,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, g_SwapChainImageUsage); } static void CleanupVulkan() @@ -478,7 +479,7 @@ int main(int, char**) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_height, fb_height, g_MinImageCount, g_SwapChainImageUsage); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 6063437d8..7a68ccbdd 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -47,6 +47,7 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; +static VkImageUsageFlags g_SwapChainImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static void check_vk_result(VkResult err) { @@ -228,7 +229,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, g_SwapChainImageUsage); } static void CleanupVulkan() @@ -549,7 +550,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, g_SwapChainImageUsage); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } From cc0a6690bfb5af6ae38723587ec74e120142c67b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 26 Sep 2025 17:33:32 +0200 Subject: [PATCH 1370/2359] Backends: Vulkan: minor internal renames/tweaks to reduce further patches. (#8946, #8110, #8111, #8686) --- backends/imgui_impl_vulkan.cpp | 45 +++++++++++++++++----------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 7a8d26362..49ceeef0b 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1001,22 +1001,22 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states); dynamic_state.pDynamicStates = dynamic_states; - VkGraphicsPipelineCreateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; - info.flags = bd->PipelineCreateFlags; - info.stageCount = 2; - info.pStages = stage; - info.pVertexInputState = &vertex_info; - info.pInputAssemblyState = &ia_info; - info.pViewportState = &viewport_info; - info.pRasterizationState = &raster_info; - info.pMultisampleState = &ms_info; - info.pDepthStencilState = &depth_info; - info.pColorBlendState = &blend_info; - info.pDynamicState = &dynamic_state; - info.layout = bd->PipelineLayout; - info.renderPass = renderPass; - info.subpass = subpass; + VkGraphicsPipelineCreateInfo create_info = {}; + create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + create_info.flags = bd->PipelineCreateFlags; + create_info.stageCount = 2; + create_info.pStages = stage; + create_info.pVertexInputState = &vertex_info; + create_info.pInputAssemblyState = &ia_info; + create_info.pViewportState = &viewport_info; + create_info.pRasterizationState = &raster_info; + create_info.pMultisampleState = &ms_info; + create_info.pDepthStencilState = &depth_info; + create_info.pColorBlendState = &blend_info; + create_info.pDynamicState = &dynamic_state; + create_info.layout = bd->PipelineLayout; + create_info.renderPass = renderPass; + create_info.subpass = subpass; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING if (bd->VulkanInitInfo.UseDynamicRendering) @@ -1024,14 +1024,14 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc IM_ASSERT(pipeline_rendering_create_info && "PipelineRenderingCreateInfo must not be nullptr when using dynamic rendering"); IM_ASSERT(pipeline_rendering_create_info->sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo::sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); IM_ASSERT(pipeline_rendering_create_info->pNext == nullptr && "PipelineRenderingCreateInfo::pNext must be nullptr"); - info.pNext = pipeline_rendering_create_info; - info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. + create_info.pNext = pipeline_rendering_create_info; + create_info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. } #else IM_ASSERT(pipeline_rendering_create_info == nullptr); #endif VkPipeline pipeline; - VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, &pipeline); + VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &create_info, allocator, &pipeline); check_vk_result(err); return pipeline; } @@ -1108,11 +1108,11 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() } // Create pipeline - if (v->RenderPass + bool create_main_pipeline = (v->RenderPass != VK_NULL_HANDLE); #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - || (v->UseDynamicRendering && v->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR) + create_main_pipeline |= (v->UseDynamicRendering && v->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR); #endif - ) + if (create_main_pipeline) { ImGui_ImplVulkan_MainPipelineCreateInfo mp_info = {}; mp_info.RenderPass = v->RenderPass; @@ -1292,6 +1292,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + // Sanity checks IM_ASSERT(info->Instance != VK_NULL_HANDLE); IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE); IM_ASSERT(info->Device != VK_NULL_HANDLE); From e312b99296336c01b43ca91d42036022c6c20844 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 26 Sep 2025 17:37:42 +0200 Subject: [PATCH 1371/2359] (Breaking) Backends: Vulkan: renamed ImGui_ImplVulkan_MainPipelineCreateInfo to ImGui_ImplVulkan_PipelineInfo. (#8110, #8111) --- backends/imgui_impl_vulkan.cpp | 5 +++-- backends/imgui_impl_vulkan.h | 4 ++-- docs/CHANGELOG.txt | 3 +++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 49ceeef0b..ecd8b98d2 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-26: *BREAKING CHANGE*: renamed ImGui_ImplVulkan_MainPipelineCreateInfo to ImGui_ImplVulkan_PipelineInfo. Introduced very recently so shouldn't affect many users. // 2025-09-26: *BREAKING CHANGE*: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a VkImageUsageFlags image_usage` argument, default to VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT if 0. // 2025-09-26: Vulkan: Added a way to customize shaders by filling ImGui_ImplVulkan_InitInfo::CustomShaderVertCreateInfo/CustomShaderFragCreateInfo. (#8585) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. @@ -1114,7 +1115,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() #endif if (create_main_pipeline) { - ImGui_ImplVulkan_MainPipelineCreateInfo mp_info = {}; + ImGui_ImplVulkan_PipelineInfo mp_info = {}; mp_info.RenderPass = v->RenderPass; mp_info.Subpass = v->Subpass; mp_info.MSAASamples = v->MSAASamples; @@ -1147,7 +1148,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() return true; } -void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCreateInfo& info) +void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo& info) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 62158b7f9..a174e72d5 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -121,7 +121,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_i // (Advanced) Use e.g. if you need to recreate pipeline without reinitializing the backend (see #8110, #8111) // The main window pipeline will be created by ImGui_ImplVulkan_Init() if possible (== RenderPass xor (UseDynamicRendering && PipelineRenderingCreateInfo->sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR)) // Else, the pipeline can be created, or re-created, using ImGui_ImplVulkan_CreateMainPipeline() before rendering. -struct ImGui_ImplVulkan_MainPipelineCreateInfo +struct ImGui_ImplVulkan_PipelineInfo { VkRenderPass RenderPass = VK_NULL_HANDLE; uint32_t Subpass = 0; @@ -130,7 +130,7 @@ struct ImGui_ImplVulkan_MainPipelineCreateInfo VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR #endif }; -IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_MainPipelineCreateInfo& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext))) +IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext))) // (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. IMGUI_IMPL_API void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1f6e463f5..912527734 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ HOW TO UPDATE? Breaking Changes: +- Backends: Vulkan: renamed ImGui_ImplVulkan_MainPipelineCreateInfo --> ImGui_ImplVulkan_PipelineInfo + (introduced very recently and only used by `ImGui_ImplVulkan_CreateMainPipeline()` + so it should not affect many users). (#8110, #8111) - Backends: Vulkan: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a `VkImageUsageFlags image_usage` argument. It was previously hardcoded to `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` and defaults From 3470e6112b8bb81059ec461e56385dc91d89dcb7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 26 Sep 2025 18:23:03 +0200 Subject: [PATCH 1372/2359] (Breaking) Backends: Vulkan: moved fields in ImGui_ImplVulkan_InitInfo: RenderPass, Subpass, MSAASamples, PipelineRenderingCreateInfo. (#8946, #8110, #8111, #8686) --- backends/imgui_impl_vulkan.cpp | 70 +++++++++++--------------- backends/imgui_impl_vulkan.h | 36 ++++++------- docs/CHANGELOG.txt | 7 +++ examples/example_glfw_vulkan/main.cpp | 6 +-- examples/example_sdl2_vulkan/main.cpp | 6 +-- examples/example_sdl3_vulkan/main.cpp | 6 +-- examples/example_win32_vulkan/main.cpp | 6 +-- imgui.h | 2 +- 8 files changed, 67 insertions(+), 72 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index ecd8b98d2..60554368e 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-26: *BREAKING CHANGE*: moved some fields in ImGui_ImplVulkan_InitInfo: init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass, init_info.Subpass --> init_info.PipelineInfoMain.Subpass, init_info.MSAASamples --> init_info.PipelineInfoMain.MSAASamples, init_info.PipelineRenderingCreateInfo --> init_info.PipelineInfoMain.PipelineRenderingCreateInfo. // 2025-09-26: *BREAKING CHANGE*: renamed ImGui_ImplVulkan_MainPipelineCreateInfo to ImGui_ImplVulkan_PipelineInfo. Introduced very recently so shouldn't affect many users. // 2025-09-26: *BREAKING CHANGE*: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a VkImageUsageFlags image_usage` argument, default to VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT if 0. // 2025-09-26: Vulkan: Added a way to customize shaders by filling ImGui_ImplVulkan_InitInfo::CustomShaderVertCreateInfo/CustomShaderFragCreateInfo. (#8585) @@ -918,7 +919,7 @@ static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAlloca typedef void VkPipelineRenderingCreateInfoKHR; #endif -static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, uint32_t subpass, const VkPipelineRenderingCreateInfoKHR* pipeline_rendering_create_info) +static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, const ImGui_ImplVulkan_PipelineInfo* info) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_CreateShaderModules(device, allocator); @@ -976,7 +977,7 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc VkPipelineMultisampleStateCreateInfo ms_info = {}; ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - ms_info.rasterizationSamples = (MSAASamples != 0) ? MSAASamples : VK_SAMPLE_COUNT_1_BIT; + ms_info.rasterizationSamples = (info->MSAASamples != 0) ? info->MSAASamples : VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState color_attachment[1] = {}; color_attachment[0].blendEnable = VK_TRUE; @@ -1016,20 +1017,17 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc create_info.pColorBlendState = &blend_info; create_info.pDynamicState = &dynamic_state; create_info.layout = bd->PipelineLayout; - create_info.renderPass = renderPass; - create_info.subpass = subpass; + create_info.renderPass = info->RenderPass; + create_info.subpass = info->Subpass; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING if (bd->VulkanInitInfo.UseDynamicRendering) { - IM_ASSERT(pipeline_rendering_create_info && "PipelineRenderingCreateInfo must not be nullptr when using dynamic rendering"); - IM_ASSERT(pipeline_rendering_create_info->sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo::sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); - IM_ASSERT(pipeline_rendering_create_info->pNext == nullptr && "PipelineRenderingCreateInfo::pNext must be nullptr"); - create_info.pNext = pipeline_rendering_create_info; + IM_ASSERT(info->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo::sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); + IM_ASSERT(info->PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo::pNext must be nullptr"); + create_info.pNext = &info->PipelineRenderingCreateInfo; create_info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. } -#else - IM_ASSERT(pipeline_rendering_create_info == nullptr); #endif VkPipeline pipeline; VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &create_info, allocator, &pipeline); @@ -1109,21 +1107,12 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() } // Create pipeline - bool create_main_pipeline = (v->RenderPass != VK_NULL_HANDLE); + bool create_main_pipeline = (v->PipelineInfoMain.RenderPass != VK_NULL_HANDLE); #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - create_main_pipeline |= (v->UseDynamicRendering && v->PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR); + create_main_pipeline |= (v->UseDynamicRendering && v->PipelineInfoMain.PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR); #endif if (create_main_pipeline) - { - ImGui_ImplVulkan_PipelineInfo mp_info = {}; - mp_info.RenderPass = v->RenderPass; - mp_info.Subpass = v->Subpass; - mp_info.MSAASamples = v->MSAASamples; -#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - mp_info.PipelineRenderingCreateInfo = v->PipelineRenderingCreateInfo; -#endif - ImGui_ImplVulkan_CreateMainPipeline(mp_info); - } + ImGui_ImplVulkan_CreateMainPipeline(&v->PipelineInfoMain); // Create command pool/buffer for texture upload if (!bd->TexCommandPool) @@ -1148,7 +1137,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() return true; } -void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo& info) +void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo* pipeline_info_in) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; @@ -1157,28 +1146,23 @@ void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo& in vkDestroyPipeline(v->Device, bd->Pipeline, v->Allocator); bd->Pipeline = VK_NULL_HANDLE; } - v->RenderPass = info.RenderPass; - v->MSAASamples = info.MSAASamples; - v->Subpass = info.Subpass; + ImGui_ImplVulkan_PipelineInfo* pipeline_info = &v->PipelineInfoMain; + if (pipeline_info != pipeline_info_in) + *pipeline_info = *pipeline_info_in; - const VkPipelineRenderingCreateInfoKHR* pipeline_rendering_create_info = nullptr; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - if (v->UseDynamicRendering) + VkPipelineRenderingCreateInfoKHR* pipeline_rendering_create_info = &pipeline_info->PipelineRenderingCreateInfo; + if (v->UseDynamicRendering && pipeline_rendering_create_info->pColorAttachmentFormats != NULL) { - v->PipelineRenderingCreateInfo = info.PipelineRenderingCreateInfo; - pipeline_rendering_create_info = &v->PipelineRenderingCreateInfo; - if (v->PipelineRenderingCreateInfo.pColorAttachmentFormats != NULL) - { - // Deep copy buffer to reduce error-rate for end user (#8282) - ImVector formats; - formats.resize((int)v->PipelineRenderingCreateInfo.colorAttachmentCount); - memcpy(formats.Data, v->PipelineRenderingCreateInfo.pColorAttachmentFormats, (size_t)formats.size_in_bytes()); - formats.swap(bd->PipelineRenderingCreateInfoColorAttachmentFormats); - v->PipelineRenderingCreateInfo.pColorAttachmentFormats = bd->PipelineRenderingCreateInfoColorAttachmentFormats.Data; - } + // Deep copy buffer to reduce error-rate for end user (#8282) + ImVector formats; + formats.resize((int)pipeline_rendering_create_info->colorAttachmentCount); + memcpy(formats.Data, pipeline_rendering_create_info->pColorAttachmentFormats, (size_t)formats.size_in_bytes()); + formats.swap(bd->PipelineRenderingCreateInfoColorAttachmentFormats); + pipeline_rendering_create_info->pColorAttachmentFormats = bd->PipelineRenderingCreateInfoColorAttachmentFormats.Data; } #endif - bd->Pipeline = ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, v->Subpass, pipeline_rendering_create_info); + bd->Pipeline = ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, pipeline_info); } void ImGui_ImplVulkan_DestroyDeviceObjects() @@ -1298,12 +1282,14 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE); IM_ASSERT(info->Device != VK_NULL_HANDLE); IM_ASSERT(info->Queue != VK_NULL_HANDLE); + IM_ASSERT(info->MinImageCount >= 2); + IM_ASSERT(info->ImageCount >= info->MinImageCount); if (info->DescriptorPool != VK_NULL_HANDLE) // Either DescriptorPool or DescriptorPoolSize must be set, not both! IM_ASSERT(info->DescriptorPoolSize == 0); else IM_ASSERT(info->DescriptorPoolSize > 0); - IM_ASSERT(info->MinImageCount >= 2); - IM_ASSERT(info->ImageCount >= info->MinImageCount); + if (info->UseDynamicRendering) + IM_ASSERT(info->PipelineInfoMain.RenderPass == VK_NULL_HANDLE); bd->VulkanInitInfo = *info; diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index a174e72d5..afc698701 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -65,6 +65,18 @@ // Backend uses a small number of descriptors per font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture(). #define IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE (8) // Minimum per atlas +// Specify settings to create pipeline and swapchain +struct ImGui_ImplVulkan_PipelineInfo +{ + // For Main and Secondary viewports + VkRenderPass RenderPass; // Ignored if using dynamic rendering + uint32_t Subpass; // + VkSampleCountFlagBits MSAASamples = {}; // 0 defaults to VK_SAMPLE_COUNT_1_BIT +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR +#endif +}; + // Initialization data, for ImGui_ImplVulkan_Init() // [Please zero-clear before use!] // - About descriptor pool: @@ -88,16 +100,15 @@ struct ImGui_ImplVulkan_InitInfo VkPipelineCache PipelineCache; // Optional // Pipeline - VkRenderPass RenderPass; // Ignored if using dynamic rendering - uint32_t Subpass; - VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT + ImGui_ImplVulkan_PipelineInfo PipelineInfoMain; // Infos for Main Viewport (created by app/user) + //VkRenderPass RenderPass; // --> Since 2025/09/26: set 'PipelineInfoMain.RenderPass' instead + //uint32_t Subpass; // --> Since 2025/09/26: set 'PipelineInfoMain.Subpass' instead + //VkSampleCountFlagBits MSAASamples; // --> Since 2025/09/26: set 'PipelineInfoMain.MSAASamples' instead + //VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Since 2025/09/26: set 'PipelineInfoMain.PipelineRenderingCreateInfo' instead // (Optional) Dynamic Rendering - // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3 + setup PipelineRenderingCreateInfo. + // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3 + setup PipelineInfoMain.PipelineRenderingCreateInfo. bool UseDynamicRendering; -#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR -#endif // (Optional) Allocation, Debugging const VkAllocationCallbacks* Allocator; @@ -121,16 +132,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_i // (Advanced) Use e.g. if you need to recreate pipeline without reinitializing the backend (see #8110, #8111) // The main window pipeline will be created by ImGui_ImplVulkan_Init() if possible (== RenderPass xor (UseDynamicRendering && PipelineRenderingCreateInfo->sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR)) // Else, the pipeline can be created, or re-created, using ImGui_ImplVulkan_CreateMainPipeline() before rendering. -struct ImGui_ImplVulkan_PipelineInfo -{ - VkRenderPass RenderPass = VK_NULL_HANDLE; - uint32_t Subpass = 0; - VkSampleCountFlagBits MSAASamples = {}; -#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; // Optional, valid if .sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR -#endif -}; -IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo& info); // (render_pass xor (p_dynamic_rendering && p_dynamic_rendering is correct (sType and pNext))) +IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo* info); // (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. IMGUI_IMPL_API void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 912527734..08337ee5c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,13 @@ HOW TO UPDATE? Breaking Changes: +- Backends: Vulkan: moved some fields in ImGui_ImplVulkan_InitInfo: + init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass + init_info.Subpass --> init_info.PipelineInfoMain.Subpass + init_info.MSAASamples --> init_info.PipelineInfoMain.MSAASamples + init_info.PipelineRenderingCreateInfo --> init_info.PipelineInfoMain.PipelineRenderingCreateInfo + It makes things more consistent and was desirable to introduce new settings for + secondary viewports. (#8946, #8110, #8111, #8686) [@ocornut, @SuperRonan, @sylmroz] - Backends: Vulkan: renamed ImGui_ImplVulkan_MainPipelineCreateInfo --> ImGui_ImplVulkan_PipelineInfo (introduced very recently and only used by `ImGui_ImplVulkan_CreateMainPipeline()` so it should not affect many users). (#8110, #8111) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 176c8c4d3..d9cbfb787 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -411,12 +411,12 @@ int main(int, char**) init_info.Queue = g_Queue; init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; - init_info.RenderPass = wd->RenderPass; - init_info.Subpass = 0; init_info.MinImageCount = g_MinImageCount; init_info.ImageCount = wd->ImageCount; - init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.Allocator = g_Allocator; + init_info.PipelineInfoMain.RenderPass = wd->RenderPass; + init_info.PipelineInfoMain.Subpass = 0; + init_info.PipelineInfoMain.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 21e892779..fd845373d 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -417,12 +417,12 @@ int main(int, char**) init_info.Queue = g_Queue; init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; - init_info.RenderPass = wd->RenderPass; - init_info.Subpass = 0; init_info.MinImageCount = g_MinImageCount; init_info.ImageCount = wd->ImageCount; - init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.Allocator = g_Allocator; + init_info.PipelineInfoMain.RenderPass = wd->RenderPass; + init_info.PipelineInfoMain.Subpass = 0; + init_info.PipelineInfoMain.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index e4cecf210..6f67e990d 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -416,12 +416,12 @@ int main(int, char**) init_info.Queue = g_Queue; init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; - init_info.RenderPass = wd->RenderPass; - init_info.Subpass = 0; init_info.MinImageCount = g_MinImageCount; init_info.ImageCount = wd->ImageCount; - init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.Allocator = g_Allocator; + init_info.PipelineInfoMain.RenderPass = wd->RenderPass; + init_info.PipelineInfoMain.Subpass = 0; + init_info.PipelineInfoMain.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info); diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 7a68ccbdd..cdf4a247e 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -404,12 +404,12 @@ int main(int, char**) init_info.Queue = g_Queue; init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; - init_info.RenderPass = wd->RenderPass; - init_info.Subpass = 0; init_info.MinImageCount = g_MinImageCount; init_info.ImageCount = wd->ImageCount; - init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.Allocator = g_Allocator; + init_info.PipelineInfoMain.RenderPass = wd->RenderPass; + init_info.PipelineInfoMain.Subpass = 0; + init_info.PipelineInfoMain.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info); diff --git a/imgui.h b/imgui.h index f04e8c0e4..7d71480b8 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.4 WIP" -#define IMGUI_VERSION_NUM 19232 +#define IMGUI_VERSION_NUM 19233 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From 1c87024840cfb0e945abb4048ca1fbb6d2aa260b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Sep 2025 13:38:27 +0200 Subject: [PATCH 1373/2359] InputText: fixed single-line InputText() not applying fine character clipping properly (regression in 1.92.3). (#8967) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 08337ee5c..d51981138 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,8 @@ Other Changes: - Windows: added lower-right resize grip on child windows using both ImGuiChildFlags_ResizeX and ImGuiChildFlags_ResizeY flags. (#8501) [@aleksijuvani] The grip is not visible before hovering to reduce clutter. +- InputText: fixed single-line InputText() not applying fine character clipping + properly (regression in 1.92.3). (#8967) [@Cyphall] - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() helpers to null all handlers. (#8945, #2769) - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4709af05b..592a76904 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5525,7 +5525,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ 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), - wrap_width, ImDrawTextFlags_WrapKeepBlanks); + wrap_width, ImDrawTextFlags_WrapKeepBlanks | ImDrawTextFlags_CpuFineClip); // Render blinking cursor if (render_cursor) From 217bc445ff0e26b70ab300480e1efa525a977662 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Tassoux?= Date: Sat, 27 Sep 2025 00:45:10 +0200 Subject: [PATCH 1374/2359] Backends: DirectX12: reuse a command list and allocator for texture uploads. (#8963, #8465) --- backends/imgui_impl_dx12.cpp | 31 ++++++++++++++++++------------- docs/CHANGELOG.txt | 2 ++ 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 86f1180ab..4a29cf529 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-09-27: DirectX12: Reuse a command list and allocator for texture uploads instead of recreating them each time. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-19: Fixed build on MinGW. (#8702, #4594) // 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. @@ -97,6 +98,9 @@ struct ImGui_ImplDX12_Data ID3D12DescriptorHeap* pd3dSrvDescHeap; UINT numFramesInFlight; + ID3D12CommandAllocator* pTexCmdAllocator; + ID3D12GraphicsCommandList* pTexCmdList; + ImGui_ImplDX12_RenderBuffers* pFrameResources; UINT frameIndex; @@ -448,13 +452,12 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - // FIXME-OPT: Can upload buffer be reused? + // FIXME-OPT: Could upload buffer be kept around, reused, and grown only when needed? Would that be worth it? ID3D12Resource* uploadBuffer = nullptr; HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer)); IM_ASSERT(SUCCEEDED(hr)); - // Create temporary command list and execute immediately ID3D12Fence* fence = nullptr; hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); IM_ASSERT(SUCCEEDED(hr)); @@ -462,15 +465,9 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) HANDLE event = ::CreateEvent(0, 0, 0, 0); IM_ASSERT(event != nullptr); - // FIXME-OPT: Create once and reuse? - ID3D12CommandAllocator* cmdAlloc = nullptr; - hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); - IM_ASSERT(SUCCEEDED(hr)); - - // FIXME-OPT: Can be use the one from user? (pass ID3D12GraphicsCommandList* to ImGui_ImplDX12_UpdateTextures) - ID3D12GraphicsCommandList* cmdList = nullptr; - hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList)); - IM_ASSERT(SUCCEEDED(hr)); + bd->pTexCmdAllocator->Reset(); + bd->pTexCmdList->Reset(bd->pTexCmdAllocator, nullptr); + ID3D12GraphicsCommandList* cmdList = bd->pTexCmdList; // Copy to upload buffer void* mapped = nullptr; @@ -535,8 +532,6 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) fence->SetEventOnCompletion(1, event); ::WaitForSingleObject(event, INFINITE); - cmdList->Release(); - cmdAlloc->Release(); ::CloseHandle(event); fence->Release(); uploadBuffer->Release(); @@ -776,6 +771,14 @@ bool ImGui_ImplDX12_CreateDeviceObjects() if (result_pipeline_state != S_OK) return false; + // Create command allocator and command list for ImGui_ImplDX12_UpdateTexture() + HRESULT hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&bd->pTexCmdAllocator)); + IM_ASSERT(SUCCEEDED(hr)); + hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, bd->pTexCmdAllocator, nullptr, IID_PPV_ARGS(&bd->pTexCmdList)); + IM_ASSERT(SUCCEEDED(hr)); + hr = bd->pTexCmdList->Close(); + IM_ASSERT(SUCCEEDED(hr)); + return true; } @@ -790,6 +793,8 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() bd->commandQueueOwned = false; SafeRelease(bd->pRootSignature); SafeRelease(bd->pPipelineState); + SafeRelease(bd->pTexCmdList); + SafeRelease(bd->pTexCmdAllocator); // Destroy all textures for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d51981138..146f1de76 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -73,6 +73,8 @@ Other Changes: - Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and ClearRendererHandlers() on shutdown, so as not to leave function pointers which may be dangling when using backend in e.g. DLL. (#8945, #2769) +- Backends: DirectX12: reuse a command list and allocator for texture uploads instead + of recreating them each time. (#8963, #8465) [@RT2Code] - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] - Backends: SDL2,SDL3: avoid using the SDL_GetGlobalMouseState() path when one of our From e459e5bf0a6db936d4de2c5978ee59c7e8ce7306 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Sep 2025 15:45:43 +0200 Subject: [PATCH 1375/2359] Backends: GLFW: fixed build on platform that are neither Windows, macOS or known Unixes. (#8969, #8920, #8921) Fix 10d0162. x --- backends/imgui_impl_glfw.cpp | 14 +++++++------- docs/CHANGELOG.txt | 2 ++ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index cfe5dc6d3..d98248acc 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -105,6 +105,11 @@ #endif // GLFW +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) +#define GLFW_HAS_X11_OR_WAYLAND 1 +#else +#define GLFW_HAS_X11_OR_WAYLAND 0 +#endif #include #ifdef _WIN32 #undef APIENTRY @@ -117,8 +122,8 @@ #define GLFW_EXPOSE_NATIVE_COCOA #endif #include -#elif !defined(__EMSCRIPTEN__) -#ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) +#elif GLFW_HAS_X11_OR_WAYLAND +#ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Display(), glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) #define GLFW_EXPOSE_NATIVE_X11 #endif #ifndef GLFW_EXPOSE_NATIVE_WAYLAND @@ -154,11 +159,6 @@ #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName() #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError() #define GLFW_HAS_GETPLATFORM (GLFW_VERSION_COMBINED >= 3400) // 3.4+ glfwGetPlatform() -#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) -#define GLFW_HAS_X11_OR_WAYLAND 1 -#else -#define GLFW_HAS_X11_OR_WAYLAND 0 -#endif // Map GLFWWindow* to ImGuiContext*. // - Would be simpler if we could use glfwSetWindowUserPointer()/glfwGetWindowUserPointer(), but this is a single and shared resource. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 146f1de76..5dc538ec9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,8 @@ Other Changes: of recreating them each time. (#8963, #8465) [@RT2Code] - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] +- Backends: GLFW: fixed build on platform that are neither Windows, macOS or + known Unixes (Regression in 1.92.3). (#8969, #8920, #8921) [@oktonion] - Backends: SDL2,SDL3: avoid using the SDL_GetGlobalMouseState() path when one of our window is hovered, as the event data is reliable and enough in this case. - Fix mouse coordinates issue in fullscreen apps with macOS notch. (#7919, #7786) From 3ff195f70216cd61c19877e0079bfe3c04491e18 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Sep 2025 16:00:17 +0200 Subject: [PATCH 1376/2359] Backends: DX12: let bd->FrameIndex start at 0 to match docking. (#8961) --- backends/imgui_impl_dx12.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 4a29cf529..fa58f3e5d 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -106,7 +106,7 @@ struct ImGui_ImplDX12_Data bool LegacySingleDescriptorUsed; - ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; } + ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts From bab3ebec14c46835de8034f238f7723621c24f1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Tassoux?= Date: Fri, 26 Sep 2025 16:07:38 +0200 Subject: [PATCH 1377/2359] Backends: DX12: Rework synchronization logic. (master) (#8961) --- docs/CHANGELOG.txt | 1 + examples/example_win32_directx12/main.cpp | 61 ++++++++--------------- 2 files changed, 22 insertions(+), 40 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5dc538ec9..c8424cf5d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -91,6 +91,7 @@ Other Changes: - Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is not available. (#5924, #5562) - Examples: SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] +- Examples: Win32+DirectX12: Rework synchronization logic. (#8961) [@RT2Code] - Examples: made examples's main.cpp consistent with returning 1 on error. diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index a5396d31b..665693462 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -102,8 +102,8 @@ bool CreateDeviceD3D(HWND hWnd); void CleanupDeviceD3D(); void CreateRenderTarget(); void CleanupRenderTarget(); -void WaitForLastSubmittedFrame(); -FrameContext* WaitForNextFrameResources(); +void WaitForPendingOperations(); +FrameContext* WaitForNextFrameContext(); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Main code @@ -256,7 +256,7 @@ int main(int, char**) // Rendering ImGui::Render(); - FrameContext* frameCtx = WaitForNextFrameResources(); + FrameContext* frameCtx = WaitForNextFrameContext(); UINT backBufferIdx = g_pSwapChain->GetCurrentBackBufferIndex(); frameCtx->CommandAllocator->Reset(); @@ -282,19 +282,17 @@ int main(int, char**) g_pd3dCommandList->Close(); g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&g_pd3dCommandList); + g_pd3dCommandQueue->Signal(g_fence, ++g_fenceLastSignaledValue); + frameCtx->FenceValue = g_fenceLastSignaledValue; // Present HRESULT hr = g_pSwapChain->Present(1, 0); // Present with vsync //HRESULT hr = g_pSwapChain->Present(0, 0); // Present without vsync g_SwapChainOccluded = (hr == DXGI_STATUS_OCCLUDED); - - UINT64 fenceValue = g_fenceLastSignaledValue + 1; - g_pd3dCommandQueue->Signal(g_fence, fenceValue); - g_fenceLastSignaledValue = fenceValue; - frameCtx->FenceValue = fenceValue; + g_frameIndex++; } - WaitForLastSubmittedFrame(); + WaitForPendingOperations(); // Cleanup ImGui_ImplDX12_Shutdown(); @@ -465,49 +463,33 @@ void CreateRenderTarget() void CleanupRenderTarget() { - WaitForLastSubmittedFrame(); + WaitForPendingOperations(); for (UINT i = 0; i < APP_NUM_BACK_BUFFERS; i++) if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = nullptr; } } -void WaitForLastSubmittedFrame() +void WaitForPendingOperations() { - FrameContext* frameCtx = &g_frameContext[g_frameIndex % APP_NUM_FRAMES_IN_FLIGHT]; + g_pd3dCommandQueue->Signal(g_fence, ++g_fenceLastSignaledValue); - UINT64 fenceValue = frameCtx->FenceValue; - if (fenceValue == 0) - return; // No fence was signaled - - frameCtx->FenceValue = 0; - if (g_fence->GetCompletedValue() >= fenceValue) - return; - - g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent); - WaitForSingleObject(g_fenceEvent, INFINITE); + g_fence->SetEventOnCompletion(g_fenceLastSignaledValue, g_fenceEvent); + ::WaitForSingleObject(g_fenceEvent, INFINITE); } -FrameContext* WaitForNextFrameResources() +FrameContext* WaitForNextFrameContext() { - UINT nextFrameIndex = g_frameIndex + 1; - g_frameIndex = nextFrameIndex; - - HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, nullptr }; - DWORD numWaitableObjects = 1; - - FrameContext* frameCtx = &g_frameContext[nextFrameIndex % APP_NUM_FRAMES_IN_FLIGHT]; - UINT64 fenceValue = frameCtx->FenceValue; - if (fenceValue != 0) // means no fence was signaled + FrameContext* frame_context = &g_frameContext[g_frameIndex % APP_NUM_FRAMES_IN_FLIGHT]; + if (g_fence->GetCompletedValue() < frame_context->FenceValue) { - frameCtx->FenceValue = 0; - g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent); - waitableObjects[1] = g_fenceEvent; - numWaitableObjects = 2; + g_fence->SetEventOnCompletion(frame_context->FenceValue, g_fenceEvent); + HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, g_fenceEvent }; + ::WaitForMultipleObjects(2, waitableObjects, TRUE, INFINITE); } + else + ::WaitForSingleObject(g_hSwapChainWaitableObject, INFINITE); - WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE); - - return frameCtx; + return frame_context; } // Forward declare message handler from imgui_impl_win32.cpp @@ -528,7 +510,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) case WM_SIZE: if (g_pd3dDevice != nullptr && wParam != SIZE_MINIMIZED) { - WaitForLastSubmittedFrame(); CleanupRenderTarget(); HRESULT result = g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT); assert(SUCCEEDED(result) && "Failed to resize swapchain."); From 5ce903af6e04e0a0bf044967a902aaffad5e82cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Tassoux?= Date: Sat, 27 Sep 2025 00:12:36 +0200 Subject: [PATCH 1378/2359] Backends: DX12: Use one fence instead of one by viewport. (master) (#8961) --- backends/imgui_impl_dx12.cpp | 30 +++++++++++++++++------------- docs/CHANGELOG.txt | 1 + 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index fa58f3e5d..a27d34ba2 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -20,7 +20,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2025-09-27: DirectX12: Reuse a command list and allocator for texture uploads instead of recreating them each time. +// 2025-09-29: DirectX12: Rework synchronization logic. (#8961) +// 2025-09-29: DirectX12: Reuse a command list and allocator for texture uploads instead of recreating them each time. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-19: Fixed build on MinGW. (#8702, #4594) // 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. @@ -96,6 +97,9 @@ struct ImGui_ImplDX12_Data DXGI_FORMAT RTVFormat; DXGI_FORMAT DSVFormat; ID3D12DescriptorHeap* pd3dSrvDescHeap; + ID3D12Fence* Fence; + UINT64 FenceLastSignaledValue; + HANDLE FenceEvent; UINT numFramesInFlight; ID3D12CommandAllocator* pTexCmdAllocator; @@ -458,13 +462,6 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer)); IM_ASSERT(SUCCEEDED(hr)); - ID3D12Fence* fence = nullptr; - hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); - IM_ASSERT(SUCCEEDED(hr)); - - HANDLE event = ::CreateEvent(0, 0, 0, 0); - IM_ASSERT(event != nullptr); - bd->pTexCmdAllocator->Reset(); bd->pTexCmdList->Reset(bd->pTexCmdAllocator, nullptr); ID3D12GraphicsCommandList* cmdList = bd->pTexCmdList; @@ -522,18 +519,16 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) ID3D12CommandQueue* cmdQueue = bd->pCommandQueue; cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); - hr = cmdQueue->Signal(fence, 1); + hr = cmdQueue->Signal(bd->Fence, ++bd->FenceLastSignaledValue); IM_ASSERT(SUCCEEDED(hr)); // FIXME-OPT: Suboptimal? // - To remove this may need to create NumFramesInFlight x ImGui_ImplDX12_FrameContext in backend data (mimick docking version) // - Store per-frame in flight: upload buffer? // - Where do cmdList and cmdAlloc fit? - fence->SetEventOnCompletion(1, event); - ::WaitForSingleObject(event, INFINITE); + bd->Fence->SetEventOnCompletion(bd->FenceLastSignaledValue, bd->FenceEvent); + ::WaitForSingleObject(bd->FenceEvent, INFINITE); - ::CloseHandle(event); - fence->Release(); uploadBuffer->Release(); tex->SetStatus(ImTextureStatus_OK); } @@ -779,6 +774,12 @@ bool ImGui_ImplDX12_CreateDeviceObjects() hr = bd->pTexCmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); + // Create fence. + hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&bd->Fence)); + IM_ASSERT(hr == S_OK); + bd->FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + IM_ASSERT(bd->FenceEvent != nullptr); + return true; } @@ -795,6 +796,9 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() SafeRelease(bd->pPipelineState); SafeRelease(bd->pTexCmdList); SafeRelease(bd->pTexCmdAllocator); + SafeRelease(bd->Fence); + CloseHandle(bd->FenceEvent); + bd->FenceEvent = nullptr; // Destroy all textures for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c8424cf5d..b1579715e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -75,6 +75,7 @@ Other Changes: which may be dangling when using backend in e.g. DLL. (#8945, #2769) - Backends: DirectX12: reuse a command list and allocator for texture uploads instead of recreating them each time. (#8963, #8465) [@RT2Code] +- Backends: DirectX12: Rework synchronization logic. (#8961) [@RT2Code] - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] - Backends: GLFW: fixed build on platform that are neither Windows, macOS or From 5cd83e689ed887778f9662f94060ee3345abd4aa Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Sep 2025 16:34:27 +0200 Subject: [PATCH 1379/2359] Backends: DirectX12: amend changelog to clarify fixes. (#3463, #5018) --- docs/CHANGELOG.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b1579715e..56b18de83 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,7 @@ Other Changes: - Backends: DirectX12: reuse a command list and allocator for texture uploads instead of recreating them each time. (#8963, #8465) [@RT2Code] - Backends: DirectX12: Rework synchronization logic. (#8961) [@RT2Code] + (presumably fixes old hard-to-repro crash issues such as #3463, #5018) - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] - Backends: GLFW: fixed build on platform that are neither Windows, macOS or From 3dafd9e898290ca890c29a379188be9e53b88537 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Sep 2025 18:30:31 +0200 Subject: [PATCH 1380/2359] Backends: DirectX12: enable swapchain tearing if available. (#8965) --- backends/imgui_impl_dx12.cpp | 21 ++++++++++++++++----- docs/CHANGELOG.txt | 1 + examples/example_win32_directx12/main.cpp | 21 +++++++++++++++++---- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index a27d34ba2..9462ca1fa 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -21,7 +21,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2025-09-29: DirectX12: Rework synchronization logic. (#8961) -// 2025-09-29: DirectX12: Reuse a command list and allocator for texture uploads instead of recreating them each time. +// 2025-09-29: DirectX12: Enable swapchain tearing to eliminate viewports framerate throttling. (#8965) +// 2025-09-29: DirectX12: Reuse a command list and allocator for texture uploads instead of recreating them each time. (#8963) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-19: Fixed build on MinGW. (#8702, #4594) // 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. @@ -59,7 +60,7 @@ // DirectX #include -#include +#include #include #ifdef _MSC_VER #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. @@ -89,6 +90,7 @@ struct ImGui_ImplDX12_Texture struct ImGui_ImplDX12_Data { ImGui_ImplDX12_InitInfo InitInfo; + IDXGIFactory5* pdxgiFactory; ID3D12Device* pd3dDevice; ID3D12RootSignature* pRootSignature; ID3D12PipelineState* pPipelineState; @@ -101,6 +103,8 @@ struct ImGui_ImplDX12_Data UINT64 FenceLastSignaledValue; HANDLE FenceEvent; UINT numFramesInFlight; + bool tearingSupport; + bool LegacySingleDescriptorUsed; ID3D12CommandAllocator* pTexCmdAllocator; ID3D12GraphicsCommandList* pTexCmdList; @@ -108,8 +112,6 @@ struct ImGui_ImplDX12_Data ImGui_ImplDX12_RenderBuffers* pFrameResources; UINT frameIndex; - bool LegacySingleDescriptorUsed; - ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); } }; @@ -545,6 +547,13 @@ bool ImGui_ImplDX12_CreateDeviceObjects() if (bd->pPipelineState) ImGui_ImplDX12_InvalidateDeviceObjects(); + HRESULT hr = ::CreateDXGIFactory1(IID_PPV_ARGS(&bd->pdxgiFactory)); + IM_ASSERT(hr == S_OK); + + BOOL allow_tearing = FALSE; + bd->pdxgiFactory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing, sizeof(allow_tearing)); + bd->tearingSupport = (allow_tearing == TRUE); + // Create the root signature { D3D12_DESCRIPTOR_RANGE descRange = {}; @@ -767,7 +776,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return false; // Create command allocator and command list for ImGui_ImplDX12_UpdateTexture() - HRESULT hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&bd->pTexCmdAllocator)); + hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&bd->pTexCmdAllocator)); IM_ASSERT(SUCCEEDED(hr)); hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, bd->pTexCmdAllocator, nullptr, IID_PPV_ARGS(&bd->pTexCmdList)); IM_ASSERT(SUCCEEDED(hr)); @@ -789,6 +798,7 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() if (!bd || !bd->pd3dDevice) return; + SafeRelease(bd->pdxgiFactory); if (bd->commandQueueOwned) SafeRelease(bd->pCommandQueue); bd->commandQueueOwned = false; @@ -853,6 +863,7 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) bd->DSVFormat = init_info->DSVFormat; bd->numFramesInFlight = init_info->NumFramesInFlight; bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap; + bd->tearingSupport = false; io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx12"; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 56b18de83..cc389c907 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,7 @@ Other Changes: of recreating them each time. (#8963, #8465) [@RT2Code] - Backends: DirectX12: Rework synchronization logic. (#8961) [@RT2Code] (presumably fixes old hard-to-repro crash issues such as #3463, #5018) +- Backends: DirectX12: Enable swapchain tearing if available. (#8965) [@RT2Code] - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] - Backends: GLFW: fixed build on platform that are neither Windows, macOS or diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 665693462..c8578b54c 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -10,7 +10,7 @@ #include "imgui_impl_win32.h" #include "imgui_impl_dx12.h" #include -#include +#include #include #ifdef _DEBUG @@ -92,6 +92,7 @@ static ID3D12Fence* g_fence = nullptr; static HANDLE g_fenceEvent = nullptr; static UINT64 g_fenceLastSignaledValue = 0; static IDXGISwapChain3* g_pSwapChain = nullptr; +static bool g_SwapChainTearingSupport = false; static bool g_SwapChainOccluded = false; static HANDLE g_hSwapChainWaitableObject = nullptr; static ID3D12Resource* g_mainRenderTargetResource[APP_NUM_BACK_BUFFERS] = {}; @@ -287,7 +288,7 @@ int main(int, char**) // Present HRESULT hr = g_pSwapChain->Present(1, 0); // Present with vsync - //HRESULT hr = g_pSwapChain->Present(0, 0); // Present without vsync + //HRESULT hr = g_pSwapChain->Present(0, g_SwapChainTearingSupport ? DXGI_PRESENT_ALLOW_TEARING : 0); // Present without vsync g_SwapChainOccluded = (hr == DXGI_STATUS_OCCLUDED); g_frameIndex++; } @@ -407,14 +408,24 @@ bool CreateDeviceD3D(HWND hWnd) return false; { - IDXGIFactory4* dxgiFactory = nullptr; + IDXGIFactory5* dxgiFactory = nullptr; IDXGISwapChain1* swapChain1 = nullptr; if (CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)) != S_OK) return false; + + BOOL allow_tearing = FALSE; + dxgiFactory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing, sizeof(allow_tearing)); + g_SwapChainTearingSupport = (allow_tearing == TRUE); + if (g_SwapChainTearingSupport) + sd.Flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING; + if (dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, nullptr, nullptr, &swapChain1) != S_OK) return false; if (swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)) != S_OK) return false; + if (g_SwapChainTearingSupport) + dxgiFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER); + swapChain1->Release(); dxgiFactory->Release(); g_pSwapChain->SetMaximumFrameLatency(APP_NUM_BACK_BUFFERS); @@ -511,7 +522,9 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) if (g_pd3dDevice != nullptr && wParam != SIZE_MINIMIZED) { CleanupRenderTarget(); - HRESULT result = g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT); + DXGI_SWAP_CHAIN_DESC1 desc = {}; + g_pSwapChain->GetDesc1(&desc); + HRESULT result = g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), desc.Format, desc.Flags); assert(SUCCEEDED(result) && "Failed to resize swapchain."); CreateRenderTarget(); } From a3d6e82dbd0b947401c118519894abf4420b26cb Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Sep 2025 16:26:27 +0200 Subject: [PATCH 1381/2359] Update README.md --- docs/README.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/README.md b/docs/README.md index 90a66119d..45977e74f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -107,22 +107,26 @@ Reading the changelogs is a good way to keep up to date with the things Dear ImG ### Demo -Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing a variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. [Here's how the demo looks](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png). +Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing a variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. +- [Web version of the demo](https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html) courtesy of [@pthom](https://github.com/pthom). +- [Screenshot of the demo](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png). You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: - [imgui-demo-binaries-20250625.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20250625.zip) (Windows, 1.92.0, built 2025/06/25, master) or [older binaries](https://www.dearimgui.com/binaries). -The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at a different scale and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.com/faq)). - ### Getting Started & Integration See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide for details. On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/backends) backends without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more imgui_impl_xxxx files instead of rewriting them: this will be less work for you, and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so. -Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading a texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles, which is essentially what Backends are doing. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that: setting up a window and using backends. If you follow the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide it should in theory take you less than an hour to integrate Dear ImGui. **Make sure to spend time reading the [FAQ](https://www.dearimgui.com/faq), comments, and the examples applications!** +Integrating Dear ImGui within your custom engine is a matter of mainly 1) wiring mouse/keyboard/gamepad inputs 2) uploading a texture to your GPU/render engine 3) providing a render function that can create/update textures and render textured triangles. This is exactly what backends are doing. +- The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications setting up a window and using standard backends. +- The [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide has instructions to integrate imgui into an existing application using standard backends. It should in theory take you less than an hour to integrate Dear ImGui into your existing codebase where support libraries are linked. Less if you read carefully. +- The [Backends](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md) guide explains what backends are doing, and has instructions to implement a custom backend. You can also refer to the source code of our ~20 backends to understand how they work. +- Generally, **make sure to spend time reading the [FAQ](https://www.dearimgui.com/faq), comments, and the examples applications!** -Officially maintained backends/bindings (in repository): +Officially maintained backends (in repository): - Renderers: DirectX9, DirectX10, DirectX11, DirectX12, Metal, OpenGL/ES/ES2, SDL_GPU, SDL_Renderer2/3, Vulkan, WebGPU. - Platforms: GLFW, SDL2/SDL3, Win32, Glut, OSX, Android. - Frameworks: Allegro5, Emscripten. @@ -130,7 +134,7 @@ Officially maintained backends/bindings (in repository): [Third-party backends/bindings](https://github.com/ocornut/imgui/wiki/Bindings) wiki page: - Languages: C, C# and: Beef, ChaiScript, CovScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lobster, Lua, Nim, Odin, Pascal, PureBasic, Python, ReaScript, Ruby, Rust, Swift, Zig... - Frameworks: AGS/Adventure Game Studio, Amethyst, Blender, bsf, Cinder, Cocos2d-x, Defold, Diligent Engine, Ebiten, Flexium, GML/Game Maker Studio, GLEQ, Godot, GTK3, Irrlicht Engine, JUCE, LÖVE+LUA, Mach Engine, Magnum, Marmalade, Monogame, NanoRT, nCine, Nim Game Lib, Nintendo 3DS/Switch/WiiU (homebrew), Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, raylib, SFML, Sokol, Unity, Unreal Engine 4/5, UWP, vtk, VulkanHpp, VulkanSceneGraph, Win32 GDI, WxWidgets. -- Many bindings are auto-generated (by good old [cimgui](https://github.com/cimgui/cimgui) or newer/experimental [dear_bindings](https://github.com/dearimgui/dear_bindings)), you can use their metadata output to generate bindings for other languages. +- Many bindings are auto-generated (by good old [cimgui](https://github.com/cimgui/cimgui) or our newer [dear_bindings](https://github.com/dearimgui/dear_bindings)), you can use their metadata output to generate bindings for other languages. [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page: - Automation/testing, Text editors, node editors, timeline editors, plotting, software renderers, remote network access, memory editors, gizmos, etc. Notable and well supported extensions include [ImPlot](https://github.com/epezent/implot) and [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine). From b987970870ec3ee3a71b125b76d1cf7aa7657a74 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 1 Oct 2025 14:58:30 +0200 Subject: [PATCH 1382/2359] Textures: fixed an issue preventing multi-contexts sharing a ImFontAtlas from being possible to destroy in any order. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- imgui.h | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cc389c907..2a937a6cf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,8 @@ Other Changes: - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. See misc/debuggers/ for details. (#8950) [@mentlerd] +- Textures: fixed an issue preventing multi-contexts sharing a ImFontAtlas from + being possible to destroy in any order. - CI: Updates Windows CI scripts to generate/use VulkanSDK. (#8925, #8778) [@yaz0r] - Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and ClearRendererHandlers() on shutdown, so as not to leave function pointers diff --git a/imgui.cpp b/imgui.cpp index 417747bca..814ed73d1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4326,7 +4326,7 @@ void ImGui::Shutdown() for (ImFontAtlas* atlas : g.FontAtlases) { UnregisterFontAtlas(atlas); - if (atlas->OwnerContext == &g) + if (atlas->RefCount == 0) { atlas->Locked = false; IM_DELETE(atlas); diff --git a/imgui.h b/imgui.h index 7d71480b8..9ec6bf20b 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.4 WIP" -#define IMGUI_VERSION_NUM 19233 +#define IMGUI_VERSION_NUM 19234 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From 9809b0b0617c4e6500fce94451fdde7e32c7047c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 1 Oct 2025 14:55:16 +0200 Subject: [PATCH 1383/2359] Textures: Fixed not updating ImTextureData's RefCount when destroying a context using a shared ImFontAtlas. (#8975) --- backends/imgui_impl_dx11.cpp | 2 +- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 4 ++++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index 1b3423654..144850faa 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -596,7 +596,7 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() if (tex->RefCount == 1) ImGui_ImplDX11_DestroyTexture(tex); - if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; } + if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2a937a6cf..43658071b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,9 @@ Other Changes: See misc/debuggers/ for details. (#8950) [@mentlerd] - Textures: fixed an issue preventing multi-contexts sharing a ImFontAtlas from being possible to destroy in any order. +- Textures: fixed not updating ImTextureData's RefCount when destroying a context + using a shared ImFontAtlas, leading standard backends to not properly free + texture resources. (#8975) [@icrashstuff] - CI: Updates Windows CI scripts to generate/use VulkanSDK. (#8925, #8778) [@yaz0r] - Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and ClearRendererHandlers() on shutdown, so as not to leave function pointers diff --git a/imgui.cpp b/imgui.cpp index 814ed73d1..1e881ca63 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8841,6 +8841,8 @@ void ImGui::RegisterFontAtlas(ImFontAtlas* atlas) atlas->RefCount++; g.FontAtlases.push_back(atlas); ImFontAtlasAddDrawListSharedData(atlas, &g.DrawListSharedData); + for (ImTextureData* tex : atlas->TexList) + tex->RefCount = (unsigned short)atlas->RefCount; } void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas) @@ -8850,6 +8852,8 @@ void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas) ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData); g.FontAtlases.find_erase(atlas); atlas->RefCount--; + for (ImTextureData* tex : atlas->TexList) + tex->RefCount = (unsigned short)atlas->RefCount; } // Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList. From ea564a6a5e9ef9d1f37c59535f3b361484aa5b8b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 1 Oct 2025 17:40:20 +0200 Subject: [PATCH 1384/2359] Textures: fixed a crash if a texture marked as _WantDestroy by a backend after it had already been destroyed. (#8977, #8811) --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 31 ++++++++++++++++++------------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 43658071b..628b909aa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,9 @@ Other Changes: - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. See misc/debuggers/ for details. (#8950) [@mentlerd] +- Textures: fixed a crash if a texture marked as _WantDestroy by a backend after + it had already been destroyed. This would typically happen when calling backend's + ImGui_ImplXXXX_InvalidateDeviceObjects() helpers twice in a row. (#8977, #8811) - Textures: fixed an issue preventing multi-contexts sharing a ImFontAtlas from being possible to destroy in any order. - Textures: fixed not updating ImTextureData's RefCount when destroying a context diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0946d7a46..082af59ac 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2790,21 +2790,29 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool rendere if (tex->Status == ImTextureStatus_WantCreate && atlas->RendererHasTextures) IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture's TexID/BackendUserData but did not update Status to OK."); + // Request destroy + // - Keep bool to true in order to differentiate a planned destroy vs a destroy decided by the backend. + // - We don't destroy pixels right away, as backend may have an in-flight copy from RAM. + if (tex->WantDestroyNextFrame && tex->Status != ImTextureStatus_Destroyed && tex->Status != ImTextureStatus_WantDestroy) + { + IM_ASSERT(tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates); + tex->Status = ImTextureStatus_WantDestroy; + } + + // If a texture has never reached the backend, they don't need to know about it. + // (note: backends between 1.92.0 and 1.92.4 could set an already destroyed texture to ImTextureStatus_WantDestroy + // when invalidating graphics objects twice, which would previously remove it from the list and crash.) + if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL) + tex->Status = ImTextureStatus_Destroyed; + + // Process texture being destroyed if (tex->Status == ImTextureStatus_Destroyed) { IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!"); if (tex->WantDestroyNextFrame) remove_from_list = true; // Destroy was scheduled by us else - tex->Status = ImTextureStatus_WantCreate; // Destroy was done was backend (e.g. freed resources mid-run) - } - else if (tex->WantDestroyNextFrame && tex->Status != ImTextureStatus_WantDestroy) - { - // Request destroy. - // - Keep bool to true in order to differentiate a planned destroy vs a destroy decided by the backend. - // - We don't destroy pixels right away, as backend may have an in-flight copy from RAM. - IM_ASSERT(tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates); - tex->Status = ImTextureStatus_WantDestroy; + tex->Status = ImTextureStatus_WantCreate; // Destroy was done was backend: recreate it (e.g. freed resources mid-run) } // The backend may need defer destroying by a few frames, to handle texture used by previous in-flight rendering. @@ -2812,13 +2820,10 @@ void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool rendere if (tex->Status == ImTextureStatus_WantDestroy) tex->UnusedFrames++; - // If a texture has never reached the backend, they don't need to know about it. - if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL) - remove_from_list = true; - // Destroy and remove if (remove_from_list) { + IM_ASSERT(atlas->TexData != tex); tex->DestroyPixels(); IM_DELETE(tex); atlas->TexList.erase(atlas->TexList.begin() + tex_n); From fc4105c8a8a99fccb2bd6a1488d131dd06df9177 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 1 Oct 2025 17:49:22 +0200 Subject: [PATCH 1385/2359] Backends: DX9,DX10,DX11,DX12,Metal,Vulkan,WGPU,SDLRenderer2,SDLRenderer3: ensure that a texture in _WantDestroy state always turn to _Destroyed. (#8977) Amend 9809b0b. Strictly speaking this is not necessary anymore but it seems generally sane to promote this. --- backends/imgui_impl_dx10.cpp | 20 ++++++++++---------- backends/imgui_impl_dx11.cpp | 20 ++++++++++---------- backends/imgui_impl_dx12.cpp | 26 +++++++++++++------------- backends/imgui_impl_dx9.cpp | 14 +++++++------- backends/imgui_impl_metal.mm | 16 ++++++++-------- backends/imgui_impl_sdlgpu3.cpp | 3 +-- backends/imgui_impl_sdlrenderer2.cpp | 6 ++---- backends/imgui_impl_sdlrenderer3.cpp | 6 ++---- backends/imgui_impl_vulkan.cpp | 28 ++++++++++++++-------------- backends/imgui_impl_wgpu.cpp | 21 ++++++++++----------- docs/CHANGELOG.txt | 3 +++ 11 files changed, 80 insertions(+), 83 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index ae6510db2..5650a3c85 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -325,18 +325,18 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) static void ImGui_ImplDX10_DestroyTexture(ImTextureData* tex) { - ImGui_ImplDX10_Texture* backend_tex = (ImGui_ImplDX10_Texture*)tex->BackendUserData; - if (backend_tex == nullptr) - return; - IM_ASSERT(backend_tex->pTextureView == (ID3D10ShaderResourceView*)(intptr_t)tex->TexID); - backend_tex->pTexture->Release(); - backend_tex->pTextureView->Release(); - IM_DELETE(backend_tex); + if (ImGui_ImplDX10_Texture* backend_tex = (ImGui_ImplDX10_Texture*)tex->BackendUserData) + { + IM_ASSERT(backend_tex->pTextureView == (ID3D10ShaderResourceView*)(intptr_t)tex->TexID); + backend_tex->pTextureView->Release(); + backend_tex->pTexture->Release(); + IM_DELETE(backend_tex); - // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) - tex->SetTexID(ImTextureID_Invalid); + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->BackendUserData = nullptr; + } tex->SetStatus(ImTextureStatus_Destroyed); - tex->BackendUserData = nullptr; } void ImGui_ImplDX10_UpdateTexture(ImTextureData* tex) diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index 144850faa..878930404 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -341,18 +341,18 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) static void ImGui_ImplDX11_DestroyTexture(ImTextureData* tex) { - ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData; - if (backend_tex == nullptr) - return; - IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID); - backend_tex->pTextureView->Release(); - backend_tex->pTexture->Release(); - IM_DELETE(backend_tex); + if (ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData) + { + IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID); + backend_tex->pTextureView->Release(); + backend_tex->pTexture->Release(); + IM_DELETE(backend_tex); - // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) - tex->SetTexID(ImTextureID_Invalid); + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->BackendUserData = nullptr; + } tex->SetStatus(ImTextureStatus_Destroyed); - tex->BackendUserData = nullptr; } void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 9462ca1fa..1e122a76e 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -345,21 +345,21 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL static void ImGui_ImplDX12_DestroyTexture(ImTextureData* tex) { - ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData; - if (backend_tex == nullptr) - return; - IM_ASSERT(backend_tex->hFontSrvGpuDescHandle.ptr == (UINT64)tex->TexID); - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, backend_tex->hFontSrvCpuDescHandle, backend_tex->hFontSrvGpuDescHandle); - SafeRelease(backend_tex->pTextureResource); - backend_tex->hFontSrvCpuDescHandle.ptr = 0; - backend_tex->hFontSrvGpuDescHandle.ptr = 0; - IM_DELETE(backend_tex); + if (ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData) + { + IM_ASSERT(backend_tex->hFontSrvGpuDescHandle.ptr == (UINT64)tex->TexID); + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, backend_tex->hFontSrvCpuDescHandle, backend_tex->hFontSrvGpuDescHandle); + SafeRelease(backend_tex->pTextureResource); + backend_tex->hFontSrvCpuDescHandle.ptr = 0; + backend_tex->hFontSrvGpuDescHandle.ptr = 0; + IM_DELETE(backend_tex); - // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) - tex->SetTexID(ImTextureID_Invalid); + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->BackendUserData = nullptr; + } tex->SetStatus(ImTextureStatus_Destroyed); - tex->BackendUserData = nullptr; } void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 4a8899a62..37b5815cc 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -431,14 +431,14 @@ void ImGui_ImplDX9_UpdateTexture(ImTextureData* tex) } else if (tex->Status == ImTextureStatus_WantDestroy) { - LPDIRECT3DTEXTURE9 backend_tex = (LPDIRECT3DTEXTURE9)tex->TexID; - if (backend_tex == nullptr) - return; - IM_ASSERT(tex->TexID == (ImTextureID)(intptr_t)backend_tex); - backend_tex->Release(); + if (LPDIRECT3DTEXTURE9 backend_tex = (LPDIRECT3DTEXTURE9)tex->TexID) + { + IM_ASSERT(tex->TexID == (ImTextureID)(intptr_t)backend_tex); + backend_tex->Release(); - // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) - tex->SetTexID(ImTextureID_Invalid); + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + } tex->SetStatus(ImTextureStatus_Destroyed); } } diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 81e8be6c4..2746efa95 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -338,16 +338,16 @@ void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id static void ImGui_ImplMetal_DestroyTexture(ImTextureData* tex) { - MetalTexture* backend_tex = (__bridge_transfer MetalTexture*)(tex->BackendUserData); - if (backend_tex == nullptr) - return; - IM_ASSERT(backend_tex.metalTexture == (__bridge id)(void*)(intptr_t)tex->TexID); - backend_tex.metalTexture = nil; + 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; - // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) - tex->SetTexID(ImTextureID_Invalid); + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->BackendUserData = nullptr; + } tex->SetStatus(ImTextureStatus_Destroyed); - tex->BackendUserData = nullptr; } void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 3afbf3db6..8d8f0a4c4 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -307,8 +307,7 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe static void ImGui_ImplSDLGPU3_DestroyTexture(ImTextureData* tex) { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); - SDL_GPUTexture* raw_tex = (SDL_GPUTexture*)(intptr_t)tex->GetTexID(); - if (raw_tex != nullptr) + if (SDL_GPUTexture* raw_tex = (SDL_GPUTexture*)(intptr_t)tex->GetTexID()) SDL_ReleaseGPUTexture(bd->InitInfo.Device, raw_tex); // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index fa1e802b1..e03d13115 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -267,10 +267,8 @@ void ImGui_ImplSDLRenderer2_UpdateTexture(ImTextureData* tex) } else if (tex->Status == ImTextureStatus_WantDestroy) { - SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID; - if (sdl_texture == nullptr) - return; - SDL_DestroyTexture(sdl_texture); + if (SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID) + SDL_DestroyTexture(sdl_texture); // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) tex->SetTexID(ImTextureID_Invalid); diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index abf636b8d..38a4383c2 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -283,10 +283,8 @@ void ImGui_ImplSDLRenderer3_UpdateTexture(ImTextureData* tex) } else if (tex->Status == ImTextureStatus_WantDestroy) { - SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID; - if (sdl_texture == nullptr) - return; - SDL_DestroyTexture(sdl_texture); + if (SDL_Texture* sdl_texture = (SDL_Texture*)(intptr_t)tex->TexID) + SDL_DestroyTexture(sdl_texture); // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) tex->SetTexID(ImTextureID_Invalid); diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 60554368e..a8eb9a8c4 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -663,22 +663,22 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm static void ImGui_ImplVulkan_DestroyTexture(ImTextureData* tex) { - ImGui_ImplVulkan_Texture* backend_tex = (ImGui_ImplVulkan_Texture*)tex->BackendUserData; - if (backend_tex == nullptr) - return; - IM_ASSERT(backend_tex->DescriptorSet == (VkDescriptorSet)tex->TexID); - ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; - ImGui_ImplVulkan_RemoveTexture(backend_tex->DescriptorSet); - vkDestroyImageView(v->Device, backend_tex->ImageView, v->Allocator); - vkDestroyImage(v->Device, backend_tex->Image, v->Allocator); - vkFreeMemory(v->Device, backend_tex->Memory, v->Allocator); - IM_DELETE(backend_tex); + if (ImGui_ImplVulkan_Texture* backend_tex = (ImGui_ImplVulkan_Texture*)tex->BackendUserData) + { + IM_ASSERT(backend_tex->DescriptorSet == (VkDescriptorSet)tex->TexID); + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + ImGui_ImplVulkan_RemoveTexture(backend_tex->DescriptorSet); + vkDestroyImageView(v->Device, backend_tex->ImageView, v->Allocator); + vkDestroyImage(v->Device, backend_tex->Image, v->Allocator); + vkFreeMemory(v->Device, backend_tex->Memory, v->Allocator); + IM_DELETE(backend_tex); - // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) - tex->SetTexID(ImTextureID_Invalid); + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->BackendUserData = nullptr; + } tex->SetStatus(ImTextureStatus_Destroyed); - tex->BackendUserData = nullptr; } void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 1f997a10a..9f731c8f1 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -533,19 +533,18 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder static void ImGui_ImplWGPU_DestroyTexture(ImTextureData* tex) { - ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData; - if (backend_tex == nullptr) - return; + if (ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData) + { + IM_ASSERT(backend_tex->TextureView == (WGPUTextureView)(intptr_t)tex->TexID); + wgpuTextureViewRelease(backend_tex->TextureView); + wgpuTextureRelease(backend_tex->Texture); + IM_DELETE(backend_tex); - IM_ASSERT(backend_tex->TextureView == (WGPUTextureView)(intptr_t)tex->TexID); - wgpuTextureViewRelease(backend_tex->TextureView); - wgpuTextureRelease(backend_tex->Texture); - IM_DELETE(backend_tex); - - // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) - tex->SetTexID(ImTextureID_Invalid); + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->BackendUserData = nullptr; + } tex->SetStatus(ImTextureStatus_Destroyed); - tex->BackendUserData = nullptr; } void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 628b909aa..14dc2c8c4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -99,6 +99,9 @@ Other Changes: XInput's dwPacketNumber has not changed. (#8556) [@MidTerm-CN] - Backends: Vulkan: added a way to specify custom shaders by filling init fields CustomShaderVertCreateInfo and CustomShaderFragCreateInfo. (#8585, #8271) [@johan0A] +- Backends: DX9,DX10,DX11,DX12,Metal,Vulkan,WGPU,SDLRenderer2,SDLRenderer3: + ensure that a texture in _WantDestroy state always turn to _Destroyed even + if your underlying graphics data was already destroyed. - Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is not available. (#5924, #5562) - Examples: SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] From 8c22b8aef6f5a80f18fff0bbebb895a97013bcdb Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 1 Oct 2025 18:38:27 +0200 Subject: [PATCH 1386/2359] Textures: allowed backend to destroy texture while inside the NewFrame/EndFrame scope. (#8811) --- docs/CHANGELOG.txt | 8 ++++++-- imgui.h | 6 ++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 14dc2c8c4..ea29c0b8d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,9 +69,13 @@ Other Changes: - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. See misc/debuggers/ for details. (#8950) [@mentlerd] -- Textures: fixed a crash if a texture marked as _WantDestroy by a backend after +- Textures: fixed a crash if texture status is set to _WantDestroy by a backend after it had already been destroyed. This would typically happen when calling backend's ImGui_ImplXXXX_InvalidateDeviceObjects() helpers twice in a row. (#8977, #8811) +- Textures: allowed backend to destroy texture while inside the NewFrame/EndFrame + scope. Basically if a backend decide to destroy a texture that we didn't request + to destroy (for e.g. freeing resources) the texture is immediately set to + a _WantCreate status again. (#8811) - Textures: fixed an issue preventing multi-contexts sharing a ImFontAtlas from being possible to destroy in any order. - Textures: fixed not updating ImTextureData's RefCount when destroying a context @@ -101,7 +105,7 @@ Other Changes: CustomShaderVertCreateInfo and CustomShaderFragCreateInfo. (#8585, #8271) [@johan0A] - Backends: DX9,DX10,DX11,DX12,Metal,Vulkan,WGPU,SDLRenderer2,SDLRenderer3: ensure that a texture in _WantDestroy state always turn to _Destroyed even - if your underlying graphics data was already destroyed. + if your underlying graphics data was already destroyed. (#8977) - Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is not available. (#5924, #5562) - Examples: SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] diff --git a/imgui.h b/imgui.h index 9ec6bf20b..b006023a2 100644 --- a/imgui.h +++ b/imgui.h @@ -3491,8 +3491,10 @@ struct ImTextureData ImTextureID GetTexID() const { return TexID; } // Called by Renderer backend - void SetTexID(ImTextureID tex_id) { TexID = tex_id; } // Call after creating or destroying the texture. Never modify TexID directly! - void SetStatus(ImTextureStatus status) { Status = status; } // Call after honoring a request. Never modify Status directly! + // - Call SetTexID() and SetStatus() after honoring texture requests. Never modify TexID and Status directly! + // - A backend may decide to destroy a texture that we did not request to destroy, which is fine (e.g. freeing resources), but we immediately set the texture back in _WantCreate mode. + void SetTexID(ImTextureID tex_id) { TexID = tex_id; } + void SetStatus(ImTextureStatus status) { Status = status; if (status == ImTextureStatus_Destroyed && !WantDestroyNextFrame) Status = ImTextureStatus_WantCreate; } }; //----------------------------------------------------------------------------- From bcf722e637b18c0884a0ba1f7b621c22f232bfd2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 2 Oct 2025 20:06:10 +0200 Subject: [PATCH 1387/2359] Docs: updated FAQ "What is the difference between Dear ImGui and traditional UI toolkits?". (#8862) --- docs/CHANGELOG.txt | 2 ++ docs/FAQ.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++ imgui.cpp | 1 + 3 files changed, 58 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ea29c0b8d..66846d00e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,8 @@ Other Changes: - Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and ClearRendererHandlers() on shutdown, so as not to leave function pointers which may be dangling when using backend in e.g. DLL. (#8945, #2769) +- Docs: updated FAQ with new "What is the difference between Dear ImGui and + traditional UI toolkits?" entry. (#8862) - Backends: DirectX12: reuse a command list and allocator for texture uploads instead of recreating them each time. (#8963, #8465) [@RT2Code] - Backends: DirectX12: Rework synchronization logic. (#8961) [@RT2Code] diff --git a/docs/FAQ.md b/docs/FAQ.md index 519a0e8a9..ec75b35f6 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -13,6 +13,7 @@ or view this file with any Markdown viewer. :---------------------------------------------------------- | | [Where is the documentation?](#q-where-is-the-documentation) | | [What is this library called?](#q-what-is-this-library-called) | +| [What is the difference between Dear ImGui and traditional UI toolkits?](#q-what-is-the-difference-between-dear-imgui-and-traditional-ui-toolkits) | | [Which version should I get?](#q-which-version-should-i-get) | | **Q&A: Integration** | | **[How to get started?](#q-how-to-get-started)** | @@ -75,6 +76,60 @@ or view this file with any Markdown viewer. --- +### Q: What is the difference between Dear ImGui and traditional UI toolkits? + +Here's a very simplified comparaison between the approach taked by Dear ImGui vs traditional toolkits: + +| Dear ImGui | Qt/Gtk/WPF.. | +|----------------------------|--------------------------| +| UI fully issued on every update. | UI issued once then later modified. | +| UI layout is fully dynamic and can change at any time.
UI is generally emitted programmatically, which empower changes and reflecting a dynamic set of data. | UI layout is mostly static.
UI may be emitted programmatically or from data created by offline tools. UI need extra code to evolve, which is often tedious and error-prone if it needs to be reflect dynamic data and systems. | +| Application can submit UI based on arbitrary logic and then forget about it. | Application needs more bookkeeping of UI elements. | +| UI library stores minimal amount of data. At one point in time it typically doesn't know or remember which other widgets are displayed and which widgets are coming next. As a result, certain layout features (alignment, resizing) are not as easy to implement or requires ad-hoc code. | UI library stores entire widgets tree and state. UI library can use this retained data to easily layout things. | +| UI code may be added anywhere.
You can even create UI to edit a local variable! | UI code needs to be added in certains spots. | +| UI layout/logic/action/data bindings are all nearby in the code. | UI layout/logic/action/data bindings in different functions, different files or formats. | +| Data is naturally always synchronized. | Use callback/signal/slot for synchronizing data (error-prone). | +| API is simple and easy to learn. In particular, doing simple things is very easy. | API is more complex and specialized. | +| API is generally low-level (raw language types). | API are higher-level (more abstractions, advanced language features). | +| Less fancy look and feel. | Standard look and feel. | +| Compile yourself. Easy to debug, hack, modify. | Mostly use precompiled librairies. Compiling and modifying is daunting if not impossible. | +| Run on every platforms. | Run on limited desktop platforms. | + +Idiomatic Dear ImGui code: +```cpp +if (ImGui::Button("Save")) + MySaveFunction(); + +ImGui::SliderFloat("Slider", &m_MyValue, 0.0f, 1.0f); +``` +Idiomatic code with traditional toolkit: +```cpp +UiButton* button = new UiButton("Save"); +button->OnClick = &MySaveFunction; +parent->Add(button); + +UiSlider* slider = new UiSlider("Slider"); +slider->SetRange(0.0f, 1.0f); +slider->BindData(&m_MyValue); +parent->Add(slider); +``` +This is only meant to give you a intuitive feeling of the main differences, but everything goes deeper than that. + +Some of those properties are typically associated to the umbrella term "IMGUI", but the term has no simple and well-agreed definition. There are many erroneous statements and misunderstanding with what IMGUI means. It is partly caused by the fact that most popular IMGUI implementations (including Dear ImGui) have originated from game industry needs and have targetted very specific use cases, causing people to conflate IMGUI properties with what a specific library does. However, it is perfectly possible to implement an IMGUI library that would have very different properties than e.g. Dear ImGui. My take on defining what an IMGUI is: + +**IMGUI refers to the API: literally the interface between the application and the UI system.** +- An IMGUI API favor the application code owning its data and being the single source of truth for it. +- An IMGUI API tries to minimize the application having to retain/manage data related to the UI system. +- An IMGUI API tries to minimize the UI system having to retain/manage data related to the application. +- Synchronization between application data and UI data is natural and less error-prone. + +**IMGUI does NOT refer to the implementation. Whatever happens inside the UI library code doesn't matter.** +
Also see: [Links to many articles about the IMGUI paradigm](https://github.com/ocornut/imgui/wiki/#about-the-imgui-paradigm). + +##### [Return to Index](#index) + +--- + ### Q: Which version should I get? I occasionally tag [Releases](https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. diff --git a/imgui.cpp b/imgui.cpp index 1e881ca63..6c37effe5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1055,6 +1055,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: associated with it. Q: What is this library called? + Q: What is the difference between Dear ImGui and traditional UI toolkits? Q: Which version should I get? >> This library is called "Dear ImGui", please don't call it "ImGui" :) >> See https://www.dearimgui.com/faq for details. From a97b0c32ab1a969714a7e3a232ac4948fbbd9f50 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 2 Oct 2025 20:31:14 +0200 Subject: [PATCH 1388/2359] Update FAQ.md --- docs/FAQ.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index ec75b35f6..c141e1b70 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -80,8 +80,8 @@ or view this file with any Markdown viewer. Here's a very simplified comparaison between the approach taked by Dear ImGui vs traditional toolkits: -| Dear ImGui | Qt/Gtk/WPF.. | -|----------------------------|--------------------------| +| Dear ImGui | Qt/Gtk/WPF... | +|--------------------------|--------------------------| | UI fully issued on every update. | UI issued once then later modified. | | UI layout is fully dynamic and can change at any time.
UI is generally emitted programmatically, which empower changes and reflecting a dynamic set of data. | UI layout is mostly static.
UI may be emitted programmatically or from data created by offline tools. UI need extra code to evolve, which is often tedious and error-prone if it needs to be reflect dynamic data and systems. | | Application can submit UI based on arbitrary logic and then forget about it. | Application needs more bookkeeping of UI elements. | @@ -92,7 +92,7 @@ Here's a very simplified comparaison between the approach taked by Dear ImGui vs | API is simple and easy to learn. In particular, doing simple things is very easy. | API is more complex and specialized. | | API is generally low-level (raw language types). | API are higher-level (more abstractions, advanced language features). | | Less fancy look and feel. | Standard look and feel. | -| Compile yourself. Easy to debug, hack, modify. | Mostly use precompiled librairies. Compiling and modifying is daunting if not impossible. | +| Compile yourself. Easy to debug, hack, modify, study. | Mostly use precompiled librairies. Compiling, modifying or studying is daunting if not impossible. | | Run on every platforms. | Run on limited desktop platforms. | Idiomatic Dear ImGui code: @@ -113,7 +113,7 @@ slider->SetRange(0.0f, 1.0f); slider->BindData(&m_MyValue); parent->Add(slider); ``` -This is only meant to give you a intuitive feeling of the main differences, but everything goes deeper than that. +This is only meant to give you a intuitive feeling of the main differences, but pros & cons goes deeper than that. Some of those properties are typically associated to the umbrella term "IMGUI", but the term has no simple and well-agreed definition. There are many erroneous statements and misunderstanding with what IMGUI means. It is partly caused by the fact that most popular IMGUI implementations (including Dear ImGui) have originated from game industry needs and have targetted very specific use cases, causing people to conflate IMGUI properties with what a specific library does. However, it is perfectly possible to implement an IMGUI library that would have very different properties than e.g. Dear ImGui. My take on defining what an IMGUI is: From 3ac624b795fcb939a42ec0b43160f65cf4ff83e5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 3 Oct 2025 18:26:06 +0200 Subject: [PATCH 1389/2359] Update FAQ.md typos. (#8862) --- docs/FAQ.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index c141e1b70..e72f63f74 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -78,22 +78,22 @@ or view this file with any Markdown viewer. ### Q: What is the difference between Dear ImGui and traditional UI toolkits? -Here's a very simplified comparaison between the approach taked by Dear ImGui vs traditional toolkits: +Here's a very simplified comparison between the approach taken by Dear ImGui vs traditional toolkits: -| Dear ImGui | Qt/Gtk/WPF... | +| Dear ImGui | Qt/GTK/WPF... | |--------------------------|--------------------------| | UI fully issued on every update. | UI issued once then later modified. | -| UI layout is fully dynamic and can change at any time.
UI is generally emitted programmatically, which empower changes and reflecting a dynamic set of data. | UI layout is mostly static.
UI may be emitted programmatically or from data created by offline tools. UI need extra code to evolve, which is often tedious and error-prone if it needs to be reflect dynamic data and systems. | +| UI layout is fully dynamic and can change at any time.
UI is generally emitted programmatically, which empowers reflecting a dynamic set of data. | UI layout is mostly static.
UI may be emitted programmatically or from data created by offline tools. UI need extra code to evolve, which is often tedious and error-prone if it needs to be reflecting dynamic data and systems. | | Application can submit UI based on arbitrary logic and then forget about it. | Application needs more bookkeeping of UI elements. | -| UI library stores minimal amount of data. At one point in time it typically doesn't know or remember which other widgets are displayed and which widgets are coming next. As a result, certain layout features (alignment, resizing) are not as easy to implement or requires ad-hoc code. | UI library stores entire widgets tree and state. UI library can use this retained data to easily layout things. | -| UI code may be added anywhere.
You can even create UI to edit a local variable! | UI code needs to be added in certains spots. | -| UI layout/logic/action/data bindings are all nearby in the code. | UI layout/logic/action/data bindings in different functions, different files or formats. | +| UI library stores minimal amounts of data. At one point in time, it typically doesn't know or remember which other widgets are displayed and which widgets are coming next. As a result, certain layout features (alignment, resizing) are not as easy to implement or require ad-hoc code. | UI library stores entire widgets tree and state. UI library can use this retained data to easily layout things. | +| UI code may be added anywhere.
You can even create UI to edit a local variable! | UI code needs to be added in dedicated spots. | +| UI layout/logic/action/data bindings are all nearby in the code. | UI layout/logic/action/data bindings in distinct functions, files or formats. | | Data is naturally always synchronized. | Use callback/signal/slot for synchronizing data (error-prone). | -| API is simple and easy to learn. In particular, doing simple things is very easy. | API is more complex and specialized. | -| API is generally low-level (raw language types). | API are higher-level (more abstractions, advanced language features). | +| API is simple and easy to learn. In particular, doing basic things is very easy. | API is more complex and specialized. | +| API is low-level (raw language types). | API are higher-level (more abstractions, advanced language features). | | Less fancy look and feel. | Standard look and feel. | -| Compile yourself. Easy to debug, hack, modify, study. | Mostly use precompiled librairies. Compiling, modifying or studying is daunting if not impossible. | -| Run on every platforms. | Run on limited desktop platforms. | +| Compile yourself. Easy to debug, hack, modify, study. | Mostly use precompiled libraries. Compiling, modifying or studying is daunting if not impossible. | +| Run on every platform. | Run on limited desktop platforms. | Idiomatic Dear ImGui code: ```cpp @@ -113,12 +113,12 @@ slider->SetRange(0.0f, 1.0f); slider->BindData(&m_MyValue); parent->Add(slider); ``` -This is only meant to give you a intuitive feeling of the main differences, but pros & cons goes deeper than that. +This is only meant to give you a intuitive feeling of the main differences, but pros & cons go deeper than that. -Some of those properties are typically associated to the umbrella term "IMGUI", but the term has no simple and well-agreed definition. There are many erroneous statements and misunderstanding with what IMGUI means. It is partly caused by the fact that most popular IMGUI implementations (including Dear ImGui) have originated from game industry needs and have targetted very specific use cases, causing people to conflate IMGUI properties with what a specific library does. However, it is perfectly possible to implement an IMGUI library that would have very different properties than e.g. Dear ImGui. My take on defining what an IMGUI is: +Some of those properties are typically associated to the umbrella term "IMGUI", but the term has no simple and well-agreed definition. There are many erroneous statements and misunderstandings with what IMGUI means. It is partly caused by the fact that most popular IMGUI implementations (including Dear ImGui) have originated from game industry needs and have targeted specific use cases, causing people to conflate IMGUI properties with what a specific library does. However, it is perfectly possible to implement an IMGUI library that would have very different properties than e.g. Dear ImGui. My take on defining what an IMGUI is: **IMGUI refers to the API: literally the interface between the application and the UI system.** -- An IMGUI API favor the application code owning its data and being the single source of truth for it. +- An IMGUI API favors the application code owning its data and being the single source of truth for it. - An IMGUI API tries to minimize the application having to retain/manage data related to the UI system. - An IMGUI API tries to minimize the UI system having to retain/manage data related to the application. - Synchronization between application data and UI data is natural and less error-prone. From 1cdec11e24832f81be947d357ed8c451e59c2de9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 3 Oct 2025 18:54:15 +0200 Subject: [PATCH 1390/2359] Drag and Drop: rework RenderDragDropTargetRect() into RenderDragDropTargetRectForItem() and add RenderDragDropTargetRectEx(). (#1603, #5204) --- imgui.cpp | 13 +++++++++---- imgui_internal.h | 3 ++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6c37effe5..272dba95d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14793,7 +14793,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop payload.Preview = was_accepted_previously; flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame) if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview) - RenderDragDropTargetRect(r, g.DragDropTargetClipRect); + RenderDragDropTargetRectForItem(r); g.DragDropAcceptFrameCount = g.FrameCount; if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1) @@ -14809,21 +14809,26 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop } // FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target. -void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect) +void ImGui::RenderDragDropTargetRectForItem(const ImRect& bb) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImRect bb_display = bb; - bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible. + bb_display.ClipWith(g.DragDropTargetClipRect); // Clip THEN expand so we have a way to visualize that target is not entirely visible. bb_display.Expand(3.5f); bool push_clip_rect = !window->ClipRect.Contains(bb_display); if (push_clip_rect) window->DrawList->PushClipRectFullScreen(); - window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); // FIXME-DPI + RenderDragDropTargetRectEx(window->DrawList, bb_display); if (push_clip_rect) window->DrawList->PopClipRect(); } +void ImGui::RenderDragDropTargetRectEx(ImDrawList* draw_list, const ImRect& bb) +{ + draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); // FIXME-DPI +} + const ImGuiPayload* ImGui::GetDragDropPayload() { ImGuiContext& g = *GImGui; diff --git a/imgui_internal.h b/imgui_internal.h index f66b91f7d..cdeddc919 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3423,7 +3423,8 @@ namespace ImGui IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id); IMGUI_API void ClearDragDrop(); IMGUI_API bool IsDragDropPayloadBeingAccepted(); - IMGUI_API void RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect); + IMGUI_API void RenderDragDropTargetRectForItem(const ImRect& bb); + IMGUI_API void RenderDragDropTargetRectEx(ImDrawList* draw_list, const ImRect& bb); // Typing-Select API // (provide Windows Explorer style "select items by typing partial name" + "cycle through items by typing same letter" feature) From 27a9374ef3fc6572f8dd1fa9ddf72e1802fceb8b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 3 Oct 2025 19:04:37 +0200 Subject: [PATCH 1391/2359] Drag and Drop: added BeginDragDropTargetViewport(), still in imgui_internal.h for now. (#5204) --- imgui.cpp | 37 ++++++++++++++++++++++++++++++++++++- imgui_internal.h | 2 ++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 272dba95d..8928335aa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4160,6 +4160,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) DragDropSourceFrameCount = -1; DragDropMouseButton = -1; DragDropTargetId = 0; + DragDropTargetFullViewport = 0; DragDropAcceptFlags = ImGuiDragDropFlags_None; DragDropAcceptIdCurrRectSurface = 0.0f; DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0; @@ -14722,6 +14723,31 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) g.DragDropTargetRect = bb; g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case? g.DragDropTargetId = id; + g.DragDropTargetFullViewport = 0; + g.DragDropWithinTarget = true; + return true; +} + +// Typical usage would be: +// if (!ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) +// if (ImGui::BeginDragDropTargetViewport(ImGui::GetMainViewport(), NULL)) +// But we are leaving the hover test to the caller for maximum flexibility. +bool ImGui::BeginDragDropTargetViewport(ImGuiViewport* viewport, const ImRect* p_bb) +{ + ImGuiContext& g = *GImGui; + if (!g.DragDropActive) + return false; + + ImRect bb = p_bb ? *p_bb : ((ImGuiViewportP*)viewport)->GetWorkRect(); + ImGuiID id = viewport->ID; + if (!IsMouseHoveringRect(bb.Min, bb.Max, false) || (id == g.DragDropPayload.SourceId)) + return false; + + IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget() + g.DragDropTargetRect = bb; + g.DragDropTargetClipRect = bb; + g.DragDropTargetId = id; + g.DragDropTargetFullViewport = id; g.DragDropWithinTarget = true; return true; } @@ -14792,8 +14818,17 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop // Render default drop visuals payload.Preview = was_accepted_previously; flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame) - if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview) + const bool draw_target_rect = payload.Preview && !(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); + if (draw_target_rect && g.DragDropTargetFullViewport != 0) + { + ImRect bb = g.DragDropTargetRect; + bb.Expand(-3.5f); + RenderDragDropTargetRectEx(GetForegroundDrawList(), bb); + } + else if (draw_target_rect) + { RenderDragDropTargetRectForItem(r); + } g.DragDropAcceptFrameCount = g.FrameCount; if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1) diff --git a/imgui_internal.h b/imgui_internal.h index cdeddc919..fe79a862f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2372,6 +2372,7 @@ struct ImGuiContext ImRect DragDropTargetRect; // Store rectangle of current target candidate (we favor small targets when overlapping) ImRect DragDropTargetClipRect; // Store ClipRect at the time of item's drawing ImGuiID DragDropTargetId; + ImGuiID DragDropTargetFullViewport; ImGuiDragDropFlags DragDropAcceptFlags; float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface) ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload) @@ -3421,6 +3422,7 @@ namespace ImGui // Drag and Drop IMGUI_API bool IsDragDropActive(); IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id); + IMGUI_API bool BeginDragDropTargetViewport(ImGuiViewport* viewport, const ImRect* p_bb = NULL); IMGUI_API void ClearDragDrop(); IMGUI_API bool IsDragDropPayloadBeingAccepted(); IMGUI_API void RenderDragDropTargetRectForItem(const ImRect& bb); From 2128e2f44b7ecd0250cfd47921e03d87e4506f4c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Oct 2025 12:16:48 +0200 Subject: [PATCH 1392/2359] Style: added ImGuiCol_UnsavedMarker. (#8983) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 3 ++- imgui.h | 1 + imgui_draw.cpp | 3 +++ imgui_widgets.cpp | 4 ++-- 5 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 66846d00e..bc6fd0063 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,8 @@ Other Changes: The grip is not visible before hovering to reduce clutter. - InputText: fixed single-line InputText() not applying fine character clipping properly (regression in 1.92.3). (#8967) [@Cyphall] +- Style: added ImGuiCol_UnsavedMarker, color of the unsaved document marker when + using ImGuiWindowFlags_UnsavedDocument/ImGuiTabItemFlags_UnsavedDocument. (#8983) - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() helpers to null all handlers. (#8945, #2769) - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, diff --git a/imgui.cpp b/imgui.cpp index 8928335aa..6b501f343 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3693,6 +3693,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_TreeLines: return "TreeLines"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; + case ImGuiCol_UnsavedMarker: return "UnsavedMarker"; case ImGuiCol_NavCursor: return "NavCursor"; case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg"; @@ -7169,7 +7170,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f; if (marker_pos.x > layout_r.Min.x) { - RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text)); + RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_UnsavedMarker)); clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f)); } } diff --git a/imgui.h b/imgui.h index b006023a2..9589fa561 100644 --- a/imgui.h +++ b/imgui.h @@ -1774,6 +1774,7 @@ enum ImGuiCol_ ImGuiCol_TextSelectedBg, // Selected text inside an InputText ImGuiCol_TreeLines, // Tree node hierarchy outlines when using ImGuiTreeNodeFlags_DrawLines ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target + ImGuiCol_UnsavedMarker, // Unsaved Document marker (in window title and tabs) ImGuiCol_NavCursor, // Color of keyboard/gamepad navigation cursor/rectangle, when visible ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 082af59ac..a2c616012 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -240,6 +240,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_UnsavedMarker] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_NavCursor] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); @@ -305,6 +306,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_UnsavedMarker] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); @@ -371,6 +373,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_UnsavedMarker] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 592a76904..45a4dcf62 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10716,8 +10716,8 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, const bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x) && (!close_button_visible || !is_hovered); if (unsaved_marker_visible) { - const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz)); - RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text)); + ImVec2 bullet_pos = button_pos + ImVec2(button_sz, button_sz) * 0.5f; + RenderBullet(draw_list, bullet_pos, GetColorU32(ImGuiCol_UnsavedMarker)); } else if (close_button_visible) { From 09e15e8c9dd1c5a780d51c8f7c8ddfdb9d400e84 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Oct 2025 13:55:54 +0200 Subject: [PATCH 1393/2359] Nav: fixed typo. --- imgui_internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index fe79a862f..c2d858580 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2306,7 +2306,7 @@ struct ImGuiContext float NavHighlightActivatedTimer; ImGuiID NavNextActivateId; // Set by ActivateItemByID(), queued until next frame. ImGuiActivateFlags NavNextActivateFlags; - ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse + ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Gamepad ImGuiSelectionUserData NavLastValidSelectionUserData; // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data. ImS8 NavCursorHideFrames; //ImGuiID NavActivateInputId; // Removed in 1.89.4 (July 2023). This is now part of g.NavActivateId and sets g.NavActivateFlags |= ImGuiActivateFlags_PreferInput. See commit c9a53aa74, issue #5606. From 4b858cf5d1327fa5e3a84ae8044ff2026f3a43d3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Oct 2025 16:55:11 +0200 Subject: [PATCH 1394/2359] Made tooltip windows inherit parent. (#8982, #1345) Intent here was for a manually focused tooltip to not steal title bar highlight. --- imgui.cpp | 4 ++-- imgui.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6b501f343..2ba3aacd9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7187,7 +7187,7 @@ void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags window->RootWindow = parent_window->RootWindow; if (parent_window && (flags & ImGuiWindowFlags_Popup)) window->RootWindowPopupTree = parent_window->RootWindowPopupTree; - if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) + if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip))) window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight; while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened) { @@ -7296,7 +7296,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window; - ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow; + ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) ? parent_window_in_stack : NULL) : window->ParentWindow; IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); // We allow window memory to be compacted so recreate the base stack when needed. diff --git a/imgui.h b/imgui.h index 9589fa561..24c6423b4 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.4 WIP" -#define IMGUI_VERSION_NUM 19234 +#define IMGUI_VERSION_NUM 19235 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From ee3d16f15070b4de6656cc68e39e89fa9a469436 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 6 Oct 2025 18:39:10 +0200 Subject: [PATCH 1395/2359] Demo: fixed layout issue in "Layout & Scrolling -> Scrolling" section. --- docs/CHANGELOG.txt | 13 +++++++------ imgui_demo.cpp | 15 +++++++++------ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bc6fd0063..496bf1d9f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,9 +68,6 @@ Other Changes: using ImGuiWindowFlags_UnsavedDocument/ImGuiTabItemFlags_UnsavedDocument. (#8983) - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() helpers to null all handlers. (#8945, #2769) -- Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, - Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. - See misc/debuggers/ for details. (#8950) [@mentlerd] - Textures: fixed a crash if texture status is set to _WantDestroy by a backend after it had already been destroyed. This would typically happen when calling backend's ImGui_ImplXXXX_InvalidateDeviceObjects() helpers twice in a row. (#8977, #8811) @@ -83,12 +80,16 @@ Other Changes: - Textures: fixed not updating ImTextureData's RefCount when destroying a context using a shared ImFontAtlas, leading standard backends to not properly free texture resources. (#8975) [@icrashstuff] -- CI: Updates Windows CI scripts to generate/use VulkanSDK. (#8925, #8778) [@yaz0r] +- Demo: fixed layout issue in "Layout & Scrolling -> Scrolling" section. +- Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, + Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. + See misc/debuggers/ for details. (#8950) [@mentlerd] +- CI: updated Windows CI scripts to generate/use VulkanSDK. (#8925, #8778) [@yaz0r] +- Docs: updated FAQ with new "What is the difference between Dear ImGui and + traditional UI toolkits?" entry. (#8862) - Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and ClearRendererHandlers() on shutdown, so as not to leave function pointers which may be dangling when using backend in e.g. DLL. (#8945, #2769) -- Docs: updated FAQ with new "What is the difference between Dear ImGui and - traditional UI toolkits?" entry. (#8862) - Backends: DirectX12: reuse a command list and allocator for texture uploads instead of recreating them each time. (#8963, #8465) [@RT2Code] - Backends: DirectX12: Rework synchronization logic. (#8961) [@RT2Code] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e3991a60e..3a6bcf5a5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4795,15 +4795,18 @@ static void DemoWindowLayout() ImGui::Checkbox("Decoration", &enable_extra_decorations); + ImGui::PushItemWidth(ImGui::GetFontSize() * 10); + enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d"); + ImGui::SameLine(); ImGui::Checkbox("Track", &enable_track); - ImGui::PushItemWidth(100); - ImGui::SameLine(140); enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d"); - bool scroll_to_off = ImGui::Button("Scroll Offset"); - ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, FLT_MAX, "+%.0f px"); + bool scroll_to_off = ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, FLT_MAX, "+%.0f px"); + ImGui::SameLine(); + scroll_to_off |= ImGui::Button("Scroll Offset"); - bool scroll_to_pos = ImGui::Button("Scroll To Pos"); - ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px"); + bool scroll_to_pos = ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px");; + ImGui::SameLine(); + scroll_to_pos |= ImGui::Button("Scroll To Pos"); ImGui::PopItemWidth(); if (scroll_to_off || scroll_to_pos) From fd0873c61ffc3e41415e00441ced4d2e1905553c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 7 Oct 2025 15:59:45 +0200 Subject: [PATCH 1396/2359] Test Engine: fixed mismatched macro signature when disabled. The macro was actually unused in our code if IMGUI_ENABLE_TEST_ENGINE is not defined, but can affect third-party code. --- imgui_internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index c2d858580..e65cbcab7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3921,7 +3921,7 @@ extern const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext* ctx, ImGuiI #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional) #define IMGUI_TEST_ENGINE_LOG(_FMT,...) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log #else -#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) ((void)0) +#define IMGUI_TEST_ENGINE_ITEM_ADD(_ID,_BB,_ITEM_DATA) ((void)0) #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) ((void)g) #endif From bee2720faac5f33401fcda7fa9eb51113d13e8d6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Oct 2025 18:44:07 +0200 Subject: [PATCH 1397/2359] Docs: clarify meaning/purpose of IMGUI_ENABLE_FREETYPE. (#8993) --- imconfig.h | 1 + misc/freetype/README.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/imconfig.h b/imconfig.h index 4dab1b604..0e7cf6182 100644 --- a/imconfig.h +++ b/imconfig.h @@ -83,6 +83,7 @@ //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) // Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). +// Note that imgui_freetype.cpp may be used _without_ this define, if you manually call ImFontAtlas::SetFontLoader(). The define is simply a convenience. // On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. //#define IMGUI_ENABLE_FREETYPE diff --git a/misc/freetype/README.md b/misc/freetype/README.md index e1bd0198b..6ea6ad1ae 100644 --- a/misc/freetype/README.md +++ b/misc/freetype/README.md @@ -7,7 +7,7 @@ Build font atlases using FreeType instead of stb_truetype (which is the default 1. Get latest FreeType binaries or build yourself (under Windows you may use vcpkg with `vcpkg install freetype --triplet=x64-windows`, `vcpkg integrate install`). 2. Add imgui_freetype.h/cpp alongside your project files. -3. Add `#define IMGUI_ENABLE_FREETYPE` in your [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) file +3. Add `#define IMGUI_ENABLE_FREETYPE` in your [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) file to make Dear ImGui automatically use the imgui_freetype loader. If your copy Dear ImGui is precompiled, you can always enable imgui_freetype by calling ImFontAtlas::SetFontLoader(). ### About Gamma Correct Blending From 2b770a029ba01b78c6e27d6fc74de308eaefb634 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 8 Oct 2025 19:00:34 +0200 Subject: [PATCH 1398/2359] InputText: fixed an infinite loop error happening if a custom input text callback modifies/clear BufTextLen before calling InsertChars(). (#8994, #3237) + misc comments. --- docs/CHANGELOG.txt | 5 +++++ imgui_demo.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 8 +++++--- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 496bf1d9f..9c5b50988 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,11 @@ Other Changes: The grip is not visible before hovering to reduce clutter. - InputText: fixed single-line InputText() not applying fine character clipping properly (regression in 1.92.3). (#8967) [@Cyphall] +- InputText: fixed an infinite loop error happening if a custom input text + callback modifies/clear BufTextLen before calling InsertChars(). + (regression from 1.92.3). Note that this never really worked correctly, but + previously it would only temporary wreck cursor position, and since 1.92.3 it + would go in an infinite loop. (#8994, #3237) - Style: added ImGuiCol_UnsavedMarker, color of the unsaved document marker when using ImGuiWindowFlags_UnsavedDocument/ImGuiTabItemFlags_UnsavedDocument. (#8983) - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3a6bcf5a5..dec1bad40 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4804,7 +4804,7 @@ static void DemoWindowLayout() ImGui::SameLine(); scroll_to_off |= ImGui::Button("Scroll Offset"); - bool scroll_to_pos = ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px");; + bool scroll_to_pos = ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px"); ImGui::SameLine(); scroll_to_pos |= ImGui::Button("Scroll To Pos"); ImGui::PopItemWidth(); diff --git a/imgui_internal.h b/imgui_internal.h index e65cbcab7..1510271a0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2484,7 +2484,7 @@ struct ImGuiContext ImGuiWindow* LogWindow; ImFileHandle LogFile; // If != NULL log to stdout/ file ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. - const char* LogNextPrefix; + const char* LogNextPrefix; // See comment in LogSetNextTextDecoration(): doesn't copy underlying data, use carefully! const char* LogNextSuffix; float LogLinePosY; bool LogLineFirstItem; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 45a4dcf62..a3a4ae1cf 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3941,6 +3941,7 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c { ImGuiContext& g = *ctx; ImGuiInputTextState* obj = &g.InputTextState; + IM_ASSERT(text_end_display >= text_begin && text_end_display <= text_end); return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj->WrapWidth, text_begin, text_end_display, text_end, out_remaining, out_offset, flags); } @@ -4321,11 +4322,12 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); Buf[BufTextLen + new_text_len] = '\0'; - if (CursorPos >= pos) - CursorPos += new_text_len; - SelectionStart = SelectionEnd = CursorPos; BufDirty = true; BufTextLen += new_text_len; + if (CursorPos >= pos) + CursorPos += new_text_len; + CursorPos = ImClamp(CursorPos, 0, BufTextLen); + SelectionStart = SelectionEnd = CursorPos; } void ImGui::PushPasswordFont() From 5af650fc6d27daf585edbd9ac872465f756a65e9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 9 Oct 2025 18:54:16 +0200 Subject: [PATCH 1399/2359] Examples: GLFW+WGPU: various tweaks to reduce diff with #8381 --- backends/imgui_impl_wgpu.cpp | 2 +- backends/imgui_impl_wgpu.h | 2 +- examples/example_glfw_wgpu/main.cpp | 63 ++++++++++++++++------------- 3 files changed, 36 insertions(+), 31 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 9f731c8f1..3045f9c7c 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -46,7 +46,7 @@ #include "imgui.h" -// When targeting native platforms (i.e. NOT emscripten), one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN +// When targeting native platforms (i.e. NOT Emscripten), one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN // or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details. #ifndef __EMSCRIPTEN__ #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 61d2d23c0..499c899a0 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -32,7 +32,7 @@ // Initialization data, for ImGui_ImplWGPU_Init() struct ImGui_ImplWGPU_InitInfo { - WGPUDevice Device; + WGPUDevice Device = nullptr; int NumFramesInFlight = 3; WGPUTextureFormat RenderTargetFormat = WGPUTextureFormat_Undefined; WGPUTextureFormat DepthStencilFormat = WGPUTextureFormat_Undefined; diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 670dd08c2..59bb505a9 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -1,4 +1,4 @@ -// Dear ImGui: standalone example application for using GLFW + WebGPU +// Dear ImGui: standalone example application for GLFW + WebGPU // - Emscripten is supported for publishing on web. See https://emscripten.org. // - Dawn is used as a WebGPU implementation on desktop. @@ -12,36 +12,32 @@ #include "imgui_impl_glfw.h" #include "imgui_impl_wgpu.h" #include +#include +// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. #ifdef __EMSCRIPTEN__ #include #include #include +#include "../libs/emscripten/emscripten_mainloop_stub.h" #else #include #endif - -#include #include #include -// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. -#ifdef __EMSCRIPTEN__ -#include "../libs/emscripten/emscripten_mainloop_stub.h" -#endif - -// Global WebGPU required states +// Data static WGPUInstance wgpu_instance = nullptr; static WGPUDevice wgpu_device = nullptr; static WGPUSurface wgpu_surface = nullptr; static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm; static WGPUSwapChain wgpu_swap_chain = nullptr; -static int wgpu_swap_chain_width = 1280; -static int wgpu_swap_chain_height = 800; +static int wgpu_surface_width = 1280; +static int wgpu_surface_height = 800; // Forward declarations static bool InitWGPU(GLFWwindow* window); -static void CreateSwapChain(int width, int height); +static void ResizeSurface(int width, int height); static void glfw_error_callback(int error, const char* description) { @@ -72,19 +68,23 @@ int main(int, char**) // Make sure GLFW does not initialize any graphics context. // This needs to be done explicitly later. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - GLFWwindow* window = glfwCreateWindow(wgpu_swap_chain_width, wgpu_swap_chain_height, "Dear ImGui GLFW+WebGPU example", nullptr, nullptr); + + // Create window + float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); // Valid on GLFW 3.3+ only + wgpu_surface_width *= main_scale; + wgpu_surface_height *= main_scale; + GLFWwindow* window = glfwCreateWindow(wgpu_surface_width, wgpu_surface_height, "Dear ImGui GLFW+WebGPU example", nullptr, nullptr); if (window == nullptr) return 1; // Initialize the WebGPU environment if (!InitWGPU(window)) { - if (window) - glfwDestroyWindow(window); + glfwDestroyWindow(window); glfwTerminate(); return 1; } - CreateSwapChain(wgpu_swap_chain_width, wgpu_swap_chain_height); + ResizeSurface(wgpu_surface_width, wgpu_surface_height); glfwShowWindow(window); // Setup Dear ImGui context @@ -98,6 +98,11 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOther(window, true); #ifdef __EMSCRIPTEN__ @@ -117,15 +122,14 @@ int main(int, char**) // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - // - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details. - //io.Fonts->AddFontDefault(); + // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; + //io.Fonts->AddFontDefault(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf"); //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf"); - //io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf"); //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf"); //IM_ASSERT(font != nullptr); #endif @@ -160,10 +164,10 @@ int main(int, char**) // React to changes in screen size int width, height; glfwGetFramebufferSize((GLFWwindow*)window, &width, &height); - if (width != wgpu_swap_chain_width || height != wgpu_swap_chain_height) + if (width != wgpu_surface_width || height != wgpu_surface_height) { ImGui_ImplWGPU_InvalidateDeviceObjects(); - CreateSwapChain(width, height); + ResizeSurface(width, height); ImGui_ImplWGPU_CreateDeviceObjects(); } @@ -238,8 +242,8 @@ int main(int, char**) WGPUCommandBufferDescriptor cmd_buffer_desc = {}; WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc); - WGPUQueue queue = wgpuDeviceGetQueue(wgpu_device); - wgpuQueueSubmit(queue, 1, &cmd_buffer); + WGPUQueue wgpu_queue = wgpuDeviceGetQueue(wgpu_device); + wgpuQueueSubmit(wgpu_queue, 1, &cmd_buffer); #ifndef __EMSCRIPTEN__ wgpuSwapChainPresent(wgpu_swap_chain); @@ -311,10 +315,10 @@ static bool InitWGPU(GLFWwindow* window) #endif #ifdef __EMSCRIPTEN__ - wgpu::SurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {}; - html_surface_desc.selector = "#canvas"; + wgpu::SurfaceDescriptorFromCanvasHTMLSelector canvas_desc = {}; + canvas_desc.selector = "#canvas"; wgpu::SurfaceDescriptor surface_desc = {}; - surface_desc.nextInChain = &html_surface_desc; + surface_desc.nextInChain = &canvas_desc; wgpu::Surface surface = instance.CreateSurface(&surface_desc); wgpu::Adapter adapter = {}; @@ -326,6 +330,7 @@ static bool InitWGPU(GLFWwindow* window) wgpu_preferred_fmt = WGPUTextureFormat_BGRA8Unorm; #endif + // Moving Dawn objects into WGPU handles wgpu_instance = instance.MoveToCHandle(); wgpu_surface = surface.MoveToCHandle(); @@ -334,12 +339,12 @@ static bool InitWGPU(GLFWwindow* window) return true; } -static void CreateSwapChain(int width, int height) +static void ResizeSurface(int width, int height) { if (wgpu_swap_chain) wgpuSwapChainRelease(wgpu_swap_chain); - wgpu_swap_chain_width = width; - wgpu_swap_chain_height = height; + wgpu_surface_width = width; + wgpu_surface_height = height; WGPUSwapChainDescriptor swap_chain_desc = {}; swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment; swap_chain_desc.format = wgpu_preferred_fmt; From 00251c8921bbc08092e472ad40ffedbca81e00db Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Oct 2025 12:01:10 +0200 Subject: [PATCH 1400/2359] CI: disable PVS-Studio's --disableLicenseExpirationCheck --- .github/workflows/static-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index a69c5110c..53db04764 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -42,5 +42,5 @@ jobs: fi cd examples/example_null pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 - pvs-studio-analyzer analyze --disableLicenseExpirationCheck -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log + pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log plog-converter -a 'GA:1,2;OP:1' -d V1071 -t errorfile -w pvs-studio.log From 9be4f150ef4c4561eaf8b4abc7ac34ccf2278995 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Tassoux?= Date: Fri, 10 Oct 2025 17:56:31 +0200 Subject: [PATCH 1401/2359] Backends: DirectX12: Reuse texture upload buffer and grow it only when necessary. (#9002) --- backends/imgui_impl_dx12.cpp | 84 ++++++++++++++++++++++-------------- docs/CHANGELOG.txt | 2 + 2 files changed, 53 insertions(+), 33 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 1e122a76e..d4da6ab02 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-10-11: DirectX12: Reuse texture upload buffer and grow it only when necessary. (#9002) // 2025-09-29: DirectX12: Rework synchronization logic. (#8961) // 2025-09-29: DirectX12: Enable swapchain tearing to eliminate viewports framerate throttling. (#8965) // 2025-09-29: DirectX12: Reuse a command list and allocator for texture uploads instead of recreating them each time. (#8963) @@ -108,6 +109,9 @@ struct ImGui_ImplDX12_Data ID3D12CommandAllocator* pTexCmdAllocator; ID3D12GraphicsCommandList* pTexCmdList; + ID3D12Resource* pTexUploadBuffer; + UINT pTexUploadBufferSize; + void* pTexUploadBufferMapped; ImGui_ImplDX12_RenderBuffers* pFrameResources; UINT frameIndex; @@ -438,44 +442,53 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) UINT upload_pitch_dst = (upload_pitch_src + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); UINT upload_size = upload_pitch_dst * upload_h; - D3D12_RESOURCE_DESC desc; - ZeroMemory(&desc, sizeof(desc)); - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Alignment = 0; - desc.Width = upload_size; - desc.Height = 1; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = DXGI_FORMAT_UNKNOWN; - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - desc.Flags = D3D12_RESOURCE_FLAG_NONE; + if (bd->pTexUploadBuffer == nullptr || upload_size > bd->pTexUploadBufferSize) + { + if (bd->pTexUploadBufferMapped) + { + D3D12_RANGE range = { 0, bd->pTexUploadBufferSize }; + bd->pTexUploadBuffer->Unmap(0, &range); + bd->pTexUploadBufferMapped = nullptr; + } + SafeRelease(bd->pTexUploadBuffer); - D3D12_HEAP_PROPERTIES props; - memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); - props.Type = D3D12_HEAP_TYPE_UPLOAD; - props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + D3D12_RESOURCE_DESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Alignment = 0; + desc.Width = upload_size; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_NONE; - // FIXME-OPT: Could upload buffer be kept around, reused, and grown only when needed? Would that be worth it? - ID3D12Resource* uploadBuffer = nullptr; - HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer)); - IM_ASSERT(SUCCEEDED(hr)); + D3D12_HEAP_PROPERTIES props; + memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); + props.Type = D3D12_HEAP_TYPE_UPLOAD; + props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + + HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&bd->pTexUploadBuffer)); + IM_ASSERT(SUCCEEDED(hr)); + + D3D12_RANGE range = {0, upload_size}; + hr = bd->pTexUploadBuffer->Map(0, &range, &bd->pTexUploadBufferMapped); + IM_ASSERT(SUCCEEDED(hr)); + bd->pTexUploadBufferSize = upload_size; + } bd->pTexCmdAllocator->Reset(); bd->pTexCmdList->Reset(bd->pTexCmdAllocator, nullptr); ID3D12GraphicsCommandList* cmdList = bd->pTexCmdList; // Copy to upload buffer - void* mapped = nullptr; - D3D12_RANGE range = { 0, upload_size }; - hr = uploadBuffer->Map(0, &range, &mapped); - IM_ASSERT(SUCCEEDED(hr)); for (int y = 0; y < upload_h; y++) - memcpy((void*)((uintptr_t)mapped + y * upload_pitch_dst), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch_src); - uploadBuffer->Unmap(0, &range); + memcpy((void*)((uintptr_t)bd->pTexUploadBufferMapped + y * upload_pitch_dst), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch_src); if (need_barrier_before_copy) { @@ -492,7 +505,7 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; { - srcLocation.pResource = uploadBuffer; + srcLocation.pResource = bd->pTexUploadBuffer; srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srcLocation.PlacedFootprint.Footprint.Width = upload_w; @@ -516,9 +529,8 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) cmdList->ResourceBarrier(1, &barrier); } - hr = cmdList->Close(); + HRESULT hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); - ID3D12CommandQueue* cmdQueue = bd->pCommandQueue; cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); hr = cmdQueue->Signal(bd->Fence, ++bd->FenceLastSignaledValue); @@ -531,7 +543,6 @@ void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex) bd->Fence->SetEventOnCompletion(bd->FenceLastSignaledValue, bd->FenceEvent); ::WaitForSingleObject(bd->FenceEvent, INFINITE); - uploadBuffer->Release(); tex->SetStatus(ImTextureStatus_OK); } @@ -804,6 +815,13 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() bd->commandQueueOwned = false; SafeRelease(bd->pRootSignature); SafeRelease(bd->pPipelineState); + if (bd->pTexUploadBufferMapped) + { + D3D12_RANGE range = { 0, bd->pTexUploadBufferSize }; + bd->pTexUploadBuffer->Unmap(0, &range); + bd->pTexUploadBufferMapped = nullptr; + } + SafeRelease(bd->pTexUploadBuffer); SafeRelease(bd->pTexCmdList); SafeRelease(bd->pTexCmdAllocator); SafeRelease(bd->Fence); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9c5b50988..e72b81462 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -99,6 +99,8 @@ Other Changes: of recreating them each time. (#8963, #8465) [@RT2Code] - Backends: DirectX12: Rework synchronization logic. (#8961) [@RT2Code] (presumably fixes old hard-to-repro crash issues such as #3463, #5018) +- Backends: DirectX12: Reuse texture upload buffer and grow it only when + necessary. (#9002) [@RT2Code] - Backends: DirectX12: Enable swapchain tearing if available. (#8965) [@RT2Code] - Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] From 878c863af4cdef451d9da92df4a3078694574411 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Oct 2025 13:25:02 +0200 Subject: [PATCH 1402/2359] Docs: reformat changlog entries. --- docs/CHANGELOG.txt | 135 +++++++++++++++++++++++---------------------- 1 file changed, 70 insertions(+), 65 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e72b81462..409bcb11d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,50 +41,53 @@ HOW TO UPDATE? Breaking Changes: -- Backends: Vulkan: moved some fields in ImGui_ImplVulkan_InitInfo: - init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass - init_info.Subpass --> init_info.PipelineInfoMain.Subpass - init_info.MSAASamples --> init_info.PipelineInfoMain.MSAASamples - init_info.PipelineRenderingCreateInfo --> init_info.PipelineInfoMain.PipelineRenderingCreateInfo - It makes things more consistent and was desirable to introduce new settings for - secondary viewports. (#8946, #8110, #8111, #8686) [@ocornut, @SuperRonan, @sylmroz] -- Backends: Vulkan: renamed ImGui_ImplVulkan_MainPipelineCreateInfo --> ImGui_ImplVulkan_PipelineInfo - (introduced very recently and only used by `ImGui_ImplVulkan_CreateMainPipeline()` - so it should not affect many users). (#8110, #8111) -- Backends: Vulkan: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a - `VkImageUsageFlags image_usage` argument. - It was previously hardcoded to `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` and defaults - to that when the value is 0. In theory the function is an internal helper but - since it's used by our examples some may have used it. (#8946, #8111, #8686) +- Backends: + - Vulkan: moved some fields in ImGui_ImplVulkan_InitInfo: + init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass + init_info.Subpass --> init_info.PipelineInfoMain.Subpass + init_info.MSAASamples --> init_info.PipelineInfoMain.MSAASamples + init_info.PipelineRenderingCreateInfo --> init_info.PipelineInfoMain.PipelineRenderingCreateInfo + It makes things more consistent and was desirable to introduce new settings for + secondary viewports. (#8946, #8110, #8111, #8686) [@ocornut, @SuperRonan, @sylmroz] + - Vulkan: renamed ImGui_ImplVulkan_MainPipelineCreateInfo --> ImGui_ImplVulkan_PipelineInfo + (introduced very recently and only used by `ImGui_ImplVulkan_CreateMainPipeline()` + so it should not affect many users). (#8110, #8111) + - Vulkan: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a + `VkImageUsageFlags image_usage` argument. + It was previously hardcoded to `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` and defaults + to that when the value is 0. In theory the function is an internal helper but + since it's used by our examples some may have used it. (#8946, #8111, #8686) Other Changes: - Windows: added lower-right resize grip on child windows using both ImGuiChildFlags_ResizeX and ImGuiChildFlags_ResizeY flags. (#8501) [@aleksijuvani] The grip is not visible before hovering to reduce clutter. -- InputText: fixed single-line InputText() not applying fine character clipping - properly (regression in 1.92.3). (#8967) [@Cyphall] -- InputText: fixed an infinite loop error happening if a custom input text - callback modifies/clear BufTextLen before calling InsertChars(). - (regression from 1.92.3). Note that this never really worked correctly, but - previously it would only temporary wreck cursor position, and since 1.92.3 it - would go in an infinite loop. (#8994, #3237) - Style: added ImGuiCol_UnsavedMarker, color of the unsaved document marker when using ImGuiWindowFlags_UnsavedDocument/ImGuiTabItemFlags_UnsavedDocument. (#8983) - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() helpers to null all handlers. (#8945, #2769) -- Textures: fixed a crash if texture status is set to _WantDestroy by a backend after - it had already been destroyed. This would typically happen when calling backend's - ImGui_ImplXXXX_InvalidateDeviceObjects() helpers twice in a row. (#8977, #8811) -- Textures: allowed backend to destroy texture while inside the NewFrame/EndFrame - scope. Basically if a backend decide to destroy a texture that we didn't request - to destroy (for e.g. freeing resources) the texture is immediately set to - a _WantCreate status again. (#8811) -- Textures: fixed an issue preventing multi-contexts sharing a ImFontAtlas from - being possible to destroy in any order. -- Textures: fixed not updating ImTextureData's RefCount when destroying a context - using a shared ImFontAtlas, leading standard backends to not properly free - texture resources. (#8975) [@icrashstuff] +- InputText: + - Fixed single-line InputText() not applying fine character clipping + properly (regression in 1.92.3). (#8967) [@Cyphall] + - Fixed an infinite loop error happening if a custom input text + callback modifies/clear BufTextLen before calling InsertChars(). + (regression from 1.92.3). Note that this never really worked correctly, but + previously it would only temporary wreck cursor position, and since 1.92.3 it + would go in an infinite loop. (#8994, #3237) +- Textures: + - Fixed a crash if texture status is set to _WantDestroy by a backend after + it had already been destroyed. This would typically happen when calling backend's + ImGui_ImplXXXX_InvalidateDeviceObjects() helpers twice in a row. (#8977, #8811) + - Allowed backend to destroy texture while inside the NewFrame/EndFrame + scope. Basically if a backend decide to destroy a texture that we didn't request + to destroy (for e.g. freeing resources) the texture is immediately set to + a _WantCreate status again. (#8811) + - Fixed an issue preventing multi-contexts sharing a ImFontAtlas from + being possible to destroy in any order. + - Fixed not updating ImTextureData's RefCount when destroying a context + using a shared ImFontAtlas, leading standard backends to not properly + free texture resources. (#8975) [@icrashstuff] - Demo: fixed layout issue in "Layout & Scrolling -> Scrolling" section. - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. @@ -92,37 +95,39 @@ Other Changes: - CI: updated Windows CI scripts to generate/use VulkanSDK. (#8925, #8778) [@yaz0r] - Docs: updated FAQ with new "What is the difference between Dear ImGui and traditional UI toolkits?" entry. (#8862) -- Backends: all backends call ImGuiPlatformIO::ClearPlatformHandlers() and - ClearRendererHandlers() on shutdown, so as not to leave function pointers - which may be dangling when using backend in e.g. DLL. (#8945, #2769) -- Backends: DirectX12: reuse a command list and allocator for texture uploads instead - of recreating them each time. (#8963, #8465) [@RT2Code] -- Backends: DirectX12: Rework synchronization logic. (#8961) [@RT2Code] - (presumably fixes old hard-to-repro crash issues such as #3463, #5018) -- Backends: DirectX12: Reuse texture upload buffer and grow it only when - necessary. (#9002) [@RT2Code] -- Backends: DirectX12: Enable swapchain tearing if available. (#8965) [@RT2Code] -- Backends: OpenGL3: fixed GL loader to work on Haiku OS which does not support - `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] -- Backends: GLFW: fixed build on platform that are neither Windows, macOS or - known Unixes (Regression in 1.92.3). (#8969, #8920, #8921) [@oktonion] -- Backends: SDL2,SDL3: avoid using the SDL_GetGlobalMouseState() path when one of our - window is hovered, as the event data is reliable and enough in this case. - - Fix mouse coordinates issue in fullscreen apps with macOS notch. (#7919, #7786) - - Essentially a working for SDL3 bug which will be fixed in SDL 3.3.0. - - Better perf on X11 as querying global position requires a round trip to X11 server. -- Backends: Win32: minor optimization not submitting gamepad io again if - XInput's dwPacketNumber has not changed. (#8556) [@MidTerm-CN] -- Backends: Vulkan: added a way to specify custom shaders by filling init fields - CustomShaderVertCreateInfo and CustomShaderFragCreateInfo. (#8585, #8271) [@johan0A] -- Backends: DX9,DX10,DX11,DX12,Metal,Vulkan,WGPU,SDLRenderer2,SDLRenderer3: - ensure that a texture in _WantDestroy state always turn to _Destroyed even - if your underlying graphics data was already destroyed. (#8977) -- Examples: SDL2+DirectX11: Try WARP software driver if hardware driver is - not available. (#5924, #5562) -- Examples: SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] -- Examples: Win32+DirectX12: Rework synchronization logic. (#8961) [@RT2Code] -- Examples: made examples's main.cpp consistent with returning 1 on error. +- Backends: + - All backends call ImGuiPlatformIO::ClearPlatformHandlers() and + ClearRendererHandlers() on shutdown, so as not to leave function pointers + which may be dangling when using backend in e.g. DLL. (#8945, #2769) + - DirectX12: reuse a command list and allocator for texture uploads instead + of recreating them each time. (#8963, #8465) [@RT2Code] + - DirectX12: Rework synchronization logic. (#8961) [@RT2Code] + (presumably fixes old hard-to-repro crash issues such as #3463, #5018) + - DirectX12: Reuse texture upload buffer and grow it only when + necessary. (#9002) [@RT2Code] + - DirectX12: Enable swapchain tearing if available. (#8965) [@RT2Code] + - OpenGL3: fixed GL loader to work on Haiku OS which does not support + `RTLD_NOLOAD`. (#8952) [@Xottab-DUTY, @threedeyes] + - GLFW: fixed build on platform that are neither Windows, macOS or + known Unixes (Regression in 1.92.3). (#8969, #8920, #8921) [@oktonion] + - SDL2,SDL3: avoid using the SDL_GetGlobalMouseState() path when one of our + window is hovered, as the event data is reliable and enough in this case. + - Fix mouse coordinates issue in fullscreen apps with macOS notch. (#7919, #7786) + - Essentially a workaround for SDL3 bug which will be fixed in SDL 3.3.0. + - Better perf on X11 as querying global position requires a round trip to X11 server. + - Win32: minor optimization not submitting gamepad io again if + XInput's dwPacketNumber has not changed. (#8556) [@MidTerm-CN] + - Vulkan: added a way to specify custom shaders by filling init fields + CustomShaderVertCreateInfo and CustomShaderFragCreateInfo. (#8585, #8271) [@johan0A] + - DX9,DX10,DX11,DX12,Metal,Vulkan,WGPU,SDLRenderer2,SDLRenderer3: + ensure that a texture in _WantDestroy state always turn to _Destroyed even + if your underlying graphics data was already destroyed. (#8977) +- Examples: + - SDL2+DirectX11: Try WARP software driver if hardware driver is + not available. (#5924, #5562) + - SDL3+DirectX11: Added SDL3+DirectX11 example. (#8956, #8957) [@tomaz82] + - Win32+DirectX12: Rework synchronization logic. (#8961) [@RT2Code] + - Made examples's main.cpp consistent with returning 1 on error. ----------------------------------------------------------------------- From b6e277980fbb00317ef5a9ff319e64ac3976866c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Oct 2025 15:02:55 +0200 Subject: [PATCH 1403/2359] Shortcuts: reorganize route scoring so values are easier to read. (#9004) Score now require 16-bits but ImGuiKeyRoutingData doesn't grow size. --- imgui.cpp | 49 +++++++++++++++++++++++++----------------------- imgui_internal.h | 6 +++--- 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2ba3aacd9..484c8513f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9378,7 +9378,7 @@ static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt) routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore; routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner; - routing_entry->RoutingNextScore = 255; + routing_entry->RoutingNextScore = 0; if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner) continue; rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer @@ -9447,23 +9447,24 @@ ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord) return routing_data; } -// Current score encoding (lower is highest priority): -// - 0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive -// - 1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active) -// - 2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused -// - 3+: ImGuiInputFlags_RouteFocused (if window in focus-stack) -// - 254: ImGuiInputFlags_RouteGlobal -// - 255: never route +// Current score encoding +// - 0: Never route +// - 1: ImGuiInputFlags_RouteGlobal (lower priority) +// - 100..199: ImGuiInputFlags_RouteFocused (if window in focus-stack) +// 200: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused +// 300: ImGuiInputFlags_RouteActive or ImGuiInputFlags_RouteFocused (if item active) +// 400: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive +// - 500..599: ImGuiInputFlags_RouteFocused | ImGuiInputFlags_RouteOverActive (if window in focus-stack) (higher priority) // 'flags' should include an explicit routing policy static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags) { ImGuiContext& g = *GImGui; if (flags & ImGuiInputFlags_RouteFocused) { - // ActiveID gets top priority + // ActiveID gets high priority // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it) if (owner_id != 0 && g.ActiveId == owner_id) - return 1; + return 300; // Score based on distance to focused window (lower is better) // Assuming both windows are submitting a routing request, @@ -9473,25 +9474,27 @@ static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInput // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score. // This essentially follow the window->ParentWindowForFocusRoute chain. if (focus_scope_id == 0) - return 255; + return 0; for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++) if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id) - return 3 + index_in_focus_path; - return 255; + return 199 - index_in_focus_path; + return 0; } else if (flags & ImGuiInputFlags_RouteActive) { if (owner_id != 0 && g.ActiveId == owner_id) - return 1; - return 255; + return 300; + return 0; } else if (flags & ImGuiInputFlags_RouteGlobal) { if (flags & ImGuiInputFlags_RouteOverActive) - return 0; + return 400; + if (owner_id != 0 && g.ActiveId == owner_id) + return 300; if (flags & ImGuiInputFlags_RouteOverFocused) - return 2; - return 254; + return 200; + return 1; } IM_ASSERT(0); return 0; @@ -9587,17 +9590,17 @@ bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, I const int score = CalcRoutingScore(focus_scope_id, owner_id, flags); IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score); - if (score == 255) + if (score == 0) return false; // Submit routing for NEXT frame (assuming score is sufficient) - // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <). + // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using >= instead of >). ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); - //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore); - if (score < routing_data->RoutingNextScore) + //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score >= routing_data->RoutingNextScore) : (score > routing_data->RoutingNextScore); + if (score > routing_data->RoutingNextScore) { routing_data->RoutingNext = owner_id; - routing_data->RoutingNextScore = (ImU8)score; + routing_data->RoutingNextScore = (ImU16)score; } // Return routing state for CURRENT frame diff --git a/imgui_internal.h b/imgui_internal.h index 1510271a0..c9c1f1333 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1556,12 +1556,12 @@ struct ImGuiKeyRoutingData { ImGuiKeyRoutingIndex NextEntryIndex; ImU16 Mods; // Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. - ImU8 RoutingCurrScore; // [DEBUG] For debug display - ImU8 RoutingNextScore; // Lower is better (0: perfect score) + ImU16 RoutingCurrScore; // [DEBUG] For debug display + ImU16 RoutingNextScore; // Lower is better (0: perfect score) ImGuiID RoutingCurr; ImGuiID RoutingNext; - ImGuiKeyRoutingData() { NextEntryIndex = -1; Mods = 0; RoutingCurrScore = RoutingNextScore = 255; RoutingCurr = RoutingNext = ImGuiKeyOwner_NoOwner; } + ImGuiKeyRoutingData() { NextEntryIndex = -1; Mods = 0; RoutingCurrScore = RoutingNextScore = 0; RoutingCurr = RoutingNext = ImGuiKeyOwner_NoOwner; } }; // Routing table: maintain a desired owner for each possible key-chord (key + mods), and setup owner in NewFrame() when mods are matching. From bad5ee167b06484e06015bca34ebfb20f8aeed24 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 13 Oct 2025 15:03:26 +0200 Subject: [PATCH 1404/2359] Shortcuts: added support for combining ImGuiInputFlags_RouteFocused with ImGuiInputFlags_RouteOverActive,. (#9004) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 11 +++++++++-- imgui.h | 2 +- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 409bcb11d..73c029ae0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,10 @@ Other Changes: using ImGuiWindowFlags_UnsavedDocument/ImGuiTabItemFlags_UnsavedDocument. (#8983) - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() helpers to null all handlers. (#8945, #2769) +- Inputs: + - Shortcuts: added support for combining ImGuiInputFlags_RouteFocused + (which is the default route) with ImGuiInputFlags_RouteOverActive, allowing + to steal shortcuts from active item without using global routing. (#9004) - InputText: - Fixed single-line InputText() not applying fine character clipping properly (regression in 1.92.3). (#8967) [@Cyphall] diff --git a/imgui.cpp b/imgui.cpp index 484c8513f..2cf1cb273 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9477,7 +9477,12 @@ static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInput return 0; for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++) if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id) - return 199 - index_in_focus_path; + { + if (flags & ImGuiInputFlags_RouteOverActive) // && g.ActiveId != 0 && g.ActiveId != owner_id) + return 599 - index_in_focus_path; + else + return 199 - index_in_focus_path; + } return 0; } else if (flags & ImGuiInputFlags_RouteActive) @@ -9534,8 +9539,10 @@ bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, I else IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner); - if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused)) + if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteUnlessBgFocused)) IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal); + if (flags & ImGuiInputFlags_RouteOverActive) + IM_ASSERT(flags & (ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteFocused)); // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified. key_chord = FixupKeyChord(key_chord); diff --git a/imgui.h b/imgui.h index 24c6423b4..b798903be 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.4 WIP" -#define IMGUI_VERSION_NUM 19235 +#define IMGUI_VERSION_NUM 19236 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From 702cc9993aca927d70c963d7c5826c2cd5ff0c0e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 14 Oct 2025 16:07:07 +0200 Subject: [PATCH 1405/2359] Relaxed internal assert in MarkItemEdited() some more. (#8997) Amend e7a734f78d, 5a2b1e8482 --- docs/CHANGELOG.txt | 1 + imgui.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 73c029ae0..4d4193633 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -93,6 +93,7 @@ Other Changes: using a shared ImFontAtlas, leading standard backends to not properly free texture resources. (#8975) [@icrashstuff] - Demo: fixed layout issue in "Layout & Scrolling -> Scrolling" section. +- Misc: Relaxed internal assert in MarkItemEdited() to allow for more use cases. (#8997) - Misc: Debuggers: added type formatters for the LLDB debuggers (e.g. Xcode, Android Studio & more) to provide nicer display for ImVec2, ImVec4, ImVector etc. See misc/debuggers/ for details. (#8950) [@mentlerd] diff --git a/imgui.cpp b/imgui.cpp index 2cf1cb273..977ce3b11 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4639,7 +4639,8 @@ void ImGui::MarkItemEdited(ImGuiID id) // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343) // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714) - IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive)); + // FIXME: This assert is getting a bit meaningless over time. It helped detect some unusual use cases but eventually it is becoming an unnecessary restriction. + IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || g.NavJustMovedToId || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive)); //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited; From c8db91b7b43a01ebb0c1440663abb02a89c371fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 14 Oct 2025 18:52:27 +0200 Subject: [PATCH 1406/2359] (Breaking) TreeNode, Selectable: commented out legacy ImGuiTreeNodeFlags_AllowItemOverlap, ImGuiSelectableFlags_AllowItemOverlap names obsoleted in 1.89.7. Amend 51f564e --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 +++ imgui.h | 6 +++--- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4d4193633..4b710a55e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,6 +42,9 @@ HOW TO UPDATE? Breaking Changes: - Backends: + - TreeNode, Selectable: commented out legacy names obsoleted in 1.89.7 (July 2023): + ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap + ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap - Vulkan: moved some fields in ImGui_ImplVulkan_InitInfo: init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass init_info.Subpass --> init_info.PipelineInfoMain.Subpass diff --git a/imgui.cpp b/imgui.cpp index 977ce3b11..c2c36a9e0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -392,6 +392,9 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/10/14 (1.92.4) - TreeNode, Selectable: commented out legacy names which were obsoleted in 1.89.7 (July 2023): + - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap + - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlapB - 2025/08/08 (1.92.2) - Backends: SDL_GPU3: Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete). - 2025/06/25 (1.92.0) - Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM diff --git a/imgui.h b/imgui.h index b798903be..7b0c28831 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.4 WIP" -#define IMGUI_VERSION_NUM 19236 +#define IMGUI_VERSION_NUM 19237 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -1311,7 +1311,7 @@ enum ImGuiTreeNodeFlags_ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiTreeNodeFlags_NavLeftJumpsBackHere = ImGuiTreeNodeFlags_NavLeftJumpsToParent, // Renamed in 1.92.0 ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth, // Renamed in 1.90.7 - ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 + //ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 #endif }; @@ -1354,7 +1354,7 @@ enum ImGuiSelectableFlags_ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 - ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 + //ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 #endif }; From 25e5baf5f0da5aa0820b4fdc5b2633a7d25965aa Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 14 Oct 2025 19:00:27 +0200 Subject: [PATCH 1407/2359] (Breaking) Clipper: commented out legacy IncludeRangeByIndices name obsoleted in 1.89.9. (#6424, #3841) --- docs/CHANGELOG.txt | 8 +++++--- imgui.cpp | 7 ++++--- imgui.h | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4b710a55e..9c8a6077c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,9 +42,11 @@ HOW TO UPDATE? Breaking Changes: - Backends: - - TreeNode, Selectable: commented out legacy names obsoleted in 1.89.7 (July 2023): - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap + - TreeNode, Selectable, Clipper: commented out legacy names obsoleted in + 1.89.7 (July 2023) and 1.89.9 (Sept 2023): + ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap + ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap + ImGuiListClipper::IncludeRangeByIndices() --> ImGuiListClipper::IncludeItemsByIndex() - Vulkan: moved some fields in ImGui_ImplVulkan_InitInfo: init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass init_info.Subpass --> init_info.PipelineInfoMain.Subpass diff --git a/imgui.cpp b/imgui.cpp index c2c36a9e0..216c56ba9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -392,9 +392,10 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - - 2025/10/14 (1.92.4) - TreeNode, Selectable: commented out legacy names which were obsoleted in 1.89.7 (July 2023): - - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap - - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlapB + - 2025/10/14 (1.92.4) - TreeNode, Selectable, Clipper: commented out legacy names which were obsoleted in 1.89.7 (July 2023) and 1.89.9 (Sept 2023); + - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap + - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap + - ImGuiListClipper::IncludeRangeByIndices() --> ImGuiListClipper::IncludeItemsByIndex() - 2025/08/08 (1.92.2) - Backends: SDL_GPU3: Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) - 2025/07/31 (1.92.2) - Tabs: Renamed ImGuiTabBarFlags_FittingPolicyResizeDown to ImGuiTabBarFlags_FittingPolicyShrink. Kept inline redirection enum (will obsolete). - 2025/06/25 (1.92.0) - Layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM diff --git a/imgui.h b/imgui.h index 7b0c28831..6aa73009d 100644 --- a/imgui.h +++ b/imgui.h @@ -2855,7 +2855,7 @@ struct ImGuiListClipper IMGUI_API void SeekCursorForItem(int item_index); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9] + //inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9] //inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] //inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] #endif From 9a5d5c45f54b1301ea471622eddede70384243af Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 14 Oct 2025 19:16:43 +0200 Subject: [PATCH 1408/2359] Version 1.92.4 --- docs/CHANGELOG.txt | 15 +++++++++------ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9c8a6077c..b703e065a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.4 WIP (In Progress) + VERSION 1.92.4 (Released 2025-10-14) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92.4 + Breaking Changes: - Backends: @@ -85,13 +87,13 @@ Other Changes: previously it would only temporary wreck cursor position, and since 1.92.3 it would go in an infinite loop. (#8994, #3237) - Textures: - - Fixed a crash if texture status is set to _WantDestroy by a backend after - it had already been destroyed. This would typically happen when calling backend's + - Fixed a crash if texture status is set to ImTextureStatus_WantDestroy by a backend + after it had already been destroyed. This would typically happen when calling ImGui_ImplXXXX_InvalidateDeviceObjects() helpers twice in a row. (#8977, #8811) - Allowed backend to destroy texture while inside the NewFrame/EndFrame scope. Basically if a backend decide to destroy a texture that we didn't request to destroy (for e.g. freeing resources) the texture is immediately set to - a _WantCreate status again. (#8811) + a ImTextureStatus_WantCreate status again. (#8811) - Fixed an issue preventing multi-contexts sharing a ImFontAtlas from being possible to destroy in any order. - Fixed not updating ImTextureData's RefCount when destroying a context @@ -130,8 +132,9 @@ Other Changes: - Vulkan: added a way to specify custom shaders by filling init fields CustomShaderVertCreateInfo and CustomShaderFragCreateInfo. (#8585, #8271) [@johan0A] - DX9,DX10,DX11,DX12,Metal,Vulkan,WGPU,SDLRenderer2,SDLRenderer3: - ensure that a texture in _WantDestroy state always turn to _Destroyed even - if your underlying graphics data was already destroyed. (#8977) + ensure that a texture in ImTextureStatus_WantDestroy state always turn to + ImTextureStatus_Destroyed even if your underlying graphics data was already + destroyed. (#8977) - Examples: - SDL2+DirectX11: Try WARP software driver if hardware driver is not available. (#5924, #5562) diff --git a/imgui.cpp b/imgui.cpp index 216c56ba9..76b4a73f4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 WIP +// dear imgui, v1.92.4 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 6aa73009d..0a216b76c 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 WIP +// dear imgui, v1.92.4 // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.4 WIP" -#define IMGUI_VERSION_NUM 19237 +#define IMGUI_VERSION "1.92.4" +#define IMGUI_VERSION_NUM 19240 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index dec1bad40..e473b2520 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 WIP +// dear imgui, v1.92.4 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a2c616012..9d0f024f5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 WIP +// dear imgui, v1.92.4 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index c9c1f1333..9c920eda1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 WIP +// dear imgui, v1.92.4 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index af0e8c6cf..b4d4f891a 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 WIP +// dear imgui, v1.92.4 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a3a4ae1cf..9ebafa85b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 WIP +// dear imgui, v1.92.4 // (widgets code) /* From 7d8d587bc064e84d519a0d7fd26c49fda16f2f23 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Oct 2025 16:46:18 +0200 Subject: [PATCH 1409/2359] Version 1.92.5 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b703e065a..1be5cadaf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.5 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.92.4 (Released 2025-10-14) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 76b4a73f4..b9845a6f1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 +// dear imgui, v1.92.5 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 0a216b76c..575989a77 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 +// dear imgui, v1.92.5 WIP // (headers) // Help: @@ -28,8 +28,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.4" -#define IMGUI_VERSION_NUM 19240 +#define IMGUI_VERSION "1.92.5 WIP" +#define IMGUI_VERSION_NUM 19241 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e473b2520..0c8e51b5c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 +// dear imgui, v1.92.5 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 9d0f024f5..b7613ef5a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 +// dear imgui, v1.92.5 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 9c920eda1..0fa0ba8f2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 +// dear imgui, v1.92.5 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b4d4f891a..7e7395352 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 +// dear imgui, v1.92.5 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9ebafa85b..31bb3a060 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.4 +// dear imgui, v1.92.5 WIP // (widgets code) /* From d7fec5e1d33e4256104524fba669dbd4b68e5a65 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Oct 2025 16:50:11 +0200 Subject: [PATCH 1410/2359] Tables: fixed a bug where nesting BeginTable()->Begin()->BeginTable(). (#9005) --- docs/CHANGELOG.txt | 5 +++++ imgui_internal.h | 1 + imgui_tables.cpp | 5 +++-- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1be5cadaf..924fbdb41 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,11 @@ Breaking Changes: Other Changes: +- Tables: fixed a bug where nesting BeginTable()->Begin()->BeginTable() would + result in temporarily incorrect state, which would lead to bugs to side effects + in various locations, e.g. GetContentRegionAvail() calls or using clipper. (#9005) + EndTable() was mistakenly restoring a wrong current table. + ----------------------------------------------------------------------- VERSION 1.92.4 (Released 2025-10-14) diff --git a/imgui_internal.h b/imgui_internal.h index 0fa0ba8f2..701652e4b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3045,6 +3045,7 @@ struct IMGUI_API ImGuiTable // sizeof() ~ 136 bytes. struct IMGUI_API ImGuiTableTempData { + ImGuiID WindowID; // Shortcut to g.Tables[TableIndex]->OuterWindow->ID. int TableIndex; // Index in g.Tables.Buf[] pool float LastTimeActive; // Last timestamp this structure was used float AngledHeadersExtraWidth; // Used in EndTable() diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 7e7395352..d79cfe435 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -464,6 +464,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->HostIndentX = inner_window->DC.Indent.x; table->HostClipRect = inner_window->ClipRect; table->HostSkipItems = inner_window->SkipItems; + temp_data->WindowID = inner_window->ID; temp_data->HostBackupWorkRect = inner_window->WorkRect; temp_data->HostBackupParentWorkRect = inner_window->ParentWorkRect; temp_data->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset; @@ -1366,7 +1367,7 @@ void ImGui::EndTable() ImGuiWindow* inner_window = table->InnerWindow; ImGuiWindow* outer_window = table->OuterWindow; ImGuiTableTempData* temp_data = table->TempData; - IM_ASSERT(inner_window == g.CurrentWindow); + IM_ASSERT(inner_window == g.CurrentWindow && inner_window->ID == temp_data->WindowID); IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow); if (table->IsInsideRow) @@ -1559,7 +1560,7 @@ void ImGui::EndTable() IM_ASSERT(g.CurrentWindow == outer_window && g.CurrentTable == table); IM_ASSERT(g.TablesTempDataStacked > 0); temp_data = (--g.TablesTempDataStacked > 0) ? &g.TablesTempData[g.TablesTempDataStacked - 1] : NULL; - g.CurrentTable = temp_data ? g.Tables.GetByIndex(temp_data->TableIndex) : NULL; + g.CurrentTable = temp_data && (temp_data->WindowID == outer_window->ID) ? g.Tables.GetByIndex(temp_data->TableIndex) : NULL; if (g.CurrentTable) { g.CurrentTable->TempData = temp_data; From 2a5e9a15e4d1860df756fee9dd678569705f877d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 15 Oct 2025 19:12:40 +0200 Subject: [PATCH 1411/2359] InputTextMultiline: fixed a crash when using ImGuiInputTextFlags_WordWrap and resizing the parent window while keeping the multi-line field active. (#9007, #3237) --- docs/CHANGELOG.txt | 4 ++++ imgui_widgets.cpp | 7 ++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 924fbdb41..f42a3b030 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,10 @@ Other Changes: result in temporarily incorrect state, which would lead to bugs to side effects in various locations, e.g. GetContentRegionAvail() calls or using clipper. (#9005) EndTable() was mistakenly restoring a wrong current table. +- InputTextMultiline: fixed a crash when using ImGuiInputTextFlags_WordWrap and + resizing the parent window while keeping the multi-line field active (which is + most typically achieved when resizing programmatically or via a docking layout + reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] ----------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 31bb3a060..f0b6e2a5f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5401,7 +5401,12 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ line_index->Offsets.resize(0); int line_count = 1; if (is_multiline) - line_count = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, (render_cursor && state && state->CursorFollow) ? INT_MAX : line_visible_n1 + 1, buf_display_end ? NULL : &buf_display_end); + { + // If scrolling is expected to change build full index. + // FIXME-OPT: Could append to index when new value of line_visible_n1 becomes bigger, see second call to CalcClipRectVisibleItemsY() below. + bool will_scroll_y = state && ((state->CursorFollow && render_cursor) || (state->CursorCenterY && (render_cursor || render_selection))); + line_count = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, will_scroll_y ? INT_MAX : line_visible_n1 + 1, buf_display_end ? NULL : &buf_display_end); + } line_index->EndOffset = (int)(buf_display_end - buf_display); line_visible_n1 = ImMin(line_visible_n1, line_count); From 36de604a5b3f4e726ad5cf4480b150195246d59e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Oct 2025 16:12:29 +0200 Subject: [PATCH 1412/2359] InputText: avoid continuously overwriting ownership of ImGuiKey_Enter / ImGuiKey_KeypadEnter in order to allow e.g. external Shortcut to override behavior. (#9004) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 12 +++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f42a3b030..644ff316d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Other Changes: result in temporarily incorrect state, which would lead to bugs to side effects in various locations, e.g. GetContentRegionAvail() calls or using clipper. (#9005) EndTable() was mistakenly restoring a wrong current table. +- InputText: avoid continuously overwriting ownership of ImGuiKey_Enter/_KeypadEnter + keys in order to allow e.g. external Shortcut override behavior. (#9004) - InputTextMultiline: fixed a crash when using ImGuiInputTextFlags_WordWrap and resizing the parent window while keeping the multi-line field active (which is most typically achieved when resizing programmatically or via a docking layout diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f0b6e2a5f..035d7885a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4820,7 +4820,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Declare some inputs, the other are registered and polled via Shortcut() routing system. // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combination into individual shortcuts. - const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Enter, ImGuiKey_KeypadEnter, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End }; + const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End }; for (ImGuiKey key : always_owned_keys) SetKeyOwner(key, id); if (user_clicked) @@ -5028,7 +5028,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // We allow validate/cancel with Nav source (gamepad) to makes it easier to undo an accidental NavInput press with no keyboard wired, but otherwise it isn't very useful. const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; - const bool is_enter_pressed = IsKeyPressed(ImGuiKey_Enter, true) || IsKeyPressed(ImGuiKey_KeypadEnter, true); + const bool is_enter = Shortcut(ImGuiKey_Enter, f_repeat, id) || Shortcut(ImGuiKey_KeypadEnter, f_repeat, id); + const bool is_ctrl_enter = Shortcut(ImGuiMod_Ctrl | ImGuiKey_Enter, f_repeat, id) || Shortcut(ImGuiMod_Ctrl | ImGuiKey_KeypadEnter, f_repeat, id); const bool is_gamepad_validate = nav_gamepad_active && (IsKeyPressed(ImGuiKey_NavGamepadActivate, false) || IsKeyPressed(ImGuiKey_NavGamepadInput, false)); const bool is_cancel = Shortcut(ImGuiKey_Escape, f_repeat, id) || (nav_gamepad_active && Shortcut(ImGuiKey_NavGamepadCancel, f_repeat, id)); @@ -5063,11 +5064,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } - else if (is_enter_pressed || is_gamepad_validate) + else if (is_enter || is_ctrl_enter || is_gamepad_validate) { // Determine if we turn Enter into a \n character bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; - if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line != io.KeyCtrl)) + if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line != is_ctrl_enter)) { validated = true; if (io.ConfigInputTextEnterKeepActive && !is_multiline) @@ -5077,7 +5078,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } else if (!is_readonly) { - unsigned int c = '\n'; // Insert new line + // Insert new line + unsigned int c = '\n'; if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data)) state->OnCharPressed(c); } From 3dc511c71dd3155cd8036d64ee87ae0250cb1947 Mon Sep 17 00:00:00 2001 From: BrutPitt Date: Thu, 16 Oct 2025 18:13:34 +0200 Subject: [PATCH 1413/2359] Backends: WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ '--use-port=emdawnwebgpu' ports. (#8381, #8898) --- backends/imgui_impl_wgpu.cpp | 74 ++++++++++++++++++++---------------- backends/imgui_impl_wgpu.h | 23 ++++++++--- docs/CHANGELOG.txt | 5 +++ 3 files changed, 65 insertions(+), 37 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 3045f9c7c..fe5cd5832 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -1,6 +1,6 @@ // dear imgui: Renderer for WebGPU -// This needs to be used along with a Platform Binding (e.g. GLFW) -// (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.) +// This needs to be used along with a Platform Binding (e.g. GLFW, SDL2, SDL3) +// (Please note that WebGPU is a recent API, may not be supported by all browser, and its ecosystem is generally a mess) // Implemented features: // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID/ImTextureRef! @@ -8,6 +8,8 @@ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'. // [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures). +// Read imgui_impl_wgpu.h about how to use the IMGUI_IMPL_WEBGPU_BACKEND_WGPU or IMGUI_IMPL_WEBGPU_BACKEND_DAWN flags. + // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: @@ -18,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-10-16: Update to compile with Dawn and Emscripten's 4.0.10+ '--use-port=emdawnwebgpu' ports. (#8381, #8898) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. (#8465) // 2025-02-26: Recreate image bind groups during render. (#8426, #8046, #7765, #8027) + Update for latest webgpu-native changes. @@ -46,20 +49,20 @@ #include "imgui.h" -// When targeting native platforms (i.e. NOT Emscripten), one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN -// or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details. -#ifndef __EMSCRIPTEN__ - #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - #error exactly one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be defined! - #endif -#else - #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - #error neither IMGUI_IMPL_WEBGPU_BACKEND_DAWN nor IMGUI_IMPL_WEBGPU_BACKEND_WGPU may be defined if targeting emscripten! - #endif -#endif - #ifndef IMGUI_DISABLE #include "imgui_impl_wgpu.h" + +// One of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details. +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#error Exactly one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be defined! +#endif + +// This condition is true when it's built with EMSCRIPTEN using -sUSE_WEBGPU=1 flag (deprecated from 4.0.10) +// This condition is false for all other 3 cases: WGPU-Native, DAWN-Native or DAWN-EMSCRIPTEN (using --use-port=emdawnwebgpu flag) +#if defined(__EMSCRIPTEN__) && defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#define IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN +#endif + #include #include @@ -259,7 +262,7 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) WGPUShaderSourceWGSL wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL; wgsl_desc.code = { wgsl_source, WGPU_STRLEN }; @@ -275,7 +278,7 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c WGPUProgrammableStageDescriptor stage_desc = {}; stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc); -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) stage_desc.entryPoint = { "main", WGPU_STRLEN }; #else stage_desc.entryPoint = "main"; @@ -398,9 +401,10 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder WGPUBufferDescriptor vb_desc = { nullptr, +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) + { "Dear ImGui Vertex buffer", WGPU_STRLEN, }, +#else "Dear ImGui Vertex buffer", -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - WGPU_STRLEN, #endif WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex, MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4), @@ -425,9 +429,10 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder WGPUBufferDescriptor ib_desc = { nullptr, +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) + { "Dear ImGui Index buffer", WGPU_STRLEN, }, +#else "Dear ImGui Index buffer", -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - WGPU_STRLEN, #endif WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index, MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4), @@ -560,7 +565,7 @@ void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex) // Create texture WGPUTextureDescriptor tex_desc = {}; -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) tex_desc.label = { "Dear ImGui Texture", WGPU_STRLEN }; #else tex_desc.label = "Dear ImGui Texture"; @@ -605,7 +610,7 @@ void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex) // Update full texture or selected blocks. We only ever write to textures regions which have never been used before! // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions. -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) WGPUTexelCopyTextureInfo dst_view = {}; #else WGPUImageCopyTexture dst_view = {}; @@ -614,7 +619,7 @@ void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex) dst_view.mipLevel = 0; dst_view.origin = { (uint32_t)upload_x, (uint32_t)upload_y, 0 }; dst_view.aspect = WGPUTextureAspect_All; -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) WGPUTexelCopyBufferLayout layout = {}; #else WGPUTextureDataLayout layout = {}; @@ -636,9 +641,10 @@ static void ImGui_ImplWGPU_CreateUniformBuffer() WGPUBufferDescriptor ub_desc = { nullptr, +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) + { "Dear ImGui Uniform buffer", WGPU_STRLEN, }, +#else "Dear ImGui Uniform buffer", -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - WGPU_STRLEN, #endif WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform, MEMALIGN(sizeof(Uniforms), 16), @@ -751,7 +757,7 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() // Create depth-stencil State WGPUDepthStencilState depth_stencil_state = {}; depth_stencil_state.format = bd->depthStencilFormat; -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN) depth_stencil_state.depthWriteEnabled = WGPUOptionalBool_False; #else depth_stencil_state.depthWriteEnabled = false; @@ -833,14 +839,18 @@ bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info) // Setup backend capabilities flags ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)(); io.BackendRendererUserData = (void*)bd; +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) #if defined(__EMSCRIPTEN__) - io.BackendRendererName = "imgui_impl_webgpu_emscripten"; -#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) - io.BackendRendererName = "imgui_impl_webgpu_dawn"; -#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - io.BackendRendererName = "imgui_impl_webgpu_wgpu"; + io.BackendRendererName = "imgui_impl_wgpu (Dawn, Emscripten)"; // compiled & linked using EMSCRIPTEN with "--use-port=emdawnwebgpu" flag #else - io.BackendRendererName = "imgui_impl_webgpu"; + io.BackendRendererName = "imgui_impl_wgpu (Dawn, Native)"; +#endif +#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#if defined(__EMSCRIPTEN__) + io.BackendRendererName = "imgui_impl_wgpu (WGPU, Emscripten)"; // linked using EMSCRIPTEN with "-sUSE_WEBGPU=1" flag, deprecated from EMSCRIPTEN 4.0.10 +#else + io.BackendRendererName = "imgui_impl_wgpu (WGPU, Native)"; +#endif #endif io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 499c899a0..9443106b8 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -1,11 +1,14 @@ // dear imgui: Renderer for WebGPU -// This needs to be used along with a Platform Binding (e.g. GLFW) -// (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.) +// This needs to be used along with a Platform Binding (e.g. GLFW, SDL2, SDL3) +// (Please note that WebGPU is a recent API, may not be supported by all browser, and its ecosystem is generally a mess) -// Important note to dawn and/or wgpu users: when targeting native platforms (i.e. NOT emscripten), -// one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. +// When targeting native platforms: +// - One of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU *must* be provided. +// When targeting Emscripten: +// - We now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN is Emscripten version is 4.0.10+, which correspond to using Emscripten '--use-port=emdawnwebgpu'. +// - We can still define IMGUI_IMPL_WEBGPU_BACKEND_WGPU to use Emscripten '-s USE_WEBGPU=1' which is marked as obsolete by Emscripten. // Add #define to your imconfig.h file, or as a compilation flag in your build system. -// This requirement will be removed once WebGPU stabilizes and backends converge on a unified interface. +// This requirement may be removed once WebGPU stabilizes and backends converge on a unified interface. //#define IMGUI_IMPL_WEBGPU_BACKEND_DAWN //#define IMGUI_IMPL_WEBGPU_BACKEND_WGPU @@ -27,6 +30,16 @@ #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE +// Setup Emscripten default if not specified. +#if defined(__EMSCRIPTEN__) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#include +#if (__EMSCRIPTEN_major__ >= 4) && (__EMSCRIPTEN_minor__ >= 0) && (__EMSCRIPTEN_tiny__ >= 10) +#define IMGUI_IMPL_WEBGPU_BACKEND_DAWN +#else +#define IMGUI_IMPL_WEBGPU_BACKEND_WGPU +#endif +#endif + #include // Initialization data, for ImGui_ImplWGPU_Init() diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 644ff316d..ad385527a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,11 @@ Other Changes: resizing the parent window while keeping the multi-line field active (which is most typically achieved when resizing programmatically or via a docking layout reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] +- Backends: WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ + '--use-port=emdawnwebgpu' ports. (#8381, #8898) [@brutpitt, @trbabb] + When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN + instead of IMGUI_IMPL_WEBGPU_BACKEND_WGPU, if neither are specified. + (note: examples application were not updated yet) ----------------------------------------------------------------------- From 71447b94fbdddc19495703d70037172fccd43048 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Oct 2025 18:23:02 +0200 Subject: [PATCH 1414/2359] Examples: GLFW+WebGPU: default build to legacy for now. (#8381) --- examples/example_glfw_wgpu/Makefile.emscripten | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/examples/example_glfw_wgpu/Makefile.emscripten b/examples/example_glfw_wgpu/Makefile.emscripten index 8ee398bc8..545a50578 100644 --- a/examples/example_glfw_wgpu/Makefile.emscripten +++ b/examples/example_glfw_wgpu/Makefile.emscripten @@ -34,9 +34,16 @@ EMS = # ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) # Note: For glfw, we use emscripten-glfw port (contrib.glfw3) instead of (-s USE_GLFW=3) to get a better support for High DPI displays. EMS += -s DISABLE_EXCEPTION_CATCHING=1 --use-port=contrib.glfw3 -LDFLAGS += -s USE_WEBGPU=1 LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1 +# (1) Using legacy WebGPU implementation (Emscripten < 4.0.10) +EMS += -DIMGUI_IMPL_WEBGPU_BACKEND_WGPU +LDFLAGS += -s USE_WEBGPU=1 + +# or (2) Using newer Dawn-based WebGPU port (Emscripten >= 4.0.10) (UNSUPPORTED YET) +#EMS += --use-port=emdawnwebgpu +#LDFLAGS += --use-port=emdawnwebgpu + # Build as single file (binary text encoded in .html file) #LDFLAGS += -sSINGLE_FILE From 4b1f5aba80438a27b1ae85400e83e6d21391b0e1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 16 Oct 2025 19:10:10 +0200 Subject: [PATCH 1415/2359] Examples: GLFW+WebGPU: moving blocks to simplify upcoming diff. (#8381) --- examples/example_glfw_wgpu/main.cpp | 68 +++++++++++------------- examples/example_sdl3_directx11/main.cpp | 2 +- 2 files changed, 33 insertions(+), 37 deletions(-) diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 59bb505a9..874734936 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -27,17 +27,16 @@ #include // Data -static WGPUInstance wgpu_instance = nullptr; -static WGPUDevice wgpu_device = nullptr; -static WGPUSurface wgpu_surface = nullptr; -static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm; -static WGPUSwapChain wgpu_swap_chain = nullptr; -static int wgpu_surface_width = 1280; -static int wgpu_surface_height = 800; +static WGPUInstance wgpu_instance = nullptr; +static WGPUDevice wgpu_device = nullptr; +static WGPUSurface wgpu_surface = nullptr; +static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm; +static WGPUSwapChain wgpu_swap_chain = nullptr; +static int wgpu_surface_width = 1280; +static int wgpu_surface_height = 800; // Forward declarations static bool InitWGPU(GLFWwindow* window); -static void ResizeSurface(int width, int height); static void glfw_error_callback(int error, const char* description) { @@ -58,6 +57,21 @@ static void wgpu_error_callback(WGPUErrorType error_type, const char* message, v printf("%s error: %s\n", error_type_lbl, message); } +static void ResizeSurface(int width, int height) +{ + if (wgpu_swap_chain) + wgpuSwapChainRelease(wgpu_swap_chain); + wgpu_surface_width = width; + wgpu_surface_height = height; + WGPUSwapChainDescriptor swap_chain_desc = {}; + swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment; + swap_chain_desc.format = wgpu_preferred_fmt; + swap_chain_desc.width = width; + swap_chain_desc.height = height; + swap_chain_desc.presentMode = WGPUPresentMode_Fifo; + wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc); +} + // Main code int main(int, char**) { @@ -166,7 +180,7 @@ int main(int, char**) glfwGetFramebufferSize((GLFWwindow*)window, &width, &height); if (width != wgpu_surface_width || height != wgpu_surface_height) { - ImGui_ImplWGPU_InvalidateDeviceObjects(); + ImGui_ImplWGPU_InvalidateDeviceObjects(); // FIXME-OPT: Why doing this? This seems unnecessary and unoptimal. ResizeSurface(width, height); ImGui_ImplWGPU_CreateDeviceObjects(); } @@ -275,21 +289,21 @@ static WGPUAdapter RequestAdapter(WGPUInstance instance) auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* message, void* pUserData) { if (status == WGPURequestAdapterStatus_Success) - *(WGPUAdapter*)(pUserData) = adapter; + *(WGPUAdapter*)pUserData = adapter; else printf("Could not get WebGPU adapter: %s\n", message); -}; + }; WGPUAdapter adapter; wgpuInstanceRequestAdapter(instance, nullptr, onAdapterRequestEnded, (void*)&adapter); return adapter; } -static WGPUDevice RequestDevice(WGPUAdapter& adapter) +static WGPUDevice RequestDevice(WGPUAdapter adapter) { auto onDeviceRequestEnded = [](WGPURequestDeviceStatus status, WGPUDevice device, const char* message, void* pUserData) { if (status == WGPURequestDeviceStatus_Success) - *(WGPUDevice*)(pUserData) = device; + *(WGPUDevice*)pUserData = device; else printf("Could not get WebGPU device: %s\n", message); }; @@ -307,14 +321,7 @@ static bool InitWGPU(GLFWwindow* window) wgpu_device = emscripten_webgpu_get_device(); if (!wgpu_device) return false; -#else - WGPUAdapter adapter = RequestAdapter(instance.Get()); - if (!adapter) - return false; - wgpu_device = RequestDevice(adapter); -#endif -#ifdef __EMSCRIPTEN__ wgpu::SurfaceDescriptorFromCanvasHTMLSelector canvas_desc = {}; canvas_desc.selector = "#canvas"; wgpu::SurfaceDescriptor surface_desc = {}; @@ -324,6 +331,11 @@ static bool InitWGPU(GLFWwindow* window) wgpu::Adapter adapter = {}; wgpu_preferred_fmt = (WGPUTextureFormat)surface.GetPreferredFormat(adapter); #else + WGPUAdapter adapter = RequestAdapter(instance.Get()); + if (!adapter) + return false; + wgpu_device = RequestDevice(adapter); + wgpu::Surface surface = wgpu::glfw::CreateSurfaceForWindow(instance, window); if (!surface) return false; @@ -335,21 +347,5 @@ static bool InitWGPU(GLFWwindow* window) wgpu_surface = surface.MoveToCHandle(); wgpuDeviceSetUncapturedErrorCallback(wgpu_device, wgpu_error_callback, nullptr); - return true; } - -static void ResizeSurface(int width, int height) -{ - if (wgpu_swap_chain) - wgpuSwapChainRelease(wgpu_swap_chain); - wgpu_surface_width = width; - wgpu_surface_height = height; - WGPUSwapChainDescriptor swap_chain_desc = {}; - swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment; - swap_chain_desc.format = wgpu_preferred_fmt; - swap_chain_desc.width = width; - swap_chain_desc.height = height; - swap_chain_desc.presentMode = WGPUPresentMode_Fifo; - wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc); -} diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index 946992409..39171c8cd 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -48,7 +48,7 @@ int main(int, char**) } SDL_PropertiesID props = SDL_GetWindowProperties(window); - HWND hwnd = (HWND)SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL); + HWND hwnd = (HWND)SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) From 065f9e02695c4eab92dab548f0c37f5297fc7a63 Mon Sep 17 00:00:00 2001 From: mwlasiuk Date: Wed, 15 Oct 2025 21:34:10 +0200 Subject: [PATCH 1416/2359] Backends: Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME. (#9008, #7722, #6582, #4854) --- backends/imgui_impl_vulkan.cpp | 1 + backends/imgui_impl_vulkan.h | 11 ++++++++++- docs/CHANGELOG.txt | 2 ++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index a8eb9a8c4..baffb7e51 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-10-15: Vulkan: Added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to volk.h header. (#9008) // 2025-09-26: *BREAKING CHANGE*: moved some fields in ImGui_ImplVulkan_InitInfo: init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass, init_info.Subpass --> init_info.PipelineInfoMain.Subpass, init_info.MSAASamples --> init_info.PipelineInfoMain.MSAASamples, init_info.PipelineRenderingCreateInfo --> init_info.PipelineInfoMain.PipelineRenderingCreateInfo. // 2025-09-26: *BREAKING CHANGE*: renamed ImGui_ImplVulkan_MainPipelineCreateInfo to ImGui_ImplVulkan_PipelineInfo. Introduced very recently so shouldn't affect many users. // 2025-09-26: *BREAKING CHANGE*: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a VkImageUsageFlags image_usage` argument, default to VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT if 0. diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index afc698701..fb51a2ac0 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -41,9 +41,14 @@ // If you have no idea what this is, leave it alone! //#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES -// Convenience support for Volk +// [Configuration] Convenience support for Volk // (you can also technically use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().) +// (When using Volk from directory outside your include directories list you can specify full path to the volk.h header, +// for example when using Volk from VulkanSDK and using include_directories(${Vulkan_INCLUDE_DIRS})' from 'find_package(Vulkan REQUIRED)') //#define IMGUI_IMPL_VULKAN_USE_VOLK +//#define IMGUI_IMPL_VULKAN_VOLK_FILENAME +//#define IMGUI_IMPL_VULKAN_VOLK_FILENAME // Default +// Reminder: make those changes in your imconfig.h file, not here! #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES) #define VK_NO_PROTOTYPES @@ -54,7 +59,11 @@ // Vulkan includes #ifdef IMGUI_IMPL_VULKAN_USE_VOLK +#ifdef IMGUI_IMPL_VULKAN_VOLK_FILENAME +#include IMGUI_IMPL_VULKAN_VOLK_FILENAME +#else #include +#endif #else #include #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ad385527a..2213f5866 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,8 @@ Other Changes: resizing the parent window while keeping the multi-line field active (which is most typically achieved when resizing programmatically or via a docking layout reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] +- Backends: Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to + Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] - Backends: WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ '--use-port=emdawnwebgpu' ports. (#8381, #8898) [@brutpitt, @trbabb] When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN From e11b7a0414859a51921359e64e664e58d277be9c Mon Sep 17 00:00:00 2001 From: Ingmar Rieger Date: Sat, 18 Oct 2025 17:34:40 +0200 Subject: [PATCH 1417/2359] Make ClearPlatformHandlers and ClearRendererHandlers API public (#9016) --- imgui.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 575989a77..99ef32e17 100644 --- a/imgui.h +++ b/imgui.h @@ -3978,8 +3978,8 @@ struct ImGuiPlatformIO // Functions //------------------------------------------------------------------ - void ClearPlatformHandlers(); // Clear all Platform_XXX fields. Typically called on Platform Backend shutdown. - void ClearRendererHandlers(); // Clear all Renderer_XXX fields. Typically called on Renderer Backend shutdown. + IMGUI_API void ClearPlatformHandlers(); // Clear all Platform_XXX fields. Typically called on Platform Backend shutdown. + IMGUI_API void ClearRendererHandlers(); // Clear all Renderer_XXX fields. Typically called on Renderer Backend shutdown. }; // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). From 63bfad401fb3d44670ecd99dea4fa6d8ef607c46 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 20 Oct 2025 18:58:45 +0200 Subject: [PATCH 1418/2359] MultiSelect: added ImGuiMultiSelectFlags_NoSelectOnRightClick. (#8200, #9015) --- docs/CHANGELOG.txt | 3 +++ imgui.h | 1 + imgui_demo.cpp | 5 +++++ imgui_widgets.cpp | 4 ++-- 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2213f5866..ecc881700 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,9 @@ Other Changes: resizing the parent window while keeping the multi-line field active (which is most typically achieved when resizing programmatically or via a docking layout reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] +- MultiSelect: added ImGuiMultiSelectFlags_NoSelectOnRightClick to disable default + right-click processing, which selects item on mouse down and is designed for + context-menus. (#8200, #9015) - Backends: Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] - Backends: WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ diff --git a/imgui.h b/imgui.h index 99ef32e17..c2ea4aa50 100644 --- a/imgui.h +++ b/imgui.h @@ -3003,6 +3003,7 @@ enum ImGuiMultiSelectFlags_ ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 14, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. //ImGuiMultiSelectFlags_RangeSelect2d = 1 << 15, // Shift+Selection uses 2d geometry instead of linear sequence, so possible to use Shift+up/down to select vertically in grid. Analogous to what BoxSelect does. ImGuiMultiSelectFlags_NavWrapX = 1 << 16, // [Temporary] Enable navigation wrapping on X axis. Provided as a convenience because we don't have a design for the general Nav API for this yet. When the more general feature be public we may obsolete this flag in favor of new one. + ImGuiMultiSelectFlags_NoSelectOnRightClick = 1 << 17, // Disable default right-click processing, which selects item on mouse down, and is designed for context-menus. }; // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0c8e51b5c..8f0e393a1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2647,6 +2647,10 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d { HelpMarker("Selections can be built using Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data."); + ImGui::BulletText("Wiki page:"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("imgui/wiki/Multi-Select", "https://github.com/ocornut/imgui/wiki/Multi-Select"); + // Without any fancy API: manage single-selection yourself. IMGUI_DEMO_MARKER("Widgets/Selection State/Single-Select"); if (ImGui::TreeNode("Single-Select")) @@ -3180,6 +3184,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClearOnReselect", &flags, ImGuiMultiSelectFlags_NoAutoClearOnReselect); + ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectOnRightClick", &flags, ImGuiMultiSelectFlags_NoSelectOnRightClick); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 035d7885a..4033203da 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8213,8 +8213,8 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) } // Right-click handling. - // FIXME-MULTISELECT: Currently filtered out by ImGuiMultiSelectFlags_NoAutoSelect but maybe should be moved to Selectable(). See https://github.com/ocornut/imgui/pull/5816 - if (hovered && IsMouseClicked(1) && (flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0) + // FIXME-MULTISELECT: Maybe should be moved to Selectable()? Also see #5816, #8200, #9015 + if (hovered && IsMouseClicked(1) && (flags & (ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoSelectOnRightClick)) == 0) { if (g.ActiveId != 0 && g.ActiveId != id) ClearActiveID(); From b46f099a3fcb837af9c22e1721b6563c8afa43d4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 20 Oct 2025 23:57:09 +0200 Subject: [PATCH 1419/2359] Backends: GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) --- backends/imgui_impl_glfw.cpp | 3 --- docs/CHANGELOG.txt | 2 ++ 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index d98248acc..d7c208b93 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -126,9 +126,6 @@ #ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Display(), glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) #define GLFW_EXPOSE_NATIVE_X11 #endif -#ifndef GLFW_EXPOSE_NATIVE_WAYLAND -#define GLFW_EXPOSE_NATIVE_WAYLAND -#endif #include #endif #undef Status // X11 headers are leaking this. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ecc881700..a605dbef1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,8 @@ Other Changes: - MultiSelect: added ImGuiMultiSelectFlags_NoSelectOnRightClick to disable default right-click processing, which selects item on mouse down and is designed for context-menus. (#8200, #9015) +- Backends: GLFW: fixed building on Linux platforms where Wayland headers + are not available. (#9024, #8969, #8921, #8920) [@jagot] - Backends: Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] - Backends: WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ From bdb8243602d2b61f253dd88acb6ff0044dc4152b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Oct 2025 13:33:36 +0200 Subject: [PATCH 1420/2359] Backends: SDl3: Fixed Platform_OpenInShellFn() return value. (#9027) --- backends/imgui_impl_sdl3.cpp | 3 ++- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 564131a4d..3ddd4a7f7 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-10-22: Fixed Platform_OpenInShellFn() return value (unused in core). // 2025-09-24: Skip using the SDL_GetGlobalMouseState() state when one of our window is hovered, as the SDL_EVENT_MOUSE_MOTION data is reliable. Fix macOS notch mouse coordinates issue in fullscreen mode + better perf on X11. (#7919, #7786) // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Use SDL_GetWindowDisplayScale() on Mac to output DisplayFrameBufferScale. The function is more reliable during resolution changes e.g. going fullscreen. (#8703, #4414) @@ -505,7 +506,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; - platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url) == 0; }; + platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url); }; // Gamepad handling bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a605dbef1..91a17051c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,8 @@ Other Changes: context-menus. (#8200, #9015) - Backends: GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) [@jagot] +- Backends: SDL3: fixed Platform_OpenInShellFn() return value (the return value + was unused in core but might be used by a direct caller). (#9027) [@achabense] - Backends: Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] - Backends: WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ diff --git a/imgui.h b/imgui.h index c2ea4aa50..4ecca7f78 100644 --- a/imgui.h +++ b/imgui.h @@ -3942,7 +3942,7 @@ struct ImGuiPlatformIO void* Platform_ClipboardUserData; // Optional: Open link/folder/file in OS Shell - // (default to use ShellExecuteW() on Windows, system() on Linux/Mac) + // (default to use ShellExecuteW() on Windows, system() on Linux/Mac. expected to return false on failure, but some platforms may always return true) bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); void* Platform_OpenInShellUserData; From 5870b979a870a7364564df1dd50542b494590a0e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Oct 2025 13:38:45 +0200 Subject: [PATCH 1421/2359] Examples: GLFW+WebGPU: fixed cmakefile for example to use legacy path. (#8381) Amend 71447b94f --- examples/example_glfw_wgpu/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_glfw_wgpu/CMakeLists.txt b/examples/example_glfw_wgpu/CMakeLists.txt index 8e164e488..d21bb0919 100644 --- a/examples/example_glfw_wgpu/CMakeLists.txt +++ b/examples/example_glfw_wgpu/CMakeLists.txt @@ -34,7 +34,7 @@ if(EMSCRIPTEN) set(IMGUI_EMSCRIPTEN_GLFW3 "-sUSE_GLFW=3" CACHE STRING "Use -sUSE_GLFW=3 for GLFW implementation" FORCE) endif() set(LIBRARIES glfw) - add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1) + add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1 -DIMGUI_IMPL_WEBGPU_BACKEND_WGPU) else() # Dawn wgpu desktop set(DAWN_FETCH_DEPENDENCIES ON) From 2a022d997b14ec019cf761ea0c71cdddf6b5029d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Oct 2025 13:41:45 +0200 Subject: [PATCH 1422/2359] Examples: GLFW+WebGPU: removed unnecessary ImGui_ImplWGPU_InvalidateDeviceObjects() call during surface resize. (#8381) + Relayout changelog. --- docs/CHANGELOG.txt | 26 +++++++++++++++----------- examples/example_glfw_wgpu/main.cpp | 4 ---- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 91a17051c..bc6b8f3ae 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,17 +56,21 @@ Other Changes: - MultiSelect: added ImGuiMultiSelectFlags_NoSelectOnRightClick to disable default right-click processing, which selects item on mouse down and is designed for context-menus. (#8200, #9015) -- Backends: GLFW: fixed building on Linux platforms where Wayland headers - are not available. (#9024, #8969, #8921, #8920) [@jagot] -- Backends: SDL3: fixed Platform_OpenInShellFn() return value (the return value - was unused in core but might be used by a direct caller). (#9027) [@achabense] -- Backends: Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to - Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] -- Backends: WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ - '--use-port=emdawnwebgpu' ports. (#8381, #8898) [@brutpitt, @trbabb] - When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN - instead of IMGUI_IMPL_WEBGPU_BACKEND_WGPU, if neither are specified. - (note: examples application were not updated yet) +- Backends: + - GLFW: fixed building on Linux platforms where Wayland headers + are not available. (#9024, #8969, #8921, #8920) [@jagot] + - SDL3: fixed Platform_OpenInShellFn() return value (the return value + was unused in core but might be used by a direct caller). (#9027) [@achabense] + - Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to + Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] + - WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ + '--use-port=emdawnwebgpu' ports. (#8381, #8898) [@brutpitt, @trbabb] + When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN + instead of IMGUI_IMPL_WEBGPU_BACKEND_WGPU, if neither are specified. + (note: examples application were not updated yet) +- Examples: + - GLFW+WebGPU: removed unnecessary ImGui_ImplWGPU_InvalidateDeviceObjects() call + during surface resize. (#8381) ----------------------------------------------------------------------- diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 874734936..88c504007 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -179,11 +179,7 @@ int main(int, char**) int width, height; glfwGetFramebufferSize((GLFWwindow*)window, &width, &height); if (width != wgpu_surface_width || height != wgpu_surface_height) - { - ImGui_ImplWGPU_InvalidateDeviceObjects(); // FIXME-OPT: Why doing this? This seems unnecessary and unoptimal. ResizeSurface(width, height); - ImGui_ImplWGPU_CreateDeviceObjects(); - } // Start the Dear ImGui frame ImGui_ImplWGPU_NewFrame(); From b3dab0a406b80d30101b90cde79a93f3344e9a6f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Oct 2025 13:57:27 +0200 Subject: [PATCH 1423/2359] Examples: DirectX10, DirectX11, DirectX12: comments about fullscreen mode and swapchain setup. (#8979) --- examples/example_sdl2_directx11/main.cpp | 1 + examples/example_sdl3_directx11/main.cpp | 1 + examples/example_win32_directx10/main.cpp | 1 + examples/example_win32_directx11/main.cpp | 1 + examples/example_win32_directx12/main.cpp | 3 ++- 5 files changed, 6 insertions(+), 1 deletion(-) diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index e14085dd3..c5a315af4 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -210,6 +210,7 @@ int main(int, char**) bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain + // This is a basic setup. Optimally could use e.g. DXGI_SWAP_EFFECT_FLIP_DISCARD and handle fullscreen mode differently. See #8979 for suggestions. DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index 39171c8cd..7107a0574 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -205,6 +205,7 @@ int main(int, char**) bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain + // This is a basic setup. Optimally could use e.g. DXGI_SWAP_EFFECT_FLIP_DISCARD and handle fullscreen mode differently. See #8979 for suggestions. DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 6fd10f83d..76c1403b3 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -198,6 +198,7 @@ int main(int, char**) bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain + // This is a basic setup. Optimally could use e.g. DXGI_SWAP_EFFECT_FLIP_DISCARD and handle fullscreen mode differently. See #8979 for suggestions. DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 5b88007a9..fa3c4883e 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -198,6 +198,7 @@ int main(int, char**) bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain + // This is a basic setup. Optimally could use e.g. DXGI_SWAP_EFFECT_FLIP_DISCARD and handle fullscreen mode differently. See #8979 for suggestions. DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index c8578b54c..5a8dc0381 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -312,6 +312,7 @@ int main(int, char**) bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain + // This is a basic setup. Optimally could handle fullscreen mode differently. See #8979 for suggestions. DXGI_SWAP_CHAIN_DESC1 sd; { ZeroMemory(&sd, sizeof(sd)); @@ -525,7 +526,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) DXGI_SWAP_CHAIN_DESC1 desc = {}; g_pSwapChain->GetDesc1(&desc); HRESULT result = g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), desc.Format, desc.Flags); - assert(SUCCEEDED(result) && "Failed to resize swapchain."); + IM_ASSERT(SUCCEEDED(result) && "Failed to resize swapchain."); CreateRenderTarget(); } return 0; From bc5da9b367ef848a31b572209ff71dc74f60acff Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 22 Oct 2025 13:58:51 +0200 Subject: [PATCH 1424/2359] Examples: DirectX10: Amends. (#8979) --- examples/example_win32_directx10/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 76c1403b3..086935099 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -198,7 +198,7 @@ int main(int, char**) bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain - // This is a basic setup. Optimally could use e.g. DXGI_SWAP_EFFECT_FLIP_DISCARD and handle fullscreen mode differently. See #8979 for suggestions. + // This is a basic setup. Optimally could use handle fullscreen mode differently. See #8979 for suggestions. DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; From b8573a7e33d76705a206fa556929b9ecd5326e01 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Oct 2025 13:54:14 +0200 Subject: [PATCH 1425/2359] Groups: fixed an issue reporting IsItemEdited() signal after EndGroup() for some widgets e.g. Checkbox(), Selectable(). (#9028) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 3 ++- imgui.h | 2 +- imgui_internal.h | 1 + 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bc6b8f3ae..932edd3e8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,10 @@ Other Changes: - MultiSelect: added ImGuiMultiSelectFlags_NoSelectOnRightClick to disable default right-click processing, which selects item on mouse down and is designed for context-menus. (#8200, #9015) +- Groups: fixed an issue reporting IsItemEdited() signal after EndGroup() when + triggered by some widgets e.g. Checkbox(), Selectable() and many others, which + cleared ActiveId at the same time as editing. (#9028) + Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited). - Backends: - GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) [@jagot] diff --git a/imgui.cpp b/imgui.cpp index b9845a6f1..66e1c0e2d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11518,6 +11518,7 @@ void ImGui::BeginGroup() group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; group_data.BackupHoveredIdIsAlive = g.HoveredId != 0; group_data.BackupIsSameLine = window->DC.IsSameLine; + group_data.BackupActiveIdHasBeenEditedThisFrame = g.ActiveIdHasBeenEditedThisFrame; group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive; group_data.EmitItem = true; @@ -11582,7 +11583,7 @@ void ImGui::EndGroup() g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; // Forward Edited flag - if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame) + if (g.ActiveIdHasBeenEditedThisFrame && !group_data.BackupActiveIdHasBeenEditedThisFrame) g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited; // Forward Deactivated flag diff --git a/imgui.h b/imgui.h index 4ecca7f78..b58f09430 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.5 WIP" -#define IMGUI_VERSION_NUM 19241 +#define IMGUI_VERSION_NUM 19242 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_internal.h b/imgui_internal.h index 701652e4b..340f1482a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1173,6 +1173,7 @@ struct IMGUI_API ImGuiGroupData ImVec2 BackupCurrLineSize; float BackupCurrLineTextBaseOffset; ImGuiID BackupActiveIdIsAlive; + bool BackupActiveIdHasBeenEditedThisFrame; bool BackupDeactivatedIdIsAlive; bool BackupHoveredIdIsAlive; bool BackupIsSameLine; From e571ccf3f431c224e3c71ae98f8fbad8245ec241 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Oct 2025 18:42:12 +0200 Subject: [PATCH 1426/2359] InputText: removed unnecessary variables. --- imgui_widgets.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4033203da..910c73d36 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5262,10 +5262,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ callback_data.BufTextLen = state->TextLen; callback_data.BufSize = state->BufCapacity; callback_data.BufDirty = false; - - const int utf8_cursor_pos = callback_data.CursorPos = state->Stb->cursor; - const int utf8_selection_start = callback_data.SelectionStart = state->Stb->select_start; - const int utf8_selection_end = callback_data.SelectionEnd = state->Stb->select_end; + callback_data.CursorPos = state->Stb->cursor; + callback_data.SelectionStart = state->Stb->select_start; + callback_data.SelectionEnd = state->Stb->select_end; // Call user code callback(&callback_data); @@ -5276,9 +5275,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(callback_data.BufSize == state->BufCapacity); IM_ASSERT(callback_data.Flags == flags); const bool buf_dirty = callback_data.BufDirty; - if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; } - if (callback_data.SelectionStart != utf8_selection_start || buf_dirty) { state->Stb->select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb->cursor : callback_data.SelectionStart; } - if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb->select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb->select_start : callback_data.SelectionEnd; } + if (buf_dirty || callback_data.CursorPos != state->Stb->cursor) { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; } + if (buf_dirty || callback_data.SelectionStart != state->Stb->select_start) { state->Stb->select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb->cursor : callback_data.SelectionStart; } + if (buf_dirty || callback_data.SelectionEnd != state->Stb->select_end) { state->Stb->select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb->select_start : callback_data.SelectionEnd; } if (buf_dirty) { // Callback may update buffer and thus set buf_dirty even in read-only mode. From 750c5d2a618b39b3e88a5556d72157651c0e5e28 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Oct 2025 18:54:32 +0200 Subject: [PATCH 1427/2359] InputText: do not require anymore that CursorPos be clamped by user code. (#9029) Add clamping outside of callback code + simplify logic. The previous logic checking for difference was because old code e.g. 21d03edcb0 required a ImTextCountCharsFromUtf8() which is not required since #7925. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 11 ++++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 932edd3e8..3b2587547 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: EndTable() was mistakenly restoring a wrong current table. - InputText: avoid continuously overwriting ownership of ImGuiKey_Enter/_KeypadEnter keys in order to allow e.g. external Shortcut override behavior. (#9004) +- InputText: when using a callback to reduce/manipulate the value of BufTextLen, + we do not require anymore that CursorPos be clamped by user code. (#9029) - InputTextMultiline: fixed a crash when using ImGuiInputTextFlags_WordWrap and resizing the parent window while keeping the multi-line field active (which is most typically achieved when resizing programmatically or via a docking layout diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 910c73d36..97fb208ee 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5274,11 +5274,12 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(callback_data.Buf == callback_buf); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == state->BufCapacity); IM_ASSERT(callback_data.Flags == flags); - const bool buf_dirty = callback_data.BufDirty; - if (buf_dirty || callback_data.CursorPos != state->Stb->cursor) { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; } - if (buf_dirty || callback_data.SelectionStart != state->Stb->select_start) { state->Stb->select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb->cursor : callback_data.SelectionStart; } - if (buf_dirty || callback_data.SelectionEnd != state->Stb->select_end) { state->Stb->select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb->select_start : callback_data.SelectionEnd; } - if (buf_dirty) + if (callback_data.BufDirty || callback_data.CursorPos != state->Stb->cursor) + state->CursorFollow = true; + state->Stb->cursor = ImClamp(callback_data.CursorPos, 0, callback_data.BufTextLen); + state->Stb->select_start = ImClamp(callback_data.SelectionStart, 0, callback_data.BufTextLen); + state->Stb->select_end = ImClamp(callback_data.SelectionEnd, 0, callback_data.BufTextLen); + if (callback_data.BufDirty) { // Callback may update buffer and thus set buf_dirty even in read-only mode. IM_ASSERT(callback_data.BufTextLen == (int)ImStrlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! From 6add99f8d22b7a3a3d79bc9d3a8bac3f07d4b4f3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Oct 2025 20:00:57 +0200 Subject: [PATCH 1428/2359] Examples: SDL3+Vulkan: Fixed call to ImGui_ImplVulkanH_CreateOrResizeWindow() during resize. (#9030) Surprisingly it still worked because ImGui_ImplVulkanH_CreateWindowSwapChain() pulls from `cap.currentExtent` when available. --- examples/example_sdl3_vulkan/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 6f67e990d..51de52db0 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -479,7 +479,7 @@ int main(int, char**) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_height, fb_height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, g_SwapChainImageUsage); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } From b7e45b3a48a4a447e3e64beef9e775a6a8c8c6eb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Oct 2025 20:16:44 +0200 Subject: [PATCH 1429/2359] InputText: rework STB_TEXTEDIT_INSERTCHARS() signature to allow partial insertion (unused). (#9029) To be submitted as a PR to nothings/stb. --- imgui_widgets.cpp | 8 ++++---- imstb_textedit.h | 20 +++++++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 97fb208ee..c83158360 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4142,21 +4142,21 @@ static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n) obj->TextLen -= n; } -static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len) +static int STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len) { const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0; const int text_len = obj->TextLen; IM_ASSERT(pos <= text_len); if (!is_resizable && (new_text_len + obj->TextLen + 1 > obj->BufCapacity)) - return false; + return 0; // Grow internal buffer if needed IM_ASSERT(obj->TextSrc == obj->TextA.Data); if (new_text_len + text_len + 1 > obj->TextA.Size) { if (!is_resizable) - return false; + return 0; obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1); obj->TextSrc = obj->TextA.Data; } @@ -4170,7 +4170,7 @@ static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ch obj->TextLen += new_text_len; obj->TextA[obj->TextLen] = '\0'; - return true; + return new_text_len; } // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) diff --git a/imstb_textedit.h b/imstb_textedit.h index c41078c8a..583508f0b 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -5,7 +5,8 @@ // - 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) -// Grep for [DEAR IMGUI] to find the changes. +// - 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.14 - public domain - Sean Barrett @@ -39,6 +40,7 @@ // // VERSION HISTORY // +// !!!! (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 @@ -147,7 +149,8 @@ // as manually wordwrapping for end-of-line positioning // // STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i -// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) +// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) try to insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) +// returns number of characters actually inserted. [DEAR IMGUI] // // STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key // @@ -775,7 +778,8 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS stb_textedit_clamp(str, state); stb_textedit_delete_selection(str,state); // try to insert the characters - if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { + len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len); + if (len) { stb_text_makeundo_insert(state, state->cursor, len); state->cursor += len; state->has_preferred_x = 0; @@ -800,13 +804,15 @@ static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* sta if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { stb_text_makeundo_replace(str, state, state->cursor, 1, 1); STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); - if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) { + text_len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len); + if (text_len) { state->cursor += text_len; state->has_preferred_x = 0; } } else { stb_textedit_delete_selection(str, state); // implicitly clamps - if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) { + text_len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len); + if (text_len) { stb_text_makeundo_insert(state, state->cursor, text_len); state->cursor += text_len; state->has_preferred_x = 0; @@ -1352,7 +1358,7 @@ static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) // check type of recorded action: if (u.insert_length) { // easy case: was a deletion, so we need to insert n characters - STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); + u.insert_length = STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); s->undo_char_point -= u.insert_length; } @@ -1403,7 +1409,7 @@ static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) if (r.insert_length) { // easy case: need to insert n characters - STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); + r.insert_length = STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); s->redo_char_point += r.insert_length; } From e6125361f988d6ed94a2e1593ab929e2b8ce1d83 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 23 Oct 2025 20:53:29 +0200 Subject: [PATCH 1430/2359] InputText: paste does a truncate when not fitting instead of ignoring it. (#9029) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 30 +++++++++++++++++++----------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3b2587547..4b7cd65c6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Other Changes: result in temporarily incorrect state, which would lead to bugs to side effects in various locations, e.g. GetContentRegionAvail() calls or using clipper. (#9005) EndTable() was mistakenly restoring a wrong current table. +- InputText: when buffer is not resizable, trying to paste contents that + cannot fit will now truncate text instead of ignoring the paste. (#9029) - InputText: avoid continuously overwriting ownership of ImGuiKey_Enter/_KeypadEnter keys in order to allow e.g. external Shortcut override behavior. (#9004) - InputText: when using a callback to reduce/manipulate the value of BufTextLen, diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c83158360..e2a8e9580 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4148,15 +4148,17 @@ static int STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const cha const int text_len = obj->TextLen; IM_ASSERT(pos <= text_len); - if (!is_resizable && (new_text_len + obj->TextLen + 1 > obj->BufCapacity)) + // We support partial insertion (with a mod in stb_textedit.h) + const int avail = obj->BufCapacity - 1 - obj->TextLen; + if (!is_resizable && new_text_len > avail) + new_text_len = avail; // 0 + if (new_text_len == 0) return 0; // Grow internal buffer if needed IM_ASSERT(obj->TextSrc == obj->TextA.Data); - if (new_text_len + text_len + 1 > obj->TextA.Size) + if (text_len + new_text_len + 1 > obj->TextA.Size && is_resizable) { - if (!is_resizable) - return 0; obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1); obj->TextSrc = obj->TextA.Data; } @@ -4205,7 +4207,8 @@ static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* st state->cursor = state->select_start = state->select_end = 0; if (text_len <= 0) return; - if (ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len)) + int text_len_inserted = ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len); + if (text_len_inserted > 0) { state->cursor = state->select_start = state->select_end = text_len; state->has_preferred_x = 0; @@ -4300,15 +4303,20 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons ImGuiContext& g = *Ctx; ImGuiInputTextState* obj = &g.InputTextState; 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); + + // 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 = avail; // 0 + if (new_text_len == 0) + return; // Grow internal buffer if needed - const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; - const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text); - if (new_text_len + BufTextLen + 1 > obj->TextA.Size && (Flags & ImGuiInputTextFlags_ReadOnly) == 0) + if (new_text_len + BufTextLen + 1 > obj->TextA.Size && is_resizable && !is_readonly) { - if (!is_resizable) - return; - IM_ASSERT(Buf == obj->TextA.Data); int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; obj->TextA.resize(new_buf_size + 1); From c72d0b2cbbbc02423e30d3095ca6ce6684ca7284 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 29 Sep 2025 14:57:03 +0200 Subject: [PATCH 1431/2359] Backends: Vulkan: SwapChainImageUsage assume VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT which is added automatically. (#8946, #8110, #8111, #8686) Merge bad3c14 which was accidentally only pushed to docking. No important side effect. --- backends/imgui_impl_vulkan.cpp | 2 +- examples/example_glfw_vulkan/main.cpp | 5 ++--- examples/example_sdl2_vulkan/main.cpp | 5 ++--- examples/example_sdl3_vulkan/main.cpp | 5 ++--- examples/example_win32_vulkan/main.cpp | 5 ++--- 5 files changed, 9 insertions(+), 13 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index baffb7e51..c62510829 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1634,7 +1634,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V info.imageFormat = wd->SurfaceFormat.format; info.imageColorSpace = wd->SurfaceFormat.colorSpace; info.imageArrayLayers = 1; - info.imageUsage = (image_usage != 0) ? image_usage : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | image_usage; info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // Assume that graphics family == present family info.preTransform = (cap.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR : cap.currentTransform; info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index d9cbfb787..ef307a0b3 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -54,7 +54,6 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; -static VkImageUsageFlags g_SwapChainImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static void glfw_error_callback(int error, const char* description) { @@ -240,7 +239,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, 0); } static void CleanupVulkan() @@ -457,7 +456,7 @@ int main(int, char**) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, 0); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index fd845373d..7380edabd 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -49,7 +49,6 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; -static VkImageUsageFlags g_SwapChainImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static void check_vk_result(VkResult err) { @@ -231,7 +230,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, 0); } static void CleanupVulkan() @@ -477,7 +476,7 @@ int main(int, char**) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, 0); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 51de52db0..37e60de38 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -51,7 +51,6 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; -static VkImageUsageFlags g_SwapChainImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static void check_vk_result(VkResult err) { @@ -233,7 +232,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, 0); } static void CleanupVulkan() @@ -479,7 +478,7 @@ int main(int, char**) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, 0); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index cdf4a247e..64a8f9f1d 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -47,7 +47,6 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; -static VkImageUsageFlags g_SwapChainImageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static void check_vk_result(VkResult err) { @@ -229,7 +228,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount, 0); } static void CleanupVulkan() @@ -550,7 +549,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) if (fb_width > 0 && fb_height > 0 && (g_SwapChainRebuild || g_MainWindowData.Width != fb_width || g_MainWindowData.Height != fb_height)) { ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, g_SwapChainImageUsage); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, fb_width, fb_height, g_MinImageCount, 0); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } From a1632c6116d3d5f0cd1eccb8a0b49e61acc5398c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Oct 2025 16:42:21 +0200 Subject: [PATCH 1432/2359] InputText, Demo: amend comments to direct more users to the std::string version. https://www.youtube.com/watch?v=pLwvNdpTpjs wasted a solid hour before finding this. Crazy that people are using AI instead of actually _reading_ comments, demo and headers. (The information appeared multiple times on their screen) --- imgui.h | 2 +- imgui_demo.cpp | 11 +++++++---- imgui_widgets.cpp | 5 ++--- misc/cpp/imgui_stdlib.cpp | 12 ++++++++++++ misc/cpp/imgui_stdlib.h | 12 ++++++++++++ 5 files changed, 34 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index b58f09430..e7920e64f 100644 --- a/imgui.h +++ b/imgui.h @@ -705,7 +705,7 @@ namespace ImGui 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); // Widgets: Input with Keyboard - // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. + // - 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); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8f0e393a1..3c3900b43 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -887,8 +887,9 @@ static void DemoWindowWidgetsBasic() ImGui::SeparatorText("Inputs"); { - // To wire InputText() with std::string or any other custom string type, - // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. + // If you want to use InputText() with std::string or any custom dynamic string type: + // - For std::string: use the wrapper in misc/cpp/imgui_stdlib.h/.cpp + // - Otherwise, see the 'Dear ImGui Demo->Widgets->Text Input->Resize Callback' for using ImGuiInputTextFlags_CallbackResize. IMGUI_DEMO_MARKER("Widgets/Basic/InputText"); static char str0[128] = "Hello, world!"; ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); @@ -3696,8 +3697,10 @@ static void DemoWindowWidgetsTextInput() IMGUI_DEMO_MARKER("Widgets/Text Input/Multi-line Text Input"); if (ImGui::TreeNode("Multi-line Text Input")) { - // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize - // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings. + // WE ARE USING A FIXED-SIZE BUFFER FOR SIMPLICITY HERE. + // If you want to use InputText() with std::string or any custom dynamic string type: + // - For std::string: use the wrapper in misc/cpp/imgui_stdlib.h/.cpp + // - Otherwise, see the 'Dear ImGui Demo->Widgets->Text Input->Resize Callback' for using ImGuiInputTextFlags_CallbackResize. static char text[1024 * 16] = "/*\n" " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e2a8e9580..13d4b3be4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3920,6 +3920,7 @@ namespace ImStb #include "imstb_textedit.h" } +// 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) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() @@ -4620,9 +4621,7 @@ static ImVec2 InputTextLineIndexGetPosOffset(ImGuiContext& g, ImGuiInputTextStat // This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match // 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 ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h -// (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are -// doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188) +// - 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) { ImGuiWindow* window = GetCurrentWindow(); diff --git a/misc/cpp/imgui_stdlib.cpp b/misc/cpp/imgui_stdlib.cpp index c04d487cc..7c463ca6b 100644 --- a/misc/cpp/imgui_stdlib.cpp +++ b/misc/cpp/imgui_stdlib.cpp @@ -1,9 +1,21 @@ // dear imgui: wrappers for C++ standard library (STL) types (std::string, etc.) + // This is also an example of how you may wrap your own similar types. +// TL;DR; this is using the ImGuiInputTextFlags_CallbackResize facility, +// which also demonstrated in 'Dear ImGui Demo->Widgets->Text Input->Resize Callback'. // Changelog: // - v0.10: Initial version. Added InputText() / InputTextMultiline() calls with std::string +// Usage: +// { +// #include "misc/cpp/imgui_stdlib.h" +// #include "misc/cpp/imgui_stdlib.cpp" // <-- If you want to include implementation without messing with your project/build. +// [...] +// std::string my_string; +// ImGui::InputText("my string", &my_string); +// } + // See more C++ related extension (fmt, RAII, syntaxis sugar) on Wiki: // https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness diff --git a/misc/cpp/imgui_stdlib.h b/misc/cpp/imgui_stdlib.h index 697fc34ad..cf4b528bd 100644 --- a/misc/cpp/imgui_stdlib.h +++ b/misc/cpp/imgui_stdlib.h @@ -1,9 +1,21 @@ // dear imgui: wrappers for C++ standard library (STL) types (std::string, etc.) + // This is also an example of how you may wrap your own similar types. +// TL;DR; this is using the ImGuiInputTextFlags_CallbackResize facility, +// which also demonstrated in 'Dear ImGui Demo->Widgets->Text Input->Resize Callback'. // Changelog: // - v0.10: Initial version. Added InputText() / InputTextMultiline() calls with std::string +// Usage: +// { +// #include "misc/cpp/imgui_stdlib.h" +// #include "misc/cpp/imgui_stdlib.cpp" // <-- If you want to include implementation without messing with your project/build. +// [...] +// std::string my_string; +// ImGui::InputText("my string", &my_string); +// } + // See more C++ related extension (fmt, RAII, syntaxis sugar) on Wiki: // https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness From 8019d3954531166d2f8eefbe2d02a0663a9ba322 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Oct 2025 19:01:57 +0100 Subject: [PATCH 1433/2359] Shuffle a few internal context fields to reduce padding. --- imgui.cpp | 23 ++++++++++++----------- imgui_internal.h | 26 +++++++++++++------------- imgui_widgets.cpp | 4 ++-- 3 files changed, 27 insertions(+), 26 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 66e1c0e2d..2fe80c828 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4043,6 +4043,13 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) InputTextState.Ctx = this; Initialized = false; + WithinFrameScope = WithinFrameScopeWithImplicitWindow = false; + TestEngineHookItems = false; + FrameCount = 0; + FrameCountEnded = FrameCountRendered = -1; + Time = 0.0f; + memset(ContextName, 0, sizeof(ContextName)); + Font = NULL; FontBaked = NULL; FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f; @@ -4050,15 +4057,8 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); if (shared_font_atlas == NULL) IO.Fonts->OwnerContext = this; - Time = 0.0f; - FrameCount = 0; - FrameCountEnded = FrameCountRendered = -1; WithinEndChildID = 0; - WithinFrameScope = WithinFrameScopeWithImplicitWindow = false; - GcCompactAll = false; - TestEngineHookItems = false; TestEngine = NULL; - memset(ContextName, 0, sizeof(ContextName)); InputEventsNextMouseSource = ImGuiMouseSource_Mouse; InputEventsNextEventId = 1; @@ -4093,10 +4093,10 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) ActiveIdHasBeenEditedThisFrame = false; ActiveIdFromShortcut = false; ActiveIdClickOffset = ImVec2(-1, -1); - ActiveIdWindow = NULL; ActiveIdSource = ImGuiInputSource_None; - ActiveIdDisabledId = 0; + ActiveIdWindow = NULL; ActiveIdMouseButton = -1; + ActiveIdDisabledId = 0; ActiveIdPreviousFrame = 0; memset(&DeactivatedItemData, 0, sizeof(DeactivatedItemData)); memset(&ActiveIdValueOnActivation, 0, sizeof(ActiveIdValueOnActivation)); @@ -4111,6 +4111,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) CurrentFocusScopeId = 0; CurrentItemFlags = ImGuiItemFlags_None; DebugShowGroupRects = false; + GcCompactAll = false; NavCursorVisible = false; NavHighlightItemUnderNav = false; @@ -4219,12 +4220,12 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) memset(LocalizationTable, 0, sizeof(LocalizationTable)); LogEnabled = false; + LogLineFirstItem = false; LogFlags = ImGuiLogFlags_None; LogWindow = NULL; LogNextPrefix = LogNextSuffix = NULL; LogFile = NULL; LogLinePosY = FLT_MAX; - LogLineFirstItem = false; LogDepthRef = 0; LogDepthToExpand = LogDepthToExpandDefault = 2; @@ -4457,8 +4458,8 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL MoveId = GetID("#MOVE"); ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); - AutoFitFramesX = AutoFitFramesY = -1; AutoPosLastDirection = ImGuiDir_None; + AutoFitFramesX = AutoFitFramesY = -1; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = 0; SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; diff --git a/imgui_internal.h b/imgui_internal.h index 340f1482a..3cfd42cb4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2164,6 +2164,14 @@ struct ImGuiContextHook struct ImGuiContext { bool Initialized; + bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() + bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed + bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() + int FrameCount; + int FrameCountEnded; + int FrameCountRendered; + double Time; + char ContextName[16]; // Storage for a context name (to facilitate debugging multi-context setups) ImGuiIO IO; ImGuiPlatformIO PlatformIO; ImGuiStyle Style; @@ -2176,17 +2184,8 @@ struct ImGuiContext float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale ImDrawListSharedData DrawListSharedData; - double Time; - int FrameCount; - int FrameCountEnded; - int FrameCountRendered; ImGuiID WithinEndChildID; // Set within EndChild() - bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() - bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed - bool GcCompactAll; // Request full GC - bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() void* TestEngine; // Test engine user data - char ContextName[16]; // Storage for a context name (to facilitate debugging multi-context setups) // Inputs ImVector InputEventsQueue; // Input events which will be trickled/written into IO structure. @@ -2237,11 +2236,11 @@ struct ImGuiContext bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. bool ActiveIdHasBeenEditedThisFrame; bool ActiveIdFromShortcut; + ImS8 ActiveIdMouseButton; ImGuiID ActiveIdDisabledId; // When clicking a disabled item we set ActiveId=window->MoveId to avoid interference with widget code. Actual item ID is stored here. - int ActiveIdMouseButton : 8; ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) - ImGuiWindow* ActiveIdWindow; ImGuiInputSource ActiveIdSource; // Activating source: ImGuiInputSource_Mouse OR ImGuiInputSource_Keyboard OR ImGuiInputSource_Gamepad + ImGuiWindow* ActiveIdWindow; ImGuiID ActiveIdPreviousFrame; ImGuiDeactivatedItemData DeactivatedItemData; ImGuiDataTypeStorage ActiveIdValueOnActivation; // Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX. @@ -2271,6 +2270,7 @@ struct ImGuiContext ImGuiLastItemData LastItemData; // Storage for last submitted item (setup by ItemAdd) ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions bool DebugShowGroupRects; + bool GcCompactAll; // Request full GC // Shared stacks ImGuiCol DebugFlashStyleColorIdx; // (Keep close to ColorStack to share cache line) @@ -2481,6 +2481,7 @@ struct ImGuiContext // Capture/Logging bool LogEnabled; // Currently capturing + bool LogLineFirstItem; ImGuiLogFlags LogFlags; // Capture flags/type ImGuiWindow* LogWindow; ImFileHandle LogFile; // If != NULL log to stdout/ file @@ -2488,7 +2489,6 @@ struct ImGuiContext const char* LogNextPrefix; // See comment in LogSetNextTextDecoration(): doesn't copy underlying data, use carefully! const char* LogNextSuffix; float LogLinePosY; - bool LogLineFirstItem; int LogDepthRef; int LogDepthToExpand; int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. @@ -2655,9 +2655,9 @@ struct IMGUI_API ImGuiWindow short BeginOrderWithinParent; // Begin() order within immediate parent window, if we are a child window. Otherwise 0. short BeginOrderWithinContext; // Begin() order within entire imgui context. This is mostly used for debugging submission order related issues. short FocusOrder; // Order within WindowsFocusOrder[], altered when windows are focused. + ImGuiDir AutoPosLastDirection; ImS8 AutoFitFramesX, AutoFitFramesY; bool AutoFitOnlyGrows; - ImGuiDir AutoPosLastDirection; ImS8 HiddenFramesCanSkipItems; // Hide the window for N frames ImS8 HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size ImS8 HiddenFramesForRenderOnly; // Hide the window until frame N at Render() time only diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 13d4b3be4..f46940bda 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -619,7 +619,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere)) { SetActiveID(id, window); - g.ActiveIdMouseButton = mouse_button_clicked; + g.ActiveIdMouseButton = (ImS8)mouse_button_clicked; if (!(flags & ImGuiButtonFlags_NoNavFocus)) { SetFocusID(id, window); @@ -637,7 +637,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool ClearActiveID(); else SetActiveID(id, window); // Hold on ID - g.ActiveIdMouseButton = mouse_button_clicked; + g.ActiveIdMouseButton = (ImS8)mouse_button_clicked; if (!(flags & ImGuiButtonFlags_NoNavFocus)) { SetFocusID(id, window); From 245e12cca7a30c5c109ee1de8eca168b81be0a28 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 24 Oct 2025 18:44:33 +0200 Subject: [PATCH 1434/2359] Internals: tweak UpdateMouseMovingWindowEndFrame(). --- imgui.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2fe80c828..63ceb9311 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5198,26 +5198,28 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (g.NavWindow && g.NavWindow->Appearing) return; + ImGuiWindow* hovered_window = g.HoveredWindow; + // Click on empty space to focus window and start moving // (after we're done with all our widgets) if (g.IO.MouseClicked[0]) { // Handle the edge case of a popup being closed while clicking in its empty space. // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. - ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; - const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel); + ImGuiWindow* hovered_root = hovered_window ? hovered_window->RootWindow : NULL; + const bool is_closed_popup = hovered_root && (hovered_root->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(hovered_root->PopupId, ImGuiPopupFlags_AnyPopupLevel); - if (root_window != NULL && !is_closed_popup) + if (hovered_window != NULL && !is_closed_popup) { - StartMouseMovingWindow(g.HoveredWindow); //-V595 + StartMouseMovingWindow(hovered_window); //-V595 - // FIXME: In principal we might be able to call StopMouseMovingWindow() below. + // FIXME: In principle we might be able to call StopMouseMovingWindow() below. // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId. // Cancel moving if clicked outside of title bar if (g.IO.ConfigWindowsMoveFromTitleBarOnly) - if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) - if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) + if (!(hovered_root->Flags & ImGuiWindowFlags_NoTitleBar)) + if (!hovered_root->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; // Cancel moving if clicked over an item which was disabled or inhibited by popups @@ -5228,7 +5230,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() g.ActiveIdDisabledId = g.HoveredId; } } - else if (root_window == NULL && g.NavWindow != NULL) + else if (hovered_window == NULL && g.NavWindow != NULL) { // Clicking on void disable focus FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal); @@ -5243,8 +5245,8 @@ void ImGui::UpdateMouseMovingWindowEndFrame() // Find the top-most window between HoveredWindow and the top-most Modal Window. // This is where we can trim the popup stack. ImGuiWindow* modal = GetTopMostPopupModal(); - bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal)); - ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true); + bool hovered_window_above_modal = hovered_window && (modal == NULL || IsWindowAbove(hovered_window, modal)); + ClosePopupsOverWindow(hovered_window_above_modal ? hovered_window : modal, true); } } From 40f9e4e8e2ff3204021182726a8c0f18db68e213 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Oct 2025 18:32:35 +0100 Subject: [PATCH 1435/2359] Windows: store BgClickFlags which allows the equivalent of io.ConfigWindowsMoveFromTitleBarOnly to be overridden on a per window basis. (#899, #3071, #5044, + #3379) io.ConfigWindowsMoveFromTitleBarOnly now sets initial value for BgClickFlags. Using e.g. ImGui::GetCurrentWindow()->BgClickFlags &= ~ImGuiWindowBgClickFlags_Move; allow per-window override. This will be extended for supporting scrolling options for #3379. As a minor side effect: the effect of enabling io.ConfigWindowsMoveFromTitleBarOnly now happens one frame later ('window_modal_bounds_exceeding_work_area" test accidentally broke in some situations because of that) --- imgui.cpp | 12 ++++++++---- imgui_internal.h | 8 ++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 63ceb9311..14e90ada1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5217,7 +5217,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId. // Cancel moving if clicked outside of title bar - if (g.IO.ConfigWindowsMoveFromTitleBarOnly) + if ((hovered_window->BgClickFlags & ImGuiWindowBgClickFlags_Move) == 0) // set by io.ConfigWindowsMoveFromTitleBarOnly if (!(hovered_root->Flags & ImGuiWindowFlags_NoTitleBar)) if (!hovered_root->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; @@ -6768,7 +6768,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si const float grip_hover_outer_size = g.WindowsBorderHoverPadding; ImRect clamp_rect = visibility_rect; - const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar); + const bool window_move_from_title_bar = !(window->BgClickFlags & ImGuiWindowBgClickFlags_Move) && !(window->Flags & ImGuiWindowFlags_NoTitleBar); if (window_move_from_title_bar) clamp_rect.Min.y -= window->TitleBarHeight; @@ -6957,9 +6957,8 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect) { - ImGuiContext& g = *GImGui; ImVec2 size_for_clamping = window->Size; - if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + if (!(window->BgClickFlags & ImGuiWindowBgClickFlags_Move) && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) size_for_clamping.y = window->TitleBarHeight; window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); } @@ -7928,6 +7927,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (flags & ImGuiWindowFlags_Tooltip) g.TooltipPreviousWindow = window; + // Set default BgClickFlags + // This is set at the end of this function, so UpdateManualResize()/ClampWindowPos() may use last-frame value if overriden by user code. + // FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button. + window->BgClickFlags = g.IO.ConfigWindowsMoveFromTitleBarOnly ? ImGuiWindowBgClickFlags_None : ImGuiWindowBgClickFlags_Move; + // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). // This is useful to allow creating context menus on title bar only, etc. window->DC.WindowItemStatusFlags = ImGuiItemStatusFlags_None; diff --git a/imgui_internal.h b/imgui_internal.h index 3cfd42cb4..c3c783efa 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -209,6 +209,7 @@ typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // F typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() typedef int ImGuiTypingSelectFlags; // -> enum ImGuiTypingSelectFlags_ // Flags: for GetTypingSelectRequest() +typedef int ImGuiWindowBgClickFlags; // -> enum ImGuiWindowBgClickFlags_ // Flags: for overriding behavior of clicking on window background/void. typedef int ImGuiWindowRefreshFlags; // -> enum ImGuiWindowRefreshFlags_ // Flags: for SetNextWindowRefreshPolicy() // Table column indexing @@ -1283,6 +1284,12 @@ enum ImGuiWindowRefreshFlags_ // Refresh policy/frequency, Load Balancing etc. }; +enum ImGuiWindowBgClickFlags_ +{ + ImGuiWindowBgClickFlags_None = 0, + ImGuiWindowBgClickFlags_Move = 1 << 0, // Click on bg/void + drag to move window. Cleared by default when using io.ConfigWindowsMoveFromTitleBarOnly. +}; + enum ImGuiNextWindowDataFlags_ { ImGuiNextWindowDataFlags_None = 0, @@ -2662,6 +2669,7 @@ struct IMGUI_API ImGuiWindow ImS8 HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size ImS8 HiddenFramesForRenderOnly; // Hide the window until frame N at Render() time only ImS8 DisableInputsFrames; // Disable window interactions for N frames + ImGuiWindowBgClickFlags BgClickFlags : 8; // Configure behavior of click+dragging on window bg/void or over items. Default sets by io.ConfigWindowsMoveFromTitleBarOnly. If you use this please report in #3379. ImGuiCond SetWindowPosAllowFlags : 8; // store acceptable condition flags for SetNextWindowPos() use. ImGuiCond SetWindowSizeAllowFlags : 8; // store acceptable condition flags for SetNextWindowSize() use. ImGuiCond SetWindowCollapsedAllowFlags : 8; // store acceptable condition flags for SetNextWindowCollapsed() use. From 2a229c8cb869556ecd78199838cae59e6a0ecf57 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Oct 2025 14:21:43 +0100 Subject: [PATCH 1436/2359] Examples: SDL3+OpenGL3: fixed Emscripten makefile + ignore list. Can't get this to run however. --- .gitignore | 1 + examples/example_sdl3_opengl3/Makefile.emscripten | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index a3faf78bb..065867b82 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,7 @@ examples/example_glfw_opengl3/web/* examples/example_glfw_wgpu/web/* examples/example_glfw_wgpu/external/* examples/example_sdl2_opengl3/web/* +examples/example_sdl3_opengl3/web/* ## JetBrains IDE artifacts .idea diff --git a/examples/example_sdl3_opengl3/Makefile.emscripten b/examples/example_sdl3_opengl3/Makefile.emscripten index 57247ff21..ce873ed1a 100644 --- a/examples/example_sdl3_opengl3/Makefile.emscripten +++ b/examples/example_sdl3_opengl3/Makefile.emscripten @@ -36,7 +36,7 @@ EMS = ##--------------------------------------------------------------------- # ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) -EMS += -s USE_SDL=2 +EMS += -s USE_SDL=3 EMS += -s DISABLE_EXCEPTION_CATCHING=1 LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1 From 2c54b15a5fab73997b794c7c7c154a749004a0b9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Oct 2025 15:03:55 +0100 Subject: [PATCH 1437/2359] Update ignore list. --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 065867b82..89b77d910 100644 --- a/.gitignore +++ b/.gitignore @@ -46,7 +46,9 @@ examples/example_glfw_opengl3/web/* examples/example_glfw_wgpu/web/* examples/example_glfw_wgpu/external/* examples/example_sdl2_opengl3/web/* +examples/example_sdl2_wgpu/web/* examples/example_sdl3_opengl3/web/* +examples/example_sdl3_wgpu/web/* ## JetBrains IDE artifacts .idea From 0ba9fedf1ae8c1ff7ae6197179159d8b3a0dc4ba Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Oct 2025 16:29:47 +0100 Subject: [PATCH 1438/2359] Win32: Revert 1.92.4 change of comparing dwPacketNumber. (#8556) --- backends/imgui_impl_win32.cpp | 5 +---- docs/CHANGELOG.txt | 3 +++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index a8b9ff8ee..dc7e66f02 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-10-19: Inputs: Revert previous change to allow for io.ClearInputKeys() on focus-out not losing gamepad state. // 2025-09-23: Inputs: Minor optimization not submitting gamepad input if packet number has not changed. // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-04-30: Inputs: Fixed an issue where externally losing mouse capture (due to e.g. focus loss) would fail to claim it again the next subsequent click. (#8594) @@ -125,7 +126,6 @@ struct ImGui_ImplWin32_Data HMODULE XInputDLL; PFN_XInputGetCapabilities XInputGetCapabilities; PFN_XInputGetState XInputGetState; - DWORD XInputPacketNumber; #endif ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); } @@ -357,9 +357,6 @@ static void ImGui_ImplWin32_UpdateGamepads(ImGuiIO& io) if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS) return; io.BackendFlags |= ImGuiBackendFlags_HasGamepad; - if (bd->XInputPacketNumber != 0 && bd->XInputPacketNumber == xinput_state.dwPacketNumber) - return; - bd->XInputPacketNumber = xinput_state.dwPacketNumber; #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) #define MAP_BUTTON(KEY_NO, BUTTON_ENUM) { io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4b7cd65c6..db3c7e413 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,9 @@ Other Changes: When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN instead of IMGUI_IMPL_WEBGPU_BACKEND_WGPU, if neither are specified. (note: examples application were not updated yet) + - Win32: Revert 1.92.4 change of comparing dwPacketNumber, which prevents + refreshing accurate gamepad info after focus-out + io.ClearInputsKey(). (#8556) + - Examples: - GLFW+WebGPU: removed unnecessary ImGui_ImplWGPU_InvalidateDeviceObjects() call during surface resize. (#8381) From 7c483a0ebabc8c691083b7d6264d857ecfb67e2e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Oct 2025 16:39:37 +0100 Subject: [PATCH 1439/2359] Add indentation to ButtonBehavior() - no logic change. --- docs/CHANGELOG.txt | 2 +- imgui_widgets.cpp | 50 ++++++++++++++++++++++++---------------------- 2 files changed, 27 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index db3c7e413..a38dbcfbc 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,7 +77,7 @@ Other Changes: instead of IMGUI_IMPL_WEBGPU_BACKEND_WGPU, if neither are specified. (note: examples application were not updated yet) - Win32: Revert 1.92.4 change of comparing dwPacketNumber, which prevents - refreshing accurate gamepad info after focus-out + io.ClearInputsKey(). (#8556) + refreshing accurate gamepad info after focus-out + io.ClearInputKeys(). (#8556) - Examples: - GLFW+WebGPU: removed unnecessary ImGui_ImplWGPU_InvalidateDeviceObjects() call diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f46940bda..82d21da32 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -675,32 +675,34 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool // Keyboard/Gamepad navigation handling // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse. - if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav) - if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus)) - hovered = true; - if (g.NavActivateDownId == id) { - bool nav_activated_by_code = (g.NavActivateId == id); - bool nav_activated_by_inputs = (g.NavActivatePressedId == id); - if (!nav_activated_by_inputs && (item_flags & ImGuiItemFlags_ButtonRepeat)) + if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav) + if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus)) + hovered = true; + if (g.NavActivateDownId == id) { - // Avoid pressing multiple keys from triggering excessive amount of repeat events - const ImGuiKeyData* key1 = GetKeyData(ImGuiKey_Space); - const ImGuiKeyData* key2 = GetKeyData(ImGuiKey_Enter); - const ImGuiKeyData* key3 = GetKeyData(ImGuiKey_NavGamepadActivate); - const float t1 = ImMax(ImMax(key1->DownDuration, key2->DownDuration), key3->DownDuration); - nav_activated_by_inputs = CalcTypematicRepeatAmount(t1 - g.IO.DeltaTime, t1, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0; - } - if (nav_activated_by_code || nav_activated_by_inputs) - { - // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button. - pressed = true; - SetActiveID(id, window); - g.ActiveIdSource = g.NavInputSource; - if (!(flags & ImGuiButtonFlags_NoNavFocus) && !(g.NavActivateFlags & ImGuiActivateFlags_FromShortcut)) - SetFocusID(id, window); - if (g.NavActivateFlags & ImGuiActivateFlags_FromShortcut) - g.ActiveIdFromShortcut = true; + bool nav_activated_by_code = (g.NavActivateId == id); + bool nav_activated_by_inputs = (g.NavActivatePressedId == id); + if (!nav_activated_by_inputs && (item_flags & ImGuiItemFlags_ButtonRepeat)) + { + // Avoid pressing multiple keys from triggering excessive amount of repeat events + const ImGuiKeyData* key1 = GetKeyData(ImGuiKey_Space); + const ImGuiKeyData* key2 = GetKeyData(ImGuiKey_Enter); + const ImGuiKeyData* key3 = GetKeyData(ImGuiKey_NavGamepadActivate); + const float t1 = ImMax(ImMax(key1->DownDuration, key2->DownDuration), key3->DownDuration); + nav_activated_by_inputs = CalcTypematicRepeatAmount(t1 - g.IO.DeltaTime, t1, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0; + } + if (nav_activated_by_code || nav_activated_by_inputs) + { + // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button. + pressed = true; + SetActiveID(id, window); + g.ActiveIdSource = g.NavInputSource; + if (!(flags & ImGuiButtonFlags_NoNavFocus) && !(g.NavActivateFlags & ImGuiActivateFlags_FromShortcut)) + SetFocusID(id, window); + if (g.NavActivateFlags & ImGuiActivateFlags_FromShortcut) + g.ActiveIdFromShortcut = true; + } } } From 9753c741b98b948941115a972a31d1c45b195457 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Oct 2025 16:43:27 +0100 Subject: [PATCH 1440/2359] Disabled, ButtonBehavior: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) ButtonBehavior() was relying on lack of nav focus for keyboard handling --- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- imgui_widgets.cpp | 3 ++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a38dbcfbc..4e75a1fa5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Other Changes: result in temporarily incorrect state, which would lead to bugs to side effects in various locations, e.g. GetContentRegionAvail() calls or using clipper. (#9005) EndTable() was mistakenly restoring a wrong current table. +- Disabled: fixed a bug when a previously enabled item that got nav focus + and then turns disabled could still be activated using keyboard. (#9036) - InputText: when buffer is not resizable, trying to paste contents that cannot fit will now truncate text instead of ignoring the paste. (#9029) - InputText: avoid continuously overwriting ownership of ImGuiKey_Enter/_KeypadEnter diff --git a/imgui.h b/imgui.h index e7920e64f..2911ffa85 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.5 WIP" -#define IMGUI_VERSION_NUM 19242 +#define IMGUI_VERSION_NUM 19243 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 82d21da32..f36973992 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -675,6 +675,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool // Keyboard/Gamepad navigation handling // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse. + if ((item_flags & ImGuiItemFlags_Disabled) == 0) { if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav) if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus)) @@ -756,7 +757,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } // Activation highlight (this may be a remote activation) - if (g.NavHighlightActivatedId == id) + if (g.NavHighlightActivatedId == id && (item_flags & ImGuiItemFlags_Disabled) == 0) hovered = true; if (out_hovered) *out_hovered = hovered; From 2a194e21a0ce546972c4d306efc052ae11c2711c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Oct 2025 17:24:23 +0100 Subject: [PATCH 1441/2359] InputText: revert truncation behavior from e612536 as it can truncate mid-UTF8. (#9029) --- docs/CHANGELOG.txt | 2 -- imgui_widgets.cpp | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4e75a1fa5..b3a1fe773 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,8 +49,6 @@ Other Changes: EndTable() was mistakenly restoring a wrong current table. - Disabled: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) -- InputText: when buffer is not resizable, trying to paste contents that - cannot fit will now truncate text instead of ignoring the paste. (#9029) - InputText: avoid continuously overwriting ownership of ImGuiKey_Enter/_KeypadEnter keys in order to allow e.g. external Shortcut override behavior. (#9004) - InputText: when using a callback to reduce/manipulate the value of BufTextLen, diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f36973992..0d2c9507b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4155,7 +4155,7 @@ static int STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const cha // We support partial insertion (with a mod in stb_textedit.h) const int avail = obj->BufCapacity - 1 - obj->TextLen; if (!is_resizable && new_text_len > avail) - new_text_len = avail; // 0 + new_text_len = 0; // avail if (new_text_len == 0) return 0; @@ -4314,7 +4314,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons // 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 = avail; // 0 + new_text_len = 0; // avail if (new_text_len == 0) return; From 8df962a6eda908ac2af942f496b86bafa15115fa Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Oct 2025 17:34:02 +0100 Subject: [PATCH 1442/2359] Debug Tools: fixed DebugTextEncoding() potentially reading out of bounds if provided a trailing truncated UTF-8 sequence. --- docs/CHANGELOG.txt | 3 ++- imgui.cpp | 11 +++++++---- imgui_draw.cpp | 4 +++- imgui_widgets.cpp | 3 ++- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b3a1fe773..fe22fa6ef 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,8 @@ Other Changes: triggered by some widgets e.g. Checkbox(), Selectable() and many others, which cleared ActiveId at the same time as editing. (#9028) Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited). +- Debug Tools: fixed DebugTextEncoding() potentially reading out of bounds + if provided a trailing truncated UTF-8 sequence. - Backends: - GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) [@jagot] @@ -78,7 +80,6 @@ Other Changes: (note: examples application were not updated yet) - Win32: Revert 1.92.4 change of comparing dwPacketNumber, which prevents refreshing accurate gamepad info after focus-out + io.ClearInputKeys(). (#8556) - - Examples: - GLFW+WebGPU: removed unnecessary ImGui_ImplWGPU_InvalidateDeviceObjects() call during surface resize. (#8381) diff --git a/imgui.cpp b/imgui.cpp index 14e90ada1..8a446fc4c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1642,14 +1642,15 @@ void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c) AddInputCharacter((unsigned)cp); } -void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) +void ImGuiIO::AddInputCharactersUTF8(const char* str) { if (!AppAcceptingEvents) return; - while (*utf8_chars != 0) + const char* str_end = str + strlen(str); + while (*str != 0) { unsigned int c = 0; - utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL); + str += ImTextCharFromUtf8(&c, str, str_end); AddInputCharacter(c); } } @@ -2502,6 +2503,7 @@ int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* int len = lengths[*(const unsigned char*)in_text >> 3]; int wanted = len + (len ? 0 : 1); + // IMPORTANT: if in_text_end == NULL it assume we have enough space! if (in_text_end == NULL) in_text_end = in_text + wanted; // Max length, nulls will be taken into account. @@ -15998,10 +16000,11 @@ 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; ) { unsigned int c; - const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL); + const int c_utf8_len = ImTextCharFromUtf8(&c, p, str_end); TableNextColumn(); Text("%d", (int)(p - str)); TableNextColumn(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b7613ef5a..549b4f332 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5023,7 +5023,9 @@ const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese() void ImFontGlyphRangesBuilder::AddText(const char* text, const char* text_end) { - while (text_end ? (text < text_end) : *text) + if (text_end == NULL) + text_end = text + strlen(text); + while (text < text_end) { unsigned int c = 0; int c_len = ImTextCharFromUtf8(&c, text, text_end); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0d2c9507b..d7c0df486 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5151,12 +5151,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Filter pasted buffer const int clipboard_len = (int)ImStrlen(clipboard); + const char* clipboard_end = clipboard + clipboard_len; ImVector clipboard_filtered; clipboard_filtered.reserve(clipboard_len + 1); for (const char* s = clipboard; *s != 0; ) { unsigned int c; - int in_len = ImTextCharFromUtf8(&c, s, NULL); + int in_len = ImTextCharFromUtf8(&c, s, clipboard_end); s += in_len; if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true)) continue; From 3c578fa87ec9c6db9dcbaeb344f3288dbf0bb493 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Oct 2025 18:40:40 +0100 Subject: [PATCH 1443/2359] InputText: restore truncating, now between UTF-8 codepoint. (#9029) Amend e612536, 2a194e2. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 22 +++++++++++++++++----- imgui_internal.h | 3 ++- imgui_widgets.cpp | 4 ++-- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fe22fa6ef..25f02f298 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,9 @@ Other Changes: EndTable() was mistakenly restoring a wrong current table. - Disabled: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) +- InputText: when buffer is not resizable, trying to paste contents that + cannot fit will now truncate text to nearest UTF-8 codepoint boundaries, + instead of completely ignoring the paste. (#9029) - InputText: avoid continuously overwriting ownership of ImGuiKey_Enter/_KeypadEnter keys in order to allow e.g. external Shortcut override behavior. (#9004) - InputText: when using a callback to reduce/manipulate the value of BufTextLen, diff --git a/imgui.cpp b/imgui.cpp index 8a446fc4c..87b261046 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2663,17 +2663,29 @@ int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_e return bytes_count; } -const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr) +const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_p) { - while (in_text_curr > in_text_start) + while (in_p > in_text_start) { - in_text_curr--; - if ((*in_text_curr & 0xC0) != 0x80) - return in_text_curr; + in_p--; + if ((*in_p & 0xC0) != 0x80) + return in_p; } return in_text_start; } +const char* ImTextFindValidUtf8CodepointEnd(const char* in_text_start, const char* in_text_end, const char* in_p) +{ + if (in_text_start == in_p) + return in_text_start; + const char* prev = ImTextFindPreviousUtf8Codepoint(in_text_start, in_p); + unsigned int prev_c; + int prev_c_len = ImTextCharFromUtf8(&prev_c, prev, in_text_end); + if (prev_c != IM_UNICODE_CODEPOINT_INVALID && prev_c_len <= (int)(in_p - prev)) + return in_p; + return prev; +} + int ImTextCountLines(const char* in_text, const char* in_text_end) { if (in_text_end == NULL) diff --git a/imgui_internal.h b/imgui_internal.h index c3c783efa..149f89fea 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -428,7 +428,8 @@ IMGUI_API int ImTextStrFromUtf8(ImWchar* out_buf, int out_buf_size, co IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8 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_text_curr); // return previous UTF-8 code-point. +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. // Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d7c0df486..6d17213a2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4155,7 +4155,7 @@ static int STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const cha // We support partial insertion (with a mod in stb_textedit.h) const int avail = obj->BufCapacity - 1 - obj->TextLen; if (!is_resizable && new_text_len > avail) - new_text_len = 0; // 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. if (new_text_len == 0) return 0; @@ -4314,7 +4314,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons // 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 = 0; // 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. if (new_text_len == 0) return; From 130c3e6b75076f1a99f8ad6af280b90ca5e2f8b7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Oct 2025 16:04:14 +0100 Subject: [PATCH 1444/2359] Backends: Vulkan: tweak comments. (#9041) --- backends/imgui_impl_vulkan.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index fb51a2ac0..fde5bed20 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -93,7 +93,7 @@ struct ImGui_ImplVulkan_PipelineInfo // and must contain a pool size large enough to hold a small number of VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptors. // - As an convenience, by setting DescriptorPoolSize > 0 the backend will create one for you. // - About dynamic rendering: -// - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure. +// - When using dynamic rendering, set UseDynamicRendering=true + fill PipelineInfoMain.PipelineRenderingCreateInfo structure. struct ImGui_ImplVulkan_InitInfo { uint32_t ApiVersion; // Fill with API version of Instance, e.g. VK_API_VERSION_1_3 or your value of VkApplicationInfo::apiVersion. May be lower than header version (VK_HEADER_VERSION_COMPLETE) From 670a92723a56eb67430da6cc5365d4e3b2e14af4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Oct 2025 17:47:06 +0100 Subject: [PATCH 1445/2359] Move IM_STRINGIFY() to imgui.h --- imgui.h | 2 ++ imgui_internal.h | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 2911ffa85..c1e9a02eb 100644 --- a/imgui.h +++ b/imgui.h @@ -95,6 +95,8 @@ Index of this file: #endif #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! #define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. +#define IM_STRINGIFY_HELPER(_EXPR) #_EXPR +#define IM_STRINGIFY(_EXPR) IM_STRINGIFY_HELPER(_EXPR) // Preprocessor idiom to stringify e.g. an integer or a macro. // Check that version and structures layouts are matching between compiled imgui code and caller. Read comments above DebugCheckVersionAndDataLayout() for details. #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) diff --git a/imgui_internal.h b/imgui_internal.h index 149f89fea..361dd9805 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -278,8 +278,6 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #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)) // ImTrunc() is not inlined in MSVC debug builds #define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // -#define IM_STRINGIFY_HELPER(_X) #_X -#define IM_STRINGIFY(_X) IM_STRINGIFY_HELPER(_X) // Preprocessor idiom to stringify e.g. an integer. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS #define IM_FLOOR IM_TRUNC #endif From 149587b85b511feda41fad8393dc87906355b006 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Oct 2025 18:03:36 +0100 Subject: [PATCH 1446/2359] Config/build infos emit infos to convey when IM_ASSERT() macro is disabled. --- docs/CHANGELOG.txt | 3 +++ imconfig.h | 3 ++- imgui.h | 1 + imgui_demo.cpp | 19 +++++++++++++++++++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 25f02f298..f7f8b94a1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,9 @@ Other Changes: triggered by some widgets e.g. Checkbox(), Selectable() and many others, which cleared ActiveId at the same time as editing. (#9028) Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited). +- Demo: About Box: emit infos to convey when IM_ASSERT() macro is disabled, + - so users don't miss out on programming errors being reported. + - so it is included in config/build info submitted in new GitHub Issues. - Debug Tools: fixed DebugTextEncoding() potentially reading out of bounds if provided a trailing truncated UTF-8 sequence. - Backends: diff --git a/imconfig.h b/imconfig.h index 0e7cf6182..c6d9b8d5f 100644 --- a/imconfig.h +++ b/imconfig.h @@ -15,7 +15,8 @@ #pragma once //---- Define assertion handler. Defaults to calling assert(). -// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. +// - If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. +// - Compiling with NDEBUG will usually strip out assert() to nothing, which is NOT recommended because we use asserts to notify of programmer mistakes. //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts diff --git a/imgui.h b/imgui.h index c1e9a02eb..88c42ecb6 100644 --- a/imgui.h +++ b/imgui.h @@ -89,6 +89,7 @@ Index of this file: #endif // Helper Macros +// (note: compiling with NDEBUG will usually strip out assert() to nothing, which is NOT recommended because we use asserts to notify of programmer mistakes.) #ifndef IM_ASSERT #include #define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3c3900b43..a43fd2487 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8185,6 +8185,25 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::Text("define: __EMSCRIPTEN__"); ImGui::Text("Emscripten: %d.%d.%d", __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__); #endif +#ifdef NDEBUG + ImGui::Text("define: NDEBUG"); +#endif + + // Heuristic to detect no-op IM_ASSERT() macros + // - This is designed so people opening bug reports would convey and notice that they have disabled asserts for Dear ImGui code. + // - 16 is > strlen("((void)(_EXPR))") which we suggested in our imconfig.h template as a possible way to disable. + int assert_runs_expression = 0; + IM_ASSERT(++assert_runs_expression); + int assert_expand_len = (int)strlen(IM_STRINGIFY(IM_ASSERT(true))); + bool assert_maybe_disabled = (!assert_runs_expression || assert_expand_len <= 16); + ImGui::Text("IM_ASSERT: runs expression: %s. expand size: %s%s", + assert_runs_expression ? "OK" : "KO", (assert_expand_len > 16) ? "OK" : "KO", assert_maybe_disabled ? " (MAYBE DISABLED?!)" : ""); + if (assert_maybe_disabled) + { + ImGui::SameLine(); + HelpMarker("IM_ASSERT() calls assert() by default. Compiling with NDEBUG will usually strip out assert() to nothing, which is NOT recommended because we use asserts to notify of programmer mistakes!"); + } + ImGui::Separator(); ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL"); ImGui::Text("io.BackendRendererName: %s", io.BackendRendererName ? io.BackendRendererName : "NULL"); From db577cd4451b6627b51405d36711479a4f7bdb19 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Oct 2025 16:16:45 +0100 Subject: [PATCH 1447/2359] Fonts: rename internal fields for consistency. --- imgui.cpp | 10 ++++---- imgui.h | 10 ++++---- imgui_draw.cpp | 44 ++++++++++++++++---------------- misc/freetype/imgui_freetype.cpp | 4 +-- 4 files changed, 34 insertions(+), 34 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 87b261046..7ad8ee89d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7804,7 +7804,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Setup draw list and outer clipping rectangle IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); - window->DrawList->PushTexture(g.Font->ContainerAtlas->TexRef); + window->DrawList->PushTexture(g.Font->OwnerAtlas->TexRef); PushClipRect(host_rect.Min, host_rect.Max, false); // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71) @@ -8906,7 +8906,7 @@ void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float f #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS IM_ASSERT(font->Scale > 0.0f); #endif - ImFontAtlas* atlas = font->ContainerAtlas; + ImFontAtlas* atlas = font->OwnerAtlas; g.DrawListSharedData.FontAtlas = atlas; g.DrawListSharedData.Font = font; ImFontAtlasUpdateDrawListsSharedData(atlas); @@ -17083,7 +17083,7 @@ void ImGui::DebugNodeFont(ImFont* font) { ImGuiContext& g = *GImGui; ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; - ImFontAtlas* atlas = font->ContainerAtlas; + ImFontAtlas* atlas = font->OwnerAtlas; bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size); // Display preview text @@ -17198,7 +17198,7 @@ void ImGui::DebugNodeFont(ImFont* font) for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++) { ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n]; - if (baked->ContainerFont != font) + if (baked->OwnerFont != font) continue; PushID(baked_n); if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) @@ -17289,7 +17289,7 @@ void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); if (glyph->PackId >= 0) { - ImTextureRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId); + ImTextureRect* r = ImFontAtlasPackGetRect(font->OwnerAtlas, glyph->PackId); Text("PackId: 0x%X (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y); } Text("SourceIdx: %d", glyph->SourceIdx); diff --git a/imgui.h b/imgui.h index 88c42ecb6..3e44b9f40 100644 --- a/imgui.h +++ b/imgui.h @@ -3513,7 +3513,7 @@ struct ImFontConfig char Name[40]; // // Name (strictly to ease debugging, hence limited size buffer) void* FontData; // // TTF/OTF data int FontDataSize; // // TTF/OTF data size - bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). + bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the owner ImFontAtlas (will delete memory itself). // Options bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. @@ -3792,7 +3792,7 @@ struct ImFontBaked unsigned int LoadNoRenderOnLayout:1;// 0 // // Enable a two-steps mode where CalcTextSize() calls will load AdvanceX *without* rendering/packing glyphs. Only advantagous if you know that the glyph is unlikely to actually be rendered, otherwise it is slower because we'd do one query on the first CalcTextSize and one query on the first Draw. int LastUsedFrame; // 4 // // Record of that time this was bounds ImGuiID BakedId; // 4 // // Unique ID for this baked storage - ImFont* ContainerFont; // 4-8 // in // Parent font + ImFont* OwnerFont; // 4-8 // in // Parent font void* FontLoaderDatas; // 4-8 // // Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. // Functions @@ -3823,7 +3823,7 @@ struct ImFont { // [Internal] Members: Hot ~12-20 bytes ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked(). - ImFontAtlas* ContainerAtlas; // 4-8 // What we have been loaded into. + ImFontAtlas* OwnerAtlas; // 4-8 // What we have been loaded into. ImFontFlags Flags; // 4 // Font flags. float CurrentRasterizerDensity; // Current rasterizer density. This is a varying state of the font. @@ -3831,7 +3831,7 @@ struct ImFont // Conceptually Sources[] is the list of font sources merged to create this font. ImGuiID FontId; // Unique identifier for the font float LegacySize; // 4 // in // Font size passed to AddFont(). Use for old code calling PushFont() expecting to use that size. (use ImGui::GetFontBaked() to get font baked at current bound size). - ImVector Sources; // 16 // in // List of sources. Pointers within ContainerAtlas->Sources[] + ImVector Sources; // 16 // in // List of sources. Pointers within OwnerAtlas->Sources[] ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. @@ -3845,7 +3845,7 @@ struct ImFont IMGUI_API ImFont(); IMGUI_API ~ImFont(); IMGUI_API bool IsGlyphInFont(ImWchar c); - bool IsLoaded() const { return ContainerAtlas != NULL; } + bool IsLoaded() const { return OwnerAtlas != NULL; } const char* GetDebugName() const { return Sources.Size ? Sources[0]->Name : ""; } // Fill ImFontConfig::Name. // [Internal] Don't use! diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 549b4f332..55f105294 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -824,7 +824,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off - IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); + IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); @@ -3242,7 +3242,7 @@ void ImFontAtlas::RemoveFont(ImFont* font) ImFontAtlasBuildUpdatePointers(this); - font->ContainerAtlas = NULL; + font->OwnerAtlas = NULL; IM_DELETE(font); // Notify external systems @@ -3620,7 +3620,7 @@ void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConf { font->ClearOutputData(); //font->FontSize = src->SizePixels; - font->ContainerAtlas = atlas; + font->OwnerAtlas = atlas; IM_ASSERT(font->Sources[0] == src); } atlas->TexIsBuilt = false; // For legacy backends @@ -3643,7 +3643,7 @@ void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src) // FIXME-NEWATLAS: This borrows too much from FontLoader's FontLoadGlyph() handlers and suggest that we should add further helpers. static ImFontGlyph* ImFontAtlasBuildSetupFontBakedEllipsis(ImFontAtlas* atlas, ImFontBaked* baked) { - ImFont* font = baked->ContainerFont; + ImFont* font = baked->OwnerFont; IM_ASSERT(font->EllipsisChar != 0); const ImFontGlyph* dot_glyph = baked->FindGlyphNoFallback((ImWchar)'.'); @@ -3689,7 +3689,7 @@ static void ImFontAtlasBuildSetupFontBakedFallback(ImFontBaked* baked) { IM_ASSERT(baked->FallbackGlyphIndex == -1); IM_ASSERT(baked->FallbackAdvanceX == 0.0f); - ImFont* font = baked->ContainerFont; + ImFont* font = baked->OwnerFont; ImFontGlyph* fallback_glyph = NULL; if (font->FallbackChar != 0) fallback_glyph = baked->FindGlyphNoFallback(font->FallbackChar); @@ -3699,7 +3699,7 @@ static void ImFontAtlasBuildSetupFontBakedFallback(ImFontBaked* baked) ImFontGlyph glyph; glyph.Codepoint = 0; glyph.AdvanceX = space_glyph ? space_glyph->AdvanceX : IM_ROUND(baked->Size * 0.40f); - fallback_glyph = ImFontAtlasBakedAddFontGlyph(font->ContainerAtlas, baked, NULL, &glyph); + fallback_glyph = ImFontAtlasBakedAddFontGlyph(font->OwnerAtlas, baked, NULL, &glyph); } baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(fallback_glyph); // Storing index avoid need to update pointer on growth and simplify inner loop code baked->FallbackAdvanceX = fallback_glyph->AdvanceX; @@ -3780,7 +3780,7 @@ ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_si baked->Size = font_size; baked->RasterizerDensity = font_rasterizer_density; baked->BakedId = baked_id; - baked->ContainerFont = font; + baked->OwnerFont = font; baked->LastUsedFrame = atlas->Builder->FrameCount; // Initialize backend data @@ -3815,7 +3815,7 @@ ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, f for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) { ImFontBaked* baked = &builder->BakedPool[baked_n]; - if (baked->ContainerFont != font || baked->WantDestroy) + if (baked->OwnerFont != font || baked->WantDestroy) continue; if (step_n == 0 && baked->RasterizerDensity != font_rasterizer_density) // First try with same density continue; @@ -3871,7 +3871,7 @@ void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_fr ImFontBaked* baked = &builder->BakedPool[baked_n]; if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount) continue; - if (baked->ContainerFont != font || baked->WantDestroy) + if (baked->OwnerFont != font || baked->WantDestroy) continue; ImFontAtlasBakedDiscard(atlas, font, baked); } @@ -3886,9 +3886,9 @@ void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames) ImFontBaked* baked = &builder->BakedPool[baked_n]; if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount) continue; - if (baked->WantDestroy || (baked->ContainerFont->Flags & ImFontFlags_LockBakedSizes)) + if (baked->WantDestroy || (baked->OwnerFont->Flags & ImFontFlags_LockBakedSizes)) continue; - ImFontAtlasBakedDiscard(atlas, baked->ContainerFont, baked); + ImFontAtlasBakedDiscard(atlas, baked->OwnerFont, baked); } } @@ -4421,8 +4421,8 @@ static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint, float* only_load_advance_x) { - ImFont* font = baked->ContainerFont; - ImFontAtlas* atlas = font->ContainerAtlas; + ImFont* font = baked->OwnerFont; + ImFontAtlas* atlas = font->OwnerAtlas; if (atlas->Locked || (font->Flags & ImFontFlags_NoLoadGlyphs)) { // Lazily load fallback glyph @@ -4696,7 +4696,7 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC stbtt_MakeGlyphBitmapSubpixelPrefilter(&bd_font_data->FontInfo, bitmap_pixels, w, h, w, scale_for_raster_x, scale_for_raster_y, 0, 0, oversample_h, oversample_v, &sub_x, &sub_y, glyph_index); - const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; float font_off_x = (src->GlyphOffset.x * offsets_scale); float font_off_y = (src->GlyphOffset.y * offsets_scale); @@ -5093,7 +5093,7 @@ ImFont::~ImFont() void ImFont::ClearOutputData() { - if (ImFontAtlas* atlas = ContainerAtlas) + if (ImFontAtlas* atlas = OwnerAtlas) ImFontAtlasFontDiscardBakes(atlas, this, 0); FallbackChar = EllipsisChar = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); @@ -5138,7 +5138,7 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked if (src != NULL) { // Clamp & recenter if needed - const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; float advance_x = ImClamp(glyph->AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); if (advance_x != glyph->AdvanceX) @@ -5164,7 +5164,7 @@ ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked baked->IndexAdvanceX[codepoint] = glyph->AdvanceX; baked->IndexLookup[codepoint] = (ImU16)glyph_idx; const int page_n = codepoint / 8192; - baked->ContainerFont->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); + baked->OwnerFont->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); return glyph; } @@ -5176,7 +5176,7 @@ void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* bake if (src != NULL) { // Clamp & recenter if needed - const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; advance_x = ImClamp(advance_x, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); @@ -5198,7 +5198,7 @@ void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImTextureData* tex = atlas->TexData; IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, (unsigned char*)tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h); - ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, glyph, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h }; + ImFontAtlasPostProcessData pp_data = { atlas, baked->OwnerFont, src, baked, glyph, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h }; ImFontAtlasTextureBlockPostProcess(&pp_data); ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } @@ -5256,7 +5256,7 @@ bool ImFontBaked::IsGlyphLoaded(ImWchar c) // This is not fast query bool ImFont::IsGlyphInFont(ImWchar c) { - ImFontAtlas* atlas = ContainerAtlas; + ImFontAtlas* atlas = OwnerAtlas; ImFontAtlas_FontHookRemapCodepoint(atlas, this, &c); for (ImFontConfig* src : Sources) { @@ -5305,7 +5305,7 @@ ImFontBaked* ImFont::GetFontBaked(float size, float density) if (baked && baked->Size == size && baked->RasterizerDensity == density) return baked; - ImFontAtlas* atlas = ContainerAtlas; + ImFontAtlas* atlas = OwnerAtlas; ImFontAtlasBuilder* builder = atlas->Builder; baked = ImFontAtlasBakedGetOrAdd(atlas, this, size, density); if (baked == NULL) @@ -5326,7 +5326,7 @@ ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float fo ImFontBaked* baked = *p_baked_in_map; if (baked != NULL) { - IM_ASSERT(baked->Size == font_size && baked->ContainerFont == font && baked->BakedId == baked_id); + IM_ASSERT(baked->Size == font_size && baked->OwnerFont == font && baked->BakedId == baked_id); return baked; } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index cbbde767c..16bb9817c 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -423,7 +423,7 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* s IM_UNUSED(atlas); float size = baked->Size; if (src->MergeMode && src->SizePixels != 0.0f) - size *= (src->SizePixels / baked->ContainerFont->Sources[0]->SizePixels); + size *= (src->SizePixels / baked->OwnerFont->Sources[0]->SizePixels); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; bd_font_data->BakedLastActivated = baked; @@ -539,7 +539,7 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data; ImGui_ImplFreeType_BlitGlyph(ft_bitmap, temp_buffer, w); - const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; float font_off_x = (src->GlyphOffset.x * offsets_scale); float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent; From 505ff536f9393ddfcce4a06017131e7c3955027f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Oct 2025 16:37:42 +0100 Subject: [PATCH 1448/2359] Textures: fixed an issue preventing multi-contexts from using each others' fonts if context 2 runs after context 1's Render() function. (#9039) --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f7f8b94a1..7b101d6a7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,9 @@ Other Changes: resizing the parent window while keeping the multi-line field active (which is most typically achieved when resizing programmatically or via a docking layout reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] +- Textures: + - Fixed an issue preventing multi-contexts from using each others' fonts + if context 2 runs after context 1's Render() function. (#9039) - MultiSelect: added ImGuiMultiSelectFlags_NoSelectOnRightClick to disable default right-click processing, which selects item on mouse down and is designed for context-menus. (#8200, #9015) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 55f105294..9e6babf78 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3909,6 +3909,11 @@ void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedDat void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex) { for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + { + // If Context 2 uses font owned by Context 1 which already called EndFrame()/Render(), we don't want to mess with draw commands for Context 1 + if (shared_data->Context && !shared_data->Context->WithinFrameScope) + continue; + for (ImDrawList* draw_list : shared_data->DrawLists) { // Replace in command-buffer @@ -3922,6 +3927,7 @@ void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex if (stacked_tex == old_tex) stacked_tex = new_tex; } + } } // Update texture coordinates in all draw list shared context From d0e3b1d4e2f53100b24f30c3737e9c4edcb35035 Mon Sep 17 00:00:00 2001 From: BrutPitt Date: Fri, 31 Oct 2025 18:50:12 +0100 Subject: [PATCH 1449/2359] Backends: WebGPU: added ImGui_ImplWGPU_CreateWGPUSurfaceHelper(). (#8381, #8831, #8567, #8191, #7435) --- backends/imgui_impl_wgpu.cpp | 73 +++++++++++++++++++++++++++++++++++- backends/imgui_impl_wgpu.h | 19 ++++++++++ docs/CHANGELOG.txt | 3 ++ 3 files changed, 94 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index fe5cd5832..28b3ac1e3 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -273,7 +273,7 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c #endif WGPUShaderModuleDescriptor desc = {}; - desc.nextInChain = reinterpret_cast(&wgsl_desc); + desc.nextInChain = (WGPUChainedStruct*)&wgsl_desc; WGPUProgrammableStageDescriptor stage_desc = {}; stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc); @@ -915,6 +915,77 @@ void ImGui_ImplWGPU_NewFrame() IM_ASSERT(0 && "ImGui_ImplWGPU_CreateDeviceObjects() failed!"); } +//------------------------------------------------------------------------- +// Internal Helpers +// Those are currently used by our example applications. +//------------------------------------------------------------------------- + +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(__EMSCRIPTEN__) + +#if defined(__APPLE__) +// MacOS specific: is necessary to compile with "-x objective-c++" flags +// (e.g. using cmake: set_source_files_properties(${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") ) +#include +#include +#endif + +WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceInfo* info) +{ + WGPUSurfaceDescriptor surface_descriptor = {}; + WGPUSurface surface = {}; +#if defined(__APPLE__) + if (strcmp(info->System, "cocoa") == 0) + { + IM_ASSERT(info->RawWindow != nullptr); + NSWindow* ns_window = (NSWindow*)info->RawWindow; + id metal_layer = [CAMetalLayer layer]; + [ns_window.contentView setWantsLayer : YES] ; + [ns_window.contentView setLayer : metal_layer] ; + WGPUSurfaceSourceMetalLayer surface_src_metal = {}; + surface_src_metal.chain.sType = WGPUSType_SurfaceSourceMetalLayer; + surface_src_metal.layer = metal_layer; + surface_descriptor.nextInChain = &surface_src_metal.chain; + surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor); + } +#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) + if (strcmp(info->System, "wayland") == 0) + { + IM_ASSERT(info->RawDisplay != nullptr && info->RawSurface != nullptr); + WGPUSurfaceSourceWaylandSurface surface_src_wayland = {}; + surface_src_wayland.chain.sType = WGPUSType_SurfaceSourceWaylandSurface; + surface_src_wayland.display = info->RawDisplay; + surface_src_wayland.surface = info->RawSurface; + surface_descriptor.nextInChain = &surface_src_wayland.chain; + surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor); + } + else if (strcmp(info->System, "x11") == 0) + { + IM_ASSERT(info->RawDisplay != nullptr && info->RawWindow != nullptr); + WGPUSurfaceSourceXlibWindow surface_src_xlib = {}; + surface_src_xlib.chain.sType = WGPUSType_SurfaceSourceXlibWindow; + surface_src_xlib.display = info->RawDisplay; + surface_src_xlib.window = (uint64_t)info->RawWindow; + surface_descriptor.nextInChain = &surface_src_xlib.chain; + surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor); + } +#elif defined(_WIN32) + if (strcmp(info->System, "win32") == 0) + { + IM_ASSERT(info->RawWindow != nullptr && info->RawInstance != nullptr); + WGPUSurfaceSourceWindowsHWND surface_src_hwnd = {}; + surface_src_hwnd.chain.sType = WGPUSType_SurfaceSourceWindowsHWND; + surface_src_hwnd.hinstance = info->RawInstance; + surface_src_hwnd.hwnd = info->RawWindow; + surface_descriptor.nextInChain = &surface_src_hwnd.chain; + surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor); + } +#else +#error "Unsupported WebGPU native platform!" +#endif + return surface; +} +#endif + //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 9443106b8..6d10c53d6 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -81,4 +81,23 @@ struct ImGui_ImplWGPU_RenderState WGPURenderPassEncoder RenderPassEncoder; }; +//------------------------------------------------------------------------- +// Internal Helpers +// Those are currently used by our example applications. +//------------------------------------------------------------------------- + +// (Optional) Helper to create a surface on macOS/Wayland/X11/Window +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(__EMSCRIPTEN__) +struct ImGui_ImplWGPU_CreateSurfaceInfo +{ + WGPUInstance Instance; + const char* System; // "cocoa" | "wayland" | "x11" | "win32" + void* RawWindow; // NSWindow* | 0 | Window | HWND + void* RawDisplay; // 0 | wl_display* | Display* | 0 + void* RawSurface; // | wl_surface* | 0 | 0 + void* RawInstance; // 0 | 0 | 0 | HINSTANCE +}; +WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceInfo* info); +#endif + #endif // #ifndef IMGUI_DISABLE diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7b101d6a7..f50753868 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -82,6 +82,9 @@ Other Changes: was unused in core but might be used by a direct caller). (#9027) [@achabense] - Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] + - WebGPU: added various internal/optional helpers to wrap some of the + Dawn/WGPU/Emscripten debacle quirks: (#8381) [@brutpitt] + - ImGui_ImplWGPU_CreateWGPUSurfaceHelper(). - WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ '--use-port=emdawnwebgpu' ports. (#8381, #8898) [@brutpitt, @trbabb] When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN From c5b2a848fa0809aaf7fbbd7095a5d9a66e0e776f Mon Sep 17 00:00:00 2001 From: BrutPitt Date: Fri, 31 Oct 2025 18:55:39 +0100 Subject: [PATCH 1450/2359] Backends: WebGPU: added smaller and debug helpers. (#8381, #8831, #8567, #8191, #7435) --- backends/imgui_impl_wgpu.cpp | 102 +++++++++++++++++++++++++++++++++-- backends/imgui_impl_wgpu.h | 20 +++++++ docs/CHANGELOG.txt | 5 ++ 3 files changed, 124 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 28b3ac1e3..9ec2e3592 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -51,6 +51,9 @@ #ifndef IMGUI_DISABLE #include "imgui_impl_wgpu.h" +#include +#include +#include // One of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details. #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) @@ -63,9 +66,6 @@ #define IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN #endif -#include -#include - #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN // Dawn renamed WGPUProgrammableStageDescriptor to WGPUComputeState (see: https://github.com/webgpu-native/webgpu-headers/pull/413) // Using type alias until WGPU adopts the same naming convention (#8369) @@ -920,6 +920,102 @@ void ImGui_ImplWGPU_NewFrame() // Those are currently used by our example applications. //------------------------------------------------------------------------- +bool ImGui_ImplWGPU_IsSurfaceStatusError(WGPUSurfaceGetCurrentTextureStatus status) +{ +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) + return (status == WGPUSurfaceGetCurrentTextureStatus_Error); +#else + return (status == WGPUSurfaceGetCurrentTextureStatus_OutOfMemory || status == WGPUSurfaceGetCurrentTextureStatus_DeviceLost); +#endif +} + +bool ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(WGPUSurfaceGetCurrentTextureStatus status) +{ +#if defined(__EMSCRIPTEN__) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) + return (status == WGPUSurfaceGetCurrentTextureStatus_Timeout || status == WGPUSurfaceGetCurrentTextureStatus_Outdated || status == WGPUSurfaceGetCurrentTextureStatus_Lost); +#else + return (status == WGPUSurfaceGetCurrentTextureStatus_Timeout || status == WGPUSurfaceGetCurrentTextureStatus_Outdated || status == WGPUSurfaceGetCurrentTextureStatus_Lost || status == WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal); +#endif +} + +// Helpers to obtain a string +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +const char* ImGui_ImplWGPU_GetErrorTypeName(WGPUErrorType type) +{ + switch (type) + { + case WGPUErrorType_Validation: return "Validation"; + case WGPUErrorType_OutOfMemory: return "OutOfMemory"; + case WGPUErrorType_Unknown: return "Unknown"; + case WGPUErrorType_Internal: return "Internal"; + default: return "Unknown"; + } +} +const char* ImGui_ImplWGPU_GetDeviceLostReasonName(WGPUDeviceLostReason type) +{ + switch (type) + { + case WGPUDeviceLostReason_Unknown: return "Unknown"; + case WGPUDeviceLostReason_Destroyed: return "Destroyed"; + case WGPUDeviceLostReason_CallbackCancelled: return "CallbackCancelled"; + case WGPUDeviceLostReason_FailedCreation: return "FailedCreation"; + default: return "Unknown"; + } +} +#elif !defined(__EMSCRIPTEN__) +const char* ImGui_ImplWGPU_GetLogLevelName(WGPULogLevel level) +{ + switch (level) + { + case WGPULogLevel_Error: return "Error"; + case WGPULogLevel_Warn: return "Warn"; + case WGPULogLevel_Info: return "Info"; + case WGPULogLevel_Debug: return "Debug"; + case WGPULogLevel_Trace: return "Trace"; + default: return "Unknown"; + } +} +#endif + +const char* ImGui_ImplWGPU_GetBackendTypeName(WGPUBackendType type) +{ + switch (type) + { + case WGPUBackendType_WebGPU: return "WebGPU"; + case WGPUBackendType_D3D11: return "D3D11"; + case WGPUBackendType_D3D12: return "D3D12"; + case WGPUBackendType_Metal: return "Metal"; + case WGPUBackendType_Vulkan: return "Vulkan"; + case WGPUBackendType_OpenGL: return "OpenGL"; + case WGPUBackendType_OpenGLES: return "OpenGLES"; + default: return "Unknown"; + } +} + +const char* ImGui_ImplWGPU_GetAdapterTypeName(WGPUAdapterType type) +{ + switch (type) + { + case WGPUAdapterType_DiscreteGPU: return "DiscreteGPU"; + case WGPUAdapterType_IntegratedGPU: return "IntegratedGPU"; + case WGPUAdapterType_CPU: return "CPU"; + default: return "Unknown"; + } +} + +void ImGui_ImplWGPU_DebugPrintAdapterInfo(const WGPUAdapter& adapter) +{ + WGPUAdapterInfo info = {}; + wgpuAdapterGetInfo(adapter, &info); + printf("description: \"%.*s\"\n", (int)info.description.length, info.description.data); + printf("vendor: \"%.*s\", vendorID: %x\n", (int)info.vendor.length, info.vendor.data, info.vendorID); + printf("architecture: \"%.*s\"\n", (int) info.architecture.length, info.architecture.data); + printf("device: \"%.*s\", deviceID: %x\n", (int)info.device.length, info.device.data, info.deviceID); + printf("backendType: \"%s\"\n", ImGui_ImplWGPU_GetBackendTypeName(info.backendType)); + printf("adapterType: \"%s\"\n", ImGui_ImplWGPU_GetAdapterTypeName(info.adapterType)); + wgpuAdapterInfoFreeMembers(info); +} + #if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(__EMSCRIPTEN__) #if defined(__APPLE__) diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 6d10c53d6..3e46849b5 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -41,6 +41,11 @@ #endif #include +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +#include // for wgpu::Device, wgpu::DeviceLostReason, wgpu::ErrorType used by validation layer callbacks. +#elif !defined(__EMSCRIPTEN__) +#include // WGPULogLevel +#endif // Initialization data, for ImGui_ImplWGPU_Init() struct ImGui_ImplWGPU_InitInfo @@ -86,6 +91,21 @@ struct ImGui_ImplWGPU_RenderState // Those are currently used by our example applications. //------------------------------------------------------------------------- +// (Optional) Helper to wrap some of the Dawn/WGPU/Emscripten quirks +bool ImGui_ImplWGPU_IsSurfaceStatusError(WGPUSurfaceGetCurrentTextureStatus status); +bool ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(WGPUSurfaceGetCurrentTextureStatus status); // Return whether the texture is suboptimal and may need to be recreated. + +// (Optional) Helper for debugging/logging +void ImGui_ImplWGPU_DebugPrintAdapterInfo(const WGPUAdapter& adapter); +const char* ImGui_ImplWGPU_GetBackendTypeName(WGPUBackendType type); +const char* ImGui_ImplWGPU_GetAdapterTypeName(WGPUAdapterType type); +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +const char* ImGui_ImplWGPU_GetDeviceLostReasonName(WGPUDeviceLostReason type); +const char* ImGui_ImplWGPU_GetErrorTypeName(WGPUErrorType type); +#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) && !defined(__EMSCRIPTEN__) +const char* ImGui_ImplWGPU_GetLogLevelName(WGPULogLevel level); +#endif + // (Optional) Helper to create a surface on macOS/Wayland/X11/Window #if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(__EMSCRIPTEN__) struct ImGui_ImplWGPU_CreateSurfaceInfo diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f50753868..551a166d8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,11 @@ Other Changes: - WebGPU: added various internal/optional helpers to wrap some of the Dawn/WGPU/Emscripten debacle quirks: (#8381) [@brutpitt] - ImGui_ImplWGPU_CreateWGPUSurfaceHelper(). + - ImGui_ImplWGPU_IsSurfaceStatusError(), ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(). + - ImGui_ImplWGPU_DebugPrintAdapterInfo(), + - ImGui_ImplWGPU_GetBackendTypeName(), ImGui_ImplWGPU_GetAdapterTypeName(), + ImGui_ImplWGPU_GetDeviceLostReasonName(), ImGui_ImplWGPU_GetErrorTypeName(), + ImGui_ImplWGPU_GetLogLevelName(). - WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ '--use-port=emdawnwebgpu' ports. (#8381, #8898) [@brutpitt, @trbabb] When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN From 778aed996600c727d8f712913d86baec1865cf9f Mon Sep 17 00:00:00 2001 From: BrutPitt Date: Fri, 31 Oct 2025 18:58:05 +0100 Subject: [PATCH 1451/2359] Examples: GLFW+WebGPU: update to latest specs and to work on Emscripten 4.0.10+ and latest Dawn-Native, WGPU-Native. (#8381, #8567, #8191, #7435) --- docs/CHANGELOG.txt | 4 +- examples/example_glfw_wgpu/CMakeLists.txt | 259 +++++++---- .../example_glfw_wgpu/Makefile.emscripten | 24 +- examples/example_glfw_wgpu/README.md | 145 ++++++- examples/example_glfw_wgpu/main.cpp | 401 ++++++++++++++---- examples/example_glfw_wgpu/web/index.html | 84 ---- 6 files changed, 651 insertions(+), 266 deletions(-) delete mode 100644 examples/example_glfw_wgpu/web/index.html diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 551a166d8..88ef499c1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -91,13 +91,15 @@ Other Changes: ImGui_ImplWGPU_GetDeviceLostReasonName(), ImGui_ImplWGPU_GetErrorTypeName(), ImGui_ImplWGPU_GetLogLevelName(). - WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ - '--use-port=emdawnwebgpu' ports. (#8381, #8898) [@brutpitt, @trbabb] + '--use-port=emdawnwebgpu' ports. (#8381, #8898, #7435) [@brutpitt, @trbabb] When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN instead of IMGUI_IMPL_WEBGPU_BACKEND_WGPU, if neither are specified. (note: examples application were not updated yet) - Win32: Revert 1.92.4 change of comparing dwPacketNumber, which prevents refreshing accurate gamepad info after focus-out + io.ClearInputKeys(). (#8556) - Examples: + - GLFW+WebGPU: update example for latest specs, to work on Emscripten 4.0.10+, + latest Dawn-Native and WGPU-Native. (#8381, #8567, #8191, #7435) [@brutpitt] - GLFW+WebGPU: removed unnecessary ImGui_ImplWGPU_InvalidateDeviceObjects() call during surface resize. (#8381) diff --git a/examples/example_glfw_wgpu/CMakeLists.txt b/examples/example_glfw_wgpu/CMakeLists.txt index d21bb0919..d8c6eae4f 100644 --- a/examples/example_glfw_wgpu/CMakeLists.txt +++ b/examples/example_glfw_wgpu/CMakeLists.txt @@ -6,18 +6,30 @@ # * build/Debug/example_glfw_wgpu[.exe] # * build/example_glfw_wgpu[.exe] +# Building for desktop (WGPU-Native) with WGPU-Native: +# 1. download WGPU-Native autogenerated binary modules for your platform/compiler from: https://github.com/gfx-rs/wgpu-native/releases +# 2. unzip the downloaded file in your_preferred_folder +# 3. cmake -B build -DIMGUI_WGPU_DIR=your_preferred_folder ("full path" or "relative" starting from current directory) +# 4. cmake --build build +# The resulting binary will be found at one of the following locations: +# * build/Debug/example_glfw_wgpu[.exe] +# * build/example_glfw_wgpu[.exe] + # Building for Emscripten: # 1. Install Emscripten SDK following the instructions: https://emscripten.org/docs/getting_started/downloads.html # 2. Install Ninja build system # 3. emcmake cmake -G Ninja -B build +# (optional) -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py", see ReadMe.md # 3. cmake --build build # 4. emrun build/index.html -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.22) # Dawn requires CMake >= 3.22 project(imgui_example_glfw_wgpu C CXX) +set(IMGUI_EXECUTABLE example_glfw_wgpu) + if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE) + set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE) endif() set(CMAKE_CXX_STANDARD 17) # Dawn requires C++17 @@ -25,93 +37,172 @@ set(CMAKE_CXX_STANDARD 17) # Dawn requires C++17 # Dear ImGui set(IMGUI_DIR ../../) -# Libraries +set(IMGUI_EXAMPLE_SOURCE_FILES + # Example code + main.cpp + # Dear ImGui Backend files + ${IMGUI_DIR}/backends/imgui_impl_glfw.cpp + ${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp + # Dear ImGui files + ${IMGUI_DIR}/imgui.cpp + ${IMGUI_DIR}/imgui_draw.cpp + ${IMGUI_DIR}/imgui_demo.cpp + ${IMGUI_DIR}/imgui_tables.cpp + ${IMGUI_DIR}/imgui_widgets.cpp +) + if(EMSCRIPTEN) - if(EMSCRIPTEN_VERSION VERSION_GREATER_EQUAL "3.1.57") - set(IMGUI_EMSCRIPTEN_GLFW3 "--use-port=contrib.glfw3" CACHE STRING "Choose between --use-port=contrib.glfw3 and -sUSE_GLFW=3 for GLFW implementation (default to --use-port=contrib.glfw3)") - else() - # cannot use contrib.glfw3 prior to 3.1.57 - set(IMGUI_EMSCRIPTEN_GLFW3 "-sUSE_GLFW=3" CACHE STRING "Use -sUSE_GLFW=3 for GLFW implementation" FORCE) - endif() - set(LIBRARIES glfw) - add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1 -DIMGUI_IMPL_WEBGPU_BACKEND_WGPU) + if(NOT IMGUI_EMSCRIPTEN_WEBGPU_FLAG) # if IMGUI_EMSCRIPTEN_WEBGPU_FLAG not used, set by current EMSCRIPTEN version + if(EMSCRIPTEN_VERSION VERSION_GREATER_EQUAL "4.0.10") + set(IMGUI_EMSCRIPTEN_WEBGPU_FLAG "--use-port=emdawnwebgpu" CACHE STRING "Choose between --use-port=emdawnwebgpu (Dawn implementation of EMSCRIPTEN) and -sUSE_WEBGPU=1 (WGPU implementation of EMSCRIPTEN, deprecated in 4.0.10): default to --use-port=emdawnwebgpu for EMSCRIPTEN >= 4.0.10") + else() + set(IMGUI_EMSCRIPTEN_WEBGPU_FLAG "-sUSE_WEBGPU=1" CACHE STRING "Use -sUSE_WEBGPU=1 for EMSCRIPTEN WGPU implementation") + endif() + else() # if IMGUI_EMSCRIPTEN_WEBGPU_FLAG used, check correct version + if(EMSCRIPTEN_VERSION VERSION_LESS "4.0.10" AND "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" MATCHES "emdawnwebgpu") + # it's necessary EMSCRIPTEN >= v4.0.10 (although "--use-port=path/to/emdawnwebgpu.port.py" is supported/tested from v4.0.8) + message(FATAL_ERROR "emdawnwebgpu needs EMSCRIPTEN version >= 4.0.10") + endif() + endif() + + if(EMSCRIPTEN_VERSION VERSION_GREATER_EQUAL "3.1.57") + set(IMGUI_EMSCRIPTEN_GLFW3 "--use-port=contrib.glfw3" CACHE STRING "Choose between --use-port=contrib.glfw3 and -sUSE_GLFW=3 for GLFW implementation (default to --use-port=contrib.glfw3)") + else() # cannot use contrib.glfw3 prior to 3.1.57 + set(IMGUI_EMSCRIPTEN_GLFW3 "-sUSE_GLFW=3" CACHE STRING "Use -sUSE_GLFW=3 for GLFW implementation" FORCE) + endif() + + set(LIBRARIES glfw) + add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1) +else() # Native/Desktop build + # Check DAWN/WGPU directory + if(NOT IMGUI_DAWN_DIR AND NOT IMGUI_WGPU_DIR) # if it's Native/Desktop build, IMGUI_DAWN_DIR or IMGUI_WGPU_DIR must be specified + message(FATAL_ERROR "Please specify the Dawn or WGPU base directory") + endif() + + if(IMGUI_DAWN_DIR AND IMGUI_WGPU_DIR) # both IMGUI_DAWN_DIR and IMGUI_WGPU_DIR cannot be set + message(FATAL_ERROR "Please specify only one between Dawn / WGPU base directory") + endif() + + if(APPLE) # Add SDL2 module to get Surface, with libs and file property for MacOS build + set_source_files_properties(${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") +# set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") + endif() + + if(IMGUI_DAWN_DIR) # DAWN-Native build options + set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") + if(NOT IMGUI_DAWN_DIR) + message(FATAL_ERROR "Please specify the Dawn repository by setting IMGUI_DAWN_DIR") + endif() + + option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) + set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") + + # Dawn builds many things by default - disable things we don't need + option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) + option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) + option(TINT_BUILD_DOCS "Build documentation" OFF) + option(TINT_BUILD_TESTS "Build tests" OFF) + if(NOT APPLE) + option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) + endif() + if(WIN32) + option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) + option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) + option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) + option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) + option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) + option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) + option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) + endif() + # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time + # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) + if(LINUX) + if($ENV{XDG_SESSION_TYPE} MATCHES wayland) + option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + endif() + endif() + + add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) + + set(LIBRARIES webgpu_dawn webgpu_glfw glfw) + else() # WGPU-Native build options + find_package(glfw3 CONFIG) + + set(WGPU_NATIVE_LIB_DIR ${IMGUI_WGPU_DIR}/lib) + find_library(WGPU_LIBRARY NAMES libwgpu_native.a wgpu_native.lib wgpu_native HINTS ${WGPU_NATIVE_LIB_DIR} REQUIRED) + if(WIN32) + set(OS_LIBRARIES d3dcompiler ws2_32 userenv bcrypt ntdll opengl32 Propsys RuntimeObject) + elseif(UNIX AND NOT APPLE) + set(OS_LIBRARIES "-lm -ldl") + elseif(APPLE) + set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") + endif() + + set(LIBRARIES glfw ${WGPU_LIBRARY} ${OS_LIBRARIES}) + endif() +endif() + +add_executable(${IMGUI_EXECUTABLE} ${IMGUI_EXAMPLE_SOURCE_FILES}) + +target_include_directories(${IMGUI_EXECUTABLE} PUBLIC + ${IMGUI_DIR} + ${IMGUI_DIR}/backends +) + +target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_EXAMPLE_GLFW_WGPU") + +# compiler option only for IMGUI_EXAMPLE_SOURCE_FILES +if (MSVC) + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC /W4) # warning level 4 else() - # Dawn wgpu desktop - set(DAWN_FETCH_DEPENDENCIES ON) - set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - if (NOT IMGUI_DAWN_DIR) - message(FATAL_ERROR "Please specify the Dawn repository by setting IMGUI_DAWN_DIR") - endif() - - option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) - - # Dawn builds many things by default - disable things we don't need - option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) - option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) - option(TINT_BUILD_DOCS "Build documentation" OFF) - option(TINT_BUILD_TESTS "Build tests" OFF) - if (NOT APPLE) - option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) - endif() - if(WIN32) - option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) - option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) - option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) - option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) - option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" OFF) - option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) - endif() - - add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) - - set(LIBRARIES webgpu_dawn webgpu_cpp webgpu_glfw glfw) + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC -Wall) # -Wextra -Wpedantic endif() -add_executable(example_glfw_wgpu - main.cpp - # backend files - ${IMGUI_DIR}/backends/imgui_impl_glfw.cpp - ${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp - # Dear ImGui files - ${IMGUI_DIR}/imgui.cpp - ${IMGUI_DIR}/imgui_draw.cpp - ${IMGUI_DIR}/imgui_demo.cpp - ${IMGUI_DIR}/imgui_tables.cpp - ${IMGUI_DIR}/imgui_widgets.cpp -) -IF(NOT EMSCRIPTEN) - target_compile_definitions(example_glfw_wgpu PUBLIC - "IMGUI_IMPL_WEBGPU_BACKEND_DAWN" - ) -endif() -target_include_directories(example_glfw_wgpu PUBLIC - ${IMGUI_DIR} - ${IMGUI_DIR}/backends -) +# In this example IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU internal define is set according to: +# EMSCRIPTEN: by used FLAG +# --use-port=emdawnwebgpu --> IMGUI_IMPL_WEBGPU_BACKEND_DAWN defined +# -sUSE_WEBGPU=1 --> IMGUI_IMPL_WEBGPU_BACKEND_WGPU defined +# NATIVE: by used SDK installation directory +# if IMGUI_DAWN_DIR is valid --> IMGUI_IMPL_WEBGPU_BACKEND_DAWN defined +# if IMGUI_WGPU_DIR is valid --> IMGUI_IMPL_WEBGPU_BACKEND_WGPU defined -target_link_libraries(example_glfw_wgpu PUBLIC ${LIBRARIES}) +if(NOT EMSCRIPTEN) # WegGPU-Native settings + # Set IMGUI_IMPL_WEBGPU_BACKEND_XXXX based on the SDK (directory) used + if(IMGUI_DAWN_DIR) + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + else() + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") + target_include_directories(${IMGUI_EXECUTABLE} PUBLIC ${IMGUI_WGPU_DIR}/include) + endif() -# Emscripten settings -if(EMSCRIPTEN) - if("${IMGUI_EMSCRIPTEN_GLFW3}" STREQUAL "--use-port=contrib.glfw3") - target_compile_options(example_glfw_wgpu PUBLIC - "${IMGUI_EMSCRIPTEN_GLFW3}" + target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp PUBLIC ${LIBRARIES}) +else() # Emscripten settings + set(CMAKE_EXECUTABLE_SUFFIX ".html") + + if("${IMGUI_EMSCRIPTEN_GLFW3}" STREQUAL "--use-port=contrib.glfw3") + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC "${IMGUI_EMSCRIPTEN_GLFW3}") + endif() + message(STATUS "Using ${IMGUI_EMSCRIPTEN_GLFW3} GLFW implementation") + + if("${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" MATCHES "emdawnwebgpu") + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}") + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + else() + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") + endif() + message(STATUS "Using ${IMGUI_EMSCRIPTEN_WEBGPU_FLAG} WebGPU implementation") + + target_link_options(${IMGUI_EXECUTABLE} PRIVATE + "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" + "${IMGUI_EMSCRIPTEN_GLFW3}" + "-sWASM=1" + "-sASYNCIFY=1" + "-sALLOW_MEMORY_GROWTH=1" + "-sNO_EXIT_RUNTIME=0" + "-sASSERTIONS=1" + "-sDISABLE_EXCEPTION_CATCHING=1" + "-sNO_FILESYSTEM=1" + "--shell-file=${CMAKE_CURRENT_LIST_DIR}/../libs/emscripten/shell_minimal.html" ) - endif() - message(STATUS "Using ${IMGUI_EMSCRIPTEN_GLFW3} GLFW implementation") - target_link_options(example_glfw_wgpu PRIVATE - "-sUSE_WEBGPU=1" - "${IMGUI_EMSCRIPTEN_GLFW3}" - "-sWASM=1" - "-sALLOW_MEMORY_GROWTH=1" - "-sNO_EXIT_RUNTIME=0" - "-sASSERTIONS=1" - "-sDISABLE_EXCEPTION_CATCHING=1" - "-sNO_FILESYSTEM=1" - ) - set_target_properties(example_glfw_wgpu PROPERTIES OUTPUT_NAME "index") - # copy our custom index.html to build directory - add_custom_command(TARGET example_glfw_wgpu POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_LIST_DIR}/web/index.html" $ - ) + set_target_properties(${IMGUI_EXECUTABLE} PROPERTIES OUTPUT_NAME "index") endif() diff --git a/examples/example_glfw_wgpu/Makefile.emscripten b/examples/example_glfw_wgpu/Makefile.emscripten index 545a50578..8fee2fc7c 100644 --- a/examples/example_glfw_wgpu/Makefile.emscripten +++ b/examples/example_glfw_wgpu/Makefile.emscripten @@ -6,8 +6,8 @@ # This Makefile assumes you have loaded emscripten's environment. # (On Windows, you may need to execute emsdk_env.bat or encmdprompt.bat ahead) # -# Running `make` will produce three files: -# - web/index.html (current stored in the repository) +# Running `make -f Makefile.emscripten` will produce three files: +# - web/index.html # - web/index.js # - web/index.wasm # @@ -16,7 +16,7 @@ CC = emcc CXX = em++ WEB_DIR = web -EXE = $(WEB_DIR)/index.js +EXE = $(WEB_DIR)/index.html IMGUI_DIR = ../.. SOURCES = main.cpp SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp @@ -34,15 +34,19 @@ EMS = # ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) # Note: For glfw, we use emscripten-glfw port (contrib.glfw3) instead of (-s USE_GLFW=3) to get a better support for High DPI displays. EMS += -s DISABLE_EXCEPTION_CATCHING=1 --use-port=contrib.glfw3 -LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1 +LDFLAGS += -s WASM=1 +LDFLAGS += -s ALLOW_MEMORY_GROWTH=1 +LDFLAGS += -s ASYNCIFY=1 +LDFLAGS += -s NO_EXIT_RUNTIME=0 +LDFLAGS += -s ASSERTIONS=1 # (1) Using legacy WebGPU implementation (Emscripten < 4.0.10) -EMS += -DIMGUI_IMPL_WEBGPU_BACKEND_WGPU -LDFLAGS += -s USE_WEBGPU=1 +#EMS += -DIMGUI_IMPL_WEBGPU_BACKEND_WGPU +#LDFLAGS += -s USE_WEBGPU=1 -# or (2) Using newer Dawn-based WebGPU port (Emscripten >= 4.0.10) (UNSUPPORTED YET) -#EMS += --use-port=emdawnwebgpu -#LDFLAGS += --use-port=emdawnwebgpu +# or (2) Using newer Dawn-based WebGPU port (Emscripten >= 4.0.10) +EMS += --use-port=emdawnwebgpu +LDFLAGS += --use-port=emdawnwebgpu # Build as single file (binary text encoded in .html file) #LDFLAGS += -sSINGLE_FILE @@ -67,7 +71,7 @@ endif CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends #CPPFLAGS += -g CPPFLAGS += -Wall -Wformat -Os $(EMS) -#LDFLAGS += --shell-file shell_minimal.html +LDFLAGS += --shell-file ../libs/emscripten/shell_minimal.html LDFLAGS += $(EMS) ##--------------------------------------------------------------------- diff --git a/examples/example_glfw_wgpu/README.md b/examples/example_glfw_wgpu/README.md index 399d431ff..119647211 100644 --- a/examples/example_glfw_wgpu/README.md +++ b/examples/example_glfw_wgpu/README.md @@ -1,4 +1,145 @@ -## How to Build +## How to Build + + +--- + +### Using CMake +#### Building for desktop (WebGPU-native) with Google Dawn: + 1. `git clone https://github.com/google/dawn dawn` + 2. `cmake -B build -DIMGUI_DAWN_DIR=dawn` + 3. `cmake --build build` +The resulting binary will be found at one of the following locations: + * build/Debug/example_glfw_wgpu[.exe] + * build/example_glfw_wgpu[.exe] + +#### Building for desktop (WebGPU-Native) with WGPU: + 1. download WGPU-Native autogenerated binary modules for your platform/compiler from: https://github.com/gfx-rs/wgpu-native/releases + 2. unzip the downloaded file in `your_preferred_folder` + 3. `cmake -B build -DIMGUI_WGPU_DIR=your_preferred_folder` ("full path" or "relative" starting from current directory) + 4. `cmake --build build` +The resulting binary will be found at one of the following locations: + * build/Debug/example_glfw_wgpu[.exe] + * build/example_glfw_wgpu[.exe] + +#### Building for Emscripten: + 1. Install Emscripten SDK following the instructions: https://emscripten.org/docs/getting_started/downloads.html + 2. Install Ninja build system + 3. `emcmake cmake -G Ninja -B build` + - (optional) `-DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py"`, see below + 4. `cmake --build build` + +#### Sync Emscripten with latest Google Dawn: +If you want to sync Emscripten with latest DAWN release it's necessary to download the `port-emdawnwgpu-package` (released daily by Google) here: +https://github.com/google/dawn/releases +Unpack it in your preferred folder and to replace the step 3 with: + +3. `emcmake cmake -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py" -G Ninja -B build` + +**N.B.** +For the WASM code produced by Emscripten to work correctly, it will also be necessary to have the "corresponding" (or newer) version of Google Canary (nightly build for developers) that includes the latest changes + + +--- + +### CMake by step + +#### Generate Dawn Native: + +- `cmake -G Ninja -DIMGUI_DAWN_DIR=path_to_sdk_dir -B where_to_build_dir` + - Using `IMGUI_DAWN_DIR` set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + +#### Generate WGPU Native: + +- `cmake -G Ninja -DIMGUI_WGPU_DIR=path_to_sdk_dir -B where_to_build_dir` + + - Using `IMGUI_WGPU_DIR` set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten: + +- `emcmake cmake -G Ninja -B where_to_build_dir`\ +CMake checks the EMSCRIPEN version then: + - if EMS >= 4.0.10 uses `--use-port=emdawnwebgpu` flag to build + - it set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + - if EMS < 4.0.10 uses `-sUSE_WEBGPU=1` flag to build + - it set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten forcing `-sUSE_WEBGPU=1` deprecated flag even with EMS >= 4.0.10 +- `emcmake cmake -G Ninja -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="-sUSE_WEBGPU=1" -B where_to_build_dir` + - it set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten using external WebGPU library (emdawnwebgpu_pkg) +- `emcmake cmake -G Ninja -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path_to_emdawnwebgpu_pkg" -B where_to_build_dir` + - it set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + - *To use external WebGPU library it's necessary to have EMS >= 4.0.10 or the minimum requirements specified by the package:* + - https://github.com/google/dawn/releases + +#### Build time + +Once the procedure for the specific builder is generated, the build command is **always the same**: + +- Build using CMake + - `cmake --build where_to_build_dir` + - It will use selected builder to build the example. + +- Build explicitly: + - `cd where_to_build_dir` + - `ninja` + - This is the builder chosen during the generation phase + +--- + +### CMake useful options +#### Generator types (alternative to **ninja** bulder): +- `-G Ninja` to build with __ninja__ builder +- `-G "Unix Makefiles"` to build with __make__ builder +- `-G "Visual Studio 17 2022" -A x64` to create a VS 2022 solution (.sln) file, Windows only + - **Native build only** + - Not **officially** supported to build Google Dawn + +Example: +- using **make** instead **ninja**: + - `cmake -G "Unix Makefiles" -DIMGUI_DAWN_DIR=path_to_sdk_dir -B where_to_build_dir` + +**Syntax is case sensitive and the "" are necessary in case of spaces between words* + +#### Directories +- The directory path can be absolute or relative (starting from the current directory) +- It's necessary to use different `where_to_build_dir` for different CMake generations + + +#### Build type +The default build type is **Debug** +It is possible to use a different build type using: +- `-DCMAKE_BUILD_TYPE=Release` +- `-DCMAKE_BUILD_TYPE=MinSizeRel` +- `-DCMAKE_BUILD_TYPE=RelWithDebInfo` + +Example: +- building **Release**: + - `cmake -G ninja -DIMGUI_WGPU_DIR=path_to_sdk_dir -DCMAKE_BUILD_TYPE=Release -B where_to_build_dir ` + +#### GLFW / SDL2 / SDL3 includes, libraries, search paths and package manager + +Includes and libraries, by default, are searched in system/compiler paths (environment variables): you can add the path to your development tools to the environment variables without having to modify the `CMakeLists.txt` file. +- e.g. CLang search in path specified from the following environment variables: + - include files: CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH + - library files: LIBRARY_PATH + +If you are using a package manager (**vcpkg** / **conan** / ... ) you need/can to specify it, adding to cmake command: +- `-DCMAKE_TOOLCHAIN_FILE=path/to/package_manager.cmake` + +Examples: + +- using **vcpkg** package manager it's necessary adding: + - `-DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake` + +- full cmake command using **vcpkg** package manager: + - `cmake -G Ninja -DIMGUI_DAWN_DIR=path_to_sdk_dir -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake -B where_to_build_dir` + +--- + + +### Using makefile - You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions @@ -10,6 +151,8 @@ - Requires recent Emscripten as WGPU is still a work-in-progress API. +--- + ## How to Run To run on a local machine: diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 88c504007..9ea267154 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -12,26 +12,31 @@ #include "imgui_impl_glfw.h" #include "imgui_impl_wgpu.h" #include +#include #include // This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. #ifdef __EMSCRIPTEN__ #include #include +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) #include -#include "../libs/emscripten/emscripten_mainloop_stub.h" -#else -#include #endif #include #include +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#else +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +#include +#endif +#endif // Data static WGPUInstance wgpu_instance = nullptr; static WGPUDevice wgpu_device = nullptr; static WGPUSurface wgpu_surface = nullptr; -static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm; -static WGPUSwapChain wgpu_swap_chain = nullptr; +static WGPUQueue wgpu_queue = nullptr; +static WGPUSurfaceConfiguration wgpu_surface_configuration = {}; static int wgpu_surface_width = 1280; static int wgpu_surface_height = 800; @@ -43,33 +48,11 @@ static void glfw_error_callback(int error, const char* description) printf("GLFW Error %d: %s\n", error, description); } -static void wgpu_error_callback(WGPUErrorType error_type, const char* message, void*) -{ - const char* error_type_lbl = ""; - switch (error_type) - { - case WGPUErrorType_Validation: error_type_lbl = "Validation"; break; - case WGPUErrorType_OutOfMemory: error_type_lbl = "Out of memory"; break; - case WGPUErrorType_Unknown: error_type_lbl = "Unknown"; break; - case WGPUErrorType_DeviceLost: error_type_lbl = "Device lost"; break; - default: error_type_lbl = "Unknown"; - } - printf("%s error: %s\n", error_type_lbl, message); -} - static void ResizeSurface(int width, int height) { - if (wgpu_swap_chain) - wgpuSwapChainRelease(wgpu_swap_chain); - wgpu_surface_width = width; - wgpu_surface_height = height; - WGPUSwapChainDescriptor swap_chain_desc = {}; - swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment; - swap_chain_desc.format = wgpu_preferred_fmt; - swap_chain_desc.width = width; - swap_chain_desc.height = height; - swap_chain_desc.presentMode = WGPUPresentMode_Fifo; - wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc); + wgpu_surface_configuration.width = wgpu_surface_width = width; + wgpu_surface_configuration.height = wgpu_surface_height = height; + wgpuSurfaceConfigure(wgpu_surface, &wgpu_surface_configuration); } // Main code @@ -98,7 +81,7 @@ int main(int, char**) glfwTerminate(); return 1; } - ResizeSurface(wgpu_surface_width, wgpu_surface_height); + glfwShowWindow(window); // Setup Dear ImGui context @@ -125,7 +108,7 @@ int main(int, char**) ImGui_ImplWGPU_InitInfo init_info; init_info.Device = wgpu_device; init_info.NumFramesInFlight = 3; - init_info.RenderTargetFormat = wgpu_preferred_fmt; + init_info.RenderTargetFormat = wgpu_surface_configuration.format; init_info.DepthStencilFormat = WGPUTextureFormat_Undefined; ImGui_ImplWGPU_Init(&init_info); @@ -181,6 +164,23 @@ int main(int, char**) if (width != wgpu_surface_width || height != wgpu_surface_height) ResizeSurface(width, height); + // Check surface status for error. If texture is not optimal, try to reconfigure the surface. + WGPUSurfaceTexture surface_texture; + wgpuSurfaceGetCurrentTexture(wgpu_surface, &surface_texture); + if (ImGui_ImplWGPU_IsSurfaceStatusError(surface_texture.status)) + { + fprintf(stderr, "Unrecoverable Surface Texture status=%#.8x\n", surface_texture.status); + abort(); + } + if (ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(surface_texture.status)) + { + if (surface_texture.texture) + wgpuTextureRelease(surface_texture.texture); + if (width > 0 && height > 0) + ResizeSurface(width, height); + continue; + } + // Start the Dear ImGui frame ImGui_ImplWGPU_NewFrame(); ImGui_ImplGlfw_NewFrame(); @@ -226,17 +226,21 @@ int main(int, char**) // Rendering ImGui::Render(); -#ifndef __EMSCRIPTEN__ - // Tick needs to be called in Dawn to display validation errors - wgpuDeviceTick(wgpu_device); -#endif + WGPUTextureViewDescriptor view_desc = {}; + view_desc.format = wgpu_surface_configuration.format; + view_desc.dimension = WGPUTextureViewDimension_2D ; + view_desc.mipLevelCount = WGPU_MIP_LEVEL_COUNT_UNDEFINED; + view_desc.arrayLayerCount = WGPU_ARRAY_LAYER_COUNT_UNDEFINED; + view_desc.aspect = WGPUTextureAspect_All; + + WGPUTextureView texture_view = wgpuTextureCreateView(surface_texture.texture, &view_desc); WGPURenderPassColorAttachment color_attachments = {}; color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED; color_attachments.loadOp = WGPULoadOp_Clear; color_attachments.storeOp = WGPUStoreOp_Store; color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; - color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain); + color_attachments.view = texture_view; WGPURenderPassDescriptor render_pass_desc = {}; render_pass_desc.colorAttachmentCount = 1; @@ -252,14 +256,16 @@ int main(int, char**) WGPUCommandBufferDescriptor cmd_buffer_desc = {}; WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc); - WGPUQueue wgpu_queue = wgpuDeviceGetQueue(wgpu_device); wgpuQueueSubmit(wgpu_queue, 1, &cmd_buffer); #ifndef __EMSCRIPTEN__ - wgpuSwapChainPresent(wgpu_swap_chain); + wgpuSurfacePresent(wgpu_surface); + // Tick needs to be called in Dawn to display validation errors +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) + wgpuDeviceTick(wgpu_device); #endif - - wgpuTextureViewRelease(color_attachments.view); +#endif + wgpuTextureViewRelease(texture_view); wgpuRenderPassEncoderRelease(pass); wgpuCommandEncoderRelease(encoder); wgpuCommandBufferRelease(cmd_buffer); @@ -273,75 +279,298 @@ int main(int, char**) ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); + wgpuSurfaceUnconfigure(wgpu_surface); + wgpuSurfaceRelease(wgpu_surface); + wgpuQueueRelease(wgpu_queue); + wgpuDeviceRelease(wgpu_device); + wgpuInstanceRelease(wgpu_instance); + glfwDestroyWindow(window); glfwTerminate(); return 0; } -#ifndef __EMSCRIPTEN__ -static WGPUAdapter RequestAdapter(WGPUInstance instance) -{ - auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* message, void* pUserData) - { - if (status == WGPURequestAdapterStatus_Success) - *(WGPUAdapter*)pUserData = adapter; - else - printf("Could not get WebGPU adapter: %s\n", message); - }; - WGPUAdapter adapter; - wgpuInstanceRequestAdapter(instance, nullptr, onAdapterRequestEnded, (void*)&adapter); - return adapter; -} +// GLFW helper to create a WebGPU surface, used only in WGPU-Native. DAWN-Native already has a built-in function +// As of today (2025/10) there is no "official" support in GLFW to create a surface for WebGPU backend +// This stub uses "low level" GLFW calls to acquire information from a specific Window Manager. +// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. +#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) -static WGPUDevice RequestDevice(WGPUAdapter adapter) +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) +#define GLFW_HAS_X11_OR_WAYLAND 1 +#else +#define GLFW_HAS_X11_OR_WAYLAND 0 +#endif +#ifdef _WIN32 +#undef APIENTRY +#ifndef GLFW_EXPOSE_NATIVE_WIN32 // for glfwGetWin32Window() +#define GLFW_EXPOSE_NATIVE_WIN32 +#endif +#elif defined(__APPLE__) +#ifndef GLFW_EXPOSE_NATIVE_COCOA // for glfwGetCocoaWindow() +#define GLFW_EXPOSE_NATIVE_COCOA +#endif +#elif GLFW_HAS_X11_OR_WAYLAND +#ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Display(), glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) +#define GLFW_EXPOSE_NATIVE_X11 +#endif +#ifndef GLFW_EXPOSE_NATIVE_WAYLAND +#if defined(__has_include) && __has_include() +#define GLFW_EXPOSE_NATIVE_WAYLAND +#endif +#endif +#endif +#include +#undef Status // X11 headers are leaking this. + +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, GLFWwindow* window) { - auto onDeviceRequestEnded = [](WGPURequestDeviceStatus status, WGPUDevice device, const char* message, void* pUserData) + ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; + create_info.Instance = instance; +#if defined(GLFW_EXPOSE_NATIVE_COCOA) { - if (status == WGPURequestDeviceStatus_Success) - *(WGPUDevice*)pUserData = device; - else - printf("Could not get WebGPU device: %s\n", message); - }; - WGPUDevice device; - wgpuAdapterRequestDevice(adapter, nullptr, onDeviceRequestEnded, (void*)&device); - return device; + create_info.System = "cocoa"; + create_info.RawWindow = (void*)glfwGetCocoaWindow(window); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(GLFW_EXPOSE_NATIVE_WAYLAND) + if (glfwGetPlatform() == GLFW_PLATFORM_WAYLAND) + { + create_info.System = "wayland"; + create_info.RawDisplay = (void*)glfwGetWaylandDisplay(); + create_info.RawSurface = (void*)glfwGetWaylandWindow(window); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(GLFW_EXPOSE_NATIVE_X11) + if (glfwGetPlatform() == GLFW_PLATFORM_X11) + { + create_info.System = "x11"; + create_info.RawWindow = (void*)glfwGetX11Window(window); + create_info.RawDisplay = (void*)glfwGetX11Display(); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(GLFW_EXPOSE_NATIVE_WIN32) + { + create_info.System = "win32"; + create_info.RawWindow = (void*)glfwGetWin32Window(window); + create_info.RawInstance = (void*)::GetModuleHandle(NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#else +#error "Unsupported WebGPU native platform!" +#endif + return nullptr; } #endif +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +static WGPUAdapter RequestAdapter(wgpu::Instance& instance) +{ + wgpu::Adapter acquired_adapter; + wgpu::RequestAdapterOptions adapter_options; + auto onRequestAdapter = [&](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter, wgpu::StringView message) + { + if (status != wgpu::RequestAdapterStatus::Success) + { + printf("Failed to get an adapter: %s\n", message.data); + return; + } + acquired_adapter = std::move(adapter); + }; + + // Synchronously (wait until) acquire Adapter + wgpu::Future waitAdapterFunc { instance.RequestAdapter(&adapter_options, wgpu::CallbackMode::WaitAnyOnly, onRequestAdapter) }; + wgpu::WaitStatus waitStatusAdapter = instance.WaitAny(waitAdapterFunc, UINT64_MAX); + IM_ASSERT(acquired_adapter != nullptr && waitStatusAdapter == wgpu::WaitStatus::Success && "Error on Adapter request"); + return acquired_adapter.MoveToCHandle(); +} + +static WGPUDevice RequestDevice(wgpu::Instance& instance, wgpu::Adapter& adapter) +{ + // Set device callback functions + wgpu::DeviceDescriptor device_desc; + device_desc.SetDeviceLostCallback(wgpu::CallbackMode::AllowSpontaneous, + [](const wgpu::Device&, wgpu::DeviceLostReason type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetDeviceLostReasonName((WGPUDeviceLostReason)type), msg.data); } + ); + device_desc.SetUncapturedErrorCallback( + [](const wgpu::Device&, wgpu::ErrorType type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetErrorTypeName((WGPUErrorType)type), msg.data); } + ); + + wgpu::Device acquired_device; + auto onRequestDevice = [&](wgpu::RequestDeviceStatus status, wgpu::Device local_device, wgpu::StringView message) + { + if (status != wgpu::RequestDeviceStatus::Success) + { + printf("Failed to get an device: %s\n", message.data); + return; + } + acquired_device = std::move(local_device); + }; + + // Synchronously (wait until) get Device + wgpu::Future waitDeviceFunc { adapter.RequestDevice(&device_desc, wgpu::CallbackMode::WaitAnyOnly, onRequestDevice) }; + wgpu::WaitStatus waitStatusDevice = instance.WaitAny(waitDeviceFunc, UINT64_MAX); + IM_ASSERT(acquired_device != nullptr && waitStatusDevice == wgpu::WaitStatus::Success && "Error on Device request"); + return acquired_device.MoveToCHandle(); +} +#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#ifdef __EMSCRIPTEN__ +// Adapter and device initialization via JS +EM_ASYNC_JS( void, getAdapterAndDeviceViaJS, (), +{ + if (!navigator.gpu) + throw Error("WebGPU not supported."); + const adapter = await navigator.gpu.requestAdapter(); + const device = await adapter.requestDevice(); + Module.preinitializedWebGPUDevice = device; +} ); +#else // __EMSCRIPTEN__ +static void handle_request_adapter(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void* userdata1, void* userdata2) +{ + if (status == WGPURequestAdapterStatus_Success) + { + WGPUAdapter* extAdapter = (WGPUAdapter*)userdata1; + *extAdapter = adapter; + } + else + { + printf("Request_adapter status=%#.8x message=%.*s\n", status, (int) message.length, message.data); + } +} + +static void handle_request_device(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView message, void* userdata1, void* userdata2) +{ + if (status == WGPURequestDeviceStatus_Success) + { + WGPUDevice* extDevice = (WGPUDevice*)userdata1; + *extDevice = device; + } + else + { + printf("Request_device status=%#.8x message=%.*s\n", status, (int) message.length, message.data); + } +} + +static WGPUAdapter RequestAdapter(WGPUInstance& instance) +{ + WGPURequestAdapterOptions adapter_options = {}; + + WGPUAdapter local_adapter; + WGPURequestAdapterCallbackInfo adapterCallbackInfo = {}; + adapterCallbackInfo.callback = handle_request_adapter; + adapterCallbackInfo.userdata1 = &local_adapter; + + wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + IM_ASSERT(local_adapter && "Error on Adapter request"); + return local_adapter; +} + +static WGPUDevice RequestDevice(WGPUAdapter& adapter) +{ + WGPUDevice local_device; + WGPURequestDeviceCallbackInfo deviceCallbackInfo = {}; + deviceCallbackInfo.callback = handle_request_device; + deviceCallbackInfo.userdata1 = &local_device; + wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + IM_ASSERT(local_device && "Error on Device request"); + return local_device; +} +#endif // __EMSCRIPTEN__ +#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU + static bool InitWGPU(GLFWwindow* window) { - wgpu::Instance instance = wgpuCreateInstance(nullptr); + WGPUTextureFormat preferred_fmt = WGPUTextureFormat_Undefined; // acquired from SurfaceCapabilities + // Google DAWN backend: Adapter and Device acquisition, Surface creation +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) + wgpu::InstanceDescriptor instance_desc = {}; + static constexpr wgpu::InstanceFeatureName timedWaitAny = wgpu::InstanceFeatureName::TimedWaitAny; + instance_desc.requiredFeatureCount = 1; + instance_desc.requiredFeatures = &timedWaitAny; + wgpu::Instance instance = wgpu::CreateInstance(&instance_desc); + + wgpu::Adapter adapter = RequestAdapter(instance); + ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter.Get()); + + wgpu_device = RequestDevice(instance, adapter); + + // Create the surface. #ifdef __EMSCRIPTEN__ - wgpu_device = emscripten_webgpu_get_device(); - if (!wgpu_device) - return false; - - wgpu::SurfaceDescriptorFromCanvasHTMLSelector canvas_desc = {}; + wgpu::EmscriptenSurfaceSourceCanvasHTMLSelector canvas_desc = {}; canvas_desc.selector = "#canvas"; + wgpu::SurfaceDescriptor surface_desc = {}; surface_desc.nextInChain = &canvas_desc; - wgpu::Surface surface = instance.CreateSurface(&surface_desc); - - wgpu::Adapter adapter = {}; - wgpu_preferred_fmt = (WGPUTextureFormat)surface.GetPreferredFormat(adapter); + wgpu_surface = instance.CreateSurface(&surface_desc).MoveToCHandle(); #else - WGPUAdapter adapter = RequestAdapter(instance.Get()); - if (!adapter) - return false; - wgpu_device = RequestDevice(adapter); - - wgpu::Surface surface = wgpu::glfw::CreateSurfaceForWindow(instance, window); - if (!surface) - return false; - wgpu_preferred_fmt = WGPUTextureFormat_BGRA8Unorm; + wgpu_surface = CreateWGPUSurface(instance.Get(), window); #endif + if (!wgpu_surface) + return false; // Moving Dawn objects into WGPU handles wgpu_instance = instance.MoveToCHandle(); - wgpu_surface = surface.MoveToCHandle(); - wgpuDeviceSetUncapturedErrorCallback(wgpu_device, wgpu_error_callback, nullptr); + WGPUSurfaceCapabilities surface_capabilities = {}; + wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; + + // WGPU backend: Adapter and Device acquisition, Surface creation +#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) + wgpu_instance = wgpuCreateInstance(nullptr); + +#ifdef __EMSCRIPTEN__ + getAdapterAndDeviceViaJS(); + + wgpu_device = emscripten_webgpu_get_device(); + IM_ASSERT(wgpu_device != nullptr && "Error creating the Device"); + + WGPUSurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {}; + html_surface_desc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; + html_surface_desc.selector = "#canvas"; + + WGPUSurfaceDescriptor surface_desc = {}; + surface_desc.nextInChain = &html_surface_desc.chain; + + // Create the surface. + wgpu_surface = wgpuInstanceCreateSurface(wgpu_instance, &surface_desc); + preferred_fmt = wgpuSurfaceGetPreferredFormat(wgpu_surface, {} /* adapter */); +#else // __EMSCRIPTEN__ + wgpuSetLogCallback( + [](WGPULogLevel level, WGPUStringView msg, void* userdata) { fprintf(stderr, "%s: %.*s\n", ImGui_ImplWGPU_GetLogLevelName(level), (int)msg.length, msg.data); }, nullptr + ); + wgpuSetLogLevel(WGPULogLevel_Warn); + + WGPUAdapter adapter = RequestAdapter(wgpu_instance); + ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter); + + wgpu_device = RequestDevice(adapter); + + // Create the surface. + wgpu_surface = CreateWGPUSurface(wgpu_instance, window); + if (!wgpu_surface) + return false; + + WGPUSurfaceCapabilities surface_capabilities = {}; + wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; +#endif // __EMSCRIPTEN__ +#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU + + wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; + wgpu_surface_configuration.alphaMode = WGPUCompositeAlphaMode_Auto; + wgpu_surface_configuration.usage = WGPUTextureUsage_RenderAttachment; + wgpu_surface_configuration.width = wgpu_surface_width; + wgpu_surface_configuration.height = wgpu_surface_height; + wgpu_surface_configuration.device = wgpu_device; + wgpu_surface_configuration.format = preferred_fmt; + + wgpuSurfaceConfigure(wgpu_surface, &wgpu_surface_configuration); + wgpu_queue = wgpuDeviceGetQueue(wgpu_device); + return true; } diff --git a/examples/example_glfw_wgpu/web/index.html b/examples/example_glfw_wgpu/web/index.html deleted file mode 100644 index a2a91c4a7..000000000 --- a/examples/example_glfw_wgpu/web/index.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - Dear ImGui Emscripten+GLFW+WebGPU example - - - - - - - From ff672b2db39002c7334c142544f9eddfc68652f0 Mon Sep 17 00:00:00 2001 From: BrutPitt Date: Fri, 31 Oct 2025 18:59:34 +0100 Subject: [PATCH 1452/2359] Examples: SDL2+WebGPU, SDL3+WebGPU: add new examples. (#8381) --- docs/CHANGELOG.txt | 2 + examples/example_sdl2_wgpu/CMakeLists.txt | 197 +++++++ .../example_sdl2_wgpu/Makefile.emscripten | 103 ++++ examples/example_sdl2_wgpu/README.md | 167 ++++++ examples/example_sdl2_wgpu/main.cpp | 539 +++++++++++++++++ examples/example_sdl3_wgpu/CMakeLists.txt | 199 +++++++ .../example_sdl3_wgpu/Makefile.emscripten | 103 ++++ examples/example_sdl3_wgpu/README.md | 167 ++++++ examples/example_sdl3_wgpu/main.cpp | 553 ++++++++++++++++++ 9 files changed, 2030 insertions(+) create mode 100644 examples/example_sdl2_wgpu/CMakeLists.txt create mode 100644 examples/example_sdl2_wgpu/Makefile.emscripten create mode 100644 examples/example_sdl2_wgpu/README.md create mode 100644 examples/example_sdl2_wgpu/main.cpp create mode 100644 examples/example_sdl3_wgpu/CMakeLists.txt create mode 100644 examples/example_sdl3_wgpu/Makefile.emscripten create mode 100644 examples/example_sdl3_wgpu/README.md create mode 100644 examples/example_sdl3_wgpu/main.cpp diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 88ef499c1..bea104171 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -102,6 +102,8 @@ Other Changes: latest Dawn-Native and WGPU-Native. (#8381, #8567, #8191, #7435) [@brutpitt] - GLFW+WebGPU: removed unnecessary ImGui_ImplWGPU_InvalidateDeviceObjects() call during surface resize. (#8381) + - SDL2+WebGPU: added new example (Emscripten + native Dawn/WGPU). (#8381) [@brutpitt] + - SDL3+WebGPU: added new example (Emscripten + native Dawn/WGPU). (#8381) [@brutpitt] ----------------------------------------------------------------------- diff --git a/examples/example_sdl2_wgpu/CMakeLists.txt b/examples/example_sdl2_wgpu/CMakeLists.txt new file mode 100644 index 000000000..815c702f6 --- /dev/null +++ b/examples/example_sdl2_wgpu/CMakeLists.txt @@ -0,0 +1,197 @@ +# Building for desktop (WebGPU-native) with Dawn: +# 1. git clone https://github.com/google/dawn dawn +# 2. cmake -B build -DIMGUI_DAWN_DIR=dawn +# 3. cmake --build build +# The resulting binary will be found at one of the following locations: +# * build/Debug/example_sdl2_wgpu[.exe] +# * build/example_sdl2_wgpu[.exe] + +# Building for desktop (WGPU-Native) with WGPU-Native: +# 1. download WGPU-Native autogenerated binary modules for your platform/compiler from: https://github.com/gfx-rs/wgpu-native/releases +# 2. unzip the downloaded file in your_preferred_folder +# 3. cmake -B build -DIMGUI_WGPU_DIR=your_preferred_folder ("full path" or "relative" starting from current directory) +# 4. cmake --build build +# The resulting binary will be found at one of the following locations: +# * build/Debug/example_sdl2_wgpu[.exe] +# * build/example_sdl2_wgpu[.exe] + +# Building for Emscripten: +# 1. Install Emscripten SDK following the instructions: https://emscripten.org/docs/getting_started/downloads.html +# 2. Install Ninja build system +# 3. emcmake cmake -G Ninja -B build +# (optional) -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py", see ReadMe.md +# 3. cmake --build build +# 4. emrun build/index.html + +cmake_minimum_required(VERSION 3.22) # Dawn requires CMake >= 3.22 +project(imgui_example_sdl2_wgpu C CXX) + +set(IMGUI_EXECUTABLE example_sdl2_wgpu) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE) +endif() + +set(CMAKE_CXX_STANDARD 17) # Dawn requires C++17 + +# Dear ImGui +set(IMGUI_DIR ../../) + +# ImGui example commons source files +set(IMGUI_EXAMPLE_SOURCE_FILES + main.cpp + # backend files + ${IMGUI_DIR}/backends/imgui_impl_sdl2.cpp + ${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp + # Dear ImGui files + ${IMGUI_DIR}/imgui.cpp + ${IMGUI_DIR}/imgui_draw.cpp + ${IMGUI_DIR}/imgui_demo.cpp + ${IMGUI_DIR}/imgui_tables.cpp + ${IMGUI_DIR}/imgui_widgets.cpp +) + +if(EMSCRIPTEN) + if(NOT IMGUI_EMSCRIPTEN_WEBGPU_FLAG) # if IMGUI_EMSCRIPTEN_WEBGPU_FLAG not used, set by current EMSCRIPTEN version + if(EMSCRIPTEN_VERSION VERSION_GREATER_EQUAL "4.0.10") + set(IMGUI_EMSCRIPTEN_WEBGPU_FLAG "--use-port=emdawnwebgpu" CACHE STRING "Choose between --use-port=emdawnwebgpu (Dawn implementation of EMSCRIPTEN) and -sUSE_WEBGPU=1 (WGPU implementation of EMSCRIPTEN, deprecated in 4.0.10): default to --use-port=emdawnwebgpu for EMSCRIPTEN >= 4.0.10") + else() + set(IMGUI_EMSCRIPTEN_WEBGPU_FLAG "-sUSE_WEBGPU=1" CACHE STRING "Use -sUSE_WEBGPU=1 for EMSCRIPTEN WGPU implementation") + endif() + else() # if IMGUI_EMSCRIPTEN_WEBGPU_FLAG used, check correct version + if(EMSCRIPTEN_VERSION VERSION_LESS "4.0.10" AND "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" MATCHES "emdawnwebgpu") + # it's necessary EMSCRIPTEN >= v4.0.10 (although "--use-port=path/to/emdawnwebgpu.port.py" is supported/tested from v4.0.8) + message(FATAL_ERROR "emdawnwebgpu needs EMSCRIPTEN version >= 4.0.10") + endif() + endif() + + add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1) +else() # Native/Desktop build + find_package(SDL2 REQUIRED) # SDL_MAIN_HANDLED + + if(NOT IMGUI_DAWN_DIR AND NOT IMGUI_WGPU_DIR) # if it's Native/Desktop build, IMGUI_DAWN_DIR or IMGUI_WGPU_DIR must be specified + message(FATAL_ERROR "Please specify the Dawn or WGPU base directory") + endif() + + if(IMGUI_DAWN_DIR AND IMGUI_WGPU_DIR) # both IMGUI_DAWN_DIR and IMGUI_WGPU_DIR cannot be set + message(FATAL_ERROR "Please specify only one between Dawn / WGPU base directory") + endif() + + if(APPLE) # Add SDL2 module to get Surface, with libs and file property for MacOS build + set_source_files_properties(${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") + set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") + endif() + + if(IMGUI_DAWN_DIR) # DAWN-Native build options + set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") + if(NOT IMGUI_DAWN_DIR) + message(FATAL_ERROR "Please specify the Dawn repository by setting IMGUI_DAWN_DIR") + endif() + + option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 + + option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) + set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") + + # Dawn builds many things by default - disable things we don't need + option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) + option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) + option(TINT_BUILD_DOCS "Build documentation" OFF) + option(TINT_BUILD_TESTS "Build tests" OFF) + if(NOT APPLE) + option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) + endif() + if(WIN32) + option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) + option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) + option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) + option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) + option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) + option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) + option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) + endif() + # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time + # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) + if(LINUX) + if($ENV{XDG_SESSION_TYPE} MATCHES wayland) + option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + endif() + endif() + + add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) + + set(LIBRARIES webgpu_dawn ${OS_LIBRARIES}) + else() # WGPU-Native build options + + set(WGPU_NATIVE_LIB_DIR ${IMGUI_WGPU_DIR}/lib) + find_library(WGPU_LIBRARY NAMES libwgpu_native.a wgpu_native.lib wgpu_native HINTS ${WGPU_NATIVE_LIB_DIR} REQUIRED) + if(WIN32) + set(OS_LIBRARIES d3dcompiler ws2_32 userenv bcrypt ntdll opengl32 Propsys RuntimeObject) + elseif(UNIX AND NOT APPLE) + set(OS_LIBRARIES "-lm -ldl") + endif() + + set(LIBRARIES ${WGPU_LIBRARY} ${OS_LIBRARIES}) + endif() +endif() + +add_executable(${IMGUI_EXECUTABLE} ${IMGUI_EXAMPLE_SOURCE_FILES}) + +target_include_directories(${IMGUI_EXECUTABLE} PUBLIC + ${IMGUI_DIR} + ${IMGUI_DIR}/backends + ${SDL2_INCLUDE_DIRS} +) + +target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_EXAMPLE_SDL2_WGPU") + +# compiler option only for IMGUI_EXAMPLE_SOURCE_FILES +if (MSVC) + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC /W4) # warning level 4 +else() + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC -Wall) # -Wextra -Wpedantic +endif() + +# IMGUI_IMPL_WEBGPU_BACKEND_DAWN/WGPU internal define is set according to: +# EMSCRIPTEN: by used FLAG +# --use-port=emdawnwebgpu --> IMGUI_IMPL_WEBGPU_BACKEND_DAWN enabled (+EMSCRIPTEN) +# -sUSE_WEBGPU=1 --> IMGUI_IMPL_WEBGPU_BACKEND_WGPU enabled (+EMSCRIPTEN) +# NATIVE: by used SDK installation directory +# if IMGUI_DAWN_DIR is valid --> IMGUI_IMPL_WEBGPU_BACKEND_DAWN enabled +# if IMGUI_WGPU_DIR is valid --> IMGUI_IMPL_WEBGPU_BACKEND_WGPU enabled + +if(NOT EMSCRIPTEN) # WegGPU-Native settings + if(IMGUI_DAWN_DIR) + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + else() + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") + target_include_directories(${IMGUI_EXECUTABLE} PUBLIC ${IMGUI_WGPU_DIR}/include) + endif() + + target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp PUBLIC ${LIBRARIES} ${SDL2_LIBRARIES}) +else() # Emscripten settings + set(CMAKE_EXECUTABLE_SUFFIX ".html") + + if("${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" MATCHES "emdawnwebgpu") + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}") + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + else() + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") + endif() + message(STATUS "Using ${IMGUI_EMSCRIPTEN_WEBGPU_FLAG} WebGPU implementation") + + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC "-sUSE_SDL=2") + target_link_options(${IMGUI_EXECUTABLE} PRIVATE + "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" + "-sUSE_SDL=2" + "-sWASM=1" + "-sASYNCIFY=1" + "-sALLOW_MEMORY_GROWTH=1" + "-sNO_EXIT_RUNTIME=0" + "-sASSERTIONS=1" + "-sDISABLE_EXCEPTION_CATCHING=1" + "-sNO_FILESYSTEM=1" + "--shell-file=${CMAKE_CURRENT_LIST_DIR}/../libs/emscripten/shell_minimal.html" + ) + set_target_properties(${IMGUI_EXECUTABLE} PROPERTIES OUTPUT_NAME "index") +endif() diff --git a/examples/example_sdl2_wgpu/Makefile.emscripten b/examples/example_sdl2_wgpu/Makefile.emscripten new file mode 100644 index 000000000..69bcb00e7 --- /dev/null +++ b/examples/example_sdl2_wgpu/Makefile.emscripten @@ -0,0 +1,103 @@ +# +# Makefile to use with emscripten +# See https://emscripten.org/docs/getting_started/downloads.html +# for installation instructions. +# +# This Makefile assumes you have loaded emscripten's environment. +# (On Windows, you may need to execute emsdk_env.bat or encmdprompt.bat ahead) +# +# Running `make -f Makefile.emscripten` will produce three files: +# - web/index.html +# - web/index.js +# - web/index.wasm +# +# All three are needed to run the demo. + +CC = emcc +CXX = em++ +WEB_DIR = web +EXE = $(WEB_DIR)/index.html +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl2.cpp $(IMGUI_DIR)/backends/imgui_impl_wgpu.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) +CPPFLAGS = +LDFLAGS = +EMS = + +##--------------------------------------------------------------------- +## EMSCRIPTEN OPTIONS +##--------------------------------------------------------------------- + +# ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) +EMS += -s USE_SDL=2 +EMS += -s DISABLE_EXCEPTION_CATCHING=1 +LDFLAGS += -s WASM=1 +LDFLAGS += -s ALLOW_MEMORY_GROWTH=1 +LDFLAGS += -s ASYNCIFY=1 +LDFLAGS += -s NO_EXIT_RUNTIME=0 +LDFLAGS += -s ASSERTIONS=1 + +# (1) Using legacy WebGPU implementation (Emscripten < 4.0.10) +#EMS += -DIMGUI_IMPL_WEBGPU_BACKEND_WGPU +#LDFLAGS += -s USE_WEBGPU=1 + +# or (2) Using newer Dawn-based WebGPU port (Emscripten >= 4.0.10) +EMS += --use-port=emdawnwebgpu +LDFLAGS += --use-port=emdawnwebgpu + +# Build as single file (binary text encoded in .html file) +#LDFLAGS += -sSINGLE_FILE + +# Emscripten allows preloading a file or folder to be accessible at runtime. +# The Makefile for this example project suggests embedding the misc/fonts/ folder into our application, it will then be accessible as "/fonts" +# See documentation for more details: https://emscripten.org/docs/porting/files/packaging_files.html +# (Default value is 0. Set to 1 to enable file-system and include the misc/fonts/ folder as part of the build.) +USE_FILE_SYSTEM ?= 0 +ifeq ($(USE_FILE_SYSTEM), 0) +LDFLAGS += -s NO_FILESYSTEM=1 +CPPFLAGS += -DIMGUI_DISABLE_FILE_FUNCTIONS +endif +ifeq ($(USE_FILE_SYSTEM), 1) +LDFLAGS += --no-heap-copy --preload-file ../../misc/fonts@/fonts +endif + +##--------------------------------------------------------------------- +## FINAL BUILD FLAGS +##--------------------------------------------------------------------- + +CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +#CPPFLAGS += -g +CPPFLAGS += -Wall -Wformat -Os $(EMS) +LDFLAGS += --shell-file ../libs/emscripten/shell_minimal.html +LDFLAGS += $(EMS) + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(EXE) + +$(WEB_DIR): + mkdir $@ + +serve: all + python3 -m http.server -d $(WEB_DIR) + +$(EXE): $(OBJS) $(WEB_DIR) + $(CXX) -o $@ $(OBJS) $(LDFLAGS) + +clean: + rm -f $(EXE) $(OBJS) $(WEB_DIR)/*.js $(WEB_DIR)/*.wasm $(WEB_DIR)/*.wasm.pre diff --git a/examples/example_sdl2_wgpu/README.md b/examples/example_sdl2_wgpu/README.md new file mode 100644 index 000000000..cdfd032da --- /dev/null +++ b/examples/example_sdl2_wgpu/README.md @@ -0,0 +1,167 @@ +## How to Build + + +--- + +### Using CMake +#### Building for desktop (WebGPU-native) with Google Dawn: + 1. `git clone https://github.com/google/dawn dawn` + 2. `cmake -B build -DIMGUI_DAWN_DIR=dawn` + 3. `cmake --build build` +The resulting binary will be found at one of the following locations: + * build/Debug/example_sdl2_wgpu[.exe] + * build/example_sdl2_wgpu[.exe] + +#### Building for desktop (WebGPU-Native) with WGPU: + 1. download WGPU-Native autogenerated binary modules for your platform/compiler from: https://github.com/gfx-rs/wgpu-native/releases + 2. unzip the downloaded file in `your_preferred_folder` + 3. `cmake -B build -DIMGUI_WGPU_DIR=your_preferred_folder` ("full path" or "relative" starting from current directory) + 4. `cmake --build build` +The resulting binary will be found at one of the following locations: + * build/Debug/example_sdl2_wgpu[.exe] + * build/example_sdl2_wgpu[.exe] + +#### Building for Emscripten: + 1. Install Emscripten SDK following the instructions: https://emscripten.org/docs/getting_started/downloads.html + 2. Install Ninja build system + 3. `emcmake cmake -G Ninja -B build` + - (optional) `-DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py"`, see below + 4. `cmake --build build` + +#### Sync Emscripten with latest Google Dawn: +If you want to sync Emscripten with latest DAWN release it's necessary to download the `port-emdawnwgpu-package` (released daily by Google) here: +https://github.com/google/dawn/releases +Unpack it in your preferred folder and to replace the step 3 with: + +3. `emcmake cmake -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py" -G Ninja -B build` + +**N.B.** +For the WASM code produced by Emscripten to work correctly, it will also be necessary to have the "corresponding" (or newer) version of Google Canary (nightly build for developers) that includes the latest changes + + +--- + +### CMake by step + +#### Generate Dawn Native: + +- `cmake -G Ninja -DIMGUI_DAWN_DIR=path_to_sdk_dir -B where_to_build_dir` + - Using `IMGUI_DAWN_DIR` set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + +#### Generate WGPU Native: + +- `cmake -G Ninja -DIMGUI_WGPU_DIR=path_to_sdk_dir -B where_to_build_dir` + + - Using `IMGUI_WGPU_DIR` set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten: + +- `emcmake cmake -G Ninja -B where_to_build_dir`\ +CMake checks the EMSCRIPEN version then: + - if EMS >= 4.0.10 uses `--use-port=emdawnwebgpu` flag to build + - it set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + - if EMS < 4.0.10 uses `-sUSE_WEBGPU=1` flag to build + - it set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten forcing `-sUSE_WEBGPU=1` deprecated flag even with EMS >= 4.0.10 +- `emcmake cmake -G Ninja -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="-sUSE_WEBGPU=1" -B where_to_build_dir` + - it set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten using external WebGPU library (emdawnwebgpu_pkg) +- `emcmake cmake -G Ninja -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path_to_emdawnwebgpu_pkg" -B where_to_build_dir` + - it set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + - *To use external WebGPU library it's necessary to have EMS >= 4.0.10 or the minimum requirements specified by the package:* + - https://github.com/google/dawn/releases + +#### Build time + +Once the procedure for the specific builder is generated, the build command is **always the same**: + +- Build using CMake + - `cmake --build where_to_build_dir` + - It will use selected builder to build the example. + +- Build explicitly: + - `cd where_to_build_dir` + - `ninja` + - This is the builder chosen during the generation phase + +--- + +### CMake useful options +#### Generator types (alternative to **ninja** bulder): +- `-G Ninja` to build with __ninja__ builder +- `-G "Unix Makefiles"` to build with __make__ builder +- `-G "Visual Studio 17 2022" -A x64` to create a VS 2022 solution (.sln) file, Windows only + - **Native build only** + - Not **officially** supported to build Google Dawn + +Example: +- using **make** instead **ninja**: + - `cmake -G "Unix Makefiles" -DIMGUI_DAWN_DIR=path_to_sdk_dir -B where_to_build_dir` + +**Syntax is case sensitive and the "" are necessary in case of spaces between words* + +#### Directories +- The directory path can be absolute or relative (starting from the current directory) +- It's necessary to use different `where_to_build_dir` for different CMake generations + + +#### Build type +The default build type is **Debug** +It is possible to use a different build type using: +- `-DCMAKE_BUILD_TYPE=Release` +- `-DCMAKE_BUILD_TYPE=MinSizeRel` +- `-DCMAKE_BUILD_TYPE=RelWithDebInfo` + +Example: +- building **Release**: + - `cmake -G ninja -DIMGUI_WGPU_DIR=path_to_sdk_dir -DCMAKE_BUILD_TYPE=Release -B where_to_build_dir ` + +#### GLFW / SDL2 / SDL3 includes, libraries, search paths and package manager + +Includes and libraries, by default, are searched in system/compiler paths (environment variables): you can add the path to your development tools to the environment variables without having to modify the `CMakeLists.txt` file. +- e.g. CLang search in path specified from the following environment variables: + - include files: CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH + - library files: LIBRARY_PATH + +If you are using a package manager (**vcpkg** / **conan** / ... ) you need/can to specify it, adding to cmake command: +- `-DCMAKE_TOOLCHAIN_FILE=path/to/package_manager.cmake` + +Examples: + +- using **vcpkg** package manager it's necessary adding: + - `-DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake` + +- full cmake command using **vcpkg** package manager: + - `cmake -G Ninja -DIMGUI_DAWN_DIR=path_to_sdk_dir -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake -B where_to_build_dir` + +--- + + +### Using makefile + +- You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions + +- Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools. + +- You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. + +- Then build using `make -f Makefile.emscripten` while in the `example_glfw_wgpu/` directory. + +- Requires recent Emscripten as WGPU is still a work-in-progress API. + +--- + +## How to Run + +To run on a local machine: +- Make sure your browse supports WGPU and it is enabled. WGPU is still WIP not enabled by default in most browser. +- `make serve` will use Python3 to spawn a local webserver, you can then browse http://localhost:8000 to access your build. +- Otherwise, generally you will need a local webserver: + - Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
+_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ + - Emscripten SDK has a handy `emrun` command: `emrun web/example_glfw_wgpu.html --browser firefox` which will spawn a temporary local webserver (in Firefox). See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. + - You may use Python 3 builtin webserver: `python -m http.server -d web` (this is what `make serve` uses). + - You may use Python 2 builtin webserver: `cd web && python -m SimpleHTTPServer`. + - If you are accessing the files over a network, certain browsers, such as Firefox, will restrict Gamepad API access to secure contexts only (e.g. https only). diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp new file mode 100644 index 000000000..1d95da572 --- /dev/null +++ b/examples/example_sdl2_wgpu/main.cpp @@ -0,0 +1,539 @@ +// Dear ImGui: standalone example application for using SDL2 + WebGPU +// - Emscripten is supported for publishing on web. See https://emscripten.org. +// - Dawn is used as a WebGPU implementation on desktop. + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#include "imgui.h" +#include "imgui_impl_sdl2.h" +#include "imgui_impl_wgpu.h" +#include +#include + +// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. +#ifdef __EMSCRIPTEN__ +#include +#include +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#include +#endif +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#endif + +#include +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +#include +#endif + +// Data +WGPUInstance wgpu_instance = nullptr; +WGPUDevice wgpu_device = nullptr; +WGPUSurface wgpu_surface = nullptr; +WGPUQueue wgpu_queue = nullptr; +WGPUSurfaceConfiguration wgpu_surface_configuration = {}; +int wgpu_surface_width = 1280; +int wgpu_surface_height = 800; + +// Forward declarations +static bool InitWGPU(SDL_Window* window); + +static void ResizeSurface(int width, int height) +{ + wgpu_surface_configuration.width = wgpu_surface_width = width; + wgpu_surface_configuration.height = wgpu_surface_height = height; + wgpuSurfaceConfigure(wgpu_surface, (WGPUSurfaceConfiguration*)&wgpu_surface_configuration); +} + +// Main code +int main(int, char**) +{ + // Setup SDL + SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER); + + // Create window with graphics context + float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0); + SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE; + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+WebGPU example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, wgpu_surface_width, wgpu_surface_height, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return 1; + } + + // Initialize WGPU + InitWGPU(window); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + + // Setup Platform/Renderer backends + ImGui_ImplSDL2_InitForOther(window); + ImGui_ImplWGPU_InitInfo init_info; + init_info.Device = wgpu_device; + init_info.NumFramesInFlight = 3; + init_info.RenderTargetFormat = wgpu_surface_configuration.format; + init_info.DepthStencilFormat = WGPUTextureFormat_Undefined; + ImGui_ImplWGPU_Init(&init_info); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. + //style.FontSizeBase = 20.0f; + //io.Fonts->AddFontDefault(); +#ifndef IMGUI_DISABLE_FILE_FUNCTIONS + //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf"); + //IM_ASSERT(font != nullptr); +#endif + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; +#ifdef __EMSCRIPTEN__ + // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. + // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. + io.IniFilename = nullptr; + EMSCRIPTEN_MAINLOOP_BEGIN +#else + while (!done) +#endif + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL2_ProcessEvent(&event); + if (event.type == SDL_QUIT) + done = true; + if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) + done = true; + } + + // React to changes in screen size + int width, height; + SDL_GetWindowSize(window, &width, &height); + if (width != wgpu_surface_width || height != wgpu_surface_height) + ResizeSurface(width, height); + + // Check surface status for error. If texture is not optimal, try to reconfigure the surface. + WGPUSurfaceTexture surface_texture; + wgpuSurfaceGetCurrentTexture(wgpu_surface, &surface_texture); + if (ImGui_ImplWGPU_IsSurfaceStatusError(surface_texture.status)) + { + fprintf(stderr, "Unrecoverable Surface Texture status=%#.8x\n", surface_texture.status); + abort(); + } + if (ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(surface_texture.status)) + { + if (surface_texture.texture) + wgpuTextureRelease(surface_texture.texture); + if (width > 0 && height > 0) + ResizeSurface(width, height); + continue; + } + + // Start the Dear ImGui frame + ImGui_ImplWGPU_NewFrame(); + ImGui_ImplSDL2_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + + WGPUTextureViewDescriptor view_desc = {}; + view_desc.format = wgpu_surface_configuration.format; + view_desc.dimension = WGPUTextureViewDimension_2D; + view_desc.mipLevelCount = WGPU_MIP_LEVEL_COUNT_UNDEFINED; + view_desc.arrayLayerCount = WGPU_ARRAY_LAYER_COUNT_UNDEFINED; + view_desc.aspect = WGPUTextureAspect_All; + + WGPUTextureView texture_view = wgpuTextureCreateView(surface_texture.texture, &view_desc); + + WGPURenderPassColorAttachment color_attachments = {}; + color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED; + color_attachments.loadOp = WGPULoadOp_Clear; + color_attachments.storeOp = WGPUStoreOp_Store; + color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; + color_attachments.view = texture_view; + + WGPURenderPassDescriptor render_pass_desc = {}; + render_pass_desc.colorAttachmentCount = 1; + render_pass_desc.colorAttachments = &color_attachments; + render_pass_desc.depthStencilAttachment = nullptr; + + WGPUCommandEncoderDescriptor enc_desc = {}; + WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc); + + WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc); + ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass); + wgpuRenderPassEncoderEnd(pass); + + WGPUCommandBufferDescriptor cmd_buffer_desc = {}; + WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc); + wgpuQueueSubmit(wgpu_queue, 1, &cmd_buffer); + +#ifndef __EMSCRIPTEN__ + wgpuSurfacePresent(wgpu_surface); + // Tick needs to be called in Dawn to display validation errors +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) + wgpuDeviceTick(wgpu_device); +#endif +#endif + wgpuTextureViewRelease(texture_view); + wgpuRenderPassEncoderRelease(pass); + wgpuCommandEncoderRelease(encoder); + wgpuCommandBufferRelease(cmd_buffer); + } +#ifdef __EMSCRIPTEN__ + EMSCRIPTEN_MAINLOOP_END; +#endif + + // Cleanup + ImGui_ImplWGPU_Shutdown(); + ImGui_ImplSDL2_Shutdown(); + ImGui::DestroyContext(); + + wgpuSurfaceUnconfigure(wgpu_surface); + wgpuSurfaceRelease(wgpu_surface); + wgpuQueueRelease(wgpu_queue); + wgpuDeviceRelease(wgpu_device); + wgpuInstanceRelease(wgpu_instance); + + SDL_DestroyWindow(window); + SDL_Quit(); + + return 0; +} + +// SDL2 helper to create a WebGPU surface (exclusively!) for Native/Desktop applications: available only together with WebGPU/WGPU backend +// As of today (2025/10/31) there is no "official" support in SDL2 to create a surface for WebGPU backend. +// This stub uses "low level" SDL2 calls to acquire information from a specific Window Manager. +// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. +#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) + +#include +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) +{ + SDL_SysWMinfo sysWMInfo; + SDL_VERSION(&sysWMInfo.version); + SDL_GetWindowWMInfo(window, &sysWMInfo); + + ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; + create_info.Instance = instance; +#if defined(SDL_VIDEO_DRIVER_COCOA) + { + create_info.System = "cocoa"; + create_info.RawWindow = (void*)sysWMInfo.info.cocoa.window; + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(SDL_VIDEO_DRIVER_WAYLAND) || defined(SDL_VIDEO_DRIVER_X11) + const char* sdl_driver = SDL_GetCurrentVideoDriver(); + if (sdl_driver && strcmp(sdl_driver, "wayland") == 0) + { + create_info.System = "wayland"; + create_info.RawDisplay = (void*)sysWMInfo.info.wl.display; + create_info.RawSurface = (void*)sysWMInfo.info.wl.surface; + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } + else + { + create_info.System = "x11"; + create_info.RawWindow = (void*)sysWMInfo.info.x11.window; + create_info.RawDisplay = (void*)sysWMInfo.info.x11.display; + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(SDL_VIDEO_DRIVER_WINDOWS) + { + create_info.System = "win32"; + create_info.RawWindow = (void*)sysWMInfo.info.win.window; + create_info.RawInstance = (void*)sysWMInfo.info.win.hinstance; + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#else +#error "Unsupported WebGPU native platform!" +#endif + return nullptr; +} +#endif + +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +static WGPUAdapter RequestAdapter(wgpu::Instance& instance) +{ + wgpu::Adapter acquired_adapter; + wgpu::RequestAdapterOptions adapter_options; + auto onRequestAdapter = [&](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter, wgpu::StringView message) + { + if (status != wgpu::RequestAdapterStatus::Success) + { + printf("Failed to get an adapter: %s\n", message.data); + return; + } + acquired_adapter = std::move(adapter); + }; + + // Synchronously (wait until) acquire Adapter + wgpu::Future waitAdapterFunc { instance.RequestAdapter(&adapter_options, wgpu::CallbackMode::WaitAnyOnly, onRequestAdapter) }; + wgpu::WaitStatus waitStatusAdapter = instance.WaitAny(waitAdapterFunc, UINT64_MAX); + IM_ASSERT(acquired_adapter != nullptr && waitStatusAdapter == wgpu::WaitStatus::Success && "Error on Adapter request"); + return acquired_adapter.MoveToCHandle(); +} + +static WGPUDevice RequestDevice(wgpu::Instance& instance, wgpu::Adapter& adapter) +{ + // Set device callback functions + wgpu::DeviceDescriptor device_desc; + device_desc.SetDeviceLostCallback(wgpu::CallbackMode::AllowSpontaneous, + [](const wgpu::Device&, wgpu::DeviceLostReason type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetDeviceLostReasonName((WGPUDeviceLostReason)type), msg.data); } + ); + device_desc.SetUncapturedErrorCallback( + [](const wgpu::Device&, wgpu::ErrorType type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetErrorTypeName((WGPUErrorType)type), msg.data); } + ); + + wgpu::Device acquired_device; + auto onRequestDevice = [&](wgpu::RequestDeviceStatus status, wgpu::Device local_device, wgpu::StringView message) + { + if (status != wgpu::RequestDeviceStatus::Success) + { + printf("Failed to get an device: %s\n", message.data); + return; + } + acquired_device = std::move(local_device); + }; + + // Synchronously (wait until) get Device + wgpu::Future waitDeviceFunc { adapter.RequestDevice(&device_desc, wgpu::CallbackMode::WaitAnyOnly, onRequestDevice) }; + wgpu::WaitStatus waitStatusDevice = instance.WaitAny(waitDeviceFunc, UINT64_MAX); + IM_ASSERT(acquired_device != nullptr && waitStatusDevice == wgpu::WaitStatus::Success && "Error on Device request"); + return acquired_device.MoveToCHandle(); +} +#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#ifdef __EMSCRIPTEN__ +// Adapter and device initialization via JS +EM_ASYNC_JS( void, getAdapterAndDeviceViaJS, (), +{ + if (!navigator.gpu) + throw Error("WebGPU not supported."); + const adapter = await navigator.gpu.requestAdapter(); + const device = await adapter.requestDevice(); + Module.preinitializedWebGPUDevice = device; +} ); +#else // __EMSCRIPTEN__ +static void handle_request_adapter(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void* userdata1, void* userdata2) +{ + if (status == WGPURequestAdapterStatus_Success) + { + WGPUAdapter* extAdapter = (WGPUAdapter*)userdata1; + *extAdapter = adapter; + } + else + { + printf("Request_adapter status=%#.8x message=%.*s\n", status, (int)message.length, message.data); + } +} + +static void handle_request_device(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView message, void* userdata1, void* userdata2) +{ + if (status == WGPURequestDeviceStatus_Success) + { + WGPUDevice* extDevice = (WGPUDevice*)userdata1; + *extDevice = device; + } + else + { + printf("Request_device status=%#.8x message=%.*s\n", status, (int)message.length, message.data); + } +} + +static WGPUAdapter RequestAdapter(WGPUInstance& instance) +{ + WGPURequestAdapterOptions adapter_options = {}; + + WGPUAdapter local_adapter; + WGPURequestAdapterCallbackInfo adapterCallbackInfo = {}; + adapterCallbackInfo.callback = handle_request_adapter; + adapterCallbackInfo.userdata1 = &local_adapter; + + wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + IM_ASSERT(local_adapter && "Error on Adapter request"); + return local_adapter; +} + +static WGPUDevice RequestDevice(WGPUAdapter& adapter) +{ + WGPUDevice local_device; + WGPURequestDeviceCallbackInfo deviceCallbackInfo = {}; + deviceCallbackInfo.callback = handle_request_device; + deviceCallbackInfo.userdata1 = &local_device; + wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + IM_ASSERT(local_device && "Error on Device request"); + return local_device; +} +#endif // __EMSCRIPTEN__ +#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU + +static bool InitWGPU(SDL_Window* window) +{ + WGPUTextureFormat preferred_fmt = WGPUTextureFormat_Undefined; // acquired from SurfaceCapabilities + + // Google DAWN backend: Adapter and Device acquisition, Surface creation +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) + wgpu::InstanceDescriptor instance_desc = {}; + static constexpr wgpu::InstanceFeatureName timedWaitAny = wgpu::InstanceFeatureName::TimedWaitAny; + instance_desc.requiredFeatureCount = 1; + instance_desc.requiredFeatures = &timedWaitAny; + wgpu::Instance instance = wgpu::CreateInstance(&instance_desc); + + wgpu::Adapter adapter = RequestAdapter(instance); + ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter.Get()); + + wgpu_device = RequestDevice(instance, adapter); + + // Create the surface. +#ifdef __EMSCRIPTEN__ + wgpu::EmscriptenSurfaceSourceCanvasHTMLSelector canvas_desc = {}; + canvas_desc.selector = "#canvas"; + + wgpu::SurfaceDescriptor surface_desc = {}; + surface_desc.nextInChain = &canvas_desc; + wgpu::Surface surface = instance.CreateSurface(&surface_desc); +#else + wgpu::Surface surface = CreateWGPUSurface(instance.Get(), window); +#endif + if (!surface) + return false; + + // Moving Dawn objects into WGPU handles + wgpu_instance = instance.MoveToCHandle(); + wgpu_surface = surface.MoveToCHandle(); + + WGPUSurfaceCapabilities surface_capabilities = {}; + wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; + + // WGPU backend: Adapter and Device acquisition, Surface creation +#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) + wgpu_instance = wgpuCreateInstance(nullptr); + +#ifdef __EMSCRIPTEN__ + getAdapterAndDeviceViaJS(); + + wgpu_device = emscripten_webgpu_get_device(); + assert(wgpu_device != nullptr && "Error creating the Device"); + + WGPUSurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {}; + html_surface_desc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; + html_surface_desc.selector = "#canvas"; + + WGPUSurfaceDescriptor surface_desc = {}; + surface_desc.nextInChain = &html_surface_desc.chain; + + // Create the surface. + wgpu_surface = wgpuInstanceCreateSurface(wgpu_instance, &surface_desc); + preferred_fmt = wgpuSurfaceGetPreferredFormat(wgpu_surface, {} /* adapter */); +#else // __EMSCRIPTEN__ + wgpuSetLogCallback( + [](WGPULogLevel level, WGPUStringView msg, void* userdata) { fprintf(stderr, "%s: %.*s\n", ImGui_ImplWGPU_GetLogLevelName(level), (int)msg.length, msg.data); }, nullptr + ); + wgpuSetLogLevel(WGPULogLevel_Warn); + + WGPUAdapter adapter = RequestAdapter(wgpu_instance); + ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter); + + wgpu_device = RequestDevice(adapter); + + // Create the surface. + wgpu_surface = CreateWGPUSurface(wgpu_instance, window); + if (!wgpu_surface) + return false; + + WGPUSurfaceCapabilities surface_capabilities = {}; + wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; +#endif // __EMSCRIPTEN__ +#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU + + wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; + wgpu_surface_configuration.alphaMode = WGPUCompositeAlphaMode_Auto; + wgpu_surface_configuration.usage = WGPUTextureUsage_RenderAttachment; + wgpu_surface_configuration.width = wgpu_surface_width; + wgpu_surface_configuration.height = wgpu_surface_height; + wgpu_surface_configuration.device = wgpu_device; + wgpu_surface_configuration.format = preferred_fmt; + + wgpuSurfaceConfigure(wgpu_surface, &wgpu_surface_configuration); + wgpu_queue = wgpuDeviceGetQueue(wgpu_device); + + return true; +} diff --git a/examples/example_sdl3_wgpu/CMakeLists.txt b/examples/example_sdl3_wgpu/CMakeLists.txt new file mode 100644 index 000000000..05d57650c --- /dev/null +++ b/examples/example_sdl3_wgpu/CMakeLists.txt @@ -0,0 +1,199 @@ +# Building for desktop (WebGPU-native) with Dawn: +# 1. git clone https://github.com/google/dawn dawn +# 2. cmake -B build -DIMGUI_DAWN_DIR=dawn +# 3. cmake --build build +# The resulting binary will be found at one of the following locations: +# * build/Debug/example_sdl3_wgpu[.exe] +# * build/example_sdl3_wgpu[.exe] + +# Building for desktop (WGPU-Native) with WGPU-Native: +# 1. download WGPU-Native autogenerated binary modules for your platform/compiler from: https://github.com/gfx-rs/wgpu-native/releases +# 2. unzip the downloaded file in your_preferred_folder +# 3. cmake -B build -DIMGUI_WGPU_DIR=your_preferred_folder ("full path" or "relative" starting from current directory) +# 4. cmake --build build +# The resulting binary will be found at one of the following locations: +# * build/Debug/example_sdl3_wgpu[.exe] +# * build/example_sdl3_wgpu[.exe] + +# Building for Emscripten: +# 1. Install Emscripten SDK following the instructions: https://emscripten.org/docs/getting_started/downloads.html +# 2. Install Ninja build system +# 3. emcmake cmake -G Ninja -B build +# (optional) -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py", see ReadMe.md +# 4. cmake --build build +# 5. emrun build/index.html + +cmake_minimum_required(VERSION 3.22) # Dawn requires CMake >= 3.22 +project(imgui_example_sdl3_wgpu C CXX) + +set(IMGUI_EXECUTABLE example_sdl3_wgpu) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE) +endif() + +set(CMAKE_CXX_STANDARD 17) # Dawn requires C++17 + +# Dear ImGui +set(IMGUI_DIR ../../) + +# ImGui example commons source files +set(IMGUI_EXAMPLE_SOURCE_FILES + main.cpp + # backend files + ${IMGUI_DIR}/backends/imgui_impl_sdl3.cpp + ${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp + # Dear ImGui files + ${IMGUI_DIR}/imgui.cpp + ${IMGUI_DIR}/imgui_draw.cpp + ${IMGUI_DIR}/imgui_demo.cpp + ${IMGUI_DIR}/imgui_tables.cpp + ${IMGUI_DIR}/imgui_widgets.cpp +) + +if(EMSCRIPTEN) + if(EMSCRIPTEN_VERSION VERSION_LESS "4.0.15") + message(FATAL_ERROR "Using Emscripten with SDL3 needs Emscripten version >= 4.0.15") + endif() + if(NOT IMGUI_EMSCRIPTEN_WEBGPU_FLAG) # if IMGUI_EMSCRIPTEN_WEBGPU_FLAG not used, set by current EMSCRIPTEN version + if(EMSCRIPTEN_VERSION VERSION_GREATER_EQUAL "4.0.10") + set(IMGUI_EMSCRIPTEN_WEBGPU_FLAG "--use-port=emdawnwebgpu" CACHE STRING "Choose between --use-port=emdawnwebgpu (Dawn implementation of EMSCRIPTEN) and -sUSE_WEBGPU=1 (WGPU implementation of EMSCRIPTEN, deprecated in 4.0.10): default to --use-port=emdawnwebgpu for EMSCRIPTEN >= 4.0.10") + else() + set(IMGUI_EMSCRIPTEN_WEBGPU_FLAG "-sUSE_WEBGPU=1" CACHE STRING "Use -sUSE_WEBGPU=1 for EMSCRIPTEN WGPU implementation") + endif() + else() # if IMGUI_EMSCRIPTEN_WEBGPU_FLAG used, check correct version + if(EMSCRIPTEN_VERSION VERSION_LESS "4.0.10" AND "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" MATCHES "emdawnwebgpu") + # it's necessary EMSCRIPTEN >= v4.0.10 (although "--use-port=path/to/emdawnwebgpu.port.py" is supported/tested from v4.0.8) + message(FATAL_ERROR "emdawnwebgpu needs EMSCRIPTEN version >= 4.0.10") + endif() + endif() + + add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1) +else() # Native/Desktop build + find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3) + + if(NOT IMGUI_DAWN_DIR AND NOT IMGUI_WGPU_DIR) # if it's Native/Desktop build, IMGUI_DAWN_DIR or IMGUI_WGPU_DIR must be specified + message(FATAL_ERROR "Please specify the Dawn or WGPU base directory") + endif() + + if(IMGUI_DAWN_DIR AND IMGUI_WGPU_DIR) # both IMGUI_DAWN_DIR and IMGUI_WGPU_DIR cannot be set + message(FATAL_ERROR "Please specify only one between Dawn / WGPU base directory") + endif() + + if(APPLE) # Add SDL3 module to get Surface, with libs and file property for MacOS build + set_source_files_properties(${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") + set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") + endif() + + if(IMGUI_DAWN_DIR) # DAWN-Native build options + set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") + if(NOT IMGUI_DAWN_DIR) + message(FATAL_ERROR "Please specify the Dawn repository by setting IMGUI_DAWN_DIR") + endif() + + option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 + + option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) + set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") + + # Dawn builds many things by default - disable things we don't need + option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) + option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) + option(TINT_BUILD_DOCS "Build documentation" OFF) + option(TINT_BUILD_TESTS "Build tests" OFF) + if(NOT APPLE) + option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) + endif() + if(WIN32) + option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) + option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) + option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) + option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) + option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) + option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) + option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) + endif() + # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time + # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) + if(LINUX) + if($ENV{XDG_SESSION_TYPE} MATCHES wayland) + option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + endif() + endif() + + add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) + + set(LIBRARIES webgpu_dawn ${OS_LIBRARIES}) + else() # WGPU-Native build options + set(WGPU_NATIVE_LIB_DIR ${IMGUI_WGPU_DIR}/lib) + find_library(WGPU_LIBRARY NAMES libwgpu_native.a wgpu_native.lib wgpu_native HINTS ${WGPU_NATIVE_LIB_DIR} REQUIRED) + if(WIN32) + set(OS_LIBRARIES d3dcompiler ws2_32 userenv bcrypt ntdll opengl32 Propsys RuntimeObject) + elseif(UNIX AND NOT APPLE) + set(OS_LIBRARIES "-lm -ldl") + endif() + + set(LIBRARIES ${WGPU_LIBRARY} ${OS_LIBRARIES}) + endif() +endif() + +add_executable(${IMGUI_EXECUTABLE} ${IMGUI_EXAMPLE_SOURCE_FILES}) + +target_include_directories(${IMGUI_EXECUTABLE} PUBLIC + ${IMGUI_DIR} + ${IMGUI_DIR}/backends + ${SDL3_INCLUDE_DIRS} +) + +target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_EXAMPLE_SDL3_WGPU") + +# Enable warning level compiler option only for IMGUI_EXAMPLE_SOURCE_FILES +if (MSVC) + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC /W4) # warning level 4 +else() + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC -Wall) # -Wextra -Wpedantic +endif() + +# IMGUI_IMPL_WEBGPU_BACKEND_DAWN/WGPU internal define is set according to: +# EMSCRIPTEN: by used FLAG +# --use-port=emdawnwebgpu --> IMGUI_IMPL_WEBGPU_BACKEND_DAWN enabled (+EMSCRIPTEN) +# -sUSE_WEBGPU=1 --> IMGUI_IMPL_WEBGPU_BACKEND_WGPU enabled (+EMSCRIPTEN) +# NATIVE: by used SDK installation directory +# if IMGUI_DAWN_DIR is valid --> IMGUI_IMPL_WEBGPU_BACKEND_DAWN enabled +# if IMGUI_WGPU_DIR is valid --> IMGUI_IMPL_WEBGPU_BACKEND_WGPU enabled + +if(NOT EMSCRIPTEN) # WegGPU-Native settings + if(IMGUI_DAWN_DIR) + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + else() + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") + target_include_directories(${IMGUI_EXECUTABLE} PUBLIC ${IMGUI_WGPU_DIR}/include) + endif() + + target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp PUBLIC ${LIBRARIES} SDL3::SDL3) +else() # Emscripten settings + set(CMAKE_EXECUTABLE_SUFFIX ".html") + + if("${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" MATCHES "emdawnwebgpu") + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}") + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + else() + target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") + endif() + message(STATUS "Using ${IMGUI_EMSCRIPTEN_WEBGPU_FLAG} WebGPU implementation") + + target_compile_options(${IMGUI_EXECUTABLE} PUBLIC "-sUSE_SDL=3") + target_link_options(${IMGUI_EXECUTABLE} PRIVATE + "${IMGUI_EMSCRIPTEN_WEBGPU_FLAG}" + "-sUSE_SDL=3" + "-sWASM=1" + "-sASYNCIFY=1" + "-sALLOW_MEMORY_GROWTH=1" + "-sNO_EXIT_RUNTIME=0" + "-sASSERTIONS=1" + "-sDISABLE_EXCEPTION_CATCHING=1" +# "-sNO_FILESYSTEM=1" + "--shell-file=${CMAKE_CURRENT_LIST_DIR}/../libs/emscripten/shell_minimal.html" + ) + set_target_properties(${IMGUI_EXECUTABLE} PROPERTIES OUTPUT_NAME "index") +endif() diff --git a/examples/example_sdl3_wgpu/Makefile.emscripten b/examples/example_sdl3_wgpu/Makefile.emscripten new file mode 100644 index 000000000..58639a1fd --- /dev/null +++ b/examples/example_sdl3_wgpu/Makefile.emscripten @@ -0,0 +1,103 @@ +# +# Makefile to use with emscripten +# See https://emscripten.org/docs/getting_started/downloads.html +# for installation instructions. +# +# This Makefile assumes you have loaded emscripten's environment. +# (On Windows, you may need to execute emsdk_env.bat or encmdprompt.bat ahead) +# +# Running `make -f Makefile.emscripten` will produce three files: +# - web/index.html +# - web/index.js +# - web/index.wasm +# +# All three are needed to run the demo. + +CC = emcc +CXX = em++ +WEB_DIR = web +EXE = $(WEB_DIR)/index.html +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl3.cpp $(IMGUI_DIR)/backends/imgui_impl_wgpu.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) +CPPFLAGS = +LDFLAGS = +EMS = + +##--------------------------------------------------------------------- +## EMSCRIPTEN OPTIONS +##--------------------------------------------------------------------- + +# ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) +EMS += -s USE_SDL=3 +EMS += -s DISABLE_EXCEPTION_CATCHING=1 +LDFLAGS += -s WASM=1 +LDFLAGS += -s ALLOW_MEMORY_GROWTH=1 +LDFLAGS += -s ASYNCIFY=1 +LDFLAGS += -s NO_EXIT_RUNTIME=0 +LDFLAGS += -s ASSERTIONS=1 + +# (1) Using legacy WebGPU implementation (Emscripten < 4.0.10) +#EMS += -DIMGUI_IMPL_WEBGPU_BACKEND_WGPU +#LDFLAGS += -s USE_WEBGPU=1 + +# or (2) Using newer Dawn-based WebGPU port (Emscripten >= 4.0.10) +EMS += --use-port=emdawnwebgpu +LDFLAGS += --use-port=emdawnwebgpu + +# Build as single file (binary text encoded in .html file) +#LDFLAGS += -sSINGLE_FILE + +# Emscripten allows preloading a file or folder to be accessible at runtime. +# The Makefile for this example project suggests embedding the misc/fonts/ folder into our application, it will then be accessible as "/fonts" +# See documentation for more details: https://emscripten.org/docs/porting/files/packaging_files.html +# (Default value is 0. Set to 1 to enable file-system and include the misc/fonts/ folder as part of the build.) +USE_FILE_SYSTEM ?= 0 +ifeq ($(USE_FILE_SYSTEM), 0) +LDFLAGS += -s NO_FILESYSTEM=1 +CPPFLAGS += -DIMGUI_DISABLE_FILE_FUNCTIONS +endif +ifeq ($(USE_FILE_SYSTEM), 1) +LDFLAGS += --no-heap-copy --preload-file ../../misc/fonts@/fonts +endif + +##--------------------------------------------------------------------- +## FINAL BUILD FLAGS +##--------------------------------------------------------------------- + +CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +#CPPFLAGS += -g +CPPFLAGS += -Wall -Wformat -Os $(EMS) +LDFLAGS += --shell-file ../libs/emscripten/shell_minimal.html +LDFLAGS += $(EMS) + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(EXE) + +$(WEB_DIR): + mkdir $@ + +serve: all + python3 -m http.server -d $(WEB_DIR) + +$(EXE): $(OBJS) $(WEB_DIR) + $(CXX) -o $@ $(OBJS) $(LDFLAGS) + +clean: + rm -f $(EXE) $(OBJS) $(WEB_DIR)/*.js $(WEB_DIR)/*.wasm $(WEB_DIR)/*.wasm.pre diff --git a/examples/example_sdl3_wgpu/README.md b/examples/example_sdl3_wgpu/README.md new file mode 100644 index 000000000..bd7c33652 --- /dev/null +++ b/examples/example_sdl3_wgpu/README.md @@ -0,0 +1,167 @@ +## How to Build + + +--- + +### Using CMake +#### Building for desktop (WebGPU-native) with Google Dawn: + 1. `git clone https://github.com/google/dawn dawn` + 2. `cmake -B build -DIMGUI_DAWN_DIR=dawn` + 3. `cmake --build build` +The resulting binary will be found at one of the following locations: + * build/Debug/example_sdl3_wgpu[.exe] + * build/example_sdl3_wgpu[.exe] + +#### Building for desktop (WebGPU-Native) with WGPU: + 1. download WGPU-Native autogenerated binary modules for your platform/compiler from: https://github.com/gfx-rs/wgpu-native/releases + 2. unzip the downloaded file in `your_preferred_folder` + 3. `cmake -B build -DIMGUI_WGPU_DIR=your_preferred_folder` ("full path" or "relative" starting from current directory) + 5. `cmake --build build` +The resulting binary will be found at one of the following locations: + * build/Debug/example_sdl3_wgpu[.exe] + * build/example_sdl3_wgpu[.exe] + +#### Building for Emscripten: + 1. Install Emscripten SDK following the instructions: https://emscripten.org/docs/getting_started/downloads.html + 2. Install Ninja build system + 3. `emcmake cmake -G Ninja -B build` + - (optional) `-DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py"`, see below + 4. `cmake --build build` + +#### Sync Emscripten with latest Google Dawn: +If you want to sync Emscripten with latest DAWN release it's necessary to download the `port-emdawnwgpu-package` (released daily by Google) here: +https://github.com/google/dawn/releases +Unpack it in your preferred folder and to replace the step 3 with: + +3. `emcmake cmake -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path/to/emdawnwebgpu_package/emdawnwebgpu.port.py" -G Ninja -B build` + +**N.B.** +For the WASM code produced by Emscripten to work correctly, it will also be necessary to have the "corresponding" (or newer) version of Google Canary (nightly build for developers) that includes the latest changes + + +--- + +### CMake by step + +#### Generate Dawn Native: + +- `cmake -G Ninja -DIMGUI_DAWN_DIR=path_to_sdk_dir -B where_to_build_dir` + - Using `IMGUI_DAWN_DIR` set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + +#### Generate WGPU Native: + +- `cmake -G Ninja -DIMGUI_WGPU_DIR=path_to_sdk_dir -B where_to_build_dir` + + - Using `IMGUI_WGPU_DIR` set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten: + +- `emcmake cmake -G Ninja -B where_to_build_dir`\ +CMake checks the EMSCRIPEN version then: + - if EMS >= 4.0.10 uses `--use-port=emdawnwebgpu` flag to build + - it set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + - if EMS < 4.0.10 uses `-sUSE_WEBGPU=1` flag to build + - it set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten forcing `-sUSE_WEBGPU=1` deprecated flag even with EMS >= 4.0.10 +- `emcmake cmake -G Ninja -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="-sUSE_WEBGPU=1" -B where_to_build_dir` + - it set `IMGUI_IMPL_WEBGPU_BACKEND_WGPU` compiler define + +#### Generate Emscripten using external WebGPU library (emdawnwebgpu_pkg) +- `emcmake cmake -G Ninja -DIMGUI_EMSCRIPTEN_WEBGPU_FLAG="--use-port=path_to_emdawnwebgpu_pkg" -B where_to_build_dir` + - it set `IMGUI_IMPL_WEBGPU_BACKEND_DAWN` compiler define + - *To use external WebGPU library it's necessary to have EMS >= 4.0.10 or the minimum requirements specified by the package:* + - https://github.com/google/dawn/releases + +#### Build time + +Once the procedure for the specific builder is generated, the build command is **always the same**: + +- Build using CMake + - `cmake --build where_to_build_dir` + - It will use selected builder to build the example. + +- Build explicitly: + - `cd where_to_build_dir` + - `ninja` + - This is the builder chosen during the generation phase + +--- + +### CMake useful options +#### Generator types (alternative to **ninja** bulder): +- `-G Ninja` to build with __ninja__ builder +- `-G "Unix Makefiles"` to build with __make__ builder +- `-G "Visual Studio 17 2022" -A x64` to create a VS 2022 solution (.sln) file, Windows only + - **Native build only** + - Not **officially** supported to build Google Dawn + +Example: +- using **make** instead **ninja**: + - `cmake -G "Unix Makefiles" -DIMGUI_DAWN_DIR=path_to_sdk_dir -B where_to_build_dir` + +**Syntax is case sensitive and the "" are necessary in case of spaces between words* + +#### Directories +- The directory path can be absolute or relative (starting from the current directory) +- It's necessary to use different `where_to_build_dir` for different CMake generations + + +#### Build type +The default build type is **Debug** +It is possible to use a different build type using: +- `-DCMAKE_BUILD_TYPE=Release` +- `-DCMAKE_BUILD_TYPE=MinSizeRel` +- `-DCMAKE_BUILD_TYPE=RelWithDebInfo` + +Example: +- building **Release**: + - `cmake -G ninja -DIMGUI_WGPU_DIR=path_to_sdk_dir -DCMAKE_BUILD_TYPE=Release -B where_to_build_dir ` + +#### GLFW / SDL2 / SDL3 includes, libraries, search paths and package manager + +Includes and libraries, by default, are searched in system/compiler paths (environment variables): you can add the path to your development tools to the environment variables without having to modify the `CMakeLists.txt` file. +- e.g. CLang search in path specified from the following environment variables: + - include files: CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH + - library files: LIBRARY_PATH + +If you are using a package manager (**vcpkg** / **conan** / ... ) you need/can to specify it, adding to cmake command: +- `-DCMAKE_TOOLCHAIN_FILE=path/to/package_manager.cmake` + +Examples: + +- using **vcpkg** package manager it's necessary adding: + - `-DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake` + +- full cmake command using **vcpkg** package manager: + - `cmake -G Ninja -DIMGUI_DAWN_DIR=path_to_sdk_dir -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake -B where_to_build_dir` + +--- + + +### Using makefile + +- You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions + +- Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools. + +- You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. + +- Then build using `make -f Makefile.emscripten` while in the `example_glfw_wgpu/` directory. + +- Requires recent Emscripten as WGPU is still a work-in-progress API. + +--- + +## How to Run + +To run on a local machine: +- Make sure your browse supports WGPU and it is enabled. WGPU is still WIP not enabled by default in most browser. +- `make serve` will use Python3 to spawn a local webserver, you can then browse http://localhost:8000 to access your build. +- Otherwise, generally you will need a local webserver: + - Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
+_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ + - Emscripten SDK has a handy `emrun` command: `emrun web/example_glfw_wgpu.html --browser firefox` which will spawn a temporary local webserver (in Firefox). See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. + - You may use Python 3 builtin webserver: `python -m http.server -d web` (this is what `make serve` uses). + - You may use Python 2 builtin webserver: `cd web && python -m SimpleHTTPServer`. + - If you are accessing the files over a network, certain browsers, such as Firefox, will restrict Gamepad API access to secure contexts only (e.g. https only). diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp new file mode 100644 index 000000000..377ffd9bb --- /dev/null +++ b/examples/example_sdl3_wgpu/main.cpp @@ -0,0 +1,553 @@ +// Dear ImGui: standalone example application for using SDL3 + WebGPU +// - Emscripten is supported for publishing on web. See https://emscripten.org. +// - Dawn is used as a WebGPU implementation on desktop. + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + + +#include "imgui.h" +#include "imgui_impl_sdl3.h" +#include "imgui_impl_wgpu.h" +#include +#include +#include + +// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. +#ifdef __EMSCRIPTEN__ +#include +#include +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#include +#endif +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#endif + +#include +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +#include +#endif + +// Data +WGPUInstance wgpu_instance = nullptr; +WGPUDevice wgpu_device = nullptr; +WGPUSurface wgpu_surface = nullptr; +WGPUQueue wgpu_queue = nullptr; +WGPUSurfaceConfiguration wgpu_surface_configuration = {}; +int wgpu_surface_width = 1280; +int wgpu_surface_height = 800; + +// Forward declarations +static bool InitWGPU(SDL_Window* window); + +void ResizeSurface(int width, int height) +{ + wgpu_surface_configuration.width = wgpu_surface_width = width; + wgpu_surface_configuration.height = wgpu_surface_height = height; + wgpuSurfaceConfigure( wgpu_surface, (WGPUSurfaceConfiguration*)&wgpu_surface_configuration ); +} + +// Main code +int main(int, char**) +{ + // Setup SDL + // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function] + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) + { + printf("Error: SDL_Init(): %s\n", SDL_GetError()); + return 1; + } + + // Create SDL window graphics context + float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); + SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE; + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+WebGPU example", wgpu_surface_width, wgpu_surface_height, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return 1; + } + + // Initialize WGPU + InitWGPU(window); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + + // Setup Platform/Renderer backends + ImGui_ImplSDL3_InitForOther(window); + + ImGui_ImplWGPU_InitInfo init_info; + init_info.Device = wgpu_device; + init_info.NumFramesInFlight = 3; + init_info.RenderTargetFormat = wgpu_surface_configuration.format; + init_info.DepthStencilFormat = WGPUTextureFormat_Undefined; + ImGui_ImplWGPU_Init(&init_info); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. + //style.FontSizeBase = 20.0f; + //io.Fonts->AddFontDefault(); +#ifndef IMGUI_DISABLE_FILE_FUNCTIONS + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf"); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf"); + //IM_ASSERT(font != nullptr); +#endif + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; +#ifdef __EMSCRIPTEN__ + // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. + // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. + io.IniFilename = nullptr; + EMSCRIPTEN_MAINLOOP_BEGIN +#else + while (!done) +#endif + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function] + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL3_ProcessEvent(&event); + if (event.type == SDL_EVENT_QUIT) + done = true; + if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) + done = true; + } + + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function] + // React to changes in screen size + int width, height; + SDL_GetWindowSize(window, &width, &height); + if (width != wgpu_surface_width || height != wgpu_surface_height) + ResizeSurface(width, height); + + // Check surface status for error. If texture is not optimal, try to reconfigure the surface. + WGPUSurfaceTexture surface_texture; + wgpuSurfaceGetCurrentTexture(wgpu_surface, &surface_texture); + if (ImGui_ImplWGPU_IsSurfaceStatusError(surface_texture.status)) + { + fprintf(stderr, "Unrecoverable Surface Texture status=%#.8x\n", surface_texture.status); + abort(); + } + if (ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(surface_texture.status)) + { + if (surface_texture.texture) + wgpuTextureRelease(surface_texture.texture); + if (width > 0 && height > 0) + ResizeSurface(width, height); + continue; + } + + // Start the Dear ImGui frame + ImGui_ImplWGPU_NewFrame(); + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + + WGPUTextureViewDescriptor view_desc = {}; + view_desc.format = wgpu_surface_configuration.format; + view_desc.dimension = WGPUTextureViewDimension_2D; + view_desc.mipLevelCount = WGPU_MIP_LEVEL_COUNT_UNDEFINED; + view_desc.arrayLayerCount = WGPU_ARRAY_LAYER_COUNT_UNDEFINED; + view_desc.aspect = WGPUTextureAspect_All; + + WGPUTextureView texture_view = wgpuTextureCreateView(surface_texture.texture, &view_desc); + + WGPURenderPassColorAttachment color_attachments = {}; + color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED; + color_attachments.loadOp = WGPULoadOp_Clear; + color_attachments.storeOp = WGPUStoreOp_Store; + color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; + color_attachments.view = texture_view; + + WGPURenderPassDescriptor render_pass_desc = {}; + render_pass_desc.colorAttachmentCount = 1; + render_pass_desc.colorAttachments = &color_attachments; + render_pass_desc.depthStencilAttachment = nullptr; + + WGPUCommandEncoderDescriptor enc_desc = {}; + WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc); + + WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc); + ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass); + wgpuRenderPassEncoderEnd(pass); + + WGPUCommandBufferDescriptor cmd_buffer_desc = {}; + WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc); + wgpuQueueSubmit(wgpu_queue, 1, &cmd_buffer); + +#ifndef __EMSCRIPTEN__ + wgpuSurfacePresent(wgpu_surface); + // Tick needs to be called in Dawn to display validation errors +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) + wgpuDeviceTick(wgpu_device); +#endif +#endif + wgpuTextureViewRelease(texture_view); + wgpuRenderPassEncoderRelease(pass); + wgpuCommandEncoderRelease(encoder); + wgpuCommandBufferRelease(cmd_buffer); + } +#ifdef __EMSCRIPTEN__ + EMSCRIPTEN_MAINLOOP_END; +#endif + + // Cleanup + // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function] + ImGui_ImplWGPU_Shutdown(); + ImGui_ImplSDL3_Shutdown(); + ImGui::DestroyContext(); + + wgpuSurfaceUnconfigure(wgpu_surface); + wgpuSurfaceRelease(wgpu_surface); + wgpuQueueRelease(wgpu_queue); + wgpuDeviceRelease(wgpu_device); + wgpuInstanceRelease(wgpu_instance); + + SDL_DestroyWindow(window); + SDL_Quit(); + + return 0; +} + +// SDL3 helper to create a WebGPU surface (exclusively!) for Native/Desktop applications: available only together with WebGPU/WGPU backend +// As of today (2025/10) there is no "official" support in SDL3 to create a surface for WebGPU backend +// This stub uses "low level" SDL3 calls to acquire information from a specific Window Manager. +// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. +#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) + +#if defined(SDL_PLATFORM_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include +#endif + +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) +{ + SDL_PropertiesID propertiesID = SDL_GetWindowProperties(window); + + ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; + create_info.Instance = instance; +#if defined(SDL_PLATFORM_MACOS) + { + create_info.System = "cocoa"; + create_info.RawWindow = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(SDL_PLATFORM_LINUX) + if (SDL_strcmp(SDL_GetCurrentVideoDriver(), "wayland") == 0) + { + create_info.System = "wayland"; + create_info.RawDisplay = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER, NULL); + create_info.RawSurface = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } + else if (!SDL_strcmp(SDL_GetCurrentVideoDriver(), "x11")) + { + create_info.System = "x11"; + create_info.RawWindow = (void*)SDL_GetNumberProperty(propertiesID, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0); + create_info.RawDisplay = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_X11_DISPLAY_POINTER, NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(SDL_PLATFORM_WIN32) + { + create_info.System = "win32"; + create_info.RawWindow = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL); + create_info.RawInstance = (void*)::GetModuleHandle(NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#else +#error "Unsupported WebGPU native platform!" +#endif + return nullptr; +} +#endif + +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +static WGPUAdapter RequestAdapter(wgpu::Instance& instance) +{ + wgpu::Adapter acquired_adapter; + wgpu::RequestAdapterOptions adapter_options; + auto onRequestAdapter = [&](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter, wgpu::StringView message) + { + if (status != wgpu::RequestAdapterStatus::Success) + { + printf("Failed to get an adapter: %s\n", message.data); + return; + } + acquired_adapter = std::move(adapter); + }; + + // Synchronously (wait until) acquire Adapter + wgpu::Future waitAdapterFunc { instance.RequestAdapter(&adapter_options, wgpu::CallbackMode::WaitAnyOnly, onRequestAdapter) }; + wgpu::WaitStatus waitStatusAdapter = instance.WaitAny(waitAdapterFunc, UINT64_MAX); + IM_ASSERT(acquired_adapter != nullptr && waitStatusAdapter == wgpu::WaitStatus::Success && "Error on Adapter request"); + return acquired_adapter.MoveToCHandle(); +} + +static WGPUDevice RequestDevice(wgpu::Instance& instance, wgpu::Adapter& adapter) +{ + // Set device callback functions + wgpu::DeviceDescriptor device_desc; + device_desc.SetDeviceLostCallback(wgpu::CallbackMode::AllowSpontaneous, + [](const wgpu::Device&, wgpu::DeviceLostReason type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetDeviceLostReasonName((WGPUDeviceLostReason)type), msg.data); } + ); + device_desc.SetUncapturedErrorCallback( + [](const wgpu::Device&, wgpu::ErrorType type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetErrorTypeName((WGPUErrorType)type), msg.data); } + ); + + wgpu::Device acquired_device; + auto onRequestDevice = [&](wgpu::RequestDeviceStatus status, wgpu::Device local_device, wgpu::StringView message) + { + if (status != wgpu::RequestDeviceStatus::Success) + { + printf("Failed to get an device: %s\n", message.data); + return; + } + acquired_device = std::move(local_device); + }; + + // Synchronously (wait until) get Device + wgpu::Future waitDeviceFunc { adapter.RequestDevice(&device_desc, wgpu::CallbackMode::WaitAnyOnly, onRequestDevice) }; + wgpu::WaitStatus waitStatusDevice = instance.WaitAny(waitDeviceFunc, UINT64_MAX); + IM_ASSERT(acquired_device != nullptr && waitStatusDevice == wgpu::WaitStatus::Success && "Error on Device request"); + return acquired_device.MoveToCHandle(); +} +#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) +#ifdef __EMSCRIPTEN__ +// Adapter and device initialization via JS +EM_ASYNC_JS( void, getAdapterAndDeviceViaJS, (), +{ + if (!navigator.gpu) + throw Error("WebGPU not supported."); + const adapter = await navigator.gpu.requestAdapter(); + const device = await adapter.requestDevice(); + Module.preinitializedWebGPUDevice = device; +} ); +#else // __EMSCRIPTEN__ +static void handle_request_adapter(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void* userdata1, void* userdata2) +{ + if (status == WGPURequestAdapterStatus_Success) + { + WGPUAdapter* extAdapter = (WGPUAdapter*)userdata1; + *extAdapter = adapter; + } + else + { + printf("Request_adapter status=%#.8x message=%.*s\n", status, (int)message.length, message.data); + } +} + +static void handle_request_device(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView message, void* userdata1, void* userdata2) +{ + if (status == WGPURequestDeviceStatus_Success) + { + WGPUDevice* extDevice = (WGPUDevice*)userdata1; + *extDevice = device; + } + else + { + printf("Request_device status=%#.8x message=%.*s\n", status, (int)message.length, message.data); + } +} + +static WGPUAdapter RequestAdapter(WGPUInstance& instance) +{ + WGPURequestAdapterOptions adapter_options = {}; + + WGPUAdapter local_adapter; + WGPURequestAdapterCallbackInfo adapterCallbackInfo = {}; + adapterCallbackInfo.callback = handle_request_adapter; + adapterCallbackInfo.userdata1 = &local_adapter; + + wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + IM_ASSERT(local_adapter && "Error on Adapter request"); + return local_adapter; +} + +static WGPUDevice RequestDevice(WGPUAdapter& adapter) +{ + WGPUDevice local_device; + WGPURequestDeviceCallbackInfo deviceCallbackInfo = {}; + deviceCallbackInfo.callback = handle_request_device; + deviceCallbackInfo.userdata1 = &local_device; + wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + IM_ASSERT(local_device && "Error on Device request"); + return local_device; +} +#endif // __EMSCRIPTEN__ +#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU + +static bool InitWGPU(SDL_Window* window) +{ + WGPUTextureFormat preferred_fmt = WGPUTextureFormat_Undefined; // acquired from SurfaceCapabilities + + // Google DAWN backend: Adapter and Device acquisition, Surface creation +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) + wgpu::InstanceDescriptor instance_desc = {}; + static constexpr wgpu::InstanceFeatureName timedWaitAny = wgpu::InstanceFeatureName::TimedWaitAny; + instance_desc.requiredFeatureCount = 1; + instance_desc.requiredFeatures = &timedWaitAny; + wgpu::Instance instance = wgpu::CreateInstance(&instance_desc); + + wgpu::Adapter adapter = RequestAdapter(instance); + ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter.Get()); + + wgpu_device = RequestDevice(instance, adapter); + + // Create the surface. +#ifdef __EMSCRIPTEN__ + wgpu::EmscriptenSurfaceSourceCanvasHTMLSelector canvas_desc = {}; + canvas_desc.selector = "#canvas"; + + wgpu::SurfaceDescriptor surface_desc = {}; + surface_desc.nextInChain = &canvas_desc; + wgpu::Surface surface = instance.CreateSurface(&surface_desc); +#else + wgpu::Surface surface = CreateWGPUSurface(instance.Get(), window); +#endif + if (!surface) + return false; + + // Moving Dawn objects into WGPU handles + wgpu_instance = instance.MoveToCHandle(); + wgpu_surface = surface.MoveToCHandle(); + + WGPUSurfaceCapabilities surface_capabilities = {}; + wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; + + // WGPU backend: Adapter and Device acquisition, Surface creation +#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) + wgpu_instance = wgpuCreateInstance(nullptr); + +#ifdef __EMSCRIPTEN__ + getAdapterAndDeviceViaJS(); + + wgpu_device = emscripten_webgpu_get_device(); + IM_ASSERT(wgpu_device != nullptr && "Error creating the Device"); + + WGPUSurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {}; + html_surface_desc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; + html_surface_desc.selector = "#canvas"; + + WGPUSurfaceDescriptor surface_desc = {}; + surface_desc.nextInChain = &html_surface_desc.chain; + + // Create the surface. + wgpu_surface = wgpuInstanceCreateSurface(wgpu_instance, &surface_desc); + preferred_fmt = wgpuSurfaceGetPreferredFormat(wgpu_surface, {} /* adapter */); +#else // __EMSCRIPTEN__ + wgpuSetLogCallback( + [](WGPULogLevel level, WGPUStringView msg, void* userdata) { fprintf(stderr, "%s: %.*s\n", ImGui_ImplWGPU_GetLogLevelName(level), (int)msg.length, msg.data); }, nullptr + ); + wgpuSetLogLevel(WGPULogLevel_Warn); + + WGPUAdapter adapter = RequestAdapter(wgpu_instance); + ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter); + + wgpu_device = RequestDevice(adapter); + + // Create the surface. + wgpu_surface = CreateWGPUSurface(wgpu_instance, window); + if (!wgpu_surface) + return false; + + WGPUSurfaceCapabilities surface_capabilities = {}; + wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; +#endif // __EMSCRIPTEN__ +#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU + + wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; + wgpu_surface_configuration.alphaMode = WGPUCompositeAlphaMode_Auto; + wgpu_surface_configuration.usage = WGPUTextureUsage_RenderAttachment; + wgpu_surface_configuration.width = wgpu_surface_width; + wgpu_surface_configuration.height = wgpu_surface_height; + wgpu_surface_configuration.device = wgpu_device; + wgpu_surface_configuration.format = preferred_fmt; + + wgpuSurfaceConfigure(wgpu_surface, &wgpu_surface_configuration); + wgpu_queue = wgpuDeviceGetQueue(wgpu_device); + + return true; +} From 823ccc274ec053b496f02a4cf989d66e6d67251a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Oct 2025 19:34:12 +0100 Subject: [PATCH 1453/2359] Examples: update docs. (#8381) --- docs/EXAMPLES.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index f61297fd1..45ad97309 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -72,7 +72,7 @@ OSX + OpenGL2 example.
You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) [example_glfw_wgpu/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_wgpu/)
-GLFW + WebGPU example. Supports Emscripten (web) or Dawn (desktop)
+GLFW + WebGPU example. Supports Emscripten (web), Dawn (native), WGPU (native).
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_wgpu.cpp Note that the 'example_glfw_opengl3' and 'example_sdl2_opengl3' examples also supports Emscripten! @@ -149,6 +149,11 @@ SDL2 (Win32, Mac, Linux, etc.) + Vulkan example.
This is quite long and tedious, because: Vulkan.
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. +[example_sdl2_wgpu/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_wgpu/)
+SDL2 + WebGPU example. Supports Emscripten (web), Dawn (native), WGPU (native).
+= main.cpp + imgui_impl_sdl2.cpp + imgui_impl_wgpu.cpp +(note that the 'example_sdl2_opengl3' example also supports Emscripten!) + [example_sdl3_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_directx11/)
SDL3 + DirectX11 examples, Windows only.
= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_dx11.cpp
@@ -177,6 +182,11 @@ SDL3 (Win32, Mac, Linux, etc.) + Vulkan example.
This is quite long and tedious, because: Vulkan.
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. +[example_sdl3_wgpu/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl3_wgpu/)
+SDL3 + WebGPU example. Supports Emscripten (web), Dawn (native), WGPU (native).
+= main.cpp + imgui_impl_sdl3.cpp + imgui_impl_wgpu.cpp +(note that the 'example_sdl3_opengl3' example also supports Emscripten!) + [example_win32_directx9/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx9/)
DirectX9 example, Windows only.
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp From a3546b52f8a6f4645e3a61ebe6918cba5177681e Mon Sep 17 00:00:00 2001 From: Brenton Bostick Date: Mon, 3 Nov 2025 07:26:12 -0500 Subject: [PATCH 1454/2359] Various typo fixes (#9042) --- imgui.cpp | 16 ++++++++-------- imgui.h | 14 +++++++------- imgui_demo.cpp | 2 +- imgui_internal.h | 6 +++--- imgui_tables.cpp | 8 ++++---- misc/cpp/README.txt | 2 +- misc/cpp/imgui_stdlib.cpp | 2 +- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7ad8ee89d..5a3a28af5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -437,7 +437,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: ImFontConfig cfg2; cfg2.MergeMode = true; io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); - - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate unde + - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate understanding which font input is providing which glyph. - Fonts: **IMPORTANT** on Thread Safety: - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded. - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). @@ -11115,7 +11115,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere. if (!(g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav)) { - // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test. + // FIXME-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test. window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent); if (g.NavId == id || g.NavAnyRequest) if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) @@ -11897,7 +11897,7 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext } SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f); - //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :( + //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkerboard has issue with transparent colors :( tooltip_flags |= ImGuiTooltipFlags_OverridePrevious; } @@ -12454,10 +12454,10 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s // Combo Box policy (we want a connecting edge) if (policy == ImGuiPopupPositionPolicy_ComboBox) { - const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up }; + const ImGuiDir dir_preferred_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up }; for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) { - const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; + const ImGuiDir dir = (n == -1) ? *last_dir : dir_preferred_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; ImVec2 pos; @@ -12476,10 +12476,10 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s // (Always first try the direction we used on the last frame, if any) if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default) { - const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; + const ImGuiDir dir_preferred_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) { - const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; + const ImGuiDir dir = (n == -1) ? *last_dir : dir_preferred_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; @@ -14671,7 +14671,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) ret = BeginTooltipHidden(); else ret = BeginTooltip(); - IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame(). + IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddenAndSkipItemsForCurrentFrame(). IM_UNUSED(ret); } diff --git a/imgui.h b/imgui.h index 3e44b9f40..bcafbf9a8 100644 --- a/imgui.h +++ b/imgui.h @@ -333,7 +333,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various // constructors if you like. You will need to implement ==/!= operators. // History: -// - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requirig 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. +// - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requiring 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. // - In v1.92.0 (2025/06/11): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef #ifndef ImTextureID typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that. @@ -738,7 +738,7 @@ namespace ImGui // 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 decorelate 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 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(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(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); @@ -1275,7 +1275,7 @@ enum ImGuiInputTextFlags_ // - It is much slower than regular text fields. // Ballpark estimate of cost on my 2019 desktop PC: for a 100 KB text buffer: +~0.3 ms (Optimized) / +~1.0 ms (Debug build). // The CPU cost is very roughly proportional to text length, so a 10 KB buffer should cost about ten times less. - ImGuiInputTextFlags_WordWrap = 1 << 24, // InputTextMultine(): word-wrap lines that are too long. + ImGuiInputTextFlags_WordWrap = 1 << 24, // InputTextMultiline(): word-wrap lines that are too long. // Obsolete names //ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior @@ -1302,7 +1302,7 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (label will still fit in current column) ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, // Label will span all columns of its container table //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible - ImGuiTreeNodeFlags_NavLeftJumpsToParent = 1 << 17, // Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfullfilled Left nav request remaining. + ImGuiTreeNodeFlags_NavLeftJumpsToParent = 1 << 17, // Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfulfilled Left nav request remaining. ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, // [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. @@ -2290,7 +2290,7 @@ struct ImGuiStyle float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. float ScrollbarRounding; // Radius of grab corners for scrollbar. - float ScrollbarPadding; // Padding of scrollbar grab within its frame (same for both axises). + float ScrollbarPadding; // Padding of scrollbar grab within its frame (same for both axes). float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. @@ -3409,7 +3409,7 @@ struct ImDrawData ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Copied from viewport->FramebufferScale (== io.DisplayFramebufferScale for main viewport). Generally (1,1) on normal display, (2,2) on OSX with Retina display. ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). - ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overriden or set to NULL if you want to manually update textures. + ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overridden or set to NULL if you want to manually update textures. // Functions ImDrawData() { Clear(); } @@ -4133,7 +4133,7 @@ typedef ImFontAtlasRect ImFontAtlasCustomRect; //}; // RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) -// RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022). Exceptionally commented out ahead of obscolescence schedule to reduce confusion and because they were not meant to be used in the first place. +// RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022). Exceptionally commented out ahead of obsolescence schedule to reduce confusion and because they were not meant to be used in the first place. //typedef ImGuiKeyChord ImGuiModFlags; // == int. We generally use ImGuiKeyChord to mean "a ImGuiKey or-ed with any number of ImGuiMod_XXX value", so you may store mods in there. //enum ImGuiModFlags_ { ImGuiModFlags_None = 0, ImGuiModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiModFlags_Shift = ImGuiMod_Shift, ImGuiModFlags_Alt = ImGuiMod_Alt, ImGuiModFlags_Super = ImGuiMod_Super }; //typedef ImGuiKeyChord ImGuiKeyModFlags; // == int diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a43fd2487..14f70d675 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7031,7 +7031,7 @@ static void DemoWindowTables() // [2.3] Right-click in columns to open another custom popup HelpMarker( "Demonstrate mixing table context menu (over header), item context button (over button) " - "and custom per-colunm context menu (over column body)."); + "and custom per-column context menu (over column body)."); ImGuiTableFlags flags2 = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders; if (ImGui::BeginTable("table_context_menu_2", COLUMNS_COUNT, flags2)) { diff --git a/imgui_internal.h b/imgui_internal.h index 361dd9805..8da4e1aa4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2708,7 +2708,7 @@ struct IMGUI_API ImGuiWindow ImGuiWindow* RootWindowPopupTree; // Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. - ImGuiWindow* ParentWindowForFocusRoute; // Set to manual link a window to its logical parent so that Shortcut() chain are honoerd (e.g. Tool linked to Document) + ImGuiWindow* ParentWindowForFocusRoute; // Set to manual link a window to its logical parent so that Shortcut() chain are honored (e.g. Tool linked to Document) ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) @@ -3029,7 +3029,7 @@ struct IMGUI_API ImGuiTable bool IsContextPopupOpen; // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted). bool DisableDefaultContextMenu; // Disable default context menu. You may submit your own using TableBeginContextMenuPopup()/EndPopup() bool IsSettingsRequestLoad; - bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data. + bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSettings data. bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1) bool IsResetAllRequest; bool IsResetDisplayOrderRequest; @@ -3389,7 +3389,7 @@ namespace ImGui // Legacy functions use ImGuiKeyOwner_Any meaning that they typically ignore ownership, unless a call to SetKeyOwner() explicitly used ImGuiInputFlags_LockThisFrame or ImGuiInputFlags_LockUntilRelease. // - Binding generators may want to ignore those for now, or suffix them with Ex() until we decide if this gets moved into public API. IMGUI_API bool IsKeyDown(ImGuiKey key, ImGuiID owner_id); - IMGUI_API bool IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0); // Important: when transitioning from old to new IsKeyPressed(): old API has "bool repeat = true", so would default to repeat. New API requiress explicit ImGuiInputFlags_Repeat. + IMGUI_API bool IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0); // Important: when transitioning from old to new IsKeyPressed(): old API has "bool repeat = true", so would default to repeat. New API requires explicit ImGuiInputFlags_Repeat. IMGUI_API bool IsKeyReleased(ImGuiKey key, ImGuiID owner_id); IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id = 0); IMGUI_API bool IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index d79cfe435..39e45367b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -451,7 +451,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable(). table->WorkRect = table->OuterRect = table->InnerRect = outer_rect; table->HasScrollbarYPrev = table->HasScrollbarYCurr = false; - table->InnerWindow->DC.TreeDepth++; // This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking accross a table + table->InnerWindow->DC.TreeDepth++; // This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking across a table } // Push a standardized ID for both child-using and not-child-using tables @@ -947,7 +947,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very // large height (= first frame scrollbar display very off + clipper would skip lots of items). // This is merely making the side-effect less extreme, but doesn't properly fixes it. - // FIXME: Move this to ->WidthGiven to avoid temporary lossyless? + // FIXME: Move this to ->WidthGiven to avoid temporary lossyness? // FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller. if (column->AutoFitQueue > 0x01 && table->IsInitializing && !column->IsPreserveWidthAuto) column->WidthRequest = ImMax(column->WidthRequest, table->MinColumnWidth * 4.0f); // FIXME-TABLE: Another constant/scale? @@ -1191,7 +1191,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } // In case the table is visible (e.g. decorations) but all columns clipped, we keep a column visible. - // Else if give no chance to a clipper-savy user to submit rows and therefore total contents height used by scrollbar. + // Else if give no chance to a clipper-savvy user to submit rows and therefore total contents height used by scrollbar. if (has_at_least_one_column_requesting_output == false) { table->Columns[table->LeftMostEnabledColumn].IsRequestOutput = true; @@ -2526,7 +2526,7 @@ void ImGui::TablePopColumnChannel() // - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call) // - Clip --> 2+D+N channels // - FreezeRows --> 2+D+N*2 (unless scrolling value is zero) -// - FreezeRows || FreezeColunns --> 3+D+N*2 (unless scrolling value is zero) +// - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero) // Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0. void ImGui::TableSetupDrawChannels(ImGuiTable* table) { diff --git a/misc/cpp/README.txt b/misc/cpp/README.txt index 17f0a3cd3..5d6aeff13 100644 --- a/misc/cpp/README.txt +++ b/misc/cpp/README.txt @@ -9,5 +9,5 @@ imgui_scoped.h Try by merging: https://github.com/ocornut/imgui/pull/2197 Discuss at: https://github.com/ocornut/imgui/issues/2096 -See more C++ related extension (fmt, RAII, syntaxis sugar) on Wiki: +See more C++ related extension (fmt, RAII, syntactic sugar) on Wiki: https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness diff --git a/misc/cpp/imgui_stdlib.cpp b/misc/cpp/imgui_stdlib.cpp index 7c463ca6b..282ca6234 100644 --- a/misc/cpp/imgui_stdlib.cpp +++ b/misc/cpp/imgui_stdlib.cpp @@ -16,7 +16,7 @@ // ImGui::InputText("my string", &my_string); // } -// See more C++ related extension (fmt, RAII, syntaxis sugar) on Wiki: +// See more C++ related extension (fmt, RAII, syntactic sugar) on Wiki: // https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness #include "imgui.h" From f1becf7e4bd4c7c025448d5d845f1be1f4ba4c6b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Nov 2025 14:31:14 +0100 Subject: [PATCH 1455/2359] Amend 149587b config/build infos change to be resilient to IM_ASSERT() macros using stringification inside a list. --- imgui_demo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 14f70d675..b96d8ea60 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8194,7 +8194,7 @@ void ImGui::ShowAboutWindow(bool* p_open) // - 16 is > strlen("((void)(_EXPR))") which we suggested in our imconfig.h template as a possible way to disable. int assert_runs_expression = 0; IM_ASSERT(++assert_runs_expression); - int assert_expand_len = (int)strlen(IM_STRINGIFY(IM_ASSERT(true))); + int assert_expand_len = (int)strlen(IM_STRINGIFY((IM_ASSERT(true)))); bool assert_maybe_disabled = (!assert_runs_expression || assert_expand_len <= 16); ImGui::Text("IM_ASSERT: runs expression: %s. expand size: %s%s", assert_runs_expression ? "OK" : "KO", (assert_expand_len > 16) ? "OK" : "KO", assert_maybe_disabled ? " (MAYBE DISABLED?!)" : ""); From 3cc8b470a6438a869ae4c404eafc08c663bc17ca Mon Sep 17 00:00:00 2001 From: BrutPitt Date: Sat, 1 Nov 2025 10:43:26 +0100 Subject: [PATCH 1456/2359] =?UTF-8?q?Backends,=20Examples:=20WebGPU:=20hea?= =?UTF-8?q?der=20optimization.=20Added=20the=20code=20for=20using=20Dawn?= =?UTF-8?q?=20=E2=80=9Cpre-built=E2=80=9D=20library.=20(#8381)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backends/imgui_impl_wgpu.cpp | 1 - backends/imgui_impl_wgpu.h | 4 +- examples/example_glfw_wgpu/CMakeLists.txt | 81 ++++++++++++----------- examples/example_sdl2_wgpu/CMakeLists.txt | 80 ++++++++++++---------- examples/example_sdl3_wgpu/CMakeLists.txt | 80 ++++++++++++---------- 5 files changed, 133 insertions(+), 113 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 9ec2e3592..86c30cfd4 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -53,7 +53,6 @@ #include "imgui_impl_wgpu.h" #include #include -#include // One of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details. #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 3e46849b5..3d0cf5cc1 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -41,9 +41,7 @@ #endif #include -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) -#include // for wgpu::Device, wgpu::DeviceLostReason, wgpu::ErrorType used by validation layer callbacks. -#elif !defined(__EMSCRIPTEN__) +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) && !defined(__EMSCRIPTEN__) #include // WGPULogLevel #endif diff --git a/examples/example_glfw_wgpu/CMakeLists.txt b/examples/example_glfw_wgpu/CMakeLists.txt index d8c6eae4f..11248df26 100644 --- a/examples/example_glfw_wgpu/CMakeLists.txt +++ b/examples/example_glfw_wgpu/CMakeLists.txt @@ -85,57 +85,61 @@ else() # Native/Desktop build if(APPLE) # Add SDL2 module to get Surface, with libs and file property for MacOS build set_source_files_properties(${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") -# set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") + set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") endif() + + find_package(glfw3 REQUIRED) if(IMGUI_DAWN_DIR) # DAWN-Native build options - set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - if(NOT IMGUI_DAWN_DIR) - message(FATAL_ERROR "Please specify the Dawn repository by setting IMGUI_DAWN_DIR") - endif() + list(APPEND CMAKE_PREFIX_PATH ${IMGUI_DAWN_DIR}) + find_package(Dawn) # Search for a Dawn installation using IMGUI_DAWN_DIR in CMAKE_PREFIX_PATH + if(Dawn_FOUND) + message("Dawn Installation has been found!") + set(LIBRARIES dawn::webgpu_dawn glfw ${OS_LIBRARIES}) + else() + set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) - set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") + option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) + set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") - # Dawn builds many things by default - disable things we don't need - option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) - option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) - option(TINT_BUILD_DOCS "Build documentation" OFF) - option(TINT_BUILD_TESTS "Build tests" OFF) - if(NOT APPLE) - option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) - endif() - if(WIN32) - option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) - option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) - option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) - option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) - option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) - option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) - option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) - endif() - # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time - # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) - if(LINUX) - if($ENV{XDG_SESSION_TYPE} MATCHES wayland) - option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 + + # Dawn builds many things by default - disable things we don't need + option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) + option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) + option(TINT_BUILD_DOCS "Build documentation" OFF) + option(TINT_BUILD_TESTS "Build tests" OFF) + if(NOT APPLE) + option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) + endif() + if(WIN32) + option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) + option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) + option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) + option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) + option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) + option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) + option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) + endif() + # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time + # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) + if(LINUX) + if($ENV{XDG_SESSION_TYPE} MATCHES wayland) + option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + endif() endif() - endif() - add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) + add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) - set(LIBRARIES webgpu_dawn webgpu_glfw glfw) + set(LIBRARIES webgpu_dawn glfw) + endif() else() # WGPU-Native build options - find_package(glfw3 CONFIG) - set(WGPU_NATIVE_LIB_DIR ${IMGUI_WGPU_DIR}/lib) find_library(WGPU_LIBRARY NAMES libwgpu_native.a wgpu_native.lib wgpu_native HINTS ${WGPU_NATIVE_LIB_DIR} REQUIRED) if(WIN32) set(OS_LIBRARIES d3dcompiler ws2_32 userenv bcrypt ntdll opengl32 Propsys RuntimeObject) elseif(UNIX AND NOT APPLE) set(OS_LIBRARIES "-lm -ldl") - elseif(APPLE) - set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") endif() set(LIBRARIES glfw ${WGPU_LIBRARY} ${OS_LIBRARIES}) @@ -170,12 +174,15 @@ if(NOT EMSCRIPTEN) # WegGPU-Native settings # Set IMGUI_IMPL_WEBGPU_BACKEND_XXXX based on the SDK (directory) used if(IMGUI_DAWN_DIR) target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + if(NOT Dawn_FOUND) + target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp) + endif() else() target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") target_include_directories(${IMGUI_EXECUTABLE} PUBLIC ${IMGUI_WGPU_DIR}/include) endif() + target_link_libraries(${IMGUI_EXECUTABLE} PUBLIC ${LIBRARIES}) - target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp PUBLIC ${LIBRARIES}) else() # Emscripten settings set(CMAKE_EXECUTABLE_SUFFIX ".html") diff --git a/examples/example_sdl2_wgpu/CMakeLists.txt b/examples/example_sdl2_wgpu/CMakeLists.txt index 815c702f6..c4c3eee86 100644 --- a/examples/example_sdl2_wgpu/CMakeLists.txt +++ b/examples/example_sdl2_wgpu/CMakeLists.txt @@ -67,8 +67,6 @@ if(EMSCRIPTEN) add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1) else() # Native/Desktop build - find_package(SDL2 REQUIRED) # SDL_MAIN_HANDLED - if(NOT IMGUI_DAWN_DIR AND NOT IMGUI_WGPU_DIR) # if it's Native/Desktop build, IMGUI_DAWN_DIR or IMGUI_WGPU_DIR must be specified message(FATAL_ERROR "Please specify the Dawn or WGPU base directory") endif() @@ -82,45 +80,52 @@ else() # Native/Desktop build set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") endif() + find_package(SDL2 REQUIRED) # SDL_MAIN_HANDLED + if(IMGUI_DAWN_DIR) # DAWN-Native build options - set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - if(NOT IMGUI_DAWN_DIR) - message(FATAL_ERROR "Please specify the Dawn repository by setting IMGUI_DAWN_DIR") - endif() + list(APPEND CMAKE_PREFIX_PATH ${IMGUI_DAWN_DIR}) + find_package(Threads) # required from Dawn installation + find_package(Dawn) # Search for a Dawn installation using IMGUI_DAWN_DIR in CMAKE_PREFIX_PATH + if(Dawn_FOUND) + message("Dawn Installation has been found!") + set(LIBRARIES dawn::webgpu_dawn ${OS_LIBRARIES}) + else() + set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 + option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 - option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) - set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") + option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) + set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") - # Dawn builds many things by default - disable things we don't need - option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) - option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) - option(TINT_BUILD_DOCS "Build documentation" OFF) - option(TINT_BUILD_TESTS "Build tests" OFF) - if(NOT APPLE) - option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) - endif() - if(WIN32) - option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) - option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) - option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) - option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) - option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) - option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) - option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) - endif() - # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time - # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) - if(LINUX) - if($ENV{XDG_SESSION_TYPE} MATCHES wayland) - option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + # Dawn builds many things by default - disable things we don't need + option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) + option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) + option(TINT_BUILD_DOCS "Build documentation" OFF) + option(TINT_BUILD_TESTS "Build tests" OFF) + if(NOT APPLE) + option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) endif() + if(WIN32) + option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) + option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) + option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) + option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) + option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) + option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) + option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) + endif() + # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time + # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) + if(LINUX) + if($ENV{XDG_SESSION_TYPE} MATCHES wayland) + option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + endif() + endif() + + add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) + + set(LIBRARIES webgpu_dawn ${OS_LIBRARIES}) endif() - - add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) - - set(LIBRARIES webgpu_dawn ${OS_LIBRARIES}) else() # WGPU-Native build options set(WGPU_NATIVE_LIB_DIR ${IMGUI_WGPU_DIR}/lib) @@ -163,12 +168,15 @@ endif() if(NOT EMSCRIPTEN) # WegGPU-Native settings if(IMGUI_DAWN_DIR) target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + if(NOT Dawn_FOUND) + target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp) + endif() else() target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") target_include_directories(${IMGUI_EXECUTABLE} PUBLIC ${IMGUI_WGPU_DIR}/include) endif() - target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp PUBLIC ${LIBRARIES} ${SDL2_LIBRARIES}) + target_link_libraries(${IMGUI_EXECUTABLE} PUBLIC ${LIBRARIES} ${SDL2_LIBRARIES}) else() # Emscripten settings set(CMAKE_EXECUTABLE_SUFFIX ".html") diff --git a/examples/example_sdl3_wgpu/CMakeLists.txt b/examples/example_sdl3_wgpu/CMakeLists.txt index 05d57650c..0b8dc48e9 100644 --- a/examples/example_sdl3_wgpu/CMakeLists.txt +++ b/examples/example_sdl3_wgpu/CMakeLists.txt @@ -70,8 +70,6 @@ if(EMSCRIPTEN) add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1) else() # Native/Desktop build - find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3) - if(NOT IMGUI_DAWN_DIR AND NOT IMGUI_WGPU_DIR) # if it's Native/Desktop build, IMGUI_DAWN_DIR or IMGUI_WGPU_DIR must be specified message(FATAL_ERROR "Please specify the Dawn or WGPU base directory") endif() @@ -85,45 +83,52 @@ else() # Native/Desktop build set(OS_LIBRARIES "-framework CoreFoundation -framework QuartzCore -framework Metal -framework MetalKit -framework Cocoa") endif() + find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3) + if(IMGUI_DAWN_DIR) # DAWN-Native build options - set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - if(NOT IMGUI_DAWN_DIR) - message(FATAL_ERROR "Please specify the Dawn repository by setting IMGUI_DAWN_DIR") - endif() + list(APPEND CMAKE_PREFIX_PATH ${IMGUI_DAWN_DIR}) + find_package(Threads) # required from Dawn installation + find_package(Dawn) # Search for a Dawn installation using IMGUI_DAWN_DIR in CMAKE_PREFIX_PATH + if(Dawn_FOUND) + message("Dawn Installation has been found!") + set(LIBRARIES dawn::webgpu_dawn ${OS_LIBRARIES}) + else() + set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 + option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 - option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) - set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") + option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) + set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") - # Dawn builds many things by default - disable things we don't need - option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) - option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) - option(TINT_BUILD_DOCS "Build documentation" OFF) - option(TINT_BUILD_TESTS "Build tests" OFF) - if(NOT APPLE) - option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) - endif() - if(WIN32) - option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) - option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) - option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) - option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) - option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) - option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) - option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) - endif() - # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time - # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) - if(LINUX) - if($ENV{XDG_SESSION_TYPE} MATCHES wayland) - option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + # Dawn builds many things by default - disable things we don't need + option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) + option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF) + option(TINT_BUILD_DOCS "Build documentation" OFF) + option(TINT_BUILD_TESTS "Build tests" OFF) + if(NOT APPLE) + option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF) endif() + if(WIN32) + option(DAWN_FORCE_SYSTEM_COMPONENT_LOAD "Allow system component fallback" ON) + option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF) + option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON) + option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF) + option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF) + option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" ON) + option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON) + endif() + # check if WAYLAND is the current Session Type and enable DAWN_USE_WAYLAND Wayland option @compile time + # You can override this using: cmake -DDAWN_USE_WAYLAND=X (X = ON | OFF) + if(LINUX) + if($ENV{XDG_SESSION_TYPE} MATCHES wayland) + option(DAWN_USE_WAYLAND "Enable support for Wayland surface" ON) + endif() + endif() + + add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) + + set(LIBRARIES webgpu_dawn ${OS_LIBRARIES}) endif() - - add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL) - - set(LIBRARIES webgpu_dawn ${OS_LIBRARIES}) else() # WGPU-Native build options set(WGPU_NATIVE_LIB_DIR ${IMGUI_WGPU_DIR}/lib) find_library(WGPU_LIBRARY NAMES libwgpu_native.a wgpu_native.lib wgpu_native HINTS ${WGPU_NATIVE_LIB_DIR} REQUIRED) @@ -165,12 +170,15 @@ endif() if(NOT EMSCRIPTEN) # WegGPU-Native settings if(IMGUI_DAWN_DIR) target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_DAWN") + if(NOT Dawn_FOUND) + target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp) + endif() else() target_compile_definitions(${IMGUI_EXECUTABLE} PUBLIC "IMGUI_IMPL_WEBGPU_BACKEND_WGPU") target_include_directories(${IMGUI_EXECUTABLE} PUBLIC ${IMGUI_WGPU_DIR}/include) endif() - target_link_libraries(${IMGUI_EXECUTABLE} INTERFACE webgpu_cpp PUBLIC ${LIBRARIES} SDL3::SDL3) + target_link_libraries(${IMGUI_EXECUTABLE} PUBLIC ${LIBRARIES} SDL3::SDL3) else() # Emscripten settings set(CMAKE_EXECUTABLE_SUFFIX ".html") From 8e5e79054e7f05fe9afe072e3b0c1fab4e7b380e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Nov 2025 19:04:44 +0100 Subject: [PATCH 1457/2359] Examples: WGPU: tweak headers and standardize other things so examples have less differences. (#8381) --- examples/example_glfw_wgpu/main.cpp | 10 +++++----- examples/example_sdl2_wgpu/main.cpp | 17 ++++++++++------- examples/example_sdl3_wgpu/main.cpp | 16 ++++++++-------- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 9ea267154..36ca9074b 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -22,13 +22,12 @@ #if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) #include #endif -#include -#include #include "../libs/emscripten/emscripten_mainloop_stub.h" -#else -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) -#include #endif + +#include +#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) +#include #endif // Data @@ -323,6 +322,7 @@ int main(int, char**) #endif #include #undef Status // X11 headers are leaking this. +#undef Success // X11 headers are leaking this. WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, GLFWwindow* window) { diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index 1d95da572..3911cc58a 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -30,13 +30,13 @@ #endif // Data -WGPUInstance wgpu_instance = nullptr; -WGPUDevice wgpu_device = nullptr; -WGPUSurface wgpu_surface = nullptr; -WGPUQueue wgpu_queue = nullptr; -WGPUSurfaceConfiguration wgpu_surface_configuration = {}; -int wgpu_surface_width = 1280; -int wgpu_surface_height = 800; +static WGPUInstance wgpu_instance = nullptr; +static WGPUDevice wgpu_device = nullptr; +static WGPUSurface wgpu_surface = nullptr; +static WGPUQueue wgpu_queue = nullptr; +static WGPUSurfaceConfiguration wgpu_surface_configuration = {}; +static int wgpu_surface_width = 1280; +static int wgpu_surface_height = 800; // Forward declarations static bool InitWGPU(SDL_Window* window); @@ -282,6 +282,9 @@ int main(int, char**) #if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) #include +#undef Status // X11 headers are leaking this. +#undef Success // X11 headers are leaking this. + WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) { SDL_SysWMinfo sysWMInfo; diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index 377ffd9bb..63bfd8c66 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -32,18 +32,18 @@ #endif // Data -WGPUInstance wgpu_instance = nullptr; -WGPUDevice wgpu_device = nullptr; -WGPUSurface wgpu_surface = nullptr; -WGPUQueue wgpu_queue = nullptr; -WGPUSurfaceConfiguration wgpu_surface_configuration = {}; -int wgpu_surface_width = 1280; -int wgpu_surface_height = 800; +static WGPUInstance wgpu_instance = nullptr; +static WGPUDevice wgpu_device = nullptr; +static WGPUSurface wgpu_surface = nullptr; +static WGPUQueue wgpu_queue = nullptr; +static WGPUSurfaceConfiguration wgpu_surface_configuration = {}; +static int wgpu_surface_width = 1280; +static int wgpu_surface_height = 800; // Forward declarations static bool InitWGPU(SDL_Window* window); -void ResizeSurface(int width, int height) +static void ResizeSurface(int width, int height) { wgpu_surface_configuration.width = wgpu_surface_width = width; wgpu_surface_configuration.height = wgpu_surface_height = height; From df3f2fff88ca91fb9ec2e0ee681021d87a57d740 Mon Sep 17 00:00:00 2001 From: BrutPitt Date: Sat, 1 Nov 2025 10:41:59 +0100 Subject: [PATCH 1458/2359] Examples: WebGPU: moved CreateWGPUSurface to the bottom of the file due to interference with X.h. (#8381) --- examples/example_glfw_wgpu/main.cpp | 150 ++++++++++++++-------------- examples/example_sdl2_wgpu/main.cpp | 109 ++++++++++---------- examples/example_sdl3_wgpu/main.cpp | 112 ++++++++++----------- 3 files changed, 185 insertions(+), 186 deletions(-) diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 36ca9074b..2fd746903 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -40,7 +40,8 @@ static int wgpu_surface_width = 1280; static int wgpu_surface_height = 800; // Forward declarations -static bool InitWGPU(GLFWwindow* window); +static bool InitWGPU(GLFWwindow* window); +static WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, GLFWwindow* window); static void glfw_error_callback(int error, const char* description) { @@ -290,80 +291,6 @@ int main(int, char**) return 0; } -// GLFW helper to create a WebGPU surface, used only in WGPU-Native. DAWN-Native already has a built-in function -// As of today (2025/10) there is no "official" support in GLFW to create a surface for WebGPU backend -// This stub uses "low level" GLFW calls to acquire information from a specific Window Manager. -// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. -#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) - -#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) -#define GLFW_HAS_X11_OR_WAYLAND 1 -#else -#define GLFW_HAS_X11_OR_WAYLAND 0 -#endif -#ifdef _WIN32 -#undef APIENTRY -#ifndef GLFW_EXPOSE_NATIVE_WIN32 // for glfwGetWin32Window() -#define GLFW_EXPOSE_NATIVE_WIN32 -#endif -#elif defined(__APPLE__) -#ifndef GLFW_EXPOSE_NATIVE_COCOA // for glfwGetCocoaWindow() -#define GLFW_EXPOSE_NATIVE_COCOA -#endif -#elif GLFW_HAS_X11_OR_WAYLAND -#ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Display(), glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) -#define GLFW_EXPOSE_NATIVE_X11 -#endif -#ifndef GLFW_EXPOSE_NATIVE_WAYLAND -#if defined(__has_include) && __has_include() -#define GLFW_EXPOSE_NATIVE_WAYLAND -#endif -#endif -#endif -#include -#undef Status // X11 headers are leaking this. -#undef Success // X11 headers are leaking this. - -WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, GLFWwindow* window) -{ - ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; - create_info.Instance = instance; -#if defined(GLFW_EXPOSE_NATIVE_COCOA) - { - create_info.System = "cocoa"; - create_info.RawWindow = (void*)glfwGetCocoaWindow(window); - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#elif defined(GLFW_EXPOSE_NATIVE_WAYLAND) - if (glfwGetPlatform() == GLFW_PLATFORM_WAYLAND) - { - create_info.System = "wayland"; - create_info.RawDisplay = (void*)glfwGetWaylandDisplay(); - create_info.RawSurface = (void*)glfwGetWaylandWindow(window); - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#elif defined(GLFW_EXPOSE_NATIVE_X11) - if (glfwGetPlatform() == GLFW_PLATFORM_X11) - { - create_info.System = "x11"; - create_info.RawWindow = (void*)glfwGetX11Window(window); - create_info.RawDisplay = (void*)glfwGetX11Display(); - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#elif defined(GLFW_EXPOSE_NATIVE_WIN32) - { - create_info.System = "win32"; - create_info.RawWindow = (void*)glfwGetWin32Window(window); - create_info.RawInstance = (void*)::GetModuleHandle(NULL); - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#else -#error "Unsupported WebGPU native platform!" -#endif - return nullptr; -} -#endif - #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -574,3 +501,76 @@ static bool InitWGPU(GLFWwindow* window) return true; } + +// GLFW helper to create a WebGPU surface, used only in WGPU-Native. DAWN-Native already has a built-in function +// As of today (2025/10) there is no "official" support in GLFW to create a surface for WebGPU backend +// This stub uses "low level" GLFW calls to acquire information from a specific Window Manager. +// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. +#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) + +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) +#define GLFW_HAS_X11_OR_WAYLAND 1 +#else +#define GLFW_HAS_X11_OR_WAYLAND 0 +#endif +#ifdef _WIN32 +#undef APIENTRY +#ifndef GLFW_EXPOSE_NATIVE_WIN32 // for glfwGetWin32Window() +#define GLFW_EXPOSE_NATIVE_WIN32 +#endif +#elif defined(__APPLE__) +#ifndef GLFW_EXPOSE_NATIVE_COCOA // for glfwGetCocoaWindow() +#define GLFW_EXPOSE_NATIVE_COCOA +#endif +#elif GLFW_HAS_X11_OR_WAYLAND +#ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Display(), glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) +#define GLFW_EXPOSE_NATIVE_X11 +#endif +#ifndef GLFW_EXPOSE_NATIVE_WAYLAND +#if defined(__has_include) && __has_include() +#define GLFW_EXPOSE_NATIVE_WAYLAND +#endif +#endif +#endif +#include +#undef Status // X11 headers are leaking this and also 'Success', 'Always', 'None', all used in DAWN api. Add #undef if necessary. + +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, GLFWwindow* window) +{ + ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; + create_info.Instance = instance; +#if defined(GLFW_EXPOSE_NATIVE_COCOA) + { + create_info.System = "cocoa"; + create_info.RawWindow = (void*)glfwGetCocoaWindow(window); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(GLFW_EXPOSE_NATIVE_WAYLAND) + if (glfwGetPlatform() == GLFW_PLATFORM_WAYLAND) + { + create_info.System = "wayland"; + create_info.RawDisplay = (void*)glfwGetWaylandDisplay(); + create_info.RawSurface = (void*)glfwGetWaylandWindow(window); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(GLFW_EXPOSE_NATIVE_X11) + if (glfwGetPlatform() == GLFW_PLATFORM_X11) + { + create_info.System = "x11"; + create_info.RawWindow = (void*)glfwGetX11Window(window); + create_info.RawDisplay = (void*)glfwGetX11Display(); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(GLFW_EXPOSE_NATIVE_WIN32) + { + create_info.System = "win32"; + create_info.RawWindow = (void*)glfwGetWin32Window(window); + create_info.RawInstance = (void*)::GetModuleHandle(NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#else +#error "Unsupported WebGPU native platform!" +#endif + return nullptr; +} +#endif diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index 3911cc58a..bddc91b39 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -24,7 +24,6 @@ #include "../libs/emscripten/emscripten_mainloop_stub.h" #endif -#include #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) #include #endif @@ -40,6 +39,7 @@ static int wgpu_surface_height = 800; // Forward declarations static bool InitWGPU(SDL_Window* window); +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window); static void ResizeSurface(int width, int height) { @@ -275,60 +275,6 @@ int main(int, char**) return 0; } -// SDL2 helper to create a WebGPU surface (exclusively!) for Native/Desktop applications: available only together with WebGPU/WGPU backend -// As of today (2025/10/31) there is no "official" support in SDL2 to create a surface for WebGPU backend. -// This stub uses "low level" SDL2 calls to acquire information from a specific Window Manager. -// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. -#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) - -#include -#undef Status // X11 headers are leaking this. -#undef Success // X11 headers are leaking this. - -WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) -{ - SDL_SysWMinfo sysWMInfo; - SDL_VERSION(&sysWMInfo.version); - SDL_GetWindowWMInfo(window, &sysWMInfo); - - ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; - create_info.Instance = instance; -#if defined(SDL_VIDEO_DRIVER_COCOA) - { - create_info.System = "cocoa"; - create_info.RawWindow = (void*)sysWMInfo.info.cocoa.window; - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#elif defined(SDL_VIDEO_DRIVER_WAYLAND) || defined(SDL_VIDEO_DRIVER_X11) - const char* sdl_driver = SDL_GetCurrentVideoDriver(); - if (sdl_driver && strcmp(sdl_driver, "wayland") == 0) - { - create_info.System = "wayland"; - create_info.RawDisplay = (void*)sysWMInfo.info.wl.display; - create_info.RawSurface = (void*)sysWMInfo.info.wl.surface; - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } - else - { - create_info.System = "x11"; - create_info.RawWindow = (void*)sysWMInfo.info.x11.window; - create_info.RawDisplay = (void*)sysWMInfo.info.x11.display; - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#elif defined(SDL_VIDEO_DRIVER_WINDOWS) - { - create_info.System = "win32"; - create_info.RawWindow = (void*)sysWMInfo.info.win.window; - create_info.RawInstance = (void*)sysWMInfo.info.win.hinstance; - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#else -#error "Unsupported WebGPU native platform!" -#endif - return nullptr; -} -#endif - #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -540,3 +486,56 @@ static bool InitWGPU(SDL_Window* window) return true; } + +// SDL2 helper to create a WebGPU surface (exclusively!) for Native/Desktop applications: available only together with WebGPU/WGPU backend +// As of today (2025/10/31) there is no "official" support in SDL2 to create a surface for WebGPU backend. +// This stub uses "low level" SDL2 calls to acquire information from a specific Window Manager. +// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. +#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) + +#include +#undef Status // X11 headers are leaking this and also 'Success', 'Always', 'None', all used in DAWN api. Add #undef if necessary. + +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) +{ + SDL_SysWMinfo sysWMInfo; + SDL_VERSION(&sysWMInfo.version); + SDL_GetWindowWMInfo(window, &sysWMInfo); + + ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; + create_info.Instance = instance; +#if defined(SDL_VIDEO_DRIVER_COCOA) + { + create_info.System = "cocoa"; + create_info.RawWindow = (void*)sysWMInfo.info.cocoa.window; + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(SDL_VIDEO_DRIVER_WAYLAND) || defined(SDL_VIDEO_DRIVER_X11) + const char* sdl_driver = SDL_GetCurrentVideoDriver(); + if (sdl_driver && strcmp(sdl_driver, "wayland") == 0) + { + create_info.System = "wayland"; + create_info.RawDisplay = (void*)sysWMInfo.info.wl.display; + create_info.RawSurface = (void*)sysWMInfo.info.wl.surface; + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } + else + { + create_info.System = "x11"; + create_info.RawWindow = (void*)sysWMInfo.info.x11.window; + create_info.RawDisplay = (void*)sysWMInfo.info.x11.display; + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(SDL_VIDEO_DRIVER_WINDOWS) + { + create_info.System = "win32"; + create_info.RawWindow = (void*)sysWMInfo.info.win.window; + create_info.RawInstance = (void*)sysWMInfo.info.win.hinstance; + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#else +#error "Unsupported WebGPU native platform!" +#endif + return nullptr; +} +#endif diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index 63bfd8c66..abfbf6cfa 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -26,7 +26,6 @@ #include "../libs/emscripten/emscripten_mainloop_stub.h" #endif -#include #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) #include #endif @@ -41,7 +40,8 @@ static int wgpu_surface_width = 1280; static int wgpu_surface_height = 800; // Forward declarations -static bool InitWGPU(SDL_Window* window); +static bool InitWGPU(SDL_Window* window); +static WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window); static void ResizeSurface(int width, int height) { @@ -286,60 +286,6 @@ int main(int, char**) return 0; } -// SDL3 helper to create a WebGPU surface (exclusively!) for Native/Desktop applications: available only together with WebGPU/WGPU backend -// As of today (2025/10) there is no "official" support in SDL3 to create a surface for WebGPU backend -// This stub uses "low level" SDL3 calls to acquire information from a specific Window Manager. -// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. -#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) - -#if defined(SDL_PLATFORM_WIN32) -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN 1 -#endif -#include -#endif - -WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) -{ - SDL_PropertiesID propertiesID = SDL_GetWindowProperties(window); - - ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; - create_info.Instance = instance; -#if defined(SDL_PLATFORM_MACOS) - { - create_info.System = "cocoa"; - create_info.RawWindow = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL); - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#elif defined(SDL_PLATFORM_LINUX) - if (SDL_strcmp(SDL_GetCurrentVideoDriver(), "wayland") == 0) - { - create_info.System = "wayland"; - create_info.RawDisplay = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER, NULL); - create_info.RawSurface = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, NULL); - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } - else if (!SDL_strcmp(SDL_GetCurrentVideoDriver(), "x11")) - { - create_info.System = "x11"; - create_info.RawWindow = (void*)SDL_GetNumberProperty(propertiesID, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0); - create_info.RawDisplay = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_X11_DISPLAY_POINTER, NULL); - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#elif defined(SDL_PLATFORM_WIN32) - { - create_info.System = "win32"; - create_info.RawWindow = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL); - create_info.RawInstance = (void*)::GetModuleHandle(NULL); - return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); - } -#else -#error "Unsupported WebGPU native platform!" -#endif - return nullptr; -} -#endif - #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -551,3 +497,57 @@ static bool InitWGPU(SDL_Window* window) return true; } + +// SDL3 helper to create a WebGPU surface (exclusively!) for Native/Desktop applications: available only together with WebGPU/WGPU backend +// As of today (2025/10) there is no "official" support in SDL3 to create a surface for WebGPU backend +// This stub uses "low level" SDL3 calls to acquire information from a specific Window Manager. +// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. +#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) + +#if defined(SDL_PLATFORM_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include +#endif + +static WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) +{ + SDL_PropertiesID propertiesID = SDL_GetWindowProperties(window); + + ImGui_ImplWGPU_CreateSurfaceInfo create_info = {}; + create_info.Instance = instance; +#if defined(SDL_PLATFORM_MACOS) + { + create_info.System = "cocoa"; + create_info.RawWindow = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(SDL_PLATFORM_LINUX) + if (SDL_strcmp(SDL_GetCurrentVideoDriver(), "wayland") == 0) + { + create_info.System = "wayland"; + create_info.RawDisplay = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER, NULL); + create_info.RawSurface = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } + else if (!SDL_strcmp(SDL_GetCurrentVideoDriver(), "x11")) + { + create_info.System = "x11"; + create_info.RawWindow = (void*)SDL_GetNumberProperty(propertiesID, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0); + create_info.RawDisplay = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_X11_DISPLAY_POINTER, NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#elif defined(SDL_PLATFORM_WIN32) + { + create_info.System = "win32"; + create_info.RawWindow = (void*)SDL_GetPointerProperty(propertiesID, SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL); + create_info.RawInstance = (void*)::GetModuleHandle(NULL); + return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info); + } +#else +#error "Unsupported WebGPU native platform!" +#endif + return nullptr; +} +#endif From dc6e0f4b9e14b99c85c7caa00daf78576c0df7f8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Nov 2025 19:35:19 +0100 Subject: [PATCH 1459/2359] Tables: Angled headers: fixed an auto-resize feedback loop that could affect tables with empty non-resizing columns using angled headers. --- docs/CHANGELOG.txt | 3 +++ imgui_tables.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bea104171..e2cca4da7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,9 @@ Other Changes: result in temporarily incorrect state, which would lead to bugs to side effects in various locations, e.g. GetContentRegionAvail() calls or using clipper. (#9005) EndTable() was mistakenly restoring a wrong current table. +- Tables: Angled headers: fixed an auto-resize feedback loop that could + affect tables with empty non-resizing columns using angled headers, making + them typically flicker back and forth between +0 and +1 pixels. - Disabled: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) - InputText: when buffer is not resizable, trying to paste contents that diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 39e45367b..faf859141 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3421,7 +3421,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label // Left<>Right alignment float line_off_curr_x = flip_label ? (label_lines - 1) * line_off_step_x : 0.0f; - float line_off_for_align_x = ImMax((((column->MaxX - column->MinX) - padding.x * 2.0f) - (label_lines * line_off_step_x)), 0.0f) * align.x; + float line_off_for_align_x = ImFloor(ImMax((((column->MaxX - column->MinX) - padding.x * 2.0f) - (label_lines * line_off_step_x)), 0.0f) * align.x); line_off_curr_x += line_off_for_align_x - line_off_for_ascent_x; // Register header width From 051a31594fa047a818e176cb509aa39785def34f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 3 Nov 2025 19:48:57 +0100 Subject: [PATCH 1460/2359] Metrics: fixed table and columns rect highlight from display when metrics window is not in the same viewport as the table. --- docs/CHANGELOG.txt | 7 +++++-- imgui.cpp | 8 ++++---- imgui_tables.cpp | 6 +++--- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e2cca4da7..4450c9baf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,8 +76,11 @@ Other Changes: - Demo: About Box: emit infos to convey when IM_ASSERT() macro is disabled, - so users don't miss out on programming errors being reported. - so it is included in config/build info submitted in new GitHub Issues. -- Debug Tools: fixed DebugTextEncoding() potentially reading out of bounds - if provided a trailing truncated UTF-8 sequence. +- Debug Tools: + - Fixed DebugTextEncoding() potentially reading out of bounds when + provided a trailing truncated UTF-8 sequence. + - Metrics: fixed table and columns rect highlight from display when + debug/metrics window is not in the same viewport as the table. - Backends: - GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) [@jagot] diff --git a/imgui.cpp b/imgui.cpp index 5a3a28af5..dc7fa4440 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16416,7 +16416,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name); if (IsItemHovered()) - GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + GetForegroundDrawList(table->OuterWindow)->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); Indent(); char buf[128]; for (int rect_n = 0; rect_n < TRT_Count; rect_n++) @@ -16431,7 +16431,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]); Selectable(buf); if (IsItemHovered()) - GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); } } else @@ -16440,7 +16440,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]); Selectable(buf); if (IsItemHovered()) - GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); } } Unindent(); @@ -17328,7 +17328,7 @@ void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label) if (!is_active) { PopStyleColor(); } if (is_active && IsItemHovered()) { - ImDrawList* draw_list = GetForegroundDrawList(); + ImDrawList* draw_list = GetForegroundDrawList(tab_bar->Window); draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index faf859141..e3a3baea2 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -4028,9 +4028,9 @@ void ImGui::DebugNodeTable(ImGuiTable* table) bool open = TreeNode(table, "Table 0x%08X (%d columns, in '%s')%s", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? "" : " *Inactive*"); if (!is_active) { PopStyleColor(); } if (IsItemHovered()) - GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); + GetForegroundDrawList(table->OuterWindow)->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); if (IsItemVisible() && table->HoveredColumnBody != -1) - GetForegroundDrawList()->AddRect(GetItemRectMin(), GetItemRectMax(), IM_COL32(255, 255, 0, 255)); + GetForegroundDrawList(table->OuterWindow)->AddRect(GetItemRectMin(), GetItemRectMax(), IM_COL32(255, 255, 0, 255)); if (!open) return; if (table->InstanceCurrent > 0) @@ -4084,7 +4084,7 @@ void ImGui::DebugNodeTable(ImGuiTable* table) if (IsItemHovered()) { ImRect r(column->MinX, table->OuterRect.Min.y, column->MaxX, table->OuterRect.Max.y); - GetForegroundDrawList()->AddRect(r.Min, r.Max, IM_COL32(255, 255, 0, 255)); + GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min, r.Max, IM_COL32(255, 255, 0, 255)); } } if (ImGuiTableSettings* settings = TableGetBoundSettings(table)) From 1897248bda4873654bc79cddebb8a9119f16467a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 4 Nov 2025 17:55:18 +0100 Subject: [PATCH 1461/2359] Misc: added assert to detect ~ImGuiContext() called without DestroyContext(). (#9051) --- imgui.cpp | 5 +++++ imgui_internal.h | 1 + 2 files changed, 6 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index dc7fa4440..46a6fd79d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4277,6 +4277,11 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) memset(TempKeychordName, 0, sizeof(TempKeychordName)); } +ImGuiContext::~ImGuiContext() +{ + IM_ASSERT(Initialized == false && "Forgot to call DestroyContext()?"); +} + void ImGui::Initialize() { ImGuiContext& g = *GImGui; diff --git a/imgui_internal.h b/imgui_internal.h index 8da4e1aa4..810036b96 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2546,6 +2546,7 @@ struct ImGuiContext char TempKeychordName[64]; ImGuiContext(ImFontAtlas* shared_font_atlas); + ~ImGuiContext(); }; //----------------------------------------------------------------------------- From e674f57bb61065fcd97647839e13aa2afbd46baa Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Nov 2025 18:54:47 +0100 Subject: [PATCH 1462/2359] Backends: SDL3: Fixed an issue with missing characters events when an already active text field changes viewports. (#9054) Always use SDL_GetKeyboardFocus(). (tried to defer ImGui_ImplSDL3_PlatformSetImeData() processing for when OS-window is available but it didn't actually work because we don't systemetically OS-focus new viewports and SDL3 only sent characters to keyboard focused window.) --- backends/imgui_impl_sdl3.cpp | 42 +++++++++++++++++++++++++++--------- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- 3 files changed, 35 insertions(+), 11 deletions(-) diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 3ddd4a7f7..0a8647794 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-11-05: Fixed an issue with missing characters events when an already active text field changes viewports. (#9054) // 2025-10-22: Fixed Platform_OpenInShellFn() return value (unused in core). // 2025-09-24: Skip using the SDL_GetGlobalMouseState() state when one of our window is hovered, as the SDL_EVENT_MOUSE_MOTION data is reliable. Fix macOS notch mouse coordinates issue in fullscreen mode + better perf on X11. (#7919, #7786) // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. @@ -112,6 +113,8 @@ struct ImGui_ImplSDL3_Data // IME handling SDL_Window* ImeWindow; + ImGuiPlatformImeData ImeData; + bool ImeDirty; // Mouse handling Uint32 MouseWindowID; @@ -139,6 +142,9 @@ static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplSDL3_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } +// Forward Declarations +static void ImGui_ImplSDL3_UpdateIme(); + // Functions static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*) { @@ -154,16 +160,38 @@ static void ImGui_ImplSDL3_SetClipboardText(ImGuiContext*, const char* text) SDL_SetClipboardText(text); } -static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) +static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); - SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle; - SDL_Window* window = SDL_GetWindowFromID(window_id); + return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr; +} + +static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData* data) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + bd->ImeData = *data; + bd->ImeDirty = true; + ImGui_ImplSDL3_UpdateIme(); +} + +// We discard viewport passed via ImGuiPlatformImeData and always call SDL_StartTextInput() on SDL_GetKeyboardFocus(). +static void ImGui_ImplSDL3_UpdateIme() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGuiPlatformImeData* data = &bd->ImeData; + SDL_Window* window = SDL_GetKeyboardFocus(); + + // Stop previous input if ((!(data->WantVisible || data->WantTextInput) || bd->ImeWindow != window) && bd->ImeWindow != nullptr) { SDL_StopTextInput(bd->ImeWindow); bd->ImeWindow = nullptr; } + if ((!bd->ImeDirty && bd->ImeWindow == window) || (window == NULL)) + return; + + // Start/update current input + bd->ImeDirty = false; if (data->WantVisible) { SDL_Rect r; @@ -340,13 +368,6 @@ static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0); } - -static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id) -{ - ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); - return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr; -} - // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. @@ -835,6 +856,7 @@ void ImGui_ImplSDL3_NewFrame() ImGui_ImplSDL3_UpdateMouseData(); ImGui_ImplSDL3_UpdateMouseCursor(); + ImGui_ImplSDL3_UpdateIme(); // Update game controllers (if enabled and available) ImGui_ImplSDL3_UpdateGamepads(); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4450c9baf..aa9feda65 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -86,6 +86,8 @@ Other Changes: are not available. (#9024, #8969, #8921, #8920) [@jagot] - SDL3: fixed Platform_OpenInShellFn() return value (the return value was unused in core but might be used by a direct caller). (#9027) [@achabense] + - SDL3: fixed an issue with missing characters events when an already active text + field changes viewports. (#9054) - Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] - WebGPU: added various internal/optional helpers to wrap some of the diff --git a/imgui.cpp b/imgui.cpp index 46a6fd79d..05ae2f026 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5870,9 +5870,9 @@ void ImGui::EndFrame() ImGuiPlatformImeData* ime_data = &g.PlatformImeData; if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) { - IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y); IM_ASSERT(ime_data->ViewportId == IMGUI_VIEWPORT_DEFAULT_ID); // master branch ImGuiViewport* viewport = GetMainViewport(); + IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y, viewport->ID); g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data); } g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0; From a0bfbe4d8f6ddf7f678e6aeac7b1253fe2fc9cda Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Nov 2025 20:14:34 +0100 Subject: [PATCH 1463/2359] Windows: BgClickFlags inherited by default + missing info in Changelog. Amend 40f9e4e. (#899, #3071, #5044, #3379) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index aa9feda65..5590ba798 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,9 @@ Other Changes: - Tables: Angled headers: fixed an auto-resize feedback loop that could affect tables with empty non-resizing columns using angled headers, making them typically flicker back and forth between +0 and +1 pixels. +- Windows: io.ConfigWindowsMoveFromTitleBarOnly is latched during Begin(), + effectively allowing to change the value on a per-window basis (although + there is a better internal mechanism for it). - Disabled: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) - InputText: when buffer is not resizable, trying to paste contents that diff --git a/imgui.cpp b/imgui.cpp index 05ae2f026..89a57174c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7949,7 +7949,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Set default BgClickFlags // This is set at the end of this function, so UpdateManualResize()/ClampWindowPos() may use last-frame value if overriden by user code. // FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button. - window->BgClickFlags = g.IO.ConfigWindowsMoveFromTitleBarOnly ? ImGuiWindowBgClickFlags_None : ImGuiWindowBgClickFlags_Move; + window->BgClickFlags = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->BgClickFlags : (g.IO.ConfigWindowsMoveFromTitleBarOnly ? ImGuiWindowBgClickFlags_None : ImGuiWindowBgClickFlags_Move); // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). // This is useful to allow creating context menus on title bar only, etc. From 59db6ceeb15ea7b685c2564a7bc889fd5ba7eef9 Mon Sep 17 00:00:00 2001 From: Clownacy Date: Wed, 5 Nov 2025 19:49:15 +0000 Subject: [PATCH 1464/2359] Backends: GLFW: lower minimum requirement from GLFW 3.1 to GLFW 3.0. (#9055) --- backends/imgui_impl_glfw.cpp | 18 ++++++++++++++---- backends/imgui_impl_glfw.h | 2 +- docs/CHANGELOG.txt | 2 ++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index d7c208b93..5f7bcd126 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -1,14 +1,14 @@ // dear imgui: Platform Backend for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) -// (Requires: GLFW 3.1+. Prefer GLFW 3.3+ or GLFW 3.4+ for full feature support.) +// (Requires: GLFW 3.0+. Prefer GLFW 3.3+/3.4+ for full feature support.) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors) with GLFW 3.1+. Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Multiple Dear ImGui contexts support. // Missing features or Issues: // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-11-06: Lower minimum requirement to GLFW 3.0. Though a recent version e.g GLFW 3.4 is highly recommended. // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Content Scales are always reported as 1.0 on Wayland. FramebufferScale are always reported as 1.0 on X11. (#8920, #8921) // 2025-07-08: Made ImGui_ImplGlfw_GetContentScaleForWindow(), ImGui_ImplGlfw_GetContentScaleForMonitor() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733) @@ -152,6 +153,7 @@ #else #define GLFW_HAS_NEW_CURSORS (0) #endif +#define GLFW_HAS_CREATECURSOR (GLFW_VERSION_COMBINED >= 3100) // 3.1+ glfwCreateCursor() #define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName() #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError() @@ -182,7 +184,9 @@ struct ImGui_ImplGlfw_Data GlfwClientApi ClientApi; double Time; GLFWwindow* MouseWindow; +#if GLFW_HAS_CREATECURSOR GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT]; +#endif ImVec2 LastValidMousePos; bool IsWayland; bool InstalledCallbacks; @@ -653,7 +657,9 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_glfw (%d)", GLFW_VERSION_COMBINED); io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = bd->BackendPlatformName; +#if GLFW_HAS_CREATECURSOR io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) +#endif io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Context = ImGui::GetCurrentContext(); @@ -679,6 +685,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist, // GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting. // Missing cursors will return nullptr and our _UpdateMouseCursor() function will use the Arrow cursor instead.) +#if GLFW_HAS_CREATECURSOR GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr); bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR); @@ -697,6 +704,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); #endif glfwSetErrorCallback(prev_error_callback); +#endif #if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908) (void)glfwGetError(nullptr); #endif @@ -775,10 +783,10 @@ void ImGui_ImplGlfw_Shutdown() if (bd->CanvasSelector) emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, nullptr); #endif - +#if GLFW_HAS_CREATECURSOR for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) glfwDestroyCursor(bd->MouseCursors[cursor_n]); - +#endif // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); @@ -846,7 +854,9 @@ static void ImGui_ImplGlfw_UpdateMouseCursor() { // Show OS mouse cursor // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here. +#if GLFW_HAS_CREATECURSOR glfwSetCursor(window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]); +#endif glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } } diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index 80e2b55ef..ce954ed9f 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -7,7 +7,7 @@ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors) with GLFW 3.1+. Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Multiple Dear ImGui contexts support. // Missing features or Issues: // [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5590ba798..6ae746a88 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -87,6 +87,8 @@ Other Changes: - Backends: - GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) [@jagot] + - GLFW: lower minimum requirement from GLFW 3.1 to GLFW 3.0. Though + a recent version e.g GLFW 3.4 is highly recommended! (#9055) [@Clownacy] - SDL3: fixed Platform_OpenInShellFn() return value (the return value was unused in core but might be used by a direct caller). (#9027) [@achabense] - SDL3: fixed an issue with missing characters events when an already active text From 7954d6782e0d7324eb68caac6c2dfbcc9afc9954 Mon Sep 17 00:00:00 2001 From: aaronkirkham Date: Wed, 5 Nov 2025 23:16:48 +0000 Subject: [PATCH 1465/2359] Drag and Drop, Style: added basic styling options to DragDrop target rect. (#9056) --- imgui.cpp | 14 ++++++++++++-- imgui.h | 6 +++++- imgui_draw.cpp | 3 +++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 89a57174c..955f7b8a9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1450,6 +1450,9 @@ ImGuiStyle::ImGuiStyle() AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + DragDropTargetRectRounding = 0.0f; // Corner radius of the drag-drop hover frame + DragDropTargetRectLineThickness = 2.0f; // Thickness of the drop-drop hover frame lines + DragDropTargetRectExpansionSize = 3.5f; // The size in which the drag-drop hover rect will expand over the target // Behaviors HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. @@ -3711,6 +3714,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_TreeLines: return "TreeLines"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; + case ImGuiCol_DragDropTargetBg: return "DragDropTargetBg"; case ImGuiCol_UnsavedMarker: return "UnsavedMarker"; case ImGuiCol_NavCursor: return "NavCursor"; case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; @@ -14893,7 +14897,7 @@ void ImGui::RenderDragDropTargetRectForItem(const ImRect& bb) ImGuiWindow* window = g.CurrentWindow; ImRect bb_display = bb; bb_display.ClipWith(g.DragDropTargetClipRect); // Clip THEN expand so we have a way to visualize that target is not entirely visible. - bb_display.Expand(3.5f); + bb_display.Expand(g.Style.DragDropTargetRectExpansionSize); bool push_clip_rect = !window->ClipRect.Contains(bb_display); if (push_clip_rect) window->DrawList->PushClipRectFullScreen(); @@ -14904,7 +14908,13 @@ void ImGui::RenderDragDropTargetRectForItem(const ImRect& bb) void ImGui::RenderDragDropTargetRectEx(ImDrawList* draw_list, const ImRect& bb) { - draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); // FIXME-DPI + ImGuiContext& g = *GImGui; + + const ImVec4& color_bg = GetStyleColorVec4(ImGuiCol_DragDropTargetBg); + if (color_bg.w > 0.0f) + draw_list->AddRectFilled(bb.Min, bb.Max, GetColorU32(color_bg), g.Style.DragDropTargetRectRounding, 0); + + draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTarget), g.Style.DragDropTargetRectRounding, 0, g.Style.DragDropTargetRectLineThickness); // FIXME-DPI } const ImGuiPayload* ImGui::GetDragDropPayload() diff --git a/imgui.h b/imgui.h index bcafbf9a8..82d64ec1d 100644 --- a/imgui.h +++ b/imgui.h @@ -1776,7 +1776,8 @@ enum ImGuiCol_ ImGuiCol_TextLink, // Hyperlink color ImGuiCol_TextSelectedBg, // Selected text inside an InputText ImGuiCol_TreeLines, // Tree node hierarchy outlines when using ImGuiTreeNodeFlags_DrawLines - ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target + ImGuiCol_DragDropTarget, // Rectangle border highlighting a drop target + ImGuiCol_DragDropTargetBg, // Rectangle background highlighting a drop target ImGuiCol_UnsavedMarker, // Unsaved Document marker (in window title and tabs) ImGuiCol_NavCursor, // Color of keyboard/gamepad navigation cursor/rectangle, when visible ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB @@ -2322,6 +2323,9 @@ struct ImGuiStyle bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + float DragDropTargetRectRounding; // Corner radius of the drag-drop target rect + float DragDropTargetRectLineThickness; // Thickness of the drop-drop target rect lines + float DragDropTargetRectExpansionSize; // The size in which the drag-drop target rect will expand over the target // Colors ImVec4 Colors[ImGuiCol_COUNT]; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 9e6babf78..54d72f410 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -240,6 +240,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_DragDropTargetBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_UnsavedMarker] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_NavCursor] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); @@ -306,6 +307,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_DragDropTargetBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_UnsavedMarker] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); @@ -373,6 +375,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_DragDropTargetBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_UnsavedMarker] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); From f45adb995cfdfdf66fbf225139b6adf313e723f7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 15:35:13 +0100 Subject: [PATCH 1466/2359] Drag and Drop, Style: added basic styling options to DragDrop target rect. Amends. (#9056) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 19 +++++++++---------- imgui.h | 6 +++--- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ae746a88..b7688f703 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,9 @@ Other Changes: triggered by some widgets e.g. Checkbox(), Selectable() and many others, which cleared ActiveId at the same time as editing. (#9028) Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited). +- Style, Drag and Drop: added ImGuiCol_DragDropTargetBg, style.DragDropTargetRounding, + style.DragDropTargetBorderSize and style.DragDropTargetPadding to configure + the drop target highlight. (#9056) [@aaronkirkham] - Demo: About Box: emit infos to convey when IM_ASSERT() macro is disabled, - so users don't miss out on programming errors being reported. - so it is included in config/build info submitted in new GitHub Issues. diff --git a/imgui.cpp b/imgui.cpp index 955f7b8a9..22ff59d71 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1436,6 +1436,9 @@ ImGuiStyle::ImGuiStyle() TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone; TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line. + DragDropTargetRounding = 0.0f; // Radius of the drag and drop target frame. + DragDropTargetBorderSize = 2.0f; // Thickness of the drag and drop target border. + DragDropTargetPadding = 3.0f; // Size to expand the drag and drop target from actual target item size. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. @@ -1450,9 +1453,6 @@ ImGuiStyle::ImGuiStyle() AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. - DragDropTargetRectRounding = 0.0f; // Corner radius of the drag-drop hover frame - DragDropTargetRectLineThickness = 2.0f; // Thickness of the drop-drop hover frame lines - DragDropTargetRectExpansionSize = 3.5f; // The size in which the drag-drop hover rect will expand over the target // Behaviors HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. @@ -1503,6 +1503,9 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor); + DragDropTargetRounding = ImTrunc(DragDropTargetRounding * scale_factor); + DragDropTargetBorderSize = ImTrunc(DragDropTargetBorderSize * scale_factor); + DragDropTargetPadding = ImTrunc(DragDropTargetPadding * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); @@ -14897,7 +14900,7 @@ void ImGui::RenderDragDropTargetRectForItem(const ImRect& bb) ImGuiWindow* window = g.CurrentWindow; ImRect bb_display = bb; bb_display.ClipWith(g.DragDropTargetClipRect); // Clip THEN expand so we have a way to visualize that target is not entirely visible. - bb_display.Expand(g.Style.DragDropTargetRectExpansionSize); + bb_display.Expand(g.Style.DragDropTargetPadding); bool push_clip_rect = !window->ClipRect.Contains(bb_display); if (push_clip_rect) window->DrawList->PushClipRectFullScreen(); @@ -14909,12 +14912,8 @@ void ImGui::RenderDragDropTargetRectForItem(const ImRect& bb) void ImGui::RenderDragDropTargetRectEx(ImDrawList* draw_list, const ImRect& bb) { ImGuiContext& g = *GImGui; - - const ImVec4& color_bg = GetStyleColorVec4(ImGuiCol_DragDropTargetBg); - if (color_bg.w > 0.0f) - draw_list->AddRectFilled(bb.Min, bb.Max, GetColorU32(color_bg), g.Style.DragDropTargetRectRounding, 0); - - draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTarget), g.Style.DragDropTargetRectRounding, 0, g.Style.DragDropTargetRectLineThickness); // FIXME-DPI + draw_list->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTargetBg), g.Style.DragDropTargetRounding, 0); + draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_DragDropTarget), g.Style.DragDropTargetRounding, 0, g.Style.DragDropTargetBorderSize); } const ImGuiPayload* ImGui::GetDragDropPayload() diff --git a/imgui.h b/imgui.h index 82d64ec1d..0bbe73e8c 100644 --- a/imgui.h +++ b/imgui.h @@ -2309,6 +2309,9 @@ struct ImGuiStyle ImGuiTreeNodeFlags TreeLinesFlags; // Default way to draw lines connecting TreeNode hierarchy. ImGuiTreeNodeFlags_DrawLinesNone or ImGuiTreeNodeFlags_DrawLinesFull or ImGuiTreeNodeFlags_DrawLinesToNodes. float TreeLinesSize; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. float TreeLinesRounding; // Radius of lines connecting child nodes to the vertical line. + float DragDropTargetRounding; // Radius of the drag and drop target frame. + float DragDropTargetBorderSize; // Thickness of the drag and drop target border. + float DragDropTargetPadding; // Size to expand the drag and drop target from actual target item size. ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. @@ -2323,9 +2326,6 @@ struct ImGuiStyle bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. - float DragDropTargetRectRounding; // Corner radius of the drag-drop target rect - float DragDropTargetRectLineThickness; // Thickness of the drop-drop target rect lines - float DragDropTargetRectExpansionSize; // The size in which the drag-drop target rect will expand over the target // Colors ImVec4 Colors[ImGuiCol_COUNT]; From 189d8c9d9c1bcd3a0a42203047d1bf51add52aba Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 16:09:54 +0100 Subject: [PATCH 1467/2359] (Breaking) Commented out legacy ImGuiChildFlags_Border (#462), ImGuiWindowFlags_NavFlattened (#7687), ImGuiWindowFlags_AlwaysUseWindowPadding. --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 12 ++++++++---- imgui.h | 8 ++++---- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b7688f703..b77ac9b44 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,15 @@ HOW TO UPDATE? Breaking Changes: + - BeginChild: commented out legacy names which were obsoleted in 1.90.0 (Nov 2023), + 1.90.9 (July 2024), 1.91.1 (August 2024). (#462, #7687) + - ImGuiChildFlags_Border --> ImGuiChildFlags_Borders + - ImGuiWindowFlags_NavFlattened --> ImGuiChildFlags_NavFlattened (moved to ImGuiChildFlags). + - ImGuiWindowFlags_AlwaysUseWindowPadding --> ImGuiChildFlags_AlwaysUseWindowPadding (moved to ImGuiChildFlags). + So: + - BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0) + - BeginChild(name, size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding) --> BeginChild(name, size, ImGuiChildFlags_AlwaysUseWindowPadding, 0) + Other Changes: - Tables: fixed a bug where nesting BeginTable()->Begin()->BeginTable() would diff --git a/imgui.cpp b/imgui.cpp index 22ff59d71..a515a0adc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -392,6 +392,10 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/11/06 (1.92.5) - BeginChild: commented out some legacy names which were obsoleted in 1.90.0 (Nov 2023), 1.90.9 (July 2024), 1.91.1 (August 2024): + - ImGuiChildFlags_Border --> ImGuiChildFlags_Borders + - ImGuiWindowFlags_NavFlattened --> ImGuiChildFlags_NavFlattened (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0) + - ImGuiWindowFlags_AlwaysUseWindowPadding --> ImGuiChildFlags_AlwaysUseWindowPadding (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding) --> BeginChild(name, size, ImGuiChildFlags_AlwaysUseWindowPadding, 0) - 2025/10/14 (1.92.4) - TreeNode, Selectable, Clipper: commented out legacy names which were obsoleted in 1.89.7 (July 2023) and 1.89.9 (Sept 2023); - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap @@ -6303,10 +6307,10 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!"); } #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding) - child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding; - if (window_flags & ImGuiWindowFlags_NavFlattened) - child_flags |= ImGuiChildFlags_NavFlattened; + //if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding) + // child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding; + //if (window_flags & ImGuiWindowFlags_NavFlattened) + // child_flags |= ImGuiChildFlags_NavFlattened; #endif if (child_flags & ImGuiChildFlags_AutoResizeX) child_flags &= ~ImGuiChildFlags_ResizeX; diff --git a/imgui.h b/imgui.h index 0bbe73e8c..d21249f8a 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.5 WIP" -#define IMGUI_VERSION_NUM 19243 +#define IMGUI_VERSION_NUM 19244 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -1183,8 +1183,8 @@ enum ImGuiWindowFlags_ // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiWindowFlags_NavFlattened = 1 << 29, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call. - ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90.0: Use ImGuiChildFlags_AlwaysUseWindowPadding in BeginChild() call. + //ImGuiWindowFlags_NavFlattened = 1 << 29, // Obsoleted in 1.90.9: moved to ImGuiChildFlags. BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0) + //ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90.0: moved to ImGuiChildFlags. BeginChild(name, size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding) --> BeginChild(name, size, ImGuiChildFlags_AlwaysUseWindowPadding, 0) #endif }; @@ -1212,7 +1212,7 @@ enum ImGuiChildFlags_ // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiChildFlags_Border = ImGuiChildFlags_Borders, // Renamed in 1.91.1 (August 2024) for consistency. + //ImGuiChildFlags_Border = ImGuiChildFlags_Borders, // Renamed in 1.91.1 (August 2024) for consistency. #endif }; From 62162747e7d163f89ab9dd0a29f766b6fde86678 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 16:12:56 +0100 Subject: [PATCH 1468/2359] (Breaking) Keys: commented out legacy names which were obsoleted in 1.89. ImGuiKey_ModCtrl --> ImGuiMod_Ctrl, ImGuiKey_ModShift --> ImGuiMod_Shift, ImGuiKey_ModAlt --> ImGuiMod_Alt, ImGuiKey_ModSuper --> ImGuiMod_Super. --- docs/CHANGELOG.txt | 5 +++++ imgui.cpp | 5 +++++ imgui.h | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b77ac9b44..2c96e6309 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,11 @@ HOW TO UPDATE? Breaking Changes: + - Keys: commented out legacy names which were obsoleted in 1.89.0 (August 2022). + - ImGuiKey_ModCtrl --> ImGuiMod_Ctrl + - ImGuiKey_ModShift --> ImGuiMod_Shift + - ImGuiKey_ModAlt --> ImGuiMod_Alt + - ImGuiKey_ModSuper --> ImGuiMod_Super - BeginChild: commented out legacy names which were obsoleted in 1.90.0 (Nov 2023), 1.90.9 (July 2024), 1.91.1 (August 2024). (#462, #7687) - ImGuiChildFlags_Border --> ImGuiChildFlags_Borders diff --git a/imgui.cpp b/imgui.cpp index a515a0adc..9ef8a16ec 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -396,6 +396,11 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - ImGuiChildFlags_Border --> ImGuiChildFlags_Borders - ImGuiWindowFlags_NavFlattened --> ImGuiChildFlags_NavFlattened (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0) - ImGuiWindowFlags_AlwaysUseWindowPadding --> ImGuiChildFlags_AlwaysUseWindowPadding (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding) --> BeginChild(name, size, ImGuiChildFlags_AlwaysUseWindowPadding, 0) + - 2025/11/06 (1.92.5) - Keys: commented out legacy names which were obsoleted in 1.89.0 (August 2022): + - ImGuiKey_ModCtrl --> ImGuiMod_Ctrl + - ImGuiKey_ModShift --> ImGuiMod_Shift + - ImGuiKey_ModAlt --> ImGuiMod_Alt + - ImGuiKey_ModSuper --> ImGuiMod_Super - 2025/10/14 (1.92.4) - TreeNode, Selectable, Clipper: commented out legacy names which were obsoleted in 1.89.7 (July 2023) and 1.89.9 (Sept 2023); - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap diff --git a/imgui.h b/imgui.h index d21249f8a..f7358c7c8 100644 --- a/imgui.h +++ b/imgui.h @@ -1659,7 +1659,7 @@ enum ImGuiKey : int #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was extremely misleading (since named keys don't start at 0 anymore) ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl - ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 + //ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 //ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 #endif }; From 1c3a60047c20927f6b0f42631216d576974368a8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 16:14:41 +0100 Subject: [PATCH 1469/2359] (Breaking) IO: commented out legacy io.ClearInputCharacters() obsoleted in 1.89.8. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 10 +--------- imgui.h | 5 ++--- 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2c96e6309..f24b03c27 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,8 @@ Breaking Changes: - ImGuiKey_ModShift --> ImGuiMod_Shift - ImGuiKey_ModAlt --> ImGuiMod_Alt - ImGuiKey_ModSuper --> ImGuiMod_Super + - IO: commented out legacy io.ClearInputCharacters() obsoleted in 1.89.8 (Aug 2023). + Using io.ClearInputKeys() is enough. - BeginChild: commented out legacy names which were obsoleted in 1.90.0 (Nov 2023), 1.90.9 (July 2024), 1.91.1 (August 2024). (#462, #7687) - ImGuiChildFlags_Border --> ImGuiChildFlags_Borders diff --git a/imgui.cpp b/imgui.cpp index 9ef8a16ec..8c62d6a82 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -401,6 +401,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - ImGuiKey_ModShift --> ImGuiMod_Shift - ImGuiKey_ModAlt --> ImGuiMod_Alt - ImGuiKey_ModSuper --> ImGuiMod_Super + - 2025/11/06 (1.92.5) - IO: commented out legacy io.ClearInputCharacters() obsoleted in 1.89.8 (Aug 2023). Calling io.ClearInputKeys() is enough. - 2025/10/14 (1.92.4) - TreeNode, Selectable, Clipper: commented out legacy names which were obsoleted in 1.89.7 (July 2023) and 1.89.9 (Sept 2023); - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap @@ -1714,15 +1715,6 @@ void ImGuiIO::ClearInputMouse() MouseWheel = MouseWheelH = 0.0f; } -// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue. -// Current frame character buffer is now also cleared by ClearInputKeys(). -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -void ImGuiIO::ClearInputCharacters() -{ - InputQueueCharacters.resize(0); -} -#endif - static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1) { ImGuiContext& g = *ctx; diff --git a/imgui.h b/imgui.h index f7358c7c8..e336e6d21 100644 --- a/imgui.h +++ b/imgui.h @@ -2511,9 +2511,6 @@ struct ImGuiIO IMGUI_API void ClearEventsQueue(); // Clear all incoming events. IMGUI_API void ClearInputKeys(); // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. IMGUI_API void ClearInputMouse(); // Clear current mouse state. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - IMGUI_API void ClearInputCharacters(); // [Obsoleted in 1.89.8] Clear the current frame text input buffer. Now included within ClearInputKeys(). -#endif //------------------------------------------------------------------ // Output - Updated by NewFrame() or EndFrame()/Render() @@ -2598,6 +2595,8 @@ struct ImGuiIO const char* (*GetClipboardTextFn)(void* user_data); void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; + + //void ClearInputCharacters() { InputQueueCharacters.resize(0); } // [Obsoleted in 1.89.8] Clear the current frame text input buffer. Now included within ClearInputKeys(). Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue. #endif IMGUI_API ImGuiIO(); From e389502ffb155443563af984d9eaea95aa704d6b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 16:19:21 +0100 Subject: [PATCH 1470/2359] Amends comments referring to 1.92.X to refer to 1.92.0. FontAllowUserScaling not marked obsolete anymore. --- imgui.h | 34 +++++++++++++++++----------------- imgui_internal.h | 4 ++-- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/imgui.h b/imgui.h index e336e6d21..edfd7a05f 100644 --- a/imgui.h +++ b/imgui.h @@ -1657,7 +1657,7 @@ enum ImGuiKey : int ImGuiMod_Mask_ = 0xF000, // 4-bits #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was extremely misleading (since named keys don't start at 0 anymore) + ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was misleading (since named keys don't start at 0 anymore) ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl //ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 //ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 @@ -1906,7 +1906,7 @@ enum ImGuiColorEditFlags_ // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiColorEditFlags_AlphaPreview = 0, // [Removed in 1.91.8] This is the default now. Will display a checkerboard unless ImGuiColorEditFlags_AlphaNoBg is set. + ImGuiColorEditFlags_AlphaPreview = 0, // Removed in 1.91.8. This is the default now. Will display a checkerboard unless ImGuiColorEditFlags_AlphaNoBg is set. #endif //ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] }; @@ -2393,7 +2393,7 @@ struct ImGuiIO // Font system ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. - bool FontAllowUserScaling; // = false // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel. + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. // Keyboard/Gamepad Navigation options bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. @@ -3374,8 +3374,8 @@ struct ImDrawList // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x - inline void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x + inline void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.0 + inline void PopTextureID() { PopTexture(); } // RENAMED in 1.92.0 #endif //inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) @@ -3690,7 +3690,7 @@ struct ImFontAtlas // Register and retrieve custom rectangles // - You can request arbitrary rectangles to be packed into the atlas, for your own purpose. - // - Since 1.92.X, packing is done immediately in the function call (previously packing was done during the Build call) + // - Since 1.92.0, packing is done immediately in the function call (previously packing was done during the Build call) // - You can render your pixels into the texture right after calling the AddCustomRect() functions. // - VERY IMPORTANT: // - Texture may be created/resized at any time when calling ImGui or ImFontAtlas functions. @@ -3729,7 +3729,7 @@ struct ImFontAtlas #ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImTextureRef TexRef; // Latest texture identifier == TexData->GetTexRef(). #else - union { ImTextureRef TexRef; ImTextureRef TexID; }; // Latest texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.x + union { ImTextureRef TexRef; ImTextureRef TexID; }; // Latest texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.0. #endif ImTextureData* TexData; // Latest texture. @@ -3759,15 +3759,15 @@ struct ImFontAtlas #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. ImFontAtlasRect TempRect; // For old GetCustomRectByIndex() API - inline ImFontAtlasRectId AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.X - inline const ImFontAtlasRect* GetCustomRectByIndex(ImFontAtlasRectId id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.X - inline void CalcCustomRectUV(const ImFontAtlasRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { *out_uv_min = r->uv0; *out_uv_max = r->uv1; } // OBSOLETED in 1.92.X - IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig - IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X + inline ImFontAtlasRectId AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.0 + inline const ImFontAtlasRect* GetCustomRectByIndex(ImFontAtlasRectId id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.0 + inline void CalcCustomRectUV(const ImFontAtlasRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { *out_uv_min = r->uv0; *out_uv_max = r->uv1; } // OBSOLETED in 1.92.0 + IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.0: Use custom ImFontLoader in ImFontConfig + IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.0 #endif - //unsigned int FontBuilderFlags; // OBSOLETED in 1.92.X: Renamed to FontLoaderFlags. - //int TexDesiredWidth; // OBSOLETED in 1.92.X: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. - //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X + //unsigned int FontBuilderFlags; // OBSOLETED in 1.92.0: Renamed to FontLoaderFlags. + //int TexDesiredWidth; // OBSOLETED in 1.92.0: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.0 //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ }; @@ -3819,7 +3819,7 @@ enum ImFontFlags_ // Font runtime data and rendering // - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. -// - Since 1.92.X a font may be rendered as any size! Therefore a font doesn't have one specific size. +// - Since 1.92.0 a font may be rendered as any size! Therefore a font doesn't have one specific size. // - Use 'font->GetFontBaked(size)' to retrieve the ImFontBaked* corresponding to a given size. // - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetFontBaked(g.FontSize). struct ImFont @@ -4100,7 +4100,7 @@ namespace ImGui //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 } -//-- OBSOLETED in 1.92.x: ImFontAtlasCustomRect becomes ImTextureRect +//-- OBSOLETED in 1.92.0: ImFontAtlasCustomRect becomes ImTextureRect // - ImFontAtlasCustomRect::X,Y --> ImTextureRect::x,y // - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h // - ImFontAtlasCustomRect::GlyphColored --> if you need to write to this, instead you can write to 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph() diff --git a/imgui_internal.h b/imgui_internal.h index 810036b96..b0d226653 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -279,7 +279,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // ImTrunc() is not inlined in MSVC debug builds #define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -#define IM_FLOOR IM_TRUNC +#define IM_FLOOR IM_TRUNC // [OBSOLETE] Renamed in 1.90.0 (Sept 2023) #endif // Hint for branch prediction @@ -2736,7 +2736,7 @@ public: ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } - // [Obsolete] ImGuiWindow::CalcFontSize() was removed in 1.92.x because error-prone/misleading. You can use window->FontRefSize for a copy of g.FontSize at the time of the last Begin() call for this window. + // [OBSOLETE] ImGuiWindow::CalcFontSize() was removed in 1.92.0 because error-prone/misleading. You can use window->FontRefSize for a copy of g.FontSize at the time of the last Begin() call for this window. //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontSizeBase * FontWindowScale * FontWindowScaleParents; }; From 8e2e87d6383b56ae8911e7edefa8b0c20f33037d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 16:27:09 +0100 Subject: [PATCH 1471/2359] (Breaking) Commented out legacy SetItemAllowOverlap() obsoleted in 1.89.7: this never worked right. Use SetNextItemAllowOverlap() _before_ item instead. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 21 +++++++++++---------- imgui.h | 4 ++-- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f24b03c27..bf7ebe8c7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,8 @@ Breaking Changes: So: - BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0) - BeginChild(name, size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding) --> BeginChild(name, size, ImGuiChildFlags_AlwaysUseWindowPadding, 0) + - Commented out legacy SetItemAllowOverlap() obsoleted in 1.89.7: this never worked right. + Use SetNextItemAllowOverlap() _before_ item instead. Other Changes: diff --git a/imgui.cpp b/imgui.cpp index 8c62d6a82..bbf450f16 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -402,6 +402,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - ImGuiKey_ModAlt --> ImGuiMod_Alt - ImGuiKey_ModSuper --> ImGuiMod_Super - 2025/11/06 (1.92.5) - IO: commented out legacy io.ClearInputCharacters() obsoleted in 1.89.8 (Aug 2023). Calling io.ClearInputKeys() is enough. + - 2025/11/06 (1.92.5) - Commented out legacy SetItemAllowOverlap() obsoleted in 1.89.7: this never worked right. Use SetNextItemAllowOverlap() _before_ item instead. - 2025/10/14 (1.92.4) - TreeNode, Selectable, Clipper: commented out legacy names which were obsoleted in 1.89.7 (July 2023) and 1.89.9 (Sept 2023); - ImGuiTreeNodeFlags_AllowItemOverlap --> ImGuiTreeNodeFlags_AllowOverlap - ImGuiSelectableFlags_AllowItemOverlap --> ImGuiSelectableFlags_AllowOverlap @@ -6227,16 +6228,16 @@ void ImGui::SetNextItemAllowOverlap() #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. -// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead. -void ImGui::SetItemAllowOverlap() -{ - ImGuiContext& g = *GImGui; - ImGuiID id = g.LastItemData.ID; - if (g.HoveredId == id) - g.HoveredIdAllowOverlap = true; - if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id. - g.ActiveIdAllowOverlap = true; -} +// Use SetNextItemAllowOverlap() *before* your item instead of calling this! +//void ImGui::SetItemAllowOverlap() +//{ +// ImGuiContext& g = *GImGui; +// ImGuiID id = g.LastItemData.ID; +// if (g.HoveredId == id) +// g.HoveredIdAllowOverlap = true; +// if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id. +// g.ActiveIdAllowOverlap = true; +//} #endif // This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations. diff --git a/imgui.h b/imgui.h index edfd7a05f..4381040f1 100644 --- a/imgui.h +++ b/imgui.h @@ -4031,10 +4031,10 @@ namespace ImGui inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } 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); 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); - // OBSOLETED in 1.89.7 (from June 2023) - IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() before item. // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + // OBSOLETED in 1.89.7 (from June 2023) + //IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() _before_ item. //-- OBSOLETED in 1.89.4 (from March 2023) //static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } //static inline void PopAllowKeyboardFocus() { PopItemFlag(); } From dacd0806399081b4909fc0a52d5aa1bcbf3847a4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 17:30:00 +0100 Subject: [PATCH 1472/2359] Docs: added link to imgui-module. (#8868( --- misc/cpp/README.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/misc/cpp/README.txt b/misc/cpp/README.txt index 5d6aeff13..f865c1b3e 100644 --- a/misc/cpp/README.txt +++ b/misc/cpp/README.txt @@ -9,5 +9,9 @@ imgui_scoped.h Try by merging: https://github.com/ocornut/imgui/pull/2197 Discuss at: https://github.com/ocornut/imgui/issues/2096 +imgui-module: + C++20 module binding + https://github.com/stripe2933/imgui-module + See more C++ related extension (fmt, RAII, syntactic sugar) on Wiki: https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness From b0d3c3a6741b9a105cb74508a67e47431f8c90cf Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 17:59:01 +0100 Subject: [PATCH 1473/2359] Drag and Drop: prev/curr storage for DragDropAcceptFlags. ImGuiDragDropFlags_AcceptNoPreviewTooltip test uses DragDropAcceptFlagsPrev for consistency. (#143) I don't think this would have materialized as a visible bug. --- imgui.cpp | 10 ++++++---- imgui_internal.h | 3 ++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bbf450f16..b71c539cc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4190,7 +4190,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) DragDropMouseButton = -1; DragDropTargetId = 0; DragDropTargetFullViewport = 0; - DragDropAcceptFlags = ImGuiDragDropFlags_None; + DragDropAcceptFlagsCurr = DragDropAcceptFlagsPrev = ImGuiDragDropFlags_None; DragDropAcceptIdCurrRectSurface = 0.0f; DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0; DragDropAcceptFrameCount = -1; @@ -5528,6 +5528,8 @@ void ImGui::NewFrame() // Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; g.DragDropAcceptIdCurr = 0; + g.DragDropAcceptFlagsPrev = g.DragDropAcceptFlagsCurr; + g.DragDropAcceptFlagsCurr = ImGuiDragDropFlags_None; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; g.DragDropWithinSource = false; g.DragDropWithinTarget = false; @@ -14552,7 +14554,7 @@ void ImGui::ClearDragDrop() IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n"); g.DragDropActive = false; g.DragDropPayload.Clear(); - g.DragDropAcceptFlags = ImGuiDragDropFlags_None; + g.DragDropAcceptFlagsCurr = ImGuiDragDropFlags_None; g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; g.DragDropAcceptFrameCount = -1; @@ -14681,7 +14683,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. bool ret; - if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip)) + if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlagsPrev & ImGuiDragDropFlags_AcceptNoPreviewTooltip)) ret = BeginTooltipHidden(); else ret = BeginTooltip(); @@ -14862,7 +14864,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop if (r_surface > g.DragDropAcceptIdCurrRectSurface) return NULL; - g.DragDropAcceptFlags = flags; + g.DragDropAcceptFlagsCurr = flags; g.DragDropAcceptIdCurr = g.DragDropTargetId; g.DragDropAcceptIdCurrRectSurface = r_surface; //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId); diff --git a/imgui_internal.h b/imgui_internal.h index b0d226653..438b75f0f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2380,7 +2380,8 @@ struct ImGuiContext ImRect DragDropTargetClipRect; // Store ClipRect at the time of item's drawing ImGuiID DragDropTargetId; ImGuiID DragDropTargetFullViewport; - ImGuiDragDropFlags DragDropAcceptFlags; + ImGuiDragDropFlags DragDropAcceptFlagsCurr; + ImGuiDragDropFlags DragDropAcceptFlagsPrev; float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface) ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload) ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) From bd0e2036e01ad5299a6bddea0266c1ae57f84f9e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 18:07:02 +0100 Subject: [PATCH 1474/2359] Drag and Drop: added ImGuiDragDropFlags_AcceptDrawAsHovered. (#8632) Not calling SetHoveredId() in that path, does not seem necessary. --- docs/CHANGELOG.txt | 9 ++++++--- imgui.h | 1 + imgui_widgets.cpp | 8 ++++++-- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bf7ebe8c7..3bab14762 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -94,9 +94,12 @@ Other Changes: triggered by some widgets e.g. Checkbox(), Selectable() and many others, which cleared ActiveId at the same time as editing. (#9028) Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited). -- Style, Drag and Drop: added ImGuiCol_DragDropTargetBg, style.DragDropTargetRounding, - style.DragDropTargetBorderSize and style.DragDropTargetPadding to configure - the drop target highlight. (#9056) [@aaronkirkham] +- Drag and Drop: + - Added ImGuiDragDropFlags_AcceptDrawAsHovered to make accepting item render + as hovered, which can allow using e.g. Button() as drop target. (#8632) + - Style: added ImGuiCol_DragDropTargetBg, style.DragDropTargetRounding, + style.DragDropTargetBorderSize and style.DragDropTargetPadding to configure + the drop target highlight. (#9056) [@aaronkirkham] - Demo: About Box: emit infos to convey when IM_ASSERT() macro is disabled, - so users don't miss out on programming errors being reported. - so it is included in config/build info submitted in new GitHub Issues. diff --git a/imgui.h b/imgui.h index 4381040f1..81774857f 100644 --- a/imgui.h +++ b/imgui.h @@ -1484,6 +1484,7 @@ enum ImGuiDragDropFlags_ ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + ImGuiDragDropFlags_AcceptDrawAsHovered = 1 << 13, // Accepting item will render as if hovered. Useful for e.g. a Button() used as a drop target. ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6d17213a2..8c322e8dd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -574,8 +574,9 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool // Special mode for Drag and Drop used by openables (tree nodes, tabs etc.) // where holding the button pressed for a long time while drag a payload item triggers the button. - if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers)) - if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + if (g.DragDropActive) + { + if ((flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { hovered = true; SetHoveredID(id); @@ -586,6 +587,9 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool FocusWindow(window); } } + if (g.DragDropAcceptIdPrev == id && (g.DragDropAcceptFlagsPrev & ImGuiDragDropFlags_AcceptDrawAsHovered)) + hovered = true; + } if (flatten_hovered_children) g.HoveredWindow = backup_hovered_window; From 635eb1d8e92d0fff4042fd63efcf56ba9deda812 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Nov 2025 18:01:42 +0100 Subject: [PATCH 1475/2359] Added .tmp files. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 89b77d910..1aedcf779 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ imgui*.ini examples/*/Debug/* examples/*/Release/* examples/*/x64/* +examples/*.tmp ## Visual Studio artifacts .vs From 86daa8930e3b8ca9e75fac7307a1181e740c064a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Nov 2025 13:24:10 +0100 Subject: [PATCH 1476/2359] Backends, Examples: WebGPU: simplified ifndef (#8381) --- backends/imgui_impl_wgpu.cpp | 4 ++-- backends/imgui_impl_wgpu.h | 4 ++-- examples/example_glfw_wgpu/main.cpp | 4 ++-- examples/example_sdl2_wgpu/main.cpp | 4 ++-- examples/example_sdl3_wgpu/main.cpp | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 86c30cfd4..47c31726b 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -1015,7 +1015,7 @@ void ImGui_ImplWGPU_DebugPrintAdapterInfo(const WGPUAdapter& adapter) wgpuAdapterInfoFreeMembers(info); } -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(__EMSCRIPTEN__) +#ifndef __EMSCRIPTEN__ #if defined(__APPLE__) // MacOS specific: is necessary to compile with "-x objective-c++" flags @@ -1079,7 +1079,7 @@ WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceI #endif return surface; } -#endif +#endif // #ifndef __EMSCRIPTEN__ //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 3d0cf5cc1..f17fe6c25 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -105,7 +105,7 @@ const char* ImGui_ImplWGPU_GetLogLevelName(WGPULogLevel level); #endif // (Optional) Helper to create a surface on macOS/Wayland/X11/Window -#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(__EMSCRIPTEN__) +#ifndef __EMSCRIPTEN__ struct ImGui_ImplWGPU_CreateSurfaceInfo { WGPUInstance Instance; @@ -116,6 +116,6 @@ struct ImGui_ImplWGPU_CreateSurfaceInfo void* RawInstance; // 0 | 0 | 0 | HINSTANCE }; WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceInfo* info); -#endif +#endif // #ifndef __EMSCRIPTEN__ #endif // #ifndef IMGUI_DISABLE diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 2fd746903..ad64ef403 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -506,7 +506,7 @@ static bool InitWGPU(GLFWwindow* window) // As of today (2025/10) there is no "official" support in GLFW to create a surface for WebGPU backend // This stub uses "low level" GLFW calls to acquire information from a specific Window Manager. // Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. -#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) +#ifndef __EMSCRIPTEN__ #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) #define GLFW_HAS_X11_OR_WAYLAND 1 @@ -573,4 +573,4 @@ WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, GLFWwindow* window) #endif return nullptr; } -#endif +#endif // #ifndef __EMSCRIPTEN__ diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index bddc91b39..d4b9a021b 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -491,7 +491,7 @@ static bool InitWGPU(SDL_Window* window) // As of today (2025/10/31) there is no "official" support in SDL2 to create a surface for WebGPU backend. // This stub uses "low level" SDL2 calls to acquire information from a specific Window Manager. // Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. -#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) +#ifndef __EMSCRIPTEN__ #include #undef Status // X11 headers are leaking this and also 'Success', 'Always', 'None', all used in DAWN api. Add #undef if necessary. @@ -538,4 +538,4 @@ WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) #endif return nullptr; } -#endif +#endif // #ifndef __EMSCRIPTEN__ diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index abfbf6cfa..d56b703c0 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -502,7 +502,7 @@ static bool InitWGPU(SDL_Window* window) // As of today (2025/10) there is no "official" support in SDL3 to create a surface for WebGPU backend // This stub uses "low level" SDL3 calls to acquire information from a specific Window Manager. // Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN. -#if !defined(__EMSCRIPTEN__) && (defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)) +#ifndef __EMSCRIPTEN__ #if defined(SDL_PLATFORM_WIN32) #ifndef WIN32_LEAN_AND_MEAN @@ -550,4 +550,4 @@ static WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* w #endif return nullptr; } -#endif +#endif // #ifndef __EMSCRIPTEN__ From 7537ba2b4424b6bde2d77e3b423737230c02a4ad Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 10 Nov 2025 19:36:16 +0100 Subject: [PATCH 1477/2359] Windows: fixed single-axis auto-sizing (via double-clicking a border) to take account of remaining scrollbar on the other axis. (#9060) Potentially now should apply same logic to the other resizing path also described in #9060 --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 21 ++++++++++++--------- imgui.h | 2 +- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3bab14762..dbc2c51be 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,8 @@ Other Changes: - Windows: io.ConfigWindowsMoveFromTitleBarOnly is latched during Begin(), effectively allowing to change the value on a per-window basis (although there is a better internal mechanism for it). +- Windows: fixed single-axis auto-sizing (via double-clicking a border) to + take account of remaining scrollbar on the other axis. (#9060) - Disabled: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) - InputText: when buffer is not resizable, trying to paste contents that diff --git a/imgui.cpp b/imgui.cpp index b71c539cc..c1415483c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1338,7 +1338,7 @@ static void UpdateFontsEndFrame(); static void UpdateTexturesNewFrame(); static void UpdateTexturesEndFrame(); static void UpdateSettings(); -static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); +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); @@ -6625,14 +6625,16 @@ static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_cur content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y); } -static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents) +static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents, int axis_mask) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x; const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y; ImVec2 size_pad = window->WindowPadding * 2.0f; - ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars); + ImVec2 size_desired; + size_desired[ImGuiAxis_X] = (axis_mask & 1) ? size_contents.x + size_pad.x + decoration_w_without_scrollbars : window->Size.x; + size_desired[ImGuiAxis_Y] = (axis_mask & 2) ? size_contents.y + size_pad.y + decoration_h_without_scrollbars : window->Size.y; // Determine maximum window size // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction @@ -6674,7 +6676,7 @@ ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window) ImVec2 size_contents_current; ImVec2 size_contents_ideal; CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal); - ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal); + ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal, ~0); ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit); return size_final; } @@ -6780,7 +6782,7 @@ ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir) // Handle resize for: Resize Grips, Borders, Gamepad // Return true when using auto-fit (double-click on resize grip) -static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect) +static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; @@ -6830,6 +6832,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si if (held && g.IO.MouseDoubleClicked[0]) { // Auto-fit when double-clicking + ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, ~0); size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit); ret_auto_fit_mask = 0x03; // Both axes ClearActiveID(); @@ -6876,10 +6879,10 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si if (held && g.IO.MouseDoubleClicked[0]) { // Double-clicking bottom or right border auto-fit on this axis - // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars. // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases. if (border_n == 1 || border_n == 3) // Right and bottom border { + ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, 1 << axis); size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis]; ret_auto_fit_mask |= (1 << axis); hovered = held = false; // So border doesn't show highlighted at new position @@ -7575,7 +7578,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->ScrollbarSizes = ImVec2(0.0f, 0.0f); // Calculate auto-fit size, handle automatic resize - const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal); + const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, ~0); if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) { // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. @@ -7708,7 +7711,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); if (handle_borders_and_resize_grips && !window->Collapsed) - if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) + if (int auto_fit_mask = UpdateWindowManualResize(window, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) { if (auto_fit_mask & (1 << ImGuiAxis_X)) use_current_size_for_scrollbar_x = true; @@ -7958,7 +7961,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) g.TooltipPreviousWindow = window; // Set default BgClickFlags - // This is set at the end of this function, so UpdateManualResize()/ClampWindowPos() may use last-frame value if overriden by user code. + // This is set at the end of this function, so UpdateWindowManualResize()/ClampWindowPos() may use last-frame value if overriden by user code. // FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button. window->BgClickFlags = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->BgClickFlags : (g.IO.ConfigWindowsMoveFromTitleBarOnly ? ImGuiWindowBgClickFlags_None : ImGuiWindowBgClickFlags_Move); diff --git a/imgui.h b/imgui.h index 81774857f..9990253de 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.5 WIP" -#define IMGUI_VERSION_NUM 19244 +#define IMGUI_VERSION_NUM 19245 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From fc262355ca214bc1d03573807aabb9477306aa2f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Nov 2025 19:40:24 +0100 Subject: [PATCH 1478/2359] Windows: Fixed an issue where repeated calls to SetNextWindowSize() using 0.0f to auto-size would keep marking ini settings as dirty. + marking dirty on old io.FontAllowUserScaling Ctrl+Wheel --- docs/CHANGELOG.txt | 13 ++++++++----- imgui.cpp | 14 ++++++++------ 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dbc2c51be..7a3ff9019 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,11 +68,14 @@ Other Changes: - Tables: Angled headers: fixed an auto-resize feedback loop that could affect tables with empty non-resizing columns using angled headers, making them typically flicker back and forth between +0 and +1 pixels. -- Windows: io.ConfigWindowsMoveFromTitleBarOnly is latched during Begin(), - effectively allowing to change the value on a per-window basis (although - there is a better internal mechanism for it). -- Windows: fixed single-axis auto-sizing (via double-clicking a border) to - take account of remaining scrollbar on the other axis. (#9060) +- Windows: + - Config flag io.ConfigWindowsMoveFromTitleBarOnly is now latched during + Begin(), effectively allowing to change the value on a per-window basis. + (although there is a better internal mechanism for it). + - Fixed single-axis auto-sizing (via double-clicking a border) to + take account of remaining scrollbar on the other axis. (#9060) + - Fixed an issue where repeated calls to SetNextWindowSize() using 0.0f + to auto-size on a given axis would keep marking ini settings as dirty. - Disabled: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) - InputText: when buffer is not resizable, trying to paste contents that diff --git a/imgui.cpp b/imgui.cpp index c1415483c..80aa77d10 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6968,8 +6968,8 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, int* border_hove } // Apply back modified position/size to window - const ImVec2 curr_pos = window->Pos; - const ImVec2 curr_size = window->SizeFull; + const ImVec2 old_pos = window->Pos; + const ImVec2 old_size = window->SizeFull; if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x)) window->Size.x = window->SizeFull.x = size_target.x; if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y)) @@ -6978,7 +6978,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, int* border_hove window->Pos.x = ImTrunc(pos_target.x); if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y)) window->Pos.y = ImTrunc(pos_target.y); - if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y) + if (old_pos.x != window->Pos.x || old_pos.y != window->Pos.y || old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y) MarkIniSettingsDirty(window); // Recalculate next expected border expected coordinates @@ -7579,6 +7579,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Calculate auto-fit size, handle automatic resize const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, ~0); + const ImVec2 old_size = window->SizeFull; if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) { // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. @@ -7607,9 +7608,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; use_current_size_for_scrollbar_y = true; } - if (!window->Collapsed) - MarkIniSettingsDirty(window); } + if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y) + MarkIniSettingsDirty(window); // Apply minimum/maximum window size constraints and final size window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull); @@ -10220,8 +10221,9 @@ void ImGui::UpdateMouseWheel() { const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; SetWindowPos(window, window->Pos + offset, 0); - window->Size = ImTrunc(window->Size * scale); + window->Size = ImTrunc(window->Size * scale); // FIXME: Legacy-ish code, call SetWindowSize()? window->SizeFull = ImTrunc(window->SizeFull * scale); + MarkIniSettingsDirty(window); } return; } From 52e9d94f93a1f05155a03b0bbeaa221ecbd9e7f1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Nov 2025 20:01:07 +0100 Subject: [PATCH 1479/2359] Windows: reorganize auto-fitting code blocks in Begin(), aimed to have no side-effect, but.. ..outer ImGuiWindowFlags_AlwaysAutoResize previously took priority for both axis. New logic per-axis. Toward #9060 --- imgui.cpp | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 80aa77d10..99e2f496f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7578,32 +7578,32 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->ScrollbarSizes = ImVec2(0.0f, 0.0f); // Calculate auto-fit size, handle automatic resize + // - Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. + // - We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. + // - Auto-fit may only grow window during the first few frames. const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, ~0); const ImVec2 old_size = window->SizeFull; - if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) + if (!window_size_x_set_by_api) { - // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. - if (!window_size_x_set_by_api) + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) { window->SizeFull.x = size_auto_fit.x; use_current_size_for_scrollbar_x = true; } - if (!window_size_y_set_by_api) - { - window->SizeFull.y = size_auto_fit.y; - use_current_size_for_scrollbar_y = true; - } - } - else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) - { - // Auto-fit may only grow window during the first few frames - // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. - if (!window_size_x_set_by_api && window->AutoFitFramesX > 0) + else if (window->AutoFitFramesX > 0) { window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; use_current_size_for_scrollbar_x = true; } - if (!window_size_y_set_by_api && window->AutoFitFramesY > 0) + } + if (!window_size_y_set_by_api) + { + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) + { + window->SizeFull.y = size_auto_fit.y; + use_current_size_for_scrollbar_y = true; + } + else if (window->AutoFitFramesY > 0) { window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; use_current_size_for_scrollbar_y = true; From b51f6e073c9b31b9672f75d194768247b9344137 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Nov 2025 21:15:43 +0100 Subject: [PATCH 1480/2359] Windows: reorganize auto-fitting code blocks in Begin(), step 2. Toward #9060 --- imgui.cpp | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 99e2f496f..2c5c73885 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7581,33 +7581,28 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // - Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. // - We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. // - Auto-fit may only grow window during the first few frames. + const bool size_auto_fit_x_always = !window_size_x_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; + const bool size_auto_fit_y_always = !window_size_y_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; + const bool size_auto_fit_x_current = !window_size_x_set_by_api && (window->AutoFitFramesX > 0); + const bool size_auto_fit_y_current = !window_size_y_set_by_api && (window->AutoFitFramesY > 0); const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, ~0); + const ImVec2 old_size = window->SizeFull; - if (!window_size_x_set_by_api) + if (size_auto_fit_x_always || size_auto_fit_x_current) { - if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) - { + if (size_auto_fit_x_always) window->SizeFull.x = size_auto_fit.x; - use_current_size_for_scrollbar_x = true; - } - else if (window->AutoFitFramesX > 0) - { + else window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; - use_current_size_for_scrollbar_x = true; - } + use_current_size_for_scrollbar_x = true; } - if (!window_size_y_set_by_api) + if (size_auto_fit_y_always || size_auto_fit_y_current) { - if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) - { + if (size_auto_fit_y_always) window->SizeFull.y = size_auto_fit.y; - use_current_size_for_scrollbar_y = true; - } - else if (window->AutoFitFramesY > 0) - { + else window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; - use_current_size_for_scrollbar_y = true; - } + use_current_size_for_scrollbar_y = true; } if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y) MarkIniSettingsDirty(window); From a2544f94962ef83c1ea5873cc106d100958715bc Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Nov 2025 21:37:21 +0100 Subject: [PATCH 1481/2359] Windows: programmatic auto-sizing on a single axis also apply proper logic. (#9060) --- docs/CHANGELOG.txt | 5 +++-- imgui.cpp | 7 ++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7a3ff9019..e14d32a1a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -72,8 +72,9 @@ Other Changes: - Config flag io.ConfigWindowsMoveFromTitleBarOnly is now latched during Begin(), effectively allowing to change the value on a per-window basis. (although there is a better internal mechanism for it). - - Fixed single-axis auto-sizing (via double-clicking a border) to - take account of remaining scrollbar on the other axis. (#9060) + - Fixed single-axis auto-sizing (via double-clicking a border or passing + 0.0f on one axis of SetNextWindowSize() call) to take account of remaining + scrollbar on the other axis. (#9060) - Fixed an issue where repeated calls to SetNextWindowSize() using 0.0f to auto-size on a given axis would keep marking ini settings as dirty. - Disabled: fixed a bug when a previously enabled item that got nav focus diff --git a/imgui.cpp b/imgui.cpp index 2c5c73885..949f140ba 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7585,7 +7585,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const bool size_auto_fit_y_always = !window_size_y_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; const bool size_auto_fit_x_current = !window_size_x_set_by_api && (window->AutoFitFramesX > 0); const bool size_auto_fit_y_current = !window_size_y_set_by_api && (window->AutoFitFramesY > 0); - const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, ~0); + int size_auto_fit_mask = 0; + if (size_auto_fit_x_always || size_auto_fit_x_current) + size_auto_fit_mask |= (1 << ImGuiAxis_X); + if (size_auto_fit_y_always || size_auto_fit_y_current) + size_auto_fit_mask |= (1 << ImGuiAxis_Y); + const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, size_auto_fit_mask); const ImVec2 old_size = window->SizeFull; if (size_auto_fit_x_always || size_auto_fit_x_current) From 501e0adcdbb6cb0bf0f2ea7a963b8114d3ac408e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Nov 2025 21:47:15 +0100 Subject: [PATCH 1482/2359] Windows: CalcWindowAutoFitSize() remove child-specific hack added by 29439bdd27 and made obsolete by 7537ba2b4. (#9060, #1710) --- imgui.cpp | 8 -------- 1 file changed, 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 949f140ba..e195c3bc1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6650,14 +6650,6 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont ImVec2 size_min = CalcWindowMinSize(window); ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max); - // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars, - // we may need to compute/store three variants of size_auto_fit, for x/y/xy. - // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well: - if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & (ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeY))) - size_auto_fit.y = window->SizeFull.y; - else if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && !(window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeX))) - size_auto_fit.x = window->SizeFull.x; - // When the window cannot fit all contents (either because of constraints, either because screen is too small), // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit); From de917ebb95830b0a31a0332a95d2babff82b109b Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 11 Nov 2025 21:48:17 +0100 Subject: [PATCH 1483/2359] Windows: move auto-fit block into braces for clarify. (no-op) --- imgui.cpp | 58 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e195c3bc1..a43dd0097 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7573,36 +7573,38 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // - Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. // - We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. // - Auto-fit may only grow window during the first few frames. - const bool size_auto_fit_x_always = !window_size_x_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; - const bool size_auto_fit_y_always = !window_size_y_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; - const bool size_auto_fit_x_current = !window_size_x_set_by_api && (window->AutoFitFramesX > 0); - const bool size_auto_fit_y_current = !window_size_y_set_by_api && (window->AutoFitFramesY > 0); - int size_auto_fit_mask = 0; - if (size_auto_fit_x_always || size_auto_fit_x_current) - size_auto_fit_mask |= (1 << ImGuiAxis_X); - if (size_auto_fit_y_always || size_auto_fit_y_current) - size_auto_fit_mask |= (1 << ImGuiAxis_Y); - const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, size_auto_fit_mask); + { + const bool size_auto_fit_x_always = !window_size_x_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; + const bool size_auto_fit_y_always = !window_size_y_set_by_api && (flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed; + const bool size_auto_fit_x_current = !window_size_x_set_by_api && (window->AutoFitFramesX > 0); + const bool size_auto_fit_y_current = !window_size_y_set_by_api && (window->AutoFitFramesY > 0); + int size_auto_fit_mask = 0; + if (size_auto_fit_x_always || size_auto_fit_x_current) + size_auto_fit_mask |= (1 << ImGuiAxis_X); + if (size_auto_fit_y_always || size_auto_fit_y_current) + size_auto_fit_mask |= (1 << ImGuiAxis_Y); + const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal, size_auto_fit_mask); - const ImVec2 old_size = window->SizeFull; - if (size_auto_fit_x_always || size_auto_fit_x_current) - { - if (size_auto_fit_x_always) - window->SizeFull.x = size_auto_fit.x; - else - window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; - use_current_size_for_scrollbar_x = true; + const ImVec2 old_size = window->SizeFull; + if (size_auto_fit_x_always || size_auto_fit_x_current) + { + if (size_auto_fit_x_always) + window->SizeFull.x = size_auto_fit.x; + else + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + use_current_size_for_scrollbar_x = true; + } + if (size_auto_fit_y_always || size_auto_fit_y_current) + { + if (size_auto_fit_y_always) + window->SizeFull.y = size_auto_fit.y; + else + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + use_current_size_for_scrollbar_y = true; + } + if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y) + MarkIniSettingsDirty(window); } - if (size_auto_fit_y_always || size_auto_fit_y_current) - { - if (size_auto_fit_y_always) - window->SizeFull.y = size_auto_fit.y; - else - window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; - use_current_size_for_scrollbar_y = true; - } - if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y) - MarkIniSettingsDirty(window); // Apply minimum/maximum window size constraints and final size window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull); From 613cfaf0b4021cfe0a39f65514dffe493d2b30d2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 13:44:21 +0100 Subject: [PATCH 1484/2359] Tooltips: made BeginTooltipEx() not hide nested tooltips. It's not typically possible to nest tooltips since BeginTooltipEx() imply ImGuiWindowFlags_NoInputs + following mouse pos + most tooltips would be triggered on hover. But BeginErrorTooltip() bypass that. --- imgui.cpp | 24 +++++++++++++++++------- imgui_internal.h | 1 + 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a43dd0097..e8b65a0b2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8261,6 +8261,15 @@ bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, return false; } +bool ImGui::IsWindowInBeginStack(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + for (int n = g.CurrentWindowStack.Size - 1; n >= 0; n--) + if (g.CurrentWindowStack[n].Window == window) + return true; + return false; +} + bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent) { if (window->RootWindow == potential_parent) @@ -11916,16 +11925,17 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext tooltip_flags |= ImGuiTooltipFlags_OverridePrevious; } + // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. + if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active && !IsWindowInBeginStack(g.TooltipPreviousWindow)) + { + //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name); + SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow); + g.TooltipOverrideCount++; + } + const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d"; char window_name[32]; ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, g.TooltipOverrideCount); - if ((tooltip_flags & ImGuiTooltipFlags_OverridePrevious) && g.TooltipPreviousWindow != NULL && g.TooltipPreviousWindow->Active) - { - // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. - //IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name); - SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow); - ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, ++g.TooltipOverrideCount); - } ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; Begin(window_name, NULL, flags | extra_window_flags); // 2023-03-09: Added bool return value to the API, but currently always returning true. diff --git a/imgui_internal.h b/imgui_internal.h index 438b75f0f..f065df6e4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3136,6 +3136,7 @@ namespace ImGui IMGUI_API void UpdateWindowSkipRefresh(ImGuiWindow* window); IMGUI_API ImVec2 CalcWindowNextAutoFitSize(ImGuiWindow* window); IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy); + IMGUI_API bool IsWindowInBeginStack(ImGuiWindow* window); IMGUI_API bool IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent); IMGUI_API bool IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below); IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); From 68a44776bdeb387c635b3cb23a4e252ee476f5af Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 13:44:47 +0100 Subject: [PATCH 1485/2359] Misc: tweak conflicting id error tooltip to use a link. Now that nested tooltips are not hiding each others. --- imgui.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e8b65a0b2..2664d3050 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11033,8 +11033,7 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() Text("(Hold CTRL to "); } SameLine(0.0f, 0.0f); - if (SmallButton("Open FAQ->About ID Stack System") && g.PlatformIO.Platform_OpenInShellFn != NULL) - g.PlatformIO.Platform_OpenInShellFn(&g, "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage"); + TextLinkOpenURL("Read FAQ \"About ID Stack System\"", "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage"); SameLine(0.0f, 0.0f); Text(")"); EndErrorTooltip(); From e3979c20986d06fb4039014c2c2b1e4490a27a95 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 14:22:34 +0100 Subject: [PATCH 1486/2359] Demo: removing absolute __FILE_ from being emitted by default. (#9033) --- imgui_demo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b96d8ea60..380e58f90 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -288,7 +288,7 @@ extern ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback; extern void* GImGuiDemoMarkerCallbackUserData; ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback = NULL; void* GImGuiDemoMarkerCallbackUserData = NULL; -#define IMGUI_DEMO_MARKER(section) do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback(__FILE__, __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0) +#define IMGUI_DEMO_MARKER(section) do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback("imgui_demo.cpp", __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0) //----------------------------------------------------------------------------- // [SECTION] Demo Window / ShowDemoWindow() From 873fe34b3184d8b5e6daeeab178a510e22d35bef Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 15:05:16 +0100 Subject: [PATCH 1487/2359] Debug Tools: ID Stack Tool: preserve first data type, so user of PushOverrideID() e.g. TreeNode() elements don't get demoted from _String to _ID. --- imgui.cpp | 3 ++- imgui_internal.h | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2664d3050..eed1686a3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17892,7 +17892,8 @@ void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* dat tool->ResultPathsBuf.append(result, result_end + 1); // Include zero terminator } info->QuerySuccess = true; - info->DataType = (ImS8)data_type; + if (info->DataType == -1) + info->DataType = (ImS8)data_type; } static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size) diff --git a/imgui_internal.h b/imgui_internal.h index f065df6e4..48cd46d9d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2125,7 +2125,7 @@ struct ImGuiStackLevelInfo ImS8 DataType; // ImGuiDataType int DescOffset; // -1 or offset into parent's ResultPathsBuf - ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); DescOffset = -1; } + ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); DataType = -1; DescOffset = -1; } }; // State for ID Stack tool queries From e60e5bff63014a44ab56e48abd4981d48552fa96 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 15:24:03 +0100 Subject: [PATCH 1488/2359] Misc: standardized casing of keyboard mods in comments and demo ("CTRL" -> "Ctrl"). --- docs/CHANGELOG.txt | 2 + imgui.cpp | 90 +++++++++++++++++++-------------------- imgui.h | 52 +++++++++++------------ imgui_demo.cpp | 104 ++++++++++++++++++++++----------------------- imgui_internal.h | 16 +++---- imgui_tables.cpp | 6 +-- imgui_widgets.cpp | 36 ++++++++-------- 7 files changed, 154 insertions(+), 152 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e14d32a1a..afc5290dc 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -100,6 +100,8 @@ Other Changes: triggered by some widgets e.g. Checkbox(), Selectable() and many others, which cleared ActiveId at the same time as editing. (#9028) Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited). +- Misc: standardized casing of keyboard mods in comments and demo, showing + as e.g. "Ctrl" instead of "CTRL". - Drag and Drop: - Added ImGuiDragDropFlags_AcceptDrawAsHovered to make accepting item render as hovered, which can allow using e.g. Button() as drop target. (#8632) diff --git a/imgui.cpp b/imgui.cpp index eed1686a3..61c5f7445 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -131,7 +131,7 @@ CODE - MOUSE CONTROLS - Mouse wheel: Scroll vertically. - - SHIFT+Mouse wheel: Scroll horizontally. + - Shift+Mouse wheel: Scroll horizontally. - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin(). - Click ^, Double-Click title: Collapse window. - Drag on corner/border: Resize window (double-click to auto fit window to its contents). @@ -139,23 +139,23 @@ CODE - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack). - TEXT EDITOR - - Hold SHIFT or Drag Mouse: Select text. - - CTRL+Left/Right: Word jump. - - CTRL+Shift+Left/Right: Select words. - - CTRL+A or Double-Click: Select All. - - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard. - - CTRL+Z Undo. - - CTRL+Y or CTRL+Shift+Z: Redo. + - Hold Shift or Drag Mouse: Select text. + - Ctrl+Left/Right: Word jump. + - Ctrl+Shift+Left/Right: Select words. + - Ctrl+A or Double-Click: Select All. + - Ctrl+X, Ctrl+C, Ctrl+V: Use OS clipboard. + - Ctrl+Z Undo. + - Ctrl+Y or Ctrl+Shift+Z: Redo. - ESCAPE: Revert text to its original value. - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors. - KEYBOARD CONTROLS - Basic: - - Tab, SHIFT+Tab Cycle through text editable fields. - - CTRL+Tab, CTRL+Shift+Tab Cycle through windows. - - CTRL+Click Input text into a Slider or Drag widget. + - Tab, Shift+Tab Cycle through text editable fields. + - Ctrl+Tab, Ctrl+Shift+Tab Cycle through windows. + - Ctrl+Click Input text into a Slider or Drag widget. - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`: - - Tab, SHIFT+Tab: Cycle through every items. + - Tab, Shift+Tab: Cycle through every items. - Arrow keys Move through items using directional navigation. Tweak value. - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys). - Enter Activate item (prefer text input when possible). @@ -164,7 +164,7 @@ CODE - Page Up, Page Down Previous page, next page. - Home, End Scroll to top, scroll to bottom. - Alt Toggle between scrolling layer and menu layer. - - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving. + - Ctrl+Tab then Ctrl+Arrows Move window. Hold Shift to resize instead of moving. - Output when ImGuiConfigFlags_NavEnableKeyboard set, - io.WantCaptureKeyboard flag is set when keyboard is claimed. - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set. @@ -1245,13 +1245,13 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: #endif // Debug options -#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction. +#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold Ctrl to display for all candidates. Ctrl+Arrow to change last direction. #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window // Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls. static const float FONT_DEFAULT_SIZE = 20.0f; -// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. +// When using Ctrl+Tab (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear static const float NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10f; // Time to highlight an item activated by a shortcut. @@ -5175,7 +5175,7 @@ void ImGui::StopMouseMovingWindow() } // Handle mouse moving window -// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() +// Note: moving window with the navigation keys (Square + d-pad / Ctrl+Tab + Arrows) are processed in NavUpdateWindowing() // FIXME: We don't have strong guarantee that g.MovingWindow stay synced with g.ActiveId == g.MovingWindow->MoveId. // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs, // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other. @@ -5448,7 +5448,7 @@ void ImGui::NewFrame() KeepAliveID(g.DragDropPayload.SourceId); // [DEBUG] - if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL + if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding Ctrl g.DebugDrawIdConflictsId = 0; if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1) g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame; @@ -5835,10 +5835,10 @@ static void ImGui::RenderDimmedBackgrounds() } else if (dim_bg_for_window_list) { - // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window + // Draw dimming behind Ctrl+Tab target window and behind Ctrl+Tab UI window RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio)); - // Draw border around CTRL+Tab target window + // Draw border around Ctrl+Tab target window ImGuiWindow* window = g.NavWindowingTargetAnim; ImGuiViewport* viewport = GetMainViewport(); float distance = g.FontSize; @@ -5894,7 +5894,7 @@ void ImGui::EndFrame() g.CurrentWindow->Active = false; End(); - // Update navigation: CTRL+Tab, wrap-around requests + // Update navigation: Ctrl+Tab, wrap-around requests NavEndFrame(); // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) @@ -7460,7 +7460,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. bool window_title_visible_elsewhere = false; - if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB + if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using Ctrl+Tab window_title_visible_elsewhere = true; if (flags & ImGuiWindowFlags_ChildMenu) window_title_visible_elsewhere = true; @@ -7938,7 +7938,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (want_focus && window == g.NavWindow) NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls - // Pressing CTRL+C copy window content into the clipboard + // Pressing Ctrl+C copy window content into the clipboard // [EXPERIMENTAL] Breaks on nested Begin/End pairs. We need to work that out and add better logging scope. // [EXPERIMENTAL] Text outputs has many issues. if (g.IO.ConfigWindowsCopyContentsWithCtrlC) @@ -10059,7 +10059,7 @@ static void ImGui::UpdateMouseInputs() ImGuiIO& io = g.IO; // Mouse Wheel swapping flag - // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead + // As a standard behavior holding Shift while using Vertical Mouse Wheel triggers Horizontal scroll instead // - We avoid doing it on OSX as it the OS input layer handles this already. // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature. // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source. @@ -11021,7 +11021,7 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() Separator(); if (g.IO.ConfigDebugHighlightIdConflictsShowItemPicker) { - Text("(Hold CTRL to: use "); + Text("(Hold Ctrl to: use "); SameLine(0.0f, 0.0f); if (SmallButton("Item Picker")) DebugStartItemPicker(); @@ -11030,10 +11030,10 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() } else { - Text("(Hold CTRL to "); + Text("(Hold Ctrl to: "); } SameLine(0.0f, 0.0f); - TextLinkOpenURL("Read FAQ \"About ID Stack System\"", "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage"); + TextLinkOpenURL("read FAQ \"About ID Stack System\"", "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#qa-usage"); SameLine(0.0f, 0.0f); Text(")"); EndErrorTooltip(); @@ -11042,8 +11042,8 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() if (g.ErrorCountCurrentFrame > 0 && BeginErrorTooltip()) // Amend at end of frame { Separator(); - Text("(Hold CTRL to:"); - SameLine(); + Text("(Hold Ctrl to: "); + SameLine(0.0f, 0.0f); if (SmallButton("Enable Asserts")) g.IO.ConfigErrorRecoveryEnableAssert = true; //SameLine(); @@ -11056,7 +11056,7 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() #endif } -// Pseudo-tooltip. Follow mouse until CTRL is held. When CTRL is held we lock position, allowing to click it. +// Pseudo-tooltip. Follow mouse until Ctrl is held. When Ctrl is held we lock position, allowing to click it. bool ImGui::BeginErrorTooltip() { ImGuiContext& g = *GImGui; @@ -13054,7 +13054,7 @@ static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb) const ImGuiDir move_dir = g.NavMoveDir; #if IMGUI_DEBUG_NAV_SCORING char buf[200]; - if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate. + if (g.IO.KeyCtrl) // Hold Ctrl to preview score in matching quadrant. Ctrl+Arrow to rotate. { if (quadrant == move_dir) { @@ -13600,7 +13600,7 @@ static void ImGui::NavUpdate() if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main) g.NavWindow->NavLastChildNavWindow = NULL; - // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.) + // Update Ctrl+Tab and Windowing features (hold Square to move/resize/etc.) NavUpdateWindowing(); // Set output flags for user application @@ -13817,7 +13817,7 @@ void ImGui::NavUpdateCreateMoveRequest() g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y); } - // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction. + // [DEBUG] Always send a request when holding Ctrl. Hold Ctrl + Arrow change the direction. #if IMGUI_DEBUG_NAV_SCORING //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C)) // g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3); @@ -14169,7 +14169,7 @@ static void ImGui::NavEndFrame() { ImGuiContext& g = *GImGui; - // Show CTRL+TAB list window + // Show Ctrl+Tab list window if (g.NavWindowingTarget != NULL) NavUpdateWindowingOverlay(); @@ -14239,8 +14239,8 @@ static void ImGui::NavUpdateCreateWrappingRequest() NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags); } -// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) -// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. +// Can we focus this window with Ctrl+Tab (or PadMenu + PadFocusPrev/PadFocusNext) +// Note that NoNavFocus makes the window not reachable with Ctrl+Tab but it can still be focused with mouse or programmatically. // If you want a window to never be focused, you may use the e.g. NoInputs flag. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) { @@ -14292,7 +14292,7 @@ static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window) // If the window has ONLY a menu layer (no main layer), select it directly // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame, - // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since + // so Ctrl+Tab where the keys are only held for 1 frame will be able to use correct layers mask since // the target window as already been previewed once. // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases, // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask* @@ -14304,7 +14304,7 @@ static void ImGui::NavUpdateWindowingApplyFocus(ImGuiWindow* apply_focus_window) } // Windowing management mode -// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer) +// Keyboard: Ctrl+Tab (change focus/move/resize), Alt (toggle menu layer) // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer) static void ImGui::NavUpdateWindowing() { @@ -14315,7 +14315,7 @@ static void ImGui::NavUpdateWindowing() bool apply_toggle_layer = false; ImGuiWindow* modal_window = GetTopMostPopupModal(); - bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal. + bool allow_windowing = (modal_window == NULL); // FIXME: This prevent Ctrl+Tab from being usable with windows that are inside the Begin-stack of that modal. if (!allow_windowing) g.NavWindowingTarget = NULL; @@ -14327,7 +14327,7 @@ static void ImGui::NavUpdateWindowing() g.NavWindowingTargetAnim = NULL; } - // Start CTRL+Tab or Square+L/R window selection + // Start Ctrl+Tab or Square+L/R window selection // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab) const ImGuiID owner_id = ImHashStr("##NavUpdateWindowing"); const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; @@ -14395,7 +14395,7 @@ static void ImGui::NavUpdateWindowing() // Keyboard: Focus if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard) { - // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise + // Visuals only appears after a brief time after pressing TAB the first time, so that a fast Ctrl+Tab doesn't add visual noise ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_; IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows. g.NavWindowingTimer += io.DeltaTime; @@ -14406,7 +14406,7 @@ static void ImGui::NavUpdateWindowing() apply_focus_window = g.NavWindowingTarget; } - // Keyboard: Press and Release ALT to toggle menu layer + // Keyboard: Press and Release Alt to toggle menu layer const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt }; bool windowing_toggle_layer_start = false; if (g.NavWindow != NULL && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) @@ -14512,7 +14512,7 @@ static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window) return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled); } -// Overlay displayed when using CTRL+TAB. Called by EndFrame(). +// Overlay displayed when using Ctrl+Tab. Called by EndFrame(). void ImGui::NavUpdateWindowingOverlay() { ImGuiContext& g = *GImGui; @@ -16704,7 +16704,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) Text("Keys down:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyDown(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); } Text("Keys pressed:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyPressed(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); } Text("Keys released:"); for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (!IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); } - Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "Ctrl " : "", io.KeyShift ? "Shift " : "", io.KeyAlt ? "Alt " : "", io.KeySuper ? "Super " : ""); Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public. DebugRenderKeyboardPreview(GetWindowDrawList()); Unindent(); @@ -17571,7 +17571,7 @@ static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags) } else { - ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)"); + ImGui::SetItemTooltip("Hold Shift when clicking to enable for 2 frames only (useful for spammy log entries)"); } } @@ -17952,7 +17952,7 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) 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."); - // CTRL+C to copy path + // Ctrl+C to copy path const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime; PushStyleVarY(ImGuiStyleVar_FramePadding, 0.0f); Checkbox("Hex-encode non-ASCII", &tool->OptHexEncodeNonAsciiChars); diff --git a/imgui.h b/imgui.h index 9990253de..ca1b9b6de 100644 --- a/imgui.h +++ b/imgui.h @@ -214,9 +214,9 @@ struct ImGuiViewport; // A Platform Window (always only one in 'ma // Enumerations // - We don't use strongly typed enums much because they add constraints (can't extend in private code, can't store typed in bit fields, extra casting on iteration) // - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! -// - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. -// - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. -// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. enum ImGuiDir : int; // -> enum ImGuiDir // Enum: A cardinal direction (Left, Right, Up, Down) enum ImGuiKey : int; // -> enum ImGuiKey // Enum: A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value) enum ImGuiMouseSource : int; // -> enum ImGuiMouseSource // Enum; A mouse input source identifier (Mouse, TouchScreen, Pen) @@ -231,9 +231,9 @@ typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A // Flags (declared as int to allow using as flags without overhead, and to not pollute the top of this file) // - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! -// - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. -// - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. -// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Internal, do not use! @@ -662,13 +662,13 @@ namespace ImGui 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); // 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. + // - 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. // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every function, note that 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 address of your first element out of a contiguous set, e.g. &myvector.x // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. // - Format string may also be set to NULL or use the default format ("%f" or "%d"). // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For keyboard/gamepad navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). - // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used. + // - Use v_min < v_max to clamp edits to given limits. Note that Ctrl+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used. // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. // - 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. @@ -687,7 +687,7 @@ namespace ImGui 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); // 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. + // - 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. // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. // - 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. @@ -763,7 +763,7 @@ namespace ImGui 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. // 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. + // - 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. // - ImGuiSelectionUserData is often used to store your item index within the current view (but may store something else). // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. // - TreeNode() is technically supported but... using this correctly is more complicated. You need some sort of linear/random access to your tree, @@ -1168,7 +1168,7 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) ImGuiWindowFlags_NoNavInputs = 1 << 16, // No keyboard/gamepad navigation within the window - ImGuiWindowFlags_NoNavFocus = 1 << 17, // No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by CTRL+TAB) + ImGuiWindowFlags_NoNavFocus = 1 << 17, // No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by Ctrl+Tab) ImGuiWindowFlags_UnsavedDocument = 1 << 18, // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, @@ -1682,7 +1682,7 @@ enum ImGuiInputFlags_ ImGuiInputFlags_RouteAlways = 1 << 13, // Do not register route, poll keys directly. // - Routing options ImGuiInputFlags_RouteOverFocused = 1 << 14, // Option: global route: higher priority than focused route (unless active item in focused route). - ImGuiInputFlags_RouteOverActive = 1 << 15, // Option: global route: higher priority than active item. Unlikely you need to use that: will interfere with every active items, e.g. CTRL+A registered by InputText will be overridden by this. May not be fully honored as user/internal code is likely to always assume they can access keys when active. + ImGuiInputFlags_RouteOverActive = 1 << 15, // Option: global route: higher priority than active item. Unlikely you need to use that: will interfere with every active items, e.g. Ctrl+A registered by InputText will be overridden by this. May not be fully honored as user/internal code is likely to always assume they can access keys when active. ImGuiInputFlags_RouteUnlessBgFocused = 1 << 16, // Option: global route: will not be applied if underlying background/void is focused (== no Dear ImGui windows are focused). Useful for overlay applications. ImGuiInputFlags_RouteFromRootWindow = 1 << 17, // Option: route evaluated from the point of view of root window rather than current window. @@ -1781,8 +1781,8 @@ enum ImGuiCol_ ImGuiCol_DragDropTargetBg, // Rectangle background highlighting a drop target ImGuiCol_UnsavedMarker, // Unsaved Document marker (in window title and tabs) ImGuiCol_NavCursor, // Color of keyboard/gamepad navigation cursor/rectangle, when visible - ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB - ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active + ImGuiCol_NavWindowingHighlight, // Highlight window when using Ctrl+Tab + ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the Ctrl+Tab window list, when active ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active ImGuiCol_COUNT, @@ -1798,9 +1798,9 @@ enum ImGuiCol_ // - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. // During initialization or between frames, feel free to just poke into ImGuiStyle directly. // - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description. -// - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. -// - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. -// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. // - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. enum ImGuiStyleVar_ { @@ -1920,9 +1920,9 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_None = 0, ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). - ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget. + ImGuiSliderFlags_NoInput = 1 << 7, // Disable Ctrl+Click or Enter key allowing to input text directly into the widget. ImGuiSliderFlags_WrapAround = 1 << 8, // Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now. - ImGuiSliderFlags_ClampOnInput = 1 << 9, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiSliderFlags_ClampOnInput = 1 << 9, // Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds. ImGuiSliderFlags_ClampZeroRange = 1 << 10, // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it. ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, // Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, @@ -2394,7 +2394,7 @@ struct ImGuiIO // Font system ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. - bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with Ctrl+Wheel. // Keyboard/Gamepad Navigation options bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. @@ -2415,7 +2415,7 @@ struct ImGuiIO bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard. bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. - bool ConfigWindowsCopyContentsWithCtrlC; // = false // [EXPERIMENTAL] CTRL+C copy the contents of focused window into the clipboard. Experimental because: (1) has known issues with nested Begin/End pairs (2) text output quality varies (3) text output is in submission order rather than spatial order. + bool ConfigWindowsCopyContentsWithCtrlC; // = false // [EXPERIMENTAL] Ctrl+C copy the contents of focused window into the clipboard. Experimental because: (1) has known issues with nested Begin/End pairs (2) text output quality varies (3) text output is in submission order rather than spatial order. bool ConfigScrollbarScrollByPage; // = true // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location. float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. @@ -2544,7 +2544,7 @@ struct ImGuiIO // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. - float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold SHIFT to turn vertical scroll into horizontal scroll. + float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold Shift to turn vertical scroll into horizontal scroll. float MouseWheelH; // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends. ImGuiMouseSource MouseSource; // Mouse actual input peripheral (Mouse/TouchScreen/Pen). bool KeyCtrl; // Keyboard modifier down: Ctrl (non-macOS), Cmd (macOS) @@ -2567,8 +2567,8 @@ struct ImGuiIO double MouseReleasedTime[5]; // Time of last released (rarely used! but useful to handle delayed single-click when trying to disambiguate them from double-click). bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. - bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding SHIFT requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system. - bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a Ctrl+click that spawned a simulated right click + bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding Shift requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system. + bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a Ctrl+Click that spawned a simulated right click float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) float MouseDownDurationPrev[5]; // Previous time the mouse button has been down float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) @@ -2956,7 +2956,7 @@ struct ImColor // Multi-selection system // Documentation at: https://github.com/ocornut/imgui/wiki/Multi-Select // - Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos using this. -// - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) +// - This system implements standard multi-selection idioms (Ctrl+Mouse/Keyboard, Shift+Mouse/Keyboard, etc) // with support for clipper (skipping non-visible items), box-select and many other details. // - Selectable(), Checkbox() are supported but custom widgets may use it as well. // - TreeNode() is technically supported but... using this correctly is more complicated: you need some sort of linear/random access to your tree, @@ -2994,7 +2994,7 @@ enum ImGuiMultiSelectFlags_ { ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! - ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to select all. + ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable Ctrl+A shortcut to select all. ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). With BoxSelect is also ensure contiguous SetRange requests are not combined into one. This allows not handling interpolation in SetRange requests. ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes). ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 380e58f90..1c8779951 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -59,9 +59,9 @@ // Because we can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp. // Navigating this file: -// - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. -// - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. -// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. // - You can search/grep for all sections listed in the index to find the section. /* @@ -510,7 +510,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback."); ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly); ImGui::Checkbox("io.ConfigWindowsCopyContentsWithCtrlC", &io.ConfigWindowsCopyContentsWithCtrlC); // [EXPERIMENTAL] - ImGui::SameLine(); HelpMarker("*EXPERIMENTAL* CTRL+C copy the contents of focused window into the clipboard.\n\nExperimental because:\n- (1) has known issues with nested Begin/End pairs.\n- (2) text output quality varies.\n- (3) text output is in submission order rather than spatial order."); + ImGui::SameLine(); HelpMarker("*EXPERIMENTAL* Ctrl+C copy the contents of focused window into the clipboard.\n\nExperimental because:\n- (1) has known issues with nested Begin/End pairs.\n- (2) text output quality varies.\n- (3) text output is in submission order rather than spatial order."); ImGui::Checkbox("io.ConfigScrollbarScrollByPage", &io.ConfigScrollbarScrollByPage); ImGui::SameLine(); HelpMarker("Enable scrolling page by page when clicking outside the scrollbar grab.\nWhen disabled, always scroll to clicked location.\nWhen enabled, Shift+Click scrolls to clicked location."); @@ -895,12 +895,12 @@ static void DemoWindowWidgetsBasic() ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); ImGui::SameLine(); HelpMarker( "USER:\n" - "Hold SHIFT or use mouse to select text.\n" - "CTRL+Left/Right to word jump.\n" - "CTRL+A or Double-Click to select all.\n" - "CTRL+X,CTRL+C,CTRL+V for clipboard.\n" - "CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo.\n" - "ESCAPE to revert.\n\n" + "Hold Shift or use mouse to select text.\n" + "Ctrl+Left/Right to word jump.\n" + "Ctrl+A or Double-Click to select all.\n" + "Ctrl+X,Ctrl+C,Ctrl+V for clipboard.\n" + "Ctrl+Z to undo, Ctrl+Y/Ctrl+Shift+Z to redo.\n" + "Escape to revert.\n\n" "PROGRAMMER:\n" "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() " "to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated " @@ -937,8 +937,8 @@ static void DemoWindowWidgetsBasic() ImGui::DragInt("drag int", &i1, 1); ImGui::SameLine(); HelpMarker( "Click and drag to edit value.\n" - "Hold SHIFT/ALT for faster/slower edit.\n" - "Double-click or CTRL+click to input value."); + "Hold Shift/Alt for faster/slower edit.\n" + "Double-Click or Ctrl+Click to input value."); ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); ImGui::DragInt("drag int wrap 100..200", &i3, 1, 100, 200, "%d", ImGuiSliderFlags_WrapAround); @@ -954,7 +954,7 @@ static void DemoWindowWidgetsBasic() IMGUI_DEMO_MARKER("Widgets/Basic/SliderInt, SliderFloat"); static int i1 = 0; ImGui::SliderInt("slider int", &i1, -1, 3); - ImGui::SameLine(); HelpMarker("CTRL+click to input value."); + ImGui::SameLine(); HelpMarker("Ctrl+Click to input value."); static float f1 = 0.123f, f2 = 0.0f; ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); @@ -972,7 +972,7 @@ static void DemoWindowWidgetsBasic() static int elem = Element_Fire; const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown"; - ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); // Use ImGuiSliderFlags_NoInput flag to disable CTRL+Click here. + ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); // Use ImGuiSliderFlags_NoInput flag to disable Ctrl+Click here. ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer."); } @@ -986,8 +986,8 @@ static void DemoWindowWidgetsBasic() ImGui::SameLine(); HelpMarker( "Click on the color square to open a color picker.\n" "Click and hold to use drag and drop.\n" - "Right-click on the color square to show options.\n" - "CTRL+click on individual component to input value.\n"); + "Right-Click on the color square to show options.\n" + "Ctrl+Click on individual component to input value.\n"); ImGui::ColorEdit4("color 2", col2); } @@ -1105,7 +1105,7 @@ static void DemoWindowWidgetsColorAndPickers() ImGui::Text("Color widget:"); ImGui::SameLine(); HelpMarker( "Click on the color square to open a color picker.\n" - "CTRL+click on individual component to input value.\n"); + "Ctrl+Click on individual component to input value.\n"); ImGui::ColorEdit3("MyColor##1", (float*)&color, base_flags); IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (HSV, with Alpha)"); @@ -1437,7 +1437,7 @@ static void DemoWindowWidgetsDataTypes() ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); ImGui::SameLine(); HelpMarker( "As with every widget in dear imgui, we never modify values unless there is a user interaction.\n" - "You can override the clamping limits by using CTRL+Click to input a value."); + "You can override the clamping limits by using Ctrl+Click to input a value."); ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL); ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms"); ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL); @@ -1697,7 +1697,7 @@ static void DemoWindowWidgetsDragsAndSliders() static ImGuiSliderFlags flags = ImGuiSliderFlags_None; ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp); ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", &flags, ImGuiSliderFlags_ClampOnInput); - ImGui::SameLine(); HelpMarker("Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds."); + ImGui::SameLine(); HelpMarker("Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds."); ImGui::CheckboxFlags("ImGuiSliderFlags_ClampZeroRange", &flags, ImGuiSliderFlags_ClampZeroRange); ImGui::SameLine(); HelpMarker("Clamp even if min==max==0.0f. Otherwise DragXXX functions don't clamp."); ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic); @@ -1705,7 +1705,7 @@ static void DemoWindowWidgetsDragsAndSliders() ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat); ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput); - ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); + ImGui::SameLine(); HelpMarker("Disable Ctrl+Click or Enter key allowing to input text directly into the widget."); ImGui::CheckboxFlags("ImGuiSliderFlags_NoSpeedTweaks", &flags, ImGuiSliderFlags_NoSpeedTweaks); ImGui::SameLine(); HelpMarker("Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic."); ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuiSliderFlags_WrapAround); @@ -2668,11 +2668,11 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d } // Demonstrate implementation a most-basic form of multi-selection manually - // This doesn't support the SHIFT modifier which requires BeginMultiSelect()! + // This doesn't support the Shift modifier which requires BeginMultiSelect()! IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (manual/simplified, without BeginMultiSelect)"); if (ImGui::TreeNode("Multi-Select (manual/simplified, without BeginMultiSelect)")) { - HelpMarker("Hold CTRL and click to select multiple items."); + HelpMarker("Hold Ctrl and Click to select multiple items."); static bool selection[5] = { false, false, false, false, false }; for (int n = 0; n < 5; n++) { @@ -2680,7 +2680,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d sprintf(buf, "Object %d", n); if (ImGui::Selectable(buf, selection[n])) { - if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held + if (!ImGui::GetIO().KeyCtrl) // Clear selection when Ctrl is not held memset(selection, 0, sizeof(selection)); selection[n] ^= 1; // Toggle current item } @@ -2689,7 +2689,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d } // Demonstrate handling proper multi-selection using the BeginMultiSelect/EndMultiSelect API. - // SHIFT+Click w/ CTRL and other standard features are supported. + // Shift+Click w/ Ctrl and other standard features are supported. // We use the ImGuiSelectionBasicStorage helper which you may freely reimplement. IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); if (ImGui::TreeNode("Multi-Select")) @@ -2698,7 +2698,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::BulletText("Keyboard navigation (arrows, page up/down, home/end, space)."); ImGui::BulletText("Ctrl modifier to preserve and toggle selection."); ImGui::BulletText("Shift modifier for range selection."); - ImGui::BulletText("CTRL+A to select all."); + ImGui::BulletText("Ctrl+A to select all."); ImGui::BulletText("Escape to clear selection."); ImGui::BulletText("Click and drag to box-select."); ImGui::Text("Tip: Use 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen."); @@ -4072,7 +4072,7 @@ static void DemoWindowWidgetsTreeNodes() { HelpMarker( "This is a more typical looking tree with selectable nodes.\n" - "Click to select, CTRL+Click to toggle, click on arrows or double-click to open."); + "Click to select, Ctrl+Click to toggle, click on arrows or double-click to open."); static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth; static bool align_label_with_current_x_position = false; static bool test_drag_and_drop = false; @@ -4159,7 +4159,7 @@ static void DemoWindowWidgetsTreeNodes() // Update selection state // (process outside of tree loop to avoid visual inconsistencies during the clicking frame) if (ImGui::GetIO().KeyCtrl) - selection_mask ^= (1 << node_clicked); // CTRL+click to toggle + selection_mask ^= (1 << node_clicked); // Ctrl+Click to toggle else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection selection_mask = (1 << node_clicked); // Click to single-select } @@ -5466,7 +5466,7 @@ static void DemoWindowPopups() ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); ImGui::Separator(); - ImGui::MenuItem("Menu item", "CTRL+M"); + ImGui::MenuItem("Menu item", "Ctrl+M"); if (ImGui::BeginMenu("Menu inside a regular window")) { ShowExampleMenuFile(); @@ -7897,16 +7897,16 @@ static void DemoWindowInputs() ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(1.0f, 0.0f, 1.0f, 0.1f)); ImGui::BeginChild("WindowA", ImVec2(-FLT_MIN, line_height * 14), true); - ImGui::Text("Press CTRL+A and see who receives it!"); + ImGui::Text("Press Ctrl+A and see who receives it!"); ImGui::Separator(); - // 1: Window polling for CTRL+A + // 1: Window polling for Ctrl+A ImGui::Text("(in WindowA)"); ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); - // 2: InputText also polling for CTRL+A: it always uses _RouteFocused internally (gets priority when active) + // 2: InputText also polling for Ctrl+A: it always uses _RouteFocused internally (gets priority when active) // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) - //char str[16] = "Press CTRL+A"; + //char str[16] = "Press Ctrl+A"; //ImGui::Spacing(); //ImGui::InputText("InputTextB", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly); //ImGuiID item_id = ImGui::GetItemID(); @@ -7919,7 +7919,7 @@ static void DemoWindowInputs() ImGui::Text("IsWindowFocused: %d", ImGui::IsWindowFocused()); ImGui::EndChild(); - // 4: Child window polling for CTRL+A. It is deeper than WindowA and gets priority when focused. + // 4: Child window polling for Ctrl+A. It is deeper than WindowA and gets priority when focused. ImGui::BeginChild("ChildE", ImVec2(-FLT_MIN, line_height * 4), true); ImGui::Text("(in ChildE: using same Shortcut)"); ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); @@ -7976,7 +7976,7 @@ static void DemoWindowInputs() IMGUI_DEMO_MARKER("Inputs & Focus/Tabbing"); if (ImGui::TreeNode("Tabbing")) { - ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields."); + ImGui::Text("Use Tab/Shift+Tab to cycle through keyboard editable fields."); static char buf[32] = "hello"; ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); @@ -8539,7 +8539,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ShowFontAtlas(atlas); // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. - // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). + // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows Ctrl+Click text to get out of bounds). /* SeparatorText("Legacy Scaling"); const float MIN_SCALE = 0.3f; @@ -8643,18 +8643,18 @@ void ImGui::ShowUserGuide() BulletText( "Click and drag on lower corner to resize window\n" "(double-click to auto fit window to its contents)."); - BulletText("CTRL+Click on a slider or drag box to input value as text."); - BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); - BulletText("CTRL+Tab to select a window."); + BulletText("Ctrl+Click on a slider or drag box to input value as text."); + BulletText("Tab/Shift+Tab to cycle through keyboard editable fields."); + BulletText("Ctrl+Tab to select a window."); if (io.FontAllowUserScaling) - BulletText("CTRL+Mouse Wheel to zoom window contents."); + BulletText("Ctrl+Mouse Wheel to zoom window contents."); BulletText("While inputting text:\n"); Indent(); - BulletText("CTRL+Left/Right to word jump."); - BulletText("CTRL+A or double-click to select all."); - BulletText("CTRL+X/C/V to use clipboard cut/copy/paste."); - BulletText("CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo."); - BulletText("ESCAPE to revert."); + BulletText("Ctrl+Left/Right to word jump."); + BulletText("Ctrl+A or double-click to select all."); + BulletText("Ctrl+X/C/V to use clipboard cut/copy/paste."); + BulletText("Ctrl+Z to undo, Ctrl+Y/Ctrl+Shift+Z to redo."); + BulletText("Escape to revert."); Unindent(); BulletText("With keyboard navigation enabled:"); Indent(); @@ -8688,12 +8688,12 @@ static void ShowExampleAppMainMenuBar() } if (ImGui::BeginMenu("Edit")) { - if (ImGui::MenuItem("Undo", "CTRL+Z")) {} - if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item + if (ImGui::MenuItem("Undo", "Ctrl+Z")) {} + if (ImGui::MenuItem("Redo", "Ctrl+Y", false, false)) {} // Disabled item ImGui::Separator(); - if (ImGui::MenuItem("Cut", "CTRL+X")) {} - if (ImGui::MenuItem("Copy", "CTRL+C")) {} - if (ImGui::MenuItem("Paste", "CTRL+V")) {} + if (ImGui::MenuItem("Cut", "Ctrl+X")) {} + if (ImGui::MenuItem("Copy", "Ctrl+C")) {} + if (ImGui::MenuItem("Paste", "Ctrl+V")) {} ImGui::EndMenu(); } ImGui::EndMainMenuBar(); @@ -9698,7 +9698,7 @@ static void ShowExampleAppConstrainedResize(bool* p_open) } else { - ImGui::Text("(Hold SHIFT to display a dummy viewport)"); + ImGui::Text("(Hold Shift to display a dummy viewport)"); if (ImGui::Button("Set 200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine(); if (ImGui::Button("Set 500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine(); if (ImGui::Button("Set 800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); } @@ -10635,7 +10635,7 @@ struct ExampleAssetsBrowser ImGui::SeparatorText("Layout"); ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f"); - ImGui::SameLine(); HelpMarker("Use CTRL+Wheel to zoom"); + ImGui::SameLine(); HelpMarker("Use Ctrl+Wheel to zoom"); ImGui::SliderInt("Icon Spacing", &IconSpacing, 0, 32); ImGui::SliderInt("Icon Hit Spacing", &IconHitSpacing, 0, 32); ImGui::Checkbox("Stretch Spacing", &StretchSpacing); @@ -10827,7 +10827,7 @@ struct ExampleAssetsBrowser if (want_delete) Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus); - // Zooming with CTRL+Wheel + // Zooming with Ctrl+Wheel if (ImGui::IsWindowAppearing()) ZoomWheelAccum = 0.0f; if (ImGui::IsWindowHovered() && io.MouseWheel != 0.0f && ImGui::IsKeyDown(ImGuiMod_Ctrl) && ImGui::IsAnyItemActive() == false) diff --git a/imgui_internal.h b/imgui_internal.h index 48cd46d9d..091873bf8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2350,13 +2350,13 @@ struct ImGuiContext bool NavJustMovedToIsTabbing; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. - // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) - bool ConfigNavWindowingWithGamepad; // = true. Enable CTRL+TAB by holding ImGuiKey_GamepadFaceLeft (== ImGuiKey_NavGamepadMenu). When false, the button may still be used to toggle Menu layer. + // Navigation: Windowing (Ctrl+Tab for list, or Menu button + keys or directional pads to move/resize) + bool ConfigNavWindowingWithGamepad; // = true. Enable Ctrl+Tab by holding ImGuiKey_GamepadFaceLeft (== ImGuiKey_NavGamepadMenu). When false, the button may still be used to toggle Menu layer. ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828) ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X) - ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! + ImGuiWindow* NavWindowingTarget; // Target window when doing Ctrl+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. - ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents + ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the Ctrl+Tab contents float NavWindowingTimer; float NavWindowingHighlightAlpha; ImGuiInputSource NavWindowingInputSource; @@ -2366,7 +2366,7 @@ struct ImGuiContext ImVec2 NavWindowingAccumDeltaSize; // Render - float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) + float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and Ctrl+Tab list) // Drag and Drop bool DragDropActive; @@ -2435,7 +2435,7 @@ struct ImGuiContext ImGuiInputTextDeactivatedState InputTextDeactivatedState; ImFontBaked InputTextPasswordFontBackupBaked; ImFontFlags InputTextPasswordFontBackupFlags; - ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc. + ImGuiID TempInputId; // Temporary text input when using Ctrl+Click on a slider, etc. ImGuiDataTypeStorage DataTypeZeroValue; // 0 for all data types int BeginMenuDepth; int BeginComboDepth; @@ -2511,7 +2511,7 @@ struct ImGuiContext // Debug Tools // (some of the highly frequently used data are interleaved in other structures above: DebugBreakXXX fields, DebugHookIdInfo, DebugLocateId etc.) - int DebugDrawIdConflictsCount; // Locked count (preserved when holding CTRL) + int DebugDrawIdConflictsCount; // Locked count (preserved when holding Ctrl) ImGuiDebugLogFlags DebugLogFlags; ImGuiTextBuffer DebugLogBuf; ImGuiTextIndex DebugLogIndex; @@ -2791,7 +2791,7 @@ struct IMGUI_API ImGuiTabBar ImGuiID ID; // Zero for tab-bars used by docking ImGuiID SelectedTabId; // Selected tab/window ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation - ImGuiID VisibleTabId; // 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; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e3a3baea2..8f5a746f1 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -24,9 +24,9 @@ Index of this file: */ // Navigating this file: -// - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. -// - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. -// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. +// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot. +// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. +// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. //----------------------------------------------------------------------------- // [SECTION] Commentary diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8c322e8dd..89b6d6e6f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2701,7 +2701,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { - // Tabbing or CTRL+click on Drag turns it into an InputText + // Tabbing or Ctrl+Click on Drag turns it into an InputText const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id); const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2 && TestKeyOwner(ImGuiKey_MouseLeft, id)); const bool make_active = (clicked || double_clicked || g.NavActivateId == id); @@ -2735,7 +2735,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, if (temp_input_is_active) { - // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp) + // Only clamp Ctrl+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp) bool clamp_enabled = false; if ((flags & ImGuiSliderFlags_ClampOnInput) && (p_min != NULL || p_max != NULL)) { @@ -3305,7 +3305,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { - // Tabbing or CTRL+click on Slider turns it into an input box + // Tabbing or Ctrl+Click on Slider turns it into an input box const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id); const bool make_active = (clicked || g.NavActivateId == id); if (make_active && clicked) @@ -3329,7 +3329,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat if (temp_input_is_active) { - // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp) + // Only clamp Ctrl+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp) const bool clamp_enabled = (flags & ImGuiSliderFlags_ClampOnInput) != 0; return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL); } @@ -3666,7 +3666,7 @@ int ImParseFormatPrecision(const char* fmt, int default_precision) return (precision == INT_MAX) ? default_precision : precision; } -// Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets) +// Create text input in place of another active widget (e.g. used when doing a Ctrl+Click on drag/slider widgets) // FIXME: Facilitate using this in variety of other situations. // FIXME: Among other things, setting ImGuiItemFlags_AllowDuplicateId in LastItemData is currently correct but // the expected relationship between TempInputXXX functions and LastItemData is a little fishy. @@ -3692,7 +3692,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. +// 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) { @@ -4012,7 +4012,7 @@ static bool ImCharIsSeparatorW(unsigned int c) static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx) { - // When ImGuiInputTextFlags_Password is set, we don't want actions such as CTRL+Arrow to leak the fact that underlying data are blanks or separators. + // When ImGuiInputTextFlags_Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators. if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0) return 0; @@ -4928,7 +4928,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if ((multiclick_count % 2) == 0) { // Double-click: Select word - // We always use the "Mac" word advance for double-click select vs CTRL+Right which use the platform dependent variant: + // We always use the "Mac" word advance for double-click select vs Ctrl+Right which use the platform dependent variant: // FIXME: There are likely many ways to improve this behavior, but there's no "right" behavior (depends on use-case, software, OS) const bool is_bol = (state->Stb->cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor - 1) == '\n'; if (STB_TEXT_HAS_SELECTION(state->Stb) || !is_bol) @@ -4997,7 +4997,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } // Process regular text input (before we check for Return because using some IME will effectively send a Return?) - // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. + // We ignore Ctrl inputs, but need to allow Alt+Ctrl as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeyCtrl); if (io.InputQueueCharacters.Size > 0) { @@ -5030,7 +5030,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl const bool is_startend_key_down = is_osx && io.KeyCtrl && !io.KeySuper && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End - // Using Shortcut() with ImGuiInputFlags_RouteFocused (default policy) to allow routing operations for other code (e.g. calling window trying to use CTRL+A and CTRL+B: former would be handled by InputText) + // Using Shortcut() with ImGuiInputFlags_RouteFocused (default policy) to allow routing operations for other code (e.g. calling window trying to use Ctrl+A and Ctrl+B: former would be handled by InputText) // Otherwise we could simply assume that we own the keys as we are active. const ImGuiInputFlags f_repeat = ImGuiInputFlags_Repeat; const bool is_cut = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_X, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Delete, f_repeat, id)) && !is_readonly && !is_password && (!is_multiline || state->HasSelection()); @@ -5208,7 +5208,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ apply_new_text_length = state->TextToRevertTo.Size - 1; // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents. - // Push records into the undo stack so we can CTRL+Z the revert operation itself + // Push records into the undo stack so we can Ctrl+Z the revert operation itself value_changed = true; stb_textedit_replace(state, state->Stb, state->TextToRevertTo.Data, state->TextToRevertTo.Size - 1); } @@ -5708,7 +5708,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. +// 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) { ImGuiWindow* window = GetCurrentWindow(); @@ -7948,7 +7948,7 @@ ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int sel } } - // Shortcut: Select all (CTRL+A) + // Shortcut: Select all (Ctrl+A) if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll)) if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A)) request_select_all = true; @@ -8093,7 +8093,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags if (ms->LoopRequestSetAll != -1) selected = (ms->LoopRequestSetAll == 1); - // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) + // When using Shift+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection) // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function) if (ms->IsKeyboardSetRange) { @@ -8124,7 +8124,7 @@ void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags // Alter button behavior flags // To handle drag and drop of multiple items we need to avoid clearing selection on click. - // Enabling this test makes actions using CTRL+SHIFT delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. + // Enabling this test makes actions using Ctrl+Shift delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items. if (p_button_flags != NULL) { ImGuiButtonFlags button_flags = *p_button_flags; @@ -8323,7 +8323,7 @@ void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed) MultiSelectAddSetRange(ms, range_selected, range_direction, storage->RangeSrcItem, item_data); } - // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect) + // Update/store the selection state of the Source item (used by Ctrl+Shift, when Source is unselected we perform a range unselect) if (storage->RangeSrcItem == item_data) storage->RangeSelected = selected ? 1 : 0; @@ -8537,7 +8537,7 @@ void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) else { // Append insertion + single sort likely be faster. - // Use req.RangeDirection to set order field so that shift+clicking from 1 to 5 is different than shift+clicking from 5 to 1 + // Use req.RangeDirection to set order field so that Shift+Clicking from 1 to 5 is different than Shift+Clicking from 5 to 1 const int size_before_amends = _Storage.Data.Size; int selection_order = _SelectionOrder + ((req.RangeDirection < 0) ? selection_changes - 1 : 0); for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++, selection_order += req.RangeDirection) @@ -10464,7 +10464,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } // Lock visibility - // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!) + // (Note: tab_contents_visible != tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) bool tab_contents_visible = (tab_bar->VisibleTabId == id); if (tab_contents_visible) tab_bar->VisibleTabWasSubmitted = true; From d2468507875486faa03bbf95f56171047b65b6a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 15:42:19 +0100 Subject: [PATCH 1489/2359] Fonts: added comment about the classic AddFontFromMemoryTTF() issue. (#9067, #6916, #6781, #5330, #4307, #2042, #2029, #1734, #1259, #220) --- imgui_draw.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 54d72f410..21ae9e258 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3633,6 +3633,11 @@ void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConf void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src) { IM_UNUSED(atlas); + // IF YOU GET A CRASH IN THE IM_FREE() CALL HERE AND USED AddFontFromMemoryTTF(): + // - DUE TO LEGACY REASON AddFontFromMemoryTTF() TRANSFERS MEMORY OWNERSHIP BY DEFAULT. + // - IT WILL THEREFORE CRASH WHEN PASSED DATA WHICH MAY NOT BE FREEED BY IMGUI. + // - USE `ImFontConfig font_cfg; font_cfg.FontDataOwnedByAtlas = false; io.Fonts->AddFontFromMemoryTTF(....., &cfg);` to disable passing ownership/ + // WE WILL ADDRESS THIS IN A FUTURE REWORK OF THE API. if (src->FontDataOwnedByAtlas) IM_FREE(src->FontData); src->FontData = NULL; From ec6219752dbbf30b30b25c86ff0024956a503ed4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 15:54:36 +0100 Subject: [PATCH 1490/2359] Fonts: calling ImFontAtlas::Clear() mid-frame without re-adding a font will lead to a more explicit crash. (#9067) + reformat Changelog. --- docs/CHANGELOG.txt | 26 +++++++++++++++----------- imgui.h | 2 +- imgui_draw.cpp | 5 ++++- imgui_internal.h | 1 + 4 files changed, 21 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index afc5290dc..82af01649 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -79,17 +79,21 @@ Other Changes: to auto-size on a given axis would keep marking ini settings as dirty. - Disabled: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) -- InputText: when buffer is not resizable, trying to paste contents that - cannot fit will now truncate text to nearest UTF-8 codepoint boundaries, - instead of completely ignoring the paste. (#9029) -- InputText: avoid continuously overwriting ownership of ImGuiKey_Enter/_KeypadEnter - keys in order to allow e.g. external Shortcut override behavior. (#9004) -- InputText: when using a callback to reduce/manipulate the value of BufTextLen, - we do not require anymore that CursorPos be clamped by user code. (#9029) -- InputTextMultiline: fixed a crash when using ImGuiInputTextFlags_WordWrap and - resizing the parent window while keeping the multi-line field active (which is - most typically achieved when resizing programmatically or via a docking layout - reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] +- InputText: + - When buffer is not resizable, trying to paste contents that cannot + fit will now truncate text to nearest UTF-8 codepoint boundaries, + instead of completely ignoring the paste. (#9029) + - Avoid continuously overwriting ownership of ImGuiKey_Enter/_KeypadEnter + keys in order to allow e.g. external Shortcut override behavior. (#9004) + - When using a callback to reduce/manipulate the value of BufTextLen, + we do not require anymore that CursorPos be clamped by user code. (#9029) + - InputTextMultiline: fixed a crash when using ImGuiInputTextFlags_WordWrap and + resizing the parent window while keeping the multi-line field active (which is + most typically achieved when resizing programmatically or via a docking layout + reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] +- Fonts: + - Calling ImFontAtlas::Clear() mid-frame without re-adding a font will + lead to a more explicit crash. - Textures: - Fixed an issue preventing multi-contexts from using each others' fonts if context 2 runs after context 1's Render() function. (#9039) diff --git a/imgui.h b/imgui.h index ca1b9b6de..a52ec5764 100644 --- a/imgui.h +++ b/imgui.h @@ -3638,7 +3638,7 @@ struct ImFontAtlas 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 void RemoveFont(ImFont* font); - IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) + IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures). IMGUI_API void CompactCache(); // Compact cached glyphs and texture. IMGUI_API void SetFontLoader(const ImFontLoader* font_loader); // Change font loader at runtime. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 21ae9e258..7111fb0b9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2656,6 +2656,7 @@ ImFontAtlas::~ImFontAtlas() TexData = NULL; } +// If you call this mid-frame, you would need to add new font and bind them! void ImFontAtlas::Clear() { bool backup_renderer_has_textures = RendererHasTextures; @@ -2706,6 +2707,8 @@ void ImFontAtlas::ClearFonts() { // FIXME-NEWATLAS: Illegal to remove currently bound font. IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + for (ImFont* font : Fonts) + ImFontAtlasBuildNotifySetFont(this, font, NULL); ImFontAtlasBuildDestroy(this); ClearInputData(); Fonts.clear_delete(); @@ -3200,7 +3203,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed // On font removal we need to remove references (otherwise we could queue removal?) // We allow old_font == new_font which forces updating all values (e.g. sizes) -static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font) +void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font) { for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) { diff --git a/imgui_internal.h b/imgui_internal.h index 091873bf8..2ada86891 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3856,6 +3856,7 @@ IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader); +IMGUI_API void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font); IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); IMGUI_API void ImFontAtlasBuildClear(ImFontAtlas* atlas); // Clear output and custom rects From 5a0c67c4b8257faa6699b36a745e7a91c817321c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 16:14:45 +0100 Subject: [PATCH 1491/2359] Debug Tools: ID Stack Tool: extracted code into a StackToolGetResultAsPath() function. --- imgui.cpp | 60 ++++++++++++++++++++++++++---------------------- imgui_internal.h | 2 +- 2 files changed, 33 insertions(+), 29 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 61c5f7445..df9a826c3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17900,19 +17900,44 @@ static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_f { ImGuiStackLevelInfo* info = &tool->Results[n]; ImGuiWindow* window = (info->DescOffset == -1 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL; - if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked) + if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked) return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", ImHashSkipUncontributingPrefix(window->Name)); - if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) + if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", ImHashSkipUncontributingPrefix(&tool->ResultPathsBuf.Buf[info->DescOffset])); - if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. + if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. return (*buf = 0); #ifdef IMGUI_ENABLE_TEST_ENGINE - if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo() + if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo() return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", ImHashSkipUncontributingPrefix(label)); #endif return ImFormatString(buf, buf_size, "???"); } +static const char* StackToolGetResultAsPath(ImGuiIDStackTool* tool, bool hex_encode_non_ascii_chars) +{ + ImGuiTextBuffer* buf = &tool->ResultFullPathBuf; + buf->resize(0); + for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++) + { + char level_desc[256]; + StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); + buf->append(stack_n == 0 ? "//" : "/"); + for (const char* p = level_desc; *p != 0; ) + { + unsigned int c; + const char* p_next = p + ImTextCharFromUtf8(&c, p, NULL); + if (c == '/') + buf->append("\\"); + if (c < 256 || !hex_encode_non_ascii_chars) + buf->append(p, p_next); + else for (; p < p_next; p++) + buf->appendf("\\x%02x", (unsigned char)*p); + p = p_next; + } + } + return buf->c_str(); +} + // ID Stack Tool: Display UI void ImGui::ShowIDStackToolWindow(bool* p_open) { @@ -17927,27 +17952,7 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) // Display hovered/active status ImGuiIDStackTool* tool = &g.DebugIDStackTool; - - // Build and display path - tool->ResultTempBuf.resize(0); - for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++) - { - char level_desc[256]; - StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); - tool->ResultTempBuf.append(stack_n == 0 ? "//" : "/"); - for (const char* p = level_desc; *p != 0; ) - { - unsigned int c; - const char* p_next = p + ImTextCharFromUtf8(&c, p, NULL); - if (c == '/') - tool->ResultTempBuf.append("\\"); - if (c < 256 || !tool->OptHexEncodeNonAsciiChars) - tool->ResultTempBuf.append(p, p_next); - else for (; p < p_next; p++) - tool->ResultTempBuf.appendf("\\x%02x", (unsigned char)*p); - p = p_next; - } - } + const char* result_path = StackToolGetResultAsPath(tool, tool->OptHexEncodeNonAsciiChars); Text("0x%08X", tool->QueryMainId); 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."); @@ -17964,14 +17969,13 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) if (tool->OptCopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused)) { tool->CopyToClipboardLastTime = (float)g.Time; - SetClipboardText(tool->ResultTempBuf.c_str()); + SetClipboardText(result_path); } - Text("- Path \"%s\"", tool->ResultTempBuf.c_str()); + Text("- Path \"%s\"", result_path); #ifdef IMGUI_ENABLE_TEST_ENGINE Text("- Label \"%s\"", tool->QueryMainId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryMainId) : ""); #endif - Separator(); // Display decorated stack diff --git a/imgui_internal.h b/imgui_internal.h index 2ada86891..283215295 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2140,7 +2140,7 @@ struct ImGuiIDStackTool bool OptCopyToClipboardOnCtrlC; float CopyToClipboardLastTime; ImGuiTextBuffer ResultPathsBuf; - ImGuiTextBuffer ResultTempBuf; + ImGuiTextBuffer ResultFullPathBuf; ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); LastActiveFrame = -1; OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; } }; From c254db763709e12eeabea54c52631c2b972b7d58 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 16:19:27 +0100 Subject: [PATCH 1492/2359] Debug Tools: ID Stack Tool: store ResultsComplete and don't display incomplete paths. --- imgui.cpp | 7 ++++--- imgui_internal.h | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index df9a826c3..441f62b0a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17819,9 +17819,10 @@ void ImGui::UpdateDebugToolStackQueries() if (stack_level >= 0 && stack_level < tool->Results.Size) if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2) tool->StackLevel++; - - // Update hook stack_level = tool->StackLevel; + + // Update status and hook + tool->ResultsComplete = (stack_level == tool->Results.Size); if (stack_level == -1) { g.DebugHookIdInfoId = query_main_id; @@ -17972,7 +17973,7 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) SetClipboardText(result_path); } - Text("- Path \"%s\"", result_path); + Text("- Path \"%s\"", tool->ResultsComplete ? result_path : ""); #ifdef IMGUI_ENABLE_TEST_ENGINE Text("- Label \"%s\"", tool->QueryMainId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryMainId) : ""); #endif diff --git a/imgui_internal.h b/imgui_internal.h index 283215295..fcd02f280 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2132,9 +2132,10 @@ struct ImGuiStackLevelInfo struct ImGuiIDStackTool { int LastActiveFrame; - int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level - ImGuiID QueryMainId; // ID to query details for + int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level. + ImGuiID QueryMainId; // ID to query details for. ImVector Results; + bool ResultsComplete; // All sub-query have succeeeded, result is complete. bool QueryHookActive; // Used to disambiguate the case where DebugHookIdInfoId == 0 which is valid. bool OptHexEncodeNonAsciiChars; bool OptCopyToClipboardOnCtrlC; From f145b0cffd5aa4ed43d2bab20d027441ce5a2d91 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 13 Nov 2025 16:43:34 +0100 Subject: [PATCH 1493/2359] Debug Tools: ID Stack Tool: refactor, extract data/code into ImGuiDebugItemPathQuery for reuse. --- imgui.cpp | 143 ++++++++++++++++++++++++----------------------- imgui_internal.h | 29 ++++++---- 2 files changed, 90 insertions(+), 82 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 441f62b0a..fc52026ae 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1322,7 +1322,7 @@ static void ErrorCheckNewFrameSanityChecks(); static void ErrorCheckEndFrameSanityChecks(); #ifndef IMGUI_DISABLE_DEBUG_TOOLS static void UpdateDebugToolItemPicker(); -static void UpdateDebugToolStackQueries(); +static void UpdateDebugToolItemPathQuery(); static void UpdateDebugToolFlashStyleColor(); #endif @@ -5621,7 +5621,7 @@ void ImGui::NewFrame() // [DEBUG] Update debug features #ifndef IMGUI_DISABLE_DEBUG_TOOLS UpdateDebugToolItemPicker(); - UpdateDebugToolStackQueries(); + UpdateDebugToolItemPathQuery(); UpdateDebugToolFlashStyleColor(); if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0) { @@ -17789,82 +17789,83 @@ void ImGui::UpdateDebugToolItemPicker() EndTooltip(); } -// [DEBUG] ID Stack Tool: update queries. Called by NewFrame() -void ImGui::UpdateDebugToolStackQueries() +// Update queries. The steps are: -1: query Stack, >= 0: query each stack item +// We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time +static ImGuiID DebugItemPathQuery_UpdateAndGetHookId(ImGuiDebugItemPathQuery* query, ImGuiID id) { - ImGuiContext& g = *GImGui; - ImGuiIDStackTool* tool = &g.DebugIDStackTool; - - // Clear hook when id stack tool is not visible - g.DebugHookIdInfoId = 0; - tool->QueryHookActive = false; - if (g.FrameCount != tool->LastActiveFrame + 1) - return; - - // Update queries. The steps are: -1: query Stack, >= 0: query each stack item - // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time - const ImGuiID query_main_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId; - if (tool->QueryMainId != query_main_id) + // Update query. Clear hook when no active query + if (query->MainID != id) { - tool->QueryMainId = query_main_id; - tool->StackLevel = -1; - tool->Results.resize(0); - tool->ResultPathsBuf.resize(0); + query->MainID = id; + query->Step = -1; + query->Complete = false; + query->Results.resize(0); + query->ResultsDescBuf.resize(0); } - if (query_main_id == 0) - return; + query->Active = false; + if (id == 0) + return 0; // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result) - int stack_level = tool->StackLevel; - if (stack_level >= 0 && stack_level < tool->Results.Size) - if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2) - tool->StackLevel++; - stack_level = tool->StackLevel; + if (query->Step >= 0 && query->Step < query->Results.Size) + if (query->Results[query->Step].QuerySuccess || query->Results[query->Step].QueryFrameCount > 2) + query->Step++; // Update status and hook - tool->ResultsComplete = (stack_level == tool->Results.Size); - if (stack_level == -1) + query->Complete = (query->Step == query->Results.Size); + if (query->Step == -1) { - g.DebugHookIdInfoId = query_main_id; - tool->QueryHookActive = true; + query->Active = true; + return id; } - else if (stack_level >= 0 && stack_level < tool->Results.Size) + else if (query->Step >= 0 && query->Step < query->Results.Size) { - g.DebugHookIdInfoId = tool->Results[stack_level].ID; - tool->Results[stack_level].QueryFrameCount++; - tool->QueryHookActive = true; + query->Results[query->Step].QueryFrameCount++; + query->Active = true; + return query->Results[query->Step].ID; } + return 0; +} + +// [DEBUG] ID Stack Tool: update query. Called by NewFrame() +void ImGui::UpdateDebugToolItemPathQuery() +{ + ImGuiContext& g = *GImGui; + ImGuiID id = 0; + if (g.DebugIDStackTool.LastActiveFrame + 1 == g.FrameCount) + id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId; + g.DebugHookIdInfoId = DebugItemPathQuery_UpdateAndGetHookId(&g.DebugItemPathQuery, id); } // [DEBUG] ID Stack tool: hooks called by GetID() family functions void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end) { ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - ImGuiIDStackTool* tool = &g.DebugIDStackTool; - if (tool->QueryHookActive == false) + ImGuiDebugItemPathQuery* query = &g.DebugItemPathQuery; + if (query->Active == false) { IM_ASSERT(id == 0); return; } + ImGuiWindow* window = g.CurrentWindow; - // Step 0: stack query + // Step -1: stack query // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget. - if (tool->StackLevel == -1) + if (query->Step == -1) { - IM_ASSERT(tool->Results.Size == 0); - tool->StackLevel++; - tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo()); + IM_ASSERT(query->Results.Size == 0); + query->Step++; + query->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo()); for (int n = 0; n < window->IDStack.Size + 1; n++) - tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id; + query->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id; return; } - // Step 1+: query for individual level - IM_ASSERT(tool->StackLevel >= 0); - if (tool->StackLevel != window->IDStack.Size) + // Step 0+: query for individual level + IM_ASSERT(query->Step >= 0); + if (query->Step != window->IDStack.Size) return; - ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel]; + ImGuiStackLevelInfo* info = &query->Results[query->Step]; IM_ASSERT(info->ID == id && info->QueryFrameCount > 0); if (info->DescOffset == -1) @@ -17889,23 +17890,23 @@ void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* dat default: IM_ASSERT(0); } - info->DescOffset = tool->ResultPathsBuf.size(); - tool->ResultPathsBuf.append(result, result_end + 1); // Include zero terminator + info->DescOffset = query->ResultsDescBuf.size(); + query->ResultsDescBuf.append(result, result_end + 1); // Include zero terminator } info->QuerySuccess = true; if (info->DataType == -1) info->DataType = (ImS8)data_type; } -static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size) +static int DebugItemPathQuery_FormatLevelInfo(ImGuiDebugItemPathQuery* query, int n, bool format_for_ui, char* buf, size_t buf_size) { - ImGuiStackLevelInfo* info = &tool->Results[n]; + ImGuiStackLevelInfo* info = &query->Results[n]; ImGuiWindow* window = (info->DescOffset == -1 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL; if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked) return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", ImHashSkipUncontributingPrefix(window->Name)); if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) - return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", ImHashSkipUncontributingPrefix(&tool->ResultPathsBuf.Buf[info->DescOffset])); - if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. + return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", ImHashSkipUncontributingPrefix(&query->ResultsDescBuf.Buf[info->DescOffset])); + if (query->Step < query->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. return (*buf = 0); #ifdef IMGUI_ENABLE_TEST_ENGINE if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo() @@ -17914,14 +17915,14 @@ static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_f return ImFormatString(buf, buf_size, "???"); } -static const char* StackToolGetResultAsPath(ImGuiIDStackTool* tool, bool hex_encode_non_ascii_chars) +static const char* DebugItemPathQuery_GetResultAsPath(ImGuiDebugItemPathQuery* query, bool hex_encode_non_ascii_chars) { - ImGuiTextBuffer* buf = &tool->ResultFullPathBuf; + ImGuiTextBuffer* buf = &query->ResultPathBuf; buf->resize(0); - for (int stack_n = 0; stack_n < tool->Results.Size; stack_n++) + for (int stack_n = 0; stack_n < query->Results.Size; stack_n++) { char level_desc[256]; - StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); + DebugItemPathQuery_FormatLevelInfo(query, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); buf->append(stack_n == 0 ? "//" : "/"); for (const char* p = level_desc; *p != 0; ) { @@ -17951,10 +17952,11 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) return; } - // Display hovered/active status + ImGuiDebugItemPathQuery* query = &g.DebugItemPathQuery; ImGuiIDStackTool* tool = &g.DebugIDStackTool; - const char* result_path = StackToolGetResultAsPath(tool, tool->OptHexEncodeNonAsciiChars); - Text("0x%08X", tool->QueryMainId); + 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."); @@ -17973,32 +17975,31 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) SetClipboardText(result_path); } - Text("- Path \"%s\"", tool->ResultsComplete ? result_path : ""); + Text("- Path \"%s\"", query->Complete ? result_path : ""); #ifdef IMGUI_ENABLE_TEST_ENGINE - Text("- Label \"%s\"", tool->QueryMainId ? ImGuiTestEngine_FindItemDebugLabel(&g, tool->QueryMainId) : ""); + Text("- Label \"%s\"", query->MainID ? ImGuiTestEngine_FindItemDebugLabel(&g, query->MainID) : ""); #endif Separator(); // Display decorated stack - tool->LastActiveFrame = g.FrameCount; - if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders)) + if (query->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders)) { const float id_width = CalcTextSize("0xDDDDDDDD").x; TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width); TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch); TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width); TableHeadersRow(); - for (int n = 0; n < tool->Results.Size; n++) + for (int n = 0; n < query->Results.Size; n++) { - ImGuiStackLevelInfo* info = &tool->Results[n]; + ImGuiStackLevelInfo* info = &query->Results[n]; TableNextColumn(); - Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0); + Text("0x%08X", (n > 0) ? query->Results[n - 1].ID : 0); TableNextColumn(); - StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size); + DebugItemPathQuery_FormatLevelInfo(query, n, true, g.TempBuffer.Data, g.TempBuffer.Size); TextUnformatted(g.TempBuffer.Data); TableNextColumn(); Text("0x%08X", info->ID); - if (n == tool->Results.Size - 1) + if (n == query->Results.Size - 1) TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header)); } EndTable(); diff --git a/imgui_internal.h b/imgui_internal.h index fcd02f280..f16fa73df 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2120,28 +2120,34 @@ struct ImGuiMetricsConfig struct ImGuiStackLevelInfo { ImGuiID ID; - ImS8 QueryFrameCount; // >= 1: Query in progress - bool QuerySuccess; // Obtained result from DebugHookIdInfo() + ImS8 QueryFrameCount; // >= 1: Sub-query in progress + bool QuerySuccess; // Sub-query obtained result from DebugHookIdInfo() ImS8 DataType; // ImGuiDataType - int DescOffset; // -1 or offset into parent's ResultPathsBuf + int DescOffset; // -1 or offset into parent's ResultsPathsBuf ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); DataType = -1; DescOffset = -1; } }; +struct ImGuiDebugItemPathQuery +{ + ImGuiID MainID; // ID to query details for. + bool Active; // Used to disambiguate the case when ID == 0 and e.g. some code calls PushOverrideID(0). + bool Complete; // All sub-queries are finished (some may have failed). + ImS8 Step; // -1: query stack + init Results, >= 0: filling individual stack level. + ImVector Results; + ImGuiTextBuffer ResultsDescBuf; + ImGuiTextBuffer ResultPathBuf; + + ImGuiDebugItemPathQuery() { memset(this, 0, sizeof(*this)); } +}; + // State for ID Stack tool queries struct ImGuiIDStackTool { - int LastActiveFrame; - int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level. - ImGuiID QueryMainId; // ID to query details for. - ImVector Results; - bool ResultsComplete; // All sub-query have succeeeded, result is complete. - bool QueryHookActive; // Used to disambiguate the case where DebugHookIdInfoId == 0 which is valid. bool OptHexEncodeNonAsciiChars; bool OptCopyToClipboardOnCtrlC; + int LastActiveFrame; float CopyToClipboardLastTime; - ImGuiTextBuffer ResultPathsBuf; - ImGuiTextBuffer ResultFullPathBuf; ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); LastActiveFrame = -1; OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; } }; @@ -2529,6 +2535,7 @@ struct ImGuiContext float DebugFlashStyleColorTime; ImVec4 DebugFlashStyleColorBackup; ImGuiMetricsConfig DebugMetricsConfig; + ImGuiDebugItemPathQuery DebugItemPathQuery; ImGuiIDStackTool DebugIDStackTool; ImGuiDebugAllocInfo DebugAllocInfo; #if defined(IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS) From 9e15ebb402c1f08948a4c9e45c15c870fcc98a30 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 13:37:20 +0100 Subject: [PATCH 1494/2359] Backends: GLFW: fixed last `ImGui_ImplGlfw_Shutdown()` call not immediately clearing the context map. (#9075, #8676, #8239, #8069) Amend/fix f633a6058 --- backends/imgui_impl_glfw.cpp | 2 +- docs/CHANGELOG.txt | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 5f7bcd126..9ec9ccbf9 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -166,7 +166,7 @@ struct ImGui_ImplGlfw_WindowToContext { GLFWwindow* Window; ImGuiContext* Context; }; static ImVector g_ContextMap; static void ImGui_ImplGlfw_ContextMap_Add(GLFWwindow* window, ImGuiContext* ctx) { g_ContextMap.push_back(ImGui_ImplGlfw_WindowToContext{ window, ctx }); } -static void ImGui_ImplGlfw_ContextMap_Remove(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) { g_ContextMap.erase_unsorted(&entry); return; } } +static void ImGui_ImplGlfw_ContextMap_Remove(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) { g_ContextMap.erase_unsorted(&entry); if (g_ContextMap.empty()) g_ContextMap.clear(); return; } } static ImGuiContext* ImGui_ImplGlfw_ContextMap_Get(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) return entry.Context; return nullptr; } enum GlfwClientApi diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 82af01649..7d65a172d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -125,6 +125,8 @@ Other Changes: are not available. (#9024, #8969, #8921, #8920) [@jagot] - GLFW: lower minimum requirement from GLFW 3.1 to GLFW 3.0. Though a recent version e.g GLFW 3.4 is highly recommended! (#9055) [@Clownacy] + - GLFW: fixed last `ImGui_ImplGlfw_Shutdown()` not immediately clearing the context + map, which would be detected by leak trackers. (#9075, #8676, #8239, #8069) [@erincatto] - SDL3: fixed Platform_OpenInShellFn() return value (the return value was unused in core but might be used by a direct caller). (#9027) [@achabense] - SDL3: fixed an issue with missing characters events when an already active text From b885382a632d5eb18992e3d006d33f7baebb22ae Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 15:05:43 +0100 Subject: [PATCH 1495/2359] Backends: Null: added imgui_impl_null platform/renderer backend. --- backends/imgui_impl_null.cpp | 97 ++++++++++ backends/imgui_impl_null.h | 34 ++++ docs/BACKENDS.md | 1 + docs/CHANGELOG.txt | 2 + docs/EXAMPLES.md | 4 +- examples/README.txt | 7 +- examples/example_null/build_win32.bat | 2 +- examples/example_null/example_null.vcxproj | 173 ++++++++++++++++++ .../example_null/example_null.vcxproj.filters | 57 ++++++ examples/example_null/main.cpp | 15 +- examples/imgui_examples.sln | 10 + imgui.h | 2 +- 12 files changed, 392 insertions(+), 12 deletions(-) create mode 100644 backends/imgui_impl_null.cpp create mode 100644 backends/imgui_impl_null.h create mode 100644 examples/example_null/example_null.vcxproj create mode 100644 examples/example_null/example_null.vcxproj.filters diff --git a/backends/imgui_impl_null.cpp b/backends/imgui_impl_null.cpp new file mode 100644 index 000000000..eb99f5313 --- /dev/null +++ b/backends/imgui_impl_null.cpp @@ -0,0 +1,97 @@ +// dear imgui: Null Platform+Renderer Backends +// This is designed if you need to use a blind Dear Imgui context with no input and no output. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2025-11-17: Initial version. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_null.h" + +bool ImGui_ImplNull_Init() +{ + ImGui_ImplNullPlatform_Init(); + ImGui_ImplNullRender_Init(); + return true; +} + +void ImGui_ImplNull_Shutdown() +{ + ImGui_ImplNullRender_Shutdown(); + ImGui_ImplNullPlatform_Shutdown(); +} + +void ImGui_ImplNull_NewFrame() +{ + ImGui_ImplNullPlatform_NewFrame(); + ImGui_ImplNullRender_NewFrame(); +} + +bool ImGui_ImplNullPlatform_Init() +{ + ImGuiIO& io = ImGui::GetIO(); + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; + return true; +} + +void ImGui_ImplNullPlatform_Shutdown() +{ + ImGuiIO& io = ImGui::GetIO(); + io.BackendFlags &= ~ImGuiBackendFlags_HasMouseCursors; +} + +void ImGui_ImplNullPlatform_NewFrame() +{ + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize = ImVec2(1920, 1080); + io.DeltaTime = 1.0f / 60.0f; +} + +bool ImGui_ImplNullRender_Init() +{ + ImGuiIO& io = ImGui::GetIO(); + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; + return true; +} + +void ImGui_ImplNullRender_Shutdown() +{ + ImGuiIO& io = ImGui::GetIO(); + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasTextures; +} + +void ImGui_ImplNullRender_NewFrame() +{ +} + +void ImGui_ImplNullRender_UpdateTexture(ImTextureData* tex) +{ + if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantDestroy) + tex->SetStatus(ImTextureStatus_OK); + if (tex->Status == ImTextureStatus_WantDestroy) + { + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); + } +} + +void ImGui_ImplNullRender_RenderDrawData(ImDrawData* draw_data) +{ + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplNullRender_UpdateTexture(tex); +} + +#endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_null.h b/backends/imgui_impl_null.h new file mode 100644 index 000000000..b5cfb5a2c --- /dev/null +++ b/backends/imgui_impl_null.h @@ -0,0 +1,34 @@ +// dear imgui: Null Platform+Renderer Backends +// This is designed if you need to use a blind Dear Imgui context with no input and no output. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! + +// Null = NullPlatform + NullRender +IMGUI_IMPL_API bool ImGui_ImplNull_Init(); +IMGUI_IMPL_API void ImGui_ImplNull_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplNull_NewFrame(); + +// Null platform only (single screen, fixed timestep, no inputs) +IMGUI_IMPL_API bool ImGui_ImplNullPlatform_Init(); +IMGUI_IMPL_API void ImGui_ImplNullPlatform_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplNullPlatform_NewFrame(); + +// Null renderer only (no output) +IMGUI_IMPL_API bool ImGui_ImplNullRender_Init(); +IMGUI_IMPL_API void ImGui_ImplNullRender_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplNullRender_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplNullRender_RenderDrawData(ImDrawData* draw_data); + +#endif // #ifndef IMGUI_DISABLE diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 629f8d83f..62acb1e21 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -100,6 +100,7 @@ List of Renderer Backends: List of high-level Frameworks Backends (combining Platform + Renderer): imgui_impl_allegro5.cpp + imgui_impl_null.cpp Emscripten is also supported! The SDL2+GL, SDL3+GL, GLFW+GL and GLFW+WebGPU examples are all ready to build and run with Emscripten. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7d65a172d..e0bf08e69 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -121,6 +121,8 @@ Other Changes: - Metrics: fixed table and columns rect highlight from display when debug/metrics window is not in the same viewport as the table. - Backends: + - Null: added imgui_impl_null platform/renderer backend. + This is designed if you need to run e.g. context with no input or no ouput. - GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) [@jagot] - GLFW: lower minimum requirement from GLFW 3.1 to GLFW 3.0. Though diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index 45ad97309..676d745bc 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -109,9 +109,11 @@ Note that GLUT/FreeGLUT is largely obsolete software, prefer using GLFW or SDL. [example_null/](https://github.com/ocornut/imgui/blob/master/examples/example_null/)
Null example, compile and link imgui, create context, run headless with no inputs and no graphics output.
-= main.cpp
+= main.cpp + imgui_impl_null.cpp
This is used to quickly test compilation of core imgui files in as many setups as possible. Because this application doesn't create a window nor a graphic context, there's no graphics output. +Please note that imgui_impl_null itself is a rather empty backend. We provide it for consistency but +it is similarly easy to create a skeleton application without the null backend. [example_sdl2_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_directx11/)
SDL2 + DirectX11 example, Windows only.
diff --git a/examples/README.txt b/examples/README.txt index 6db2f3c48..1a711e7b8 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,9 +1,12 @@ -See BACKENDS and EXAMPLES files in the docs/ folder, or on the web at: https://github.com/ocornut/imgui/tree/master/docs +New to Dear ImGui? +- Check out the Getting Started guide: https://github.com/ocornut/imgui/wiki/Getting-Started +- About Backends: docs/BACKENDS.md file, or on the web: https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md +- About Examples: docs/EXAMPLES.md file, or on the web: https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md Backends = Helper code to facilitate integration with platforms/graphics api (used by Examples + should be used by your app). Examples = Standalone applications showcasing integration with platforms/graphics api. -Some Examples have extra README files in their respective directory, please check them too! +A few Examples have extra README files in their respective directory, please check them too! Once Dear ImGui is running (in either examples or your own application/game/engine), run and refer to ImGui::ShowDemoWindow() in imgui_demo.cpp for the end-user API. diff --git a/examples/example_null/build_win32.bat b/examples/example_null/build_win32.bat index be81d8093..3a07d8f8d 100644 --- a/examples/example_null/build_win32.bat +++ b/examples/example_null/build_win32.bat @@ -1,3 +1,3 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /utf-8 /I ..\.. %* *.cpp ..\..\*.cpp /FeDebug/example_null.exe /FoDebug/ /link gdi32.lib shell32.lib imm32.lib +cl /nologo /Zi /MD /utf-8 /I ..\.. %* *.cpp ..\..\*.cpp ..\..\backends\imgui_impl_null.cpp /FeDebug/example_null.exe /FoDebug/ /link gdi32.lib shell32.lib imm32.lib diff --git a/examples/example_null/example_null.vcxproj b/examples/example_null/example_null.vcxproj new file mode 100644 index 000000000..7d0d59279 --- /dev/null +++ b/examples/example_null/example_null.vcxproj @@ -0,0 +1,173 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D} + example_win32_directx11 + + + + Application + true + Unicode + v140 + + + Application + true + Unicode + v140 + + + Application + false + true + Unicode + v140 + + + Application + false + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + + Level4 + Disabled + ..\..;..\..\backends;%(AdditionalIncludeDirectories); + /utf-8 %(AdditionalOptions) + + + true + d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + Console + + + + + Level4 + Disabled + ..\..;..\..\backends;%(AdditionalIncludeDirectories); + /utf-8 %(AdditionalOptions) + + + true + d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + Console + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%(AdditionalIncludeDirectories); + false + /utf-8 %(AdditionalOptions) + + + true + true + true + d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + Console + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%(AdditionalIncludeDirectories); + false + /utf-8 %(AdditionalOptions) + + + true + true + true + d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + Console + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/example_null/example_null.vcxproj.filters b/examples/example_null/example_null.vcxproj.filters new file mode 100644 index 000000000..f5dd02f2d --- /dev/null +++ b/examples/example_null/example_null.vcxproj.filters @@ -0,0 +1,57 @@ + + + + + {0587d7a3-f2ce-4d56-b84f-a0005d3bfce6} + + + {08e36723-ce4f-4cff-9662-c40801cf1acf} + + + + + imgui + + + imgui + + + imgui + + + sources + + + + + imgui + + + sources + + + imgui + + + imgui + + + imgui + + + imgui + + + sources + + + + + + imgui + + + imgui + + + diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index 460f33cab..5e94a6fb6 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -3,24 +3,23 @@ // This is useful to test building, but you cannot interact with anything here! #include "imgui.h" #include +#include "imgui_impl_null.h" int main(int, char**) { IMGUI_CHECKVERSION(); + ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); - // Build atlas - //unsigned char* tex_pixels = nullptr; - //int tex_w, tex_h; - //io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_w, &tex_h); - io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; + ImGui_ImplNullPlatform_Init(); + ImGui_ImplNullRender_Init(); for (int n = 0; n < 20; n++) { printf("NewFrame() %d\n", n); - io.DisplaySize = ImVec2(1920, 1080); - io.DeltaTime = 1.0f / 60.0f; + ImGui_ImplNullPlatform_NewFrame(); + ImGui_ImplNullRender_NewFrame(); ImGui::NewFrame(); static float f = 0.0f; @@ -33,6 +32,8 @@ int main(int, char**) } printf("DestroyContext()\n"); + ImGui_ImplNullRender_Shutdown(); + ImGui_ImplNullPlatform_Shutdown(); ImGui::DestroyContext(); return 0; } diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index 8ad1a2566..96087aeac 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -41,6 +41,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_sdlgpu3", "exa EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl3_directx11", "example_sdl3_directx11\example_sdl3_directx11.vcxproj", "{009DAC16-1A9C-47BE-9770-A30A046E8090}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_null", "example_null\example_null.vcxproj", "{1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -201,6 +203,14 @@ Global {009DAC16-1A9C-47BE-9770-A30A046E8090}.Release|Win32.Build.0 = Release|Win32 {009DAC16-1A9C-47BE-9770-A30A046E8090}.Release|x64.ActiveCfg = Release|x64 {009DAC16-1A9C-47BE-9770-A30A046E8090}.Release|x64.Build.0 = Release|x64 + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}.Debug|Win32.ActiveCfg = Debug|Win32 + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}.Debug|Win32.Build.0 = Debug|Win32 + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}.Debug|x64.ActiveCfg = Debug|x64 + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}.Debug|x64.Build.0 = Debug|x64 + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}.Release|Win32.ActiveCfg = Release|Win32 + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}.Release|Win32.Build.0 = Release|Win32 + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}.Release|x64.ActiveCfg = Release|x64 + {1A0BF63C-18EF-4BAE-A8DA-055481B11F5D}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/imgui.h b/imgui.h index a52ec5764..e5e4dda91 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.5 WIP" -#define IMGUI_VERSION_NUM 19245 +#define IMGUI_VERSION_NUM 19246 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From eb19a77848a0e0a581441df47a2e0ec1ab0bebf2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 15:51:39 +0100 Subject: [PATCH 1496/2359] Examples: fix example_null Makefile. Amend b885382 --- docs/TODO.txt | 2 +- examples/example_null/Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 111852b43..6107e5dc0 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -308,7 +308,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - examples: window minimize, maximize (#583) - examples: provide a zero frame-rate/idle example. - - examples: dx11/dx12: try to use new swapchain blit models (#2970) + - examples: dx11/dx12: try to use new swapchain blit models (#2970, #9031) - backends: report it better when not able to create texture? - backends: glfw: could go idle when minimized? if (glfwGetWindowAttrib(window, GLFW_ICONIFIED)) { glfwWaitEvents(); continue; } // issue: DeltaTime will be super high on resume, perhaps provide a way to let impl know (#440) - backends: opengl: rename imgui_impl_opengl2 to impl_opengl_legacy and imgui_impl_opengl3 to imgui_impl_opengl? (#1900) diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index 4a67cecd8..9cd0d0635 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -17,7 +17,7 @@ SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS += -std=c++11 -I$(IMGUI_DIR) +CXXFLAGS += -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = From 7e919a543c350eb704f60dcddb7e9bc3cb88c3d3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 15:58:12 +0100 Subject: [PATCH 1497/2359] Examples: fix example_null Makefile. Amend b885382,eb19a77 --- examples/example_null/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index 9cd0d0635..91c8dd78c 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -14,6 +14,7 @@ EXE = example_null IMGUI_DIR = ../.. SOURCES = main.cpp SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_null.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) From d99baf332c5c1332c5c0edfe43fcc21875053ea1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 16:11:05 +0100 Subject: [PATCH 1498/2359] CI: fixes for example_null building. --- .github/workflows/build.yml | 28 +++++++++++++++++++++++----- docs/CHANGELOG.txt | 2 ++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 92d41dac1..97bd3c94e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -61,7 +61,7 @@ jobs: echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp g++ -I. -Wall -Wformat -shared -o libimgui.dll -Wl,--out-implib,libimgui.a example_single_file.cpp -limm32 - g++ -I. -Wall -Wformat -DIMGUI_API='__declspec(dllimport)' -o example_null.exe examples/example_null/main.cpp -L. -limgui + g++ -I. -Ibackends -Wall -Wformat -DIMGUI_API='__declspec(dllimport)' -o example_null.exe examples/example_null/main.cpp backends/imgui_impl_null.cpp -L. -limgui rm -f example_null.exe libimgui.* example_single_file.* - name: Build example_null (extra warnings, msvc 64-bit) @@ -78,10 +78,11 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "examples/backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 + g++ -I. -Ibackends -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 - name: Build example_null (with IMGUI_DISABLE_WIN32_FUNCTIONS) shell: bash @@ -91,10 +92,11 @@ jobs: #define IMGUI_DISABLE_WIN32_FUNCTIONS #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "examples/backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 + g++ -I. -Ibackends -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 - name: Build example_null (as DLL) shell: cmd @@ -105,8 +107,8 @@ jobs: echo #define IMGUI_IMPLEMENTATION >> example_single_file.cpp echo #include "misc/single_file/imgui_single_file.h" >> example_single_file.cpp - cl.exe /D_USRDLL /D_WINDLL /I. example_single_file.cpp /LD /FeImGui.dll /link - cl.exe /DIMGUI_API=__declspec(dllimport) /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp + cl.exe /D_USRDLL /D_WINDLL /I. /Ibackends example_single_file.cpp /LD /FeImGui.dll /link + cl.exe /DIMGUI_API=__declspec(dllimport) /I. ImGui.lib /Feexample_null.exe backends/imgui_impl_null.cpp examples/example_null/main.cpp # Win64 examples are more frequently compilted than the Win32 examples. # More of the Win32 examples requires 'workflow_run' to reduce waste. @@ -294,6 +296,7 @@ jobs: #define IM_ASSERT(x) #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -310,6 +313,7 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -322,6 +326,7 @@ jobs: #define IMGUI_USE_WCHAR32 #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -335,6 +340,7 @@ jobs: #define ImDrawIdx unsigned int #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -347,6 +353,7 @@ jobs: #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -359,6 +366,7 @@ jobs: #define IMGUI_DISABLE_OBSOLETE_KEYIO #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -371,6 +379,7 @@ jobs: #define IMGUI_DISABLE_OBSOLETE_KEYIO #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -384,6 +393,7 @@ jobs: #define IMGUI_DISABLE_DEBUG_TOOLS #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -396,6 +406,7 @@ jobs: #define IMGUI_DISABLE_FILE_FUNCTIONS #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -408,6 +419,7 @@ jobs: #define IMGUI_USE_BGRA_PACKED_COLOR #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -428,6 +440,7 @@ jobs: operator MyVec4() const { return MyVec4(x, y, z, w); } #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -440,6 +453,7 @@ jobs: #define IMGUI_IMPLEMENTATION #define IMGUI_DISABLE_DEMO_WINDOWS #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -452,6 +466,7 @@ jobs: #define IMGUI_IMPLEMENTATION #define IMGUI_DISABLE_DEMO_WINDOWS #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -492,6 +507,7 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -503,6 +519,7 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF @@ -514,6 +531,7 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" + #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e0bf08e69..3ad4d4aa7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -151,6 +151,8 @@ Other Changes: - Win32: Revert 1.92.4 change of comparing dwPacketNumber, which prevents refreshing accurate gamepad info after focus-out + io.ClearInputKeys(). (#8556) - Examples: + - Null: update examples_null to use imgui_impl_null (which is a bit overengineering + but somehow consistent). - GLFW+WebGPU: update example for latest specs, to work on Emscripten 4.0.10+, latest Dawn-Native and WGPU-Native. (#8381, #8567, #8191, #7435) [@brutpitt] - GLFW+WebGPU: removed unnecessary ImGui_ImplWGPU_InvalidateDeviceObjects() call From 0cf5b93a0a29fef0a367ca72fae818e7e5b8f70b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 16:18:12 +0100 Subject: [PATCH 1499/2359] CI, Backends: fixes for example_null building. Add consistent IMGUI_IMPL_API in backend. --- .github/workflows/build.yml | 34 +++++++++++++++++----------------- backends/imgui_impl_null.cpp | 20 ++++++++++---------- backends/imgui_impl_win32.cpp | 12 ++++++------ 3 files changed, 33 insertions(+), 33 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 97bd3c94e..b1403d394 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -300,7 +300,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -Wextra -Werror -Wno-zero-as-null-pointer-constant -Wno-double-promotion -Wno-variadic-macros -Wno-empty-body -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -Wextra -Werror -Wno-zero-as-null-pointer-constant -Wno-double-promotion -Wno-variadic-macros -Wno-empty-body -o example_single_file example_single_file.cpp - name: Build example_null (freetype) run: | @@ -317,7 +317,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with ImWchar32) run: | @@ -330,7 +330,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with large ImDrawIdx + pointer ImTextureID) run: | @@ -344,7 +344,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_OBSOLETE_FUNCTIONS) run: | @@ -357,7 +357,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_OBSOLETE_KEYIO) run: | @@ -370,7 +370,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with C++20) run: | @@ -383,7 +383,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_DEMO_WINDOWS and IMGUI_DISABLE_DEBUG_TOOLS) run: | @@ -397,7 +397,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_FILE_FUNCTIONS) run: | @@ -410,7 +410,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_USE_BGRA_PACKED_COLOR) run: | @@ -423,7 +423,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IM_VEC2_CLASS_EXTRA and IM_VEC4_CLASS_EXTRA) run: | @@ -444,7 +444,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (C++26, Clang) run: | @@ -457,7 +457,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - clang++ -I. -std=c++26 -Wall -Wformat -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + clang++ -I. -Ibackends -std=c++26 -Wall -Wformat -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - name: Build example_null (without c++ runtime, Clang) run: | @@ -470,7 +470,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - clang++ -I. -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + clang++ -I. -Ibackends -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 @@ -487,7 +487,7 @@ jobs: run: make -C examples/example_sdl2_opengl3 - name: Build with IMGUI_IMPL_VULKAN_NO_PROTOTYPES - run: g++ -c -I. -std=c++11 -DIMGUI_IMPL_VULKAN_NO_PROTOTYPES=1 backends/imgui_impl_vulkan.cpp + run: g++ -c -I. -Ibackends -std=c++11 -DIMGUI_IMPL_VULKAN_NO_PROTOTYPES=1 backends/imgui_impl_vulkan.cpp MacOS: runs-on: macos-latest @@ -511,7 +511,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - clang++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + clang++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (single file build, c++20) run: | @@ -523,7 +523,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - clang++ -I. -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp + clang++ -I. -Ibackends -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (without c++ runtime) run: | @@ -535,7 +535,7 @@ jobs: #include "examples/example_null/main.cpp" EOF - clang++ -I. -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + clang++ -I. -Ibackends -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 diff --git a/backends/imgui_impl_null.cpp b/backends/imgui_impl_null.cpp index eb99f5313..9503b1789 100644 --- a/backends/imgui_impl_null.cpp +++ b/backends/imgui_impl_null.cpp @@ -17,46 +17,46 @@ #ifndef IMGUI_DISABLE #include "imgui_impl_null.h" -bool ImGui_ImplNull_Init() +IMGUI_IMPL_API bool ImGui_ImplNull_Init() { ImGui_ImplNullPlatform_Init(); ImGui_ImplNullRender_Init(); return true; } -void ImGui_ImplNull_Shutdown() +IMGUI_IMPL_API void ImGui_ImplNull_Shutdown() { ImGui_ImplNullRender_Shutdown(); ImGui_ImplNullPlatform_Shutdown(); } -void ImGui_ImplNull_NewFrame() +IMGUI_IMPL_API void ImGui_ImplNull_NewFrame() { ImGui_ImplNullPlatform_NewFrame(); ImGui_ImplNullRender_NewFrame(); } -bool ImGui_ImplNullPlatform_Init() +IMGUI_IMPL_API bool ImGui_ImplNullPlatform_Init() { ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; return true; } -void ImGui_ImplNullPlatform_Shutdown() +IMGUI_IMPL_API void ImGui_ImplNullPlatform_Shutdown() { ImGuiIO& io = ImGui::GetIO(); io.BackendFlags &= ~ImGuiBackendFlags_HasMouseCursors; } -void ImGui_ImplNullPlatform_NewFrame() +IMGUI_IMPL_API void ImGui_ImplNullPlatform_NewFrame() { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(1920, 1080); io.DeltaTime = 1.0f / 60.0f; } -bool ImGui_ImplNullRender_Init() +IMGUI_IMPL_API bool ImGui_ImplNullRender_Init() { ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; @@ -64,14 +64,14 @@ bool ImGui_ImplNullRender_Init() return true; } -void ImGui_ImplNullRender_Shutdown() +IMGUI_IMPL_API void ImGui_ImplNullRender_Shutdown() { ImGuiIO& io = ImGui::GetIO(); io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasTextures; } -void ImGui_ImplNullRender_NewFrame() +IMGUI_IMPL_API void ImGui_ImplNullRender_NewFrame() { } @@ -86,7 +86,7 @@ void ImGui_ImplNullRender_UpdateTexture(ImTextureData* tex) } } -void ImGui_ImplNullRender_RenderDrawData(ImDrawData* draw_data) +IMGUI_IMPL_API void ImGui_ImplNullRender_RenderDrawData(ImDrawData* draw_data) { if (draw_data->Textures != nullptr) for (ImTextureData* tex : *draw_data->Textures) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index dc7e66f02..2973f6178 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -220,7 +220,7 @@ IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd) return ImGui_ImplWin32_InitEx(hwnd, true); } -void ImGui_ImplWin32_Shutdown() +IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown() { ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); @@ -392,7 +392,7 @@ static void ImGui_ImplWin32_UpdateGamepads(ImGuiIO& io) #endif } -void ImGui_ImplWin32_NewFrame() +IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame() { ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized? Did you call ImGui_ImplWin32_Init()?"); @@ -861,7 +861,7 @@ typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update) // Helper function to enable DPI awareness without setting up a manifest -void ImGui_ImplWin32_EnableDpiAwareness() +IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness() { if (_IsWindows10OrGreater()) { @@ -890,7 +890,7 @@ void ImGui_ImplWin32_EnableDpiAwareness() #pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32' #endif -float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) +IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) { UINT xdpi = 96, ydpi = 96; if (_IsWindows8Point1OrGreater()) @@ -916,7 +916,7 @@ float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) return xdpi / 96.0f; } -float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) +IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) { HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST); return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); @@ -933,7 +933,7 @@ float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) // [experimental] // Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c // (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW) -void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) +IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) { if (!_IsWindowsVistaOrGreater()) return; From cfb48969afb3650e40cd5714517c555668894787 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 16:36:54 +0100 Subject: [PATCH 1500/2359] Examples: CI: backtrack and make example_null embed backend: simpler for all sorts of quick build scripts. --- .github/workflows/build.yml | 62 +++++++------------ backends/imgui_impl_win32.cpp | 12 ++-- examples/example_null/Makefile | 3 +- examples/example_null/build_win32.bat | 2 +- examples/example_null/example_null.vcxproj | 1 - .../example_null/example_null.vcxproj.filters | 5 +- examples/example_null/main.cpp | 6 +- 7 files changed, 36 insertions(+), 55 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b1403d394..92d41dac1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -61,7 +61,7 @@ jobs: echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp g++ -I. -Wall -Wformat -shared -o libimgui.dll -Wl,--out-implib,libimgui.a example_single_file.cpp -limm32 - g++ -I. -Ibackends -Wall -Wformat -DIMGUI_API='__declspec(dllimport)' -o example_null.exe examples/example_null/main.cpp backends/imgui_impl_null.cpp -L. -limgui + g++ -I. -Wall -Wformat -DIMGUI_API='__declspec(dllimport)' -o example_null.exe examples/example_null/main.cpp -L. -limgui rm -f example_null.exe libimgui.* example_single_file.* - name: Build example_null (extra warnings, msvc 64-bit) @@ -78,11 +78,10 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "examples/backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 + g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 - name: Build example_null (with IMGUI_DISABLE_WIN32_FUNCTIONS) shell: bash @@ -92,11 +91,10 @@ jobs: #define IMGUI_DISABLE_WIN32_FUNCTIONS #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "examples/backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 + g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 - name: Build example_null (as DLL) shell: cmd @@ -107,8 +105,8 @@ jobs: echo #define IMGUI_IMPLEMENTATION >> example_single_file.cpp echo #include "misc/single_file/imgui_single_file.h" >> example_single_file.cpp - cl.exe /D_USRDLL /D_WINDLL /I. /Ibackends example_single_file.cpp /LD /FeImGui.dll /link - cl.exe /DIMGUI_API=__declspec(dllimport) /I. ImGui.lib /Feexample_null.exe backends/imgui_impl_null.cpp examples/example_null/main.cpp + cl.exe /D_USRDLL /D_WINDLL /I. example_single_file.cpp /LD /FeImGui.dll /link + cl.exe /DIMGUI_API=__declspec(dllimport) /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp # Win64 examples are more frequently compilted than the Win32 examples. # More of the Win32 examples requires 'workflow_run' to reduce waste. @@ -296,11 +294,10 @@ jobs: #define IM_ASSERT(x) #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -Wextra -Werror -Wno-zero-as-null-pointer-constant -Wno-double-promotion -Wno-variadic-macros -Wno-empty-body -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -Wextra -Werror -Wno-zero-as-null-pointer-constant -Wno-double-promotion -Wno-variadic-macros -Wno-empty-body -o example_single_file example_single_file.cpp - name: Build example_null (freetype) run: | @@ -313,11 +310,10 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with ImWchar32) run: | @@ -326,11 +322,10 @@ jobs: #define IMGUI_USE_WCHAR32 #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with large ImDrawIdx + pointer ImTextureID) run: | @@ -340,11 +335,10 @@ jobs: #define ImDrawIdx unsigned int #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_OBSOLETE_FUNCTIONS) run: | @@ -353,11 +347,10 @@ jobs: #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_OBSOLETE_KEYIO) run: | @@ -366,11 +359,10 @@ jobs: #define IMGUI_DISABLE_OBSOLETE_KEYIO #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with C++20) run: | @@ -379,11 +371,10 @@ jobs: #define IMGUI_DISABLE_OBSOLETE_KEYIO #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_DEMO_WINDOWS and IMGUI_DISABLE_DEBUG_TOOLS) run: | @@ -393,11 +384,10 @@ jobs: #define IMGUI_DISABLE_DEBUG_TOOLS #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_FILE_FUNCTIONS) run: | @@ -406,11 +396,10 @@ jobs: #define IMGUI_DISABLE_FILE_FUNCTIONS #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_USE_BGRA_PACKED_COLOR) run: | @@ -419,11 +408,10 @@ jobs: #define IMGUI_USE_BGRA_PACKED_COLOR #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IM_VEC2_CLASS_EXTRA and IM_VEC4_CLASS_EXTRA) run: | @@ -440,11 +428,10 @@ jobs: operator MyVec4() const { return MyVec4(x, y, z, w); } #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - g++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (C++26, Clang) run: | @@ -453,11 +440,10 @@ jobs: #define IMGUI_IMPLEMENTATION #define IMGUI_DISABLE_DEMO_WINDOWS #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - clang++ -I. -Ibackends -std=c++26 -Wall -Wformat -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + clang++ -I. -std=c++26 -Wall -Wformat -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - name: Build example_null (without c++ runtime, Clang) run: | @@ -466,11 +452,10 @@ jobs: #define IMGUI_IMPLEMENTATION #define IMGUI_DISABLE_DEMO_WINDOWS #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - clang++ -I. -Ibackends -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + clang++ -I. -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 @@ -487,7 +472,7 @@ jobs: run: make -C examples/example_sdl2_opengl3 - name: Build with IMGUI_IMPL_VULKAN_NO_PROTOTYPES - run: g++ -c -I. -Ibackends -std=c++11 -DIMGUI_IMPL_VULKAN_NO_PROTOTYPES=1 backends/imgui_impl_vulkan.cpp + run: g++ -c -I. -std=c++11 -DIMGUI_IMPL_VULKAN_NO_PROTOTYPES=1 backends/imgui_impl_vulkan.cpp MacOS: runs-on: macos-latest @@ -507,11 +492,10 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - clang++ -I. -Ibackends -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + clang++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (single file build, c++20) run: | @@ -519,11 +503,10 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - clang++ -I. -Ibackends -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp + clang++ -I. -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (without c++ runtime) run: | @@ -531,11 +514,10 @@ jobs: #define IMGUI_IMPLEMENTATION #include "misc/single_file/imgui_single_file.h" - #include "backends/imgui_impl_null.cpp" #include "examples/example_null/main.cpp" EOF - clang++ -I. -Ibackends -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + clang++ -I. -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 2973f6178..dc7e66f02 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -220,7 +220,7 @@ IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd) return ImGui_ImplWin32_InitEx(hwnd, true); } -IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown() +void ImGui_ImplWin32_Shutdown() { ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); @@ -392,7 +392,7 @@ static void ImGui_ImplWin32_UpdateGamepads(ImGuiIO& io) #endif } -IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame() +void ImGui_ImplWin32_NewFrame() { ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized? Did you call ImGui_ImplWin32_Init()?"); @@ -861,7 +861,7 @@ typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update) // Helper function to enable DPI awareness without setting up a manifest -IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness() +void ImGui_ImplWin32_EnableDpiAwareness() { if (_IsWindows10OrGreater()) { @@ -890,7 +890,7 @@ IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness() #pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32' #endif -IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) +float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) { UINT xdpi = 96, ydpi = 96; if (_IsWindows8Point1OrGreater()) @@ -916,7 +916,7 @@ IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) return xdpi / 96.0f; } -IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) +float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) { HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST); return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); @@ -933,7 +933,7 @@ IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) // [experimental] // Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c // (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW) -IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) +void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) { if (!_IsWindowsVistaOrGreater()) return; diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index 91c8dd78c..4a67cecd8 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -14,11 +14,10 @@ EXE = example_null IMGUI_DIR = ../.. SOURCES = main.cpp SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp -SOURCES += $(IMGUI_DIR)/backends/imgui_impl_null.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS += -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS += -std=c++11 -I$(IMGUI_DIR) CXXFLAGS += -g -Wall -Wformat LIBS = diff --git a/examples/example_null/build_win32.bat b/examples/example_null/build_win32.bat index 3a07d8f8d..be81d8093 100644 --- a/examples/example_null/build_win32.bat +++ b/examples/example_null/build_win32.bat @@ -1,3 +1,3 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /utf-8 /I ..\.. %* *.cpp ..\..\*.cpp ..\..\backends\imgui_impl_null.cpp /FeDebug/example_null.exe /FoDebug/ /link gdi32.lib shell32.lib imm32.lib +cl /nologo /Zi /MD /utf-8 /I ..\.. %* *.cpp ..\..\*.cpp /FeDebug/example_null.exe /FoDebug/ /link gdi32.lib shell32.lib imm32.lib diff --git a/examples/example_null/example_null.vcxproj b/examples/example_null/example_null.vcxproj index 7d0d59279..c8836c7e4 100644 --- a/examples/example_null/example_null.vcxproj +++ b/examples/example_null/example_null.vcxproj @@ -151,7 +151,6 @@ - diff --git a/examples/example_null/example_null.vcxproj.filters b/examples/example_null/example_null.vcxproj.filters index f5dd02f2d..9b485d5f4 100644 --- a/examples/example_null/example_null.vcxproj.filters +++ b/examples/example_null/example_null.vcxproj.filters @@ -18,9 +18,6 @@ imgui - - sources - @@ -54,4 +51,4 @@ imgui - + \ No newline at end of file diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index 5e94a6fb6..eba675670 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -3,7 +3,11 @@ // This is useful to test building, but you cannot interact with anything here! #include "imgui.h" #include -#include "imgui_impl_null.h" + +// For imgui_impl_null: use relative filename + embed implementation directly by including the .cpp file. +// This is to simplify casual building of this example from all sorts of test scripts. +#include "../../backends/imgui_impl_null.h" +#include "../../backends/imgui_impl_null.cpp" int main(int, char**) { From e1f9b8b3a76dff38968b5e0599c80a1b85dd0f6f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 16:49:34 +0100 Subject: [PATCH 1501/2359] CI: fixes warning building example_null w/ mingw 64-bit, as DLL --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 92d41dac1..5511d55fe 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -61,7 +61,7 @@ jobs: echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp g++ -I. -Wall -Wformat -shared -o libimgui.dll -Wl,--out-implib,libimgui.a example_single_file.cpp -limm32 - g++ -I. -Wall -Wformat -DIMGUI_API='__declspec(dllimport)' -o example_null.exe examples/example_null/main.cpp -L. -limgui + g++ -I. -Wall -Wformat -DIMGUI_API=__declspec(dllimport) -DIMGUI_IMPL_API= -o example_null.exe examples/example_null/main.cpp -L. -limgui rm -f example_null.exe libimgui.* example_single_file.* - name: Build example_null (extra warnings, msvc 64-bit) From 04af1a39176e0789982038b2c33431336e21913e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 17:43:09 +0100 Subject: [PATCH 1502/2359] CI: fixes warning building example_null w/ mingw 64-bit, as DLL --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5511d55fe..cc6208516 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -61,7 +61,7 @@ jobs: echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp g++ -I. -Wall -Wformat -shared -o libimgui.dll -Wl,--out-implib,libimgui.a example_single_file.cpp -limm32 - g++ -I. -Wall -Wformat -DIMGUI_API=__declspec(dllimport) -DIMGUI_IMPL_API= -o example_null.exe examples/example_null/main.cpp -L. -limgui + g++ -I. -Wall -Wformat -DIMGUI_API='__declspec(dllimport)' -DIMGUI_IMPL_API= -o example_null.exe examples/example_null/main.cpp -L. -limgui rm -f example_null.exe libimgui.* example_single_file.* - name: Build example_null (extra warnings, msvc 64-bit) From 52caa2f38a15ce6a83c253fa58a6d6ca8e753e9d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 17:50:37 +0100 Subject: [PATCH 1503/2359] CI: fixes warning building example_null w/ msvc as DLL --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cc6208516..ab8f507d0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -106,7 +106,7 @@ jobs: echo #include "misc/single_file/imgui_single_file.h" >> example_single_file.cpp cl.exe /D_USRDLL /D_WINDLL /I. example_single_file.cpp /LD /FeImGui.dll /link - cl.exe /DIMGUI_API=__declspec(dllimport) /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp + cl.exe /DIMGUI_API=__declspec(dllimport) -DIMGUI_IMPL_API /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp # Win64 examples are more frequently compilted than the Win32 examples. # More of the Win32 examples requires 'workflow_run' to reduce waste. From c3835de38a7c4c4c15c7c64fabdcfa7f63169721 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Nov 2025 18:01:51 +0100 Subject: [PATCH 1504/2359] CI: fixes warning building example_null w/ msvc as DLL --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ab8f507d0..1c9e8dcdb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -106,7 +106,7 @@ jobs: echo #include "misc/single_file/imgui_single_file.h" >> example_single_file.cpp cl.exe /D_USRDLL /D_WINDLL /I. example_single_file.cpp /LD /FeImGui.dll /link - cl.exe /DIMGUI_API=__declspec(dllimport) -DIMGUI_IMPL_API /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp + cl.exe /DIMGUI_API=__declspec(dllimport) -DIMGUI_IMPL_API= /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp # Win64 examples are more frequently compilted than the Win32 examples. # More of the Win32 examples requires 'workflow_run' to reduce waste. From 9afc62d087bdbb5a951101c351f9d17e22dc6d50 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Nov 2025 16:20:51 +0100 Subject: [PATCH 1505/2359] InputText: Fixed an assert when using ImGuiInputTextFlags_ReadOnly and making underlying contents shorter while text is selected. (#9069) --- docs/CHANGELOG.txt | 3 +++ imgui_widgets.cpp | 9 ++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3ad4d4aa7..f7ab1336d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -87,6 +87,9 @@ Other Changes: keys in order to allow e.g. external Shortcut override behavior. (#9004) - When using a callback to reduce/manipulate the value of BufTextLen, we do not require anymore that CursorPos be clamped by user code. (#9029) + - Fixed an assert when using ImGuiInputTextFlags_ReadOnly and making + underlying contents shorter while text is selected. (#9069, #3237) + (regression from 1.92.3) - InputTextMultiline: fixed a crash when using ImGuiInputTextFlags_WordWrap and resizing the parent window while keeping the multi-line field active (which is most typically achieved when resizing programmatically or via a docking layout diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 89b6d6e6f..0e49d1c19 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4762,8 +4762,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ state->TextLen = new_len; memcpy(state->TextA.Data, buf, state->TextLen + 1); state->Stb->select_start = state->ReloadSelectionStart; - state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd; - state->CursorClamp(); + state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd; // will be clamped to bounds below } else if ((init_state && g.ActiveId != id) || init_changed_specs) { @@ -4803,9 +4802,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Recycle existing cursor/selection/undo stack but clamp position // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. - if (recycle_state) - state->CursorClamp(); - else + if (!recycle_state) stb_textedit_initialize_state(state->Stb, !is_multiline); if (!is_multiline) @@ -4862,6 +4859,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Read-only mode always ever read from source buffer. Refresh TextLen when active. if (is_readonly && state != NULL) state->TextLen = (int)ImStrlen(buf); + if (state != NULL) + state->CursorClamp(); //if (is_readonly && state != NULL) // state->TextA.clear(); // Uncomment to facilitate debugging, but we otherwise prefer to keep/amortize th allocation. } From 6ae32c696a32af58cfe9185e464d65596c9ffafd Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Nov 2025 16:34:35 +0100 Subject: [PATCH 1506/2359] Backends: fixed misc zealous Clang warnings. --- backends/imgui_impl_dx12.h | 2 +- backends/imgui_impl_glfw.cpp | 10 ++++++---- backends/imgui_impl_null.cpp | 7 ++++++- backends/imgui_impl_sdl3.cpp | 4 ++-- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 4ff510455..3bb66c1fb 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -44,7 +44,7 @@ struct ImGui_ImplDX12_InitInfo D3D12_GPU_DESCRIPTOR_HANDLE LegacySingleSrvGpuDescriptor; #endif - ImGui_ImplDX12_InitInfo() { memset((void*)this, 0, sizeof(*this)); } + ImGui_ImplDX12_InitInfo() { memset(this, 0, sizeof(*this)); } }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 9ec9ccbf9..ac176a080 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -101,8 +101,10 @@ // Clang warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast -#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. #endif // GLFW @@ -957,8 +959,8 @@ static void ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(GLFWwindow* window, int display_w, display_h; glfwGetWindowSize(window, &w, &h); glfwGetFramebufferSize(window, &display_w, &display_h); - float fb_scale_x = (w > 0) ? (float)display_w / w : 1.0f; - float fb_scale_y = (h > 0) ? (float)display_h / h : 1.0f; + float fb_scale_x = (w > 0) ? (float)display_w / (float)w : 1.0f; + float fb_scale_y = (h > 0) ? (float)display_h / (float)h : 1.0f; #if GLFW_HAS_X11_OR_WAYLAND ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); if (!bd->IsWayland) diff --git a/backends/imgui_impl_null.cpp b/backends/imgui_impl_null.cpp index 9503b1789..6bf3ddb22 100644 --- a/backends/imgui_impl_null.cpp +++ b/backends/imgui_impl_null.cpp @@ -17,6 +17,11 @@ #ifndef IMGUI_DISABLE #include "imgui_impl_null.h" +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#endif + IMGUI_IMPL_API bool ImGui_ImplNull_Init() { ImGui_ImplNullPlatform_Init(); @@ -75,7 +80,7 @@ IMGUI_IMPL_API void ImGui_ImplNullRender_NewFrame() { } -void ImGui_ImplNullRender_UpdateTexture(ImTextureData* tex) +static void ImGui_ImplNullRender_UpdateTexture(ImTextureData* tex) { if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantDestroy) tex->SetStatus(ImTextureStatus_OK); diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 0a8647794..815929595 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -819,8 +819,8 @@ static void ImGui_ImplSDL3_GetWindowSizeAndFramebufferScale(SDL_Window* window, #else int display_w, display_h; SDL_GetWindowSizeInPixels(window, &display_w, &display_h); - float fb_scale_x = (w > 0) ? (float)display_w / w : 1.0f; - float fb_scale_y = (h > 0) ? (float)display_h / h : 1.0f; + float fb_scale_x = (w > 0) ? (float)display_w / (float)w : 1.0f; + float fb_scale_y = (h > 0) ? (float)display_h / (float)h : 1.0f; #endif if (out_size != nullptr) From 91b5256c57002b476ec40c6bf136136f7fe87eaa Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Nov 2025 17:00:01 +0100 Subject: [PATCH 1507/2359] Clipper: fixed an issue when using up/down from an item outside of visible bound and using the clipper. (#9079) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 10 +++++----- imgui.h | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f7ab1336d..dea1b0a44 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -94,6 +94,9 @@ Other Changes: resizing the parent window while keeping the multi-line field active (which is most typically achieved when resizing programmatically or via a docking layout reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] +- Nav: + - Clipper: fixed an issue when using up/down from an item outside of + visible bound and using the clipper. (#9079) - Fonts: - Calling ImFontAtlas::Clear() mid-frame without re-adding a font will lead to a more explicit crash. diff --git a/imgui.cpp b/imgui.cpp index fc52026ae..c0fa600b4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3346,10 +3346,12 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) { // Add range selected to be included for navigation const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); + const int nav_off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; + const int nav_off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0; if (is_nav_request) { - data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, 0, 0)); - data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0)); + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, nav_off_min, nav_off_max)); + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, nav_off_min, nav_off_max)); } if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1) data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount)); @@ -3378,9 +3380,7 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) } // Add main visible range - const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; - const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0; - data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max)); + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, nav_off_min, nav_off_max)); } // Convert position ranges to item index ranges diff --git a/imgui.h b/imgui.h index e5e4dda91..d0bf6fa7b 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.5 WIP" -#define IMGUI_VERSION_NUM 19246 +#define IMGUI_VERSION_NUM 19247 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From 405c80260776d3c966cdbb4c9d40588cd65f182e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Nov 2025 17:54:43 +0100 Subject: [PATCH 1508/2359] Nav: shallow tweaks. --- imgui.cpp | 15 ++++++++------- imgui_internal.h | 2 +- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c0fa600b4..3332e62bf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13808,13 +13808,13 @@ void ImGui::NavUpdateCreateMoveRequest() // Update PageUp/PageDown/Home/End scroll // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag? - float scoring_rect_offset_y = 0.0f; + float scoring_page_offset_y = 0.0f; if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active) - scoring_rect_offset_y = NavUpdatePageUpPageDown(); - if (scoring_rect_offset_y != 0.0f) + scoring_page_offset_y = NavUpdatePageUpPageDown(); + if (scoring_page_offset_y != 0.0f) { g.NavScoringNoClipRect = window->InnerRect; - g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y); + g.NavScoringNoClipRect.TranslateY(scoring_page_offset_y); } // [DEBUG] Always send a request when holding Ctrl. Hold Ctrl + Arrow change the direction. @@ -13879,12 +13879,13 @@ void ImGui::NavUpdateCreateMoveRequest() { ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); scoring_rect = WindowRectRelToAbs(window, nav_rect_rel); - scoring_rect.TranslateY(scoring_rect_offset_y); + scoring_rect.TranslateY(scoring_page_offset_y); + //GetForegroundDrawList()->AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)); // [DEBUG] Pre-bias if (g.NavMoveSubmitted) NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags); IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem(). - //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG] - //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG] + //GetForegroundDrawList()->AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)); // [DEBUG] Post-bias + //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRectFilled(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(100, 255, 0, 80)); } // [DEBUG] } g.NavScoringRect = scoring_rect; //g.NavScoringNoClipRect.Add(scoring_rect); diff --git a/imgui_internal.h b/imgui_internal.h index f16fa73df..88af027d7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1722,7 +1722,7 @@ enum ImGuiNavMoveFlags_ ImGuiNavMoveFlags_WrapMask_ = ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_WrapY, ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5, // Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown) - ImGuiNavMoveFlags_ScrollToEdgeY = 1 << 6, // Force scrolling to min/max (used by Home/End) // FIXME-NAV: Aim to remove or reword, probably unnecessary + ImGuiNavMoveFlags_ScrollToEdgeY = 1 << 6, // Force scrolling to min/max (used by Home/End) // FIXME-NAV: Aim to remove or reword as ImGuiScrollFlags ImGuiNavMoveFlags_Forwarded = 1 << 7, ImGuiNavMoveFlags_DebugNoResult = 1 << 8, // Dummy scoring for debug purpose, don't apply result ImGuiNavMoveFlags_FocusApi = 1 << 9, // Requests from focus API can land/focus/activate items even if they are marked with _NoTabStop (see NavProcessItemForTabbingRequest() for details) From 81e01ddebe166f1dd9942ad8132f9d5846d57237 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Nov 2025 18:57:32 +0100 Subject: [PATCH 1509/2359] Nav: reworked PageUp/PageDown to pick same-page top/bottom page based on inner rectangle rather than clipping rectangle. --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 12 ++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dea1b0a44..f5d620027 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -95,6 +95,10 @@ Other Changes: most typically achieved when resizing programmatically or via a docking layout reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] - Nav: + - Reworked PageUp/PageDown to pick same-page top/bottom page based + on inner rectangle rather than clipping rectangle, ensuring consistent + (but occasionally less practical) navigation result when a window is + partially out of screen. (#787) - Clipper: fixed an issue when using up/down from an item outside of visible bound and using the clipper. (#9079) - Fonts: diff --git a/imgui.cpp b/imgui.cpp index 3332e62bf..f9b65c484 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13207,10 +13207,14 @@ static void ImGui::NavProcessItem() // Features like PageUp/PageDown need to maintain a separate score for the visible set of items. const float VISIBLE_RATIO = 0.70f; - if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb)) - if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) - if (NavScoreItem(&g.NavMoveResultLocalVisible, nav_bb)) - NavApplyItemToResult(&g.NavMoveResultLocalVisible); + if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) + { + const ImRect& r = window->InnerRect; // window->ClipRect + if (r.Overlaps(nav_bb)) + if (ImClamp(nav_bb.Max.y, r.Min.y, r.Max.y) - ImClamp(nav_bb.Min.y, r.Min.y, r.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) + if (NavScoreItem(&g.NavMoveResultLocalVisible, nav_bb)) + NavApplyItemToResult(&g.NavMoveResultLocalVisible); + } } } } From 37f91531058534fbcbf809e9c38a1f57c05f4756 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Nov 2025 18:59:06 +0100 Subject: [PATCH 1510/2359] Nav: improved/clarified behavior when requesting PageUp/PageDown from a focused item which is outside of visible boundaries. (#9079) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 9 ++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f5d620027..1a92b7f40 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -99,6 +99,9 @@ Other Changes: on inner rectangle rather than clipping rectangle, ensuring consistent (but occasionally less practical) navigation result when a window is partially out of screen. (#787) + - Improved/clarified behavior when requesting PageUp/PageDown from a + focused item which is outside of visible boundaries: now ends up one + page away from focused item. (#9079) - Clipper: fixed an issue when using up/down from an item outside of visible bound and using the clipper. (#9079) - Fonts: diff --git a/imgui.cpp b/imgui.cpp index f9b65c484..170bca0fd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13815,11 +13815,6 @@ void ImGui::NavUpdateCreateMoveRequest() float scoring_page_offset_y = 0.0f; if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active) scoring_page_offset_y = NavUpdatePageUpPageDown(); - if (scoring_page_offset_y != 0.0f) - { - g.NavScoringNoClipRect = window->InnerRect; - g.NavScoringNoClipRect.TranslateY(scoring_page_offset_y); - } // [DEBUG] Always send a request when holding Ctrl. Hold Ctrl + Arrow change the direction. #if IMGUI_DEBUG_NAV_SCORING @@ -13883,7 +13878,11 @@ void ImGui::NavUpdateCreateMoveRequest() { ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); scoring_rect = WindowRectRelToAbs(window, nav_rect_rel); + if (scoring_page_offset_y != 0.0f) + g.NavScoringNoClipRect = scoring_rect; scoring_rect.TranslateY(scoring_page_offset_y); + if (scoring_page_offset_y != 0.0f) + g.NavScoringNoClipRect.Add(scoring_rect); //GetForegroundDrawList()->AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)); // [DEBUG] Pre-bias if (g.NavMoveSubmitted) NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags); From 23bd697f053bd5cf24601ee3f29572c0a645bd8f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Nov 2025 19:17:20 +0100 Subject: [PATCH 1511/2359] Drag and Drop: Pressing Escape while carrying a payload automatically cancel the active drag and drop. (#9071) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1a92b7f40..116e3760d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -122,6 +122,8 @@ Other Changes: - Drag and Drop: - Added ImGuiDragDropFlags_AcceptDrawAsHovered to make accepting item render as hovered, which can allow using e.g. Button() as drop target. (#8632) + - Pressing Escape while carrying a payload automatically cancel the + active drag and drop. (#9071) - Style: added ImGuiCol_DragDropTargetBg, style.DragDropTargetRounding, style.DragDropTargetBorderSize and style.DragDropTargetPadding to configure the drop target highlight. (#9056) [@aaronkirkham] diff --git a/imgui.cpp b/imgui.cpp index 170bca0fd..c20e8dfa3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5534,6 +5534,11 @@ void ImGui::NewFrame() g.DragDropWithinSource = false; g.DragDropWithinTarget = false; g.DragDropHoldJustPressedId = 0; + if (g.DragDropActive && IsKeyPressed(ImGuiKey_Escape, ImGuiInputFlags_None, g.ActiveId)) // Also works when g.ActiveId==0 (aka leftover payload in progress, no active id) + { + ClearActiveID(); + ClearDragDrop(); + } g.TooltipPreviousWindow = NULL; // Close popups on focus lost (currently wip/opt-in) From 68894d414977b6b970858dd9ac17e32eb4e443ac Mon Sep 17 00:00:00 2001 From: achabense <60953653+achabense@users.noreply.github.com> Date: Wed, 19 Nov 2025 22:45:20 +0800 Subject: [PATCH 1512/2359] Docs: fixed outdated comment. (#9082) --- imgui.h | 2 +- imgui_demo.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index d0bf6fa7b..68e7f2616 100644 --- a/imgui.h +++ b/imgui.h @@ -1452,7 +1452,7 @@ enum ImGuiHoveredFlags_ // Tooltips mode // - typically used in IsItemHovered() + SetTooltip() sequence. // - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior. - // e.g. 'TooltipHoveredFlagsForMouse' defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort'. + // e.g. 'HoverFlagsForTooltipMouse' defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled'. // - for frequently actioned or hovered items providing a tooltip, you want may to use ImGuiHoveredFlags_ForTooltip (stationary + delay) so the tooltip doesn't show too often. // - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay. ImGuiHoveredFlags_ForTooltip = 1 << 12, // Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1c8779951..6a16f7ff3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -5323,7 +5323,7 @@ static void DemoWindowPopups() if (ImGui::BeginPopupContextItem()) // <-- use last item id as popup id { selected = n; - ImGui::Text("This a popup for \"%s\"!", names[n]); + ImGui::Text("This is a popup for \"%s\"!", names[n]); if (ImGui::Button("Close")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); From b4a3d423e07c7e3bea796e3b5c35c61cd74be9e5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Nov 2025 17:06:44 +0100 Subject: [PATCH 1513/2359] Docs: amend BeginDisabled() comments. (#9082) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 68e7f2616..2279e6300 100644 --- a/imgui.h +++ b/imgui.h @@ -976,7 +976,7 @@ namespace ImGui // Disabling [BETA API] // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) - // - Tooltips windows by exception are opted out of disabling. + // - Tooltips windows are automatically opted out of disabling. Note that IsItemHovered() by default returns false on disabled items, unless using ImGuiHoveredFlags_AllowWhenDisabled. // - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls) IMGUI_API void BeginDisabled(bool disabled = true); IMGUI_API void EndDisabled(); From 1f16ca5e5cca7dd7e2fa793099664fbf8824cb02 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Nov 2025 17:12:49 +0100 Subject: [PATCH 1514/2359] Docs: update ShowUserGuide() + PR guidelines. (#9071) --- .github/pull_request_template.md | 6 ++++-- imgui_demo.cpp | 10 +++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 796ec0b9e..d40b14ccf 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -2,7 +2,9 @@ 1. PLEASE CAREFULLY READ: [Contributing Guidelines](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md) -2. Make sure you're using a special branch just for this pull request. (Sometimes people unknowingly use a default branch, then later update that branch, which updates the pull request with the other changes if it hasn't been merged yet.) +2. **Make sure you're using a special branch just for this pull request**. (In git, 1 PR = 1 branch. If you update the branch the PR will be updated.) -3. Clear this template before submitting your PR. +3. Consider running the [imgui_test_suite](https://github.com/ocornut/imgui_test_engine) or adding new tests to test for expected behaviors. + +4. Clear this template before submitting your PR. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6a16f7ff3..92857aa3f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8641,11 +8641,11 @@ void ImGui::ShowUserGuide() ImGuiIO& io = GetIO(); BulletText("Double-click on title bar to collapse window."); BulletText( - "Click and drag on lower corner to resize window\n" - "(double-click to auto fit window to its contents)."); + "Click and drag on lower corner or border to resize window.\n" + "(double-click to auto fit window to its contents)"); BulletText("Ctrl+Click on a slider or drag box to input value as text."); BulletText("Tab/Shift+Tab to cycle through keyboard editable fields."); - BulletText("Ctrl+Tab to select a window."); + BulletText("Ctrl+Tab/Ctrl+Shift+Tab to focus windows."); if (io.FontAllowUserScaling) BulletText("Ctrl+Mouse Wheel to zoom window contents."); BulletText("While inputting text:\n"); @@ -8658,10 +8658,10 @@ void ImGui::ShowUserGuide() Unindent(); BulletText("With keyboard navigation enabled:"); Indent(); - BulletText("Arrow keys to navigate."); + BulletText("Arrow keys or Home/End/PageUp/PageDown to navigate."); BulletText("Space to activate a widget."); BulletText("Return to input text into a widget."); - BulletText("Escape to deactivate a widget, close popup, exit child window."); + BulletText("Escape to deactivate a widget, close popup,\nexit a child window or the menu layer, clear focus."); BulletText("Alt to jump to the menu layer of a window."); Unindent(); } From db6b8e0fb34b93e0ddf9d669f6f56eeba78ce44a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Nov 2025 17:21:17 +0100 Subject: [PATCH 1515/2359] Drag and Drop: handling of Escape after UpdateKeyboardInputs(). (#9071) --- imgui.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c20e8dfa3..fcf248aba 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5525,6 +5525,18 @@ void ImGui::NewFrame() g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer. } + // Close popups on focus lost (currently wip/opt-in) + //if (g.IO.AppFocusLost) + // ClosePopupsExceptModals(); + + // Update keyboard input state + UpdateKeyboardInputs(); + + //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl)); + //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift)); + //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt)); + //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper)); + // Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; g.DragDropAcceptIdCurr = 0; @@ -5541,18 +5553,6 @@ void ImGui::NewFrame() } g.TooltipPreviousWindow = NULL; - // Close popups on focus lost (currently wip/opt-in) - //if (g.IO.AppFocusLost) - // ClosePopupsExceptModals(); - - // Update keyboard input state - UpdateKeyboardInputs(); - - //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl)); - //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift)); - //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt)); - //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper)); - // Update keyboard/gamepad navigation NavUpdate(); From 0faa0dba15d635ddcf0c98250eda72c064ff6f67 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Nov 2025 18:26:31 +0100 Subject: [PATCH 1516/2359] Drag and Drop: rework cancel drag and drop logic to be overridable. (#9071) --- imgui.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fcf248aba..9e84b75d0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5546,10 +5546,18 @@ void ImGui::NewFrame() g.DragDropWithinSource = false; g.DragDropWithinTarget = false; g.DragDropHoldJustPressedId = 0; - if (g.DragDropActive && IsKeyPressed(ImGuiKey_Escape, ImGuiInputFlags_None, g.ActiveId)) // Also works when g.ActiveId==0 (aka leftover payload in progress, no active id) + if (g.DragDropActive) { - ClearActiveID(); - ClearDragDrop(); + // Also works when g.ActiveId==0 (aka leftover payload in progress, no active id) + // You may disable this externally by hijacking the input route: + // 'if (GetDragDropPayload() != NULL) { Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive); } + // but you will not get a return value from Shortcut() due to ActiveIdUsingAllKeyboardKeys logic. You can however poll IsKeyPressed(ImGuiKey_Escape) afterwards. + ImGuiID owner_id = g.ActiveId ? g.ActiveId : ImHashStr("##DragDropCancelHandler"); + if (Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteGlobal, owner_id)) + { + ClearActiveID(); + ClearDragDrop(); + } } g.TooltipPreviousWindow = NULL; From 4ab86e1d61c58688e1c7df90e842687c7a49bfdf Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Nov 2025 19:01:03 +0100 Subject: [PATCH 1517/2359] Nav: fixed scoring when using PageUp/PageDown from a focused item which is outside of visible boundaries. (#9079) We only use ImGuiNavMoveFlags_AlsoScoreVisibleSet when starting point is visible. --- imgui.cpp | 16 +++++++++++----- imgui.h | 2 +- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9e84b75d0..6704cb294 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13891,11 +13891,17 @@ void ImGui::NavUpdateCreateMoveRequest() { ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); scoring_rect = WindowRectRelToAbs(window, nav_rect_rel); - if (scoring_page_offset_y != 0.0f) + + if (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove) + { + // When we start from a visible location, score visible items and prioritize this result. + if (window->InnerRect.Contains(scoring_rect)) + g.NavMoveFlags |= ImGuiNavMoveFlags_AlsoScoreVisibleSet; g.NavScoringNoClipRect = scoring_rect; - scoring_rect.TranslateY(scoring_page_offset_y); - if (scoring_page_offset_y != 0.0f) + scoring_rect.TranslateY(scoring_page_offset_y); g.NavScoringNoClipRect.Add(scoring_rect); + } + //GetForegroundDrawList()->AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)); // [DEBUG] Pre-bias if (g.NavMoveSubmitted) NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags); @@ -14147,14 +14153,14 @@ static float ImGui::NavUpdatePageUpPageDown() nav_scoring_rect_offset_y = -page_offset_y; g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Up; - g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_IsPageMove; // ImGuiNavMoveFlags_AlsoScoreVisibleSet may be added later } else if (IsKeyPressed(ImGuiKey_PageDown, true)) { nav_scoring_rect_offset_y = +page_offset_y; g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Down; - g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_IsPageMove; // ImGuiNavMoveFlags_AlsoScoreVisibleSet may be added later } else if (home_pressed) { diff --git a/imgui.h b/imgui.h index 2279e6300..c775df0be 100644 --- a/imgui.h +++ b/imgui.h @@ -29,7 +29,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.92.5 WIP" -#define IMGUI_VERSION_NUM 19247 +#define IMGUI_VERSION_NUM 19248 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 From e8448d04947f5d06983b82ee6c3185a1f0f13148 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Thu, 20 Nov 2025 11:33:28 +0200 Subject: [PATCH 1518/2359] CI: general update + rename steps. --- .github/workflows/build.yml | 54 ++++++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1c9e8dcdb..68b4b3d14 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,13 +16,21 @@ on: - requested jobs: - Windows: + Build-Windows: runs-on: windows-2025 + name: Build - Windows + + defaults: + run: + working-directory: ${{ github.workspace }}/imgui + env: VS_PATH: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\ MSBUILD_PATH: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\ steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 + with: + path: ${{ github.workspace }}/imgui # The VulkanSDK libs for Windows is manually generated using build_windows_vulkan_libs.ps1 + attached to issue #8925. # (we have a .yml workflow in commit history if it becomes ever useful to create this on CI too) @@ -257,10 +265,18 @@ jobs: shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' - Linux: + Build-Linux: runs-on: ubuntu-latest + name: Build - Linux + + defaults: + run: + working-directory: ${{ github.workspace }}/imgui + steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 + with: + path: ${{ github.workspace }}/imgui - name: Install Dependencies run: | @@ -474,10 +490,18 @@ jobs: - name: Build with IMGUI_IMPL_VULKAN_NO_PROTOTYPES run: g++ -c -I. -std=c++11 -DIMGUI_IMPL_VULKAN_NO_PROTOTYPES=1 backends/imgui_impl_vulkan.cpp - MacOS: + Build-MacOS: runs-on: macos-latest + name: Build - MacOS + + defaults: + run: + working-directory: ${{ github.workspace }}/imgui + steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 + with: + path: ${{ github.workspace }}/imgui - name: Install Dependencies run: | @@ -548,20 +572,24 @@ jobs: - name: Build example_apple_opengl2 run: xcodebuild -project examples/example_apple_opengl2/example_apple_opengl2.xcodeproj -target example_osx_opengl2 - iOS: + Build-iOS: runs-on: macos-14 + name: Build - iOS + steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Build example_apple_metal run: | # Code signing is required, but we disable it because it is irrelevant for CI builds. xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_ios CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO - Emscripten: + Build-Emscripten: runs-on: ubuntu-latest + name: Build - Emscripten + steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Install Dependencies run: | @@ -599,10 +627,12 @@ jobs: emcmake cmake -B build -DCMAKE_BUILD_TYPE=Release examples/example_glfw_wgpu cmake --build build - Android: + Build-Android: runs-on: ubuntu-latest + name: Build - Android + steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Build example_android_opengl3 run: | From 8ff7f35eec319ff48151a3f6603719d42f21a6ff Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Thu, 20 Nov 2025 14:35:32 +0100 Subject: [PATCH 1519/2359] CI: run imgui_test_suite as part of CI build. --- .github/workflows/build.yml | 134 ++++++++++++++++++++++++++++++++++++ docs/CHANGELOG.txt | 1 + 2 files changed, 135 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 68b4b3d14..3ee729717 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -638,3 +638,137 @@ jobs: run: | cd examples/example_android_opengl3/android gradle assembleDebug --stacktrace + + Test-Windows: + runs-on: windows-2025 + name: Test - Windows + + defaults: + run: + working-directory: ${{ github.workspace }}/imgui + + env: + MSBUILD_PATH: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\ + + steps: + - uses: actions/checkout@v5 + with: + path: ${{ github.workspace }}/imgui + + - uses: actions/checkout@v5 + continue-on-error: true + with: + fetch-depth: 1 + repository: ocornut/imgui_test_engine + path: ${{ github.workspace }}/imgui_test_engine + submodules: true + + - name: Fix Tests Projects + shell: powershell + working-directory: ${{ github.workspace }}/imgui_test_engine + run: | + # WARNING: This will need updating if toolset/sdk change in project files! + gci -recurse -filter "*.vcxproj" | ForEach-Object { + # Fix SDK and toolset for most samples. + (Get-Content $_.FullName) -Replace "v110","v142" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "8.1","10.0.20348.0" | Set-Content -Path $_.FullName + # Fix SDK and toolset for samples that require newer SDK/toolset. At the moment it is only dx12. + (Get-Content $_.FullName) -Replace "v140","v142" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "10.0.14393.0","10.0.20348.0" | Set-Content -Path $_.FullName + } + + - name: Build Tests + shell: cmd + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: '"%MSBUILD_PATH%\MSBuild.exe" imgui_test_suite.vcxproj /p:Platform=x64 /p:Configuration=Release /p:ClFlags=/WX -maxcpucount:%NUMBER_OF_PROCESSORS%' + + - name: Run Tests + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: Release/imgui_test_suite.exe -nogui -nopause -v2 -ve4 tests + + - name: Check for Docking + id: check_docking + shell: bash + working-directory: ${{ github.workspace }}/imgui + run: echo "has_dock=$(grep -q "#define IMGUI_HAS_DOCK" imgui.h && echo true || echo false)" >> $GITHUB_OUTPUT + + - name: Run Viewport Tests + if: steps.check_docking.outputs.has_dock == 'true' + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: Release/imgui_test_suite.exe -nogui -nopause -v2 -ve4 -viewport-mock viewport + + Test-Linux: + runs-on: ubuntu-latest + name: Test - Linux + + defaults: + run: + working-directory: ${{ github.workspace }}/imgui + + steps: + - uses: actions/checkout@v5 + with: + path: ${{ github.workspace }}/imgui + + - uses: actions/checkout@v5 + with: + fetch-depth: 1 + repository: ocornut/imgui_test_engine + path: ${{ github.workspace }}/imgui_test_engine + submodules: true + + - name: Build Tests + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: make -j$(nproc) + + - name: Run Tests + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: ./imgui_test_suite -nogui -nopause -v2 -ve4 tests + + - name: Check for Docking + id: check_docking + working-directory: ${{ github.workspace }}/imgui + run: echo "has_dock=$(grep -q "#define IMGUI_HAS_DOCK" imgui.h && echo true || echo false)" >> $GITHUB_OUTPUT + + - name: Run Viewport Tests + if: steps.check_docking.outputs.has_dock == 'true' + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: ./imgui_test_suite -nogui -nopause -v2 -ve4 -viewport-mock viewport + + Test-MacOS: + runs-on: macos-latest + name: Test - MacOS + + defaults: + run: + working-directory: ${{ github.workspace }}/imgui + + steps: + - uses: actions/checkout@v5 + with: + path: ${{ github.workspace }}/imgui + + - uses: actions/checkout@v5 + with: + fetch-depth: 1 + repository: ocornut/imgui_test_engine + path: ${{ github.workspace }}/imgui_test_engine + submodules: true + + - name: Build Tests + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: make -j$(nproc) + + - name: Run Tests + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: ./imgui_test_suite -nogui -nopause -v2 -ve4 tests + + - name: Check for Docking + id: check_docking + working-directory: ${{ github.workspace }}/imgui + run: echo "has_dock=$(grep -q "#define IMGUI_HAS_DOCK" imgui.h && echo true || echo false)" >> $GITHUB_OUTPUT + + - name: Run Viewport Tests + if: steps.check_docking.outputs.has_dock == 'true' + working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite + run: ./imgui_test_suite -nogui -nopause -v2 -ve4 -viewport-mock viewport diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 116e3760d..f598e3f03 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -119,6 +119,7 @@ Other Changes: Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited). - Misc: standardized casing of keyboard mods in comments and demo, showing as e.g. "Ctrl" instead of "CTRL". +- CI: Added Dear ImGui Test Suite to CI builds. [@rokups] - Drag and Drop: - Added ImGuiDragDropFlags_AcceptDrawAsHovered to make accepting item render as hovered, which can allow using e.g. Button() as drop target. (#8632) From a484fd2b56f9d208f304d4e1ec0b57cd51502b48 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Nov 2025 14:50:08 +0100 Subject: [PATCH 1520/2359] Examples: Win32+OpenGL3: enable DPI awareness. (#9083) --- docs/CHANGELOG.txt | 1 + examples/example_win32_opengl3/main.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f598e3f03..e17e64e2a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -175,6 +175,7 @@ Other Changes: during surface resize. (#8381) - SDL2+WebGPU: added new example (Emscripten + native Dawn/WGPU). (#8381) [@brutpitt] - SDL3+WebGPU: added new example (Emscripten + native Dawn/WGPU). (#8381) [@brutpitt] + - Win32+OpenGL3: enable DPI awareness. (#9083) ----------------------------------------------------------------------- diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 9ad74d61f..8d29c41ca 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -37,7 +37,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Make process DPI aware and obtain main monitor scale - //ImGui_ImplWin32_EnableDpiAwareness(); // FIXME: This somehow doesn't work in the Win32+OpenGL example. Why? + ImGui_ImplWin32_EnableDpiAwareness(); float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); // Create application window From 26ff93dadc85c54fc6a467239fe91726540fef2a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Nov 2025 14:51:25 +0100 Subject: [PATCH 1521/2359] Examples: NULL: fixed msvc project. --- examples/example_null/example_null.vcxproj | 8 +++++++- examples/example_null/example_null.vcxproj.filters | 3 +++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/examples/example_null/example_null.vcxproj b/examples/example_null/example_null.vcxproj index c8836c7e4..8ef991f3f 100644 --- a/examples/example_null/example_null.vcxproj +++ b/examples/example_null/example_null.vcxproj @@ -148,17 +148,23 @@ + + + true + true + true + true + - diff --git a/examples/example_null/example_null.vcxproj.filters b/examples/example_null/example_null.vcxproj.filters index 9b485d5f4..6d575a8f5 100644 --- a/examples/example_null/example_null.vcxproj.filters +++ b/examples/example_null/example_null.vcxproj.filters @@ -18,6 +18,9 @@ imgui + + sources + From 6d910d5487d11ca567b61c7824b0c78c569d62f0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Nov 2025 17:25:43 +0100 Subject: [PATCH 1522/2359] Version 1.92.5 --- docs/CHANGELOG.txt | 36 +++++++++++++++++++----------------- imgui.cpp | 20 +++++++++++--------- imgui.h | 21 +++++++++++---------- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 46 insertions(+), 41 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e17e64e2a..a9c0fea2f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.5 WIP (In Progress) + VERSION 1.92.5 (Released 2025-11-20) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92.5 + Breaking Changes: - Keys: commented out legacy names which were obsoleted in 1.89.0 (August 2022). @@ -61,13 +63,6 @@ Breaking Changes: Other Changes: -- Tables: fixed a bug where nesting BeginTable()->Begin()->BeginTable() would - result in temporarily incorrect state, which would lead to bugs to side effects - in various locations, e.g. GetContentRegionAvail() calls or using clipper. (#9005) - EndTable() was mistakenly restoring a wrong current table. -- Tables: Angled headers: fixed an auto-resize feedback loop that could - affect tables with empty non-resizing columns using angled headers, making - them typically flicker back and forth between +0 and +1 pixels. - Windows: - Config flag io.ConfigWindowsMoveFromTitleBarOnly is now latched during Begin(), effectively allowing to change the value on a per-window basis. @@ -77,6 +72,14 @@ Other Changes: scrollbar on the other axis. (#9060) - Fixed an issue where repeated calls to SetNextWindowSize() using 0.0f to auto-size on a given axis would keep marking ini settings as dirty. +- Tables: + - Fixed a bug where nesting BeginTable()->Begin()->BeginTable() would + result in temporarily incorrect state, which would lead to bugs to side effects + in various locations, e.g. GetContentRegionAvail() calls or using clipper. (#9005) + EndTable() was mistakenly restoring a wrong current table. + - Angled headers: fixed an auto-resize feedback loop that could + affect tables with empty non-resizing columns using angled headers, making + them typically flicker back and forth between +0 and +1 pixels. - Disabled: fixed a bug when a previously enabled item that got nav focus and then turns disabled could still be activated using keyboard. (#9036) - InputText: @@ -95,7 +98,7 @@ Other Changes: most typically achieved when resizing programmatically or via a docking layout reacting to a platform window resize). (#3237, #9007) [@anton-kl, @ocornut] - Nav: - - Reworked PageUp/PageDown to pick same-page top/bottom page based + - Reworked PageUp/PageDown logic to pick same-page top/bottom page based on inner rectangle rather than clipping rectangle, ensuring consistent (but occasionally less practical) navigation result when a window is partially out of screen. (#787) @@ -116,7 +119,7 @@ Other Changes: - Groups: fixed an issue reporting IsItemEdited() signal after EndGroup() when triggered by some widgets e.g. Checkbox(), Selectable() and many others, which cleared ActiveId at the same time as editing. (#9028) - Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited). + Note that IsItemDeactivatedAfterEdit() was not affected, only IsItemEdited(). - Misc: standardized casing of keyboard mods in comments and demo, showing as e.g. "Ctrl" instead of "CTRL". - CI: Added Dear ImGui Test Suite to CI builds. [@rokups] @@ -137,7 +140,7 @@ Other Changes: - Metrics: fixed table and columns rect highlight from display when debug/metrics window is not in the same viewport as the table. - Backends: - - Null: added imgui_impl_null platform/renderer backend. + - NULL: added imgui_impl_null platform/renderer backend. This is designed if you need to run e.g. context with no input or no ouput. - GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) [@jagot] @@ -151,6 +154,10 @@ Other Changes: field changes viewports. (#9054) - Vulkan: added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to Volk (default to "volk.h"). (#9008, #7722, #6582, #4854) [@mwlasiuk] + - WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ + '--use-port=emdawnwebgpu' ports. (#8381, #8898, #7435) [@brutpitt, @trbabb] + When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN + instead of IMGUI_IMPL_WEBGPU_BACKEND_WGPU, if neither are specified. - WebGPU: added various internal/optional helpers to wrap some of the Dawn/WGPU/Emscripten debacle quirks: (#8381) [@brutpitt] - ImGui_ImplWGPU_CreateWGPUSurfaceHelper(). @@ -159,15 +166,10 @@ Other Changes: - ImGui_ImplWGPU_GetBackendTypeName(), ImGui_ImplWGPU_GetAdapterTypeName(), ImGui_ImplWGPU_GetDeviceLostReasonName(), ImGui_ImplWGPU_GetErrorTypeName(), ImGui_ImplWGPU_GetLogLevelName(). - - WebGPU: update to compile with Dawn and Emscripten's 4.0.10+ - '--use-port=emdawnwebgpu' ports. (#8381, #8898, #7435) [@brutpitt, @trbabb] - When using Emscripten 4.0.10+, backend now defaults to IMGUI_IMPL_WEBGPU_BACKEND_DAWN - instead of IMGUI_IMPL_WEBGPU_BACKEND_WGPU, if neither are specified. - (note: examples application were not updated yet) - Win32: Revert 1.92.4 change of comparing dwPacketNumber, which prevents refreshing accurate gamepad info after focus-out + io.ClearInputKeys(). (#8556) - Examples: - - Null: update examples_null to use imgui_impl_null (which is a bit overengineering + - NULL: update examples_null to use imgui_impl_null (which is a bit overengineering but somehow consistent). - GLFW+WebGPU: update example for latest specs, to work on Emscripten 4.0.10+, latest Dawn-Native and WGPU-Native. (#8381, #8567, #8191, #7435) [@brutpitt] diff --git a/imgui.cpp b/imgui.cpp index 6704cb294..2bb3ad3d9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,27 +1,28 @@ -// dear imgui, v1.92.5 WIP +// dear imgui, v1.92.5 // (main code and documentation) // Help: -// - See links below. // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // - Read top of imgui.cpp for more details, links and comments. +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including imgui.h (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. // Resources: // - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) // - Homepage ................... https://github.com/ocornut/imgui -// - Releases & changelog ....... https://github.com/ocornut/imgui/releases +// - Releases & Changelog ....... https://github.com/ocornut/imgui/releases // - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) // - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) // - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) // - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) -// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines) -// - Glossary https://github.com/ocornut/imgui/wiki/Glossary +// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings + backends for various tech/engines) // - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools +// - Glossary https://github.com/ocornut/imgui/wiki/Glossary // - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui // - Issues & support ........... https://github.com/ocornut/imgui/issues // - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) +// - Web version of the Demo .... https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html (w/ source code browser) -// For first-time users having issues compiling/linking/running: +// For FIRST-TIME users having issues compiling/linking/running: // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. // Since 1.92, we encourage font loading questions to also be posted in 'Issues'. @@ -122,7 +123,7 @@ CODE Designed primarily for developers and content-creators, not the typical end-user! Some of the current weaknesses (which we aim to address in the future) includes: - - Doesn't look fancy. + - Doesn't look fancy by default. - Limited layout features, intricate layouts are typically crafted in code. @@ -147,7 +148,8 @@ CODE - Ctrl+Z Undo. - Ctrl+Y or Ctrl+Shift+Z: Redo. - ESCAPE: Revert text to its original value. - - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors. + - On macOS, controls are automatically adjusted to match standard macOS text editing and behaviors. + (for 99% of shortcuts, Ctrl is replaced by Cmd on macOS). - KEYBOARD CONTROLS - Basic: @@ -200,7 +202,7 @@ CODE READ FIRST ---------- - - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki) + - Remember to check the wonderful Wiki: https://github.com/ocornut/imgui/wiki - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs. diff --git a/imgui.h b/imgui.h index c775df0be..be945c611 100644 --- a/imgui.h +++ b/imgui.h @@ -1,35 +1,36 @@ -// dear imgui, v1.92.5 WIP +// dear imgui, v1.92.5 // (headers) // Help: -// - See links below. // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // - Read top of imgui.cpp for more details, links and comments. -// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. +// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including imgui.h (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. // Resources: // - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) // - Homepage ................... https://github.com/ocornut/imgui -// - Releases & changelog ....... https://github.com/ocornut/imgui/releases +// - Releases & Changelog ....... https://github.com/ocornut/imgui/releases // - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) // - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) // - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) // - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) -// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines) -// - Glossary https://github.com/ocornut/imgui/wiki/Glossary +// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings + backends for various tech/engines) // - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools +// - Glossary https://github.com/ocornut/imgui/wiki/Glossary // - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui // - Issues & support ........... https://github.com/ocornut/imgui/issues // - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) +// - Web version of the Demo .... https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html (w/ source code browser) -// For first-time users having issues compiling/linking/running/loading fonts: +// For FIRST-TIME users having issues compiling/linking/running: // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. -// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. +// EVERYTHING ELSE should be asked in 'Issues'! We are building a database of cross-linked knowledge there. +// Since 1.92, we encourage font loading questions to also be posted in 'Issues'. // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.5 WIP" -#define IMGUI_VERSION_NUM 19248 +#define IMGUI_VERSION "1.92.5" +#define IMGUI_VERSION_NUM 19250 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 92857aa3f..a3996d961 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 WIP +// dear imgui, v1.92.5 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7111fb0b9..de6462295 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 WIP +// dear imgui, v1.92.5 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 88af027d7..f577c170b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 WIP +// dear imgui, v1.92.5 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 8f5a746f1..41fdf6a4c 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 WIP +// dear imgui, v1.92.5 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0e49d1c19..e487b3f96 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 WIP +// dear imgui, v1.92.5 // (widgets code) /* From ee48fad09d51cbe04696a6ca1b287d347bd6c17b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Nov 2025 19:47:03 +0100 Subject: [PATCH 1523/2359] Internals: rename ImStableVector's BLOCK_SIZE to avoid conflict with Linux header defines. (#9088) --- imgui_internal.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index f577c170b..b8d6c469b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -712,10 +712,10 @@ struct ImSpanAllocator }; // Helper: ImStableVector<> -// Allocating chunks of BLOCK_SIZE items. Objects pointers are never invalidated when growing, only by clear(). +// Allocating chunks of BLOCKSIZE items. Objects pointers are never invalidated when growing, only by clear(). // Important: does not destruct anything! // Implemented only the minimum set of functions we need for it. -template +template struct ImStableVector { int Size = 0; @@ -729,19 +729,19 @@ struct ImStableVector inline void resize(int new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; } inline void reserve(int new_cap) { - new_cap = IM_MEMALIGN(new_cap, BLOCK_SIZE); - int old_count = Capacity / BLOCK_SIZE; - int new_count = new_cap / BLOCK_SIZE; + new_cap = IM_MEMALIGN(new_cap, BLOCKSIZE); + int old_count = Capacity / BLOCKSIZE; + int new_count = new_cap / BLOCKSIZE; if (new_count <= old_count) return; Blocks.resize(new_count); for (int n = old_count; n < new_count; n++) - Blocks[n] = (T*)IM_ALLOC(sizeof(T) * BLOCK_SIZE); + Blocks[n] = (T*)IM_ALLOC(sizeof(T) * BLOCKSIZE); Capacity = new_cap; } - inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; } - inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; } - inline T* push_back(const T& v) { int i = Size; IM_ASSERT(i >= 0); if (Size == Capacity) reserve(Capacity + BLOCK_SIZE); void* ptr = &Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; memcpy(ptr, &v, sizeof(v)); Size++; return (T*)ptr; } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCKSIZE][i % BLOCKSIZE]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCKSIZE][i % BLOCKSIZE]; } + inline T* push_back(const T& v) { int i = Size; IM_ASSERT(i >= 0); if (Size == Capacity) reserve(Capacity + BLOCKSIZE); void* ptr = &Blocks[i / BLOCKSIZE][i % BLOCKSIZE]; memcpy(ptr, &v, sizeof(v)); Size++; return (T*)ptr; } }; // Helper: ImPool<> From 324cea1f41fa6dcdacfa363abfde10d44efaea58 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Nov 2025 13:35:41 +0100 Subject: [PATCH 1524/2359] Version 1.92.6 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a9c0fea2f..68c4096d0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.6 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.92.5 (Released 2025-11-20) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 2bb3ad3d9..5f6e5057e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 +// dear imgui, v1.92.6 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index be945c611..fe1385da2 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 +// dear imgui, v1.92.6 WIP // (headers) // Help: @@ -29,8 +29,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.5" -#define IMGUI_VERSION_NUM 19250 +#define IMGUI_VERSION "1.92.6 WIP" +#define IMGUI_VERSION_NUM 19251 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a3996d961..35451730c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 +// dear imgui, v1.92.6 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index de6462295..589de9b91 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 +// dear imgui, v1.92.6 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index b8d6c469b..f5a90918f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 +// dear imgui, v1.92.6 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 41fdf6a4c..25d945d2a 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 +// dear imgui, v1.92.6 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e487b3f96..a4b3e7ed1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.5 +// dear imgui, v1.92.6 WIP // (widgets code) /* From 136d067eed66204cc50c528812e7ad00104751cb Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Nov 2025 14:27:03 +0100 Subject: [PATCH 1525/2359] Scrollbar: fixed a codepath leading to a divide-by-zero. (#9089) --- docs/CHANGELOG.txt | 3 +++ imgui_widgets.cpp | 2 ++ 2 files changed, 5 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 68c4096d0..82c81a6ff 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,9 @@ Breaking Changes: Other Changes: +- Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be + noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] + ----------------------------------------------------------------------- VERSION 1.92.5 (Released 2025-11-20) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a4b3e7ed1..9009bbc8c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1037,6 +1037,8 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight(); + if (scrollbar_size_v < 1.0f) + return false; // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) // But we maintain a minimum size in pixel to allow for the user to still aim inside. From 5f82275ba1f31e4c8e12c04e699d50f30a4e7a95 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Nov 2025 14:49:16 +0100 Subject: [PATCH 1526/2359] Docs: updated 1.91.5 logs for missing info that GetKeyIndex() was removed at this date. Amend 6f287dd16 --- docs/CHANGELOG.txt | 1 + imgui.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 82c81a6ff..df9330ea2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -1386,6 +1386,7 @@ Breaking changes: - Commented out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before). - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022). Use IsKeyDown() instead. - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022). + - GetKeyIndex() is removed (obsoleted March 2022). The indirection is now unnecessary. - Pre-1.87 backends are not supported: - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields. - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields. diff --git a/imgui.cpp b/imgui.cpp index 5f6e5057e..2cd202386 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -524,6 +524,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - 2024/11/06 (1.91.5) - commented/obsoleted out pre-1.87 IO system (equivalent to using IMGUI_DISABLE_OBSOLETE_KEYIO or IMGUI_DISABLE_OBSOLETE_FUNCTIONS before) - io.KeyMap[] and io.KeysDown[] are removed (obsoleted February 2022). - io.NavInputs[] and ImGuiNavInput are removed (obsoleted July 2022). + - GetKeyIndex() is removed (obsoleted March 2022). The indirection is now unnecessary. - pre-1.87 backends are not supported: - backends need to call io.AddKeyEvent(), io.AddMouseEvent() instead of writing to io.KeysDown[], io.MouseDown[] fields. - backends need to call io.AddKeyAnalogEvent() for gamepad values instead of writing to io.NavInputs[] fields. From 98636f4a239aed1dfccbc42bd38b76756d7ac0ba Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Nov 2025 15:39:41 +0100 Subject: [PATCH 1527/2359] Fonts: fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data. (#9086) Amend 815168c7e + Added explicit casts for intent/clarity when passing to stb_truetype/freetype. --- docs/CHANGELOG.txt | 5 +++++ imgui_draw.cpp | 10 ++-------- misc/freetype/imgui_freetype.cpp | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index df9330ea2..4e1c1c1a7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,11 @@ Breaking Changes: Other Changes: +- Fonts: fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which + did erroneously make a copy of the font data, essentially defeating the purpose + of this flag and wasting memory. + Undetected since July 2015 and now spotted by @TellowKrinkle, this is perhaps + the oldest bug in Dear ImGui history (albeit for a rarely used feature)! (#9086) - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 589de9b91..0084dc187 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3052,12 +3052,6 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) font->Sources.push_back(font_cfg); ImFontAtlasBuildUpdatePointers(this); // Pointers to Sources are otherwise dangling after we called Sources.push_back(). - if (font_cfg->FontDataOwnedByAtlas == false) - { - font_cfg->FontDataOwnedByAtlas = true; - font_cfg->FontData = ImMemdup(font_cfg->FontData, (size_t)font_cfg->FontDataSize); - } - // Sanity check // We don't round cfg.SizePixels yet as relative size of merged fonts are used afterwards. if (font_cfg->GlyphExcludeRanges != NULL) @@ -4583,14 +4577,14 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* IM_ASSERT(src->FontLoaderData == NULL); // Initialize helper structure for font loading and verify that the TTF/OTF data is correct - const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src->FontData, src->FontNo); + const int font_offset = stbtt_GetFontOffsetForIndex((const unsigned char*)src->FontData, src->FontNo); if (font_offset < 0) { IM_DELETE(bd_font_data); IM_ASSERT_USER_ERROR(0, "stbtt_GetFontOffsetForIndex(): FontData is incorrect, or FontNo cannot be found."); return false; } - if (!stbtt_InitFont(&bd_font_data->FontInfo, (unsigned char*)src->FontData, font_offset)) + if (!stbtt_InitFont(&bd_font_data->FontInfo, (const unsigned char*)src->FontData, font_offset)) { IM_DELETE(bd_font_data); IM_ASSERT_USER_ERROR(0, "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 16bb9817c..26a087017 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -174,7 +174,7 @@ struct ImGui_ImplFreeType_FontSrcBakedData bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_font_loader_flags) { - FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (FT_Long)src->FontDataSize, (FT_Long)src->FontNo, &FtFace); + FT_Error error = FT_New_Memory_Face(ft_library, (const FT_Byte*)src->FontData, (FT_Long)src->FontDataSize, (FT_Long)src->FontNo, &FtFace); if (error != 0) return false; error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE); From 3a45bae9dc6a9006226d58d2fea35c9fa21ad21c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 24 Nov 2025 18:11:23 +0100 Subject: [PATCH 1528/2359] Backends: Vulkan: helper for creating a swapchain selects VkSwapchainCreateInfoKHR's compositeAlpha based on cap.supportedCompositeAlpha. (#8784) --- backends/imgui_impl_vulkan.cpp | 8 +++++++- docs/CHANGELOG.txt | 4 ++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index c62510829..21a7a8580 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-11-24: Vulkan: Helper for creating a swap-chain (used by examples and multi-viewports) selects VkSwapchainCreateInfoKHR's compositeAlpha based on cap.supportedCompositeAlpha. (#8784) // 2025-10-15: Vulkan: Added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to volk.h header. (#9008) // 2025-09-26: *BREAKING CHANGE*: moved some fields in ImGui_ImplVulkan_InitInfo: init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass, init_info.Subpass --> init_info.PipelineInfoMain.Subpass, init_info.MSAASamples --> init_info.PipelineInfoMain.MSAASamples, init_info.PipelineRenderingCreateInfo --> init_info.PipelineInfoMain.PipelineRenderingCreateInfo. // 2025-09-26: *BREAKING CHANGE*: renamed ImGui_ImplVulkan_MainPipelineCreateInfo to ImGui_ImplVulkan_PipelineInfo. Introduced very recently so shouldn't affect many users. @@ -1637,7 +1638,12 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | image_usage; info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // Assume that graphics family == present family info.preTransform = (cap.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR : cap.currentTransform; - info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + if (cap.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) + info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + else if (cap.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) + info.compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR; + else + IM_ASSERT(false && "No supported composite alpha mode found!"); info.presentMode = wd->PresentMode; info.clipped = VK_TRUE; info.oldSwapchain = old_swapchain; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4e1c1c1a7..5a72aade9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,10 @@ Other Changes: the oldest bug in Dear ImGui history (albeit for a rarely used feature)! (#9086) - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] +- Backends: + - Vulkan: helper for creating a swapchain (used by examples and multi-viewports) + selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on + `cap.supportedCompositeAlpha`. (#8784) [@FelixStach] ----------------------------------------------------------------------- From 3fef0d553df7d32c373fc5d1ab484a0097c44a0b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Nov 2025 14:11:22 +0100 Subject: [PATCH 1529/2359] Textures: fixed a building issue when ImTextureID is defined as a struct. + Added CI for this case. --- .github/workflows/build.yml | 17 ++++++++++++++++- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 20 +++++++++++++------- imgui_draw.cpp | 6 +++--- imgui_internal.h | 2 +- 5 files changed, 35 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3ee729717..482804b47 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -343,7 +343,7 @@ jobs: EOF g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - - name: Build example_null (with large ImDrawIdx + pointer ImTextureID) + - name: Build example_null (with large ImDrawIdx + custom ImTextureID) run: | cat > example_single_file.cpp <<'EOF' @@ -356,6 +356,21 @@ jobs: EOF g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + // Test build ImTextureID defined as a struct + struct SomeType { int a = 0; int b = 0; }; + #define ImTextureID SomeType + #define ImTextureID_Invalid SomeType() + inline bool operator==(const SomeType& lhs, const SomeType& rhs) { return lhs.a == rhs.a && lhs.b == rhs.b; } + inline bool operator!=(const SomeType& lhs, const SomeType& rhs) { return lhs.a != rhs.a || lhs.b != rhs.b; } + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (with IMGUI_DISABLE_OBSOLETE_FUNCTIONS) run: | cat > example_single_file.cpp <<'EOF' diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5a72aade9..ed3a65a4a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,8 @@ Other Changes: of this flag and wasting memory. Undetected since July 2015 and now spotted by @TellowKrinkle, this is perhaps the oldest bug in Dear ImGui history (albeit for a rarely used feature)! (#9086) +- Textures: + - Fixed a building issue when ImTextureID is defined as a struct. - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Backends: diff --git a/imgui.cpp b/imgui.cpp index 2cd202386..85d2622fd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16121,14 +16121,20 @@ void ImGui::UpdateDebugToolFlashStyleColor() DebugFlashStyleColorStop(); } +ImU64 ImGui::DebugTextureIDToU64(ImTextureID tex_id) +{ + ImU64 v = 0; + memcpy(&v, &tex_id, ImMin(sizeof(ImU64), sizeof(tex_id))); + return v; +} + static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id) { - union { void* ptr; int integer; } tex_id_opaque; - memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id))); + ImU64 v = ImGui::DebugTextureIDToU64(tex_id); if (sizeof(tex_id) >= sizeof(void*)) - ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr); + ImFormatString(buf, buf_size, "0x%p", v); else - ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer); + ImFormatString(buf, buf_size, "0x%04X", v); return buf; } @@ -16137,7 +16143,7 @@ static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTe char* buf_end = buf + buf_size; if (tex_ref._TexData != NULL) buf += ImFormatString(buf, buf_end - buf, "#%03d: ", tex_ref._TexData->UniqueID); - return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), tex_ref.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID() + return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), tex_ref.GetTexID()); } #ifdef IMGUI_ENABLE_FREETYPE @@ -16323,9 +16329,9 @@ void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRe } PopStyleVar(); - char texid_desc[30]; + char texref_desc[30]; Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors); - Text("TexID = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->GetTexRef()), tex->BackendUserData); + Text("TexRef = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texref_desc, IM_ARRAYSIZE(texref_desc), tex->GetTexRef()), tex->BackendUserData); TreePop(); } PopID(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0084dc187..88ad02966 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4538,16 +4538,16 @@ void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) if (tex->Status == ImTextureStatus_WantCreate) IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: create %dx%d\n", tex->UniqueID, tex->Width, tex->Height); else if (tex->Status == ImTextureStatus_WantDestroy) - IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: destroy %dx%d, texid=0x%" IM_PRIX64 ", backend_data=%p\n", tex->UniqueID, tex->Width, tex->Height, IM_TEXTUREID_TO_U64(tex->TexID), tex->BackendUserData); + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: destroy %dx%d, texid=0x%" IM_PRIX64 ", backend_data=%p\n", tex->UniqueID, tex->Width, tex->Height, ImGui::DebugTextureIDToU64(tex->TexID), tex->BackendUserData); else if (tex->Status == ImTextureStatus_WantUpdates) { - IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, IM_TEXTUREID_TO_U64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData); + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, ImGui::DebugTextureIDToU64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData); for (const ImTextureRect& r : tex->Updates) { IM_UNUSED(r); IM_ASSERT(r.x >= 0 && r.y >= 0); IM_ASSERT(r.x + r.w <= tex->Width && r.y + r.h <= tex->Height); // In theory should subtract PackPadding but it's currently part of atlas and mid-frame change would wreck assert. - //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, IM_TEXTUREID_TO_U64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData); + //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, ImGui::DebugTextureIDToU64(tex->TexID), (ImU64)(intptr_t)tex->BackendUserData); } } } diff --git a/imgui_internal.h b/imgui_internal.h index f5a90918f..557a380c7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -335,7 +335,6 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IM_PRIu64 "llu" #define IM_PRIX64 "llX" #endif -#define IM_TEXTUREID_TO_U64(_TEXID) ((ImU64)(intptr_t)(_TEXID)) //----------------------------------------------------------------------------- // [SECTION] Generic helpers @@ -3697,6 +3696,7 @@ namespace ImGui IMGUI_API bool DebugBreakButton(const char* label, const char* description_of_location); IMGUI_API void DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location); IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); + IMGUI_API ImU64 DebugTextureIDToU64(ImTextureID tex_id); IMGUI_API void DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end); IMGUI_API void DebugNodeColumns(ImGuiOldColumns* columns); IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label); From e768f91dc210149626d0c1b5d4db1bd7d6da28e9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Nov 2025 14:18:51 +0100 Subject: [PATCH 1530/2359] Textures: fixed displaying texture # in metrics/debugger. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 18 +++++------------- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ed3a65a4a..63ee6c4e0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,7 @@ Other Changes: the oldest bug in Dear ImGui history (albeit for a rarely used feature)! (#9086) - Textures: - Fixed a building issue when ImTextureID is defined as a struct. + - Fixed displaying texture # in Metrics/Debugger window. - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Backends: diff --git a/imgui.cpp b/imgui.cpp index 85d2622fd..6cbdcea1e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16124,26 +16124,18 @@ void ImGui::UpdateDebugToolFlashStyleColor() ImU64 ImGui::DebugTextureIDToU64(ImTextureID tex_id) { ImU64 v = 0; - memcpy(&v, &tex_id, ImMin(sizeof(ImU64), sizeof(tex_id))); + memcpy(&v, &tex_id, ImMin(sizeof(ImU64), sizeof(ImTextureID))); return v; } -static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id) -{ - ImU64 v = ImGui::DebugTextureIDToU64(tex_id); - if (sizeof(tex_id) >= sizeof(void*)) - ImFormatString(buf, buf_size, "0x%p", v); - else - ImFormatString(buf, buf_size, "0x%04X", v); - return buf; -} - static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTextureRef tex_ref) { + char* buf_p = buf; char* buf_end = buf + buf_size; if (tex_ref._TexData != NULL) - buf += ImFormatString(buf, buf_end - buf, "#%03d: ", tex_ref._TexData->UniqueID); - return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), tex_ref.GetTexID()); + buf_p += ImFormatString(buf_p, buf_end - buf_p, "#%03d: ", tex_ref._TexData->UniqueID); + buf_p += ImFormatString(buf_p, buf_end - buf_p, "0x%X", ImGui::DebugTextureIDToU64(tex_ref.GetTexID())); + return buf; } #ifdef IMGUI_ENABLE_FREETYPE From d981b33dd0c95bf8ed2f0918fc7425c26f5f1ce4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Nov 2025 14:24:55 +0100 Subject: [PATCH 1531/2359] Textures: amend to please static analyzer. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 6cbdcea1e..f878a116c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16134,7 +16134,7 @@ static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTe char* buf_end = buf + buf_size; if (tex_ref._TexData != NULL) buf_p += ImFormatString(buf_p, buf_end - buf_p, "#%03d: ", tex_ref._TexData->UniqueID); - buf_p += ImFormatString(buf_p, buf_end - buf_p, "0x%X", ImGui::DebugTextureIDToU64(tex_ref.GetTexID())); + ImFormatString(buf_p, buf_end - buf_p, "0x%X", ImGui::DebugTextureIDToU64(tex_ref.GetTexID())); return buf; } From 285e3042badff61de25aac44082dc757932e463c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Nov 2025 14:49:11 +0100 Subject: [PATCH 1532/2359] Docs: tweaks. Add reference to imgui-module from main README. (#9092, #8868) --- docs/CHANGELOG.txt | 3 ++- docs/README.md | 4 +++- imgui.cpp | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 63ee6c4e0..87ce9e528 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,7 +56,8 @@ Other Changes: - Backends: - Vulkan: helper for creating a swapchain (used by examples and multi-viewports) selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on - `cap.supportedCompositeAlpha`. (#8784) [@FelixStach] + `cap.supportedCompositeAlpha`, which seems to be required on some Android + devices. (#8784) [@FelixStach] ----------------------------------------------------------------------- diff --git a/docs/README.md b/docs/README.md index 45977e74f..8cc36713a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -39,10 +39,12 @@ Dear ImGui is particularly suited to integration in game engines (for tooling), ### Usage -**The core of Dear ImGui is self-contained within a few platform-agnostic files** which you can easily compile in your application/engine. They are all the files in the root folder of the repository (imgui*.cpp, imgui*.h). **No specific build process is required**. You can add the .cpp files into your existing project. +**The core of Dear ImGui is self-contained within a few platform-agnostic files** which you can easily compile in your application/engine. They are all the files in the root folder of the repository (`imgui*.cpp`, `imgui*.h`). **No specific build process is required**: you can add all files into your existing project. **Backends for a variety of graphics API and rendering platforms** are provided in the [backends/](https://github.com/ocornut/imgui/tree/master/backends) folder, along with example applications in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui. +C++20 users wishing to use a module may the use [stripe2933/imgui-module](https://github.com/stripe2933/imgui-module) third-party extension. + See the [Getting Started & Integration](#getting-started--integration) section of this document for more details. After Dear ImGui is set up in your application, you can use it from \_anywhere\_ in your program loop: diff --git a/imgui.cpp b/imgui.cpp index f878a116c..fd005d39c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4328,7 +4328,7 @@ void ImGui::Initialize() g.Viewports.push_back(viewport); g.TempBuffer.resize(1024 * 3 + 1, 0); - // Build KeysMayBeCharInput[] lookup table (1 bool per named key) + // Build KeysMayBeCharInput[] lookup table (1 bit per named key) for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9) || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period From fd887f5241eb43f68e8086c5abec83ec967a990e Mon Sep 17 00:00:00 2001 From: Leon Lysak Date: Wed, 26 Nov 2025 14:51:22 +0100 Subject: [PATCH 1533/2359] Backends: SDL_GPU3: use MSL on macOS and MetalLib on iOS to fix shader compatibility. (#9076) Edit original PR to keep metallib shader binary since next commit is going to use them. --- backends/imgui_impl_sdlgpu3.cpp | 15 +++++++++++ backends/imgui_impl_sdlgpu3_shaders.h | 34 +++++++++++++++++++++++++ backends/sdlgpu3/build_instructions.txt | 2 ++ docs/CHANGELOG.txt | 3 +++ examples/example_sdl3_sdlgpu3/main.cpp | 2 +- 5 files changed, 55 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 8d8f0a4c4..197e9c411 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -22,6 +22,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG +// 2025-11-26: Use MSL shaders on macOS to support macOS 10.14+ (instead of Metallib shaders requiring macOS 14+). Requires calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-08-20: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and ImGui_ImplSDLGPU3_InitInfo::PresentMode to configure how secondary viewports are created. // 2025-08-08: *BREAKING* Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) @@ -452,6 +453,19 @@ static void ImGui_ImplSDLGPU3_CreateShaders() #ifdef __APPLE__ else { +#include +#if TARGET_OS_OSX + // macOS: using MSL source + vertex_shader_info.entrypoint = "main0"; + vertex_shader_info.format = SDL_GPU_SHADERFORMAT_MSL; + vertex_shader_info.code = msl_vertex; + vertex_shader_info.code_size = sizeof(msl_vertex); + fragment_shader_info.entrypoint = "main0"; + fragment_shader_info.format = SDL_GPU_SHADERFORMAT_MSL; + fragment_shader_info.code = msl_fragment; + fragment_shader_info.code_size = sizeof(msl_fragment); +#elif TARGET_OS_IPHONE + // iOS device: using metallib blobs vertex_shader_info.entrypoint = "main0"; vertex_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; vertex_shader_info.code = metallib_vertex; @@ -460,6 +474,7 @@ static void ImGui_ImplSDLGPU3_CreateShaders() fragment_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; fragment_shader_info.code = metallib_fragment; fragment_shader_info.code_size = sizeof(metallib_fragment); +#endif } #endif bd->VertexShader = SDL_CreateGPUShader(v->Device, &vertex_shader_info); diff --git a/backends/imgui_impl_sdlgpu3_shaders.h b/backends/imgui_impl_sdlgpu3_shaders.h index f792aa6ab..ca94075f1 100644 --- a/backends/imgui_impl_sdlgpu3_shaders.h +++ b/backends/imgui_impl_sdlgpu3_shaders.h @@ -221,6 +221,40 @@ const uint8_t metallib_fragment[3787] = { 148,161,0,0,0,0,109,97,105,110,48,97,105,114,46,115,97,109,112,108,101,95,116,101,120,116,117,114,101,95,50,100,46,118,52,102,51,50,51,50,48,50,51,46,51,54,56,97,105,114,54,52,45,97, 112,112,108,101,45,109,97,99,111,115,120,49,52,46,48,46,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +static uint8_t msl_vertex[800] = +{ + 35,105,110,99,108,117,100,101,32,60,109,101,116,97,108,95,115,116,100,108,105,98,62,10,35,105,110,99,108,117,100,101,32,60,115,105,109,100,47,115,105,109,100,46,104,62,10,10,117,115, + 105,110,103,32,110,97,109,101,115,112,97,99,101,32,109,101,116,97,108,59,10,10,115,116,114,117,99,116,32,95,57,10,123,10,32,32,32,32,102,108,111,97,116,52,32,67,111,108,111,114,59, + 10,32,32,32,32,102,108,111,97,116,50,32,85,86,59,10,125,59,10,10,115,116,114,117,99,116,32,85,66,79,10,123,10,32,32,32,32,102,108,111,97,116,50,32,117,83,99,97,108,101,59,10,32,32, + 32,32,102,108,111,97,116,50,32,117,84,114,97,110,115,108,97,116,101,59,10,125,59,10,10,115,116,114,117,99,116,32,109,97,105,110,48,95,111,117,116,10,123,10,32,32,32,32,102,108,111, + 97,116,52,32,79,117,116,95,67,111,108,111,114,32,91,91,117,115,101,114,40,108,111,99,110,48,41,93,93,59,10,32,32,32,32,102,108,111,97,116,50,32,79,117,116,95,85,86,32,91,91,117,115, + 101,114,40,108,111,99,110,49,41,93,93,59,10,32,32,32,32,102,108,111,97,116,52,32,103,108,95,80,111,115,105,116,105,111,110,32,91,91,112,111,115,105,116,105,111,110,93,93,59,10,125, + 59,10,10,115,116,114,117,99,116,32,109,97,105,110,48,95,105,110,10,123,10,32,32,32,32,102,108,111,97,116,50,32,97,80,111,115,32,91,91,97,116,116,114,105,98,117,116,101,40,48,41,93, + 93,59,10,32,32,32,32,102,108,111,97,116,50,32,97,85,86,32,91,91,97,116,116,114,105,98,117,116,101,40,49,41,93,93,59,10,32,32,32,32,102,108,111,97,116,52,32,97,67,111,108,111,114,32, + 91,91,97,116,116,114,105,98,117,116,101,40,50,41,93,93,59,10,125,59,10,10,118,101,114,116,101,120,32,109,97,105,110,48,95,111,117,116,32,109,97,105,110,48,40,109,97,105,110,48,95,105, + 110,32,105,110,32,91,91,115,116,97,103,101,95,105,110,93,93,44,32,99,111,110,115,116,97,110,116,32,85,66,79,38,32,117,98,111,32,91,91,98,117,102,102,101,114,40,48,41,93,93,41,10,123, + 10,32,32,32,32,109,97,105,110,48,95,111,117,116,32,111,117,116,32,61,32,123,125,59,10,32,32,32,32,95,57,32,79,117,116,32,61,32,123,125,59,10,32,32,32,32,79,117,116,46,67,111,108,111, + 114,32,61,32,105,110,46,97,67,111,108,111,114,59,10,32,32,32,32,79,117,116,46,85,86,32,61,32,105,110,46,97,85,86,59,10,32,32,32,32,111,117,116,46,103,108,95,80,111,115,105,116,105, + 111,110,32,61,32,102,108,111,97,116,52,40,40,105,110,46,97,80,111,115,32,42,32,117,98,111,46,117,83,99,97,108,101,41,32,43,32,117,98,111,46,117,84,114,97,110,115,108,97,116,101,44, + 32,48,46,48,44,32,49,46,48,41,59,10,32,32,32,32,111,117,116,46,103,108,95,80,111,115,105,116,105,111,110,46,121,32,42,61,32,40,45,49,46,48,41,59,10,32,32,32,32,111,117,116,46,79,117, + 116,95,67,111,108,111,114,32,61,32,79,117,116,46,67,111,108,111,114,59,10,32,32,32,32,111,117,116,46,79,117,116,95,85,86,32,61,32,79,117,116,46,85,86,59,10,32,32,32,32,114,101,116, + 117,114,110,32,111,117,116,59,10,125,10,10, +}; +static uint8_t msl_fragment[580] = +{ + 35,105,110,99,108,117,100,101,32,60,109,101,116,97,108,95,115,116,100,108,105,98,62,10,35,105,110,99,108,117,100,101,32,60,115,105,109,100,47,115,105,109,100,46,104,62,10,10,117,115, + 105,110,103,32,110,97,109,101,115,112,97,99,101,32,109,101,116,97,108,59,10,10,115,116,114,117,99,116,32,95,49,49,10,123,10,32,32,32,32,102,108,111,97,116,52,32,67,111,108,111,114, + 59,10,32,32,32,32,102,108,111,97,116,50,32,85,86,59,10,125,59,10,10,115,116,114,117,99,116,32,109,97,105,110,48,95,111,117,116,10,123,10,32,32,32,32,102,108,111,97,116,52,32,102,67, + 111,108,111,114,32,91,91,99,111,108,111,114,40,48,41,93,93,59,10,125,59,10,10,115,116,114,117,99,116,32,109,97,105,110,48,95,105,110,10,123,10,32,32,32,32,102,108,111,97,116,52,32, + 73,110,95,67,111,108,111,114,32,91,91,117,115,101,114,40,108,111,99,110,48,41,93,93,59,10,32,32,32,32,102,108,111,97,116,50,32,73,110,95,85,86,32,91,91,117,115,101,114,40,108,111,99, + 110,49,41,93,93,59,10,125,59,10,10,102,114,97,103,109,101,110,116,32,109,97,105,110,48,95,111,117,116,32,109,97,105,110,48,40,109,97,105,110,48,95,105,110,32,105,110,32,91,91,115,116, + 97,103,101,95,105,110,93,93,44,32,116,101,120,116,117,114,101,50,100,60,102,108,111,97,116,62,32,115,84,101,120,116,117,114,101,32,91,91,116,101,120,116,117,114,101,40,48,41,93,93, + 44,32,115,97,109,112,108,101,114,32,115,84,101,120,116,117,114,101,83,109,112,108,114,32,91,91,115,97,109,112,108,101,114,40,48,41,93,93,41,10,123,10,32,32,32,32,109,97,105,110,48, + 95,111,117,116,32,111,117,116,32,61,32,123,125,59,10,32,32,32,32,95,49,49,32,73,110,32,61,32,123,125,59,10,32,32,32,32,73,110,46,67,111,108,111,114,32,61,32,105,110,46,73,110,95,67, + 111,108,111,114,59,10,32,32,32,32,73,110,46,85,86,32,61,32,105,110,46,73,110,95,85,86,59,10,32,32,32,32,111,117,116,46,102,67,111,108,111,114,32,61,32,73,110,46,67,111,108,111,114, + 32,42,32,115,84,101,120,116,117,114,101,46,115,97,109,112,108,101,40,115,84,101,120,116,117,114,101,83,109,112,108,114,44,32,73,110,46,85,86,41,59,10,32,32,32,32,114,101,116,117,114, + 110,32,111,117,116,59,10,125,10,10, +}; #elif TARGET_OS_IPHONE const uint8_t metallib_vertex[3876] = { 77,84,76,66,1,0,2,0,7,0,0,130,18,0,1,0,36,15,0,0,0,0,0,0,88,0,0,0,0,0,0,0,123,0,0,0,0,0,0,0,219,0,0,0,0,0,0,0,49,0,0,0,0,0,0,0,12,1,0,0,0,0,0,0,8,0,0,0,0,0,0,0,20,1,0,0,0,0,0,0,16, diff --git a/backends/sdlgpu3/build_instructions.txt b/backends/sdlgpu3/build_instructions.txt index 25f4a5d28..79a09200e 100644 --- a/backends/sdlgpu3/build_instructions.txt +++ b/backends/sdlgpu3/build_instructions.txt @@ -34,6 +34,8 @@ Instructions to rebuild imgui_impl_sdlgpu3_shaders.h xcrun -sdk macosx metallib -o vertex.metallib -c vertex.ir xcrun -sdk macosx metallib -o fragment.metallib -c fragment.ir + note: use .metal outputs for updating msl_vertex / msl_fragment variables, and use .metallib outputs for metallib_vertex / metallib_fragment variables + Proceed to step 4 diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 87ce9e528..488eba81d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,9 @@ Other Changes: - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Backends: + - SDL_GPU3: on macOS, use MSL shaders in order to support macOS 10.14+ + (instead of Metallib shaders requiring macOS 14+). (#9076) [@Niminem] + Requires calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. - Vulkan: helper for creating a swapchain (used by examples and multi-viewports) selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on `cap.supportedCompositeAlpha`, which seems to be required on some Android diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 84b0a254f..a33c0cfe9 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -47,7 +47,7 @@ int main(int, char**) SDL_ShowWindow(window); // Create GPU Device - SDL_GPUDevice* gpu_device = SDL_CreateGPUDevice(SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_DXIL | SDL_GPU_SHADERFORMAT_METALLIB,true,nullptr); + SDL_GPUDevice* gpu_device = SDL_CreateGPUDevice(SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_DXIL | SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_METALLIB, true, nullptr); if (gpu_device == nullptr) { printf("Error: SDL_CreateGPUDevice(): %s\n", SDL_GetError()); From 75db81cf0882992b7c750ee76afaa0d7ed57877c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Nov 2025 15:05:05 +0100 Subject: [PATCH 1534/2359] Backends: SDL_GPU3: select between metallib and MSL shaders based on availability. (#9076) Amend fd887f5 --- backends/imgui_impl_sdlgpu3.cpp | 49 +++++++++++++++++---------------- docs/CHANGELOG.txt | 6 ++-- 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 197e9c411..e5934c302 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -22,7 +22,7 @@ // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info. // CHANGELOG -// 2025-11-26: Use MSL shaders on macOS to support macOS 10.14+ (instead of Metallib shaders requiring macOS 14+). Requires calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. +// 2025-11-26: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-08-20: Added ImGui_ImplSDLGPU3_InitInfo::SwapchainComposition and ImGui_ImplSDLGPU3_InitInfo::PresentMode to configure how secondary viewports are created. // 2025-08-08: *BREAKING* Changed ImTextureID type from SDL_GPUTextureSamplerBinding* to SDL_GPUTexture*, which is more natural and easier for user to manage. If you need to change the current sampler, you can access the ImGui_ImplSDLGPU3_RenderState struct. (#8866, #8163, #7998, #7988) @@ -453,28 +453,31 @@ static void ImGui_ImplSDLGPU3_CreateShaders() #ifdef __APPLE__ else { -#include -#if TARGET_OS_OSX - // macOS: using MSL source - vertex_shader_info.entrypoint = "main0"; - vertex_shader_info.format = SDL_GPU_SHADERFORMAT_MSL; - vertex_shader_info.code = msl_vertex; - vertex_shader_info.code_size = sizeof(msl_vertex); - fragment_shader_info.entrypoint = "main0"; - fragment_shader_info.format = SDL_GPU_SHADERFORMAT_MSL; - fragment_shader_info.code = msl_fragment; - fragment_shader_info.code_size = sizeof(msl_fragment); -#elif TARGET_OS_IPHONE - // iOS device: using metallib blobs - vertex_shader_info.entrypoint = "main0"; - vertex_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; - vertex_shader_info.code = metallib_vertex; - vertex_shader_info.code_size = sizeof(metallib_vertex); - fragment_shader_info.entrypoint = "main0"; - fragment_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; - fragment_shader_info.code = metallib_fragment; - fragment_shader_info.code_size = sizeof(metallib_fragment); -#endif + SDL_GPUShaderFormat supported_formats = SDL_GetGPUShaderFormats(v->Device); + if (supported_formats & SDL_GPU_SHADERFORMAT_METALLIB) + { + // Using metallib blobs (macOS 14+, iOS) + vertex_shader_info.entrypoint = "main0"; + vertex_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; + vertex_shader_info.code = metallib_vertex; + vertex_shader_info.code_size = sizeof(metallib_vertex); + fragment_shader_info.entrypoint = "main0"; + fragment_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB; + fragment_shader_info.code = metallib_fragment; + fragment_shader_info.code_size = sizeof(metallib_fragment); + } + else if (supported_formats & SDL_GPU_SHADERFORMAT_MSL) + { + // macOS: using MSL source + vertex_shader_info.entrypoint = "main0"; + vertex_shader_info.format = SDL_GPU_SHADERFORMAT_MSL; + vertex_shader_info.code = msl_vertex; + vertex_shader_info.code_size = sizeof(msl_vertex); + fragment_shader_info.entrypoint = "main0"; + fragment_shader_info.format = SDL_GPU_SHADERFORMAT_MSL; + fragment_shader_info.code = msl_fragment; + fragment_shader_info.code_size = sizeof(msl_fragment); + } } #endif bd->VertexShader = SDL_CreateGPUShader(v->Device, &vertex_shader_info); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 488eba81d..ee3186bd9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,9 +54,9 @@ Other Changes: - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Backends: - - SDL_GPU3: on macOS, use MSL shaders in order to support macOS 10.14+ - (instead of Metallib shaders requiring macOS 14+). (#9076) [@Niminem] - Requires calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. + - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ + (vs Metallib shaders requiring macOS 14+). Requires application calling + SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. (#9076) [@Niminem] - Vulkan: helper for creating a swapchain (used by examples and multi-viewports) selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on `cap.supportedCompositeAlpha`, which seems to be required on some Android From f0699effedb45108a0de18b9e8810e5f84597d25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Tassoux?= Date: Sat, 22 Nov 2025 12:47:10 +0100 Subject: [PATCH 1535/2359] Examples: Win32+DirectX12: Disable breaking on the D3D12_MESSAGE_ID_FENCE_ZERO_WAIT warning. (#9093, #9084) --- examples/example_win32_directx12/main.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 5a8dc0381..5430fde26 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -351,6 +351,15 @@ bool CreateDeviceD3D(HWND hWnd) pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true); pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true); pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, true); + + // Disable breaking on this warning because of a suspected bug in the D3D12 SDK layer, see #9084 for details. + const int D3D12_MESSAGE_ID_FENCE_ZERO_WAIT_ = 1424; // not in all copies of d3d12sdklayers.h + D3D12_MESSAGE_ID disabledMessages[] = { (D3D12_MESSAGE_ID)D3D12_MESSAGE_ID_FENCE_ZERO_WAIT_ }; + D3D12_INFO_QUEUE_FILTER filter = {}; + filter.DenyList.NumIDs = 1; + filter.DenyList.pIDList = disabledMessages; + pInfoQueue->AddStorageFilterEntries(&filter); + pInfoQueue->Release(); pdx12Debug->Release(); } From c36162fc6c86ca8b53b06d1c7229ec1b161d22a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Nov 2025 17:29:37 +0100 Subject: [PATCH 1536/2359] Internals: add SetContextName() helper. (#9097) Amend 37c243b. --- imgui.cpp | 7 +++++++ imgui_internal.h | 11 ++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fd005d39c..6ca0d0148 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4443,6 +4443,13 @@ void ImGui::Shutdown() g.Initialized = false; } +// When using multiple context it can be helpful to give name a name. +// (A) Will be visible in debugger, (B) Will be included in all IMGUI_DEBUG_LOG() calls, (C) Should be <= 15 characters long. +void ImGui::SetContextName(ImGuiContext* ctx, const char* name) +{ + ImStrncpy(ctx->ContextName, name, IM_ARRAYSIZE(ctx->ContextName)); +} + // No specific ordering/dependency support, will see as needed ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook) { diff --git a/imgui_internal.h b/imgui_internal.h index 557a380c7..af90db9df 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3193,6 +3193,12 @@ namespace ImGui IMGUI_API void Initialize(); IMGUI_API void Shutdown(); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext(). + // Context name & generic context hooks + IMGUI_API void SetContextName(ImGuiContext* ctx, const char* name); + IMGUI_API ImGuiID AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook); + IMGUI_API void RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_to_remove); + IMGUI_API void CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType type); + // NewFrame IMGUI_API void UpdateInputEvents(bool trickle_fast_inputs); IMGUI_API void UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos); @@ -3202,11 +3208,6 @@ namespace ImGui IMGUI_API void UpdateMouseMovingWindowNewFrame(); IMGUI_API void UpdateMouseMovingWindowEndFrame(); - // Generic context hooks - IMGUI_API ImGuiID AddContextHook(ImGuiContext* context, const ImGuiContextHook* hook); - IMGUI_API void RemoveContextHook(ImGuiContext* context, ImGuiID hook_to_remove); - IMGUI_API void CallContextHooks(ImGuiContext* context, ImGuiContextHookType type); - // Viewports IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale); IMGUI_API void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport); From 9c75ef5a6158befe6c0611dab6f50c8ff70a228a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Nov 2025 18:25:30 +0100 Subject: [PATCH 1537/2359] Tables: clarify TableNextRow() row_height and adjust demo to make this clearer (demo height were arbitrary and therefore misleading). --- docs/CHANGELOG.txt | 3 +++ imgui.h | 2 +- imgui_demo.cpp | 7 ++++--- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ee3186bd9..9cc1edb6f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,9 @@ Other Changes: selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on `cap.supportedCompositeAlpha`, which seems to be required on some Android devices. (#8784) [@FelixStach] +- Examples: + - Win32+DirectX12: ignore seemingly incorrect D3D12_MESSAGE_ID_FENCE_ZERO_WAIT + warning on startups on some setups. (#9084, #9093) [@RT2Code, @LeoGautheron] ----------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index fe1385da2..ac64c2ded 100644 --- a/imgui.h +++ b/imgui.h @@ -897,7 +897,7 @@ namespace ImGui // - 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 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. + 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. IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 35451730c..1e49dd6fa 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6509,7 +6509,7 @@ static void DemoWindowTables() ImGui::TableNextColumn(); ImGui::Text("A0 Row 0"); { - float rows_height = TEXT_BASE_HEIGHT * 2; + float rows_height = (TEXT_BASE_HEIGHT * 2.0f) + (ImGui::GetStyle().CellPadding.y * 2.0f); if (ImGui::BeginTable("table_nested2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) { ImGui::TableSetupColumn("B0"); @@ -6551,7 +6551,7 @@ static void DemoWindowTables() { for (int row = 0; row < 8; row++) { - float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0.30f * row); + float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0.30f * row + ImGui::GetStyle().CellPadding.y * 2.0f); ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); ImGui::TableNextColumn(); ImGui::Text("min_row_height = %.2f", min_row_height); @@ -6655,9 +6655,10 @@ static void DemoWindowTables() ImGui::SameLine(); if (ImGui::BeginTable("table3", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f))) { + const float rows_height = TEXT_BASE_HEIGHT * 1.5f + ImGui::GetStyle().CellPadding.y * 2.0f; for (int row = 0; row < 3; row++) { - ImGui::TableNextRow(0, TEXT_BASE_HEIGHT * 1.5f); + ImGui::TableNextRow(0, rows_height); for (int column = 0; column < 3; column++) { ImGui::TableNextColumn(); From ae873b1e0d2fedd971973aa6e00e2901ea92b1d0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Nov 2025 12:33:49 +0100 Subject: [PATCH 1538/2359] Misc: rename extraneous parenthesizes from return statements. --- examples/example_apple_opengl2/main.mm | 4 ++-- imgui.cpp | 16 ++++++++-------- imgui_demo.cpp | 6 +++--- imgui_internal.h | 2 +- imgui_tables.cpp | 5 +++++ imgui_widgets.cpp | 2 +- 6 files changed, 20 insertions(+), 15 deletions(-) diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index d7aa7eb5b..14f3f4321 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -169,7 +169,7 @@ -(NSWindow*)window { if (_window != nil) - return (_window); + return _window; NSRect viewRect = NSMakeRect(100.0, 100.0, 100.0 + 1280.0, 100 + 800.0); @@ -179,7 +179,7 @@ [_window setOpaque:YES]; [_window makeKeyAndOrderFront:NSApp]; - return (_window); + return _window; } -(void)setupMenu diff --git a/imgui.cpp b/imgui.cpp index 6ca0d0148..640d6b34a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2029,7 +2029,7 @@ bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; - return ((b1 == b2) && (b2 == b3)); + return (b1 == b2) && (b2 == b3); } void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w) @@ -3129,7 +3129,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE static bool GetSkipItemForListClipping() { ImGuiContext& g = *GImGui; - return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems); + return g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems; } static void ImGuiListClipper_SortAndFuseRanges(ImVector& ranges, int offset = 0) @@ -5290,7 +5290,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() static bool IsWindowActiveAndVisible(ImGuiWindow* window) { - return (window->Active) && (!window->Hidden); + return window->Active && !window->Hidden; } // The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app) @@ -5692,7 +5692,7 @@ static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs) return d; if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) return d; - return (a->BeginOrderWithinParent - b->BeginOrderWithinParent); + return a->BeginOrderWithinParent - b->BeginOrderWithinParent; } static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window) @@ -6168,7 +6168,7 @@ bool ImGui::IsItemDeactivated() ImGuiContext& g = *GImGui; if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated) return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0; - return (g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount); + return g.DeactivatedItemData.ID == g.LastItemData.ID && g.LastItemData.ID != 0 && g.DeactivatedItemData.ElapseFrame >= g.FrameCount; } bool ImGui::IsItemDeactivatedAfterEdit() @@ -9394,7 +9394,7 @@ int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, flo if (t0 >= t1) return 0; if (repeat_rate <= 0.0f) - return (t0 < repeat_delay) && (t1 >= repeat_delay); + return t0 < repeat_delay && t1 >= repeat_delay; const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate); const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate); const int count = count_t1 - count_t0; @@ -10513,7 +10513,7 @@ bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id) ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key); if (owner_id == ImGuiKeyOwner_Any) - return (owner_data->LockThisFrame == false); + return owner_data->LockThisFrame == false; // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things. @@ -12693,7 +12693,7 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) if (flags & ImGuiFocusedFlags_ChildWindows) return IsWindowChildOf(ref_window, cur_window, popup_hierarchy); else - return (ref_window == cur_window); + return ref_window == cur_window; } static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1e49dd6fa..8c4a2a426 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2530,7 +2530,7 @@ struct ExampleDualListBox { const int* a = (const int*)lhs; const int* b = (const int*)rhs; - return (*a - *b); + return *a - *b; } void SortItems(int n) { @@ -5545,7 +5545,7 @@ struct MyItem // qsort() is instable so always return a way to differentiate items. // Your own compare function may want to avoid fallback on implicit sort specs. // e.g. a Name compare if it wasn't already part of the sort specs. - return (a->ID - b->ID); + return a->ID - b->ID; } }; const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL; @@ -10516,7 +10516,7 @@ struct ExampleAsset if (delta < 0) return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; } - return ((int)a->ID - (int)b->ID); + return (int)a->ID - (int)b->ID; } }; const ImGuiTableSortSpecs* ExampleAsset::s_current_sort_specs = NULL; diff --git a/imgui_internal.h b/imgui_internal.h index af90db9df..788d1d5e6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3651,7 +3651,7 @@ namespace ImGui IMGUI_API void InputTextDeactivateHook(ImGuiID id); IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); 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); - inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } + inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return g.ActiveId == id && g.TempInputId == 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. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 25d945d2a..0a259e0c9 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2458,6 +2458,11 @@ void ImGui::TableUpdateColumnsWeightFromWidth(ImGuiTable* table) // - TableDrawBorders() [Internal] //------------------------------------------------------------------------- + +// FIXME: This could be abstracted and merged with PushColumnsBackground(), by creating a generic struct +// with storage for backup cliprect + backup channel + storage for splitter pointer, new clip rect. +// This would slightly simplify caller code. + // Bg2 is used by Selectable (and possibly other widgets) to render to the background. // Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect. void ImGui::TablePushBackgroundChannel() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9009bbc8c..1a13eea3d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1834,7 +1834,7 @@ static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs) const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs; if (int d = (int)(b->Width - a->Width)) return d; - return (b->Index - a->Index); + return b->Index - a->Index; } // Shrink excess width from a set of item, by removing width from the larger items first. From 1f5466579938ac0a6c7b4df3fefa6761421513a5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Nov 2025 19:46:13 +0100 Subject: [PATCH 1539/2359] Menus: fixed MenuItem() label baseline when using inside a line with an offset. Amend f8fae022704 --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 9 +++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9cc1edb6f..f317f620b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other Changes: - Textures: - Fixed a building issue when ImTextureID is defined as a struct. - Fixed displaying texture # in Metrics/Debugger window. +- Menus: fixed MenuItem() label baseline when using inside a line with an offset. - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Backends: diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1a13eea3d..d917d30a1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9434,21 +9434,22 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w); // Feedback for next frame float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w); + ImVec2 text_pos(pos.x, pos.y + window->DC.CurrLineTextBaseOffset); pressed = Selectable("", false, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y)); if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) { - RenderText(pos + ImVec2(offsets->OffsetLabel, 0.0f), label); + RenderText(text_pos + ImVec2(offsets->OffsetLabel, 0.0f), label); if (icon_w > 0.0f) - RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon); + RenderText(text_pos + ImVec2(offsets->OffsetIcon, 0.0f), icon); if (shortcut_w > 0.0f) { PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); LogSetNextTextDecoration("(", ")"); - RenderText(pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false); + RenderText(text_pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false); PopStyleColor(); } if (selected) - RenderCheckMark(window->DrawList, pos + ImVec2(offsets->OffsetMark + stretch_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(ImGuiCol_Text), g.FontSize * 0.866f); + RenderCheckMark(window->DrawList, text_pos + ImVec2(offsets->OffsetMark + stretch_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(ImGuiCol_Text), g.FontSize * 0.866f); } } IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0)); From 3ff8c466bf9e02f8e09ec16ec978d6bf638304e1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Nov 2025 20:05:07 +0100 Subject: [PATCH 1540/2359] Menus: fixed BeginMenuEx() icon/arrow baseline when using inside a line with an offset. Amend 1f54665. --- imgui_widgets.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d917d30a1..8c5614cae 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9227,13 +9227,13 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); float min_w = window->DC.MenuColumns.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 + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y)); LogSetNextTextDecoration("", ">"); - RenderText(text_pos, label); + RenderText(ImVec2(text_pos.x + offsets->OffsetLabel, text_pos.y), label); if (icon_w > 0.0f) - RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon); - RenderArrow(window->DrawList, pos + ImVec2(offsets->OffsetMark + extra_w + g.FontSize * 0.30f, 0.0f), GetColorU32(ImGuiCol_Text), ImGuiDir_Right); + 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); } if (!enabled) EndDisabled(); From 2026e3db882332bc5de5ea232d2808331131580b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Nov 2025 21:48:10 +0100 Subject: [PATCH 1541/2359] Menus: fixed BeginMenu() child popup position when used inside a line with a baseline offset. --- docs/CHANGELOG.txt | 4 +++- imgui_widgets.cpp | 11 ++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f317f620b..a8fdd4704 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,7 +51,9 @@ Other Changes: - Textures: - Fixed a building issue when ImTextureID is defined as a struct. - Fixed displaying texture # in Metrics/Debugger window. -- Menus: fixed MenuItem() label baseline when using inside a line with an offset. +- Menus: + - Fixed MenuItem() label position and BeginMenu() arrow/icon/popup positions, + when used inside a line with a baseline offset. - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Backends: diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8c5614cae..ebb7491ff 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9192,7 +9192,8 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, // However the final position is going to be different! It is chosen by FindBestWindowPosForPopup(). // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. - ImVec2 popup_pos, pos = window->DC.CursorPos; + ImVec2 popup_pos; + ImVec2 pos = window->DC.CursorPos; PushID(label); if (!enabled) BeginDisabled(); @@ -9206,34 +9207,34 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) // Menu inside a horizontal menu bar // Selectable extend their highlight by half ItemSpacing in each direction. // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin() - popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight); window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f); PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f); float w = label_size.x; - ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, pos.y + window->DC.CurrLineTextBaseOffset); pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, label_size.y)); LogSetNextTextDecoration("[", "]"); RenderText(text_pos, label); 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); } else { // 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.) - popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f; float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); float min_w = window->DC.MenuColumns.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, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + 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); 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); + popup_pos = ImVec2(pos.x, text_pos.y - style.WindowPadding.y); } if (!enabled) EndDisabled(); From 1a62292ac0b60308dd6c90084524e4a0ed5ac99f Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Nov 2025 22:37:00 +0100 Subject: [PATCH 1542/2359] Tables: fixed an issue where a very thin scrolling table would advance parent layout slightly differently depending on its visibility. --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 8 ++++---- imgui_internal.h | 2 ++ imgui_tables.cpp | 2 +- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a8fdd4704..838f8e1c3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,10 @@ Other Changes: - Menus: - Fixed MenuItem() label position and BeginMenu() arrow/icon/popup positions, when used inside a line with a baseline offset. +- Tables: + - Fixed an issue where a very thin scrolling table would advance parent layout + slightly differently depending on its visibility (caused by a mismatch + between hard minimum window size and table minimum size). - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Backends: diff --git a/imgui.cpp b/imgui.cpp index 640d6b34a..536bb17b0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6584,13 +6584,13 @@ static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window) ImVec2 size_min; if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) { - size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f; - size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f; + size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : IMGUI_WINDOW_HARD_MIN_SIZE; + size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : IMGUI_WINDOW_HARD_MIN_SIZE; } else { - size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f; - size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f; + size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : IMGUI_WINDOW_HARD_MIN_SIZE; + size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : IMGUI_WINDOW_HARD_MIN_SIZE; } // Reduce artifacts with very small windows diff --git a/imgui_internal.h b/imgui_internal.h index 788d1d5e6..318d013d4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2561,6 +2561,8 @@ struct ImGuiContext // [SECTION] ImGuiWindowTempData, ImGuiWindow //----------------------------------------------------------------------------- +#define IMGUI_WINDOW_HARD_MIN_SIZE 4.0f + // Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. // (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) // (This doesn't need a constructor because we zero-clear it as part of ImGuiWindow and all frame-temporary data are setup on Begin) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0a259e0c9..0e8c5f17e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -335,7 +335,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[]. const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0; const ImVec2 avail_size = GetContentRegionAvail(); - const ImVec2 actual_outer_size = ImTrunc(CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f)); + const ImVec2 actual_outer_size = ImTrunc(CalcItemSize(outer_size, ImMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window ? ImMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) : 0.0f)); const ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size); const bool outer_window_is_measuring_size = (outer_window->AutoFitFramesX > 0) || (outer_window->AutoFitFramesY > 0); // Doesn't apply to AlwaysAutoResize windows! if (use_child_window && IsClippedEx(outer_rect, 0) && !outer_window_is_measuring_size) From 7c6febed6620a6d356080ddb229130f97ab07c90 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Nov 2025 22:54:51 +0100 Subject: [PATCH 1543/2359] Tables: fixed an issue where submitting non-integer row heights would eventually advance table parent layout by +0/+1 depending on its visibility. --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 838f8e1c3..044c099ae 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,8 @@ Other Changes: - Fixed an issue where a very thin scrolling table would advance parent layout slightly differently depending on its visibility (caused by a mismatch between hard minimum window size and table minimum size). + - Fixed an issue where submitting non-integer row heights would eventually + advance table parent layout by +0/+1 depending on its visibility. - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Backends: diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0e8c5f17e..4aa868317 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1383,7 +1383,7 @@ void ImGui::EndTable() inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize; inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize; inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos; - const float inner_content_max_y = table->RowPosY2; + 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) IM_ASSERT(table->RowPosY2 == inner_window->DC.CursorPos.y); if (inner_window != outer_window) inner_window->DC.CursorMaxPos.y = inner_content_max_y; From 47766ca40335db5cdc62e14d17a7c8a139eb7ea8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Nov 2025 23:40:52 +0100 Subject: [PATCH 1544/2359] Demo: fix in 'Demo->Selection->Multi-Select in a Table' section. --- imgui_demo.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8c4a2a426..f3bf332d6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2863,7 +2863,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d const int ITEMS_COUNT = 10000; ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT); - if (ImGui::BeginTable("##Basket", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter)) + if (ImGui::BeginTable("##Basket", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter, ImVec2(0.0f, ImGui::GetFontSize() * 20))) { ImGui::TableSetupColumn("Object"); ImGui::TableSetupColumn("Action"); @@ -2884,6 +2884,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d { ImGui::TableNextRow(); ImGui::TableNextColumn(); + ImGui::PushID(n); char label[64]; sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); bool item_is_selected = selection.Contains((ImGuiID)n); @@ -2891,6 +2892,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); ImGui::TableNextColumn(); ImGui::SmallButton("hello"); + ImGui::PopID(); } } From 620a33dd85ddd405a76cd5bd4e3995e33585127d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Nov 2025 22:01:25 +0100 Subject: [PATCH 1545/2359] TreeNode: fixed highlight position when used inside a line with a large text baseline offset. Most old logic e.g. df749e3f135, ec0e953ccac. Never quite worked for this situation. --- docs/CHANGELOG.txt | 4 ++++ imgui.h | 2 +- imgui_demo.cpp | 21 +++++++++++++++------ imgui_widgets.cpp | 15 ++++++++------- 4 files changed, 28 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 044c099ae..590fa118c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,10 @@ Other Changes: - Menus: - Fixed MenuItem() label position and BeginMenu() arrow/icon/popup positions, when used inside a line with a baseline offset. +- TreeNode: + - Fixed highlight position when used inside a line with a large text baseline offset. + (never quite worked in this situation; but then most of the time the text + baseline offset ends up being zero or FramePadding.y for a given line). - Tables: - Fixed an issue where a very thin scrolling table would advance parent layout slightly differently depending on its visibility (caused by a mismatch diff --git a/imgui.h b/imgui.h index ac64c2ded..facb99975 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19251 +#define IMGUI_VERSION_NUM 19252 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f3bf332d6..1d914b371 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4086,6 +4086,7 @@ static void DemoWindowWidgetsTreeNodes() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); 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); HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); @@ -4750,7 +4751,7 @@ static void DemoWindowLayout() // Tree // (here the node appears after a button and has odd intent, so we use ImGuiTreeNodeFlags_DrawLinesNone to disable hierarchy outline) const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; - ImGui::Button("Button##1"); + ImGui::Button("Button##1"); // Will make line higher ImGui::SameLine(0.0f, spacing); if (ImGui::TreeNodeEx("Node##1", ImGuiTreeNodeFlags_DrawLinesNone)) { @@ -4760,14 +4761,22 @@ static void DemoWindowLayout() ImGui::TreePop(); } + const float padding = (float)(int)(ImGui::GetFontSize() * 1.20f); // Large padding + ImGui::PushStyleVarY(ImGuiStyleVar_FramePadding, padding); + ImGui::Button("Button##2"); + ImGui::PopStyleVar(); + ImGui::SameLine(0.0f, spacing); + if (ImGui::TreeNodeEx("Node##2", ImGuiTreeNodeFlags_DrawLinesNone)) + ImGui::TreePop(); + // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. // Otherwise you can use SmallButton() (smaller fit). ImGui::AlignTextToFramePadding(); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add - // other contents below the node. - bool node_open = ImGui::TreeNode("Node##2"); - ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); + // other contents "inside" the node. + bool node_open = ImGui::TreeNode("Node##3"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##3"); if (node_open) { // Placeholder tree data @@ -4777,13 +4786,13 @@ static void DemoWindowLayout() } // Bullet - ImGui::Button("Button##3"); + ImGui::Button("Button##4"); ImGui::SameLine(0.0f, spacing); ImGui::BulletText("Bullet text"); ImGui::AlignTextToFramePadding(); ImGui::BulletText("Node"); - ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##5"); ImGui::Unindent(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ebb7491ff..2e05af1c6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6776,7 +6776,6 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) window->DC.TreeRecordsClippedNodesY2Mask |= (1 << window->DC.TreeDepth); } -// When using public API, currently 'id == storage_id' is always true, but we separate the values to facilitate advanced user code doing storage queries outside of UI loop. bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) { ImGuiWindow* window = GetCurrentWindow(); @@ -6785,26 +6784,28 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; + + // When not framed, we vertically increase height up to typical framed widget height const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; - const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y)); + 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 float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapsing arrow width + Spacing - const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it + 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 = g.FontSize + label_size.x + padding.x * 2; // Include collapsing arrow - // We vertically grow up to current line height up the typical widget height. - const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2); + const float frame_height = label_size.y + padding.y * 2; const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL); const bool span_all_columns_label = (flags & ImGuiTreeNodeFlags_LabelSpanAllColumns) != 0 && (g.CurrentTable != NULL); ImRect frame_bb; frame_bb.Min.x = span_all_columns ? window->ParentWorkRect.Min.x : (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x; - frame_bb.Min.y = window->DC.CursorPos.y; + frame_bb.Min.y = window->DC.CursorPos.y + (text_offset_y - padding.y); frame_bb.Max.x = span_all_columns ? window->ParentWorkRect.Max.x : (flags & ImGuiTreeNodeFlags_SpanLabelWidth) ? window->DC.CursorPos.x + text_width + padding.x : window->WorkRect.Max.x; - frame_bb.Max.y = window->DC.CursorPos.y + frame_height; + frame_bb.Max.y = window->DC.CursorPos.y + (text_offset_y - padding.y) + frame_height; if (display_frame) { const float outer_extend = IM_TRUNC(window->WindowPadding.x * 0.5f); // Framed header expand a little outside of current limits From bfe137893abd0d08fa6617ae247d5a3379bdd571 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Dec 2025 17:02:51 +0100 Subject: [PATCH 1546/2359] Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to io.AddInputCharacter(). (#9099) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 590fa118c..058c853d3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,9 @@ Other Changes: advance table parent layout by +0/+1 depending on its visibility. - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] +- Debug Tools: + - Debug Log: fixed incorrectly printing characters in IO log when submitting + non-ASCII values to io.AddInputCharacter(). (#9099) - Backends: - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling diff --git a/imgui.cpp b/imgui.cpp index 536bb17b0..e21353a62 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10332,11 +10332,12 @@ static const char* GetMouseSourceName(ImGuiMouseSource source) static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e) { ImGuiContext& g = *GImGui; + char buf[5]; if (e->Type == ImGuiInputEventType_MousePos) { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; } if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; } if (e->Type == ImGuiInputEventType_MouseWheel) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; } if (e->Type == ImGuiInputEventType_Key) { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; } - if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; } + if (e->Type == ImGuiInputEventType_Text) { ImTextCharToUtf8(buf, e->Text.Char); IMGUI_DEBUG_LOG_IO("[io] %s: Text: '%s' (U+%08X)\n", prefix, buf, e->Text.Char); return; } if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; } } #endif From 87b193399e3fc7e1ab3902ed027d9b5dc9c9b4d5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Dec 2025 13:30:46 +0100 Subject: [PATCH 1547/2359] Backends: Win32: change param to MultiByteToWideChar() to be consistent (should be no-op?). Amend 0a7054c7e4 (#5725, #1807, #471, #2815, #1060 + #9099, #3653, #5961) --- backends/imgui_impl_win32.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index dc7e66f02..b1d715436 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -784,7 +784,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPA else { wchar_t wch = 0; - ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1); + ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 2, &wch, 1); io.AddInputCharacter(wch); } return 0; From d27dce58cda087f72418f891c7f95d9ce596fd6d Mon Sep 17 00:00:00 2001 From: ulhc <350246356@qq.com> Date: Fri, 28 Nov 2025 23:05:45 +0800 Subject: [PATCH 1548/2359] Backends: Win32: handle WM_IME_CHAR/WM_IME_COMPOSITION messages to support Unicode inputs on MBCS Windows. (#9099, #3653, #5961) --- backends/imgui_impl_win32.cpp | 19 +++++++++++++++++++ docs/CHANGELOG.txt | 2 ++ 2 files changed, 21 insertions(+) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index b1d715436..5f42466ae 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-12-03: Inputs: handle WM_IME_CHAR/WM_IME_COMPOSITION messages to support Unicode inputs on MBCS (non-Unicode) Windows. (#9099, #3653, #5961) // 2025-10-19: Inputs: Revert previous change to allow for io.ClearInputKeys() on focus-out not losing gamepad state. // 2025-09-23: Inputs: Minor optimization not submitting gamepad input if packet number has not changed. // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. @@ -788,6 +789,24 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPA io.AddInputCharacter(wch); } return 0; + case WM_IME_COMPOSITION: + { + // Handling WM_IME_COMPOSITION ensure that WM_IME_CHAR value is correct even for MBCS apps. + // (see #9099, #3653 and https://stackoverflow.com/questions/77450354 topics) + LRESULT result = ::DefWindowProcW(hwnd, msg, wParam, lParam); + return (lParam & GCS_RESULTSTR) ? 1 : result; + } + case WM_IME_CHAR: + if (::IsWindowUnicode(hwnd) == FALSE) + { + if (::IsDBCSLeadByte(HIBYTE(wParam))) + wParam = (WPARAM)MAKEWORD(HIBYTE(wParam), LOBYTE(wParam)); + wchar_t wch = 0; + ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 2, &wch, 1); + io.AddInputCharacterUTF16(wch); + return 1; + } + return 0; case WM_SETCURSOR: // This is required to restore cursor when transitioning from e.g resize borders to client area. if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor(io, bd->LastMouseCursor)) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 058c853d3..14ecb0dd0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,8 @@ Other Changes: selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on `cap.supportedCompositeAlpha`, which seems to be required on some Android devices. (#8784) [@FelixStach] + - Win32: handle WM_IME_CHAR/WM_IME_COMPOSITION to support Unicode inputs on + MBCS (non-Unicode) Windows. (#9099, #3653, #5961) [@ulhc, @ocornut, @Othereum] - Examples: - Win32+DirectX12: ignore seemingly incorrect D3D12_MESSAGE_ID_FENCE_ZERO_WAIT warning on startups on some setups. (#9084, #9093) [@RT2Code, @LeoGautheron] From 6e0ee6ff03324b58b20001f25d18d40dfb921a91 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Dec 2025 20:15:25 +0100 Subject: [PATCH 1549/2359] Fonts: removed misleading SizePixels >= 0.0f test and stbtt_ScaleForMappingEmToPixels() call in ImGui_ImplStbTrueType_FontSrcInit(). (#8857) Logic was picked in 9a9712807e while extracting code from stbtt_PackFontRangesGatherRects(), but ScaleForMappingEmToPixels() was actually never called: we assert against negative SizePixels since 2015. --- imgui_draw.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 88ad02966..b01e57358 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4596,10 +4596,7 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* if (src->MergeMode && src->SizePixels == 0.0f) src->SizePixels = ref_size; - if (src->SizePixels >= 0.0f) - bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); - else - bd_font_data->ScaleFactor = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); + bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); if (src->MergeMode && src->SizePixels != 0.0f && ref_size != 0.0f) bd_font_data->ScaleFactor *= src->SizePixels / ref_size; // FIXME-NEWATLAS: Should tidy up that a bit From d1e262ad555e0410a792cae973b35baf8933e88b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Dec 2025 15:57:31 +0100 Subject: [PATCH 1550/2359] Internals: refactor RenderRectFilledRangeH() into RenderRectFilledInRangeH() to take absolute coordinates instead of normalized ones. Amend 01d4bf299a (#1296) --- imgui.h | 2 +- imgui_demo.cpp | 13 +++++++------ imgui_draw.cpp | 14 +++++++------- imgui_internal.h | 2 +- imgui_widgets.cpp | 7 +++++-- 5 files changed, 21 insertions(+), 17 deletions(-) diff --git a/imgui.h b/imgui.h index facb99975..788061cd7 100644 --- a/imgui.h +++ b/imgui.h @@ -1927,7 +1927,7 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_ClampZeroRange = 1 << 10, // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it. ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, // Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, - ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from legacy API (obsoleted 2020-08) that has got miscast to this enum, and will trigger an assert if needed. }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1d914b371..a131680bd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2045,10 +2045,12 @@ static void DemoWindowWidgetsProgressBars() if (ImGui::TreeNode("Progress Bars")) { // Animate a simple progress bar - static float progress = 0.0f, progress_dir = 1.0f; - progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; - if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; } - if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } + static float progress_accum = 0.0f, progress_dir = 1.0f; + progress_accum += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; + if (progress_accum >= +1.1f) { progress_accum = +1.1f; progress_dir *= -1.0f; } + if (progress_accum <= -0.1f) { progress_accum = -0.1f; progress_dir *= -1.0f; } + + const float progress = IM_CLAMP(progress_accum, 0.0f, 1.0f); // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width, // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. @@ -2056,9 +2058,8 @@ static void DemoWindowWidgetsProgressBars() ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::Text("Progress Bar"); - float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f); char buf[32]; - sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753); + sprintf(buf, "%d/%d", (int)(progress * 1753), 1753); ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf); // Pass an animated negative value, e.g. -1.0f * (float)ImGui::GetTime() is the recommended value. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b01e57358..64e88fb55 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5830,7 +5830,7 @@ begin: // - RenderBullet() // - RenderCheckMark() // - RenderArrowPointingAt() -// - RenderRectFilledRangeH() +// - RenderRectFilledInRangeH() // - RenderRectFilledWithHole() //----------------------------------------------------------------------------- // Function in need of a redesign (legacy mess) @@ -5913,15 +5913,15 @@ static inline float ImAcos01(float x) } // FIXME: Cleanup and move code to ImDrawList. -void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding) +// - Before 2025-12-04: RenderRectFilledRangeH() with 'float x_start_norm, float x_end_norm` <- normalized +// - After 2025-12-04: RenderRectFilledInRangeH() with 'float x1, float x2' <- absolute coords!! +void ImGui::RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x1, float x2, float rounding) { - if (x_end_norm == x_start_norm) + if (x1 == x2) return; - if (x_start_norm > x_end_norm) - ImSwap(x_start_norm, x_end_norm); - ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y); - ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y); + ImVec2 p0 = ImVec2(x1, rect.Min.y); + ImVec2 p1 = ImVec2(x2, rect.Max.y); if (rounding == 0.0f) { draw_list->AddRectFilled(p0, p1, col, 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index 318d013d4..2da881038 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3587,7 +3587,7 @@ namespace ImGui 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 RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); + IMGUI_API void RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x1, float x2, float rounding); IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); // Widgets: Text diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2e05af1c6..85e77f041 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1440,7 +1440,10 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over // Render RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize)); - RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), fill_n0, fill_n1, style.FrameRounding); + float fill_x0 = ImLerp(bb.Min.x, bb.Max.x, fill_n0); + float fill_x1 = ImLerp(bb.Min.x, bb.Max.x, fill_n1); + if (fill_x0 < fill_x1) + RenderRectFilledInRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), fill_x0, fill_x1, style.FrameRounding); // Default displaying the fraction as percentage string, but user can override it // Don't display text for indeterminate bars by default @@ -1456,7 +1459,7 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over ImVec2 overlay_size = CalcTextSize(overlay, NULL); if (overlay_size.x > 0.0f) { - float text_x = is_indeterminate ? (bb.Min.x + bb.Max.x - overlay_size.x) * 0.5f : ImLerp(bb.Min.x, bb.Max.x, fill_n1) + style.ItemSpacing.x; + 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); } } From d71091a95761e71262162150a3c164848d65c7a2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Dec 2025 16:27:54 +0100 Subject: [PATCH 1551/2359] Internals: amend RenderRectFilledRangeH() to avoid shadowed variables. --- imgui_draw.cpp | 8 ++++---- imgui_internal.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 64e88fb55..bee1503de 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5915,13 +5915,13 @@ static inline float ImAcos01(float x) // FIXME: Cleanup and move code to ImDrawList. // - Before 2025-12-04: RenderRectFilledRangeH() with 'float x_start_norm, float x_end_norm` <- normalized // - After 2025-12-04: RenderRectFilledInRangeH() with 'float x1, float x2' <- absolute coords!! -void ImGui::RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x1, float x2, float rounding) +void ImGui::RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float fill_x0, float fill_x1, float rounding) { - if (x1 == x2) + if (fill_x0 > fill_x1) return; - ImVec2 p0 = ImVec2(x1, rect.Min.y); - ImVec2 p1 = ImVec2(x2, rect.Max.y); + ImVec2 p0 = ImVec2(fill_x0, rect.Min.y); + ImVec2 p1 = ImVec2(fill_x1, rect.Max.y); if (rounding == 0.0f) { draw_list->AddRectFilled(p0, p1, col, 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index 2da881038..c1fcfbaf4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3587,7 +3587,7 @@ namespace ImGui 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 x1, float x2, float rounding); + 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); // Widgets: Text From fee06a92ea7a21f3e5ebf77a30a3564bcb85cb43 Mon Sep 17 00:00:00 2001 From: achabense <60953653+achabense@users.noreply.github.com> Date: Fri, 5 Dec 2025 18:36:16 +0800 Subject: [PATCH 1552/2359] Text: fixed word-wrapping function reading from *text_end when passed a string range. (#9107) Likely caused by 4d4889bf1b (#5720) --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 14ecb0dd0..ecd57ffbb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,9 @@ Other Changes: between hard minimum window size and table minimum size). - Fixed an issue where submitting non-integer row heights would eventually advance table parent layout by +0/+1 depending on its visibility. +- Text: + - Fixed low-level word-wrapping function reading from *text_end when passed + a string range. (#9107) [@achabense] - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Debug Tools: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bee1503de..1b83fea92 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5364,7 +5364,7 @@ const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_e if ((flags & ImDrawTextFlags_WrapKeepBlanks) == 0) while (text < text_end && ImCharIsBlankA(*text)) text++; - if (*text == '\n') + if (text < text_end && *text == '\n') text++; return text; } From e2c49530cb677fa68ec56d5292575b861adc3596 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Dec 2025 13:42:15 +0100 Subject: [PATCH 1553/2359] ImDrawList: harden/clarify static asserts about ImDrawCmd / ImDrawCmdHeader layout. --- imgui_draw.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1b83fea92..88e897ac3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -444,10 +444,13 @@ void ImDrawList::_SetDrawListSharedData(ImDrawListSharedData* data) // In the majority of cases, you would want to call PushClipRect() and PushTexture() after this. void ImDrawList::_ResetForNewFrame() { - // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. + // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory to match ImDrawCmdHeader. IM_STATIC_ASSERT(offsetof(ImDrawCmd, ClipRect) == 0); IM_STATIC_ASSERT(offsetof(ImDrawCmd, TexRef) == sizeof(ImVec4)); IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureRef)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, ClipRect) == offsetof(ImDrawCmdHeader, ClipRect)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, TexRef) == offsetof(ImDrawCmdHeader, TexRef)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == offsetof(ImDrawCmdHeader, VtxOffset)); if (_Splitter._Count > 1) _Splitter.Merge(this); From 9d4fafa6713fdbf8b6424a8b88c5eec1dba953a8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Dec 2025 14:16:14 +0100 Subject: [PATCH 1554/2359] Nav: removed an unnecessary FindWindowByName() call. Amend c7016c25e8. It's not clear to me why it was committed like that, maybe a leftover of wip code which used the pointer before Begin(). --- imgui.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e21353a62..3fe059b6e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14555,13 +14555,12 @@ void ImGui::NavUpdateWindowingOverlay() if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) return; - if (g.NavWindowingListWindow == NULL) - g.NavWindowingListWindow = FindWindowByName("##NavWindowingOverlay"); const ImGuiViewport* viewport = GetMainViewport(); SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); Begin("##NavWindowingOverlay", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); + g.NavWindowingListWindow = g.CurrentWindow; if (g.ContextName[0] != 0) SeparatorText(g.ContextName); for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--) From ded52c71d983114a4efa9fef8ef31393998689e1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Dec 2025 15:07:44 +0100 Subject: [PATCH 1555/2359] Debug Log: can output to debugger. Added ImGuiDebugLogFlags_OutputToDebugger. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 14 ++++++++++++-- imgui_internal.h | 3 ++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ecd57ffbb..595072275 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -72,6 +72,7 @@ Other Changes: - Debug Tools: - Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to io.AddInputCharacter(). (#9099) + - Debug Log: can output to debugger on Windows. (#5855) - Backends: - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling diff --git a/imgui.cpp b/imgui.cpp index 3fe059b6e..3c87bd87c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17560,14 +17560,23 @@ void ImGui::DebugLogV(const char* fmt, va_list args) g.DebugLogBuf.appendf("[%05d] ", g.FrameCount); g.DebugLogBuf.appendfv(fmt, args); g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size()); + + const char* str = g.DebugLogBuf.begin() + old_size; if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY) - IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size); + IMGUI_DEBUG_PRINTF("%s", str); +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) + if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToDebugger) + { + ::OutputDebugStringA("[imgui] "); + ::OutputDebugStringA(str); + } +#endif #ifdef IMGUI_ENABLE_TEST_ENGINE // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically const int new_size = g.DebugLogBuf.size(); const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n'); if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine) - IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size); + IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), str); #endif } @@ -17647,6 +17656,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open) if (BeginPopup("Outputs")) { CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY); + CheckboxFlags("OutputToDebugger", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToDebugger); #ifndef IMGUI_ENABLE_TEST_ENGINE BeginDisabled(); #endif diff --git a/imgui_internal.h b/imgui_internal.h index c1fcfbaf4..23680045d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2078,7 +2078,8 @@ enum ImGuiDebugLogFlags_ ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventFont | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport, ImGuiDebugLogFlags_OutputToTTY = 1 << 20, // Also send output to TTY - ImGuiDebugLogFlags_OutputToTestEngine = 1 << 21, // Also send output to Test Engine + ImGuiDebugLogFlags_OutputToDebugger = 1 << 21, // Also send output to Debugger Console [Windows only] + ImGuiDebugLogFlags_OutputToTestEngine = 1 << 22, // Also send output to Dear ImGui Test Engine }; struct ImGuiDebugAllocEntry From a7ecbcdeba912ba8e945878edf6f0c18164ce1ad Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Dec 2025 16:45:45 +0100 Subject: [PATCH 1556/2359] Shuffle ImGuiColorEditFlags flag values. ImGuiColorEditFlags_AlphaOpaque, ImGuiColorEditFlags_AlphaNoBg, ImGuiColorEditFlags_AlphaPreviewHalf, ImGuiColorEditFlags_AlphaBar. --- imgui.h | 8 ++++---- imgui_demo.cpp | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index 788061cd7..8f60c2fc8 100644 --- a/imgui.h +++ b/imgui.h @@ -1878,12 +1878,12 @@ enum ImGuiColorEditFlags_ // - Prior to 1.91.8 (2025/01/21): alpha was made opaque in the preview by default using old name ImGuiColorEditFlags_AlphaPreview. // - We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. // - The new flags may be combined better and allow finer controls. - ImGuiColorEditFlags_AlphaOpaque = 1 << 11, // // ColorEdit, ColorPicker, ColorButton: disable alpha in the preview,. Contrary to _NoAlpha it may still be edited when calling ColorEdit4()/ColorPicker4(). For ColorButton() this does the same as _NoAlpha. - ImGuiColorEditFlags_AlphaNoBg = 1 << 12, // // ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. - ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 13, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. + ImGuiColorEditFlags_AlphaOpaque = 1 << 12, // // ColorEdit, ColorPicker, ColorButton: disable alpha in the preview,. Contrary to _NoAlpha it may still be edited when calling ColorEdit4()/ColorPicker4(). For ColorButton() this does the same as _NoAlpha. + ImGuiColorEditFlags_AlphaNoBg = 1 << 13, // // ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 14, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. // User Options (right-click on widget to change some of them). - ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + ImGuiColorEditFlags_AlphaBar = 1 << 18, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // " diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a131680bd..294efd748 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1726,7 +1726,7 @@ static void DemoWindowWidgetsDragsAndSliders() // Sliders static float slider_f = 0.5f; static int slider_i = 50; - const ImGuiSliderFlags flags_for_sliders = flags & ~ImGuiSliderFlags_WrapAround; + const ImGuiSliderFlags flags_for_sliders = (flags & ~ImGuiSliderFlags_WrapAround); 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); From fa4b47c5e2b53dba5093384562440bd9a6bba2a0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Dec 2025 16:29:15 +0100 Subject: [PATCH 1557/2359] Added RGBA color markers to ColorEdit3/ColorEdit4 + opt-in ImGuiSliderFlags_ColorMarkers for Drags/Sliders. + Added ImGuiColorEditFlags_NoColorMarkers + Added style.ColorMarkerSize. --- docs/CHANGELOG.txt | 8 ++++++++ imgui.cpp | 14 ++++++++++++++ imgui.h | 9 ++++++++- imgui_demo.cpp | 10 +++++++++- imgui_internal.h | 1 + imgui_widgets.cpp | 33 ++++++++++++++++++++++++++------- 6 files changed, 66 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 595072275..894baad88 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,14 @@ Other Changes: between hard minimum window size and table minimum size). - Fixed an issue where submitting non-integer row heights would eventually advance table parent layout by +0/+1 depending on its visibility. +- ColorEdit: + - Added R/G/B/A color markers next to each component (enabled by default). + - Added ImGuiColorEditFlags_NoColorMarkers to disable them. + - Added style.ColorMarkerSize to configure width of color component markers. +- Sliders, Drags: + - Added ImGuiSliderFlags_ColorMarkers to opt-in adding R/G/B/A color markers + next to each components, in multi-components functions. + - Added a way to select a specific marker color. - Text: - Fixed low-level word-wrapping function reading from *text_end when passed a string range. (#9107) [@achabense] diff --git a/imgui.cpp b/imgui.cpp index 3c87bd87c..a321d357e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1453,6 +1453,7 @@ ImGuiStyle::ImGuiStyle() DragDropTargetRounding = 0.0f; // Radius of the drag and drop target frame. DragDropTargetBorderSize = 2.0f; // Thickness of the drag and drop target border. DragDropTargetPadding = 3.0f; // Size to expand the drag and drop target from actual target item size. + ColorMarkerSize = 3.0f; // Size of R/G/B/A color markers for ColorEdit4() and for Drags/Sliders when using ImGuiSliderFlags_ColorMarkers. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. @@ -1520,6 +1521,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) DragDropTargetRounding = ImTrunc(DragDropTargetRounding * scale_factor); DragDropTargetBorderSize = ImTrunc(DragDropTargetBorderSize * scale_factor); DragDropTargetPadding = ImTrunc(DragDropTargetPadding * scale_factor); + ColorMarkerSize = ImTrunc(ColorMarkerSize * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); @@ -3923,6 +3925,18 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) } } +// FIXME: Might move those to style if there is a real need. +static const ImU32 GColorMarkers[4] = { IM_COL32(240,20,20,255), IM_COL32(20,240,20,255), IM_COL32(20,20,240,255), IM_COL32(140,140,140,255) }; + +void ImGui::RenderColorComponentMarker(int component_idx, const ImRect& bb, float rounding) +{ + if (!(component_idx >= 0 && component_idx < 4) || (bb.Min.x + 1 >= bb.Max.x)) + return; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + RenderRectFilledInRangeH(window->DrawList, bb, GetColorU32(GColorMarkers[component_idx]), bb.Min.x, ImMin(bb.Min.x + g.Style.ColorMarkerSize, bb.Max.x), rounding); +} + void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags) { ImGuiContext& g = *GImGui; diff --git a/imgui.h b/imgui.h index 8f60c2fc8..8b359d57f 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19252 +#define IMGUI_VERSION_NUM 19253 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -1873,6 +1873,7 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) + ImGuiColorEditFlags_NoColorMarkers = 1 << 11, // // ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. // Alpha preview // - Prior to 1.91.8 (2025/01/21): alpha was made opaque in the preview by default using old name ImGuiColorEditFlags_AlphaPreview. @@ -1927,6 +1928,11 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_ClampZeroRange = 1 << 10, // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it. ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, // Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, + + // Color Markers + ImGuiSliderFlags_ColorMarkers = 1 << 12, // DragScalarN(), SliderScalarN(): Draw R/G/B/A color markers on each component. + ImGuiSliderFlags_ColorMarkersIndexShift_ = 13, // [Internal] DragScalar(), SliderScalar(): Pass ([0..3] << ImGuiSliderFlags_ColorMarkersIndexShift_) along with ImGuiSliderFlags_ColorMarkers to select an individual R/G/B/A color. + ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from legacy API (obsoleted 2020-08) that has got miscast to this enum, and will trigger an assert if needed. }; @@ -2314,6 +2320,7 @@ struct ImGuiStyle float DragDropTargetRounding; // Radius of the drag and drop target frame. float DragDropTargetBorderSize; // Thickness of the drag and drop target border. float DragDropTargetPadding; // Size to expand the drag and drop target from actual target item size. + float ColorMarkerSize; // Size of R/G/B/A color markers for ColorEdit4() and for Drags/Sliders when using ImGuiSliderFlags_ColorMarkers. ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 294efd748..9dd4c5591 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1096,8 +1096,9 @@ static void DemoWindowWidgetsColorAndPickers() ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaOpaque", &base_flags, ImGuiColorEditFlags_AlphaOpaque); ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaNoBg", &base_flags, ImGuiColorEditFlags_AlphaNoBg); ImGui::CheckboxFlags("ImGuiColorEditFlags_AlphaPreviewHalf", &base_flags, ImGuiColorEditFlags_AlphaPreviewHalf); - ImGui::CheckboxFlags("ImGuiColorEditFlags_NoDragDrop", &base_flags, ImGuiColorEditFlags_NoDragDrop); ImGui::CheckboxFlags("ImGuiColorEditFlags_NoOptions", &base_flags, ImGuiColorEditFlags_NoOptions); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoDragDrop", &base_flags, ImGuiColorEditFlags_NoDragDrop); + ImGui::CheckboxFlags("ImGuiColorEditFlags_NoColorMarkers", &base_flags, ImGuiColorEditFlags_NoColorMarkers); ImGui::CheckboxFlags("ImGuiColorEditFlags_HDR", &base_flags, ImGuiColorEditFlags_HDR); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit"); @@ -1710,9 +1711,12 @@ static void DemoWindowWidgetsDragsAndSliders() ImGui::SameLine(); HelpMarker("Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic."); ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuiSliderFlags_WrapAround); ImGui::SameLine(); HelpMarker("Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions)"); + ImGui::CheckboxFlags("ImGuiSliderFlags_ColorMarkers", &flags, ImGuiSliderFlags_ColorMarkers); + //ImGui::CheckboxFlags("ImGuiSliderFlags_ColorMarkersG", &flags, 1 << ImGuiSliderFlags_ColorMarkersIndexShift_); // Not explicitly documented but possible. // Drags static float drag_f = 0.5f; + static float drag_f4[4]; static int drag_i = 50; ImGui::Text("Underlying float value: %f", drag_f); ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags); @@ -1722,14 +1726,17 @@ 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::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 static float slider_f = 0.5f; + static float slider_f4[4]; static int slider_i = 50; const ImGuiSliderFlags flags_for_sliders = (flags & ~ImGuiSliderFlags_WrapAround); 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); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. ImGui::TreePop(); } @@ -8444,6 +8451,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1); SeparatorText("Widgets"); + SliderFloat("ColorMarkerSize", &style.ColorMarkerSize, 0.0f, 8.0f, "%.0f"); Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); diff --git a/imgui_internal.h b/imgui_internal.h index 23680045d..849e48897 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3575,6 +3575,7 @@ namespace ImGui 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 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(int component_idx, const ImRect& bb, float rounding); IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); IMGUI_API void RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags = ImGuiNavRenderCursorFlags_None); // Navigation highlight #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 85e77f041..086a64c8d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2756,7 +2756,10 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavCursor(frame_bb, id); - RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding); + if ((flags & ImGuiSliderFlags_ColorMarkers) && style.ColorMarkerSize > 0.0f) + RenderColorComponentMarker(flags >> ImGuiSliderFlags_ColorMarkersIndexShift_, frame_bb, style.FrameRounding); + RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding); // Drag behavior const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags); @@ -2794,7 +2797,12 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags); + + ImGuiSliderFlags flags_for_component = flags; + if ((flags & ImGuiSliderFlags_ColorMarkers) && (flags & (0x03 << ImGuiSliderFlags_ColorMarkersIndexShift_)) == 0 && (i < 4)) + flags_for_component |= (i << ImGuiSliderFlags_ColorMarkersIndexShift_); + + value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags_for_component); PopID(); PopItemWidth(); p_data = (void*)((char*)p_data + type_size); @@ -3342,7 +3350,10 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavCursor(frame_bb, id); - RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding); + if ((flags & ImGuiSliderFlags_ColorMarkers) && style.ColorMarkerSize > 0.0f) + RenderColorComponentMarker(flags >> ImGuiSliderFlags_ColorMarkersIndexShift_, frame_bb, style.FrameRounding); + RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding); // Slider behavior ImRect grab_bb; @@ -3386,7 +3397,12 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags); + + ImGuiSliderFlags flags_for_component = flags; + if ((flags & ImGuiSliderFlags_ColorMarkers) && (flags & (0x03 << ImGuiSliderFlags_ColorMarkersIndexShift_ )) == 0 && (i < 4)) + flags_for_component |= (i << ImGuiSliderFlags_ColorMarkersIndexShift_); + + value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags_for_component); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); @@ -5784,8 +5800,10 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag { // RGB/HSV 0..255 Sliders const float w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1); + const float w_per_component = IM_TRUNC(w_items / components); + const bool draw_color_marker = (flags & (ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_NoColorMarkers)) == 0; - const bool hide_prefix = (IM_TRUNC(w_items / components) <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); + const bool hide_prefix = draw_color_marker || (w_per_component <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); static const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; static const char* fmt_table_int[3][4] = { @@ -5811,14 +5829,15 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag prev_split = next_split; // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. + ImGuiSliderFlags drag_flags = draw_color_marker ? (ImGuiSliderFlags_ColorMarkers | (n << ImGuiSliderFlags_ColorMarkersIndexShift_)) : ImGuiSliderFlags_None; if (flags & ImGuiColorEditFlags_Float) { - value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); + value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n], drag_flags); value_changed_as_float |= value_changed; } else { - value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); + value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n], drag_flags); } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); From 60f8b0733cec95431891c8344914c3f348103747 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Dec 2025 18:06:34 +0100 Subject: [PATCH 1558/2359] Rework color marker internals to facilitate arbitrary override using SetNextItemColorMarker(). Amend fa4b47c --- imgui.cpp | 9 +++------ imgui.h | 6 +----- imgui_internal.h | 17 ++++++++++------- imgui_widgets.cpp | 37 ++++++++++++++++++++----------------- 4 files changed, 34 insertions(+), 35 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a321d357e..1e8eeae9b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3925,16 +3925,13 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) } } -// FIXME: Might move those to style if there is a real need. -static const ImU32 GColorMarkers[4] = { IM_COL32(240,20,20,255), IM_COL32(20,240,20,255), IM_COL32(20,20,240,255), IM_COL32(140,140,140,255) }; - -void ImGui::RenderColorComponentMarker(int component_idx, const ImRect& bb, float rounding) +void ImGui::RenderColorComponentMarker(const ImRect& bb, ImU32 col, float rounding) { - if (!(component_idx >= 0 && component_idx < 4) || (bb.Min.x + 1 >= bb.Max.x)) + if (bb.Min.x + 1 >= bb.Max.x) return; ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - RenderRectFilledInRangeH(window->DrawList, bb, GetColorU32(GColorMarkers[component_idx]), bb.Min.x, ImMin(bb.Min.x + g.Style.ColorMarkerSize, bb.Max.x), rounding); + RenderRectFilledInRangeH(window->DrawList, bb, col, bb.Min.x, ImMin(bb.Min.x + g.Style.ColorMarkerSize, bb.Max.x), rounding); } void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags) diff --git a/imgui.h b/imgui.h index 8b359d57f..89dcc6713 100644 --- a/imgui.h +++ b/imgui.h @@ -1927,12 +1927,8 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_ClampOnInput = 1 << 9, // Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds. ImGuiSliderFlags_ClampZeroRange = 1 << 10, // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it. ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, // Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. - ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, - - // Color Markers ImGuiSliderFlags_ColorMarkers = 1 << 12, // DragScalarN(), SliderScalarN(): Draw R/G/B/A color markers on each component. - ImGuiSliderFlags_ColorMarkersIndexShift_ = 13, // [Internal] DragScalar(), SliderScalar(): Pass ([0..3] << ImGuiSliderFlags_ColorMarkersIndexShift_) along with ImGuiSliderFlags_ColorMarkers to select an individual R/G/B/A color. - + ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from legacy API (obsoleted 2020-08) that has got miscast to this enum, and will trigger an assert if needed. }; diff --git a/imgui_internal.h b/imgui_internal.h index 849e48897..e61f830d5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1334,12 +1334,13 @@ struct ImGuiNextWindowData enum ImGuiNextItemDataFlags_ { - ImGuiNextItemDataFlags_None = 0, - ImGuiNextItemDataFlags_HasWidth = 1 << 0, - ImGuiNextItemDataFlags_HasOpen = 1 << 1, - ImGuiNextItemDataFlags_HasShortcut = 1 << 2, - ImGuiNextItemDataFlags_HasRefVal = 1 << 3, - ImGuiNextItemDataFlags_HasStorageID = 1 << 4, + ImGuiNextItemDataFlags_None = 0, + ImGuiNextItemDataFlags_HasWidth = 1 << 0, + ImGuiNextItemDataFlags_HasOpen = 1 << 1, + ImGuiNextItemDataFlags_HasShortcut = 1 << 2, + ImGuiNextItemDataFlags_HasRefVal = 1 << 3, + ImGuiNextItemDataFlags_HasStorageID = 1 << 4, + ImGuiNextItemDataFlags_HasColorMarker = 1 << 5, }; struct ImGuiNextItemData @@ -1357,6 +1358,7 @@ struct ImGuiNextItemData ImU8 OpenCond; // Set by SetNextItemOpen() ImGuiDataTypeStorage RefVal; // Not exposed yet, for ImGuiInputTextFlags_ParseEmptyAsRefVal ImGuiID StorageId; // Set by SetNextItemStorageID() + ImU32 ColorMarker; // Set by SetNextItemColorMarker(). Not exposed yet, supported by DragScalar,SliderScalar and for ImGuiSliderFlags_ColorMarkers. ImGuiNextItemData() { memset(this, 0, sizeof(*this)); SelectionUserData = -1; } inline void ClearFlags() { HasFlags = ImGuiNextItemDataFlags_None; ItemFlags = ImGuiItemFlags_None; } // Also cleared manually by ItemAdd()! @@ -3575,7 +3577,7 @@ namespace ImGui 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 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(int component_idx, const ImRect& bb, float rounding); + IMGUI_API void RenderColorComponentMarker(const ImRect& bb, ImU32 col, float rounding); IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); IMGUI_API void RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags = ImGuiNavRenderCursorFlags_None); // Navigation highlight #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -3664,6 +3666,7 @@ namespace ImGui IMGUI_API void ColorTooltip(const char* 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 086a64c8d..6be8f7691 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2240,6 +2240,11 @@ bool ImGui::Combo(const char* label, int* current_item, bool (*old_getter)(void* // - RoundScalarWithFormat<>() //------------------------------------------------------------------------- +static const ImU32 GDefaultRgbaColorMarkers[4] = +{ + IM_COL32(240,20,20,255), IM_COL32(20,240,20,255), IM_COL32(20,20,240,255), IM_COL32(140,140,140,255) +}; + static const ImGuiDataTypeInfo GDataTypeInfo[] = { { sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8 @@ -2688,6 +2693,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); + const ImU32 color_marker = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasColorMarker) ? g.NextItemData.ColorMarker : 0; const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); @@ -2757,8 +2763,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavCursor(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding); - if ((flags & ImGuiSliderFlags_ColorMarkers) && style.ColorMarkerSize > 0.0f) - RenderColorComponentMarker(flags >> ImGuiSliderFlags_ColorMarkersIndexShift_, frame_bb, style.FrameRounding); + if (color_marker != 0 && style.ColorMarkerSize > 0.0f) + RenderColorComponentMarker(frame_bb, GetColorU32(color_marker), style.FrameRounding); RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding); // Drag behavior @@ -2797,12 +2803,9 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - - ImGuiSliderFlags flags_for_component = flags; - if ((flags & ImGuiSliderFlags_ColorMarkers) && (flags & (0x03 << ImGuiSliderFlags_ColorMarkersIndexShift_)) == 0 && (i < 4)) - flags_for_component |= (i << ImGuiSliderFlags_ColorMarkersIndexShift_); - - value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags_for_component); + if (flags & ImGuiSliderFlags_ColorMarkers) + SetNextItemColorMarker(GDefaultRgbaColorMarkers[i]); + value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags); PopID(); PopItemWidth(); p_data = (void*)((char*)p_data + type_size); @@ -3300,6 +3303,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); + const ImU32 color_marker = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasColorMarker) ? g.NextItemData.ColorMarker : 0; const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); @@ -3351,8 +3355,8 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavCursor(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding); - if ((flags & ImGuiSliderFlags_ColorMarkers) && style.ColorMarkerSize > 0.0f) - RenderColorComponentMarker(flags >> ImGuiSliderFlags_ColorMarkersIndexShift_, frame_bb, style.FrameRounding); + if (color_marker != 0 && style.ColorMarkerSize > 0.0f) + RenderColorComponentMarker(frame_bb, GetColorU32(color_marker), style.FrameRounding); RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding); // Slider behavior @@ -3397,12 +3401,9 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - - ImGuiSliderFlags flags_for_component = flags; - if ((flags & ImGuiSliderFlags_ColorMarkers) && (flags & (0x03 << ImGuiSliderFlags_ColorMarkersIndexShift_ )) == 0 && (i < 4)) - flags_for_component |= (i << ImGuiSliderFlags_ColorMarkersIndexShift_); - - value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags_for_component); + if (flags & ImGuiSliderFlags_ColorMarkers) + SetNextItemColorMarker(GDefaultRgbaColorMarkers[i]); + value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); @@ -5818,6 +5819,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA }; const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1; + const ImGuiSliderFlags drag_flags = draw_color_marker ? ImGuiSliderFlags_ColorMarkers : ImGuiSliderFlags_None; float prev_split = 0.0f; for (int n = 0; n < components; n++) @@ -5827,9 +5829,10 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag float next_split = IM_TRUNC(w_items * (n + 1) / components); SetNextItemWidth(ImMax(next_split - prev_split, 1.0f)); prev_split = next_split; + if (draw_color_marker) + SetNextItemColorMarker(GDefaultRgbaColorMarkers[n]); // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. - ImGuiSliderFlags drag_flags = draw_color_marker ? (ImGuiSliderFlags_ColorMarkers | (n << ImGuiSliderFlags_ColorMarkersIndexShift_)) : ImGuiSliderFlags_None; if (flags & ImGuiColorEditFlags_Float) { value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n], drag_flags); From 7f78f5224318750393ce6235edf0b7b9b6133a21 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Dec 2025 18:44:21 +0100 Subject: [PATCH 1559/2359] Demo: removed some hardcoded widths. --- imgui.cpp | 2 +- imgui_demo.cpp | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1e8eeae9b..a977c773c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15224,7 +15224,7 @@ void ImGui::LogButtons() const bool log_to_file = Button("Log To File"); SameLine(); const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); PushItemFlag(ImGuiItemFlags_NoTabStop, true); - SetNextItemWidth(80.0f); + SetNextItemWidth(CalcTextSize("999").x); SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); PopItemFlag(); PopID(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9dd4c5591..8ace9ff6a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4582,16 +4582,14 @@ static void DemoWindowLayout() // Various static float f0 = 1.0f, f1 = 2.0f, f2 = 3.0f; - ImGui::PushItemWidth(80); + ImGui::PushItemWidth(ImGui::CalcTextSize("AAAAAAA").x); const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; static int item = -1; ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); ImGui::SliderFloat("X", &f0, 0.0f, 5.0f); ImGui::SameLine(); ImGui::SliderFloat("Y", &f1, 0.0f, 5.0f); ImGui::SameLine(); ImGui::SliderFloat("Z", &f2, 0.0f, 5.0f); - ImGui::PopItemWidth(); - ImGui::PushItemWidth(80); ImGui::Text("Lists:"); static int selection[4] = { 0, 1, 2, 3 }; for (int i = 0; i < 4; i++) @@ -5026,7 +5024,7 @@ static void DemoWindowLayout() if (explicit_content_size) { ImGui::SameLine(); - ImGui::SetNextItemWidth(100); + ImGui::SetNextItemWidth(ImGui::CalcTextSize("123456").x); ImGui::DragFloat("##csx", &contents_size_x); ImVec2 p = ImGui::GetCursorScreenPos(); ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE); @@ -8504,7 +8502,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) } LogFinish(); } - SameLine(); SetNextItemWidth(120); Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + SameLine(); SetNextItemWidth(GetFontSize() * 10); Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); SameLine(); Checkbox("Only Modified Colors", &output_only_modified); static ImGuiTextFilter filter; From a726bded11f46fc5ee116089dd2fe6f12735befb Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Dec 2025 19:12:50 +0100 Subject: [PATCH 1560/2359] Fonts: ClearOutputData() doesn't need to clear FallbackChar, EllipsisChar. Fixed crash changing font loader. --- docs/CHANGELOG.txt | 13 ++++++++----- imgui_draw.cpp | 3 +-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 894baad88..c59efdcb5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,11 +43,14 @@ Breaking Changes: Other Changes: -- Fonts: fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which - did erroneously make a copy of the font data, essentially defeating the purpose - of this flag and wasting memory. - Undetected since July 2015 and now spotted by @TellowKrinkle, this is perhaps - the oldest bug in Dear ImGui history (albeit for a rarely used feature)! (#9086) +- Fonts: + - Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which + did erroneously make a copy of the font data, essentially defeating the purpose + of this flag and wasting memory. + Undetected since July 2015 and now spotted by @TellowKrinkle, this is perhaps + the oldest bug in Dear ImGui history (albeit for a rarely used feature)! (#9086) + - Fixed an issue related to EllipsisChar handling, while changing + font loader or font loader flags dynamically in Style->Fonts menus. - Textures: - Fixed a building issue when ImTextureID is defined as a struct. - Fixed displaying texture # in Metrics/Debugger window. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 88e897ac3..2dddaece7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3230,7 +3230,6 @@ void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* void ImFontAtlas::RemoveFont(ImFont* font) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - font->ClearOutputData(); ImFontAtlasFontDestroyOutput(this, font); for (ImFontConfig* src : font->Sources) @@ -5106,7 +5105,7 @@ void ImFont::ClearOutputData() { if (ImFontAtlas* atlas = OwnerAtlas) ImFontAtlasFontDiscardBakes(atlas, this, 0); - FallbackChar = EllipsisChar = 0; + //FallbackChar = EllipsisChar = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); LastBaked = NULL; } From cf64b7fa72776c434c7e39bc45f51ddf1af755a6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Dec 2025 19:29:41 +0100 Subject: [PATCH 1561/2359] Tables: Fixed losing stored display order when reducing column count. (#9108, #4046) Amend f2df804fcc --- docs/CHANGELOG.txt | 2 ++ imgui.h | 4 ++-- imgui_internal.h | 1 + imgui_tables.cpp | 50 +++++++++++++++++++++++++++++++++++----------- 4 files changed, 43 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c59efdcb5..2353faddb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,8 @@ Other Changes: between hard minimum window size and table minimum size). - Fixed an issue where submitting non-integer row heights would eventually advance table parent layout by +0/+1 depending on its visibility. + - Fixed losing stored display order when reducing column count or when .ini + data has missing or duplicate values. (#9108, #4046) - ColorEdit: - Added R/G/B/A color markers next to each component (enabled by default). - Added ImGuiColorEditFlags_NoColorMarkers to disable them. diff --git a/imgui.h b/imgui.h index 89dcc6713..7f8b6f3ac 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19253 +#define IMGUI_VERSION_NUM 19254 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -2019,7 +2019,7 @@ enum ImGuiTableFlags_ ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu. ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. - ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file. + ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width, visibility and sort settings in the .ini file. ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). // Decorations ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) diff --git a/imgui_internal.h b/imgui_internal.h index e61f830d5..254665dee 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3514,6 +3514,7 @@ namespace ImGui IMGUI_API void TableMergeDrawChannels(ImGuiTable* table); inline ImGuiTableInstanceData* TableGetInstanceData(ImGuiTable* table, int instance_no) { if (instance_no == 0) return &table->InstanceDataFirst; return &table->InstanceDataExtra[instance_no - 1]; } inline ImGuiID TableGetInstanceID(ImGuiTable* table, int instance_no) { return TableGetInstanceData(table, instance_no)->TableInstanceID; } + IMGUI_API void TableFixDisplayOrder(ImGuiTable* table); IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); IMGUI_API void TableSortSpecsBuild(ImGuiTable* table); IMGUI_API ImGuiSortDirection TableGetColumnNextSortDirection(ImGuiTableColumn* column); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 4aa868317..0ea14727e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -566,7 +566,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG { // Attempt to preserve width on column count change (#4046) old_columns_to_preserve = table->Columns.Data; - old_columns_raw_data = table->RawData; + old_columns_raw_data = table->RawData; // Free at end of function table->RawData = NULL; } if (table->RawData == NULL) @@ -592,7 +592,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG ImGuiTableColumn* column = &table->Columns[n]; if (old_columns_to_preserve && n < old_columns_count) { - // FIXME: We don't attempt to preserve column order in this path. *column = old_columns_to_preserve[n]; } else @@ -602,8 +601,9 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG column->WidthAuto = width_auto; column->IsPreserveWidthAuto = true; // Preserve WidthAuto when reinitializing a live table: not technically necessary but remove a visible flicker column->IsEnabled = column->IsUserEnabled = column->IsUserEnabledNextFrame = true; + column->DisplayOrder = (ImGuiTableColumnIdx)n; } - column->DisplayOrder = table->DisplayOrderToIndex[n] = (ImGuiTableColumnIdx)n; + table->DisplayOrderToIndex[n] = column->DisplayOrder; } } if (old_columns_raw_data) @@ -3792,7 +3792,6 @@ void ImGui::TableLoadSettings(ImGuiTable* table) // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); - ImU64 display_order_mask = 0; for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++) { int column_n = column_settings->Index; @@ -3809,24 +3808,51 @@ void ImGui::TableLoadSettings(ImGuiTable* table) } if (settings->SaveFlags & ImGuiTableFlags_Reorderable) column->DisplayOrder = column_settings->DisplayOrder; - display_order_mask |= (ImU64)1 << column->DisplayOrder; if ((settings->SaveFlags & ImGuiTableFlags_Hideable) && column_settings->IsEnabled != -1) column->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled == 1; column->SortOrder = column_settings->SortOrder; column->SortDirection = column_settings->SortDirection; } - // Validate and fix invalid display order data - const ImU64 expected_display_order_mask = (settings->ColumnsCount == 64) ? ~0 : ((ImU64)1 << settings->ColumnsCount) - 1; - if (display_order_mask != expected_display_order_mask) - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - table->Columns[column_n].DisplayOrder = (ImGuiTableColumnIdx)column_n; - - // Rebuild index + // Fix display order and build index + if (settings->SaveFlags & ImGuiTableFlags_Reorderable) + TableFixDisplayOrder(table); for (int column_n = 0; column_n < table->ColumnsCount; column_n++) table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n; } +struct ImGuiTableFixDisplayOrderColumnData +{ + ImGuiTableColumnIdx Idx; + ImGuiTable* Table; // This is unfortunate but we don't have userdata in qsort api. +}; + +// Sort by DisplayOrder and then Index +static int IMGUI_CDECL TableFixDisplayOrderComparer(const void* lhs, const void* rhs) +{ + const ImGuiTable* table = ((const ImGuiTableFixDisplayOrderColumnData*)lhs)->Table; + const ImGuiTableColumnIdx lhs_idx = ((const ImGuiTableFixDisplayOrderColumnData*)lhs)->Idx; + const ImGuiTableColumnIdx rhs_idx = ((const ImGuiTableFixDisplayOrderColumnData*)rhs)->Idx; + const int order_delta = (table->Columns[lhs_idx].DisplayOrder - table->Columns[rhs_idx].DisplayOrder); + return (order_delta > 0) ? +1 : (order_delta < 0) ? -1 : (lhs_idx > rhs_idx) ? +1 : -1; +} + +// Fix invalid display order data: compact values (0,1,3 -> 0,1,2); preserve relative order (0,3,1 -> 0,2,1); deduplicate (0,4,1,1 -> 0,3,1,2) +void ImGui::TableFixDisplayOrder(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + g.TempBuffer.reserve((int)(sizeof(ImGuiTableFixDisplayOrderColumnData) * table->ColumnsCount)); // FIXME: Maybe wrap those two lines as a helper. + ImGuiTableFixDisplayOrderColumnData* fdo_columns = (ImGuiTableFixDisplayOrderColumnData*)g.TempBuffer.Data; + for (int n = 0; n < table->ColumnsCount; n++) + { + fdo_columns[n].Idx = (ImGuiTableColumnIdx)n; + fdo_columns[n].Table = table; + } + ImQsort(fdo_columns, (size_t)table->ColumnsCount, sizeof(ImGuiTableFixDisplayOrderColumnData), TableFixDisplayOrderComparer); + for (int n = 0; n < table->ColumnsCount; n++) + table->Columns[fdo_columns[n].Idx].DisplayOrder = (ImGuiTableColumnIdx)n; +} + static void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { ImGuiContext& g = *ctx; From 9a4fd69f6dd6f9cdf89c744bb7a796bc9db0a0b2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Dec 2025 18:35:22 +0100 Subject: [PATCH 1562/2359] Backends: GLFW: avoid repeated glfwSetCursor()/glfwSetInputMode() calls when unnecessary. --- backends/imgui_impl_glfw.cpp | 17 ++++++++++++++--- docs/CHANGELOG.txt | 2 ++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index ac176a080..d088e9693 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-12-10: Avoid repeated glfwSetCursor()/glfwSetInputMode() calls when unnecessary. Lowers overhead for very high framerates (e.g. 10k+ FPS). // 2025-11-06: Lower minimum requirement to GLFW 3.0. Though a recent version e.g GLFW 3.4 is highly recommended. // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Content Scales are always reported as 1.0 on Wayland. FramebufferScale are always reported as 1.0 on X11. (#8920, #8921) @@ -188,6 +189,7 @@ struct ImGui_ImplGlfw_Data GLFWwindow* MouseWindow; #if GLFW_HAS_CREATECURSOR GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT]; + GLFWcursor* LastMouseCursor; #endif ImVec2 LastValidMousePos; bool IsWayland; @@ -849,15 +851,24 @@ static void ImGui_ImplGlfw_UpdateMouseCursor() GLFWwindow* window = bd->Window; if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) { - // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor - glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + if (bd->LastMouseCursor != nullptr) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + bd->LastMouseCursor = nullptr; + } } else { // Show OS mouse cursor // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here. #if GLFW_HAS_CREATECURSOR - glfwSetCursor(window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]); + GLFWcursor* cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; + if (bd->LastMouseCursor != cursor) + { + glfwSetCursor(window, cursor); + bd->LastMouseCursor = cursor; + } #endif glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2353faddb..32008203d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -87,6 +87,8 @@ Other Changes: non-ASCII values to io.AddInputCharacter(). (#9099) - Debug Log: can output to debugger on Windows. (#5855) - Backends: + - GLFW: Avoid repeated glfwSetCursor()/glfwSetInputMode() calls when unnecessary. + Lowers overhead for very high framerates (e.g. 10k+ FPS). [@maxliani] - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. (#9076) [@Niminem] From a07b2828ce89c2e10cfcf26450c0b0c3cc4a208f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Dec 2025 18:57:02 +0100 Subject: [PATCH 1563/2359] Backends: GLFW: add IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND. (#9109, #9116) cc #8884, #8474, #8289 --- backends/imgui_impl_glfw.cpp | 22 ++++++++++++++-------- backends/imgui_impl_glfw.h | 1 + docs/CHANGELOG.txt | 2 ++ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index d088e9693..58cb6f1b1 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-12-12: Added IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND to forcefully disable either. // 2025-12-10: Avoid repeated glfwSetCursor()/glfwSetInputMode() calls when unnecessary. Lowers overhead for very high framerates (e.g. 10k+ FPS). // 2025-11-06: Lower minimum requirement to GLFW 3.0. Though a recent version e.g GLFW 3.4 is highly recommended. // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. @@ -109,10 +110,15 @@ #endif // GLFW -#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) -#define GLFW_HAS_X11_OR_WAYLAND 1 +#if !defined(IMGUI_IMPL_GLFW_DISABLE_X11) && (defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)) +#define GLFW_HAS_X11 1 #else -#define GLFW_HAS_X11_OR_WAYLAND 0 +#define GLFW_HAS_X11 0 +#endif +#if !defined(IMGUI_IMPL_GLFW_DISABLE_WAYLAND) && (defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)) +#define GLFW_HAS_WAYLAND 1 +#else +#define GLFW_HAS_WAYLAND 0 #endif #include #ifdef _WIN32 @@ -126,7 +132,7 @@ #define GLFW_EXPOSE_NATIVE_COCOA #endif #include -#elif GLFW_HAS_X11_OR_WAYLAND +#elif GLFW_HAS_X11 #ifndef GLFW_EXPOSE_NATIVE_X11 // for glfwGetX11Display(), glfwGetX11Window() on Freedesktop (Linux, BSD, etc.) #define GLFW_EXPOSE_NATIVE_X11 #endif @@ -239,7 +245,7 @@ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData(GLFWwindow* window) // Functions static bool ImGui_ImplGlfw_IsWayland() { -#if !GLFW_HAS_X11_OR_WAYLAND +#if !GLFW_HAS_WAYLAND return false; #elif GLFW_HAS_GETPLATFORM return glfwGetPlatform() == GLFW_PLATFORM_WAYLAND; @@ -933,7 +939,7 @@ static void ImGui_ImplGlfw_UpdateGamepads() // - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle. float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) { -#if GLFW_HAS_X11_OR_WAYLAND +#if GLFW_HAS_WAYLAND if (ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window)) if (bd->IsWayland) return 1.0f; @@ -950,7 +956,7 @@ float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) { -#if GLFW_HAS_X11_OR_WAYLAND +#if GLFW_HAS_WAYLAND if (ImGui_ImplGlfw_IsWayland()) // We can't access our bd->IsWayland cache for a monitor. return 1.0f; #endif @@ -972,7 +978,7 @@ static void ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(GLFWwindow* window, glfwGetFramebufferSize(window, &display_w, &display_h); float fb_scale_x = (w > 0) ? (float)display_w / (float)w : 1.0f; float fb_scale_y = (h > 0) ? (float)display_h / (float)h : 1.0f; -#if GLFW_HAS_X11_OR_WAYLAND +#if GLFW_HAS_WAYLAND ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); if (!bd->IsWayland) fb_scale_x = fb_scale_y = 1.0f; diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index ce954ed9f..98fae51c7 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -1,6 +1,7 @@ // dear imgui: Platform Backend for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) +// (Requires: GLFW 3.0+. Prefer GLFW 3.3+/3.4+ for full feature support.) // Implemented features: // [X] Platform: Clipboard support. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 32008203d..824e05990 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -89,6 +89,8 @@ Other Changes: - Backends: - GLFW: Avoid repeated glfwSetCursor()/glfwSetInputMode() calls when unnecessary. Lowers overhead for very high framerates (e.g. 10k+ FPS). [@maxliani] + - GLFW: Added IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND to + forcefully disable either. (#9109, #9116) - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. (#9076) [@Niminem] From 99712515740102ad6ea4db96300ed319453fa1fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Dec 2025 21:42:07 +0100 Subject: [PATCH 1564/2359] Fonts: amend/comment on FontDataOwnedByAtlas=false fix being a breaking change. (#9086, #8465) --- docs/CHANGELOG.txt | 17 ++++++++++++----- docs/FONTS.md | 1 + imgui.cpp | 6 ++++++ imgui.h | 2 +- 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 824e05990..faf1ebb2c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,14 +41,21 @@ HOW TO UPDATE? Breaking Changes: +- Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which + did erroneously make a copy of the font data, essentially defeating the purpose + of this flag and wasting memory (undetected since July 2015 and now spotted + by @TellowKrinkle, this is perhaps the oldest bug in Dear ImGui history, + albeit for a rarely used feature!) (#9086, #8465) + HOWEVER, fixing this bug is likely to surface bugs in user/app code: + - Prior to 1.92, font data only needs to be available during the atlas->AddFontXXX() call. + - Since 1.92, font data needs to available until atlas->RemoveFont(), or more typically + until a shutdown of the owning context or font atlas. + - The fact that handling of `FontDataOwnedByAtlas = false` was broken + bypassed the issue altogether. + Other Changes: - Fonts: - - Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which - did erroneously make a copy of the font data, essentially defeating the purpose - of this flag and wasting memory. - Undetected since July 2015 and now spotted by @TellowKrinkle, this is perhaps - the oldest bug in Dear ImGui history (albeit for a rarely used feature)! (#9086) - Fixed an issue related to EllipsisChar handling, while changing font loader or font loader flags dynamically in Style->Fonts menus. - Textures: diff --git a/docs/FONTS.md b/docs/FONTS.md index 072ca9762..1a466be8d 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -228,6 +228,7 @@ ImFontConfig font_cfg; font_cfg.FontDataOwnedByAtlas = false; ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg); ``` +IMPORTANT: Since 1.92, when using `FontDataOwnedByAtlas = false`, font data needs to available until `atlas->RemoveFont()`, or more typically until a shutdown of the owning context or font atlas. It was not immediately noticeable in 1.92.0 due to a bug in handling `FontDataOwnedByAtlas = false`, which was fixed in 1.92.6. ##### [Return to Index](#index) diff --git a/imgui.cpp b/imgui.cpp index a977c773c..52b4f0f66 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -394,6 +394,12 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/11/24 (1.92.6) - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory. + (trivia: undetected since July 2015, this is perhaps the oldest bug in Dear ImGui history, albeit for a rarely used feature, see #9086) + HOWEVER, fixing this bug is likely to surface bugs in user code using `FontDataOwnedByAtlas = false`. + - Prior to 1.92, font data only needed to be available during the atlas->AddFontXXX() call. + - Since 1.92, font data needs to available until atlas->RemoveFont(), or more typically until a shutdown of the owning context or font atlas. + - The fact that handling of `FontDataOwnedByAtlas = false` was broken bypassed the issue altogether. - 2025/11/06 (1.92.5) - BeginChild: commented out some legacy names which were obsoleted in 1.90.0 (Nov 2023), 1.90.9 (July 2024), 1.91.1 (August 2024): - ImGuiChildFlags_Border --> ImGuiChildFlags_Borders - ImGuiWindowFlags_NavFlattened --> ImGuiChildFlags_NavFlattened (moved to ImGuiChildFlags). BeginChild(name, size, 0, ImGuiWindowFlags_NavFlattened) --> BeginChild(name, size, ImGuiChildFlags_NavFlattened, 0) diff --git a/imgui.h b/imgui.h index 7f8b6f3ac..09fef133f 100644 --- a/imgui.h +++ b/imgui.h @@ -3521,7 +3521,7 @@ struct ImFontConfig char Name[40]; // // Name (strictly to ease debugging, hence limited size buffer) void* FontData; // // TTF/OTF data int FontDataSize; // // TTF/OTF data size - bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the owner ImFontAtlas (will delete memory itself). + bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the owner ImFontAtlas (will delete memory itself). SINCE 1.92, THE DATA NEEDS TO PERSIST FOR WHOLE DURATION OF ATLAS. // Options bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. From 0d2dd30ee9783969cb7fe34deb67b1da92fc2431 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Dec 2025 17:17:57 +0100 Subject: [PATCH 1565/2359] Tabs: minor tweaks to facilitate mods altering spacing. --- imgui.h | 2 +- imgui_widgets.cpp | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 09fef133f..6c59e78f8 100644 --- a/imgui.h +++ b/imgui.h @@ -349,7 +349,7 @@ typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or // The identifier is valid even before the texture has been uploaded to the GPU/graphics system. // This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`. // This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering. -// - When a texture is created by user code (e.g. custom images), we directly stores the low-level ImTextureID. +// - When a texture is created by user code (e.g. custom images), we directly store the low-level ImTextureID. // Because of this, when displaying your own texture you are likely to ever only manage ImTextureID values on your side. // - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection // to extract the ImTextureID value during rendering, after texture upload has happened. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6be8f7691..84ea505f6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9788,8 +9788,9 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection); // Calculate spacing between sections - sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; - sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + const float tab_spacing = g.Style.ItemInnerSpacing.x; + sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? tab_spacing : 0.0f; + sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? tab_spacing : 0.0f; // Setup next selected tab ImGuiID scroll_to_tab_id = 0; @@ -9850,8 +9851,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) int section_n = TabItemGetSectionIdx(tab); ImGuiTabBarSection* section = §ions[section_n]; - section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f); - section->WidthAfterShrinkMinWidth += ImMin(tab->ContentWidth, shrink_min_width) + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f); + section->Width += tab->ContentWidth + (section_n == curr_section_n ? tab_spacing : 0.0f); + section->WidthAfterShrinkMinWidth += ImMin(tab->ContentWidth, shrink_min_width) + (section_n == curr_section_n ? tab_spacing : 0.0f); curr_section_n = section_n; // Store data so we can build an array sorted by width if we need to shrink tabs down @@ -10156,6 +10157,7 @@ void ImGui::TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* s if ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) == 0) return; + const float tab_spacing = g.Style.ItemInnerSpacing.x; const bool is_central_section = (src_tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0; const float bar_offset = tab_bar->BarRect.Min.x - (is_central_section ? tab_bar->ScrollingTarget : 0); @@ -10174,8 +10176,8 @@ void ImGui::TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* s dst_idx = i; // Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered. - const float x1 = bar_offset + dst_tab->Offset - g.Style.ItemInnerSpacing.x; - const float x2 = bar_offset + dst_tab->Offset + dst_tab->Width + g.Style.ItemInnerSpacing.x; + const float x1 = bar_offset + dst_tab->Offset - tab_spacing; + const float x2 = bar_offset + dst_tab->Offset + dst_tab->Width + tab_spacing; //GetForegroundDrawList()->AddRect(ImVec2(x1, tab_bar->BarRect.Min.y), ImVec2(x2, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255)); if ((dir < 0 && mouse_pos.x > x1) || (dir > 0 && mouse_pos.x < x2)) break; From bd6f48fe20ff87757485458d9147a50a445f06fa Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Dec 2025 18:28:23 +0100 Subject: [PATCH 1566/2359] Backends: OpenGL3: Fixed embedded loader multiple init/shutdown cycles broken on some platforms. (#8792, #9112) --- backends/imgui_impl_opengl3.cpp | 1 + backends/imgui_impl_opengl3_loader.h | 9 +++++++++ docs/CHANGELOG.txt | 2 ++ 3 files changed, 12 insertions(+) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 3e0e265b1..9b303ac08 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -23,6 +23,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025-12-11: OpenGL: Fixed embedded loader multiple init/shutdown cycles broken on some platforms. (#8792, #9112) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-07-22: OpenGL: Add and call embedded loader shutdown during ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792) // 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures (#8802) + restore non-WebGL/ES update path that doesn't require a CPU-side copy. diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index 2c80cc598..2c485841a 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -836,6 +836,7 @@ static int parse_version(void) } static void load_procs(GL3WGetProcAddressProc proc); +static void clear_procs(); int imgl3wInit(void) { @@ -855,6 +856,7 @@ int imgl3wInit2(GL3WGetProcAddressProc proc) void imgl3wShutdown(void) { close_libgl(); + clear_procs(); } int imgl3wIsSupported(int major, int minor) @@ -943,6 +945,13 @@ static void load_procs(GL3WGetProcAddressProc proc) imgl3wProcs.ptr[i] = proc(proc_names[i]); } +static void clear_procs() +{ + size_t i; + for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++) + imgl3wProcs.ptr[i] = nullptr; +} + #ifdef __cplusplus } #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index faf1ebb2c..8c82d6a14 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -98,6 +98,8 @@ Other Changes: Lowers overhead for very high framerates (e.g. 10k+ FPS). [@maxliani] - GLFW: Added IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND to forcefully disable either. (#9109, #9116) + - OpenGL3: Fixed embedded loader multiple init/shutdown cycles broken on some + platforms. (#8792, #9112) - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. (#9076) [@Niminem] From 1e7d2adc29f611157f1a50fa87a33ca30a96a24d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Dec 2025 21:36:42 +0100 Subject: [PATCH 1567/2359] Fixed Clang cast-align warning + Added missing Changelog entry in 1.92.4. (#8893) --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8c82d6a14..4219987b9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -298,6 +298,8 @@ Other Changes: using ImGuiWindowFlags_UnsavedDocument/ImGuiTabItemFlags_UnsavedDocument. (#8983) - IO: added ImGuiPlatformIO::ClearPlatformHandlers(), ClearRendererHandlers() helpers to null all handlers. (#8945, #2769) +- Tables: changed ImGuiTableFlags_NoBordersInBody behavior to not draw border in + body even when resizing. (#8893) - Inputs: - Shortcuts: added support for combining ImGuiInputFlags_RouteFocused (which is the default route) with ImGuiInputFlags_RouteOverActive, allowing diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0ea14727e..20ca7af1b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -564,7 +564,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG const int old_columns_count = table->Columns.size(); if (old_columns_count != 0 && old_columns_count != columns_count) { - // Attempt to preserve width on column count change (#4046) + // Attempt to preserve width and other settings on column count/specs change (#4046) old_columns_to_preserve = table->Columns.Data; old_columns_raw_data = table->RawData; // Free at end of function table->RawData = NULL; @@ -3842,7 +3842,7 @@ void ImGui::TableFixDisplayOrder(ImGuiTable* table) { ImGuiContext& g = *GImGui; g.TempBuffer.reserve((int)(sizeof(ImGuiTableFixDisplayOrderColumnData) * table->ColumnsCount)); // FIXME: Maybe wrap those two lines as a helper. - ImGuiTableFixDisplayOrderColumnData* fdo_columns = (ImGuiTableFixDisplayOrderColumnData*)g.TempBuffer.Data; + ImGuiTableFixDisplayOrderColumnData* fdo_columns = (ImGuiTableFixDisplayOrderColumnData*)(void*)g.TempBuffer.Data; for (int n = 0; n < table->ColumnsCount; n++) { fdo_columns[n].Idx = (ImGuiTableColumnIdx)n; From fc89c61089729f72aa0579f689406edfbddd603a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 26 Dec 2019 21:40:58 +0100 Subject: [PATCH 1568/2359] Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore. This has various simplifying properties. Need a test engine update too. + Demo: removed misleading/unnecessary usage of ###. --- docs/CHANGELOG.txt | 8 ++++++++ imgui.cpp | 20 +++++++++++++------- imgui.h | 2 +- imgui_demo.cpp | 2 +- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4219987b9..90d85aaf2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,14 @@ HOW TO UPDATE? Breaking Changes: +- Hashing: handling of "###" operator to reset to seed within a string identifier + doesn't include the "###" characters in the output hash anymore: + Before: GetID("Hello###World") == GetID("###World") != GetID("World"); + Now: GetID("Hello###World") == GetID("###World") == GetID("World"); + - This has the property of facilitating concatenating and manipulating + identifers using "###", and will allow fixing other dangling issues. + - This will invalidate hashes (stored in .ini data) for Tables and Windows + that are using the "###" operators. (#713, #1698) - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory (undetected since July 2015 and now spotted diff --git a/imgui.cpp b/imgui.cpp index 52b4f0f66..05be5f3bc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2368,11 +2368,8 @@ ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed) #endif } -// Zero-terminated string hash, with support for ### to reset back to seed value -// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. -// Because this syntax is rarely used we are optimizing for the common case. -// - If we reach ### in the string we discard the hash so far and reset to the seed. -// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build) +// 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) { @@ -2384,11 +2381,16 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed) #endif if (data_size != 0) { - while (data_size-- != 0) + while (data_size-- > 0) { unsigned char c = *data++; if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#') + { crc = seed; + data += 2; + data_size -= 2; + continue; + } #ifndef IMGUI_ENABLE_SSE4_2_CRC crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; #else @@ -2401,7 +2403,11 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed) while (unsigned char c = *data++) { if (c == '#' && data[0] == '#' && data[1] == '#') + { crc = seed; + data += 2; + continue; + } #ifndef IMGUI_ENABLE_SSE4_2_CRC crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; #else @@ -2419,7 +2425,7 @@ const char* ImHashSkipUncontributingPrefix(const char* label) const char* result = label; while (unsigned char c = *label++) if (c == '#' && label[0] == '#' && label[1] == '#') - result = label - 1; + result = label + 2; return result; } diff --git a/imgui.h b/imgui.h index 6c59e78f8..40493eb33 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19254 +#define IMGUI_VERSION_NUM 19255 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8ace9ff6a..beb181986 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3358,7 +3358,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::TableNextColumn(); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); - ImGui::InputText("###NoLabel", (char*)(void*)item_category, strlen(item_category), ImGuiInputTextFlags_ReadOnly); + ImGui::InputText("##NoLabel", (char*)(void*)item_category, strlen(item_category), ImGuiInputTextFlags_ReadOnly); ImGui::PopStyleVar(); } From 4dac00ca0c8138b5db6434a15dc273ee8b26cfbd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Dec 2025 23:12:52 +0100 Subject: [PATCH 1569/2359] Windows: fixed always updating internal buffer for ### window titles even when Ctrl+Tab window is hidden. Instead forcing an update on mismatching when appearing. 3997e8b555 was already doing that. (Relates to 8e67fe1: code assume pointer used to be nulled when ctrl+tab window is disabled. not the case). --- imgui.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 05be5f3bc..6d7b02654 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7506,11 +7506,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. bool window_title_visible_elsewhere = false; - if (g.NavWindowingListWindow != NULL && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using Ctrl+Tab + if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->WasActive && (flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using Ctrl+Tab window_title_visible_elsewhere = true; if (flags & ImGuiWindowFlags_ChildMenu) window_title_visible_elsewhere = true; - if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0) + if ((window_title_visible_elsewhere || window_just_activated_by_user) && !window_just_created && strcmp(name, window->Name) != 0) { size_t buf_len = (size_t)window->NameBufLen; window->Name = ImStrdupcpy(window->Name, &buf_len, name); From dc48a7c88eef4a347000d55062d35cc94e00ef70 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Dec 2025 16:59:22 +0100 Subject: [PATCH 1570/2359] Docs: amend fc89c61 --- docs/CHANGELOG.txt | 2 +- imgui.cpp | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 90d85aaf2..a178da986 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,7 +46,7 @@ Breaking Changes: Before: GetID("Hello###World") == GetID("###World") != GetID("World"); Now: GetID("Hello###World") == GetID("###World") == GetID("World"); - This has the property of facilitating concatenating and manipulating - identifers using "###", and will allow fixing other dangling issues. + identifiers using "###", and will allow fixing other dangling issues. - This will invalidate hashes (stored in .ini data) for Tables and Windows that are using the "###" operators. (#713, #1698) - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which diff --git a/imgui.cpp b/imgui.cpp index 6d7b02654..58588ced4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -394,6 +394,12 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/12/11 (1.92.6) - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore. + - Before: GetID("Hello###World") == GetID("###World") != GetID("World"); + - Now: GetID("Hello###World") == GetID("###World") == GetID("World"); + - This has the property of facilitating concatenating and manipulating identifiers using "###", and will allow fixing other dangling issues. + - This will invalidate hashes (stored in .ini data) for Tables and Windows! + that are using the "###" operators. (#713, #1698) - 2025/11/24 (1.92.6) - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory. (trivia: undetected since July 2015, this is perhaps the oldest bug in Dear ImGui history, albeit for a rarely used feature, see #9086) HOWEVER, fixing this bug is likely to surface bugs in user code using `FontDataOwnedByAtlas = false`. From ebbd8c320d339a7f86275b5533f9dee5f1da9121 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Jun 2024 19:09:54 +0200 Subject: [PATCH 1571/2359] Fix for latest --- imgui.cpp | 4 ++-- imgui_widgets.cpp | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5b9c5f7da..1f7415a07 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6418,8 +6418,8 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl #ifdef WIN98 // windows style title bar - close_button_pos += ImVec2(0.0f, 2.0f); - collapse_button_pos += ImVec2(0.0f, 2.0f); + close_button_pos += ImVec2(-2.0f, -2.0f); + collapse_button_pos += ImVec2(-2.0f, -2.0f); ImU32 col_left = IM_COL32(128,128,128,255); ImU32 col_right = IM_COL32(181,181,181,255); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a8e479d11..ce20aa0ba 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6640,6 +6640,10 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFl float button_size = g.FontSize; float button_x = ImMax(g.LastItemData.Rect.Min.x, g.LastItemData.Rect.Max.x - g.Style.FramePadding.x - button_size); float button_y = g.LastItemData.Rect.Min.y + g.Style.FramePadding.y; +#ifdef WIN98 + button_x -= 4; + button_y -= 1; +#endif ImGuiID close_button_id = GetIDWithSeed("#CLOSE", NULL, id); if (CloseButton(close_button_id, ImVec2(button_x, button_y))) *p_visible = false; From 99bca397d84f40312f26f80aef7e461358fe6779 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Dec 2025 11:41:54 +0100 Subject: [PATCH 1572/2359] Docs: clarify PixelSnapH / PixelSnapV + comment on PushTextWrapPos(). --- imgui.cpp | 5 +++-- imgui.h | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 58588ced4..7eaf6614d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8263,12 +8263,13 @@ void ImGui::EndDisabledOverrideReenable() g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup; } -void ImGui::PushTextWrapPos(float wrap_pos_x) +// ATTENTION THIS IS IN LEGACY LOCAL SPACE. +void ImGui::PushTextWrapPos(float wrap_local_pos_x) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos); - window->DC.TextWrapPos = wrap_pos_x; + window->DC.TextWrapPos = wrap_local_pos_x; } void ImGui::PopTextWrapPos() diff --git a/imgui.h b/imgui.h index 40493eb33..e1c73df57 100644 --- a/imgui.h +++ b/imgui.h @@ -3525,8 +3525,8 @@ struct ImFontConfig // Options bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. - bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. - bool PixelSnapV; // true // Align Scaled GlyphOffset.y to pixel boundaries. + bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Prevents fractional font size from working correctly! Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + bool PixelSnapV; // false // Align Scaled GlyphOffset.y to pixel boundaries. Prevents fractional font size from working correctly!. ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. From 4e7c05504a95e0f054fd98074fed4561b486eb21 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Dec 2025 14:30:01 +0100 Subject: [PATCH 1573/2359] Renamed IM_ARRAYSIZE() -> IM_COUNTOF(). Kept legacy name for now. --- backends/imgui_impl_dx12.cpp | 2 +- backends/imgui_impl_glfw.cpp | 2 +- backends/imgui_impl_opengl3.cpp | 2 +- backends/imgui_impl_vulkan.cpp | 4 +- backends/imgui_impl_win32.cpp | 2 +- docs/CHANGELOG.txt | 1 + docs/FONTS.md | 4 +- docs/README.md | 2 +- examples/example_glfw_vulkan/main.cpp | 6 +- examples/example_sdl2_vulkan/main.cpp | 6 +- examples/example_sdl3_vulkan/main.cpp | 6 +- examples/example_win32_vulkan/main.cpp | 6 +- imgui.cpp | 119 +++++++------- imgui.h | 6 +- imgui_demo.cpp | 212 ++++++++++++------------- imgui_draw.cpp | 22 +-- imgui_internal.h | 2 +- imgui_tables.cpp | 10 +- imgui_widgets.cpp | 52 +++--- 19 files changed, 235 insertions(+), 231 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index d4da6ab02..14c0fc60f 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -624,7 +624,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories. // See https://github.com/ocornut/imgui/pull/3696 for details. const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample - for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++) + for (int i = 0; i < IM_COUNTOF(localD3d12Paths); i++) if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr) break; diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 58cb6f1b1..35b167b28 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -454,7 +454,7 @@ static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode) { const char char_names[] = "`-=[]\\,;\'./"; const int char_keys[] = { GLFW_KEY_GRAVE_ACCENT, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_BACKSLASH, GLFW_KEY_COMMA, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, 0 }; - IM_ASSERT(IM_ARRAYSIZE(char_names) == IM_ARRAYSIZE(char_keys)); + IM_ASSERT(IM_COUNTOF(char_names) == IM_COUNTOF(char_keys)); if (key_name[0] >= '0' && key_name[0] <= '9') { key = GLFW_KEY_0 + (key_name[0] - '0'); } else if (key_name[0] >= 'A' && key_name[0] <= 'Z') { key = GLFW_KEY_A + (key_name[0] - 'A'); } else if (key_name[0] >= 'a' && key_name[0] <= 'z') { key = GLFW_KEY_A + (key_name[0] - 'a'); } diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 9b303ac08..3ead5fec6 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -387,7 +387,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) glsl_version = "#version 130"; #endif } - IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(bd->GlslVersionString)); + IM_ASSERT((int)strlen(glsl_version) + 2 < IM_COUNTOF(bd->GlslVersionString)); strcpy(bd->GlslVersionString, glsl_version); strcat(bd->GlslVersionString, "\n"); diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 21a7a8580..242fa53b3 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1002,7 +1002,7 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamic_state = {}; dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; - dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states); + dynamic_state.dynamicStateCount = (uint32_t)IM_COUNTOF(dynamic_states); dynamic_state.pDynamicStates = dynamic_states; VkGraphicsPipelineCreateInfo create_info = {}; @@ -1667,7 +1667,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V check_vk_result(err); VkImage backbuffers[16] = {}; IM_ASSERT(wd->ImageCount >= min_image_count); - IM_ASSERT(wd->ImageCount < IM_ARRAYSIZE(backbuffers)); + IM_ASSERT(wd->ImageCount < IM_COUNTOF(backbuffers)); err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers); check_vk_result(err); diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 5f42466ae..c3b7ca9cc 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -197,7 +197,7 @@ static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) "xinput1_2.dll", // DirectX SDK "xinput1_1.dll" // DirectX SDK }; - for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++) + for (int n = 0; n < IM_COUNTOF(xinput_dll_names); n++) if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n])) { bd->XInputDLL = dll; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a178da986..8931aa070 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,7 @@ Breaking Changes: identifiers using "###", and will allow fixing other dangling issues. - This will invalidate hashes (stored in .ini data) for Tables and Windows that are using the "###" operators. (#713, #1698) +- Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name. - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory (undetected since July 2015 and now spotted diff --git a/docs/FONTS.md b/docs/FONTS.md index 1a466be8d..ff2de79cc 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -202,7 +202,7 @@ if (ImGui::Button(u8"ロード")) { // do stuff } -ImGui::InputText("string", buf, IM_ARRAYSIZE(buf)); +ImGui::InputText("string", buf, IM_COUNTOF(buf)); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ``` @@ -439,7 +439,7 @@ unsigned char* tex_pixels = nullptr; int tex_width, tex_height; io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); -for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) +for (int rect_n = 0; rect_n < IM_COUNTOF(rect_ids); rect_n++) if (const ImTextureRect* rect = io.Fonts->GetCustomRect(rect_ids[rect_n])) { // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!) diff --git a/docs/README.md b/docs/README.md index 8cc36713a..782a3434f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -52,7 +52,7 @@ After Dear ImGui is set up in your application, you can use it from \_anywhere\_ ImGui::Text("Hello, world %d", 123); if (ImGui::Button("Save")) MySaveFunction(); -ImGui::InputText("string", buf, IM_ARRAYSIZE(buf)); +ImGui::InputText("string", buf, IM_COUNTOF(buf)); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ``` ![sample code output (dark, segoeui font, freetype)](https://user-images.githubusercontent.com/8225057/191050833-b7ecf528-bfae-4a9f-ac1b-f3d83437a2f4.png) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index ef307a0b3..ba5a8ad84 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -201,7 +201,7 @@ static void SetupVulkan(ImVector instance_extensions) pool_info.maxSets = 0; for (VkDescriptorPoolSize& pool_size : pool_sizes) pool_info.maxSets += pool_size.descriptorCount; - pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); + pool_info.poolSizeCount = (uint32_t)IM_COUNTOF(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); check_vk_result(err); @@ -226,7 +226,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; - wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); + wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode #ifdef APP_USE_UNLIMITED_FRAME_RATE @@ -234,7 +234,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; #endif - wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_ARRAYSIZE(present_modes)); + wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_COUNTOF(present_modes)); //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 7380edabd..2d2d906e9 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -192,7 +192,7 @@ static void SetupVulkan(ImVector instance_extensions) pool_info.maxSets = 0; for (VkDescriptorPoolSize& pool_size : pool_sizes) pool_info.maxSets += pool_size.descriptorCount; - pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); + pool_info.poolSizeCount = (uint32_t)IM_COUNTOF(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); check_vk_result(err); @@ -217,7 +217,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; - wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); + wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode #ifdef APP_USE_UNLIMITED_FRAME_RATE @@ -225,7 +225,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; #endif - wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_ARRAYSIZE(present_modes)); + wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_COUNTOF(present_modes)); //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 37e60de38..da8d73ee7 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -194,7 +194,7 @@ static void SetupVulkan(ImVector instance_extensions) pool_info.maxSets = 0; for (VkDescriptorPoolSize& pool_size : pool_sizes) pool_info.maxSets += pool_size.descriptorCount; - pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); + pool_info.poolSizeCount = (uint32_t)IM_COUNTOF(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); check_vk_result(err); @@ -219,7 +219,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; - wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); + wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode #ifdef APP_USE_UNLIMITED_FRAME_RATE @@ -227,7 +227,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; #endif - wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_ARRAYSIZE(present_modes)); + wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_COUNTOF(present_modes)); //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 64a8f9f1d..c4fe2d500 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -190,7 +190,7 @@ static void SetupVulkan(ImVector instance_extensions) pool_info.maxSets = 0; for (VkDescriptorPoolSize& pool_size : pool_sizes) pool_info.maxSets += pool_size.descriptorCount; - pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); + pool_info.poolSizeCount = (uint32_t)IM_COUNTOF(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); check_vk_result(err); @@ -215,7 +215,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; - wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); + wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode #ifdef APP_USE_UNLIMITED_FRAME_RATE @@ -223,7 +223,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; #endif - wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_ARRAYSIZE(present_modes)); + wd->PresentMode = ImGui_ImplVulkanH_SelectPresentMode(g_PhysicalDevice, wd->Surface, &present_modes[0], IM_COUNTOF(present_modes)); //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. diff --git a/imgui.cpp b/imgui.cpp index 7eaf6614d..d50a7ead2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -394,6 +394,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/12/17 (1.92.6) - Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name for now. - 2025/12/11 (1.92.6) - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore. - Before: GetID("Hello###World") == GetID("###World") != GetID("World"); - Now: GetID("Hello###World") == GetID("###World") == GetID("World"); @@ -1544,7 +1545,7 @@ ImGuiIO::ImGuiIO() { // Most fields are initialized with zero memset(this, 0, sizeof(*this)); - IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); + IM_STATIC_ASSERT(IM_COUNTOF(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_COUNTOF(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Settings ConfigFlags = ImGuiConfigFlags_None; @@ -1616,8 +1617,8 @@ ImGuiIO::ImGuiIO() MousePos = ImVec2(-FLT_MAX, -FLT_MAX); MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX); MouseSource = ImGuiMouseSource_Mouse; - for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; - for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; } + for (int i = 0; i < IM_COUNTOF(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_COUNTOF(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; } AppAcceptingEvents = true; } @@ -1725,7 +1726,7 @@ void ImGuiIO::ClearInputMouse() key_data->DownDurationPrev = -1.0f; } MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++) + for (int n = 0; n < IM_COUNTOF(MouseDown); n++) { MouseDown[n] = false; MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f; @@ -2454,7 +2455,7 @@ ImFileHandle ImFileOpen(const char* filename, const char* mode) // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314). wchar_t local_temp_stack[FILENAME_MAX]; ImVector local_temp_heap; - if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack)) + if (filename_wsize + mode_wsize > IM_COUNTOF(local_temp_stack)) 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; @@ -2969,7 +2970,7 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 CountGrep = 0; if (default_filter) { - ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); + ImStrncpy(InputBuf, default_filter, IM_COUNTOF(InputBuf)); Build(); } } @@ -2978,7 +2979,7 @@ bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); - bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + bool value_changed = ImGui::InputText(label, InputBuf, IM_COUNTOF(InputBuf)); if (value_changed) Build(); return value_changed; @@ -3602,7 +3603,7 @@ static const ImGuiStyleVarInfo GStyleVarsInfo[] = const ImGuiStyleVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx) { IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT); - IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarsInfo) == ImGuiStyleVar_COUNT); + IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT); return &GStyleVarsInfo[idx]; } @@ -4343,7 +4344,7 @@ void ImGui::Initialize() TableSettingsAddSettingsHandler(); // Setup default localization table - LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS)); + LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_COUNTOF(GLocalizationEntriesEnUS)); // Setup default ImGuiPlatformIO clipboard/IME handlers. g.PlatformIO.Platform_GetClipboardTextFn = Platform_GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations @@ -4476,7 +4477,7 @@ void ImGui::Shutdown() // (A) Will be visible in debugger, (B) Will be included in all IMGUI_DEBUG_LOG() calls, (C) Should be <= 15 characters long. void ImGui::SetContextName(ImGuiContext* ctx, const char* name) { - ImStrncpy(ctx->ContextName, name, IM_ARRAYSIZE(ctx->ContextName)); + ImStrncpy(ctx->ContextName, name, IM_COUNTOF(ctx->ContextName)); } // No specific ordering/dependency support, will see as needed @@ -5047,7 +5048,7 @@ void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr IM_UNUSED(ptr); if (entry->FrameCount != frame_count) { - info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf); + info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_COUNTOF(info->LastEntriesBuf); entry = &info->LastEntriesBuf[info->LastEntriesIdx]; entry->FrameCount = frame_count; entry->AllocCount = entry->FreeCount = 0; @@ -5132,7 +5133,7 @@ static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t draw { // Create the draw list on demand, because they are not frequently used for all viewports ImGuiContext& g = *GImGui; - IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists)); + IM_ASSERT(drawlist_no < IM_COUNTOF(viewport->BgFgDrawLists)); ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no]; if (draw_list == NULL) { @@ -5355,7 +5356,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) const bool has_open_modal = (modal_window != NULL); int mouse_earliest_down = -1; bool mouse_any_down = false; - for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) + for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++) { if (io.MouseClicked[i]) { @@ -5458,8 +5459,8 @@ void ImGui::NewFrame() // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; - g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); - g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame)); + g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_COUNTOF(g.FramerateSecPerFrame); + g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_COUNTOF(g.FramerateSecPerFrame)); g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX; // Process input queue (trickle as many events as possible), turn events into writes to IO structure @@ -5768,10 +5769,10 @@ static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder) { int n = builder->Layers[0]->Size; int full_size = n; - for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++) + for (int i = 1; i < IM_COUNTOF(builder->Layers); i++) full_size += builder->Layers[i]->Size; builder->Layers[0]->resize(full_size); - for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++) + for (int layer_n = 1; layer_n < IM_COUNTOF(builder->Layers); layer_n++) { ImVector* layer = builder->Layers[layer_n]; if (layer->empty()) @@ -6047,7 +6048,7 @@ void ImGui::Render() if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1]) AddRootWindowToDrawData(window); } - for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++) + for (int n = 0; n < IM_COUNTOF(windows_to_render_top_most); n++) if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window AddRootWindowToDrawData(windows_to_render_top_most[n]); @@ -9376,7 +9377,7 @@ static const char* const GKeyNames[] = "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY", "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names. }; -IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames)); +IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_COUNTOF(GKeyNames)); const char* ImGui::GetKeyName(ImGuiKey key) { @@ -9400,7 +9401,7 @@ const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord) const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_); if (IsLRModKey(key)) key_chord &= ~GetModForLRModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift" - ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s", + ImFormatString(g.TempKeychordName, IM_COUNTOF(g.TempKeychordName), "%s%s%s%s%s", (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "", (key_chord & ImGuiMod_Shift) ? "Shift+" : "", (key_chord & ImGuiMod_Alt) ? "Alt+" : "", @@ -9808,14 +9809,14 @@ bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id) bool ImGui::IsMouseDown(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array. } bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array. } @@ -9827,7 +9828,7 @@ bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat) bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) return false; const float t = g.IO.MouseDownDuration[button]; @@ -9849,14 +9850,14 @@ bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGui bool ImGui::IsMouseReleased(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any) } bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id) } @@ -9866,7 +9867,7 @@ bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id) bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); const float time_since_release = (float)(g.Time - g.IO.MouseReleasedTime[button]); return !IsMouseDown(button) && (time_since_release - g.IO.DeltaTime < delay) && (time_since_release >= delay); } @@ -9874,21 +9875,21 @@ bool ImGui::IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay) bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); } bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id); } int ImGui::GetMouseClickedCount(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); return g.IO.MouseClickedCount[button]; } @@ -9915,7 +9916,7 @@ bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool c bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; @@ -9924,7 +9925,7 @@ bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_thresho bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); if (!g.IO.MouseDown[button]) return false; return IsMouseDragPastThreshold(button, lock_threshold); @@ -9971,7 +9972,7 @@ bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) bool ImGui::IsAnyMouseDown() { ImGuiContext& g = *GImGui; - for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++) + for (int n = 0; n < IM_COUNTOF(g.IO.MouseDown); n++) if (g.IO.MouseDown[n]) return true; return false; @@ -9983,7 +9984,7 @@ bool ImGui::IsAnyMouseDown() ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; if (g.IO.MouseDown[button] || g.IO.MouseReleased[button]) @@ -9996,7 +9997,7 @@ ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold) void ImGui::ResetMouseDragDelta(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; - IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + IM_ASSERT(button >= 0 && button < IM_COUNTOF(g.IO.MouseDown)); // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr g.IO.MouseClickedPos[button] = g.IO.MousePos; } @@ -10139,7 +10140,7 @@ static void ImGui::UpdateMouseInputs() if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f) g.NavHighlightItemUnderNav = false; - for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) + for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++) { io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f; io.MouseClickedCount[i] = 0; // Will be filled below @@ -10346,7 +10347,7 @@ void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse) static const char* GetInputSourceName(ImGuiInputSource source) { const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" }; - IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); + IM_ASSERT(IM_COUNTOF(input_source_names) == ImGuiInputSource_COUNT); if (source < 0 || source >= ImGuiInputSource_COUNT) return "Unknown"; return input_source_names[source]; @@ -10354,7 +10355,7 @@ static const char* GetInputSourceName(ImGuiInputSource source) static const char* GetMouseSourceName(ImGuiMouseSource source) { const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" }; - IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT); + IM_ASSERT(IM_COUNTOF(mouse_source_names) == ImGuiMouseSource_COUNT); if (source < 0 || source >= ImGuiMouseSource_COUNT) return "Unknown"; return mouse_source_names[source]; @@ -11988,7 +11989,7 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext const char* window_name_template = is_dragdrop_tooltip ? "##Tooltip_DragDrop_%02d" : "##Tooltip_%02d"; char window_name[32]; - ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, g.TooltipOverrideCount); + ImFormatString(window_name, IM_COUNTOF(window_name), window_name_template, g.TooltipOverrideCount); ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; Begin(window_name, NULL, flags | extra_window_flags); // 2023-03-09: Added bool return value to the API, but currently always returning true. @@ -12344,7 +12345,7 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags) char name[20]; IM_ASSERT((extra_window_flags & ImGuiWindowFlags_ChildMenu) == 0); // Use BeginPopupMenuEx() - ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // No recycling, so we can close/open during the same frame + ImFormatString(name, IM_COUNTOF(name), "##Popup_%08x", id); // No recycling, so we can close/open during the same frame 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) @@ -12364,7 +12365,7 @@ bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags ext char name[128]; IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu); - ImFormatString(name, IM_ARRAYSIZE(name), "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth + ImFormatString(name, IM_COUNTOF(name), "%s###Menu_%02d", label, 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(); @@ -13112,7 +13113,7 @@ static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb) { if (quadrant == move_dir) { - ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center); + ImFormatString(buf, IM_COUNTOF(buf), "%.0f/%.0f", dist_box, dist_center); ImDrawList* draw_list = GetForegroundDrawList(window); draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80)); draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200)); @@ -13123,7 +13124,7 @@ static bool ImGui::NavScoreItem(ImGuiNavItemData* result, const ImRect& nav_bb) const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space)); if (debug_hovering || debug_tty) { - ImFormatString(buf, IM_ARRAYSIZE(buf), + ImFormatString(buf, IM_COUNTOF(buf), "d-box (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]); if (debug_hovering) @@ -14792,7 +14793,7 @@ bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_s cond = ImGuiCond_Always; IM_ASSERT(type != NULL); - IM_ASSERT(ImStrlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long"); + IM_ASSERT(ImStrlen(type) < 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() @@ -14800,7 +14801,7 @@ bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_s if (cond == ImGuiCond_Always || payload.DataFrameCount == -1) { // Copy payload - ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType)); + ImStrncpy(payload.DataType, type, IM_COUNTOF(payload.DataType)); g.DragDropPayloadBufHeap.resize(0); if (data_size > sizeof(g.DragDropPayloadBufLocal)) { @@ -16071,7 +16072,7 @@ void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list) if (!IsItemVisible()) return; draw_list->PushClipRect(board_min, board_max, true); - for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++) + for (int n = 0; n < IM_COUNTOF(keys_to_display); n++) { const KeyLayoutData* key_data = &keys_to_display[n]; ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y); @@ -16360,7 +16361,7 @@ void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRe char texref_desc[30]; Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors); - Text("TexRef = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texref_desc, IM_ARRAYSIZE(texref_desc), tex->GetTexRef()), tex->BackendUserData); + Text("TexRef = %s, BackendUserData = %p", FormatTextureRefForDebugDisplay(texref_desc, IM_COUNTOF(texref_desc), tex->GetTexRef()), tex->BackendUserData); TreePop(); } PopID(); @@ -16515,7 +16516,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImRect r = Funcs::GetTableRect(table, rect_n, column_n); - ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]); + ImFormatString(buf, IM_COUNTOF(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]); Selectable(buf); if (IsItemHovered()) GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); @@ -16524,7 +16525,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) else { ImRect r = Funcs::GetTableRect(table, rect_n, -1); - ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]); + ImFormatString(buf, IM_COUNTOF(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]); Selectable(buf); if (IsItemHovered()) GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); @@ -16548,7 +16549,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) { static char buf[64] = ""; SetNextItemWidth(-FLT_MIN); - InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf)); + InputText("##DebugTextEncodingBuf", buf, IM_COUNTOF(buf)); if (buf[0] != 0) DebugTextEncoding(buf); } @@ -16742,7 +16743,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount); if (SmallButton("GC now")) { g.GcCompactAll = true; } Text("Recent frames with allocations:"); - int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf); + int buf_size = IM_COUNTOF(info->LastEntriesBuf); for (int n = buf_size - 1; n >= 0; n--) { ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size]; @@ -16779,7 +16780,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) else Text("Mouse pos: "); Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); - int count = IM_ARRAYSIZE(io.MouseDown); + int count = IM_COUNTOF(io.MouseDown); Text("Mouse down:"); for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } Text("Mouse clicked:"); for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); } Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); } @@ -16910,7 +16911,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow)) { char buf[32]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); + ImFormatString(buf, IM_COUNTOF(buf), "%d", window->BeginOrderWithinContext); float font_size = GetFontSize(); draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf); @@ -17061,9 +17062,9 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con } char texid_desc[30]; - FormatTextureRefForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TexRef); + FormatTextureRefForDebugDisplay(texid_desc, IM_COUNTOF(texid_desc), pcmd->TexRef); char buf[300]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + ImFormatString(buf, IM_COUNTOF(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list) @@ -17085,7 +17086,7 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con } // Display vertex information summary. Hover to get all triangles drawn in wire-frame - ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); + ImFormatString(buf, IM_COUNTOF(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); Selectable(buf); if (IsItemHovered() && fg_draw_list) DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false); @@ -17096,7 +17097,7 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con while (clipper.Step()) for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) { - char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf); + char* buf_p = buf, * buf_end = buf + IM_COUNTOF(buf); ImVec2 triangle[3]; for (int n = 0; n < 3; n++, idx_i++) { @@ -17401,7 +17402,7 @@ void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label) // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. char buf[256]; char* p = buf; - const char* buf_end = buf + IM_ARRAYSIZE(buf); + const char* buf_end = buf + IM_COUNTOF(buf); const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2); p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) @@ -17559,7 +17560,7 @@ void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int wi if (window->ParentWindowInBeginStack != parent_in_begin_stack) continue; char buf[20]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext); + ImFormatString(buf, IM_COUNTOF(buf), "[%04d] Window", window->BeginOrderWithinContext); //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name); DebugNodeWindow(window, buf); TreePush(buf); @@ -17993,7 +17994,7 @@ static const char* DebugItemPathQuery_GetResultAsPath(ImGuiDebugItemPathQuery* q for (int stack_n = 0; stack_n < query->Results.Size; stack_n++) { char level_desc[256]; - DebugItemPathQuery_FormatLevelInfo(query, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); + DebugItemPathQuery_FormatLevelInfo(query, stack_n, false, level_desc, IM_COUNTOF(level_desc)); buf->append(stack_n == 0 ? "//" : "/"); for (const char* p = level_desc; *p != 0; ) { diff --git a/imgui.h b/imgui.h index e1c73df57..a336ccd06 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19255 +#define IMGUI_VERSION_NUM 19256 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -95,7 +95,7 @@ Index of this file: #include #define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h #endif -#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! +#define IM_COUNTOF(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! #define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. #define IM_STRINGIFY_HELPER(_EXPR) #_EXPR #define IM_STRINGIFY(_EXPR) IM_STRINGIFY_HELPER(_EXPR) // Preprocessor idiom to stringify e.g. an integer or a macro. @@ -4151,6 +4151,8 @@ typedef ImFontAtlasRect ImFontAtlasCustomRect; #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +#define IM_ARRAYSIZE IM_COUNTOF // RENAMED IN 1.92.6: IM_ARRAYSIZE -> IM_COUNTOF + // RENAMED IMGUI_DISABLE_METRICS_WINDOW > IMGUI_DISABLE_DEBUG_TOOLS in 1.88 (from June 2022) #ifdef IMGUI_DISABLE_METRICS_WINDOW #error IMGUI_DISABLE_METRICS_WINDOW was renamed to IMGUI_DISABLE_DEBUG_TOOLS, please use new name. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index beb181986..b5d7e0b4e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -764,7 +764,7 @@ static const ExampleMemberInfo ExampleTreeNodeMemberInfos[] static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, ExampleTreeNode* parent) { ExampleTreeNode* node = IM_NEW(ExampleTreeNode); - snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name); + snprintf(node->Name, IM_COUNTOF(node->Name), "%s", name); node->UID = uid; node->Parent = parent; node->IndexInParent = parent ? (unsigned short)parent->Childs.Size : 0; @@ -790,19 +790,19 @@ static ExampleTreeNode* ExampleTree_CreateDemoTree() int uid = 0; ExampleTreeNode* node_L0 = ExampleTree_CreateNode("", ++uid, NULL); const int root_items_multiplier = 2; - for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * root_items_multiplier; idx_L0++) + for (int idx_L0 = 0; idx_L0 < IM_COUNTOF(root_names) * root_items_multiplier; idx_L0++) { - snprintf(name_buf, IM_ARRAYSIZE(name_buf), "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier); + snprintf(name_buf, IM_COUNTOF(name_buf), "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier); ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0); const int number_of_childs = (int)strlen(node_L1->Name); for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++) { - snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Child %d", idx_L1); + snprintf(name_buf, IM_COUNTOF(name_buf), "Child %d", idx_L1); ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1); node_L2->HasData = true; if (idx_L1 == 0) { - snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Sub-child %d", 0); + snprintf(name_buf, IM_COUNTOF(name_buf), "Sub-child %d", 0); ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2); node_L3->HasData = true; } @@ -892,7 +892,7 @@ static void DemoWindowWidgetsBasic() // - Otherwise, see the 'Dear ImGui Demo->Widgets->Text Input->Resize Callback' for using ImGuiInputTextFlags_CallbackResize. IMGUI_DEMO_MARKER("Widgets/Basic/InputText"); static char str0[128] = "Hello, world!"; - ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); + ImGui::InputText("input text", str0, IM_COUNTOF(str0)); ImGui::SameLine(); HelpMarker( "USER:\n" "Hold Shift or use mouse to select text.\n" @@ -907,7 +907,7 @@ static void DemoWindowWidgetsBasic() "in imgui_demo.cpp)."); static char str1[128] = ""; - ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1)); + ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_COUNTOF(str1)); IMGUI_DEMO_MARKER("Widgets/Basic/InputInt, InputFloat"); static int i0 = 123; @@ -998,7 +998,7 @@ static void DemoWindowWidgetsBasic() IMGUI_DEMO_MARKER("Widgets/Basic/Combo"); const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }; static int item_current = 0; - ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items)); + ImGui::Combo("combo", &item_current, items, IM_COUNTOF(items)); ImGui::SameLine(); HelpMarker( "Using the simplified one-liner Combo API here.\n" "Refer to the \"Combo\" section below for an explanation of how to use the more flexible and general BeginCombo/EndCombo API."); @@ -1010,7 +1010,7 @@ static void DemoWindowWidgetsBasic() IMGUI_DEMO_MARKER("Widgets/Basic/ListBox"); const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; static int item_current = 1; - ImGui::ListBox("listbox", &item_current, items, IM_ARRAYSIZE(items), 4); + ImGui::ListBox("listbox", &item_current, items, IM_COUNTOF(items), 4); ImGui::SameLine(); HelpMarker( "Using the simplified one-liner ListBox API here.\n" "Refer to the \"List boxes\" section below for an explanation of how to use the more flexible and general BeginListBox/EndListBox API."); @@ -1133,7 +1133,7 @@ static void DemoWindowWidgetsColorAndPickers() static ImVec4 saved_palette[32] = {}; if (saved_palette_init) { - for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) + for (int n = 0; n < IM_COUNTOF(saved_palette); n++) { ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); @@ -1166,7 +1166,7 @@ static void DemoWindowWidgetsColorAndPickers() color = backup_color; ImGui::Separator(); ImGui::Text("Palette"); - for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) + for (int n = 0; n < IM_COUNTOF(saved_palette); n++) { ImGui::PushID(n); if ((n % 8) != 0) @@ -1319,7 +1319,7 @@ static void DemoWindowWidgetsComboBoxes() const char* combo_preview_value = items[item_selected_idx]; if (ImGui::BeginCombo("combo 1", combo_preview_value, flags)) { - for (int n = 0; n < IM_ARRAYSIZE(items); n++) + for (int n = 0; n < IM_COUNTOF(items); n++) { const bool is_selected = (item_selected_idx == n); if (ImGui::Selectable(items[n], is_selected)) @@ -1345,7 +1345,7 @@ static void DemoWindowWidgetsComboBoxes() ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); filter.Draw("##Filter", -FLT_MIN); - for (int n = 0; n < IM_ARRAYSIZE(items); n++) + for (int n = 0; n < IM_COUNTOF(items); n++) { const bool is_selected = (item_selected_idx == n); if (filter.PassFilter(items[n])) @@ -1367,11 +1367,11 @@ static void DemoWindowWidgetsComboBoxes() // Simplified one-liner Combo() using an array of const char* // This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview - ImGui::Combo("combo 4 (array)", &item_current_3, items, IM_ARRAYSIZE(items)); + ImGui::Combo("combo 4 (array)", &item_current_3, items, IM_COUNTOF(items)); // 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_ARRAYSIZE(items)); + ImGui::Combo("combo 5 (function)", &item_current_4, [](void* data, int n) { return ((const char**)data)[n]; }, items, IM_COUNTOF(items)); ImGui::TreePop(); } @@ -1570,7 +1570,7 @@ static void DemoWindowWidgetsDragAndDrop() "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }; - for (int n = 0; n < IM_ARRAYSIZE(names); n++) + for (int n = 0; n < IM_COUNTOF(names); n++) { ImGui::PushID(n); if ((n % 3) != 0) @@ -1632,7 +1632,7 @@ static void DemoWindowWidgetsDragAndDrop() "We don't use the drag and drop api at all here! " "Instead we query when the item is held but not hovered, and order items accordingly."); static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }; - for (int n = 0; n < IM_ARRAYSIZE(item_names); n++) + for (int n = 0; n < IM_COUNTOF(item_names); n++) { const char* item = item_names[n]; ImGui::Selectable(item); @@ -1640,7 +1640,7 @@ static void DemoWindowWidgetsDragAndDrop() if (ImGui::IsItemActive() && !ImGui::IsItemHovered()) { int n_next = n + (ImGui::GetMouseDragDelta(0).y < 0.f ? -1 : 1); - if (n_next >= 0 && n_next < IM_ARRAYSIZE(item_names)) + if (n_next >= 0 && n_next < IM_COUNTOF(item_names)) { item_names[n] = item_names[n_next]; item_names[n_next] = item; @@ -1880,7 +1880,7 @@ static void DemoWindowWidgetsListBoxes() if (ImGui::BeginListBox("listbox 1")) { - for (int n = 0; n < IM_ARRAYSIZE(items); n++) + for (int n = 0; n < IM_COUNTOF(items); n++) { const bool is_selected = (item_selected_idx == n); if (ImGui::Selectable(items[n], is_selected)) @@ -1901,7 +1901,7 @@ static void DemoWindowWidgetsListBoxes() ImGui::Text("Full-width:"); if (ImGui::BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui::GetTextLineHeightWithSpacing()))) { - for (int n = 0; n < IM_ARRAYSIZE(items); n++) + for (int n = 0; n < IM_COUNTOF(items); n++) { bool is_selected = (item_selected_idx == n); ImGuiSelectableFlags flags = (item_highlighted_idx == n) ? ImGuiSelectableFlags_Highlight : 0; @@ -1987,8 +1987,8 @@ static void DemoWindowWidgetsPlotting() // Plot as lines and plot as histogram static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); - ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); + ImGui::PlotLines("Frame Times", arr, IM_COUNTOF(arr)); + ImGui::PlotHistogram("Histogram", arr, IM_COUNTOF(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); //ImGui::SameLine(); HelpMarker("Consider using ImPlot instead!"); // Fill an array of contiguous float values to plot @@ -2003,7 +2003,7 @@ static void DemoWindowWidgetsPlotting() { static float phase = 0.0f; values[values_offset] = cosf(phase); - values_offset = (values_offset + 1) % IM_ARRAYSIZE(values); + values_offset = (values_offset + 1) % IM_COUNTOF(values); phase += 0.10f * values_offset; refresh_time += 1.0f / 60.0f; } @@ -2012,12 +2012,12 @@ static void DemoWindowWidgetsPlotting() // (in this example, we will display an average value) { float average = 0.0f; - for (int n = 0; n < IM_ARRAYSIZE(values); n++) + for (int n = 0; n < IM_COUNTOF(values); n++) average += values[n]; - average /= (float)IM_ARRAYSIZE(values); + average /= (float)IM_COUNTOF(values); char overlay[32]; sprintf(overlay, "avg %f", average); - ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); + ImGui::PlotLines("Lines", values, IM_COUNTOF(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); } // Use functions to generate output @@ -2096,7 +2096,7 @@ static void DemoWindowWidgetsQueryingStatuses() }; static int item_type = 4; static bool item_disabled = false; - ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names)); + ImGui::Combo("Item Type", &item_type, item_names, IM_COUNTOF(item_names), IM_COUNTOF(item_names)); ImGui::SameLine(); HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui::IsItemHovered()."); ImGui::Checkbox("Item Disabled", &item_disabled); @@ -2113,8 +2113,8 @@ static void DemoWindowWidgetsQueryingStatuses() if (item_type == 2) { ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); ret = ImGui::Button("ITEM: Button"); ImGui::PopItemFlag(); } // Testing button (with repeater) if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item - if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) - if (item_type == 6) { ret = ImGui::InputTextMultiline("ITEM: InputTextMultiline", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which uses a child window) + if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_COUNTOF(str)); } // Testing input text (which handles tabbing) + if (item_type == 6) { ret = ImGui::InputTextMultiline("ITEM: InputTextMultiline", &str[0], IM_COUNTOF(str)); } // Testing input text (which uses a child window) if (item_type == 7) { ret = ImGui::InputFloat("ITEM: InputFloat", col4f, 1.0f); } // Testing +/- buttons on scalar input if (item_type == 8) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) if (item_type == 9) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) @@ -2122,8 +2122,8 @@ static void DemoWindowWidgetsQueryingStatuses() if (item_type == 11) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) if (item_type == 12) { ret = ImGui::TreeNode("ITEM: TreeNode"); if (ret) ImGui::TreePop(); } // Testing tree node if (item_type == 13) { ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. - if (item_type == 14) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::Combo("ITEM: Combo", ¤t, items, IM_ARRAYSIZE(items)); } - if (item_type == 15) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } + if (item_type == 14) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::Combo("ITEM: Combo", ¤t, items, IM_COUNTOF(items)); } + if (item_type == 15) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_COUNTOF(items), IM_COUNTOF(items)); } bool hovered_delay_none = ImGui::IsItemHovered(); bool hovered_delay_stationary = ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary); @@ -2190,7 +2190,7 @@ static void DemoWindowWidgetsQueryingStatuses() ImGui::EndDisabled(); char buf[1] = ""; - ImGui::InputText("unused", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_ReadOnly); + ImGui::InputText("unused", buf, IM_COUNTOF(buf), ImGuiInputTextFlags_ReadOnly); ImGui::SameLine(); HelpMarker("This widget is only here to be able to tab-out of the widgets above and see e.g. Deactivated() status."); @@ -2726,7 +2726,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d for (int n = 0; n < ITEMS_COUNT; n++) { char label[64]; - sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_COUNTOF(ExampleNames)]); bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); @@ -2766,7 +2766,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++) { char label[64]; - sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_COUNTOF(ExampleNames)]); bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); @@ -2828,7 +2828,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d { const ImGuiID item_id = items[n]; char label[64]; - sprintf(label, "Object %05u: %s", item_id, ExampleNames[item_id % IM_ARRAYSIZE(ExampleNames)]); + sprintf(label, "Object %05u: %s", item_id, ExampleNames[item_id % IM_COUNTOF(ExampleNames)]); bool item_is_selected = selection.Contains(item_id); ImGui::SetNextItemSelectionUserData(n); @@ -2854,7 +2854,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // Init default state static ExampleDualListBox dlb; if (dlb.Items[0].Size == 0 && dlb.Items[1].Size == 0) - for (int item_id = 0; item_id < IM_ARRAYSIZE(ExampleNames); item_id++) + for (int item_id = 0; item_id < IM_COUNTOF(ExampleNames); item_id++) dlb.Items[0].push_back((ImGuiID)item_id); // Show @@ -2894,7 +2894,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::TableNextColumn(); ImGui::PushID(n); char label[64]; - sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_COUNTOF(ExampleNames)]); bool item_is_selected = selection.Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap); @@ -2928,7 +2928,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) { - ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, -1, IM_ARRAYSIZE(items)); + ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, -1, IM_COUNTOF(items)); ImGuiSelectionExternalStorage storage_wrapper; storage_wrapper.UserData = (void*)items; storage_wrapper.AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int n, bool selected) { bool* array = (bool*)self->UserData; array[n] = selected; }; @@ -2979,7 +2979,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d for (int n = 0; n < ITEMS_COUNT; n++) { char label[64]; - sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]); + sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_COUNTOF(ExampleNames)]); bool item_is_selected = selection->Contains((ImGuiID)n); ImGui::SetNextItemSelectionUserData(n); ImGui::Selectable(label, item_is_selected); @@ -3268,7 +3268,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::TableNextColumn(); const int item_id = items[n]; - const char* item_category = ExampleNames[item_id % IM_ARRAYSIZE(ExampleNames)]; + const char* item_category = ExampleNames[item_id % IM_COUNTOF(ExampleNames)]; char label[64]; sprintf(label, "Object %05d: %s", item_id, item_category); @@ -3330,7 +3330,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d const int* payload_items = (int*)payload->Data; const int payload_count = (int)payload->DataSize / (int)sizeof(int); if (payload_count == 1) - ImGui::Text("Object %05d: %s", payload_items[0], ExampleNames[payload_items[0] % IM_ARRAYSIZE(ExampleNames)]); + ImGui::Text("Object %05d: %s", payload_items[0], ExampleNames[payload_items[0] % IM_COUNTOF(ExampleNames)]); else ImGui::Text("Dragging %d objects", payload_count); @@ -3456,7 +3456,7 @@ static void DemoWindowWidgetsTabs() ImGui::Text("Opened:"); const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" }; static bool opened[4] = { true, true, true, true }; // Persistent user state - for (int n = 0; n < IM_ARRAYSIZE(opened); n++) + for (int n = 0; n < IM_COUNTOF(opened); n++) { ImGui::SameLine(); ImGui::Checkbox(names[n], &opened[n]); @@ -3466,7 +3466,7 @@ static void DemoWindowWidgetsTabs() // the underlying bool will be set to false when the tab is closed. if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) { - for (int n = 0; n < IM_ARRAYSIZE(opened); n++) + for (int n = 0; n < IM_COUNTOF(opened); n++) if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None)) { ImGui::Text("This is the %s tab!", names[n]); @@ -3525,7 +3525,7 @@ static void DemoWindowWidgetsTabs() { bool open = true; char name[16]; - snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]); + snprintf(name, IM_COUNTOF(name), "%04d", active_tabs[n]); if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None)) { ImGui::Text("This is the %s tab!", name); @@ -3659,7 +3659,7 @@ static void DemoWindowWidgetsText() ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; //static char buf[32] = u8"NIHONGO"; // <- this is how you would write it with C++11, using real kanjis - ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("UTF-8 input", buf, IM_COUNTOF(buf)); ImGui::TreePop(); } ImGui::TreePop(); @@ -3686,7 +3686,7 @@ static void DemoWindowWidgetsTextFilter() " \"-xxx\" hide lines containing \"xxx\""); filter.Draw(); const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; - for (int i = 0; i < IM_ARRAYSIZE(lines); i++) + for (int i = 0; i < IM_COUNTOF(lines); i++) if (filter.PassFilter(lines[i])) ImGui::BulletText("%s", lines[i]); ImGui::TreePop(); @@ -3731,7 +3731,7 @@ static void DemoWindowWidgetsTextInput() ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput); ImGui::SameLine(); HelpMarker("When _AllowTabInput is set, passing through the widget with Tabbing doesn't automatically activate it, in order to also cycling through subsequent widgets."); ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine); - ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); + ImGui::InputTextMultiline("##source", text, IM_COUNTOF(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); ImGui::TreePop(); } @@ -3757,13 +3757,13 @@ static void DemoWindowWidgetsTextInput() } }; - static char buf1[32] = ""; ImGui::InputText("default", buf1, IM_ARRAYSIZE(buf1)); - static char buf2[32] = ""; ImGui::InputText("decimal", buf2, IM_ARRAYSIZE(buf2), ImGuiInputTextFlags_CharsDecimal); - static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, IM_ARRAYSIZE(buf3), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, IM_ARRAYSIZE(buf4), ImGuiInputTextFlags_CharsUppercase); - static char buf5[32] = ""; ImGui::InputText("no blank", buf5, IM_ARRAYSIZE(buf5), ImGuiInputTextFlags_CharsNoBlank); - static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, IM_ARRAYSIZE(buf6), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. - static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, IM_ARRAYSIZE(buf7), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. + static char buf1[32] = ""; ImGui::InputText("default", buf1, IM_COUNTOF(buf1)); + static char buf2[32] = ""; ImGui::InputText("decimal", buf2, IM_COUNTOF(buf2), ImGuiInputTextFlags_CharsDecimal); + static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, IM_COUNTOF(buf3), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, IM_COUNTOF(buf4), ImGuiInputTextFlags_CharsUppercase); + static char buf5[32] = ""; ImGui::InputText("no blank", buf5, IM_COUNTOF(buf5), ImGuiInputTextFlags_CharsNoBlank); + static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, IM_COUNTOF(buf6), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. + static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, IM_COUNTOF(buf7), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. ImGui::TreePop(); } @@ -3771,10 +3771,10 @@ static void DemoWindowWidgetsTextInput() if (ImGui::TreeNode("Password Input")) { static char password[64] = "password123"; - ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); + ImGui::InputText("password", password, IM_COUNTOF(password), ImGuiInputTextFlags_Password); ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); - ImGui::InputTextWithHint("password (w/ hint)", "", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); - ImGui::InputText("password (clear)", password, IM_ARRAYSIZE(password)); + ImGui::InputTextWithHint("password (w/ hint)", "", password, IM_COUNTOF(password), ImGuiInputTextFlags_Password); + ImGui::InputText("password (clear)", password, IM_COUNTOF(password)); ImGui::TreePop(); } @@ -3819,20 +3819,20 @@ static void DemoWindowWidgetsTextInput() } }; static char buf1[64]; - ImGui::InputText("Completion", buf1, IM_ARRAYSIZE(buf1), ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); + ImGui::InputText("Completion", buf1, IM_COUNTOF(buf1), ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); ImGui::SameLine(); HelpMarker( "Here we append \"..\" each time Tab is pressed. " "See 'Examples>Console' for a more meaningful demonstration of using this callback."); static char buf2[64]; - ImGui::InputText("History", buf2, IM_ARRAYSIZE(buf2), ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); + ImGui::InputText("History", buf2, IM_COUNTOF(buf2), ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); ImGui::SameLine(); HelpMarker( "Here we replace and select text each time Up/Down are pressed. " "See 'Examples>Console' for a more meaningful demonstration of using this callback."); static char buf3[64]; static int edit_count = 0; - ImGui::InputText("Edit", buf3, IM_ARRAYSIZE(buf3), ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); + ImGui::InputText("Edit", buf3, IM_COUNTOF(buf3), ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); ImGui::SameLine(); HelpMarker( "Here we toggle the casing of the first character on every edit + count edits."); ImGui::SameLine(); ImGui::Text("(%d)", edit_count); @@ -3892,7 +3892,7 @@ static void DemoWindowWidgetsTextInput() static char buf1[128] = "/path/to/some/folder/with/long/filename.cpp"; static ImGuiInputTextFlags flags = ImGuiInputTextFlags_ElideLeft; ImGui::CheckboxFlags("ImGuiInputTextFlags_ElideLeft", &flags, ImGuiInputTextFlags_ElideLeft); - ImGui::InputText("Path", buf1, IM_ARRAYSIZE(buf1), flags); + ImGui::InputText("Path", buf1, IM_COUNTOF(buf1), flags); ImGui::TreePop(); } @@ -3904,7 +3904,7 @@ static void DemoWindowWidgetsTextInput() ImGui::CheckboxFlags("ImGuiInputTextFlags_EscapeClearsAll", &flags, ImGuiInputTextFlags_EscapeClearsAll); ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); ImGui::CheckboxFlags("ImGuiInputTextFlags_NoUndoRedo", &flags, ImGuiInputTextFlags_NoUndoRedo); - ImGui::InputText("Hello", buf1, IM_ARRAYSIZE(buf1), flags); + ImGui::InputText("Hello", buf1, IM_COUNTOF(buf1), flags); ImGui::TreePop(); } @@ -3946,7 +3946,7 @@ static void DemoWindowWidgetsTooltips() { ImGui::Text("I am a fancy tooltip"); static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); + ImGui::PlotLines("Curve", arr, IM_COUNTOF(arr)); ImGui::Text("Sin(time) = %f", sinf((float)ImGui::GetTime())); ImGui::EndTooltip(); } @@ -4585,7 +4585,7 @@ static void DemoWindowLayout() ImGui::PushItemWidth(ImGui::CalcTextSize("AAAAAAA").x); const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; static int item = -1; - ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); + ImGui::Combo("Combo", &item, items, IM_COUNTOF(items)); ImGui::SameLine(); ImGui::SliderFloat("X", &f0, 0.0f, 5.0f); ImGui::SameLine(); ImGui::SliderFloat("Y", &f1, 0.0f, 5.0f); ImGui::SameLine(); ImGui::SliderFloat("Z", &f2, 0.0f, 5.0f); @@ -4596,7 +4596,7 @@ static void DemoWindowLayout() { if (i > 0) ImGui::SameLine(); ImGui::PushID(i); - ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); + ImGui::ListBox("", &selection[i], items, IM_COUNTOF(items)); ImGui::PopID(); //ImGui::SetItemTooltip("ListBox %d hovered", i); } @@ -4656,7 +4656,7 @@ static void DemoWindowLayout() // Capture the group size and create widgets using the same size ImVec2 size = ImGui::GetItemRectSize(); const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; - ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); + ImGui::PlotHistogram("##values", values, IM_COUNTOF(values), 0, NULL, 0.0f, 1.0f, size); ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); ImGui::SameLine(); @@ -5240,7 +5240,7 @@ static void DemoWindowPopups() if (ImGui::BeginPopup("my_select_popup")) { ImGui::SeparatorText("Aquarium"); - for (int i = 0; i < IM_ARRAYSIZE(names); i++) + for (int i = 0; i < IM_COUNTOF(names); i++) if (ImGui::Selectable(names[i])) selected_fish = i; ImGui::EndPopup(); @@ -5251,7 +5251,7 @@ static void DemoWindowPopups() ImGui::OpenPopup("my_toggle_popup"); if (ImGui::BeginPopup("my_toggle_popup")) { - for (int i = 0; i < IM_ARRAYSIZE(names); i++) + for (int i = 0; i < IM_COUNTOF(names); i++) ImGui::MenuItem(names[i], "", &toggles[i]); if (ImGui::BeginMenu("Sub-menu")) { @@ -5267,7 +5267,7 @@ static void DemoWindowPopups() ImGui::OpenPopup("another popup"); if (ImGui::BeginPopup("another popup")) { - for (int i = 0; i < IM_ARRAYSIZE(names); i++) + for (int i = 0; i < IM_COUNTOF(names); i++) ImGui::MenuItem(names[i], "", &toggles[i]); if (ImGui::BeginMenu("Sub-menu")) { @@ -5389,7 +5389,7 @@ static void DemoWindowPopups() if (ImGui::BeginPopupContextItem()) { ImGui::Text("Edit name:"); - ImGui::InputText("##edit", name, IM_ARRAYSIZE(name)); + ImGui::InputText("##edit", name, IM_COUNTOF(name)); if (ImGui::Button("Close")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); @@ -5594,13 +5594,13 @@ static void EditTableSizingFlags(ImGuiTableFlags* p_flags) { ImGuiTableFlags_SizingStretchSame, "ImGuiTableFlags_SizingStretchSame", "Columns default to _WidthStretch with same weights." } }; int idx; - for (idx = 0; idx < IM_ARRAYSIZE(policies); idx++) + for (idx = 0; idx < IM_COUNTOF(policies); idx++) if (policies[idx].Value == (*p_flags & ImGuiTableFlags_SizingMask_)) break; - const char* preview_text = (idx < IM_ARRAYSIZE(policies)) ? policies[idx].Name + (idx > 0 ? strlen("ImGuiTableFlags") : 0) : ""; + const char* preview_text = (idx < IM_COUNTOF(policies)) ? policies[idx].Name + (idx > 0 ? strlen("ImGuiTableFlags") : 0) : ""; if (ImGui::BeginCombo("Sizing Policy", preview_text)) { - for (int n = 0; n < IM_ARRAYSIZE(policies); n++) + for (int n = 0; n < IM_COUNTOF(policies); n++) if (ImGui::Selectable(policies[n].Name, idx == n)) *p_flags = (*p_flags & ~ImGuiTableFlags_SizingMask_) | policies[n].Value; ImGui::EndCombo(); @@ -5610,7 +5610,7 @@ static void EditTableSizingFlags(ImGuiTableFlags* p_flags) if (ImGui::BeginItemTooltip()) { ImGui::PushTextWrapPos(ImGui::GetFontSize() * 50.0f); - for (int m = 0; m < IM_ARRAYSIZE(policies); m++) + for (int m = 0; m < IM_COUNTOF(policies); m++) { ImGui::Separator(); ImGui::Text("%s:", policies[m].Name); @@ -6108,7 +6108,7 @@ static void DemoWindowTables() strcpy(text_bufs[cell], "edit me"); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::PushID(cell); - ImGui::InputText("##cell", text_bufs[cell], IM_ARRAYSIZE(text_bufs[cell])); + ImGui::InputText("##cell", text_bufs[cell], IM_COUNTOF(text_bufs[cell])); ImGui::PopID(); } if (!show_widget_frame_bg) @@ -6221,7 +6221,7 @@ static void DemoWindowTables() case CT_ShowWidth: ImGui::Text("W: %.1f", ImGui::GetContentRegionAvail().x); break; case CT_Button: ImGui::Button(label); break; case CT_FillButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break; - case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_ARRAYSIZE(text_buf)); break; + case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_COUNTOF(text_buf)); break; } ImGui::PopID(); } @@ -6940,7 +6940,7 @@ static void DemoWindowTables() if (ImGui::TreeNode("Angled headers")) { const char* column_names[] = { "Track", "cabasa", "ride", "smash", "tom-hi", "tom-mid", "tom-low", "hihat-o", "hihat-c", "snare-s", "snare-c", "clap", "rim", "kick" }; - const int columns_count = IM_ARRAYSIZE(column_names); + const int columns_count = IM_COUNTOF(column_names); const int rows_count = 12; static ImGuiTableFlags table_flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_Hideable | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_HighlightHoveredColumn; @@ -7169,7 +7169,7 @@ static void DemoWindowTables() items.resize(50, MyItem()); for (int n = 0; n < items.Size; n++) { - const int template_n = n % IM_ARRAYSIZE(template_items_names); + const int template_n = n % IM_COUNTOF(template_items_names); MyItem& item = items[n]; item.ID = n; item.Name = template_items_names[template_n]; @@ -7260,7 +7260,7 @@ static void DemoWindowTables() const char* contents_type_names[] = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" }; static int freeze_cols = 1; static int freeze_rows = 1; - static int items_count = IM_ARRAYSIZE(template_items_names) * 2; + static int items_count = IM_COUNTOF(template_items_names) * 2; static ImVec2 outer_size_value = ImVec2(0.0f, TEXT_BASE_HEIGHT * 12); static float row_min_height = 0.0f; // Auto static float inner_width_with_scroll = 0.0f; // Auto-extend @@ -7378,7 +7378,7 @@ static void DemoWindowTables() ImGui::SameLine(); HelpMarker("Specify height of the Selectable item."); ImGui::DragInt("items_count", &items_count, 0.1f, 0, 9999); - ImGui::Combo("items_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names)); + ImGui::Combo("items_type (first column)", &contents_type, contents_type_names, IM_COUNTOF(contents_type_names)); //filter.Draw("filter"); ImGui::TreePop(); } @@ -7398,7 +7398,7 @@ static void DemoWindowTables() items.resize(items_count, MyItem()); for (int n = 0; n < items_count; n++) { - const int template_n = n % IM_ARRAYSIZE(template_items_names); + const int template_n = n % IM_COUNTOF(template_items_names); MyItem& item = items[n]; item.ID = n; item.Name = template_items_names[template_n]; @@ -7800,10 +7800,10 @@ static void DemoWindowInputs() ImGui::Text("Mouse pos: "); ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); ImGui::Text("Mouse down:"); - for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDown(i)) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++) if (ImGui::IsMouseDown(i)) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); ImGui::Text("Mouse clicked count:"); - for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseClickedCount[i] > 0) { ImGui::SameLine(); ImGui::Text("b%d: %d", i, io.MouseClickedCount[i]); } + for (int i = 0; i < IM_COUNTOF(io.MouseDown); i++) if (io.MouseClickedCount[i] > 0) { ImGui::SameLine(); ImGui::Text("b%d: %d", i, io.MouseClickedCount[i]); } // We iterate both legacy native range and named ImGuiKey ranges. This is a little unusual/odd but this allows // displaying the data for old/new backends. @@ -7926,7 +7926,7 @@ static void DemoWindowInputs() // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) //char str[16] = "Press Ctrl+A"; //ImGui::Spacing(); - //ImGui::InputText("InputTextB", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly); + //ImGui::InputText("InputTextB", str, IM_COUNTOF(str), ImGuiInputTextFlags_ReadOnly); //ImGuiID item_id = ImGui::GetItemID(); //ImGui::SameLine(); HelpMarker("Internal widgets always use _RouteFocused"); //ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags, item_id) ? "PRESSED" : "..."); @@ -7951,7 +7951,7 @@ static void DemoWindowInputs() ImGui::Text("(in PopupF)"); ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) - //ImGui::InputText("InputTextG", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly); + //ImGui::InputText("InputTextG", str, IM_COUNTOF(str), ImGuiInputTextFlags_ReadOnly); //ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags, ImGui::GetItemID()) ? "PRESSED" : "..."); ImGui::EndPopup(); } @@ -7966,7 +7966,7 @@ static void DemoWindowInputs() if (ImGui::TreeNode("Mouse Cursors")) { const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "Wait", "Progress", "NotAllowed" }; - IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT); + IM_ASSERT(IM_COUNTOF(mouse_cursors_names) == ImGuiMouseCursor_COUNT); ImGuiMouseCursor current = ImGui::GetMouseCursor(); const char* cursor_name = (current >= ImGuiMouseCursor_Arrow) && (current < ImGuiMouseCursor_COUNT) ? mouse_cursors_names[current] : "N/A"; @@ -7996,14 +7996,14 @@ static void DemoWindowInputs() { ImGui::Text("Use Tab/Shift+Tab to cycle through keyboard editable fields."); static char buf[32] = "hello"; - ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); - ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); - ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("1", buf, IM_COUNTOF(buf)); + ImGui::InputText("2", buf, IM_COUNTOF(buf)); + ImGui::InputText("3", buf, IM_COUNTOF(buf)); ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, true); - ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("4 (tab skip)", buf, IM_COUNTOF(buf)); ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab."); ImGui::PopItemFlag(); - ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("5", buf, IM_COUNTOF(buf)); ImGui::TreePop(); } @@ -8017,16 +8017,16 @@ static void DemoWindowInputs() static char buf[128] = "click on a button to set focus"; if (focus_1) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("1", buf, IM_COUNTOF(buf)); if (ImGui::IsItemActive()) has_focus = 1; if (focus_2) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("2", buf, IM_COUNTOF(buf)); if (ImGui::IsItemActive()) has_focus = 2; ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, true); if (focus_3) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("3 (tab skip)", buf, IM_COUNTOF(buf)); if (ImGui::IsItemActive()) has_focus = 3; ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab."); ImGui::PopItemFlag(); @@ -8284,9 +8284,9 @@ bool ImGui::ShowStyleSelector(const char* label) static int style_idx = -1; const char* style_names[] = { "Dark", "Light", "Classic" }; bool ret = false; - if (ImGui::BeginCombo(label, (style_idx >= 0 && style_idx < IM_ARRAYSIZE(style_names)) ? style_names[style_idx] : "")) + if (ImGui::BeginCombo(label, (style_idx >= 0 && style_idx < IM_COUNTOF(style_names)) ? style_names[style_idx] : "")) { - for (int n = 0; n < IM_ARRAYSIZE(style_names); n++) + for (int n = 0; n < IM_COUNTOF(style_names); n++) { if (ImGui::Selectable(style_names[n], style_idx == n, ImGuiSelectableFlags_SelectOnNav)) { @@ -8861,8 +8861,8 @@ struct ExampleAppConsole char buf[1024]; va_list args; va_start(args, fmt); - vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args); - buf[IM_ARRAYSIZE(buf)-1] = 0; + vsnprintf(buf, IM_COUNTOF(buf), fmt, args); + buf[IM_COUNTOF(buf)-1] = 0; va_end(args); Items.push_back(Strdup(buf)); } @@ -8990,7 +8990,7 @@ struct ExampleAppConsole // Command-line bool reclaim_focus = false; ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_EscapeClearsAll | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory; - if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this)) + if (ImGui::InputText("Input", InputBuf, IM_COUNTOF(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this)) { char* s = InputBuf; Strtrim(s); @@ -9314,8 +9314,8 @@ static void ShowExampleAppLog(bool* p_open) const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" }; for (int n = 0; n < 5; n++) { - const char* category = categories[counter % IM_ARRAYSIZE(categories)]; - const char* word = words[counter % IM_ARRAYSIZE(words)]; + const char* category = categories[counter % IM_COUNTOF(categories)]; + const char* word = words[counter % IM_COUNTOF(words)]; log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n", ImGui::GetFrameCount(), category, ImGui::GetTime(), word); counter++; @@ -9416,7 +9416,7 @@ struct ExampleAppPropertyEditor ImGui::SetNextItemWidth(-FLT_MIN); ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); ImGui::PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); - if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_ARRAYSIZE(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) + if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_COUNTOF(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) Filter.Build(); ImGui::PopItemFlag(); @@ -9722,7 +9722,7 @@ static void ShowExampleAppConstrainedResize(bool* p_open) if (ImGui::Button("Set 500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine(); if (ImGui::Button("Set 800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); } ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); - ImGui::Combo("Constraint", &type, test_desc, IM_ARRAYSIZE(test_desc)); + ImGui::Combo("Constraint", &type, test_desc, IM_COUNTOF(test_desc)); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20); ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100); ImGui::Checkbox("Auto-resize", &auto_resize); @@ -9964,7 +9964,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; // Triangle //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, ImDrawFlags_Closed, th); x += sz + spacing; // Concave Shape - //draw_list->AddPolyline(concave_shape, IM_ARRAYSIZE(concave_shape), col, ImDrawFlags_Closed, th); + //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line @@ -10414,7 +10414,7 @@ void ShowExampleAppDocuments(bool* p_open) if (ImGui::BeginPopup("Rename")) { ImGui::SetNextItemWidth(ImGui::GetFontSize() * 30); - if (ImGui::InputText("###Name", app.RenamingDoc->Name, IM_ARRAYSIZE(app.RenamingDoc->Name), ImGuiInputTextFlags_EnterReturnsTrue)) + if (ImGui::InputText("###Name", app.RenamingDoc->Name, IM_COUNTOF(app.RenamingDoc->Name), ImGuiInputTextFlags_EnterReturnsTrue)) { ImGui::CloseCurrentPopup(); app.RenamingDoc = NULL; @@ -10812,7 +10812,7 @@ struct ExampleAssetsBrowser draw_list->AddRectFilled(box_min, box_max, icon_bg_color); // Background color if (ShowTypeOverlay && item_data->Type != 0) { - ImU32 type_col = icon_type_overlay_colors[item_data->Type % IM_ARRAYSIZE(icon_type_overlay_colors)]; + ImU32 type_col = icon_type_overlay_colors[item_data->Type % IM_COUNTOF(icon_type_overlay_colors)]; draw_list->AddRectFilled(ImVec2(box_max.x - 2 - icon_type_overlay_size.x, box_min.y + 2), ImVec2(box_max.x - 2, box_min.y + 2 + icon_type_overlay_size.y), type_col); } if (display_label) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2dddaece7..058b3724b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -391,9 +391,9 @@ ImDrawListSharedData::ImDrawListSharedData() { memset(this, 0, sizeof(*this)); InitialFringeScale = 1.0f; - for (int i = 0; i < IM_ARRAYSIZE(ArcFastVtx); i++) + for (int i = 0; i < IM_COUNTOF(ArcFastVtx); i++) { - const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(ArcFastVtx); + const float a = ((float)i * 2 * IM_PI) / (float)IM_COUNTOF(ArcFastVtx); ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); } ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError); @@ -411,7 +411,7 @@ void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error) IM_ASSERT(max_error > 0.0f); CircleSegmentMaxError = max_error; - for (int i = 0; i < IM_ARRAYSIZE(CircleSegmentCounts); i++) + for (int i = 0; i < IM_COUNTOF(CircleSegmentCounts); i++) { const float radius = (float)i; CircleSegmentCounts[i] = (ImU8)((i > 0) ? IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, CircleSegmentMaxError) : IM_DRAWLIST_ARCFAST_SAMPLE_MAX); @@ -646,7 +646,7 @@ int ImDrawList::_CalcCircleAutoSegmentCount(float radius) const { // Automatic segment count const int radius_idx = (int)(radius + 0.999999f); // ceil to never reduce accuracy - if (radius_idx >= 0 && radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts)) + if (radius_idx >= 0 && radius_idx < IM_COUNTOF(_Data->CircleSegmentCounts)) return _Data->CircleSegmentCounts[radius_idx]; // Use cached value else return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError); @@ -3122,7 +3122,7 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f * 1.0f; if (font_cfg.Name[0] == '\0') - ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf"); + ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "ProggyClean.ttf"); font_cfg.EllipsisChar = (ImWchar)0x0085; font_cfg.GlyphOffset.y += 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units @@ -3156,7 +3156,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, // Store a short copy of filename into 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_ARRAYSIZE(font_cfg.Name), "%s", p); + ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "%s", p); } return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); } @@ -4005,7 +4005,7 @@ static void ImFontAtlasDebugWriteTexToDisk(ImTextureData* tex, const char* descr { ImGuiContext& g = *GImGui; char buf[128]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "[%05d] Texture #%03d - %s.png", g.FrameCount, tex->UniqueID, description); + ImFormatString(buf, IM_COUNTOF(buf), "[%05d] Texture #%03d - %s.png", g.FrameCount, tex->UniqueID, description); stbi_write_png(buf, tex->Width, tex->Height, tex->BytesPerPixel, tex->Pixels, tex->GetPitch()); // tex->BytesPerPixel is technically not component, but ok for the formats we support. } #endif @@ -4885,11 +4885,11 @@ const ImWchar* ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon() 0xFF00, 0xFFEF, // Half-width characters 0xFFFD, 0xFFFD // Invalid }; - static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = { 0 }; + static ImWchar full_ranges[IM_COUNTOF(base_ranges) + IM_COUNTOF(accumulative_offsets_from_0x4E00) * 2 + 1] = { 0 }; if (!full_ranges[0]) { memcpy(full_ranges, base_ranges, sizeof(base_ranges)); - UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges)); + UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_COUNTOF(accumulative_offsets_from_0x4E00), full_ranges + IM_COUNTOF(base_ranges)); } return &full_ranges[0]; } @@ -4975,11 +4975,11 @@ const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() 0xFF00, 0xFFEF, // Half-width characters 0xFFFD, 0xFFFD // Invalid }; - static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00)*2 + 1] = { 0 }; + static ImWchar full_ranges[IM_COUNTOF(base_ranges) + IM_COUNTOF(accumulative_offsets_from_0x4E00)*2 + 1] = { 0 }; if (!full_ranges[0]) { memcpy(full_ranges, base_ranges, sizeof(base_ranges)); - UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges)); + UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_COUNTOF(accumulative_offsets_from_0x4E00), full_ranges + IM_COUNTOF(base_ranges)); } return &full_ranges[0]; } diff --git a/imgui_internal.h b/imgui_internal.h index 254665dee..28651d1bb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1581,7 +1581,7 @@ struct ImGuiKeyRoutingTable ImVector EntriesNext; // Double-buffer to avoid reallocation (could use a shared buffer) ImGuiKeyRoutingTable() { Clear(); } - void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Index); n++) Index[n] = -1; Entries.clear(); EntriesNext.clear(); } + void Clear() { for (int n = 0; n < IM_COUNTOF(Index); n++) Index[n] = -1; Entries.clear(); EntriesNext.clear(); } }; // This extends ImGuiKeyData but only for named keys (legacy keys don't support the new features) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 20ca7af1b..af97b2e96 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2624,7 +2624,7 @@ void ImGui::TableMergeDrawChannels(ImGuiTable* table) const int size_for_masks_bitarrays_one = (int)ImBitArrayGetStorageSizeInBytes(max_draw_channels); g.TempBuffer.reserve(size_for_masks_bitarrays_one * 5); memset(g.TempBuffer.Data, 0, size_for_masks_bitarrays_one * 5); - for (int n = 0; n < IM_ARRAYSIZE(merge_groups); n++) + for (int n = 0; n < IM_COUNTOF(merge_groups); n++) merge_groups[n].ChannelsMask = (ImBitArrayPtr)(void*)(g.TempBuffer.Data + (size_for_masks_bitarrays_one * n)); ImBitArrayPtr remaining_mask = (ImBitArrayPtr)(void*)(g.TempBuffer.Data + (size_for_masks_bitarrays_one * 4)); @@ -2681,7 +2681,7 @@ void ImGui::TableMergeDrawChannels(ImGuiTable* table) // [DEBUG] Display merge groups #if 0 if (g.IO.KeyShift) - for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++) + for (int merge_group_n = 0; merge_group_n < IM_COUNTOF(merge_groups); merge_group_n++) { MergeGroup* merge_group = &merge_groups[merge_group_n]; if (merge_group->ChannelsCount == 0) @@ -2709,7 +2709,7 @@ void ImGui::TableMergeDrawChannels(ImGuiTable* table) int remaining_count = splitter->_Count - (has_freeze_v ? LEADING_DRAW_CHANNELS + 1 : LEADING_DRAW_CHANNELS); //ImRect host_rect = (table->InnerWindow == table->OuterWindow) ? table->InnerClipRect : table->HostClipRect; ImRect host_rect = table->HostClipRect; - for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++) + for (int merge_group_n = 0; merge_group_n < IM_COUNTOF(merge_groups); merge_group_n++) { if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount) { @@ -3202,7 +3202,7 @@ void ImGui::TableHeader(const char* label) sort_arrow = true; if (column->SortOrder > 0) { - ImFormatString(sort_order_suf, IM_ARRAYSIZE(sort_order_suf), "%d", column->SortOrder + 1); + ImFormatString(sort_order_suf, IM_COUNTOF(sort_order_suf), "%d", column->SortOrder + 1); w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x; } } @@ -4094,7 +4094,7 @@ void ImGui::DebugNodeTable(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[n]; const char* name = TableGetColumnName(table, n); char buf[512]; - ImFormatString(buf, IM_ARRAYSIZE(buf), + ImFormatString(buf, IM_COUNTOF(buf), "Column %d order %d '%s': offset %+.2f to %+.2f%s\n" "Enabled: %d, VisibleX/Y: %d/%d, RequestOutput: %d, SkipItems: %d, DrawChannels: %d,%d\n" "WidthGiven: %.1f, Request/Auto: %.1f/%.1f, StretchWeight: %.3f (%.1f%%)\n" diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 84ea505f6..fac10d832 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1452,7 +1452,7 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over { if (!overlay) { - ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f); + ImFormatString(overlay_buf, IM_COUNTOF(overlay_buf), "%.0f%%", fraction * 100 + 0.01f); overlay = overlay_buf; } @@ -2019,7 +2019,7 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags // This is essentially a specialized version of BeginPopupEx() char name[16]; - ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginComboDepth); // Recycle windows based on depth + ImFormatString(name, IM_COUNTOF(name), "##Combo_%02d", g.BeginComboDepth); // Recycle windows based on depth // Set position given a custom constraint (peak into expected window size so we can position it) // FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function? @@ -2265,7 +2265,7 @@ static const ImGuiDataTypeInfo GDataTypeInfo[] = { sizeof(bool), "bool", "%d", "%d" }, // ImGuiDataType_Bool { 0, "char*","%s", "%s" }, // ImGuiDataType_String }; -IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT); +IM_STATIC_ASSERT(IM_COUNTOF(GDataTypeInfo) == ImGuiDataType_COUNT); const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type) { @@ -2374,7 +2374,7 @@ bool ImGui::DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) format = type_info->ScanFmt; else - format = ImParseFormatSanitizeForScanning(format, format_sanitized, IM_ARRAYSIZE(format_sanitized)); + format = ImParseFormatSanitizeForScanning(format, format_sanitized, IM_COUNTOF(format_sanitized)); // Small types need a 32-bit buffer to receive the result from scanf() int v32 = 0; @@ -2465,7 +2465,7 @@ static float GetMinimumStepAtDecimalPrecision(int decimal_precision) static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; if (decimal_precision < 0) return FLT_MIN; - return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision); + return (decimal_precision < IM_COUNTOF(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision); } template @@ -2479,12 +2479,12 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // Sanitize format char fmt_sanitized[32]; - ImParseFormatSanitizeForPrinting(fmt_start, fmt_sanitized, IM_ARRAYSIZE(fmt_sanitized)); + ImParseFormatSanitizeForPrinting(fmt_start, fmt_sanitized, IM_COUNTOF(fmt_sanitized)); fmt_start = fmt_sanitized; // Format value with our rounding, and read back char v_str[64]; - ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v); + ImFormatString(v_str, IM_COUNTOF(v_str), fmt_start, v); const char* p = v_str; while (*p == ' ') p++; @@ -2774,7 +2774,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; - const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_COUNTOF(value_buf), data_type, p_data, format); if (g.LogEnabled) LogSetNextTextDecoration("{", "}"); RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); @@ -3371,7 +3371,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; - const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_COUNTOF(value_buf), data_type, p_data, format); if (g.LogEnabled) LogSetNextTextDecoration("{", "}"); RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); @@ -3524,7 +3524,7 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; - const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_COUNTOF(value_buf), data_type, p_data, format); 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)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -3724,16 +3724,16 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type); char fmt_buf[32]; char data_buf[32]; - format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf)); + format = ImParseFormatTrimDecorations(format, fmt_buf, IM_COUNTOF(fmt_buf)); if (format[0] == 0) format = type_info->PrintFmt; - DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format); + DataTypeFormatString(data_buf, IM_COUNTOF(data_buf), data_type, p_data, format); ImStrTrimBlanks(data_buf); ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint; g.LastItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited; // Because TempInputText() uses ImGuiInputTextFlags_MergedItem it doesn't submit a new item, so we poke LastItemData. bool value_changed = false; - if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags)) + if (TempInputText(bb, id, label, data_buf, IM_COUNTOF(data_buf), flags)) { // Backup old value size_t data_type_size = type_info->Size; @@ -3786,7 +3786,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data if ((flags & ImGuiInputTextFlags_DisplayEmptyRefVal) && DataTypeCompare(data_type, p_data, p_data_default) == 0) buf[0] = 0; else - DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format); + DataTypeFormatString(buf, IM_COUNTOF(buf), data_type, p_data, format); // Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags_Edited. // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. @@ -3796,7 +3796,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data bool value_changed = false; if (p_step == NULL) { - if (InputText(label, buf, IM_ARRAYSIZE(buf), flags)) + if (InputText(label, buf, IM_COUNTOF(buf), flags)) value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL); } else @@ -3806,7 +3806,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() PushID(label); SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); - if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view + if (InputText("", buf, IM_COUNTOF(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL); IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable); @@ -5851,11 +5851,11 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // RGB Hexadecimal Input char buf[64]; if (alpha) - ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255)); + ImFormatString(buf, IM_COUNTOF(buf), "#%02X%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255)); else - ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255)); + ImFormatString(buf, IM_COUNTOF(buf), "#%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255)); SetNextItemWidth(w_inputs); - if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsUppercase)) + if (InputText("##Text", buf, IM_COUNTOF(buf), ImGuiInputTextFlags_CharsUppercase)) { value_changed = true; char* p = buf; @@ -6549,18 +6549,18 @@ void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) { int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); char buf[64]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + ImFormatString(buf, IM_COUNTOF(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); if (Selectable(buf)) SetClipboardText(buf); - ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca); + ImFormatString(buf, IM_COUNTOF(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca); if (Selectable(buf)) SetClipboardText(buf); - ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", cr, cg, cb); + ImFormatString(buf, IM_COUNTOF(buf), "#%02X%02X%02X", cr, cg, cb); if (Selectable(buf)) SetClipboardText(buf); if (!(flags & ImGuiColorEditFlags_NoAlpha)) { - ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", cr, cg, cb, ca); + ImFormatString(buf, IM_COUNTOF(buf), "#%02X%02X%02X%02X", cr, cg, cb, ca); if (Selectable(buf)) SetClipboardText(buf); } @@ -7513,7 +7513,7 @@ ImGuiTypingSelectRequest* ImGui::GetTypingSelectRequest(ImGuiTypingSelectFlags f } // Append to buffer - const int buffer_max_len = IM_ARRAYSIZE(data->SearchBuffer) - 1; + const int buffer_max_len = IM_COUNTOF(data->SearchBuffer) - 1; int buffer_len = (int)ImStrlen(data->SearchBuffer); bool select_request = false; for (ImWchar w : g.IO.InputQueueCharacters) @@ -8913,7 +8913,7 @@ void ImGui::Value(const char* prefix, float v, const char* float_format) if (float_format) { char fmt[64]; - ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); + ImFormatString(fmt, IM_COUNTOF(fmt), "%%s: %s", float_format); Text(fmt, prefix, v); } else @@ -8952,7 +8952,7 @@ void ImGuiMenuColumns::CalcNextTotalWidth(bool update_offsets) { ImU16 offset = 0; bool want_spacing = false; - for (int i = 0; i < IM_ARRAYSIZE(Widths); i++) + for (int i = 0; i < IM_COUNTOF(Widths); i++) { ImU16 width = Widths[i]; if (want_spacing && width > 0) From 683f9160b96a2ae419d9a4896481b260e85a1b87 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 18 Dec 2025 20:54:21 +0100 Subject: [PATCH 1574/2359] Internals: ImBitArray: rename storage. --- imgui_internal.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 28651d1bb..6dacb36cc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -635,15 +635,15 @@ typedef ImU32* ImBitArrayPtr; // Name for use in structs template struct ImBitArray { - ImU32 Storage[(BITCOUNT + 31) >> 5]; + ImU32 Data[(BITCOUNT + 31) >> 5]; ImBitArray() { ClearAllBits(); } - void ClearAllBits() { memset(Storage, 0, sizeof(Storage)); } - void SetAllBits() { memset(Storage, 255, sizeof(Storage)); } - bool TestBit(int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Storage, n); } - void SetBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArraySetBit(Storage, n); } - void ClearBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArrayClearBit(Storage, n); } - void SetBitRange(int n, int n2) { n += OFFSET; n2 += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT && n2 > n && n2 <= BITCOUNT); ImBitArraySetBitRange(Storage, n, n2); } // Works on range [n..n2) - bool operator[](int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Storage, n); } + void ClearAllBits() { memset(Data, 0, sizeof(Data)); } + void SetAllBits() { memset(Data, 255, sizeof(Data)); } + bool TestBit(int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Data, n); } + void SetBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArraySetBit(Data, n); } + void ClearBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArrayClearBit(Data, n); } + void SetBitRange(int n, int n2) { n += OFFSET; n2 += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT && n2 > n && n2 <= BITCOUNT); ImBitArraySetBitRange(Data, n, n2); } // Works on range [n..n2) + bool operator[](int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Data, n); } }; // Helper: ImBitVector From 22ffa3d6d34db5fad26a1ceeeef6c5c009a80adf Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 18 Dec 2025 00:12:32 +0100 Subject: [PATCH 1575/2359] Text: rewrite word-wrapping logic. (#8990, #3237, #8503, #8139, #8439, #9094, #3002, #9066, #8838) --- docs/CHANGELOG.txt | 7 +++- imgui.h | 2 +- imgui_draw.cpp | 84 ++++++++++++++++++++++++++++------------------ 3 files changed, 59 insertions(+), 34 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8931aa070..f9ee3a143 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -93,7 +93,12 @@ Other Changes: - Added ImGuiSliderFlags_ColorMarkers to opt-in adding R/G/B/A color markers next to each components, in multi-components functions. - Added a way to select a specific marker color. -- Text: +- Text, InputText: + - Reworked word-wrapping logic: + - Try to not wrap in the middle of contiguous punctuations. (#8139, #8439, #9094) + - Try to not wrap between a punctuation and a digit. (#8503) + - Inside InputTextMultiline() with _WordWrap: prefer keeping blanks at the + end of a line rather than at the beginning of next line. (#8990, #3237) - Fixed low-level word-wrapping function reading from *text_end when passed a string range. (#9107) [@achabense] - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be diff --git a/imgui.h b/imgui.h index a336ccd06..275cf566b 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19256 +#define IMGUI_VERSION_NUM 19257 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 058b3724b..06134e3aa 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -17,7 +17,7 @@ Index of this file: // [SECTION] ImFontAtlas: backend for stb_truetype // [SECTION] ImFontAtlas: glyph ranges helpers // [SECTION] ImFontGlyphRangesBuilder -// [SECTION] ImFont +// [SECTION] ImFontBaked, ImFont // [SECTION] ImGui Internal Render Helpers // [SECTION] Decompression code // [SECTION] Default font data (ProggyClean.ttf) @@ -5068,7 +5068,7 @@ void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) } //----------------------------------------------------------------------------- -// [SECTION] ImFont +// [SECTION] ImFontBaked, ImFont //----------------------------------------------------------------------------- ImFontBaked::ImFontBaked() @@ -5371,6 +5371,12 @@ const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_e return text; } +// Character classification for word-wrapping logic +enum +{ + ImWcharClass_Blank, ImWcharClass_Punct, ImWcharClass_Other +}; + // 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. // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) @@ -5392,16 +5398,20 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t const float scale = size / baked->Size; float line_width = 0.0f; - float word_width = 0.0f; float blank_width = 0.0f; wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters - const char* word_end = text; - const char* prev_word_end = NULL; - bool inside_word = true; - const char* s = text; IM_ASSERT(text_end != NULL); + + int prev_type = ImWcharClass_Other; + const bool keep_blanks = (flags & ImDrawTextFlags_WrapKeepBlanks) != 0; + + // Find next wrapping point + //const char* span_begin = s; + const char* span_end = s; + float span_width = 0.0f; + while (s < text_end) { unsigned int c = (unsigned int)*s; @@ -5417,7 +5427,7 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t return s; // Direct return, skip "Wrap_width is too small to fit anything" path. if (c == '\r') { - s = next_s; + s = next_s; // Fast-skip continue; } } @@ -5427,46 +5437,56 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t if (char_width < 0.0f) char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c); - if (ImCharIsBlankW(c)) + // Classify current character + int curr_type; + if (c == ' ' || c == '\t' || c == 0x3000) // Inline version of ImCharIsBlankW(c) + curr_type = ImWcharClass_Blank; + else if (c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"' || c == 0x3001 || c == 0x3002) + curr_type = ImWcharClass_Punct; + else + curr_type = ImWcharClass_Other; + + if (curr_type == ImWcharClass_Blank) { - if (inside_word) + // End span: 'A ' or '. ' + if (prev_type != ImWcharClass_Blank && !keep_blanks) { - line_width += blank_width; - blank_width = 0.0f; - word_end = s; + span_end = s; + line_width += span_width; + span_width = 0.0f; } blank_width += char_width; - inside_word = false; } else { - word_width += char_width; - if (inside_word) + // End span: '.X' unless X is a digit + if (prev_type == ImWcharClass_Punct && curr_type != ImWcharClass_Punct && !(c >= '0' && c <= '9')) { - word_end = next_s; + span_end = s; + line_width += span_width + blank_width; + span_width = blank_width = 0.0f; } - else + // End span: 'A ' or '. ' + else if (prev_type == ImWcharClass_Blank && keep_blanks) { - prev_word_end = word_end; - line_width += word_width + blank_width; - if ((flags & ImDrawTextFlags_WrapKeepBlanks) && line_width <= wrap_width) - prev_word_end = s; - word_width = blank_width = 0.0f; + span_end = s; + line_width += span_width + blank_width; + span_width = blank_width = 0.0f; } - - // Allow wrapping after punctuation. - inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"' && c != 0x3001 && c != 0x3002); + span_width += char_width; } - // We ignore blank width at the end of the line (they can be skipped) - if (line_width + word_width > wrap_width) + if (span_width + blank_width + line_width > wrap_width) { - // Words that cannot possibly fit within an entire line will be cut anywhere. - if (word_width < wrap_width) - s = prev_word_end ? prev_word_end : word_end; - break; + if (span_width + blank_width > wrap_width) + break; + // FIXME: Narrow wrapping e.g. "A quick brown" -> "Quic|k br|own", would require knowing if span is going to be longer than wrap_width. + //if (span_width > wrap_width && !is_blank && !was_blank) + // return s; + return span_end; } + prev_type = curr_type; s = next_s; } From a5dffbec3812bf6d5f58686e66546c078dcafa56 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 21 Dec 2025 16:42:58 +0100 Subject: [PATCH 1576/2359] Text: word-wrapping use a small lookup table. (#8990, #3237, #8503, #8139, #8439, #9094, #3002, #9066, #8838) --- imgui_draw.cpp | 68 +++++++++++++++++++++++++++++++++++++++--------- imgui_internal.h | 10 +++++++ 2 files changed, 66 insertions(+), 12 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 06134e3aa..9eb80d091 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4234,6 +4234,10 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) ImFontAtlasUpdateDrawListsSharedData(atlas); //atlas->TexIsBuilt = true; + + // Lazily initialize char/text classifier + // FIXME: This could be practically anywhere, and should eventually be parameters to CalcTextSize/word-wrapping code, but there's no obvious spot now. + ImTextInitClassifiers(); } // Destroy builder and all cached glyphs. Do not destroy actual fonts. @@ -5371,23 +5375,63 @@ const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_e return text; } -// Character classification for word-wrapping logic -enum +void ImTextClassifierClear(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class) { - ImWcharClass_Blank, ImWcharClass_Punct, ImWcharClass_Other -}; + for (unsigned int c = codepoint_min; c < codepoint_end; c++) + ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c); +} + +void ImTextClassifierSetCharClass(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, unsigned int c) +{ + IM_ASSERT(c >= codepoint_min && c < codepoint_end); + c -= codepoint_min; + const ImU32 shift = (c & 15) << 1; + bits[c >> 4] = (bits[c >> 4] & ~(0x03 << shift)) | (char_class << shift); +} + +void ImTextClassifierSetCharClassFromStr(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, const char* s) +{ + const char* s_end = s + strlen(s); + while (*s) + { + unsigned int c; + s += ImTextCharFromUtf8(&c, s, s_end); + ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c); + } +} + +#define ImTextClassifierGet(_BITS, _CHAR_OFFSET) ((_BITS[(_CHAR_OFFSET) >> 4] >> (((_CHAR_OFFSET) & 15) << 1)) & 0x03) + +// 2-bit per character +static ImU32 g_CharClassifierIsSeparator_0000_007f[128 / 16] = {}; +static ImU32 g_CharClassifierIsSeparator_3000_300f[ 16 / 16] = {}; + +void ImTextInitClassifiers() +{ + if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, ',') != 0) + return; + + // List of hardcoded separators: .,;!?'" + // Making this dynamic given known ranges is trivial BUT requires us to standardize where you pass them as parameters. (#3002, #8503) + ImTextClassifierClear(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass_Other); + ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass_Blank, " \t"); + ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass_Punct, ".,;!?\""); + + ImTextClassifierClear(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass_Other); + ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass_Blank, 0x3000); + ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass_Punct, 0x3001); + ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass_Punct, 0x3002); +} // 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. -// FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) +// 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) { // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" // ^ ^ ^ ^ ^__ ^ ^ - // List of hardcoded separators: .,;!?'" - // Skip extra blanks after a line returns (that includes not counting them in width computation) // e.g. "Hello world" --> "Hello" "World" @@ -5439,10 +5483,10 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t // Classify current character int curr_type; - if (c == ' ' || c == '\t' || c == 0x3000) // Inline version of ImCharIsBlankW(c) - curr_type = ImWcharClass_Blank; - else if (c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"' || c == 0x3001 || c == 0x3002) - curr_type = ImWcharClass_Punct; + if (c < 128) + curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, c); + else if (c >= 0x3000 && c < 0x3010) + curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_3000_300f, c & 15); //-V578 else curr_type = ImWcharClass_Other; @@ -5460,7 +5504,7 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t else { // End span: '.X' unless X is a digit - if (prev_type == ImWcharClass_Punct && curr_type != ImWcharClass_Punct && !(c >= '0' && c <= '9')) + if (prev_type == ImWcharClass_Punct && curr_type != ImWcharClass_Punct && !(c >= '0' && c <= '9')) // FIXME: Digit checks might be removed if allow custom separators (#8503) { span_end = s; line_width += span_width + blank_width; diff --git a/imgui_internal.h b/imgui_internal.h index 6dacb36cc..02b7f28e7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -441,6 +441,16 @@ IMGUI_API ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max IMGUI_API const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width, ImDrawTextFlags flags = 0); IMGUI_API const char* ImTextCalcWordWrapNextLineStart(const char* text, const char* text_end, ImDrawTextFlags flags = 0); // trim trailing space and find beginning of next line +// Character classification for word-wrapping logic +enum ImWcharClass +{ + ImWcharClass_Blank, ImWcharClass_Punct, ImWcharClass_Other +}; +IMGUI_API void ImTextInitClassifiers(); +IMGUI_API void ImTextClassifierClear(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class); +IMGUI_API void ImTextClassifierSetCharClass(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, unsigned int c); +IMGUI_API void ImTextClassifierSetCharClassFromStr(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, const char* s); + // Helpers: File System #ifdef IMGUI_DISABLE_FILE_FUNCTIONS #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS From d87650dffb37dcd2c79cd8789ef3cb87164c7eda Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 21 Dec 2025 18:22:48 +0100 Subject: [PATCH 1577/2359] Text: fixed unused variable warning on builds without asserts. --- imgui_draw.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 9eb80d091..7e1b8a290 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5384,6 +5384,7 @@ void ImTextClassifierClear(ImU32* bits, unsigned int codepoint_min, unsigned int void ImTextClassifierSetCharClass(ImU32* bits, unsigned int codepoint_min, unsigned int codepoint_end, ImWcharClass char_class, unsigned int c) { IM_ASSERT(c >= codepoint_min && c < codepoint_end); + IM_UNUSED(codepoint_end); c -= codepoint_min; const ImU32 shift = (c & 15) << 1; bits[c >> 4] = (bits[c >> 4] & ~(0x03 << shift)) | (char_class << shift); From 9055c9ed222f16fdd0147453b5fb8596c76278d0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Dec 2025 17:51:24 +0100 Subject: [PATCH 1578/2359] imgui_freetype: fixed overwriting ImFontConfig::PixelSnapH when hinting is enabled. Fix/amend 99f6b305c1. --- docs/CHANGELOG.txt | 4 ++++ imgui_draw.cpp | 1 + misc/freetype/imgui_freetype.cpp | 10 +++------- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f9ee3a143..a9dd06ba1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,10 @@ Other Changes: - Fonts: - Fixed an issue related to EllipsisChar handling, while changing font loader or font loader flags dynamically in Style->Fonts menus. + - imgui_freetype: fixed overwriting ImFontConfig::PixelSnapH when hinting + is enabled, creating side-effects when later disabling hinting or + dynamically switching to stb_truetype rasterizer. + which would prevent - Textures: - Fixed a building issue when ImTextureID is defined as a struct. - Fixed displaying texture # in Metrics/Debugger window. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7e1b8a290..553730344 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3392,6 +3392,7 @@ void ImFontAtlasBuildMain(ImFontAtlas* atlas) void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v) { + // (Only used by stb_truetype builder) // Automatically disable horizontal oversampling over size 36 const float raster_size = baked->Size * baked->RasterizerDensity * src->RasterizerDensity; *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (raster_size > 36.0f || src->PixelSnapH) ? 1 : 2; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 26a087017..d3d0a60ef 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -153,7 +153,7 @@ struct ImGui_ImplFreeType_Data struct ImGui_ImplFreeType_FontSrcData { // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. - bool InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_user_flags); + bool InitFont(FT_Library ft_library, const ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_user_flags); void CloseFont(); ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); } ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); } @@ -172,7 +172,7 @@ struct ImGui_ImplFreeType_FontSrcBakedData ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } }; -bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_font_loader_flags) +bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, const ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_font_loader_flags) { FT_Error error = FT_New_Memory_Face(ft_library, (const FT_Byte*)src->FontData, (FT_Long)src->FontDataSize, (FT_Long)src->FontNo, &FtFace); if (error != 0) @@ -187,12 +187,8 @@ bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfi LoadFlags = 0; if ((UserFlags & ImGuiFreeTypeLoaderFlags_Bitmap) == 0) LoadFlags |= FT_LOAD_NO_BITMAP; - if (UserFlags & ImGuiFreeTypeLoaderFlags_NoHinting) LoadFlags |= FT_LOAD_NO_HINTING; - else - src->PixelSnapH = true; // FIXME: A bit weird to do this this way. - if (UserFlags & ImGuiFreeTypeLoaderFlags_NoAutoHint) LoadFlags |= FT_LOAD_NO_AUTOHINT; if (UserFlags & ImGuiFreeTypeLoaderFlags_ForceAutoHint) @@ -543,7 +539,7 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; float font_off_x = (src->GlyphOffset.x * offsets_scale); float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent; - if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. + if (src->PixelSnapH || (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_NoHinting) == 0) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. font_off_x = IM_ROUND(font_off_x); if (src->PixelSnapV) font_off_y = IM_ROUND(font_off_y); From 0ff810038dae8da18be7556bef69c75b485b5196 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Dec 2025 18:33:12 +0100 Subject: [PATCH 1579/2359] Added GetItemFlags() in public API. (#9127) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 6 ++++++ imgui.h | 4 +++- imgui_internal.h | 2 -- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a9dd06ba1..114abfbdb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -107,6 +107,8 @@ Other Changes: a string range. (#9107) [@achabense] - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] +- Added GetItemFlags() in public API for consistency and to expose generic + flags of last submitted item. (#9127) - Debug Tools: - Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to io.AddInputCharacter(). (#9099) diff --git a/imgui.cpp b/imgui.cpp index d50a7ead2..483b2d88b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6330,6 +6330,12 @@ ImVec2 ImGui::GetItemRectSize() return g.LastItemData.Rect.GetSize(); } +ImGuiItemFlags ImGui::GetItemFlags() +{ + ImGuiContext& g = *GImGui; + 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'. // 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) diff --git a/imgui.h b/imgui.h index 275cf566b..2c8fecef6 100644 --- a/imgui.h +++ b/imgui.h @@ -1017,6 +1017,7 @@ namespace ImGui IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space) IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space) IMGUI_API ImVec2 GetItemRectSize(); // get size of last item + IMGUI_API ImGuiItemFlags GetItemFlags(); // get generic flags of last item // Viewports // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. @@ -1218,7 +1219,7 @@ enum ImGuiChildFlags_ }; // Flags for ImGui::PushItemFlag() -// (Those are shared by all items) +// (Those are shared by all submitted items) enum ImGuiItemFlags_ { ImGuiItemFlags_None = 0, // (Default) @@ -1228,6 +1229,7 @@ enum ImGuiItemFlags_ ImGuiItemFlags_ButtonRepeat = 1 << 3, // false // Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. ImGuiItemFlags_AutoClosePopups = 1 << 4, // true // MenuItem()/Selectable() automatically close their parent popup window. ImGuiItemFlags_AllowDuplicateId = 1 << 5, // false // Allow submitting an item with the same identifier as an item already submitted this frame without triggering a warning tooltip if io.ConfigDebugHighlightIdConflicts is set. + ImGuiItemFlags_Disabled = 1 << 6, // false // [Internal] Disable interactions. DOES NOT affect visuals. This is used by BeginDisabled()/EndDisabled() and only provided here so you can read back via GetItemFlags(). }; // Flags for ImGui::InputText() diff --git a/imgui_internal.h b/imgui_internal.h index 02b7f28e7..5d14bc486 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -965,7 +965,6 @@ enum ImGuiDataTypePrivate_ enum ImGuiItemFlagsPrivate_ { // Controlled by user - ImGuiItemFlags_Disabled = 1 << 10, // false // Disable interactions (DOES NOT affect visuals. DO NOT mix direct use of this with BeginDisabled(). See BeginDisabled()/EndDisabled() for full disable feature, and github #211). ImGuiItemFlags_ReadOnly = 1 << 11, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. ImGuiItemFlags_MixedValue = 1 << 12, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) ImGuiItemFlags_NoWindowHoverableCheck = 1 << 13, // false // Disable hoverable check in ItemHoverable() @@ -3261,7 +3260,6 @@ namespace ImGui // Basic Accessors inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.StatusFlags; } - inline ImGuiItemFlags GetItemFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.ItemFlags; } inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); From d365417e8b918484e057f27e40ff8f7770fee872 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 Dec 2025 16:47:44 +0100 Subject: [PATCH 1580/2359] CI: reduce macOS runs since they are expensive. --- .github/workflows/build.yml | 102 +++++++++++++++++++----------------- 1 file changed, 53 insertions(+), 49 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 482804b47..46ff68912 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -525,7 +525,7 @@ jobs: - name: Build example_null (extra warnings, clang 64-bit) run: make -C examples/example_null WITH_EXTRA_WARNINGS=1 - - name: Build example_null (single file build) + - name: Build macOS example_null (single file build) run: | cat > example_single_file.cpp <<'EOF' @@ -536,7 +536,7 @@ jobs: EOF clang++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - - name: Build example_null (single file build, c++20) + - name: Build macOS example_null (single file build, c++20) run: | cat > example_single_file.cpp <<'EOF' @@ -547,7 +547,7 @@ jobs: EOF clang++ -I. -std=c++20 -Wall -Wformat -o example_single_file example_single_file.cpp - - name: Build example_null (without c++ runtime) + - name: Build macOS example_null (without c++ runtime) run: | cat > example_single_file.cpp <<'EOF' @@ -558,34 +558,38 @@ jobs: EOF clang++ -I. -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - - name: Build example_glfw_opengl2 + - name: Build macOS example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 + if: github.event_name == 'workflow_run' - - name: Build example_glfw_opengl3 + - name: Build macOS example_glfw_opengl3 run: make -C examples/example_glfw_opengl3 if: github.event_name == 'workflow_run' - - name: Build example_glfw_metal + - name: Build macOS example_glfw_metal run: make -C examples/example_glfw_metal - - name: Build example_sdl2_metal + - name: Build macOS example_sdl2_metal run: make -C examples/example_sdl2_metal - - name: Build example_sdl2_opengl2 + - name: Build macOS example_sdl2_opengl2 run: make -C examples/example_sdl2_opengl2 if: github.event_name == 'workflow_run' - - name: Build example_sdl2_opengl3 + - name: Build macOS example_sdl2_opengl3 run: make -C examples/example_sdl2_opengl3 + if: github.event_name == 'workflow_run' - - name: Build example_sdl3_opengl3 + - name: Build macOS example_sdl3_opengl3 run: make -C examples/example_sdl3_opengl3 - - name: Build example_apple_metal + - name: Build macOS example_apple_metal run: xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_macos + if: github.event_name == 'workflow_run' - - name: Build example_apple_opengl2 + - name: Build macOS example_apple_opengl2 run: xcodebuild -project examples/example_apple_opengl2/example_apple_opengl2.xcodeproj -target example_osx_opengl2 + if: github.event_name == 'workflow_run' Build-iOS: runs-on: macos-14 @@ -750,40 +754,40 @@ jobs: working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite run: ./imgui_test_suite -nogui -nopause -v2 -ve4 -viewport-mock viewport - Test-MacOS: - runs-on: macos-latest - name: Test - MacOS - - defaults: - run: - working-directory: ${{ github.workspace }}/imgui - - steps: - - uses: actions/checkout@v5 - with: - path: ${{ github.workspace }}/imgui - - - uses: actions/checkout@v5 - with: - fetch-depth: 1 - repository: ocornut/imgui_test_engine - path: ${{ github.workspace }}/imgui_test_engine - submodules: true - - - name: Build Tests - working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite - run: make -j$(nproc) - - - name: Run Tests - working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite - run: ./imgui_test_suite -nogui -nopause -v2 -ve4 tests - - - name: Check for Docking - id: check_docking - working-directory: ${{ github.workspace }}/imgui - run: echo "has_dock=$(grep -q "#define IMGUI_HAS_DOCK" imgui.h && echo true || echo false)" >> $GITHUB_OUTPUT - - - name: Run Viewport Tests - if: steps.check_docking.outputs.has_dock == 'true' - working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite - run: ./imgui_test_suite -nogui -nopause -v2 -ve4 -viewport-mock viewport +# Test-MacOS: +# runs-on: macos-latest +# name: Test - MacOS +# +# defaults: +# run: +# working-directory: ${{ github.workspace }}/imgui +# +# steps: +# - uses: actions/checkout@v5 +# with: +# path: ${{ github.workspace }}/imgui +# +# - uses: actions/checkout@v5 +# with: +# fetch-depth: 1 +# repository: ocornut/imgui_test_engine +# path: ${{ github.workspace }}/imgui_test_engine +# submodules: true +# +# - name: Build Tests +# working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite +# run: make -j$(nproc) +# +# - name: Run Tests +# working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite +# run: ./imgui_test_suite -nogui -nopause -v2 -ve4 tests +# +# - name: Check for Docking +# id: check_docking +# working-directory: ${{ github.workspace }}/imgui +# run: echo "has_dock=$(grep -q "#define IMGUI_HAS_DOCK" imgui.h && echo true || echo false)" >> $GITHUB_OUTPUT +# +# - name: Run Viewport Tests +# if: steps.check_docking.outputs.has_dock == 'true' +# working-directory: ${{ github.workspace }}/imgui_test_engine/imgui_test_suite +# run: ./imgui_test_suite -nogui -nopause -v2 -ve4 -viewport-mock viewport From d1de937c314470d0f188a2d2556d3473cca8f31c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Dec 2025 19:57:21 +0100 Subject: [PATCH 1581/2359] Fonts: ImFontAtlasFontRebuildOutput() helper. --- imgui_draw.cpp | 6 ++++++ imgui_internal.h | 1 + 2 files changed, 7 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 553730344..57adc50b0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3607,6 +3607,12 @@ void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font) } } +void ImFontAtlasFontRebuildOutput(ImFontAtlas* atlas, ImFont* font) +{ + ImFontAtlasFontDestroyOutput(atlas, font); + ImFontAtlasFontInitOutput(atlas, font); +} + //----------------------------------------------------------------------------------------------------------------------------- bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src) diff --git a/imgui_internal.h b/imgui_internal.h index 5d14bc486..48ba475b2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3903,6 +3903,7 @@ IMGUI_API void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, I IMGUI_API void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src); IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font); // Using FontDestroyOutput/FontInitOutput sequence useful notably if font loader params have changed IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasFontRebuildOutput(ImFontAtlas* atlas, ImFont* font); IMGUI_API void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames); IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density); From 55ad3b4abdd9324c292070c830f01e9dcf21b7e2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 22 Dec 2025 19:57:04 +0100 Subject: [PATCH 1582/2359] Fonts: added ExtraSizeScale feature (undocumented). --- imgui.cpp | 3 +++ imgui.h | 5 +++-- imgui_draw.cpp | 2 ++ misc/freetype/imgui_freetype.cpp | 1 + 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 483b2d88b..18dbbce3f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17236,6 +17236,9 @@ void ImGui::DebugNodeFont(ImFont* font) { const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; Text("Loader: '%s'", loader->Name ? loader->Name : "N/A"); + + //if (DragFloat("ExtraSizeScale", &src->ExtraSizeScale, 0.01f, 0.10f, 2.0f)) + // ImFontAtlasFontRebuildOutput(atlas, font); #ifdef IMGUI_ENABLE_FREETYPE if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0) { diff --git a/imgui.h b/imgui.h index 2c8fecef6..36f914911 100644 --- a/imgui.h +++ b/imgui.h @@ -3532,7 +3532,7 @@ struct ImFontConfig ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. - float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). + float SizePixels; // // Output size in pixels for rasterizer (more or less maps to the resulting font height). const ImWchar* GlyphRanges; // NULL // *LEGACY* THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a small user-provided list of Unicode ranges (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. @@ -3542,9 +3542,10 @@ struct ImFontConfig float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. // FIXME-NEWATLAS: Intentionally unscaled ImU32 FontNo; // 0 // Index of font within TTF/OTF file unsigned int FontLoaderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. - //unsigned int FontBuilderFlags; // -- // [Renamed in 1.92] Ue FontLoaderFlags. + //unsigned int FontBuilderFlags; // -- // [Renamed in 1.92] Use FontLoaderFlags. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. float RasterizerDensity; // 1.0f // [LEGACY: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported] DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. + float ExtraSizeScale; // 1.0f // Extra rasterizer scale over SizePixels. // [Internal] ImFontFlags Flags; // Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 57adc50b0..db8994282 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2418,6 +2418,7 @@ ImFontConfig::ImFontConfig() FontDataOwnedByAtlas = true; OversampleH = 0; // Auto == 1 or 2 depending on size OversampleV = 0; // Auto == 1 + ExtraSizeScale = 1.0f; GlyphMaxAdvanceX = FLT_MAX; RasterizerMultiply = 1.0f; RasterizerDensity = 1.0f; @@ -4612,6 +4613,7 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); if (src->MergeMode && src->SizePixels != 0.0f && ref_size != 0.0f) bd_font_data->ScaleFactor *= src->SizePixels / ref_size; // FIXME-NEWATLAS: Should tidy up that a bit + bd_font_data->ScaleFactor *= src->ExtraSizeScale; return true; } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index d3d0a60ef..70c794159 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -420,6 +420,7 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* s float size = baked->Size; if (src->MergeMode && src->SizePixels != 0.0f) size *= (src->SizePixels / baked->OwnerFont->Sources[0]->SizePixels); + size *= src->ExtraSizeScale; ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; bd_font_data->BakedLastActivated = baked; From 73dd0e869dff793bca8813832c8dd8b65b4ae661 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 Dec 2025 14:30:16 +0100 Subject: [PATCH 1583/2359] (Breaking) Fonts: remove ImFontConfig::PixelSnapV. Post-rescale GlyphOffset is always rounded. Amend 99f6b305c, 99bca397d8. --- docs/CHANGELOG.txt | 28 ++++++++++++++++------------ imgui.cpp | 8 ++++---- imgui.h | 6 ++++-- imgui_draw.cpp | 12 ++++-------- misc/freetype/imgui_freetype.cpp | 8 ++------ 5 files changed, 30 insertions(+), 32 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 114abfbdb..679a61768 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,17 +50,21 @@ Breaking Changes: - This will invalidate hashes (stored in .ini data) for Tables and Windows that are using the "###" operators. (#713, #1698) - Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name. -- Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which - did erroneously make a copy of the font data, essentially defeating the purpose - of this flag and wasting memory (undetected since July 2015 and now spotted - by @TellowKrinkle, this is perhaps the oldest bug in Dear ImGui history, - albeit for a rarely used feature!) (#9086, #8465) - HOWEVER, fixing this bug is likely to surface bugs in user/app code: - - Prior to 1.92, font data only needs to be available during the atlas->AddFontXXX() call. - - Since 1.92, font data needs to available until atlas->RemoveFont(), or more typically - until a shutdown of the owning context or font atlas. - - The fact that handling of `FontDataOwnedByAtlas = false` was broken - bypassed the issue altogether. +- Fonts: + - Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which + did erroneously make a copy of the font data, essentially defeating the purpose + of this flag and wasting memory (undetected since July 2015 and now spotted + by @TellowKrinkle, this is perhaps the oldest bug in Dear ImGui history, + albeit for a rarely used feature!) (#9086, #8465) + HOWEVER, fixing this bug is likely to surface bugs in user/app code: + - Prior to 1.92, font data only needs to be available during the atlas->AddFontXXX() call. + Since 1.92, font data needs to available until atlas->RemoveFont(), or more typically + until a shutdown of the owning context or font atlas. + - The fact that handling of `FontDataOwnedByAtlas = false` was broken bypassed + the issue altogether. + - Removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary + (and misdocumented). Post-rescale GlyphOffset is always rounded. + Other Changes: @@ -70,7 +74,7 @@ Other Changes: - imgui_freetype: fixed overwriting ImFontConfig::PixelSnapH when hinting is enabled, creating side-effects when later disabling hinting or dynamically switching to stb_truetype rasterizer. - which would prevent + - Post rescale GlyphOffset is always rounded. - Textures: - Fixed a building issue when ImTextureID is defined as a struct. - Fixed displaying texture # in Metrics/Debugger window. diff --git a/imgui.cpp b/imgui.cpp index 18dbbce3f..14dc8afca 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -394,13 +394,13 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/12/23 (1.92.6) - Fonts: removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. - 2025/12/17 (1.92.6) - Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name for now. - 2025/12/11 (1.92.6) - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore. - Before: GetID("Hello###World") == GetID("###World") != GetID("World"); - Now: GetID("Hello###World") == GetID("###World") == GetID("World"); - This has the property of facilitating concatenating and manipulating identifiers using "###", and will allow fixing other dangling issues. - - This will invalidate hashes (stored in .ini data) for Tables and Windows! - that are using the "###" operators. (#713, #1698) + - This will invalidate hashes (stored in .ini data) for Tables and Windows that are using the "###" operators. (#713, #1698) - 2025/11/24 (1.92.6) - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory. (trivia: undetected since July 2015, this is perhaps the oldest bug in Dear ImGui history, albeit for a rarely used feature, see #9086) HOWEVER, fixing this bug is likely to surface bugs in user code using `FontDataOwnedByAtlas = false`. @@ -1265,7 +1265,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window // Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls. -static const float FONT_DEFAULT_SIZE = 20.0f; +static const float FONT_DEFAULT_SIZE_BASE = 20.0f; // When using Ctrl+Tab (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in @@ -8903,7 +8903,7 @@ void ImGui::UpdateFontsNewFrame() // Apply default font size the first time ImFont* font = ImGui::GetDefaultFont(); if (g.Style.FontSizeBase <= 0.0f) - g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE); + g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE_BASE); // Set initial font g.Font = font; diff --git a/imgui.h b/imgui.h index 36f914911..199af5d3c 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19257 +#define IMGUI_VERSION_NUM 19258 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -3528,7 +3528,6 @@ struct ImFontConfig // Options bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Prevents fractional font size from working correctly! Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. - bool PixelSnapV; // false // Align Scaled GlyphOffset.y to pixel boundaries. Prevents fractional font size from working correctly!. ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. @@ -3553,6 +3552,9 @@ struct ImFontConfig const ImFontLoader* FontLoader; // Custom font backend for this source (default source is the one stored in ImFontAtlas) void* FontLoaderData; // Font loader opaque storage (per font config) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + bool PixelSnapV; // true // [Obsoleted in 1.91.6] Align Scaled GlyphOffset.y to pixel boundaries. +#endif IMGUI_API ImFontConfig(); }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index db8994282..f437abc9f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3121,11 +3121,11 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) font_cfg.PixelSnapH = true; } if (font_cfg.SizePixels <= 0.0f) - font_cfg.SizePixels = 13.0f * 1.0f; + font_cfg.SizePixels = 13.0f; // This only serves (1) as a reference for GlyphOffset.y setting and (2) as a default for pre-1.92 backend. if (font_cfg.Name[0] == '\0') ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "ProggyClean.ttf"); font_cfg.EllipsisChar = (ImWchar)0x0085; - font_cfg.GlyphOffset.y += 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units + font_cfg.GlyphOffset.y += 1.0f * (font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units int ttf_compressed_size = 0; const char* ttf_compressed = GetDefaultCompressedFontDataTTF(&ttf_compressed_size); @@ -4721,12 +4721,8 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; - float font_off_x = (src->GlyphOffset.x * offsets_scale); - float font_off_y = (src->GlyphOffset.y * offsets_scale); - if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. - font_off_x = IM_ROUND(font_off_x); - if (src->PixelSnapV) - font_off_y = IM_ROUND(font_off_y); + float font_off_x = ImFloor(src->GlyphOffset.x * offsets_scale + 0.5f); // Snap scaled offset. + float font_off_y = ImFloor(src->GlyphOffset.y * offsets_scale + 0.5f); font_off_x += sub_x; font_off_y += sub_y + IM_ROUND(baked->Ascent); float recip_h = 1.0f / (oversample_h * rasterizer_density); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 70c794159..c358d89db 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -538,12 +538,8 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; - float font_off_x = (src->GlyphOffset.x * offsets_scale); - float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent; - if (src->PixelSnapH || (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_NoHinting) == 0) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. - font_off_x = IM_ROUND(font_off_x); - if (src->PixelSnapV) - font_off_y = IM_ROUND(font_off_y); + float font_off_x = ImFloor(src->GlyphOffset.x * offsets_scale + 0.5f); // Snap scaled offset. + float font_off_y = ImFloor(src->GlyphOffset.y * offsets_scale + 0.5f) + baked->Ascent; float recip_h = 1.0f / rasterizer_density; float recip_v = 1.0f / rasterizer_density; From cde6ad39673e83afc0a686152b6669e73c540b62 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 Dec 2025 14:40:00 +0100 Subject: [PATCH 1584/2359] Removed unused ImRect::Floor(). Clarified IM_TRUNC(), IM_ROUND(), ImRound64(). Better to remove since it uses IM_TRUNC which has unusual specs. Note: 87a6443c5 always use positive value in ImRound64(). (#3609, #8215) --- imgui_internal.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 48ba475b2..0a37c16e2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -276,8 +276,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)) // ImTrunc() is not inlined in MSVC debug builds -#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // +#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! #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS #define IM_FLOOR IM_TRUNC // [OBSOLETE] Renamed in 1.90.0 (Sept 2023) #endif @@ -527,7 +527,7 @@ inline ImVec2 ImTrunc(const ImVec2& v) { return 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 ImTrunc64(float f) { return (float)(ImS64)(f); } -inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } +inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } // FIXME: Positive values only. inline int ImModPositive(int a, int b) { return (a + b) % b; } inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } @@ -611,7 +611,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 Floor() { Min.x = IM_TRUNC(Min.x); Min.y = IM_TRUNC(Min.y); Max.x = IM_TRUNC(Max.x); Max.y = IM_TRUNC(Max.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; } From f006400f053e132fbc0d4c4beeab5e9071853d5c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 Aug 2025 17:54:10 +0200 Subject: [PATCH 1585/2359] Fonts: added AddFontDefaultVector() with embedded ProggyVector data. --- docs/CHANGELOG.txt | 7 + imgui.h | 3 +- imgui_draw.cpp | 365 +++++++++++++++++++++- misc/fonts/ProggyVector-ExtractScript.txt | 17 + 4 files changed, 386 insertions(+), 6 deletions(-) create mode 100644 misc/fonts/ProggyVector-ExtractScript.txt diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 679a61768..016bca2d5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,13 @@ Breaking Changes: Other Changes: - Fonts: + - Added AddFontDefaultVector(): a new embedded scalable font! + Based on ProggyVector by Tristan Grimmer, the same author as our good-old ProggyClean. + The font data was carefully subsetted, trimmed and compressed so the embedded + data is ~18 KB. Embedding a scalable default font ensures that Dear ImGui can + be easily and readily used in all contexts, even without file system access. + As always you can opt-out of the embedded font data if desired. A sizing tweak + was also applied to ensure the new font is a closer match to the classic font. - Fixed an issue related to EllipsisChar handling, while changing font loader or font loader flags dynamically in Style->Fonts menus. - imgui_freetype: fixed overwriting ImFontConfig::PixelSnapH when hinting diff --git a/imgui.h b/imgui.h index 199af5d3c..c969d7c1b 100644 --- a/imgui.h +++ b/imgui.h @@ -3640,7 +3640,8 @@ struct ImFontAtlas IMGUI_API ImFontAtlas(); IMGUI_API ~ImFontAtlas(); IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); - IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); // Embedded classic pixel-clean font. Recommended at Size 13px with no scaling. + IMGUI_API ImFont* AddFontDefaultVector(const ImFontConfig* font_cfg = NULL); // Embedded scalable font. Recommended at any higher size. 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. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f437abc9f..bd9bad5dc 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -21,6 +21,7 @@ Index of this file: // [SECTION] ImGui Internal Render Helpers // [SECTION] Decompression code // [SECTION] Default font data (ProggyClean.ttf) +// [SECTION] Default font data (ProggyVector-minimal.ttf) */ @@ -2517,6 +2518,7 @@ void ImTextureData::DestroyPixels() //----------------------------------------------------------------------------- // - ImFontAtlas::AddFont() // - ImFontAtlas::AddFontDefault() +// - ImFontAtlas::AddFontDefaultVector() // - ImFontAtlas::AddFontFromFileTTF() // - ImFontAtlas::AddFontFromMemoryTTF() // - ImFontAtlas::AddFontFromMemoryCompressedTTF() @@ -3044,7 +3046,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) } else { - IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. + IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. font = font_cfg_in->DstFont ? font_cfg_in->DstFont : Fonts.back(); } @@ -3106,7 +3108,8 @@ static void Decode85(const unsigned char* src, unsigned char* dst) } } #ifndef IMGUI_DISABLE_DEFAULT_FONT -static const char* GetDefaultCompressedFontDataTTF(int* out_size); +static const char* GetDefaultCompressedFontDataProggyClean(int* out_size); +static const char* GetDefaultCompressedFontDataProggyVector(int* out_size); #endif // Load embedded ProggyClean.ttf at size 13, disable oversampling @@ -3128,10 +3131,33 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) font_cfg.GlyphOffset.y += 1.0f * (font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units int ttf_compressed_size = 0; - const char* ttf_compressed = GetDefaultCompressedFontDataTTF(&ttf_compressed_size); + const char* ttf_compressed = GetDefaultCompressedFontDataProggyClean(&ttf_compressed_size); return AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg); #else - IM_ASSERT(0 && "AddFontDefault() disabled in this build."); + IM_ASSERT(0 && "Function is disabled in this build."); + IM_UNUSED(font_cfg_template); + return NULL; +#endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT +} + +// Load a minimal version of ProggyVector, designed to match our good old ProggyClean, but nicely scalable. +// (See misc/fonts/ProggyVector-ExtractScript.txt for details) +ImFont* ImFontAtlas::AddFontDefaultVector(const ImFontConfig* font_cfg_template) +{ +#ifndef IMGUI_DISABLE_DEFAULT_FONT + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.SizePixels <= 0.0f) + font_cfg.SizePixels = 16.0f; + if (font_cfg.Name[0] == '\0') + ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "ProggyVector.ttf"); + font_cfg.ExtraSizeScale = 1.140f; // Match ProggyClean + font_cfg.GlyphOffset.y += -0.5f * (font_cfg.SizePixels / 13.0f); // Closer match ProggyClean + avoid descenders going too high (with current code). + + int ttf_compressed_size = 0; + const char* ttf_compressed = GetDefaultCompressedFontDataProggyVector(&ttf_compressed_size); + return AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg); +#else + IM_ASSERT(0 && "Function is disabled in this build."); IM_UNUSED(font_cfg_template); return NULL; #endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT @@ -6406,11 +6432,340 @@ static const unsigned char proggy_clean_ttf_compressed_data[9583] = 239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,32,57,141,239,35,57,102,0,0,5,250,72,249,98,247, }; -static const char* GetDefaultCompressedFontDataTTF(int* out_size) +static const char* GetDefaultCompressedFontDataProggyClean(int* out_size) { *out_size = proggy_clean_ttf_compressed_size; return (const char*)proggy_clean_ttf_compressed_data; } + +//----------------------------------------------------------------------------- +// [SECTION] Default font data (ProggyVector-minimal.ttf) +//----------------------------------------------------------------------------- +// Based on ProggyVector.ttf, Copyright (c) 2019,2023 Tristan Grimmer / Copyright (c) 2018 Source Foundry Authors / Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. +// MIT license + public domain, see licenses at https://github.com/bluescan/proggyfonts/tree/master/ProggyVector +//----------------------------------------------------------------------------- +// See misc/fonts/ProggyVector-ExtractScript.txt for FontForge script to create this from ProggyVector.ttf +//----------------------------------------------------------------------------- + +// File: 'ProggyVector-minimal.ttf' (23952 bytes) +// Exported using binary_to_compressed_c.exe -u8 "ProggyVector-minimal.ttf" proggy_vector_minimal_ttf +static const unsigned int proggy_vector_minimal_ttf_compressed_size = 18519; +static const unsigned char proggy_vector_minimal_ttf_compressed_data[18519] = +{ + 87,188,0,0,0,0,0,0,0,0,93,144,0,4,0,0,55,0,1,0,0,0,14,0,128,0,3,0,96,70,70,84,77,165,245,48,76,0,0,93,116,130,21,38,28,71,68,69,70,0,37,130,9,34,0,93,92,130,5,44,24,79,83,47,50,135, + 98,111,82,0,0,1,104,130,15,44,96,99,109,97,112,10,236,8,177,0,0,3,88,130,19,44,82,99,118,116,32,0,34,2,136,0,0,4,172,130,31,38,4,103,97,115,112,255,255,130,89,34,0,93,84,130,15,56, + 8,103,108,121,102,169,208,238,39,0,0,6,56,0,0,84,32,104,101,97,100,39,214,168,186,130,27,32,236,130,3,33,54,104,130,16,35,6,225,0,231,130,75,32,36,130,15,40,36,104,109,116,120,37,72, + 32,85,130,15,32,200,130,3,40,142,108,111,99,97,26,185,47,212,130,95,32,176,130,15,40,136,109,97,120,112,0,201,0,151,130,11,32,72,130,47,43,32,110,97,109,101,10,160,159,163,0,0,90,131, + 143,44,68,112,111,115,116,153,185,200,234,0,0,91,156,130,35,32,184,132,235,45,1,0,0,96,193,239,192,95,15,60,245,0,11,4,130,54,37,0,0,225,81,71,241,131,8,43,228,205,29,41,255,247,255, + 2,2,162,3,161,130,15,34,8,0,2,130,5,131,2,32,1,130,225,38,182,254,184,0,143,2,102,130,31,34,196,2,162,132,73,131,25,135,3,32,4,132,17,37,195,0,104,0,5,0,134,49,131,6,132,3,32,46,132, + 5,36,2,2,102,1,144,131,29,39,2,138,2,188,0,47,0,140,131,7,40,255,92,1,224,0,49,1,2,0,131,0,32,9,132,57,143,61,43,0,66,105,114,100,0,64,0,32,32,172,3,132,131,47,3,182,1,72,32,63,0,255, + 223,253,0,0,2,14,3,182,130,48,38,32,0,1,2,102,0,34,130,9,32,0,130,7,132,3,35,0,237,0,169,130,147,46,91,0,19,0,29,1,10,0,168,0,205,0,46,0,41,130,5,32,83,130,25,44,65,0,67,0,132,0,76, + 0,75,0,40,0,72,130,11,40,70,0,66,0,63,0,239,0,209,130,33,52,45,0,44,0,81,255,251,0,18,0,79,0,70,0,69,0,94,0,117,0,51,130,7,34,100,0,61,130,5,34,108,0,38,130,21,36,58,0,86,0,58,130, + 57,42,70,0,24,0,60,0,29,0,2,0,9,130,47,50,55,0,148,0,62,0,154,0,61,255,247,0,167,0,68,0,96,0,82,130,51,34,62,0,66,130,105,40,97,0,166,0,118,0,113,0,141,130,97,32,97,130,71,32,95,130, + 3,40,129,0,106,0,128,0,84,0,50,130,183,32,38,130,85,38,101,0,92,1,6,0,102,130,147,36,0,0,232,0,105,130,17,34,102,0,18,130,187,34,99,0,160,130,33,38,135,0,40,0,44,0,178,130,9,34,159, + 0,150,130,9,52,161,0,163,0,238,0,83,0,53,0,227,0,198,0,172,0,122,0,116,0,13,132,1,32,96,130,139,32,18,136,3,32,0,130,71,33,98,0,133,1,33,100,0,133,1,32,4,132,195,32,58,130,195,131, + 3,36,75,0,4,0,74,134,1,32,18,130,33,32,94,130,187,32,68,136,3,32,20,130,197,32,62,130,215,131,3,34,109,0,134,132,1,33,69,0,131,195,32,69,130,195,131,3,34,44,0,24,130,15,32,97,132,3, + 36,52,0,95,0,52,130,123,130,166,33,0,3,130,4,131,3,34,28,0,1,130,9,36,0,0,76,0,3,132,9,32,28,130,111,32,48,130,17,46,8,0,8,0,2,0,0,0,126,0,255,32,172,255,255,130,9,34,32,0,160,131, + 9,37,255,227,255,194,224,22,132,43,130,20,131,2,34,1,6,0,136,14,35,1,2,0,0,132,55,130,6,136,2,8,152,1,0,0,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29, + 30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89, + 90,91,92,93,94,95,96,97,0,134,135,137,139,147,152,158,163,162,164,166,165,167,169,171,170,172,173,175,174,176,177,179,181,180,182,184,183,188,187,189,190,0,114,100,101,105,0,120,161, + 112,107,0,118,106,0,136,154,0,115,0,0,103,119,132,161,39,108,124,0,168,186,129,99,110,131,12,38,109,125,0,98,130,133,151,131,10,131,3,37,185,0,193,0,0,194,131,9,33,0,121,130,5,47,132, + 140,131,141,138,143,144,145,142,149,150,0,148,156,157,155,130,18,32,113,130,3,32,122,130,3,130,2,34,34,2,136,130,5,33,42,0,133,1,8,186,80,0,100,0,170,1,22,1,132,2,2,2,16,2,36,2,56, + 2,104,2,124,2,166,2,182,2,208,2,226,3,26,3,52,3,132,3,214,3,246,4,46,4,126,4,150,4,238,5,66,5,120,5,194,5,224,5,244,6,14,6,84,6,224,7,12,7,80,7,122,7,162,7,184,7,208,8,0,8,24,8,46, + 8,76,8,116,8,132,8,170,8,202,8,254,9,42,9,98,9,160,9,248,10,10,10,66,10,98,10,152,10,208,10,246,11,20,11,38,11,68,11,86,11,116,11,128,11,152,11,234,12,52,12,100,12,180,12,238,13,16, + 13,108,13,148,13,194,13,236,14,18,14,38,14,96,14,128,14,176,14,222,15,18,15,60,15,122,15,152,15,190,15,224,16,18,16,76,16,146,16,178,16,240,16,254,17,68,17,122,130,1,8,225,158,17,228, + 18,12,18,88,18,142,18,162,19,32,19,66,19,176,19,246,20,40,20,56,20,68,20,192,20,206,21,8,21,34,21,80,21,160,21,184,21,232,22,4,22,32,22,62,22,88,22,146,22,198,23,4,23,80,23,196,24, + 40,24,96,24,146,24,208,25,46,25,116,25,188,25,228,26,48,26,84,26,114,26,156,26,212,26,244,27,16,27,52,27,100,27,154,27,244,28,46,28,98,28,162,29,10,29,82,29,144,30,0,30,68,30,134,30, + 210,31,38,31,84,31,122,31,212,32,68,32,176,33,36,33,182,34,50,34,188,35,44,35,128,35,206,36,24,36,104,36,192,36,238,37,20,37,64,37,118,37,216,38,38,38,104,38,160,38,222,39,60,39,134, + 39,174,39,250,40,50,40,100,40,158,40,226,41,42,41,92,41,178,42,16,0,2,0,34,0,0,1,50,2,170,0,3,0,7,0,46,177,1,0,47,60,178,7,4,0,237,50,177,6,5,220,60,178,3,2,130,10,34,0,177,3,131,22, + 32,5,131,22,39,178,7,6,1,252,60,178,1,131,23,53,51,17,33,17,39,51,17,35,34,1,16,238,204,204,2,170,253,86,34,2,102,0,130,83,8,71,237,255,255,1,126,2,228,0,14,0,20,0,0,37,50,23,22,20, + 14,1,35,34,39,38,53,52,55,54,19,3,35,3,53,51,1,53,50,17,6,33,25,15,32,19,21,21,19,85,15,80,18,113,140,42,13,47,30,9,19,19,24,41,19,19,1,221,254,160,1,96,123,0,131,75,38,169,1,185,1, + 191,2,189,132,159,34,0,1,17,131,115,39,51,17,1,104,87,254,234,87,130,25,35,4,254,252,1,130,3,61,0,2,0,1,0,5,2,102,2,183,0,5,0,46,0,0,19,51,54,55,35,6,15,1,35,62,1,55,35,53,130,12,130, + 14,38,53,51,55,51,14,1,7,134,5,33,21,35,131,11,34,21,35,7,131,34,51,229,123,31,11,123,11,50,52,80,10,32,10,129,149,7,13,14,7,133,152,132,12,32,123,132,5,40,121,140,8,26,8,125,144,53, + 79,130,30,51,1,10,112,46,46,178,195,37,121,37,71,30,49,49,29,73,194,37,120,37,131,3,36,73,29,98,30,71,131,22,32,0,130,169,8,40,91,255,237,2,41,2,210,0,8,0,18,0,72,0,0,1,21,54,55,54, + 53,52,39,38,39,53,6,7,6,29,1,6,23,22,19,46,1,39,38,35,38,131,18,39,22,23,30,1,23,22,23,53,130,12,8,166,52,55,54,55,53,51,21,20,30,4,23,21,39,38,47,2,34,39,21,22,23,22,21,20,7,6,7,21, + 1,102,56,26,31,31,32,132,62,25,8,2,26,30,44,1,1,1,3,7,12,25,79,59,21,30,13,23,16,36,46,82,53,50,53,61,71,82,56,19,21,20,20,11,22,35,25,33,16,8,8,98,43,54,58,63,74,1,54,205,10,20,37, + 49,39,29,21,91,194,5,62,20,6,10,25,34,24,254,84,10,37,11,1,1,5,13,23,85,12,15,5,9,6,13,2,217,11,45,42,144,45,50,6,57,57,3,10,3,5,4,6,3,81,10,14,7,8,2,1,202,16,43,46,71,72,50,49,4,58, + 0,5,0,19,0,17,2,84,2,172,130,9,38,22,0,38,0,55,0,71,130,219,37,0,7,35,18,19,3,130,166,33,51,50,133,228,38,35,34,7,6,20,23,6,65,239,7,33,51,50,131,193,33,1,22,131,30,32,52,130,239,40, + 38,34,14,2,21,20,55,20,7,140,33,8,124,2,40,254,177,58,96,234,160,60,13,34,7,11,24,20,20,20,19,21,52,17,5,165,43,54,52,46,38,39,36,61,55,41,40,254,24,13,34,27,20,20,5,10,27,12,27,23, + 20,10,204,68,33,25,67,41,39,67,30,26,68,42,40,2,172,253,200,98,1,140,1,14,253,205,28,10,1,18,20,19,32,18,19,38,11,27,77,38,37,38,53,57,36,36,37,40,51,54,1,162,18,18,20,38,11,23,11, + 4,8,18,22,14,27,28,75,37,17,37,35,56,73,40,16,38,36,0,130,0,63,3,0,29,255,243,2,98,2,209,0,11,0,37,0,85,0,0,19,62,1,53,52,35,34,6,7,6,23,22,3,20,23,132,223,45,63,1,54,55,62,2,55,38, + 39,38,47,1,38,39,130,26,43,55,38,53,54,55,54,51,50,30,1,29,1,130,208,41,7,30,3,23,54,61,1,54,38,59,132,13,34,22,23,34,131,227,37,6,43,1,34,39,38,130,22,8,147,237,30,57,71,34,40,3,14, + 38,19,102,53,29,57,18,15,53,41,12,5,6,7,4,3,2,26,20,34,19,67,17,27,47,26,22,50,86,2,75,42,52,35,78,35,34,24,59,33,53,40,46,26,38,1,2,1,81,20,19,36,36,49,43,47,5,10,40,81,104,8,100, + 73,70,13,1,221,18,49,44,61,35,14,53,35,17,254,239,71,49,27,13,4,23,6,3,3,4,5,1,1,34,26,41,26,86,21,36,36,33,38,163,66,66,99,37,23,23,60,24,38,41,45,31,41,42,69,53,57,33,46,91,26,6, + 24,108,52,51,38,45,63,1,52,64,63,64,85,20,127,130,250,52,0,1,1,10,1,186,1,102,2,191,0,3,0,0,1,17,51,17,1,10,92,130,16,34,5,254,251,130,14,41,0,168,255,174,1,141,3,7,0,7,130,12,55,6, + 16,23,35,38,16,55,1,141,132,132,80,149,149,3,7,217,254,88,216,224,1,157,220,130,26,39,0,205,255,179,1,178,3,12,132,39,8,48,22,16,7,35,54,16,39,1,29,149,149,80,132,132,3,12,220,254, + 96,221,216,1,175,210,0,0,1,0,46,0,90,2,57,2,100,0,27,0,0,19,39,54,55,22,23,53,51,21,55,131,7,8,64,7,23,22,23,7,46,1,39,21,35,53,7,39,54,219,173,19,25,129,43,87,88,55,33,14,30,176,88, + 54,33,44,33,109,33,87,174,42,99,1,100,96,28,40,70,24,186,186,48,30,17,20,49,96,48,30,19,68,18,59,18,196,196,92,67,56,132,203,48,0,41,0,100,2,61,2,85,0,11,0,0,37,53,35,53,51,130,94, + 49,51,21,35,21,1,8,223,223,84,225,225,100,208,80,209,209,80,208,130,135,44,205,255,85,1,125,0,141,0,25,0,0,23,38,130,136,45,54,55,34,38,39,38,53,52,55,54,51,50,23,22,65,207,5,8,44, + 6,241,6,30,59,17,7,7,20,29,5,4,43,13,15,32,19,22,3,13,91,17,171,8,42,51,37,15,18,29,13,13,15,49,18,4,19,20,31,6,15,17,92,86,16,130,83,40,83,1,52,2,23,1,133,0,5,130,219,46,53,33,21, + 22,21,83,1,195,1,1,52,81,40,25,16,130,156,38,1,0,237,255,255,1,126,130,115,35,13,0,0,4,139,109,8,34,20,1,85,47,25,11,21,44,13,16,30,20,22,1,9,10,19,33,48,18,5,20,20,63,0,0,1,0,65,255, + 208,2,41,2,230,131,83,8,37,23,0,55,51,0,7,65,1,38,99,95,254,217,98,48,2,81,197,253,176,198,0,0,3,0,67,255,243,2,38,2,203,0,7,0,18,0,32,130,247,51,50,17,52,39,6,7,22,19,38,35,34,7,6, + 21,20,23,54,55,5,16,67,111,6,32,16,131,221,8,57,1,56,148,8,104,149,35,185,33,78,93,35,21,8,63,63,1,1,137,45,60,120,60,61,241,121,60,61,72,1,34,48,46,130,182,72,1,232,72,111,77,102, + 49,46,79,78,54,254,240,68,23,92,91,180,1,109,92,88,130,198,130,147,39,132,0,0,1,254,2,189,0,130,199,8,34,51,53,51,17,6,7,38,53,54,55,51,17,51,21,132,144,32,111,1,107,35,94,142,82,2, + 0,25,89,82,33,80,26,253,149,82,133,51,44,76,0,0,2,30,2,202,0,54,0,0,1,34,130,48,33,62,1,131,137,36,21,20,14,1,7,130,2,49,6,15,1,14,5,7,33,21,33,53,52,62,4,63,1,62,3,55,69,50,5,8,102, + 46,1,35,1,27,70,132,1,96,93,23,100,67,65,30,12,8,20,49,10,30,34,18,9,14,20,19,20,28,17,1,100,254,46,27,33,39,42,40,12,22,17,14,9,18,11,47,9,5,37,16,53,15,2,123,73,58,29,51,14,55,52, + 89,49,62,15,12,30,49,11,33,34,16,7,18,16,18,22,27,17,82,63,17,26,34,38,43,40,13,22,19,12,12,20,13,61,40,19,24,52,33,15,19,130,211,44,75,255,243,2,34,2,203,0,56,0,0,19,54,131,154,69, + 120,6,69,128,6,37,43,1,38,39,46,1,69,175,5,33,22,51,68,234,6,34,43,1,53,68,245,11,8,161,7,97,120,73,74,64,58,26,16,6,31,97,93,37,22,69,67,127,25,12,14,54,35,14,23,31,65,23,62,45,131, + 34,10,44,44,67,86,77,107,30,10,36,33,72,51,88,25,26,2,172,31,29,26,56,34,29,46,17,78,24,23,68,36,51,101,55,55,1,1,4,10,3,5,11,95,30,5,15,77,25,32,65,34,36,78,63,20,27,54,28,29,21,7, + 10,0,2,0,40,0,0,2,64,2,189,0,6,0,17,0,0,55,51,17,14,3,39,1,51,17,51,21,35,21,35,53,33,136,242,61,108,39,24,106,1,26,135,119,119,90,254,185,245,1,114,87,170,61,38,6,1,180,254,56,78, + 167,167,0,0,0,1,0,72,130,227,32,23,130,63,32,36,135,227,36,21,20,7,14,1,132,218,34,2,39,53,136,214,8,69,39,38,34,7,17,33,21,33,196,47,35,120,69,68,109,50,80,22,36,12,14,69,41,20,10, + 88,96,129,37,11,9,15,17,53,170,66,1,135,254,214,1,194,14,65,64,109,141,62,25,11,1,1,5,12,7,3,97,46,90,30,29,48,22,36,15,47,35,1,96,79,130,175,38,67,255,246,2,38,2,191,130,173,32,54, + 130,175,136,95,66,149,6,38,22,39,54,51,50,23,22,70,9,6,67,123,7,39,54,59,1,30,2,23,21,38,130,149,8,91,35,6,7,6,214,34,68,101,25,9,53,30,51,69,34,37,21,8,46,51,117,105,57,60,61,56,117, + 130,58,49,9,3,89,89,104,9,19,7,25,32,30,17,8,60,44,19,9,9,73,69,51,108,43,92,30,39,99,42,22,43,46,75,59,36,12,249,97,63,62,226,63,60,85,71,113,38,43,192,83,87,1,4,9,4,3,88,32,1,2,71, + 71,0,130,0,8,62,1,0,70,0,0,2,28,2,189,0,9,0,0,9,1,35,18,55,54,55,33,53,33,2,28,254,244,105,120,101,22,17,254,155,1,214,2,150,253,106,1,39,232,54,41,79,0,0,3,0,66,255,243,2,39,2,203, + 0,14,0,28,0,58,130,209,33,20,23,132,211,34,52,39,38,131,210,34,55,50,53,134,9,32,21,130,24,34,37,20,7,66,58,6,36,35,34,38,53,52,130,91,33,38,39,68,96,6,130,244,8,95,167,82,26,33,65, + 40,37,37,37,68,69,35,37,141,125,32,30,63,93,24,8,72,23,1,0,121,78,29,31,16,58,170,113,128,39,24,75,43,23,32,9,14,60,61,208,61,61,198,100,28,10,36,37,128,37,35,35,35,145,115,60,28,30, + 67,22,28,85,24,7,126,135,26,17,46,46,75,49,38,115,104,97,73,49,47,16,11,26,32,25,38,35,76,50,49,49,51,130,222,39,0,2,0,63,255,249,2,35,130,175,38,13,0,53,0,0,19,20,66,171,11,40,18, + 38,39,53,22,23,30,1,54,130,152,36,6,7,14,1,34,133,156,130,14,66,251,10,8,97,6,7,38,163,134,68,34,37,79,29,23,78,30,34,59,32,72,36,31,19,36,61,35,100,18,18,19,39,63,81,40,86,30,15,23, + 11,61,139,130,59,34,12,15,23,42,93,47,63,36,1,219,164,43,43,78,118,36,11,41,42,253,206,1,17,78,15,6,1,2,1,18,50,198,36,15,30,16,15,33,90,44,42,71,67,19,97,89,49,65,73,62,114,65,133, + 46,22,4,2,133,167,45,239,0,111,1,129,2,66,0,15,0,32,0,0,1,72,26,14,34,3,22,21,130,17,132,159,32,52,130,172,40,54,50,1,129,22,20,23,39,20,130,0,57,23,55,21,5,45,44,22,19,48,13,26,11, + 6,5,10,29,13,31,1,251,33,18,20,20,16,35,130,5,49,42,13,254,236,17,56,24,20,19,5,9,28,13,31,13,25,12,5,130,108,36,2,0,209,255,197,132,107,38,31,0,47,0,0,23,54,130,81,35,34,38,39,38, + 132,89,69,248,10,37,7,6,7,46,3,19,142,137,60,209,42,14,18,15,19,29,5,4,5,9,29,13,15,31,20,22,3,3,4,21,29,51,29,6,9,8,8,171,139,147,62,9,36,19,24,42,29,13,13,31,12,26,12,5,20,20,31, + 6,12,18,29,12,54,34,58,18,7,13,11,12,2,11,138,162,130,146,8,57,0,1,0,41,0,116,2,57,2,75,0,14,0,0,45,1,53,36,55,21,14,2,7,30,2,31,1,2,57,253,240,1,140,132,91,126,156,52,28,74,115,78, + 130,116,196,78,148,49,86,33,44,55,19,9,26,41,27,45,132,207,38,45,0,205,2,61,1,245,75,31,5,36,55,53,33,21,37,130,3,44,45,2,16,253,240,2,16,205,81,81,216,80,80,133,99,58,44,0,114,2,60, + 2,73,0,11,0,0,1,37,53,4,23,21,5,53,62,1,55,54,1,213,254,87,130,98,60,253,240,28,73,58,195,1,93,151,85,148,49,78,196,86,9,26,21,68,0,2,0,81,255,255,2,33,2,223,130,151,130,107,75,199, + 14,61,3,39,62,1,51,50,22,29,1,6,15,1,14,1,29,1,35,53,54,55,62,2,53,54,39,38,43,1,34,6,75,223,12,56,124,72,33,130,78,106,117,2,85,32,29,44,96,2,87,17,48,45,1,25,38,73,9,37,94,75,243, + 12,56,156,46,52,85,86,73,4,77,60,22,21,44,30,55,54,72,61,13,34,45,25,41,20,29,57,131,191,44,2,255,251,255,225,2,162,2,224,0,16,0,95,130,193,36,35,38,7,6,7,74,116,10,46,19,22,23,14, + 1,7,6,35,34,39,38,39,46,1,53,65,206,8,33,21,20,130,39,42,6,35,17,38,35,53,6,7,6,46,1,68,101,6,8,203,54,30,1,31,1,22,23,51,22,55,54,61,1,54,39,46,2,34,6,7,14,2,29,1,20,23,22,23,62,1, + 1,111,10,10,17,53,6,6,22,32,37,38,29,29,62,17,236,3,50,12,49,40,78,96,83,79,104,75,45,18,27,56,132,64,54,196,88,31,8,14,39,14,19,56,18,20,38,30,69,46,33,53,83,43,60,26,43,17,7,14,9, + 12,34,12,11,5,2,38,18,71,53,42,37,32,84,77,27,82,82,122,81,117,1,229,1,8,27,94,64,32,32,35,33,60,91,29,8,254,167,3,59,10,43,19,37,25,32,109,63,104,50,98,64,142,54,26,98,37,60,18,26, + 47,15,7,254,242,1,45,34,16,14,6,27,29,62,86,119,66,37,2,22,10,4,14,9,13,2,23,10,6,7,25,36,16,33,7,2,11,31,113,93,47,12,115,100,87,3,1,41,0,0,2,0,18,130,4,45,86,2,189,0,10,0,23,0,0, + 19,51,46,3,39,130,202,8,61,1,15,1,35,54,19,51,22,18,30,1,23,35,39,202,213,13,39,30,18,7,13,19,37,30,32,54,105,41,188,123,28,83,63,39,15,104,56,1,3,44,132,98,62,23,43,67,125,100,100, + 183,124,2,65,85,254,254,192,120,46,183,0,130,0,38,3,0,79,255,255,2,58,132,87,45,21,0,44,0,0,55,51,50,55,54,52,38,39,38,70,243,10,42,43,1,3,17,51,50,23,22,23,20,7,71,197,5,68,240,7, + 8,88,175,149,124,26,10,20,20,40,80,149,127,104,23,8,33,32,82,115,96,207,112,64,60,2,6,13,21,6,12,30,17,84,26,41,66,69,129,78,67,24,67,51,16,32,78,60,21,28,57,21,24,253,144,2,189,46, + 46,86,39,15,30,26,7,13,10,7,22,38,47,76,94,50,49,0,1,0,70,255,243,2,25,2,203,0,25,0,0,37,6,76,84,10,39,21,38,35,34,7,6,21,16,131,151,8,41,55,2,25,76,90,147,76,78,139,71,91,88,78,79, + 87,98,49,49,197,58,68,20,19,25,38,95,96,171,232,90,44,39,97,58,71,74,142,254,225,34,10,15,130,218,39,0,2,0,69,0,0,2,44,130,219,34,12,0,23,134,217,34,53,52,39,132,219,133,208,8,32,21, + 16,7,6,35,170,86,153,32,13,50,25,23,41,62,83,101,189,172,63,63,172,55,71,78,142,54,78,157,56,30,11,18,131,173,39,85,87,179,254,250,66,22,0,130,163,32,94,130,79,32,35,130,79,38,11,0, + 0,51,17,33,21,135,1,49,94,1,196,254,161,1,53,254,203,1,96,2,189,79,208,80,254,80,130,43,32,117,130,43,36,41,2,190,0,12,131,43,34,50,54,51,131,44,53,51,21,35,17,117,28,75,60,1,17,254, + 174,246,246,2,189,1,76,222,76,254,184,131,171,34,1,0,51,130,255,32,40,130,255,32,31,135,255,74,164,8,32,21,130,177,65,3,8,8,53,53,35,53,51,2,40,86,116,71,56,61,36,75,80,81,139,96,79, + 25,38,43,58,109,47,49,194,60,45,134,230,57,70,24,29,45,94,170,175,94,97,50,98,25,19,26,71,71,146,254,226,30,189,78,0,130,143,32,69,130,143,32,36,135,187,79,93,5,55,35,17,33,17,69,101, + 1,20,102,102,254,236,2,189,254,225,1,31,253,67,1,78,254,178,130,144,34,1,0,100,130,47,32,3,134,47,37,53,51,17,35,53,33,130,188,47,51,21,100,157,157,1,159,157,157,80,2,30,79,79,253, + 226,68,115,6,36,61,255,247,1,222,130,43,32,17,131,187,33,7,6,66,58,7,131,52,61,17,20,1,169,38,51,29,63,183,185,80,23,28,191,1,36,41,38,7,5,77,30,36,95,1,137,79,254,40,132,134,151,32, + 100,130,59,53,24,0,0,51,17,51,17,62,3,55,51,6,7,30,2,23,35,46,3,39,6,7,130,159,51,38,116,86,55,20,119,194,97,126,102,52,19,122,29,90,66,42,16,58,19,130,173,52,200,38,115,85,54,20,191, + 95,173,143,72,27,43,129,96,60,23,57,20,254,238,130,79,32,108,130,183,32,57,130,79,32,5,133,79,41,33,21,108,101,1,104,2,189,253,147,134,171,32,38,130,31,32,68,130,31,50,20,0,0,1,3,35, + 39,46,2,39,17,35,17,51,22,23,62,2,55,130,229,8,40,1,236,145,77,21,13,39,54,17,88,135,90,45,18,86,24,8,136,88,2,102,254,142,56,32,101,137,44,253,154,2,189,229,115,45,218,59,22,253,67, + 0,72,87,8,32,35,133,247,37,51,17,51,30,3,23,130,192,8,38,35,46,1,39,38,39,17,70,128,31,92,69,43,17,97,128,31,93,34,72,22,2,189,69,210,156,98,38,2,59,253,67,70,210,78,164,49,253,197, + 130,63,48,2,0,58,255,247,2,46,2,198,0,13,0,29,0,0,18,16,72,101,5,46,16,39,38,35,34,7,19,34,17,16,55,54,50,22,23,130,1,8,58,21,16,7,6,164,34,33,77,78,33,34,34,35,76,75,35,110,250,141, + 47,93,54,24,48,32,61,141,50,1,242,254,216,68,65,65,64,1,48,64,67,67,253,193,1,103,1,15,66,23,11,11,22,46,94,176,254,239,65,21,130,102,39,0,2,0,86,0,0,2,46,130,167,41,12,0,26,0,0,19, + 51,50,55,54,79,194,5,67,216,8,8,51,22,20,7,6,43,1,17,187,117,56,33,11,10,39,39,40,78,109,101,218,125,65,35,10,19,16,49,189,117,1,104,21,7,7,37,61,60,37,34,253,144,2,189,53,30,28,49, + 101,39,119,254,230,130,87,36,58,255,159,2,104,130,191,42,23,0,32,0,0,37,30,1,23,21,35,130,251,35,6,34,39,38,137,188,54,16,1,6,16,22,50,54,16,38,34,1,248,26,56,30,64,62,23,24,53,145, + 47,140,135,193,52,254,152,34,68,153,68,69,151,92,29,66,35,59,70,27,27,35,22,66,1,14,136,195,43,254,171,1,125,68,254,217,134,130,1,47,131,130,111,32,72,130,199,32,50,130,199,34,9,0, + 40,134,199,34,52,39,38,135,196,44,21,20,6,7,6,7,30,4,31,1,35,46,2,130,134,32,35,130,25,8,43,17,173,111,82,33,36,38,36,79,109,101,219,123,54,66,23,24,34,56,16,19,6,13,35,28,48,107,54, + 45,16,6,16,13,59,12,24,37,1,119,31,30,124,32,32,131,220,55,52,60,88,45,60,26,32,28,29,34,13,24,66,54,90,105,91,31,11,31,26,1,254,216,68,159,6,36,37,2,203,0,58,74,225,11,130,102,73, + 237,8,43,51,50,23,30,2,23,21,38,47,1,38,34,130,136,36,6,21,20,23,22,130,1,33,30,1,76,96,5,8,108,34,39,46,1,39,79,110,102,118,33,11,29,27,75,14,7,62,40,58,24,47,103,63,79,37,54,16,45, + 26,13,39,21,32,43,87,28,58,21,11,6,8,14,32,69,13,13,39,189,146,48,90,27,57,75,27,130,67,72,23,28,52,27,27,17,3,1,9,16,25,24,43,77,118,57,33,9,4,11,9,4,96,23,7,12,13,7,17,45,21,20,32, + 12,19,13,28,13,3,3,8,38,165,153,40,13,3,5,24,10,0,130,175,43,24,0,0,2,81,2,189,0,7,0,0,33,67,189,6,44,1,2,234,2,57,234,2,110,79,79,253,146,0,131,35,36,60,255,243,2,43,130,35,37,34, + 0,0,5,35,34,132,204,130,164,37,38,53,17,51,17,20,71,116,6,33,55,54,132,13,131,208,60,1,82,29,49,59,10,9,42,12,30,18,4,16,103,21,11,38,75,54,24,56,10,2,101,11,17,34,61,13,130,119,60, + 19,11,25,41,12,48,105,1,176,253,250,43,34,11,32,11,27,52,20,205,1,67,254,80,105,35,58,30,48,132,111,32,29,130,147,32,76,130,111,32,15,130,124,36,2,3,35,38,2,130,114,8,44,51,30,3,23, + 19,2,76,111,107,123,27,80,30,48,33,98,12,31,49,67,22,181,2,189,254,162,254,161,85,1,2,96,155,107,40,106,168,226,75,2,103,0,1,0,2,130,63,32,102,130,63,32,30,130,63,40,3,35,47,1,38,47, + 1,14,2,130,154,34,35,2,3,132,70,8,72,51,18,23,22,23,18,55,2,102,109,99,40,25,10,8,15,4,10,16,12,41,15,98,44,66,86,10,28,21,14,5,86,112,39,14,26,8,58,19,2,189,253,67,244,157,59,51,85, + 22,59,99,75,254,87,1,9,1,180,68,206,153,96,37,2,48,254,255,88,173,43,1,165,140,130,107,32,9,130,107,32,95,130,107,32,31,132,107,36,19,54,55,46,1,132,173,8,83,1,23,19,51,6,7,14,1,7, + 22,23,30,1,23,35,38,39,46,1,1,59,197,109,174,46,30,17,40,31,64,83,108,39,100,44,167,109,28,41,45,95,14,47,113,22,42,15,108,12,16,32,101,1,46,254,210,1,2,68,46,23,56,43,88,119,57,143, + 64,1,8,40,61,68,138,22,75,173,36,64,24,20,26,52,167,130,98,71,223,8,32,19,130,12,33,19,51,130,95,36,6,7,17,35,17,131,94,8,45,39,51,22,23,22,1,52,181,109,29,88,33,51,39,101,29,44,78, + 72,16,108,44,47,64,1,136,1,53,46,143,52,82,63,254,197,1,59,47,71,126,117,25,76,79,107,0,130,62,33,0,55,130,187,32,49,130,187,8,47,16,0,0,51,53,54,18,54,55,33,53,33,21,14,3,7,33,21, + 55,109,180,65,25,254,144,1,229,26,67,106,144,47,1,144,73,156,1,6,95,36,79,71,36,95,150,202,67,80,131,59,44,148,255,166,1,205,3,24,0,7,0,0,23,17,69,243,5,43,148,1,57,220,220,90,3,114, + 74,253,35,75,132,95,8,52,62,255,210,2,40,2,233,0,13,0,0,19,22,23,18,31,1,35,39,46,1,47,1,38,39,158,31,43,212,41,67,96,60,34,62,25,50,121,42,2,233,62,85,254,84,82,134,120,68,124,51, + 102,244,80,31,6,36,154,255,167,1,210,134,95,70,87,5,44,17,154,220,220,1,56,89,75,2,220,74,252,143,132,95,36,61,1,177,2,43,130,191,32,14,130,144,39,7,35,19,51,30,1,23,22,65,106,6,59, + 52,136,111,203,88,25,74,28,58,18,111,8,12,24,75,2,112,191,1,12,32,99,36,77,24,13,16,32,130,252,45,1,255,247,255,167,2,114,255,243,0,3,0,0,7,130,245,49,9,2,123,89,76,76,0,1,0,167,2, + 51,1,169,3,2,0,10,130,83,33,35,38,65,202,6,8,33,22,1,169,112,33,39,64,10,111,9,26,20,48,2,51,46,56,92,13,13,36,29,67,0,0,2,0,68,255,243,2,19,2,27,130,227,32,57,78,1,9,38,61,1,35,34, + 7,6,5,72,159,8,49,55,54,59,1,53,52,39,38,43,1,34,7,53,51,50,62,1,50,130,168,32,22,82,86,5,8,94,35,34,39,54,52,38,160,70,21,27,78,44,38,116,96,42,24,1,31,48,144,84,50,53,35,38,54,59, + 77,107,36,37,61,88,34,40,40,19,32,40,50,24,59,27,76,14,8,1,31,10,42,2,2,158,73,20,7,57,50,81,18,39,22,133,83,44,45,81,67,39,40,13,17,13,68,25,27,2,73,1,1,3,9,15,40,66,36,76,250,24, + 21,1,30,14,15,131,163,32,96,130,163,52,44,2,246,0,25,0,47,0,0,19,20,23,22,50,55,54,55,62,2,55,54,130,147,36,46,1,34,6,7,132,1,79,126,5,68,133,5,32,7,131,186,8,86,6,7,35,17,51,193,70, + 28,69,19,32,18,28,16,4,2,1,43,26,51,46,37,14,30,10,20,4,6,5,48,107,86,52,57,15,3,47,23,43,40,61,106,48,5,4,83,92,1,7,134,50,20,5,8,21,31,54,35,17,17,16,114,47,29,13,10,10,21,22,41, + 25,46,168,80,52,54,121,24,24,110,78,38,27,24,80,44,23,130,136,35,0,1,0,82,130,147,36,3,2,27,0,30,73,199,14,36,22,23,21,38,39,69,25,9,8,57,51,50,55,2,3,72,91,128,73,69,123,62,87,54, + 24,50,33,41,24,45,76,27,47,35,41,76,40,67,91,62,27,40,76,72,128,167,74,35,7,16,17,91,32,9,17,7,12,40,53,91,123,53,28,58,0,2,0,61,130,95,43,9,2,245,0,28,0,51,0,0,55,30,1,130,72,130, + 243,36,1,55,54,52,39,130,95,35,39,38,35,34,130,245,36,14,2,21,20,5,130,234,132,17,32,52,78,236,7,8,37,17,51,17,35,38,200,24,48,22,42,20,37,11,16,6,2,1,1,2,2,3,12,35,80,45,26,29,9,17, + 6,3,1,14,50,101,62,63,17,130,252,8,60,30,29,57,102,75,48,16,11,92,83,2,101,29,13,15,26,29,35,49,17,17,32,17,17,17,30,26,80,20,22,22,37,52,34,16,114,82,80,37,16,54,122,25,88,100,37, + 73,45,15,20,1,42,253,11,19,0,0,0,2,0,62,130,159,32,44,130,255,38,10,0,36,0,0,19,33,132,149,131,147,32,1,87,7,12,35,29,1,33,21,80,85,6,8,67,55,162,1,47,14,21,60,20,26,69,46,40,1,110, + 96,100,129,74,74,116,60,83,170,50,15,254,114,46,46,90,72,76,23,24,1,54,37,42,54,18,5,46,38,254,157,40,72,74,126,164,79,37,148,46,46,56,3,83,48,50,33,10,11,0,0,1,0,66,130,120,44,40, + 2,224,0,22,0,0,51,17,35,53,51,53,131,242,34,59,1,21,131,119,8,35,29,1,51,21,35,17,231,165,165,22,21,43,99,136,140,50,19,19,169,169,1,143,78,71,43,84,21,40,73,19,17,62,88,78,254,113, + 130,62,37,0,76,255,3,2,23,130,183,37,18,0,63,0,0,19,134,155,32,53,131,190,33,46,1,80,245,5,49,23,52,38,53,51,6,29,1,6,20,14,3,35,7,53,51,54,55,131,1,34,53,6,7,132,217,34,39,46,3,77, + 142,5,8,106,168,83,26,33,98,27,8,9,15,13,28,47,27,60,38,38,125,105,55,1,83,1,1,1,17,62,60,45,222,102,53,36,66,34,33,1,32,29,48,40,70,42,20,17,29,32,10,6,48,24,43,42,1,13,147,41,12, + 113,37,33,77,27,50,16,31,13,50,50,173,67,13,29,10,34,45,95,93,193,113,99,66,37,2,78,1,1,2,46,46,60,77,38,9,15,24,13,15,28,72,48,48,24,110,74,37,26,24,131,251,32,97,130,188,35,13,2, + 245,0,130,12,42,19,54,59,1,50,23,22,21,17,35,17,81,160,6,33,7,6,131,12,8,38,51,189,50,106,10,68,38,64,92,57,20,26,73,38,19,7,4,92,92,1,207,80,32,57,127,254,185,1,71,105,23,9,52,26, + 47,20,21,254,214,130,68,35,0,2,0,166,130,84,51,129,2,219,0,21,0,33,0,0,33,35,53,54,61,1,35,53,51,21,20,130,248,34,22,29,1,130,2,41,20,6,17,20,43,1,34,61,1,52,130,109,38,21,1,128,92, + 1,127,218,130,222,63,1,15,71,16,16,71,15,114,28,120,187,77,64,16,35,37,126,11,23,40,16,18,66,16,37,2,103,14,14,81,14,14,130,166,37,0,118,255,4,1,187,130,91,43,15,0,27,0,0,23,53,51, + 50,54,53,17,130,92,41,17,20,6,7,6,35,19,50,29,1,134,88,63,51,118,143,46,44,144,236,22,23,45,80,149,14,14,73,14,14,252,80,80,58,1,227,77,253,208,46,96,25,51,3,215,131,79,32,81,130,81, + 130,170,33,0,113,130,88,34,84,2,218,130,175,8,61,0,1,7,21,35,17,51,17,62,1,55,54,55,51,6,7,30,3,23,35,38,1,20,68,95,95,29,89,33,40,51,111,158,62,31,94,69,44,17,113,186,1,15,60,211, + 2,218,254,90,27,80,30,37,44,141,57,40,121,89,56,22,245,131,75,32,141,130,4,36,119,2,190,0,8,130,7,55,7,17,35,17,52,39,35,53,1,119,2,92,1,139,2,190,192,254,2,2,9,40,63,78,130,26,41, + 0,41,0,0,2,69,2,27,0,38,130,12,33,54,51,65,114,13,32,21,130,55,76,176,7,130,10,8,72,51,20,6,21,54,55,50,1,71,46,85,66,29,28,84,15,12,39,38,25,16,84,3,9,17,30,55,14,15,84,77,1,33,89, + 60,1,217,66,47,50,137,254,207,1,45,114,26,26,29,26,111,254,211,1,96,69,16,30,28,26,112,254,211,2,14,8,29,9,57,2,0,1,0,65,231,5,40,27,0,18,0,0,1,52,35,34,65,217,6,33,22,23,130,127,130, + 114,61,1,177,107,100,28,9,92,83,7,2,51,114,171,92,1,71,137,95,31,40,254,214,2,14,49,30,92,212,254,185,130,174,37,0,69,255,243,2,36,130,179,34,15,0,28,66,223,13,131,75,35,19,34,39,38, + 88,17,6,8,51,16,6,166,81,27,34,67,39,37,82,26,35,69,36,37,143,179,46,15,15,46,178,117,61,62,122,1,7,146,44,14,54,53,97,149,41,13,52,51,254,136,157,51,134,51,159,71,70,254,243,142,0, + 131,95,36,95,255,3,2,42,130,95,32,10,131,95,34,37,50,16,132,162,36,20,23,22,23,34,76,96,6,65,40,5,46,20,7,6,1,82,132,132,101,28,9,79,25,34,105,46,131,177,8,32,48,103,99,60,57,127,39, + 59,1,151,117,37,49,147,43,14,72,80,254,192,3,11,41,26,80,74,73,129,196,62,18,0,2,130,187,40,4,2,15,2,26,0,14,0,32,85,95,15,39,20,1,54,55,51,17,35,17,68,93,10,8,33,190,34,65,66,34,35, + 78,25,32,65,34,35,1,24,7,2,83,92,47,105,136,53,25,127,40,50,101,111,54,54,51,99,151,39,130,191,47,199,1,40,38,28,252,248,1,62,81,130,61,74,206,63,19,130,195,34,1,0,129,130,200,32,25, + 130,195,44,25,0,0,1,38,43,1,34,6,7,6,29,1,130,195,8,53,21,35,17,51,22,20,6,21,54,59,1,22,23,2,25,56,84,39,10,63,21,45,1,1,92,90,1,2,56,127,5,82,49,1,155,48,24,21,45,43,42,30,48,146, + 60,2,14,6,18,24,23,84,2,38,130,82,35,0,1,0,106,70,15,6,39,39,0,0,1,34,21,20,23,75,15,9,86,136,10,33,46,1,84,150,5,8,72,55,54,50,23,21,38,1,67,121,25,28,109,12,139,59,59,183,108,108, + 80,57,36,35,29,27,67,10,9,29,66,40,36,55,54,185,83,80,1,211,78,37,17,17,19,2,26,116,78,45,45,32,90,51,24,21,40,36,19,19,13,2,2,6,12,36,34,60,76,41,40,31,84,43,133,123,41,128,255,254, + 1,230,2,174,0,17,0,74,223,5,36,53,17,51,21,51,130,204,130,210,59,59,1,1,230,169,103,43,43,92,221,221,24,22,60,160,2,39,41,94,2,2,160,79,254,237,59,18,18,130,60,51,1,0,84,255,242,2, + 20,2,13,0,24,0,0,37,6,43,1,38,35,34,130,61,8,61,17,20,51,54,55,54,53,54,53,51,20,22,29,1,35,1,190,37,123,9,4,5,184,91,124,73,30,34,3,92,1,86,57,71,1,213,1,69,254,187,139,8,36,40,57, + 240,83,63,194,72,196,0,0,1,0,50,0,0,2,54,2,14,131,135,40,1,3,35,46,3,39,51,23,22,130,1,8,40,62,1,63,1,2,54,198,119,25,72,55,34,13,95,50,30,22,46,15,26,57,30,50,2,14,253,242,64,194, + 143,91,34,135,81,60,125,40,68,157,81,135,131,67,130,148,33,2,104,130,67,32,27,130,12,43,3,35,2,38,39,51,30,2,23,19,51,23,130,5,131,71,32,51,130,87,8,58,1,39,1,52,89,88,89,33,9,91,22, + 49,16,6,72,102,25,16,22,14,5,11,31,12,31,91,131,88,11,32,12,1,33,254,223,1,100,136,34,93,220,70,27,1,4,80,48,71,44,17,50,151,56,153,253,242,35,107,39,130,93,130,167,32,38,130,167,32, + 67,130,99,39,35,0,0,51,54,55,46,2,130,99,46,3,23,62,1,55,51,14,3,7,30,1,23,35,39,38,130,1,33,7,6,130,1,57,38,140,80,61,92,34,14,103,18,55,40,26,9,109,29,10,103,24,74,55,34,14,25,169, + 27,107,130,198,33,45,17,132,4,58,171,103,79,113,44,16,23,70,52,33,12,139,39,12,31,92,69,43,17,30,211,33,65,38,29,58,21,132,4,133,115,8,40,70,255,2,2,25,2,15,0,50,0,0,23,51,54,59,1, + 50,55,54,53,54,52,39,35,34,38,61,1,52,55,53,50,54,51,17,20,23,22,59,1,17,130,241,34,54,51,21,69,131,5,130,5,8,80,20,6,35,33,38,54,119,59,45,37,102,39,17,25,1,1,189,84,100,1,17,57,18, + 24,25,68,163,1,1,35,11,47,1,1,1,88,66,254,248,1,1,174,1,29,45,64,10,18,8,100,63,252,32,28,50,1,254,202,77,31,27,1,82,54,52,1,83,41,37,76,40,66,115,51,32,32,81,127,21,39,0,130,255,32, + 101,130,255,32,8,130,139,32,17,130,255,33,53,54,88,38,5,32,21,131,238,8,34,6,7,33,21,101,39,60,114,109,254,203,1,150,39,59,115,60,27,21,1,65,80,46,70,134,129,68,78,46,70,136,69,33, + 24,71,131,63,40,92,255,151,2,3,3,38,0,44,66,111,6,130,193,83,72,8,130,11,32,55,130,222,71,147,6,32,20,84,214,5,33,29,1,132,219,8,76,2,3,33,122,44,43,26,27,56,72,59,71,25,26,43,43,123, + 33,36,68,22,21,23,26,48,46,28,23,21,24,46,56,105,34,35,109,113,70,28,23,88,21,28,72,111,109,35,35,84,14,19,71,110,74,33,40,11,10,41,33,76,115,63,19,15,0,1,1,6,255,181,1,92,3,9,0,3, + 130,123,43,17,51,17,1,6,86,75,3,84,252,172,0,131,151,32,102,130,151,32,16,130,151,40,50,0,0,23,53,51,50,55,54,132,140,34,55,38,39,130,1,137,163,33,23,22,132,142,35,23,22,51,22,72,59, + 8,130,167,8,99,35,102,34,72,20,22,22,31,43,28,16,37,9,6,22,20,72,34,31,124,43,42,10,6,7,33,65,16,21,28,32,96,35,23,42,42,125,105,83,16,20,70,108,74,34,42,9,6,15,31,40,26,59,97,63,20, + 14,84,35,34,110,113,36,24,11,10,37,1,88,39,33,61,100,109,36,34,0,1,0,40,0,241,2,61,1,215,0,33,0,0,19,39,54,55,54,51,50,23,30,1,130,115,130,149,33,55,23,87,136,6,131,151,8,89,35,34, + 7,14,1,118,78,12,21,41,76,37,19,28,41,11,57,36,56,13,5,3,77,33,36,83,39,22,33,28,51,16,19,19,38,17,7,12,1,20,18,71,36,70,11,15,41,14,76,73,22,27,17,51,59,68,12,19,37,65,10,13,33,27, + 44,0,2,0,232,255,227,1,138,2,193,0,6,0,20,0,0,55,54,55,51,19,21,35,2,52,131,115,33,22,21,133,106,8,34,246,9,29,60,34,132,14,23,21,37,35,46,49,15,17,37,21,181,79,187,254,246,210,2,102, + 76,21,23,46,27,66,18,5,21,0,130,71,48,105,255,109,2,18,2,161,0,8,0,43,0,0,37,17,6,7,79,220,5,34,53,38,39,89,241,5,36,54,55,53,51,21,130,197,32,21,130,16,32,39,71,127,5,32,21,130,36, + 37,35,21,1,93,66,40,130,0,8,70,66,117,60,67,13,22,24,70,115,51,62,49,19,46,23,34,27,8,16,8,48,50,11,9,55,55,59,1,151,6,56,54,87,88,54,56,212,135,9,75,75,115,58,37,60,28,82,12,134,134, + 8,17,8,81,26,5,8,3,254,102,1,3,1,10,28,81,4,4,23,135,0,82,115,8,43,44,2,203,0,27,0,0,19,52,51,50,23,131,115,73,231,8,8,47,21,33,21,33,53,51,53,35,53,51,187,227,62,70,9,8,50,60,103, + 20,8,185,185,1,12,254,26,117,99,99,1,221,238,28,86,5,5,31,96,33,61,86,68,218,80,80,218,68,130,219,42,102,0,92,2,38,2,0,0,13,0,47,70,91,11,8,32,34,7,6,20,23,7,38,39,54,55,46,1,53,52, + 55,38,39,55,23,54,50,23,55,23,22,23,7,22,20,7,22,23,6,130,27,8,86,6,34,250,32,45,46,30,31,31,30,92,30,32,11,82,10,36,80,3,22,7,30,72,12,48,82,50,90,50,83,22,14,9,83,30,31,23,61,38, + 9,80,3,50,90,229,28,28,31,42,43,29,28,28,28,86,92,76,10,32,75,3,36,43,11,44,43,69,10,44,79,29,28,78,22,13,8,79,49,88,39,21,57,33,11,75,3,29,133,231,86,239,7,43,35,0,0,1,6,7,21,51,21, + 35,21,35,131,216,33,53,39,130,221,79,22,8,8,80,23,19,51,7,14,1,7,51,21,1,145,5,38,201,201,101,200,200,45,155,122,19,30,68,33,11,108,44,47,64,27,181,109,50,51,53,11,126,1,130,9,62,17, + 51,247,247,51,17,71,52,32,48,111,55,17,76,79,107,47,1,53,80,80,86,17,52,0,0,2,1,10,255,188,1,96,3,2,0,3,0,7,67,61,5,8,45,3,17,51,17,1,10,86,86,86,68,1,101,254,155,1,226,1,100,254,156, + 0,2,0,99,255,164,2,6,2,203,0,17,0,85,0,0,19,20,23,22,23,54,53,52,39,38,130,1,33,6,7,130,1,32,5,92,10,8,37,43,1,39,46,3,39,70,224,11,35,2,53,52,55,66,44,6,35,51,31,1,22,130,58,86,216, + 5,66,74,6,33,30,1,130,17,8,129,22,181,42,40,112,61,8,12,17,39,117,28,18,4,3,9,1,81,92,50,5,4,51,50,86,20,20,27,18,20,43,11,88,60,73,26,7,61,38,46,87,46,16,92,59,50,35,61,18,18,39,20, + 9,13,20,53,82,60,42,13,33,7,7,18,26,59,5,5,20,92,36,33,1,98,35,37,36,53,38,48,20,13,20,15,35,58,18,25,4,5,19,77,84,48,44,32,14,25,58,39,40,2,3,4,3,12,3,77,36,43,13,15,44,36,25,25,47, + 50,41,25,87,46,39,67,61,38,27,7,3,2,130,0,8,40,3,17,77,37,7,20,15,16,11,22,18,26,33,3,2,10,46,41,37,0,0,0,2,0,160,2,123,1,201,2,217,0,11,0,23,0,0,1,52,59,1,74,174,6,33,53,39,138,11, + 36,1,99,16,70,16,130,2,43,195,14,72,15,15,72,14,2,204,13,13,68,135,2,33,0,3,130,71,51,58,2,104,2,126,0,27,0,51,0,75,0,0,37,50,55,21,6,34,39,91,150,5,46,51,50,23,21,46,2,43,1,34,7,6, + 21,20,22,7,82,126,9,75,202,9,34,20,23,22,79,122,7,68,56,9,89,249,5,8,126,1,85,45,46,52,106,36,73,28,12,13,42,139,57,56,35,43,14,6,13,64,31,33,70,150,55,90,24,26,74,68,64,33,18,76,70, + 111,56,32,137,27,5,32,9,1,105,53,92,160,96,52,35,17,91,165,99,72,45,34,8,50,35,35,42,26,219,25,49,22,11,24,68,31,82,32,103,20,51,17,6,2,34,33,64,60,68,26,63,19,5,42,37,72,42,37,116, + 68,70,14,56,123,23,24,54,64,15,124,35,130,73,87,61,76,24,129,48,31,41,12,70,87,83,52,60,28,20,0,130,219,38,135,0,220,1,224,2,203,130,9,41,17,0,46,0,0,55,53,33,21,3,130,203,130,179, + 33,50,55,130,173,34,61,1,21,73,162,8,80,51,5,8,122,34,7,53,54,63,1,50,23,22,29,1,35,38,146,1,78,138,104,22,8,22,22,62,22,43,18,9,53,80,96,33,9,103,33,56,79,49,27,93,71,40,60,35,132, + 33,11,64,4,220,59,59,1,43,37,13,49,18,18,8,18,46,22,19,22,130,61,70,22,28,89,28,8,1,55,20,11,31,59,16,9,2,92,31,44,211,18,0,0,0,2,0,40,0,67,1,245,1,242,0,12,0,29,0,0,1,23,21,39,53, + 62,3,55,21,14,1,7,22,23,21,38,39,46,1,130,15,32,1,130,148,8,49,21,6,1,94,151,235,29,86,64,40,16,29,93,255,78,72,15,20,53,118,28,28,87,32,61,26,78,1,26,126,89,196,38,24,72,54,34,13, + 90,24,79,23,67,59,89,12,17,45,98,24,130,17,53,27,52,22,90,67,0,1,0,44,0,174,2,60,1,150,0,5,0,0,37,53,33,130,237,41,1,232,254,68,2,16,174,151,81,232,130,131,42,1,0,178,0,225,1,182,1, + 46,0,3,65,11,5,39,178,1,4,225,77,77,0,4,66,3,8,39,10,0,37,0,61,0,85,0,86,143,5,32,53,85,200,8,41,21,20,7,6,7,30,1,23,30,5,81,241,5,35,43,1,21,39,66,12,46,8,32,246,51,45,14,23,19,18, + 42,54,65,119,145,48,16,20,5,11,8,3,8,11,8,18,32,11,72,65,10,18,26,16,23,133,66,20,39,8,32,1,113,9,15,30,33,9,12,254,225,1,71,93,50,24,7,3,1,10,7,4,11,12,11,27,50,17,102,12,19,7,140, + 3,66,31,40,8,40,1,0,159,2,135,1,202,2,205,0,3,0,0,1,21,33,53,1,202,254,213,2,205,70,70,0,0,0,2,0,150,1,160,1,211,2,203,0,13,0,35,130,29,80,201,5,46,35,34,7,6,20,22,50,55,22,23,30,1, + 20,14,1,103,70,13,8,61,1,132,15,6,13,38,14,22,45,24,28,54,92,11,30,31,13,23,23,34,18,32,54,84,46,26,45,46,66,8,7,35,2,4,17,50,16,30,17,7,24,26,76,52,228,13,29,13,55,60,54,30,12,21, + 63,39,38,72,43,44,1,5,132,115,32,44,130,120,34,60,2,38,130,143,38,15,0,0,51,53,33,21,101,69,11,47,44,2,16,254,206,222,222,84,222,222,80,80,160,155,80,155,130,2,130,152,47,0,161,2,14, + 1,190,3,159,0,27,0,0,19,54,51,50,130,153,38,21,20,7,14,2,7,51,130,208,33,54,55,130,1,8,52,52,39,38,34,7,164,66,46,100,43,18,6,15,40,67,59,20,204,254,227,21,36,114,15,21,7,23,106,68, + 3,132,27,48,20,32,10,35,19,51,60,54,18,54,53,20,33,100,27,29,38,12,38,34,130,142,50,0,1,0,163,2,9,1,206,3,161,0,55,0,0,1,20,7,22,23,88,146,5,36,34,47,1,38,39,131,1,32,53,94,4,10,92, + 154,10,38,35,34,14,3,7,53,54,130,139,8,92,22,1,196,86,47,24,25,12,36,133,17,7,7,14,8,7,17,10,20,11,39,24,23,26,95,14,2,28,23,59,32,37,71,18,6,52,17,17,23,39,15,14,14,8,77,38,112,37, + 11,3,59,65,22,8,26,25,67,22,71,1,2,1,1,4,2,4,5,56,15,3,7,56,7,13,29,18,18,51,33,10,13,42,12,4,8,2,5,6,2,57,17,60,19,130,159,40,238,2,81,1,221,3,2,0,9,130,159,34,6,7,35,132,238,53,55, + 1,221,143,20,76,17,25,26,20,38,14,3,2,156,21,21,33,33,24,48,18,133,207,44,83,255,55,2,65,2,14,0,30,0,0,37,6,78,3,5,39,17,20,23,22,51,50,53,17,74,209,6,33,50,55,68,18,5,8,47,1,175,42, + 181,42,83,91,18,33,66,127,93,17,6,5,8,7,23,40,23,39,14,24,60,73,72,254,252,2,215,254,186,54,30,55,158,1,51,254,106,42,8,3,10,70,20,14,24,133,95,36,53,255,164,2,3,85,35,5,43,5,17,38, + 39,38,53,52,54,59,1,17,35,130,1,56,1,23,136,56,34,132,106,224,71,95,92,1,141,10,78,43,67,90,108,252,231,2,224,253,32,130,56,48,1,0,227,1,14,1,133,1,174,0,15,0,0,1,22,21,20,107,176, + 9,8,35,51,50,1,110,23,35,29,17,34,23,24,50,14,17,32,1,152,23,43,26,34,12,23,22,35,54,20,6,0,1,0,198,255,71,1,148,130,65,41,17,0,0,5,50,53,52,38,39,51,130,61,8,33,7,6,43,1,34,39,53, + 22,1,17,62,33,11,59,54,46,33,25,37,28,37,36,128,43,21,49,15,54,49,53,18,11,11,61,131,102,8,57,0,172,2,14,1,202,3,151,0,13,0,0,19,54,55,51,17,51,21,33,53,51,17,14,1,7,172,42,73,68,103, + 254,235,103,21,70,21,3,132,6,13,254,172,53,53,1,30,4,11,4,0,3,0,122,0,220,1,239,69,79,6,32,37,68,67,5,34,39,22,51,101,144,6,106,122,9,32,39,103,204,10,8,71,21,20,138,1,82,213,20,25, + 53,27,29,44,21,70,20,62,244,49,87,46,25,43,16,45,8,3,76,43,67,87,49,51,220,59,59,172,9,37,33,68,79,38,21,9,27,203,39,53,11,19,17,46,57,20,34,98,54,31,53,53,88,89,0,2,0,116,0,67,2,65, + 1,242,91,143,5,34,1,23,21,130,161,41,6,7,53,62,1,55,38,39,7,38,130,230,33,23,22,130,19,8,61,3,7,53,54,1,86,235,29,86,32,59,29,28,94,29,54,97,76,72,78,59,60,78,37,15,40,64,87,28,72, + 1,242,197,38,24,72,27,50,23,89,23,79,24,42,84,126,59,67,90,50,50,65,32,38,13,33,54,72,24,89,59,0,130,0,59,4,0,13,255,129,2,45,3,11,0,5,0,20,0,24,0,36,0,0,37,51,53,6,7,6,23,53,35,131, + 108,44,54,55,51,21,51,21,35,21,19,5,39,37,1,65,45,8,8,65,6,7,1,27,137,9,12,68,89,194,22,67,25,34,34,80,59,59,69,253,237,13,2,19,254,11,115,68,103,254,235,103,63,49,12,195,13,16,94, + 211,87,57,31,91,33,47,46,253,52,87,1,231,123,51,123,1,95,17,254,172,52,52,1,31,12,7,130,122,33,0,3,136,123,36,30,0,34,0,46,130,121,80,150,8,37,7,6,7,51,21,33,133,128,92,31,6,34,34, + 7,37,143,131,59,8,63,48,82,44,43,15,29,39,83,36,205,254,226,22,72,19,54,9,6,6,19,25,23,96,60,1,37,142,143,58,247,26,30,34,47,29,22,40,36,75,34,53,52,20,66,17,50,12,9,6,32,18,33,17, + 17,34,172,144,152,65,19,7,32,19,65,19,6,32,79,65,19,25,47,45,1,50,52,35,34,15,1,14,1,7,53,55,62,1,55,137,192,32,22,75,212,5,41,47,1,34,39,46,2,39,53,30,1,101,182,8,34,43,1,53,65,61, + 22,8,45,135,95,90,37,17,25,7,15,8,18,21,19,11,16,35,71,42,42,49,16,21,96,47,48,85,9,8,29,8,7,13,23,14,8,18,24,7,38,27,93,14,2,6,21,82,33,65,98,20,8,56,212,113,5,7,2,5,2,56,4,5,2,2, + 3,27,28,46,51,23,7,5,20,79,58,31,32,1,2,2,4,4,4,2,58,6,8,2,10,56,8,25,12,40,51,0,2,0,96,255,244,1,239,2,219,0,50,0,67,130,227,33,54,55,66,100,5,72,27,7,35,62,1,63,1,131,211,36,55,54, + 61,1,52,130,3,32,51,131,210,36,7,14,2,15,1,81,137,5,33,51,19,69,25,5,33,35,34,66,247,6,8,119,50,1,82,68,89,31,31,11,33,25,35,38,87,52,56,17,22,53,6,27,8,12,5,15,4,8,1,96,12,18,43,12, + 11,27,5,13,31,19,28,71,40,30,10,4,16,25,23,39,31,6,5,57,7,24,65,7,57,89,17,11,4,14,3,3,44,46,75,40,27,35,49,5,25,7,13,6,17,8,16,32,2,3,5,5,65,72,45,25,40,39,11,10,26,5,13,36,25,10, + 31,22,38,2,149,9,27,13,51,14,23,29,13,13,16,56,14,1,0,0,0,3,90,175,5,39,3,101,0,10,0,23,0,31,98,145,23,39,3,46,1,39,51,30,1,23,98,153,23,39,145,22,70,22,92,19,61,19,98,161,22,36,2, + 49,23,79,23,130,2,137,111,32,104,132,111,32,27,151,111,35,17,7,35,55,151,107,34,114,77,98,151,102,34,177,123,123,138,211,32,102,132,99,32,35,151,99,42,3,38,39,14,1,7,35,54,55,51,22, + 152,215,43,47,48,35,15,52,16,69,85,20,94,44,62,151,116,41,50,51,33,15,53,16,102,23,51,74,138,123,32,81,132,123,32,62,153,123,40,34,7,6,29,1,35,52,55,54,94,110,5,32,22,79,205,5,43,51, + 6,7,6,35,34,46,1,47,1,46,3,151,255,8,33,172,14,18,6,22,63,27,26,42,6,9,30,34,7,10,26,11,19,8,13,62,3,53,17,15,32,18,9,6,14,7,7,18,5,151,169,63,92,7,4,11,30,4,49,27,28,1,6,17,4,5,13, + 9,15,19,3,73,23,8,8,3,3,7,4,4,9,4,0,4,66,11,12,34,35,0,47,151,189,32,19,86,222,6,36,59,1,50,21,7,138,11,151,177,32,19,76,76,5,38,196,15,72,14,14,72,15,151,157,35,93,14,14,67,135,2, + 66,151,8,38,126,0,8,0,22,0,44,132,137,53,1,39,14,3,18,6,20,30,1,51,50,55,54,52,39,38,35,34,3,7,35,19,110,2,8,8,89,21,20,7,22,18,22,23,35,39,202,213,48,46,13,13,39,29,18,35,12,34,26, + 16,33,21,22,5,20,52,29,101,54,105,214,61,14,46,77,56,42,39,61,46,120,34,14,104,56,1,3,158,156,43,43,132,97,62,2,11,26,44,31,11,21,20,45,13,44,253,115,183,2,145,35,72,38,22,70,38,39, + 53,66,41,138,254,141,105,43,183,0,130,0,32,2,132,4,38,78,2,189,0,7,0,23,131,141,46,17,35,14,1,7,6,15,1,35,19,33,21,35,21,51,132,3,63,33,53,164,154,53,12,38,13,30,30,50,92,205,1,120, + 169,153,153,178,254,240,1,3,1,107,45,133,50,106,108,180,2,100,83,5,32,180,131,74,45,1,0,70,255,71,2,25,2,203,0,51,0,0,1,130,202,78,63,5,131,217,43,55,21,6,7,34,6,7,22,23,22,21,20,71, + 149,5,37,51,50,53,52,46,3,71,33,7,8,88,55,54,50,23,2,25,79,87,98,49,49,75,45,76,59,68,20,19,47,43,6,22,8,26,3,15,120,22,25,40,36,39,62,14,3,7,7,4,129,73,78,14,45,116,55,159,78,2,67, + 58,71,74,142,175,70,42,34,10,15,97,23,9,3,1,34,7,32,19,82,11,61,15,43,14,26,8,9,9,6,8,87,96,171,89,50,152,50,25,39,132,226,43,0,98,0,0,2,39,3,104,0,11,0,19,101,29,13,68,3,7,50,98,1, + 188,254,170,1,70,254,186,1,95,240,21,71,21,92,18,62,18,134,217,36,2,237,23,77,23,130,2,130,72,32,2,138,71,32,15,142,71,34,7,35,55,138,67,35,113,114,77,98,134,63,35,3,104,123,123,138, + 59,32,102,130,131,32,24,142,59,67,179,9,33,31,1,138,68,32,151,67,167,7,35,95,20,33,52,134,77,33,2,233,67,152,6,36,23,39,63,0,3,134,143,32,101,130,83,33,25,0,130,234,101,247,11,32,3, + 66,195,6,33,55,54,66,209,11,133,13,138,100,44,85,15,71,15,3,4,28,51,15,196,15,72,14,132,8,134,105,41,3,20,14,14,67,7,4,3,14,67,134,7,36,0,0,2,0,100,130,4,34,3,3,104,130,111,32,18,130, + 195,95,33,5,43,21,35,17,51,21,3,46,1,39,51,22,23,101,128,6,38,216,21,70,22,92,47,52,101,135,7,38,2,237,23,77,23,60,63,140,63,32,15,142,63,34,7,35,55,134,60,35,77,114,77,98,135,57,65, + 60,5,135,119,32,102,130,119,32,21,144,55,33,54,55,130,120,33,35,38,134,61,41,208,82,70,85,20,95,44,62,71,48,136,67,41,61,84,102,23,51,74,51,0,0,3,134,191,32,101,130,71,34,23,0,35,142, + 73,67,255,22,134,87,32,58,67,238,12,136,91,32,20,67,223,11,42,2,0,4,0,0,2,39,2,189,0,19,131,93,38,55,51,50,55,62,1,55,81,133,6,47,43,1,21,51,21,35,3,17,35,53,51,17,51,50,22,21,106, + 19,5,8,54,170,48,66,45,43,36,10,28,9,21,50,54,94,48,132,132,103,63,63,151,171,162,81,45,59,64,99,78,15,17,43,21,57,120,85,36,87,32,33,221,70,254,179,1,77,70,1,42,170,181,179,85,45, + 21,20,130,102,33,0,70,130,4,38,35,3,102,0,16,0,60,130,201,32,17,96,135,5,41,17,51,17,35,38,39,38,39,17,19,69,134,5,33,30,1,84,192,8,48,61,1,51,6,7,6,34,39,46,4,47,1,46,1,39,46,1,80, + 206,5,8,121,70,128,16,44,34,93,65,97,128,74,59,93,26,39,63,27,25,43,28,31,20,3,10,24,4,11,7,15,9,11,62,3,53,17,28,8,18,11,9,12,15,3,18,4,5,3,7,6,3,7,26,9,2,2,189,37,100,78,215,147, + 2,65,253,67,167,137,215,59,253,190,3,0,44,31,27,13,11,1,3,13,1,4,13,11,19,3,72,23,7,1,2,4,3,6,7,2,10,1,4,1,3,3,27,8,6,0,0,3,0,58,255,243,2,46,3,104,0,13,0,26,0,34,83,209,11,43,35,34, + 6,16,39,16,51,50,23,22,21,16,131,164,33,38,19,130,162,131,210,8,53,198,35,75,76,35,34,34,34,77,76,68,106,250,126,63,61,192,27,94,47,140,246,21,70,22,92,18,63,18,130,67,67,64,156,157, + 64,66,132,254,205,152,1,109,90,94,181,254,190,36,5,22,66,2,162,67,178,8,142,115,32,30,156,115,35,1,7,35,55,148,111,36,1,129,114,77,98,150,108,34,3,29,123,71,159,5,133,219,32,102,132, + 219,32,39,157,103,67,240,11,149,112,32,86,67,251,11,150,121,33,2,158,68,11,12,139,127,32,70,156,127,66,27,40,148,155,32,148,66,35,38,151,181,32,181,66,41,34,34,0,0,4,66,43,6,40,101, + 0,13,0,26,0,38,0,50,156,209,32,1,67,188,22,148,192,33,1,143,67,203,12,151,167,32,201,67,218,11,8,34,0,1,0,75,0,82,2,30,2,9,0,36,0,0,37,7,39,54,63,1,54,55,46,3,39,55,30,2,23,54,55,23, + 14,3,7,109,205,5,58,7,38,39,46,1,1,52,174,59,21,32,64,40,18,22,64,48,30,11,58,55,79,30,11,47,128,59,132,12,63,11,30,24,56,32,21,59,11,15,57,69,247,165,55,20,30,60,37,17,20,61,45,28, + 11,55,50,76,28,11,43,122,55,132,12,43,11,28,22,53,30,20,55,11,14,53,67,0,130,0,52,3,0,4,255,223,2,88,2,221,0,18,0,33,0,72,0,0,9,1,30,2,78,109,5,51,38,53,39,38,53,38,39,52,5,54,55,38, + 35,34,7,6,7,6,29,1,68,91,5,34,46,1,39,89,67,5,32,53,73,143,5,41,55,22,23,7,22,23,30,1,23,22,68,121,5,8,134,34,38,39,38,1,186,254,255,15,50,37,21,78,33,34,1,2,1,1,1,254,234,168,84,23, + 91,42,19,36,13,33,2,39,44,28,10,31,10,89,24,5,1,1,4,98,63,88,116,57,70,35,15,84,14,4,13,6,2,3,16,30,92,46,68,49,42,17,41,1,231,254,167,35,33,11,67,73,148,13,23,10,37,8,7,7,6,10,251, + 225,113,78,13,27,30,62,182,47,14,10,18,172,56,39,6,21,6,119,56,69,16,16,39,41,221,88,50,77,95,23,12,112,28,15,49,51,18,27,140,68,133,48,22,14,7,16,130,222,50,0,2,0,74,255,243,2,31, + 3,102,0,34,0,41,0,0,5,34,39,81,86,5,33,38,39,80,141,5,37,51,50,55,62,1,53,131,11,130,223,130,227,37,14,1,3,38,39,51,130,202,8,77,1,46,67,42,39,13,34,9,19,2,2,1,101,11,33,89,85,35,11, + 2,102,22,12,17,30,10,10,48,71,21,49,65,93,18,61,19,13,21,17,12,31,25,41,42,18,23,1,228,254,37,80,20,63,57,19,61,191,1,54,254,80,102,73,19,27,20,5,5,27,4,2,247,57,67,23,77,24,0,136, + 135,32,104,130,135,32,40,164,135,37,19,6,7,35,54,55,156,134,37,106,56,59,76,65,33,161,133,37,3,117,61,62,83,40,65,11,12,32,46,165,131,68,77,9,32,23,156,137,32,68,75,247,10,161,143, + 33,2,246,76,2,11,33,0,3,65,163,6,38,101,0,34,0,46,0,58,165,153,67,149,22,156,165,32,134,67,156,12,161,167,33,3,33,67,167,12,32,2,75,239,6,36,102,0,19,0,24,104,173,21,36,19,7,35,54, + 55,104,178,18,36,148,115,76,44,54,104,183,20,37,1,175,124,58,66,0,72,191,6,42,71,2,189,0,8,0,23,0,0,37,50,86,24,5,8,48,21,7,17,51,21,51,50,23,22,21,20,7,6,43,1,21,1,62,158,60,36,75, + 103,102,102,127,192,46,16,63,65,126,127,250,124,75,30,18,247,250,2,189,127,112,38,38,117,47,50,92,247,5,40,94,255,243,2,62,2,219,0,60,68,217,9,66,246,6,34,53,52,55,67,206,6,35,21,17, + 35,17,130,12,130,91,39,23,6,7,6,21,20,31,2,109,115,5,67,194,9,8,110,39,229,75,60,84,26,7,22,8,26,70,84,6,1,90,30,39,4,114,91,20,7,93,119,39,105,39,116,3,116,35,11,24,10,38,22,32,45, + 19,31,30,10,16,55,97,50,41,9,14,23,86,29,52,12,20,32,32,7,25,35,53,55,10,12,89,42,15,8,103,70,23,34,253,236,2,23,151,33,12,13,36,156,9,60,19,18,38,19,10,25,11,22,27,26,45,54,56,35, + 14,10,41,10,2,3,7,0,0,0,3,0,68,130,179,40,48,3,18,0,13,0,66,0,77,130,183,40,20,23,22,50,54,55,54,61,1,98,167,5,33,7,53,102,237,5,32,51,104,105,8,93,181,6,41,30,1,23,35,38,53,38,39, + 6,7,83,210,9,88,104,5,32,39,95,200,6,8,130,160,88,13,52,60,21,44,116,123,29,10,138,97,92,10,12,20,43,18,37,43,92,55,58,16,3,3,12,1,10,3,4,6,4,1,92,18,2,2,15,44,39,61,37,82,49,51,63, + 62,122,123,76,27,32,50,73,28,11,99,9,24,39,52,17,159,84,15,2,26,25,48,89,18,58,20,1,24,50,87,4,3,5,13,4,7,30,31,44,8,8,30,80,115,14,13,22,35,40,26,10,17,14,2,42,19,9,10,30,28,23,12, + 45,39,83,86,47,46,13,92,20,8,143,55,80,31,11,11,30,49,65,22,142,223,32,72,196,223,68,33,5,180,221,37,143,12,150,77,65,76,184,216,38,1,64,12,165,84,93,0,65,183,16,32,78,196,215,43,3, + 7,35,55,51,30,1,23,35,38,39,38,180,221,43,26,90,69,123,73,23,77,23,69,17,28,29,185,227,40,3,116,177,33,111,33,22,36,36,138,231,39,2,250,0,13,0,66,0,103,196,231,36,55,50,53,51,20,88, + 223,5,33,47,1,130,235,32,35,71,102,5,75,93,5,36,23,30,4,23,22,180,253,8,33,40,37,62,56,18,16,26,12,20,19,10,12,7,14,4,5,10,29,6,2,1,62,26,25,46,18,18,23,18,7,20,10,4,6,65,19,56,41, + 223,73,94,30,8,5,8,15,10,9,130,88,49,39,14,19,61,36,35,6,13,16,6,18,7,2,5,0,0,0,4,67,195,5,41,2,217,0,13,0,66,0,78,0,90,65,37,69,69,233,22,65,27,52,35,123,15,71,15,130,2,32,196,93, + 166,5,65,7,56,32,182,93,222,11,135,247,33,3,77,132,247,34,82,0,96,196,247,48,2,14,1,20,30,1,51,50,54,55,54,53,52,46,1,34,23,85,42,6,37,54,51,50,23,22,20,180,253,55,68,22,11,33,26,16, + 32,33,6,5,32,28,32,115,40,59,56,40,41,82,55,58,41,39,65,7,56,8,47,1,55,20,26,45,30,11,31,12,12,15,31,31,10,162,38,38,37,54,55,74,37,35,113,0,0,3,0,20,255,243,2,88,2,27,0,14,0,26,0, + 80,0,0,55,6,7,6,20,86,151,5,41,61,1,35,34,55,51,53,52,38,39,130,214,38,7,6,21,19,50,55,21,130,29,36,35,34,39,38,39,134,7,34,53,52,55,110,97,6,37,35,34,7,6,7,53,131,244,132,248,35,29, + 1,35,21,86,17,5,8,132,176,51,15,8,23,22,32,67,15,10,24,42,149,164,15,4,18,33,33,16,45,108,75,52,51,42,17,23,80,40,14,8,31,58,21,32,90,39,23,112,36,46,60,24,23,49,49,60,8,8,72,63,91, + 34,34,94,89,34,36,246,1,60,23,236,9,36,18,70,21,24,50,33,46,55,67,24,57,38,7,25,7,8,23,107,254,241,48,80,32,5,2,43,13,18,55,15,4,63,37,56,122,34,10,41,56,30,31,30,4,5,79,32,60,60,56, + 54,145,42,17,1,6,10,123,18,9,0,1,0,82,255,71,2,3,130,223,34,56,0,0,90,23,5,103,203,9,32,55,132,170,36,23,21,38,39,38,130,189,32,21,95,10,7,82,168,7,71,203,5,8,94,34,39,53,22,1,53,63, + 14,2,4,11,4,116,66,73,14,25,36,74,125,67,52,19,21,56,57,20,66,34,103,104,34,56,11,70,46,7,8,40,46,5,20,7,44,46,33,26,36,26,40,36,128,43,16,24,4,8,14,6,6,66,73,131,71,36,61,35,73,22, + 8,10,91,47,8,3,14,40,149,150,40,14,1,10,34,6,7,90,25,9,3,1,48,44,51,20,90,130,5,54,0,3,0,62,255,243,2,44,3,18,0,12,0,39,0,50,0,0,19,51,54,59,1,130,152,132,154,65,121,6,34,43,1,34,119, + 116,8,33,22,29,109,161,5,32,3,71,60,6,8,34,162,64,25,22,192,2,8,12,17,35,136,42,43,170,87,108,74,75,12,12,23,129,75,73,111,66,86,110,61,60,254,114,140,19,8,71,41,6,8,45,38,52,17,1, + 53,1,44,20,34,19,39,42,41,254,188,54,86,32,6,2,73,73,129,161,74,42,67,68,119,42,3,150,28,3,2,38,55,80,31,11,11,31,48,65,22,0,130,0,141,155,32,47,169,155,37,19,7,35,62,3,55,161,153, + 39,167,162,77,17,51,39,24,9,159,150,38,215,177,22,65,48,31,11,145,147,32,51,169,147,70,180,11,161,153,32,2,70,161,8,33,29,28,159,157,32,154,70,135,11,32,4,65,207,5,41,2,217,0,12,0, + 39,0,51,0,63,169,161,86,133,23,161,173,38,147,15,71,16,16,71,15,69,53,6,159,175,32,77,69,28,11,50,2,0,109,255,252,2,34,3,6,0,14,0,27,0,0,5,35,34,38,109,250,6,37,23,22,59,1,1,38,73, + 163,7,8,54,2,34,117,81,92,122,214,52,16,22,108,254,237,20,29,30,45,28,10,99,9,24,38,52,17,4,100,91,1,16,67,254,173,86,24,7,2,15,21,33,33,48,31,11,11,31,48,66,21,0,0,0,2,0,134,136,91, + 130,15,142,91,37,3,7,35,62,2,55,138,87,38,50,162,78,27,81,24,9,139,80,35,192,177,34,101,65,247,5,139,75,32,25,145,167,84,8,6,34,39,6,7,138,80,43,254,100,92,31,74,92,31,70,68,22,68, + 22,139,85,40,16,132,44,132,44,86,29,86,29,130,163,32,3,133,163,33,2,217,130,255,34,26,0,38,144,89,85,74,7,85,72,11,131,11,138,102,35,100,15,71,15,130,2,38,195,15,72,14,14,72,15,139, + 104,32,66,70,134,12,34,0,2,0,109,235,5,46,219,0,46,0,65,0,0,1,22,23,14,1,7,22,21,72,98,6,69,82,5,43,22,59,2,50,23,46,2,39,38,39,46,1,130,205,34,39,54,55,85,93,5,32,3,112,248,11,8,123, + 38,43,1,34,7,6,1,211,10,6,23,78,24,190,98,56,86,112,65,62,61,62,123,17,5,2,2,1,2,4,1,8,11,5,7,8,16,11,5,15,124,15,79,40,17,58,16,109,36,28,157,37,37,68,67,39,37,55,7,9,25,13,23,113, + 30,10,2,196,30,16,7,24,7,190,186,151,72,38,69,72,123,127,67,70,1,1,2,9,13,7,10,9,17,12,5,5,38,46,25,12,18,58,18,39,28,254,99,92,49,51,51,51,89,113,68,4,2,6,109,36,0,0,0,2,110,239,6, + 39,225,0,18,0,53,0,0,19,110,229,5,32,17,110,248,10,73,53,10,32,39,131,200,32,35,130,170,32,7,73,51,6,80,132,5,8,88,189,51,115,170,92,110,97,28,9,92,83,7,186,38,62,26,25,45,43,38,4, + 9,11,8,4,3,7,8,17,10,7,2,63,27,25,45,34,36,7,3,19,16,3,5,1,191,92,212,254,185,1,71,137,95,30,41,254,214,2,14,49,188,72,65,33,35,38,3,9,10,5,3,2,3,18,11,44,63,35,35,28,7,4,18,9,3,3, + 0,3,65,95,5,43,3,18,0,13,0,27,0,40,0,0,1,34,114,203,7,36,53,52,39,38,3,69,68,10,37,16,6,3,46,1,39,130,2,8,69,51,30,3,23,1,52,142,80,27,35,106,27,10,81,26,36,175,49,15,136,45,58,117, + 61,62,122,124,20,60,28,16,28,11,100,9,24,38,52,17,1,210,203,150,41,13,116,38,50,151,39,13,254,33,158,51,67,202,56,18,71,72,254,243,140,2,110,22,65,32,16,69,52,9,141,131,32,33,157,131, + 76,32,5,149,126,37,51,23,140,76,82,58,152,119,38,3,31,23,154,106,71,0,142,243,32,38,157,111,69,3,8,33,46,1,149,116,42,118,90,70,123,74,23,77,23,70,17,56,152,121,33,2,226,68,239,5,32, + 72,135,123,39,2,225,0,13,0,27,0,62,158,123,75,76,9,66,22,22,149,146,32,53,66,32,31,65,153,24,32,166,66,41,25,34,0,0,4,66,43,5,33,2,217,132,187,34,39,0,51,157,189,69,155,23,149,179, + 32,31,80,199,12,65,73,25,32,149,68,31,13,49,3,0,44,0,71,2,60,2,22,0,11,0,15,0,27,0,0,37,75,90,10,36,37,53,33,21,39,138,15,44,1,114,16,92,15,15,92,16,254,186,2,16,202,133,10,41,85,14, + 14,87,13,13,90,80,80,170,130,8,49,15,15,0,3,0,24,255,211,2,75,2,57,0,10,0,20,0,47,130,225,36,6,7,22,23,22,98,170,6,114,7,6,37,54,3,6,7,38,39,106,2,5,38,51,50,23,54,55,22,23,68,147, + 5,8,102,43,1,38,1,182,40,191,21,35,25,55,27,81,42,36,65,103,31,10,14,187,215,50,30,44,2,85,40,136,44,58,101,59,29,45,21,25,82,43,137,45,59,26,87,1,111,46,218,25,12,7,13,41,148,67,94, + 44,111,34,31,74,56,212,254,182,55,32,34,2,94,67,111,202,56,18,52,33,49,18,17,93,63,115,204,55,17,7,0,0,0,2,0,97,255,243,2,13,3,5,0,24,0,34,130,229,74,83,7,83,241,8,33,54,53,130,10, + 38,35,38,3,46,2,39,51,130,176,8,60,23,1,177,35,78,24,36,119,33,11,92,27,29,54,97,28,9,92,83,2,138,28,96,28,11,100,13,29,70,28,79,67,19,6,119,40,54,1,69,254,187,74,31,34,96,31,40,1, + 41,253,243,23,2,61,29,106,31,11,17,36,90,130,96,139,111,32,30,154,111,67,142,6,145,108,37,37,20,143,76,41,99,150,104,36,238,21,156,55,122,140,211,32,35,154,99,32,1,79,57,7,33,6,7,146, + 213,33,254,220,67,126,5,35,67,23,67,23,150,110,36,61,177,33,111,33,70,188,5,32,3,65,71,5,39,2,217,0,24,0,36,0,48,154,117,66,190,24,145,235,32,17,66,187,12,150,132,32,113,66,184,12, + 44,2,0,52,255,55,2,65,3,5,0,38,0,44,130,133,44,19,51,14,3,7,14,2,15,1,14,2,7,6,131,1,48,43,1,53,51,50,55,54,55,46,1,39,38,39,51,23,30,1,65,105,6,8,89,59,164,98,55,58,25,21,8,13,14, + 5,2,28,10,17,13,6,18,15,26,12,38,41,60,54,61,27,12,22,35,77,28,73,3,98,50,62,42,173,44,119,76,31,109,115,1,155,132,140,62,49,20,33,32,14,6,72,25,32,26,11,30,10,18,3,12,73,59,23,54, + 85,187,65,174,7,125,152,107,2,119,47,129,42,134,0,0,0,2,0,95,130,143,40,42,2,224,0,10,0,30,0,0,107,185,5,37,23,22,51,50,16,5,99,147,8,34,35,34,39,130,141,8,58,17,35,17,51,1,68,101, + 27,9,77,26,34,134,254,241,48,103,99,60,57,58,60,99,40,20,41,38,11,92,92,1,210,115,38,50,148,43,13,1,151,7,80,74,73,130,131,72,72,8,16,36,20,254,244,3,169,0,0,3,133,243,33,2,204,130, + 243,34,50,0,62,133,245,35,1,7,14,9,130,248,33,7,6,145,240,32,21,67,186,9,32,7,138,11,56,1,59,164,98,55,58,12,16,25,7,5,3,4,2,4,4,7,7,22,47,13,6,40,65,83,65,2,13,32,153,65,148,12,53, + 115,1,155,132,140,31,37,60,17,13,8,7,6,8,12,18,19,61,92,16,7,43,65,10,12,38,47,62,18,14,66,15,15,132,5,43,0,1,0,18,255,243,2,18,2,203,0,65,130,167,32,6,130,247,46,38,39,35,55,54,55, + 51,53,38,61,1,38,52,55,53,130,2,37,35,55,51,54,55,54,111,182,10,48,7,51,6,7,35,21,20,6,29,1,22,21,51,14,1,7,35,104,231,5,48,62,1,55,2,18,65,146,91,32,63,28,87,13,7,5,58,1,130,0,8,86, + 83,25,62,42,130,45,38,104,66,8,8,58,78,108,43,14,6,240,15,9,221,1,1,180,5,15,5,150,10,45,44,73,53,65,8,17,8,25,38,1,33,33,62,139,26,16,10,10,2,5,13,9,11,10,15,1,2,10,50,205,48,17,39, + 97,6,7,47,110,36,48,34,16,9,2,6,4,62,2,3,10,32,10,92,52,50,36,6,102,24,5,35,0,14,0,174,130,193,32,0,132,0,34,1,0,4,134,11,32,1,130,7,32,10,134,11,32,2,130,7,32,16,134,11,36,3,0,29, + 0,78,134,11,131,43,32,112,134,11,36,5,0,9,0,134,134,11,32,6,130,7,44,148,0,3,0,1,4,9,0,0,0,2,0,0,134,11,32,1,130,11,32,6,134,11,32,2,130,11,32,12,134,11,36,3,0,58,0,18,134,11,32,4, + 130,23,32,108,134,11,32,5,130,21,32,114,134,11,32,6,130,23,35,144,0,46,0,143,2,39,70,0,111,0,110,0,116,0,131,7,40,114,0,103,0,101,0,32,0,50,130,36,32,48,130,7,32,58,130,3,32,46,134, + 7,38,50,0,49,0,45,0,56,130,3,34,50,0,48,130,33,51,53,0,0,70,111,110,116,70,111,114,103,101,32,50,46,48,32,58,32,46,130,3,39,50,49,45,56,45,50,48,50,130,30,133,107,32,86,130,81,36,114, + 0,115,0,105,132,103,32,32,130,89,40,0,86,101,114,115,105,111,110,32,136,140,33,2,0,132,0,35,255,156,0,35,130,8,32,1,130,3,141,2,32,195,132,21,32,2,130,201,58,4,0,5,0,6,0,7,0,8,0,9, + 0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,130,235,62,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,130,93,50,36,0,37,0,38,0,39,0,40,0,41,0,42,0,43,0,44, + 0,45,130,145,32,47,130,209,32,49,130,211,9,38,51,0,52,0,53,0,54,0,55,0,56,0,57,0,58,0,59,0,60,0,61,0,62,0,63,0,64,0,65,0,66,0,67,0,68,0,69,0,70,0,71,0,72,0,73,0,74,0,75,0,76,0,77,0, + 78,0,79,0,80,0,81,0,82,0,83,0,84,0,85,0,86,0,87,0,88,0,89,0,90,0,91,0,92,0,93,0,94,0,95,0,96,0,97,0,172,0,163,0,132,0,133,0,189,0,150,0,232,0,134,0,142,0,139,0,157,0,169,0,164,1,2, + 0,138,0,218,0,131,0,147,0,242,0,243,0,141,0,151,0,136,0,195,0,222,0,241,0,158,0,170,0,245,0,244,0,246,0,162,0,173,0,201,0,199,0,174,0,98,0,99,0,144,0,100,0,203,0,101,0,200,0,202,0, + 207,0,204,0,205,0,206,0,233,0,102,0,211,0,208,0,209,0,175,0,103,0,240,0,145,0,214,0,212,0,213,0,104,0,235,0,237,0,137,0,106,0,105,0,107,0,109,0,108,0,110,0,160,0,111,0,113,0,112,0, + 114,0,115,0,117,0,116,0,118,0,119,0,234,0,120,0,122,0,121,0,123,0,125,0,124,0,184,0,161,0,127,0,126,0,128,0,129,0,236,0,238,0,186,1,3,7,117,110,105,48,48,97,100,131,7,45,50,48,97,99, + 0,0,0,1,255,255,0,2,0,1,130,9,32,12,130,3,32,16,130,3,36,2,0,0,0,4,134,7,32,0,132,25,36,0,223,214,203,49,130,17,24,92,127,12,5,250,205,249,72,146, +}; + +static const char* GetDefaultCompressedFontDataProggyVector(int* out_size) +{ + *out_size = proggy_vector_minimal_ttf_compressed_size; + return (const char*)proggy_vector_minimal_ttf_compressed_data; +} + #endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT #endif // #ifndef IMGUI_DISABLE diff --git a/misc/fonts/ProggyVector-ExtractScript.txt b/misc/fonts/ProggyVector-ExtractScript.txt new file mode 100644 index 000000000..697e88bcd --- /dev/null +++ b/misc/fonts/ProggyVector-ExtractScript.txt @@ -0,0 +1,17 @@ +# Usage: fontforge.exe -script ProggyVector-ExtractScript.txt +Open("ProggyVector-Regular.ttf") +SelectMore(0x20,0xFF) +SelectMore(0x20AC) # Euro sign +SelectInvert() +DetachAndRemoveGlyphs() +SelectAll() +RemoveOverlap() +Simplify() +i=0 +while (i < 23) + SetTTFName(0x409,i,"") + i=i+1 +endloop +SetFontNames(".",".",".",".",".",".") +Generate("ProggyVector-minimal.ttf") +# At this point you can use binary_to_compressed_c.exe -u8 ProggyVector-minimal.ttf proggy_vector_minimal_ttf From 05581da18321bee38f6d5915a1466665cdd66fc8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 Dec 2025 17:44:18 +0100 Subject: [PATCH 1586/2359] AddFontDefault() now automatically selects an embedded font between AddFontDefaultVector() and AddFontDefaultBitmap). --- docs/CHANGELOG.txt | 8 +++++++ docs/FAQ.md | 20 +++++++++++------ docs/FONTS.md | 19 ++++++++++++++-- examples/example_allegro5/main.cpp | 14 ++++++------ examples/example_apple_metal/main.mm | 14 ++++++------ examples/example_apple_opengl2/main.mm | 14 ++++++------ examples/example_glfw_metal/main.mm | 14 ++++++------ examples/example_glfw_opengl2/main.cpp | 14 ++++++------ examples/example_glfw_opengl3/main.cpp | 14 ++++++------ examples/example_glfw_vulkan/main.cpp | 14 ++++++------ examples/example_glfw_wgpu/main.cpp | 14 ++++++------ examples/example_glut_opengl2/main.cpp | 15 +++++++------ examples/example_sdl2_directx11/main.cpp | 14 ++++++------ examples/example_sdl2_metal/main.mm | 14 ++++++------ examples/example_sdl2_opengl2/main.cpp | 14 ++++++------ examples/example_sdl2_opengl3/main.cpp | 14 ++++++------ examples/example_sdl2_sdlrenderer2/main.cpp | 14 ++++++------ examples/example_sdl2_vulkan/main.cpp | 14 ++++++------ examples/example_sdl2_wgpu/main.cpp | 14 ++++++------ examples/example_sdl3_directx11/main.cpp | 14 ++++++------ examples/example_sdl3_metal/main.mm | 14 ++++++------ examples/example_sdl3_opengl3/main.cpp | 14 ++++++------ examples/example_sdl3_sdlgpu3/main.cpp | 14 ++++++------ examples/example_sdl3_sdlrenderer3/main.cpp | 15 +++++++------ examples/example_sdl3_vulkan/main.cpp | 14 ++++++------ examples/example_sdl3_wgpu/main.cpp | 14 ++++++------ examples/example_win32_directx10/main.cpp | 14 ++++++------ examples/example_win32_directx11/main.cpp | 14 ++++++------ examples/example_win32_directx12/main.cpp | 14 ++++++------ examples/example_win32_directx9/main.cpp | 14 ++++++------ examples/example_win32_opengl3/main.cpp | 14 ++++++------ examples/example_win32_vulkan/main.cpp | 14 ++++++------ imgui.cpp | 2 ++ imgui.h | 3 ++- imgui_draw.cpp | 24 ++++++++++++++++++--- 35 files changed, 295 insertions(+), 189 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 016bca2d5..154a8d44b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,12 @@ Breaking Changes: that are using the "###" operators. (#713, #1698) - Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name. - Fonts: + - AddFontDefault() now automatically selects an embedded font between: + - AddFontDefaultVector(): new scalable font. Recommended at any higher size. + - AddFontDefaultBitmap(): classic pixel-clean font. Recommended at Size 13px with no scaling. + - The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) + reaching a small threshold. Prefer calling either based on your own logic. + And you can call AddFontDefaultBitmap() to ensure legacy behavior. - Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory (undetected since July 2015 and now spotted @@ -76,6 +82,8 @@ Other Changes: be easily and readily used in all contexts, even without file system access. As always you can opt-out of the embedded font data if desired. A sizing tweak was also applied to ensure the new font is a closer match to the classic font. + - AddFontDefault() now automatically selects an embedded font between + the classic pixel-looking one and the new scalable one. - Fixed an issue related to EllipsisChar handling, while changing font loader or font loader flags dynamically in Style->Fonts menus. - imgui_freetype: fixed overwriting ImFontConfig::PixelSnapH when hinting diff --git a/docs/FAQ.md b/docs/FAQ.md index e72f63f74..282c65c3f 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -658,22 +658,28 @@ Since 1.92 (June 2025) fonts may be dynamically used at any size. **Scaling fonts** +Select default size: +```cpp +style.FontSizeBase = 20.0f; +``` +Scale all fonts: +```cpp +style.FontScaleDpi = 2.0f; +``` + To change font size: ```cpp -ImGui::PushFont(NULL, 42.0f); +ImGui::PushFont(NULL, 42.0f); // This will be multiplied by style.FontScaleDpi ``` To change font and font size: ```cpp ImGui::PushFont(new_font, 42.0f); ``` -To scale all fonts: -```cpp -style.FontScaleDpi = 2.0f; -``` + In `docking` branch or with multi-viewports: ```cpp -io.ConfigDpiScaleFonts = true; // [Experimental] Automatically overwrite style.FontScaleDpi in Begin() when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now. -io.ConfigDpiScaleViewports = true; // [Experimental] Scale Dear ImGui and Platform Windows when Monitor DPI changes. +io.ConfigDpiScaleFonts = true; // Automatically overwrite style.FontScaleDpi in Begin() when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now. +io.ConfigDpiScaleViewports = true; // Scale Dear ImGui and Platform Windows when Monitor DPI changes. ``` **Scaling style** (paddings, spacings, thicknesses) diff --git a/docs/FONTS.md b/docs/FONTS.md index ff2de79cc..8d199c843 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -89,7 +89,10 @@ See [#8465](https://github.com/ocornut/imgui/issues/8465) for more details. ## How should I handle DPI in my application? -See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-should-i-handle-dpi-in-my-application). +Since 1.92, with an updated backend, you can set `style.FontScaleDpi = your_content_scale;` to scale all fonts. +
You can call `style.ScaleAllSizes(xxx)` at init time or every frame at the beginning of your main loop to scale sizes/paddings. +
Since 1.92, with an updated backend, macOS style pixel/backing style scale is automatically handled. +
See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-should-i-handle-dpi-in-my-application) for more details. ##### [Return to Index](#index) @@ -97,10 +100,22 @@ See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-s ## Fonts Loading Instructions +**Select base size** +```cpp +ImGuiStyle& style = ImGui::GetStyle(); +style.FontSizeBase = 20.0f; +``` + **Load default font:** ```cpp ImGuiIO& io = ImGui::GetIO(); -io.Fonts->AddFontDefault(); +io.Fonts->AddFontDefault(); // Load embedded font (auto-selected). +``` +```cpp +io.Fonts->AddFontDefaultVector(); // Load embedded scalable font. +``` +```cpp +io.Fonts->AddFontDefaultBitmap(); // Load embedded bitmap font (legacy). ``` **Load .TTF/.OTF file with:** diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 08b809e35..54674a5d9 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -49,14 +49,16 @@ int main(int, char**) ImGui_ImplAllegro5_Init(display); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 4904973ac..11f54549f 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -69,14 +69,16 @@ ImGui_ImplMetal_Init(_device); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 14f3f4321..aa9b39bad 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -57,14 +57,16 @@ ImGui_ImplOpenGL2_Init(); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index cc86d655c..9627de70e 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -62,14 +62,16 @@ int main(int, char**) ImGui_ImplMetal_Init(device); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 4c19ffcc3..4fa8b0792 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -68,14 +68,16 @@ int main(int, char**) ImGui_ImplOpenGL2_Init(); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 6dfeacb96..af21d9094 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -102,15 +102,17 @@ int main(int, char**) ImGui_ImplOpenGL3_Init(glsl_version); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index ba5a8ad84..ab259a3e5 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -420,14 +420,16 @@ int main(int, char**) ImGui_ImplVulkan_Init(&init_info); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index ad64ef403..60662b031 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -113,15 +113,17 @@ int main(int, char**) ImGui_ImplWGPU_Init(&init_info); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf"); diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 72da416f9..f3b4270f2 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -78,16 +78,17 @@ int main(int argc, char** argv) // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. ImGui_ImplGLUT_InstallFuncs(); - // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index c5a315af4..1018913bc 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -90,14 +90,16 @@ int main(int, char**) ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index 0f60d771d..6dbe190da 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -30,14 +30,16 @@ int main(int, char**) //ImGui::StyleColorsLight(); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index 327780e20..59cd7ed8e 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -79,14 +79,16 @@ int main(int, char**) ImGui_ImplOpenGL2_Init(); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index 4a655ac61..43e5aad0c 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -119,15 +119,17 @@ int main(int, char**) ImGui_ImplOpenGL3_Init(glsl_version); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 214f6f471..9ede2cac8 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -81,14 +81,16 @@ int main(int, char**) ImGui_ImplSDLRenderer2_Init(renderer); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 2d2d906e9..58f4f8e10 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -426,14 +426,16 @@ int main(int, char**) ImGui_ImplVulkan_Init(&init_info); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index d4b9a021b..cddce3e63 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -93,15 +93,17 @@ int main(int, char**) ImGui_ImplWGPU_Init(&init_info); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf"); diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index 7107a0574..06d8ea505 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -81,14 +81,16 @@ int main(int, char**) ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index 1dd80d010..9c9eab54a 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -77,14 +77,16 @@ int main(int, char**) ImGui_ImplSDL3_InitForMetal(window); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 44a6417d1..1b0e100e4 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -109,15 +109,17 @@ int main(int, char**) ImGui_ImplOpenGL3_Init(glsl_version); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index a33c0cfe9..3372d56b0 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -89,14 +89,16 @@ int main(int, char**) ImGui_ImplSDLGPU3_Init(&init_info); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 39870f2c6..e275e5f07 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -71,15 +71,16 @@ int main(int, char**) ImGui_ImplSDLRenderer3_Init(renderer); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index da8d73ee7..fa2296938 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -425,14 +425,16 @@ int main(int, char**) ImGui_ImplVulkan_Init(&init_info); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index d56b703c0..b5ae84bfd 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -101,15 +101,17 @@ int main(int, char**) ImGui_ImplWGPU_Init(&init_info); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 086935099..6a7687537 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -72,14 +72,16 @@ int main(int, char**) ImGui_ImplDX10_Init(g_pd3dDevice); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index fa3c4883e..9ca7705fb 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -72,14 +72,16 @@ int main(int, char**) ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 5430fde26..85c598fb1 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -167,14 +167,16 @@ int main(int, char**) //ImGui_ImplDX12_Init(g_pd3dDevice, APP_NUM_FRAMES_IN_FLIGHT, DXGI_FORMAT_R8G8B8A8_UNORM, g_pd3dSrvDescHeap, g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(), g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart()); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index b330efdeb..2fe01420c 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -70,14 +70,16 @@ int main(int, char**) ImGui_ImplDX9_Init(g_pd3dDevice); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 8d29c41ca..f83d693f9 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -80,14 +80,16 @@ int main(int, char**) ImGui_ImplOpenGL3_Init(); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index c4fe2d500..b70cb9fcc 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -413,14 +413,16 @@ int main(int, char**) ImGui_ImplVulkan_Init(&init_info); // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //style.FontSizeBase = 20.0f; - //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf"); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf"); diff --git a/imgui.cpp b/imgui.cpp index 14dc8afca..c87fa3eb5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -394,6 +394,8 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2025/12/23 (1.92.6) - Fonts:AddFontDefault() now automatically selects an embedded font between the new scalable AddFontDefaultVector() and the classic pixel-clean AddFontDefaultBitmap(). + The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) reaching a small threshold. Prefer calling either based on your own logic. You can call AddFontDefaultBitmap() to ensure legacy behavior. - 2025/12/23 (1.92.6) - Fonts: removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. - 2025/12/17 (1.92.6) - Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name for now. - 2025/12/11 (1.92.6) - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore. diff --git a/imgui.h b/imgui.h index c969d7c1b..c69eb1905 100644 --- a/imgui.h +++ b/imgui.h @@ -3640,8 +3640,9 @@ struct ImFontAtlas IMGUI_API ImFontAtlas(); IMGUI_API ~ImFontAtlas(); IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); - IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); // Embedded classic pixel-clean font. Recommended at Size 13px with no scaling. + 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. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bd9bad5dc..494237d58 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2518,6 +2518,7 @@ void ImTextureData::DestroyPixels() //----------------------------------------------------------------------------- // - ImFontAtlas::AddFont() // - ImFontAtlas::AddFontDefault() +// - ImFontAtlas::AddFontDefaultBitmap() // - ImFontAtlas::AddFontDefaultVector() // - ImFontAtlas::AddFontFromFileTTF() // - ImFontAtlas::AddFontFromMemoryTTF() @@ -3112,9 +3113,26 @@ static const char* GetDefaultCompressedFontDataProggyClean(int* out_size); static const char* GetDefaultCompressedFontDataProggyVector(int* out_size); #endif -// Load embedded ProggyClean.ttf at size 13, disable oversampling -// If you want a similar font which may be better scaled, consider using ProggyVector from the same author! -ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) +// 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. +static float GetExpectedContextFontSize(ImGuiContext* ctx) +{ + return ((ctx->Style.FontSizeBase > 0.0f) ? ctx->Style.FontSizeBase : 13.0f) * ctx->Style.FontScaleMain * ctx->Style.FontScaleDpi; +} + +// Legacy function with heuristic to select Pixel or Vector font. +// The selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold at the time of adding the default font. +// Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. +ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg) +{ + if (OwnerContext == NULL || GetExpectedContextFontSize(OwnerContext) >= 16.0f) + return AddFontDefaultVector(font_cfg); + else + return AddFontDefaultBitmap(font_cfg); +} + +// Load embedded ProggyClean.ttf. Default size 13, disable oversampling. +// If you want a similar font which may be better scaled, consider using AddFontDefaultVector(). +ImFont* ImFontAtlas::AddFontDefaultBitmap(const ImFontConfig* font_cfg_template) { #ifndef IMGUI_DISABLE_DEFAULT_FONT ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); From b7b8f52437588daf55713809397d8740537eb23f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 Dec 2025 17:57:01 +0100 Subject: [PATCH 1587/2359] Examples: Android: update for consistency (untested). --- examples/example_android_opengl3/main.cpp | 43 ++++++++++++++--------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/examples/example_android_opengl3/main.cpp b/examples/example_android_opengl3/main.cpp index 568d6f02b..0de952dbd 100644 --- a/examples/example_android_opengl3/main.cpp +++ b/examples/example_android_opengl3/main.cpp @@ -156,37 +156,46 @@ void Init(struct android_app* app) // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - // - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them. - // We load the default font with increased size to improve readability on many devices with "high" DPI. - // FIXME: Put some effort into DPI awareness. + // Setup scaling + float main_scale = 2.0f; + ImGuiStyle& style = ImGui::GetStyle(); + style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.FontScaleDpi = main_scale; // Set initial font scale. + + // Load Fonts + // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). + // - Read 'docs/FONTS.md' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + // - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them. + //style.FontSizeBase = 20.0f; + //io.Fonts->AddFontDefaultVector(); + //io.Fonts->AddFontDefaultBitmap(); + // Important: when calling AddFontFromMemoryTTF(), ownership of font_data is transferred by Dear ImGui by default (deleted is handled by Dear ImGui), unless we set FontDataOwnedByAtlas=false in ImFontConfig - ImFontConfig font_cfg; - font_cfg.SizePixels = 22.0f; - io.Fonts->AddFontDefault(&font_cfg); - //void* font_data; - //int font_data_size; + //void* font_data; + //int font_data_size; //ImFont* font; //font_data_size = GetAssetData("segoeui.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size); //IM_ASSERT(font != nullptr); //font_data_size = GetAssetData("DroidSans.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size); //IM_ASSERT(font != nullptr); //font_data_size = GetAssetData("Roboto-Medium.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size); //IM_ASSERT(font != nullptr); //font_data_size = GetAssetData("Cousine-Regular.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 15.0f); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size); //IM_ASSERT(font != nullptr); //font_data_size = GetAssetData("ArialUni.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 18.0f); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size); //IM_ASSERT(font != nullptr); - // Arbitrary scale-up - // FIXME: Put some effort into DPI awareness - ImGui::GetStyle().ScaleAllSizes(3.0f); - g_Initialized = true; } From 922a11f0847fe1a7907345c31a22e0e77a43829c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 23 Dec 2025 19:33:37 +0100 Subject: [PATCH 1588/2359] Docs: update links, refs. --- docs/FONTS.md | 19 ++++++++++--------- docs/README.md | 2 +- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index 8d199c843..ab1deb98d 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -2,8 +2,9 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS ## Dear ImGui: Using Fonts -The code in imgui.cpp embeds a copy of [ProggyClean.ttf](http://proggyfonts.net) (by Tristan Grimmer), +The code in Dear ImGui embeds a copy of [ProggyClean.ttf](https://github.com/bluescan/proggyfonts) by Tristan Grimmer, a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions. +The code in Dear ImGui embeds a partial copy of [ProggyVector.ttf](https://github.com/bluescan/proggyfonts) by Tristan Grimmer. You may also load external .TTF/.OTF files. In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience. @@ -572,12 +573,16 @@ Some fonts files are available in the `misc/fonts/` folder: **ProggyClean.ttf**, by Tristan Grimmer
MIT License
(recommended loading setting: Size = 13.0, GlyphOffset.y = +1) -
http://www.proggyfonts.net/ +
https://github.com/bluescan/proggyfonts **ProggyTiny.ttf**, by Tristan Grimmer
MIT License
(recommended loading setting: Size = 10.0, GlyphOffset.y = +1) -
http://www.proggyfonts.net/ +
https://github.com/bluescan/proggyfonts + +**ProggyVector.ttf**, by Tristan Grimmer, Source Foundry Authors +
MIT License +
https://github.com/bluescan/proggyfonts **Karla-Regular.ttf**, by Jonathan Pinhorn
SIL OPEN FONT LICENSE Version 1.1 @@ -605,12 +610,8 @@ Some fonts files are available in the `misc/fonts/` folder: image -Pixel Perfect: -- Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php -- Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font (also include an .inl file to use directly in dear imgui.) - -Regular: -- ProggyVector if you want the old school Dear ImGui font to scale: https://github.com/bluescan/proggyfonts +- Proggy Fonts, by Tristan Grimmer https://github.com/bluescan/proggyfonts +- Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font - Google Noto Mono Fonts: https://www.google.com/get/noto/ - Typefaces for source code beautification: https://github.com/chrissimpkins/codeface - Programmation fonts: http://s9w.github.io/font_compare/ diff --git a/docs/README.md b/docs/README.md index 782a3434f..c1b413629 100644 --- a/docs/README.md +++ b/docs/README.md @@ -217,7 +217,7 @@ Maintenance/support contracts, sponsoring invoices and other B2B transactions ar Omar: "I first discovered the IMGUI paradigm at [Q-Games](https://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it." -Embeds [ProggyClean.ttf](https://www.proggyfonts.net) font by Tristan Grimmer (MIT license). +Embeds [ProggyClean.ttf, ProggyVector.ttf](https://www.proggyfonts.net) fonts by Tristan Grimmer (MIT license).
Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Special thanks to Alex Evans, Patrick Doane, Marco Koegler for kindly helping. Also thank you to everyone posting feedback, questions and patches on GitHub. From 960921f03a2bf628a802b4611af9fc3c3c9430fe Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 3 Jan 2026 01:07:58 +0100 Subject: [PATCH 1589/2359] Happy new year! --- LICENSE.txt | 2 +- imgui.cpp | 2 +- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 00ae473ab..d5ba3155f 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014-2025 Omar Cornut +Copyright (c) 2014-2026 Omar Cornut Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/imgui.cpp b/imgui.cpp index c87fa3eb5..6ba9d0b43 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -27,7 +27,7 @@ // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. // Since 1.92, we encourage font loading questions to also be posted in 'Issues'. -// Copyright (c) 2014-2025 Omar Cornut +// Copyright (c) 2014-2026 Omar Cornut // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // See LICENSE.txt for copyright and licensing details (standard MIT License). // This library is free but needs your support to sustain development and maintenance. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b5d7e0b4e..b01c86940 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8108,7 +8108,7 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::TextLinkOpenURL("Funding", "https://github.com/ocornut/imgui/wiki/Funding"); ImGui::Separator(); - ImGui::Text("(c) 2014-2025 Omar Cornut"); + ImGui::Text("(c) 2014-2026 Omar Cornut"); ImGui::Text("Developed by Omar Cornut and all Dear ImGui contributors."); ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information."); ImGui::Text("If your company uses this, please consider funding the project."); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 494237d58..b839291b0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5732,7 +5732,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 2025-2025. Use ImDrawList::AddText(). +// 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) { // Align to be pixel perfect From 25158fe33bd22871eab47b4a06f951fd6655fad8 Mon Sep 17 00:00:00 2001 From: Sammy Fatnassi Date: Sat, 3 Jan 2026 14:26:29 -0500 Subject: [PATCH 1590/2359] Textures: prevent assert/crash of having a destroyed texture recreated without the pixels data available (#9150, #8811) Amend 8c22b8aef --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index c69eb1905..62fac5151 100644 --- a/imgui.h +++ b/imgui.h @@ -3509,7 +3509,7 @@ struct ImTextureData // - Call SetTexID() and SetStatus() after honoring texture requests. Never modify TexID and Status directly! // - A backend may decide to destroy a texture that we did not request to destroy, which is fine (e.g. freeing resources), but we immediately set the texture back in _WantCreate mode. void SetTexID(ImTextureID tex_id) { TexID = tex_id; } - void SetStatus(ImTextureStatus status) { Status = status; if (status == ImTextureStatus_Destroyed && !WantDestroyNextFrame) Status = ImTextureStatus_WantCreate; } + void SetStatus(ImTextureStatus status) { Status = status; if (status == ImTextureStatus_Destroyed && !WantDestroyNextFrame && Pixels != nullptr) Status = ImTextureStatus_WantCreate; } }; //----------------------------------------------------------------------------- From f106ccd5fa11eeb751ba91cb301d0bcaec3361ef Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Jan 2026 15:58:08 +0100 Subject: [PATCH 1591/2359] Backends: Vulkan: clarify ImGui_ImplVulkanH_Window members. --- backends/imgui_impl_vulkan.h | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index fde5bed20..550834ab3 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -223,21 +223,24 @@ struct ImGui_ImplVulkanH_FrameSemaphores // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) struct ImGui_ImplVulkanH_Window { - int Width; - int Height; - VkSwapchainKHR Swapchain; - VkSurfaceKHR Surface; - VkSurfaceFormatKHR SurfaceFormat; - VkPresentModeKHR PresentMode; - VkRenderPass RenderPass; - VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo - bool UseDynamicRendering; - bool ClearEnable; - VkClearValue ClearValue; - uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) - uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) - uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR - uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) + // Input + VkSurfaceFormatKHR SurfaceFormat; + VkPresentModeKHR PresentMode; + bool UseDynamicRendering; + bool ClearEnable; + VkClearValue ClearValue; + + // Internal + int Width; // Generally same as passed to ImGui_ImplVulkanH_CreateOrResizeWindow() + int Height; + VkSwapchainKHR Swapchain; + VkSurfaceKHR Surface; + VkRenderPass RenderPass; + VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo + uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) + uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) + uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR + uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) ImVector Frames; ImVector FrameSemaphores; From 1dc1964d5b24652a64eef270985cb77f4730c4cb Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Jan 2026 16:26:59 +0100 Subject: [PATCH 1592/2359] Backends: Vulkan: change ImGui_ImplVulkanH_Window::ClearEnable to fuller featured AttachmentDesc. (#9152) --- backends/imgui_impl_vulkan.cpp | 13 ++++--------- backends/imgui_impl_vulkan.h | 21 ++++++++++++++++----- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 242fa53b3..2386f0bdf 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-01-05: Vulkan: Helper for creating render pass uses ImGui_ImplVulkanH_Window::AttachmentDesc to create render pass. Removed ClearEnabled. (#9152) // 2025-11-24: Vulkan: Helper for creating a swap-chain (used by examples and multi-viewports) selects VkSwapchainCreateInfoKHR's compositeAlpha based on cap.supportedCompositeAlpha. (#8784) // 2025-10-15: Vulkan: Added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to volk.h header. (#9008) // 2025-09-26: *BREAKING CHANGE*: moved some fields in ImGui_ImplVulkan_InitInfo: init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass, init_info.Subpass --> init_info.PipelineInfoMain.Subpass, init_info.MSAASamples --> init_info.PipelineInfoMain.MSAASamples, init_info.PipelineRenderingCreateInfo --> init_info.PipelineInfoMain.PipelineRenderingCreateInfo. @@ -1685,15 +1686,9 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V // Create the Render Pass if (wd->UseDynamicRendering == false) { - VkAttachmentDescription attachment = {}; - attachment.format = wd->SurfaceFormat.format; - attachment.samples = VK_SAMPLE_COUNT_1_BIT; - attachment.loadOp = wd->ClearEnable ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + VkAttachmentDescription attachment = wd->AttachmentDesc; + if (attachment.format == VK_FORMAT_UNDEFINED) + attachment.format = wd->SurfaceFormat.format; VkAttachmentReference color_attachment = {}; color_attachment.attachment = 0; color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 550834ab3..c6cd72cfd 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -224,11 +224,11 @@ struct ImGui_ImplVulkanH_FrameSemaphores struct ImGui_ImplVulkanH_Window { // Input + bool UseDynamicRendering; VkSurfaceFormatKHR SurfaceFormat; VkPresentModeKHR PresentMode; - bool UseDynamicRendering; - bool ClearEnable; - VkClearValue ClearValue; + VkAttachmentDescription AttachmentDesc; // RenderPass creation: main attachment description. + VkClearValue ClearValue; // RenderPass creation: clear value when using VK_ATTACHMENT_LOAD_OP_CLEAR. // Internal int Width; // Generally same as passed to ImGui_ImplVulkanH_CreateOrResizeWindow() @@ -247,8 +247,19 @@ struct ImGui_ImplVulkanH_Window ImGui_ImplVulkanH_Window() { memset((void*)this, 0, sizeof(*this)); - PresentMode = (VkPresentModeKHR)~0; // Ensure we get an error if user doesn't set this. - ClearEnable = true; + + // Parameters to create SwapChain + PresentMode = (VkPresentModeKHR)~0; // Ensure we get an error if user doesn't set this. + + // Parameters to create RenderPass + AttachmentDesc.format = VK_FORMAT_UNDEFINED; // Will automatically use wd->SurfaceFormat.format. + AttachmentDesc.samples = VK_SAMPLE_COUNT_1_BIT; + AttachmentDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + AttachmentDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + AttachmentDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + AttachmentDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + AttachmentDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + AttachmentDesc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; } }; From 69a501df6e6887a074b3c17a1c1bdd40a4c06dee Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Jan 2026 16:46:56 +0100 Subject: [PATCH 1593/2359] Backends: OpenGL3: call ImGui_ImplOpenGL3_InitLoader() in ImGui_ImplOpenGL3_CreateDeviceObjects() / ImGui_ImplOpenGL3_DestroyDeviceObjects(). (#9112) --- backends/imgui_impl_opengl3.cpp | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 3ead5fec6..133b0ed27 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -291,7 +291,8 @@ struct ImGui_ImplOpenGL3_VtxAttribState bool ImGui_ImplOpenGL3_InitLoader(); bool ImGui_ImplOpenGL3_InitLoader() { - // Initialize our loader + // Lazily initialize our loader if not already done + // (to facilitate handling multiple DLL boundaries and multiple context shutdowns we call this from all main entry points) #ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W if (glGetIntegerv == nullptr && imgl3wInit() != 0) { @@ -302,6 +303,13 @@ bool ImGui_ImplOpenGL3_InitLoader() return true; } +static void ImGui_ImplOpenGL3_ShutdownLoader() +{ +#ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W + imgl3wShutdown(); +#endif +} + // Functions bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { @@ -433,9 +441,7 @@ void ImGui_ImplOpenGL3_Shutdown() platform_io.ClearRendererHandlers(); IM_DELETE(bd); -#ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W - imgl3wShutdown(); -#endif + ImGui_ImplOpenGL3_ShutdownLoader(); } void ImGui_ImplOpenGL3_NewFrame() @@ -443,8 +449,7 @@ void ImGui_ImplOpenGL3_NewFrame() ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL3_Init()?"); - ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries. - + ImGui_ImplOpenGL3_InitLoader(); if (!bd->ShaderHandle) if (!ImGui_ImplOpenGL3_CreateDeviceObjects()) IM_ASSERT(0 && "ImGui_ImplOpenGL3_CreateDeviceObjects() failed!"); @@ -535,7 +540,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (fb_width <= 0 || fb_height <= 0) return; - ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries. + ImGui_ImplOpenGL3_InitLoader(); ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); @@ -838,6 +843,7 @@ static bool CheckProgram(GLuint handle, const char* desc) bool ImGui_ImplOpenGL3_CreateDeviceObjects() { + ImGui_ImplOpenGL3_InitLoader(); ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); // Backup GL state @@ -1036,6 +1042,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() void ImGui_ImplOpenGL3_DestroyDeviceObjects() { + ImGui_ImplOpenGL3_InitLoader(); ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; } if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; } From b467a0466c56936ba86a3369eb5603221fc95bc5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 6 Jan 2026 19:07:46 +0100 Subject: [PATCH 1594/2359] Docs: amends comments about fonts. --- docs/FONTS.md | 14 ++++++++++---- imconfig.h | 2 +- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index ab1deb98d..a3eb57d95 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -3,10 +3,16 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS ## Dear ImGui: Using Fonts The code in Dear ImGui embeds a copy of [ProggyClean.ttf](https://github.com/bluescan/proggyfonts) by Tristan Grimmer, -a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions. -The code in Dear ImGui embeds a partial copy of [ProggyVector.ttf](https://github.com/bluescan/proggyfonts) by Tristan Grimmer. +a 13 pixels high, pixel-perfect font used by default. ProggyClean does not scale very nicely. -You may also load external .TTF/.OTF files. +The code in Dear ImGui embeds a partial copy of [ProggyVector.ttf](https://github.com/bluescan/proggyfonts) by Tristan Grimmer and Source Foundry Authors, +a font mimicking ProggyClean which does scale nicely. + +We embed fonts in the code so you can use Dear ImGui without any file system access. +If you use either of those fonts in your shipping product you should include their license as part of your software (see below for links). +If you don't use them you can set `IMGUI_DISABLE_DEFAULT_FONT` in your [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) file to ship binaries without the fonts and save about ~26 KB. + +You may also load external .TTF/.OTF files, see instructions on this page. In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience. **Also read the FAQ:** https://www.dearimgui.com/faq (there is a Fonts section!) @@ -581,7 +587,7 @@ Some fonts files are available in the `misc/fonts/` folder:
https://github.com/bluescan/proggyfonts **ProggyVector.ttf**, by Tristan Grimmer, Source Foundry Authors -
MIT License +
MIT License + Bitstream Vera License
https://github.com/bluescan/proggyfonts **Karla-Regular.ttf**, by Jonathan Pinhorn diff --git a/imconfig.h b/imconfig.h index c6d9b8d5f..322e5b89d 100644 --- a/imconfig.h +++ b/imconfig.h @@ -49,7 +49,7 @@ //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). -//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded font (ProggyClean.ttf), remove ~9.5 KB from output binary. AddFontDefault() will assert. +//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded fonts (ProggyClean/ProggyVector), remove ~9 KB + ~17 KB from output binary. AddFontDefaultXXX() functions will assert. //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available //---- Enable Test Engine / Automation features. From 4ce188def8af61acce1aef5c2bca0481888326b8 Mon Sep 17 00:00:00 2001 From: JD31 Date: Wed, 7 Jan 2026 16:37:59 +0100 Subject: [PATCH 1595/2359] Backends: WebGPU: clarify build failure when attempting to build with Dawn for iOS. (#9155, #9156) --- backends/imgui_impl_wgpu.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 47c31726b..c8722cd4a 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -1020,15 +1020,18 @@ void ImGui_ImplWGPU_DebugPrintAdapterInfo(const WGPUAdapter& adapter) #if defined(__APPLE__) // MacOS specific: is necessary to compile with "-x objective-c++" flags // (e.g. using cmake: set_source_files_properties(${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") ) +#include +#if TARGET_OS_OSX #include #include #endif +#endif WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceInfo* info) { WGPUSurfaceDescriptor surface_descriptor = {}; WGPUSurface surface = {}; -#if defined(__APPLE__) +#if defined(__APPLE__) && TARGET_OS_OSX if (strcmp(info->System, "cocoa") == 0) { IM_ASSERT(info->RawWindow != nullptr); @@ -1075,7 +1078,7 @@ WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceI surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor); } #else -#error "Unsupported WebGPU native platform!" + fprintf(stderr, "'CreateWGPUSurfaceHelper' is not implemented for this platform\n"); #endif return surface; } From 7b3ad4a282dc6f5007c49d35853e32f364e3e3d7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 Jan 2026 18:15:15 +0100 Subject: [PATCH 1596/2359] (Breaking) Popups: changed 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). (#9157, #9146) --- docs/CHANGELOG.txt | 27 +++++++++++++++++++++++++++ imgui.cpp | 39 +++++++++++++++++++++++++++++++++++---- imgui.h | 39 +++++++++++++++++++-------------------- imgui_internal.h | 1 + 4 files changed, 82 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 154a8d44b..2cb0d5d94 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,33 @@ Breaking Changes: the issue altogether. - Removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. + - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for + BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). + The default value has same meaning before and after. (#9157, #9146) + - Before this version, those functions had a 'ImGuiPopupFlags popup_flags = 1' default + value in their function signature. This was introduced by a change on 2020/06/23 (1.77) + while changing the signature from 'int mouse_button' to 'ImGuiPopupFlags popup_flags' + and trying to preserve then-legacy behavior. + - We have now changed this behavior to: cleanup a very old API quirk, facilitate use by + bindings, and to remove the last and error-prone non-zero default value. Also because we + deemed it extremely rare to use those helper functions with the Left mouse button! + As using the LMB would generally be triggered via another widget, e.g. a Button() + + a OpenPopup()/BeginPopup() call. + - Before: The default = 1 means ImGuiPopupFlags_MouseButtonRight. + Explicitly passing a literal 0 means ImGuiPopupFlags_MouseButtonLeft. + - 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. + Recap: + - BeginPopupContextItem("foo"); // Behavior unchanged (use Right button) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft); // Behavior unchanged (use Left button) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft | xxx); // Behavior unchanged (use Left button + flags) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonRight | xxx); // Behavior unchanged (use Right button + flags) + - BeginPopupContextItem("foo", 1); // Behavior unchanged (as a courtesy we legacy interpret 1 as ImGuiPopupFlags_MouseButtonRight, will assert if disabling legacy behaviors. + - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft. + - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx. Other Changes: diff --git a/imgui.cpp b/imgui.cpp index 6ba9d0b43..da9a7019b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -394,6 +394,24 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2026/01/07 (1.92.6) - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). Default value has same meaning before and after. + - Refer to GitHub topic #9157 if you have any question. + - Before this version, those functions had a 'ImGuiPopupFlags popup_flags = 1' default value in their function signature. + Explicitly passing a literal 0 meant ImGuiPopupFlags_MouseButtonLeft. The default literal 1 meant ImGuiPopupFlags_MouseButtonRight. + This was introduced by a change on 2020/06/23 (1.77) while changing the signature from 'int mouse_button' to 'ImGuiPopupFlags popup_flags' and trying to preserve then-legacy behavior. + We have now changed this behavior to cleanup a very old API quirk, facilitate use by bindings, and to remove the last and error-prone non-zero default value. + Also because we deemed it extremely rare to use those helper functions with the Left mouse button! As using the LMB would generally be triggered via another widget, e.g. a Button() + a OpenPopup()/BeginPopup() call. + - Before: The default = 1 means ImGuiPopupFlags_MouseButtonRight. Explicitly passing a literal 0 means ImGuiPopupFlags_MouseButtonLeft. + - 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. + Recap: + - BeginPopupContextItem("foo"); // Behavior unchanged (use Right button) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft); // Behavior unchanged (use Left button) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft | xxx); // Behavior unchanged (use Left button + flags) + - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonRight | xxx); // Behavior unchanged (use Right button + flags) + - BeginPopupContextItem("foo", 1); // Behavior unchanged (as a courtesy we legacy interpret 1 as ImGuiPopupFlags_MouseButtonRight, will assert if disabling legacy behaviors. + - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft. + - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx. - 2025/12/23 (1.92.6) - Fonts:AddFontDefault() now automatically selects an embedded font between the new scalable AddFontDefaultVector() and the classic pixel-clean AddFontDefaultBitmap(). The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) reaching a small threshold. Prefer calling either based on your own logic. You can call AddFontDefaultBitmap() to ensure legacy behavior. - 2025/12/23 (1.92.6) - Fonts: removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. @@ -12454,13 +12472,26 @@ void ImGui::EndPopup() g.WithinEndChildID = backup_within_end_child_id; } +ImGuiMouseButton ImGui::GetMouseButtonFromPopupFlags(ImGuiPopupFlags flags) +{ +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if ((flags & ImGuiPopupFlags_InvalidMask_) != 0) // 1,2 --> ImGuiMouseButton_Right, ImGuiMouseButton_Middle + return (flags & ImGuiPopupFlags_InvalidMask_); +#else + IM_ASSERT((flags & ImGuiPopupFlags_InvalidMask_) == 0); +#endif + if (flags & ImGuiPopupFlags_MouseButtonMask_) + return ((flags & ImGuiPopupFlags_MouseButtonMask_) >> ImGuiPopupFlags_MouseButtonShift_) - 1; + return ImGuiMouseButton_Right; // Default == 1 +} + // 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() void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! @@ -12493,7 +12524,7 @@ bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flag return false; ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) - int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); @@ -12506,7 +12537,7 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_fl if (!str_id) str_id = "window_context"; ImGuiID id = window->GetID(str_id); - int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered()) OpenPopupEx(id, popup_flags); @@ -12520,7 +12551,7 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flag if (!str_id) str_id = "void_context"; ImGuiID id = window->GetID(str_id); - int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + ImGuiMouseButton mouse_button = GetMouseButtonFromPopupFlags(popup_flags); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) if (GetTopMostPopupModal() == NULL) OpenPopupEx(id, popup_flags); diff --git a/imgui.h b/imgui.h index 62fac5151..2df755416 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19258 +#define IMGUI_VERSION_NUM 19259 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -853,20 +853,23 @@ 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. - // - IMPORTANT: Notice that for OpenPopupOnItemClick() we exceptionally default flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). IMGUI_API void OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags = 0); // id overload to facilitate calling from nested stacks - IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // 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 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 void CloseCurrentPopup(); // manually close the popup we have begin-ed into. - // Popups: open+begin combined functions helpers + // Popups: Open+Begin popup combined functions helpers to create context menus. // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. - // - They are convenient to easily create context menus, hence the name. // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. - // - IMPORTANT: Notice that we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight. - IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // 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 = 1);// open+begin popup when clicked on current window. - IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows). + // - IMPORTANT: If you ever used the left mouse button with BeginPopupContextXXX() helpers before 1.92.6: + // - Before this version, OpenPopupOnItemClick(), BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid() had 'a ImGuiPopupFlags popup_flags = 1' default value in their function signature. + // - Before: Explicitly passing a literal 0 meant ImGuiPopupFlags_MouseButtonLeft. The default = 1 meant ImGuiPopupFlags_MouseButtonRight. + // - 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). // Popups: query functions // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. @@ -1322,21 +1325,14 @@ enum ImGuiTreeNodeFlags_ }; // Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. -// - To be backward compatible with older API which took an 'int mouse_button = 1' argument instead of 'ImGuiPopupFlags flags', -// we need to treat small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. -// It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. -// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. -// IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter -// and want to use another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag explicitly. +// - IMPORTANT: If you ever used the left mouse button with BeginPopupContextXXX() helpers before 1.92.6: Read "API BREAKING CHANGES" 2026/01/07 (1.92.6) entry in imgui.cpp or GitHub topic #9157. // - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). enum ImGuiPopupFlags_ { ImGuiPopupFlags_None = 0, - ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left) - ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right) - ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle) - ImGuiPopupFlags_MouseButtonMask_ = 0x1F, - ImGuiPopupFlags_MouseButtonDefault_ = 1, + ImGuiPopupFlags_MouseButtonLeft = 1 << 2, // For BeginPopupContext*(): open on Left Mouse release. Only one button allowed! + ImGuiPopupFlags_MouseButtonRight = 2 << 2, // For BeginPopupContext*(): open on Right Mouse release. Only one button allowed! (default) + ImGuiPopupFlags_MouseButtonMiddle = 3 << 2, // For BeginPopupContext*(): open on Middle Mouse release. Only one button allowed! ImGuiPopupFlags_NoReopen = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) //ImGuiPopupFlags_NoReopenAlwaysNavInit = 1 << 6, // For OpenPopup*(), BeginPopupContext*(): focus and initialize navigation even when not reopening. ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 7, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack @@ -1344,6 +1340,9 @@ enum ImGuiPopupFlags_ ImGuiPopupFlags_AnyPopupId = 1 << 10, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. ImGuiPopupFlags_AnyPopupLevel = 1 << 11, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel, + ImGuiPopupFlags_MouseButtonShift_ = 2, // [Internal] + ImGuiPopupFlags_MouseButtonMask_ = 0x0C, // [Internal] + ImGuiPopupFlags_InvalidMask_ = 0x03, // [Internal] Reserve legacy bits 0-1 to detect incorrectly passing 1 or 2 to the function. }; // Flags for ImGui::Selectable() diff --git a/imgui_internal.h b/imgui_internal.h index 0a37c16e2..86606f39f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3314,6 +3314,7 @@ namespace ImGui IMGUI_API ImGuiWindow* FindBlockingModal(ImGuiWindow* window); IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy); + IMGUI_API ImGuiMouseButton GetMouseButtonFromPopupFlags(ImGuiPopupFlags flags); // Tooltips IMGUI_API bool BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags); From 43a90adc618207da0e9ef6274f1b172c76f220ae Mon Sep 17 00:00:00 2001 From: maf Date: Thu, 8 Jan 2026 16:17:44 +0800 Subject: [PATCH 1597/2359] Docs: Fix spelling errors (#9158) --- imgui.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 2df755416..8d6b63719 100644 --- a/imgui.h +++ b/imgui.h @@ -1539,7 +1539,7 @@ enum ImGuiSortDirection : ImU8 // All our named keys are >= 512. Keys value 0 to 511 are left unused and were legacy native/opaque key values (< 1.87). // Support for legacy keys was completely removed in 1.91.5. // Read details about the 1.87+ transition : https://github.com/ocornut/imgui/issues/4921 -// Note that "Keys" related to physical keys and are not the same concept as input "Characters", the later are submitted via io.AddInputCharacter(). +// Note that "Keys" related to physical keys and are not the same concept as input "Characters", the latter are submitted via io.AddInputCharacter(). // The keyboard key enum values are named after the keys on a standard US keyboard, and on other keyboard types the keys reported may not match the keycaps. enum ImGuiKey : int { @@ -2438,7 +2438,7 @@ struct ImGuiIO // Options to configure Error Handling and how we handle recoverable errors [EXPERIMENTAL] // - Error recovery is provided as a way to facilitate: - // - Recovery after a programming error (native code or scripting language - the later tends to facilitate iterating on code while running). + // - Recovery after a programming error (native code or scripting language - the latter tends to facilitate iterating on code while running). // - Recovery after running an exception handler or any error processing which may skip code after an error has been detected. // - Error recovery is not perfect nor guaranteed! It is a feature to ease development. // You not are not supposed to rely on it in the course of a normal application run. From 9ce41a92c34ec0170247dfd09c0c48ae92e19109 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jan 2026 14:31:25 +0100 Subject: [PATCH 1598/2359] Misc/shallow merges from docking branch to reduce small drift. --- backends/imgui_impl_glfw.cpp | 6 +++--- backends/imgui_impl_glfw.h | 4 ++-- backends/imgui_impl_metal.mm | 2 +- backends/imgui_impl_osx.mm | 12 +++++++----- backends/imgui_impl_sdl2.cpp | 6 +++--- backends/imgui_impl_sdl3.cpp | 10 +++------- backends/imgui_impl_vulkan.cpp | 2 +- backends/imgui_impl_vulkan.h | 1 - backends/imgui_impl_win32.cpp | 6 +++--- examples/example_glfw_opengl2/Makefile | 3 ++- imgui_widgets.cpp | 2 +- 11 files changed, 26 insertions(+), 28 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 35b167b28..82c512fee 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -11,8 +11,8 @@ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors) with GLFW 3.1+. Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Multiple Dear ImGui contexts support. // Missing features or Issues: -// [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. -// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. +// [ ] Platform: Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. +// [ ] Platform: Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -156,13 +156,13 @@ // We gather version tests as define in order to easily see which features are version-dependent. #define GLFW_VERSION_COMBINED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION) +#define GLFW_HAS_CREATECURSOR (GLFW_VERSION_COMBINED >= 3100) // 3.1+ glfwCreateCursor() #define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetMonitorContentScale #ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released? #define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR #else #define GLFW_HAS_NEW_CURSORS (0) #endif -#define GLFW_HAS_CREATECURSOR (GLFW_VERSION_COMBINED >= 3100) // 3.1+ glfwCreateCursor() #define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName() #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError() diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index 98fae51c7..c01600d0c 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -11,8 +11,8 @@ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors) with GLFW 3.1+. Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Multiple Dear ImGui contexts support. // Missing features or Issues: -// [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. -// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. +// [ ] Platform: Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. +// [ ] Platform: Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 2746efa95..96695d9b7 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -19,7 +19,7 @@ // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplMetal_CreateFontsTexture() and ImGui_ImplMetal_DestroyFontsTexture(). // 2025-02-03: Metal: Crash fix. (#8367) -// 2024-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419). +// 2025-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419). // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. // 2022-07-05: Metal: Add dispatch synchronization. // 2022-06-30: Metal: Use __bridge for ARC based systems. diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index 189dd53e6..0dfdd8e90 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -148,9 +148,11 @@ static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view); NSWindow* window = view.window; if (!window) return; - NSRect contentRect = [window contentRectForFrameRect:window.frame]; - NSRect rect = NSMakeRect(_posX, contentRect.size.height - _posY, 0, 0); - _imeRect = [window convertRectToScreen:rect]; + { + NSRect contentRect = [window contentRectForFrameRect:window.frame]; + NSRect rect = NSMakeRect(_posX, contentRect.size.height - _posY, 0, 0); + _imeRect = [window convertRectToScreen:rect]; + } } - (void)viewDidMoveToWindow @@ -629,9 +631,9 @@ void ImGui_ImplOSX_NewFrame(NSView* view) // Setup display size if (view) { - const float dpi = (float)[view.window backingScaleFactor]; + const float fb_scale = (float)[view.window backingScaleFactor]; io.DisplaySize = ImVec2((float)view.bounds.size.width, (float)view.bounds.size.height); - io.DisplayFramebufferScale = ImVec2(dpi, dpi); + io.DisplayFramebufferScale = ImVec2(fb_scale, fb_scale); } // Setup time step diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index c2dae4053..371b1dac4 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -140,7 +140,7 @@ struct ImGui_ImplSDL2_Data { SDL_Window* Window; - Uint32 WindowID; + Uint32 WindowID; // Stored in ImGuiViewport::PlatformHandle. Use SDL_GetWindowFromID() to get SDL_Window* from Uint32 WindowID. SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; @@ -368,7 +368,6 @@ static ImGuiViewport* ImGui_ImplSDL2_GetViewportForWindowID(Uint32 window_id) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. -// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); @@ -462,7 +461,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1; if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED) io.AddFocusEvent(true); - else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST) + if (window_event == SDL_WINDOWEVENT_FOCUS_LOST) io.AddFocusEvent(false); return true; } @@ -487,6 +486,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); + //SDL_SetHint(SDL_HINT_EVENT_LOGGING, "2"); // Obtain compiled and runtime versions SDL_version ver_compiled; diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index 815929595..ffd9f8a59 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -372,7 +372,6 @@ static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. -// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); @@ -495,6 +494,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_UNUSED(sdl_gl_context); // Unused in this branch + //SDL_SetHint(SDL_HINT_EVENT_LOGGING, "2"); const int ver_linked = SDL_GetVersion(); @@ -555,22 +555,18 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application. // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click: - // you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED) -#ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH + // you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_EVENT_WINDOW_FOCUS_GAINED) SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); -#endif // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710) -#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); -#endif return true; } +// Should technically be a SDL_GLContext but due to typedef it is sane to keep it void* in public interface. bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) { - IM_UNUSED(sdl_gl_context); // Viewport branch will need this. return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context); } diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 2386f0bdf..f0ca7907a 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -261,7 +261,7 @@ struct ImGui_ImplVulkan_Data VkPipelineCreateFlags PipelineCreateFlags; VkDescriptorSetLayout DescriptorSetLayout; VkPipelineLayout PipelineLayout; - VkPipeline Pipeline; + VkPipeline Pipeline; // pipeline for main render pass (created by app) VkShaderModule ShaderModuleVert; VkShaderModule ShaderModuleFrag; VkDescriptorPool DescriptorPool; diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index c6cd72cfd..83376e597 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -77,7 +77,6 @@ // Specify settings to create pipeline and swapchain struct ImGui_ImplVulkan_PipelineInfo { - // For Main and Secondary viewports VkRenderPass RenderPass; // Ignored if using dynamic rendering uint32_t Subpass; // VkSampleCountFlagBits MSAASamples = {}; // 0 defaults to VK_SAMPLE_COUNT_1_BIT diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index c3b7ca9cc..de3c6fbd6 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -181,7 +181,7 @@ static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) bd->LastMouseCursor = ImGuiMouseCursor_COUNT; ImGui_ImplWin32_UpdateKeyboardCodePage(io); - // Set platform dependent data in viewport + // Our mouse update function expect PlatformHandle to be filled for the main viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)bd->hWnd; IM_UNUSED(platform_has_own_dc); // Used in 'docking' branch @@ -650,8 +650,8 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPA bd->MouseTrackedArea = area; } POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) }; - if (msg == WM_NCMOUSEMOVE && ::ScreenToClient(hwnd, &mouse_pos) == FALSE) // WM_NCMOUSEMOVE are provided in absolute coordinates. - return 0; + if (msg == WM_NCMOUSEMOVE) // WM_NCMOUSEMOVE are absolute coordinates. + ::ScreenToClient(hwnd, &mouse_pos); io.AddMouseSourceEvent(mouse_source); io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); return 0; diff --git a/examples/example_glfw_opengl2/Makefile b/examples/example_glfw_opengl2/Makefile index 1f15c15c0..a8a0128dc 100644 --- a/examples/example_glfw_opengl2/Makefile +++ b/examples/example_glfw_opengl2/Makefile @@ -21,6 +21,7 @@ SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) +LINUX_GL_LIBS = -lGL CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat @@ -32,7 +33,7 @@ LIBS = ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" - LIBS += -lGL `pkg-config --static --libs glfw3` + LIBS += $(LINUX_GL_LIBS) `pkg-config --static --libs glfw3` CXXFLAGS += `pkg-config --cflags glfw3` CFLAGS = $(CXXFLAGS) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fac10d832..83e931a0e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1720,7 +1720,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end const float separator_thickness = style.SeparatorTextBorderSize; const ImVec2 min_size(label_size.x + extra_w + padding.x * 2.0f, ImMax(label_size.y + padding.y * 2.0f, separator_thickness)); const ImRect bb(pos, ImVec2(window->WorkRect.Max.x, pos.y + min_size.y)); - const float text_baseline_y = ImTrunc((bb.GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.99999f); //ImMax(padding.y, ImFloor((style.SeparatorTextSize - label_size.y) * 0.5f)); + const float text_baseline_y = ImTrunc((bb.GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.99999f); //ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)); ItemSize(min_size, text_baseline_y); if (!ItemAdd(bb, id)) return; From 3389dfd9dd9edf4d6f5884d9d1848446dce87689 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jan 2026 15:58:12 +0100 Subject: [PATCH 1599/2359] IsItemHovered() doesn't filter out the signal when activated item is a shortcut remote activation. (#9138, #456) Amend a201af7354 --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2cb0d5d94..521ec6b53 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -98,7 +98,6 @@ Breaking Changes: - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft. - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx. - Other Changes: - Fonts: @@ -155,6 +154,9 @@ Other Changes: noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Added GetItemFlags() in public API for consistency and to expose generic flags of last submitted item. (#9127) +- IsItemHovered() without ImGuiHoveredFlags_AllowWhenBlockedByActiveItem + doesn't filter out the signal when activated item is a shortcut remote activation; + (which mimicks what's done internally in the ItemHoverable() function). (#9138) - Debug Tools: - Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to io.AddInputCharacter(). (#9099) diff --git a/imgui.cpp b/imgui.cpp index da9a7019b..996d162b3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4824,7 +4824,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) // Test if another item is active (e.g. being dragged) const ImGuiID id = g.LastItemData.ID; if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0) - if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) + if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap && !g.ActiveIdFromShortcut) { // When ActiveId == MoveId it means that either: // - (1) user clicked on void _or_ an item with no id, which triggers moving window (ActiveId is set even when window has _NoMove flag) @@ -13571,6 +13571,7 @@ static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.NavWindow; const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; + //const bool activated_shortcut = false // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag. if ((!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) && !activated_shortcut) @@ -13586,6 +13587,7 @@ static ImVec2 ImGui::NavCalcPreferredRefPos() ImGuiInputSource source = NavCalcPreferredRefPosSource(); const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; + //const bool activated_shortcut = false if (source != ImGuiInputSource_Mouse && !activated_shortcut && window == NULL) source = ImGuiInputSource_Mouse; From 1566c96ccd5faa7fddf34329687ac16796bebabc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jan 2026 17:04:52 +0100 Subject: [PATCH 1600/2359] InputText, Nav: fixed remote/shortcut InputText() not teleporting mouse cursor when nav cursor is active and io.ConfigNavMoveSetMousePos is enabled. Motivated by this, also made SetFocusID() immediately set g.NavIdIsAlive, which is more correct and might be other (positive) subtle side effects. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 ++ imgui_widgets.cpp | 2 ++ 3 files changed, 7 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 521ec6b53..3a2bea6e2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -150,6 +150,9 @@ Other Changes: end of a line rather than at the beginning of next line. (#8990, #3237) - Fixed low-level word-wrapping function reading from *text_end when passed a string range. (#9107) [@achabense] +- Nav: + - Fixed remote/shortcut InputText() not teleporting mouse cursor when + nav cursor is visible and `io.ConfigNavMoveSetMousePos` is enabled. - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Added GetItemFlags() in public API for consistency and to expose generic diff --git a/imgui.cpp b/imgui.cpp index 996d162b3..4e59a1a6c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13055,6 +13055,8 @@ void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window) window->NavLastIds[nav_layer] = id; if (g.LastItemData.ID == id) window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect); + if (g.NavId == g.ActiveId && g.ActiveIdIsAlive) + g.NavIdIsAlive = true; if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) g.NavHighlightItemUnderNav = true; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 83e931a0e..88d3b7ca4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4848,6 +4848,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); + if (input_requested_by_nav) + SetNavCursorVisibleAfterMove(); } if (g.ActiveId == id) { From ca9b7b4071f89457c0e01919caade8b6c59d352d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jan 2026 17:11:23 +0100 Subject: [PATCH 1601/2359] InputText, Nav: amend 1566c96. (incorrectly commited old chunk) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 4e59a1a6c..d4bd9adb3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13055,7 +13055,7 @@ void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window) window->NavLastIds[nav_layer] = id; if (g.LastItemData.ID == id) window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect); - if (g.NavId == g.ActiveId && g.ActiveIdIsAlive) + if (id == g.ActiveIdIsAlive) g.NavIdIsAlive = true; if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) From 7a02f4b545e719a00ddb8b15d35bf6fbd78c301e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jan 2026 17:14:38 +0100 Subject: [PATCH 1602/2359] Nav, Shortcuts, Tooltips: tooltip reference position not affected by remote shortcut activation. (#9138, #456) NavCalcPreferredRefPos() has different path for popups vs tooltip. Amend 197f8904fe --- imgui.cpp | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d4bd9adb3..e4a63f9c7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1347,8 +1347,8 @@ static bool NavScoreItem(ImGuiNavItemData* result, const ImRect& nav static void NavApplyItemToResult(ImGuiNavItemData* result); static void NavProcessItem(); static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags); -static ImGuiInputSource NavCalcPreferredRefPosSource(); -static ImVec2 NavCalcPreferredRefPos(); +static ImGuiInputSource NavCalcPreferredRefPosSource(ImGuiWindowFlags window_type); +static ImVec2 NavCalcPreferredRefPos(ImGuiWindowFlags window_type); static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window); static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); static void NavRestoreLayer(ImGuiNavLayer layer); @@ -12203,7 +12203,7 @@ void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) popup_ref.RestoreNavWindow = g.NavWindow; // When popup closes focus may be restored to NavWindow (depend on window type). popup_ref.OpenFrameCount = g.FrameCount; popup_ref.OpenParentId = parent_window->IDStack.back(); - popup_ref.OpenPopupPos = NavCalcPreferredRefPos(); + popup_ref.OpenPopupPos = NavCalcPreferredRefPos(ImGuiWindowFlags_Popup); popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos; IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id); @@ -12681,9 +12681,9 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) // as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin(). IM_ASSERT(g.CurrentWindow == window); const float scale = g.Style.MouseCursorScale; - const ImVec2 ref_pos = NavCalcPreferredRefPos(); + const ImVec2 ref_pos = NavCalcPreferredRefPos(ImGuiWindowFlags_Tooltip); - if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource() == ImGuiInputSource_Mouse) + if (g.IO.MouseSource == ImGuiMouseSource_TouchScreen && NavCalcPreferredRefPosSource(ImGuiWindowFlags_Tooltip) == ImGuiInputSource_Mouse) { ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - (TOOLTIP_DEFAULT_PIVOT_TOUCH * window->Size); if (r_outer.Contains(ImRect(tooltip_pos, tooltip_pos + window->Size))) @@ -13568,33 +13568,29 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) } } -static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource() +// Positioning logic altered slightly for remote activation: for Popup we want to use item rect, for Tooltip we leave things alone. (#9138) +// When calling for ImGuiWindowFlags_Popup we use LastItemData. +static ImGuiInputSource ImGui::NavCalcPreferredRefPosSource(ImGuiWindowFlags window_type) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.NavWindow; - const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; - //const bool activated_shortcut = false - // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag. - if ((!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) && !activated_shortcut) + const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; + if ((window_type & ImGuiWindowFlags_Popup) && activated_shortcut) + return ImGuiInputSource_Keyboard; + + if (!g.NavCursorVisible || !g.NavHighlightItemUnderNav || !window) return ImGuiInputSource_Mouse; else return ImGuiInputSource_Keyboard; // or Nav in general } -static ImVec2 ImGui::NavCalcPreferredRefPos() +static ImVec2 ImGui::NavCalcPreferredRefPos(ImGuiWindowFlags window_type) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.NavWindow; - ImGuiInputSource source = NavCalcPreferredRefPosSource(); + ImGuiInputSource source = NavCalcPreferredRefPosSource(window_type); - const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; - //const bool activated_shortcut = false - - if (source != ImGuiInputSource_Mouse && !activated_shortcut && window == NULL) - source = ImGuiInputSource_Mouse; - - // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag. if (source == ImGuiInputSource_Mouse) { // Mouse (we need a fallback in case the mouse becomes invalid after being used) @@ -13606,8 +13602,9 @@ static ImVec2 ImGui::NavCalcPreferredRefPos() else { // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item + const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID; ImRect ref_rect; - if (activated_shortcut) + if (activated_shortcut && (window_type & ImGuiWindowFlags_Popup)) ref_rect = g.LastItemData.NavRect; else if (window != NULL) ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]); @@ -13806,7 +13803,7 @@ static void ImGui::NavUpdate() // Update mouse position if requested // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied) if (set_mouse_pos && io.ConfigNavMoveSetMousePos && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) - TeleportMousePos(NavCalcPreferredRefPos()); + TeleportMousePos(NavCalcPreferredRefPos(ImGuiWindowFlags_Popup)); // [DEBUG] g.NavScoringDebugCount = 0; From fedf227ea4f0bffbc75ff3d3de6631a4c57a4ba1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jan 2026 17:17:06 +0100 Subject: [PATCH 1603/2359] Amend 7a02f4b. --- docs/CHANGELOG.txt | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3a2bea6e2..c3ef808a3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -157,9 +157,12 @@ Other Changes: noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - Added GetItemFlags() in public API for consistency and to expose generic flags of last submitted item. (#9127) -- IsItemHovered() without ImGuiHoveredFlags_AllowWhenBlockedByActiveItem - doesn't filter out the signal when activated item is a shortcut remote activation; - (which mimicks what's done internally in the ItemHoverable() function). (#9138) +- Shortcuts: + - IsItemHovered() without ImGuiHoveredFlags_AllowWhenBlockedByActiveItem + doesn't filter out the signal when activated item is a shortcut remote activation; + (which mimicks what's done internally in the ItemHoverable() function). (#9138) + - Fixed tooltip placement being affected for a frame when located over an item + activated by SetNextItemShortcut(). (#9138) - Debug Tools: - Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to io.AddInputCharacter(). (#9099) From f5384544cb350dd2444c27c153ac563b91cf09da Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Jan 2026 17:26:25 +0100 Subject: [PATCH 1604/2359] (Breaking) Commented out legacy names obsoleted in 1.90 (Sept 2023): BeginChildFrame(), EndChildFrame(), ShowStackToolWindow(), IM_OFFSETOF(), IM_FLOOR(). --- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 7 +++---- imgui.h | 13 +++++++------ imgui_internal.h | 6 ++---- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c3ef808a3..b7b4f2cd9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,12 @@ HOW TO UPDATE? Breaking Changes: +- Commented out legacy names obsoleted in 1.90 (Sept 2023): + - BeginChildFrame() --> BeginChild() with ImGuiChildFlags_FrameStyle flag. + - EndChildFrame() --> EndChild(). + - ShowStackToolWindow() --> ShowIDStackToolWindow(). + - IM_OFFSETOF() --> offsetof(). + - IM_FLOOR() --> IM_TRUNC() [internal, for positive values only] - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore: Before: GetID("Hello###World") == GetID("###World") != GetID("World"); diff --git a/imgui.cpp b/imgui.cpp index e4a63f9c7..b1948d665 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -394,6 +394,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2026/01/08 (1.92.6) - Commented out legacy names obsoleted in 1.90 (Sept 2023): 'BeginChildFrame()' --> 'BeginChild()' with 'ImGuiChildFlags_FrameStyle'. 'EndChildFrame()' --> 'EndChild()'. 'ShowStackToolWindow()' --> 'ShowIDStackToolWindow()'. 'IM_OFFSETOF()' --> 'offsetof()'. - 2026/01/07 (1.92.6) - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). Default value has same meaning before and after. - Refer to GitHub topic #9157 if you have any question. - Before this version, those functions had a 'ImGuiPopupFlags popup_flags = 1' default value in their function signature. @@ -6386,10 +6387,8 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!"); } #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - //if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding) - // child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding; - //if (window_flags & ImGuiWindowFlags_NavFlattened) - // child_flags |= ImGuiChildFlags_NavFlattened; + //if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding) { child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding; } + //if (window_flags & ImGuiWindowFlags_NavFlattened) { child_flags |= ImGuiChildFlags_NavFlattened; } #endif if (child_flags & ImGuiChildFlags_AutoResizeX) child_flags &= ~ImGuiChildFlags_ResizeX; diff --git a/imgui.h b/imgui.h index 8d6b63719..fb2a505af 100644 --- a/imgui.h +++ b/imgui.h @@ -4035,15 +4035,16 @@ namespace ImGui IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! // OBSOLETED in 1.90.0 (from September 2023) - inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } - inline void EndChildFrame() { EndChild(); } - //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 void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } 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); 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); // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + // OBSOLETED in 1.90.0 (from September 2023) + //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); } + //inline void EndChildFrame() { EndChild(); } + //inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } // OBSOLETED in 1.89.7 (from June 2023) //IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() _before_ item. //-- OBSOLETED in 1.89.4 (from March 2023) @@ -4153,7 +4154,7 @@ typedef ImFontAtlasRect ImFontAtlasCustomRect; //typedef ImGuiKeyChord ImGuiKeyModFlags; // == int //enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = 0, ImGuiKeyModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiKeyModFlags_Shift = ImGuiMod_Shift, ImGuiKeyModFlags_Alt = ImGuiMod_Alt, ImGuiKeyModFlags_Super = ImGuiMod_Super }; -#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // OBSOLETED IN 1.90 (now using C++11 standard version) +//#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // OBSOLETED IN 1.90 (now using C++11 standard version) #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_internal.h b/imgui_internal.h index 86606f39f..6af67614e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -278,9 +278,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #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() is not inlined in MSVC debug builds #define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // Positive values only! -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -#define IM_FLOOR IM_TRUNC // [OBSOLETE] Renamed in 1.90.0 (Sept 2023) -#endif +//#define IM_FLOOR IM_TRUNC // [OBSOLETE] Renamed in 1.90.0 (Sept 2023) // Hint for branch prediction #if (defined(__cplusplus) && (__cplusplus >= 202002L)) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 202002L)) @@ -3784,7 +3782,7 @@ struct ImFontLoader IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); #endif #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are not actually compatible but we provide this as a compile-time error report helper. +typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92.0] The types are not actually compatible but we provide this as a compile-time error report helper. #endif //----------------------------------------------------------------------------- From d1c5a66557b35f8ea473d33cf363c1b0ec46050d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Jan 2026 12:11:10 +0100 Subject: [PATCH 1605/2359] Backends: WebGPU: rework unsupported path into an assert. (#9155, #9156) --- backends/imgui_impl_wgpu.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index c8722cd4a..e98e9f3ca 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -1078,7 +1078,7 @@ WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceI surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor); } #else - fprintf(stderr, "'CreateWGPUSurfaceHelper' is not implemented for this platform\n"); + IM_ASSERT(0 && "Unsupported WebGPU native platform!"); #endif return surface; } From f64c7c37efd9b0cead78e84f9378398b68ae5f61 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Jan 2026 18:17:38 +0100 Subject: [PATCH 1606/2359] Fonts: fixed a crash when trying to use AddFont() with MergeMode=true on a font that has already been rendered. (#9162) --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 1 + 2 files changed, 3 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b7b4f2cd9..cd9315352 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -74,6 +74,8 @@ Breaking Changes: until a shutdown of the owning context or font atlas. - The fact that handling of `FontDataOwnedByAtlas = false` was broken bypassed the issue altogether. + - Fixed a crash when trying to use AddFont() with MergeMode=true on a font that + has already been rendered. (#9162) [@ocornut, @cyfewlp] - Removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b839291b0..780f6b844 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3049,6 +3049,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) { IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. font = font_cfg_in->DstFont ? font_cfg_in->DstFont : Fonts.back(); + ImFontAtlasFontDiscardBakes(this, font, 0); // Need to discard bakes if the font was already used, because baked->FontLoaderDatas[] will change size. (#9162) } // Add to list From 791ad9b82db44ada9fedb3e26b2d900974ac0959 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 13 Jan 2026 16:15:48 +0100 Subject: [PATCH 1607/2359] InvisibleButton: allow calling with size (0,0) to fit to available content size. (#9166, #7623) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 5 ++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cd9315352..76d922194 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -163,6 +163,8 @@ Other Changes: nav cursor is visible and `io.ConfigNavMoveSetMousePos` is enabled. - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] +- InvisibleButton: allow calling with size (0,0) to fit to available content + size. (#9166, #7623) - Added GetItemFlags() in public API for consistency and to expose generic flags of last submitted item. (#9127) - Shortcuts: diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 88d3b7ca4..4244c0be3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -836,11 +836,10 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiBut if (window->SkipItems) return false; - // Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size. - IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f); + // Ensure zero-size fits to contents + ImVec2 size = CalcItemSize(ImVec2(size_arg.x != 0.0f ? size_arg.x : -FLT_MIN, size_arg.y != 0.0f ? size_arg.y : -FLT_MIN), 0.0f, 0.0f); const ImGuiID id = window->GetID(str_id); - ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(size); if (!ItemAdd(bb, id, NULL, (flags & ImGuiButtonFlags_EnableNav) ? ImGuiItemFlags_None : ImGuiItemFlags_NoNav)) From 0d08927dae557cd537416661d932b19dc6f040db Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Jan 2026 14:59:39 +0100 Subject: [PATCH 1608/2359] Error handling: Improve error handling and recovery for EndMenu()/EndCombo(). (#1651, #9165, #8499) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- imgui_widgets.cpp | 18 +++++++++++++++--- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 76d922194..0645eff90 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -173,6 +173,8 @@ Other Changes: (which mimicks what's done internally in the ItemHoverable() function). (#9138) - Fixed tooltip placement being affected for a frame when located over an item activated by SetNextItemShortcut(). (#9138) +- Error Handling: + - Improve error handling and recovery for EndMenu()/EndCombo(). (#1651, #9165, #8499) - Debug Tools: - Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to io.AddInputCharacter(). (#9099) diff --git a/imgui.cpp b/imgui.cpp index b1948d665..2a63f26e7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12455,7 +12455,7 @@ void ImGui::EndPopup() ImGuiWindow* window = g.CurrentWindow; if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0) { - IM_ASSERT_USER_ERROR(0, "Calling EndPopup() too many times or in wrong window!"); + IM_ASSERT_USER_ERROR(0, "Calling EndPopup() in wrong window!"); return; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4244c0be3..3b6ee2156 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2053,8 +2053,15 @@ bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags void ImGui::EndCombo() { ImGuiContext& g = *GImGui; - EndPopup(); g.BeginComboDepth--; + char name[16]; + ImFormatString(name, IM_COUNTOF(name), "##Combo_%02d", g.BeginComboDepth); // FIXME: Move those to helpers? + if (strcmp(g.CurrentWindow->Name, name) != 0) + { + IM_ASSERT_USER_ERROR(0, "Calling EndCombo() in wrong window!"); + return; + } + EndPopup(); } // Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements @@ -9399,7 +9406,12 @@ void ImGui::EndMenu() // Nav: When a left move request our menu failed, close ourselves. ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginMenu()/EndMenu() calls + + if ((window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) != (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) + { + IM_ASSERT_USER_ERROR(0, "Calling EndMenu() in wrong window!"); + return; + } ImGuiWindow* parent_window = window->ParentWindow; // Should always be != NULL is we passed assert. if (window->BeginCount == window->BeginCountPreviousFrame) if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet()) @@ -10343,7 +10355,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f ImGuiTabBar* tab_bar = g.CurrentTabBar; if (tab_bar == NULL) { - IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!"); + IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; } IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! From 7143d711bf3818f0ee342211ae5b381a31f94d32 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Jan 2026 15:24:30 +0100 Subject: [PATCH 1609/2359] Images, Style: added style.ImageRounding, ImGuiStyleVar_ImageRounding to configure rounding of Image() widgets. (#2942, #845) Moving border drawing above AddImage() call, should not make a difference for square images. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 +++ imgui.h | 2 ++ imgui_demo.cpp | 1 + imgui_widgets.cpp | 12 ++++++++---- 5 files changed, 17 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0645eff90..1a732a04d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -167,6 +167,9 @@ Other Changes: size. (#9166, #7623) - Added GetItemFlags() in public API for consistency and to expose generic flags of last submitted item. (#9127) +- Images: + - Added style.ImageRounding, ImGuiStyleVar_ImageRounding to configure + rounding of Image() widgets. (#2942, #845) - Shortcuts: - IsItemHovered() without ImGuiHoveredFlags_AllowWhenBlockedByActiveItem doesn't filter out the signal when activated item is a shortcut remote activation; diff --git a/imgui.cpp b/imgui.cpp index 2a63f26e7..105041d18 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1470,6 +1470,7 @@ ImGuiStyle::ImGuiStyle() GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + ImageRounding = 0.0f; // Rounding of Image() calls. ImageBorderSize = 0.0f; // Thickness of border around tabs. TabRounding = 5.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. @@ -1544,6 +1545,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) GrabMinSize = ImTrunc(GrabMinSize * scale_factor); GrabRounding = ImTrunc(GrabRounding * scale_factor); LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor); + ImageRounding = ImTrunc(ImageRounding * scale_factor); ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor); @@ -3603,6 +3605,7 @@ static const ImGuiStyleVarInfo GStyleVarsInfo[] = { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ScrollbarPadding) }, // ImGuiStyleVar_ScrollbarPadding { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageRounding) }, // ImGuiStyleVar_ImageRounding { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ImageBorderSize) }, // ImGuiStyleVar_ImageBorderSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBorderSize) }, // ImGuiStyleVar_TabBorderSize diff --git a/imgui.h b/imgui.h index fb2a505af..33c642b00 100644 --- a/imgui.h +++ b/imgui.h @@ -1830,6 +1830,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_ScrollbarPadding, // float ScrollbarPadding ImGuiStyleVar_GrabMinSize, // float GrabMinSize ImGuiStyleVar_GrabRounding, // float GrabRounding + ImGuiStyleVar_ImageRounding, // float ImageRounding ImGuiStyleVar_ImageBorderSize, // float ImageBorderSize ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_TabBorderSize, // float TabBorderSize @@ -2300,6 +2301,7 @@ struct ImGuiStyle float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + float ImageRounding; // Rounding of Image() calls. float ImageBorderSize; // Thickness of border around Image() calls. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b01c86940..5db91155b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8459,6 +8459,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat2("SeparatorTextAlign", (float*)&style.SeparatorTextAlign, 0.0f, 1.0f, "%.2f"); SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); + SliderFloat("ImageRounding", &style.ImageRounding, 0.0f, 12.0f, "%.0f"); SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, 1.0f, "%.0f"); SeparatorText("Tooltips"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3b6ee2156..1071d3d8c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1130,11 +1130,15 @@ void ImGui::ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const Im return; // Render - if (g.Style.ImageBorderSize > 0.0f) - window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), 0.0f, ImDrawFlags_None, g.Style.ImageBorderSize); + float rounding = g.Style.ImageRounding; if (bg_col.w > 0.0f) - window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); - window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col), rounding); + if (rounding > 0.0f) + window->DrawList->AddImageRounded(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col), rounding); + else + window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + if (g.Style.ImageBorderSize > 0.0f) + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), rounding, ImDrawFlags_None, g.Style.ImageBorderSize); } void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1) From a1dfaf4869347b8f639f63cfc2636f2d9d8b20db Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Jan 2026 15:54:55 +0100 Subject: [PATCH 1610/2359] ImageButton() doesn't use a clamped style.FrameRounding value but instead adjust inner image rounding when FramePadding > FrameRounding. (#2942, #845) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 8 ++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1a732a04d..2cc2d9152 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -170,6 +170,8 @@ Other Changes: - Images: - Added style.ImageRounding, ImGuiStyleVar_ImageRounding to configure rounding of Image() widgets. (#2942, #845) + - ImageButton() doesn't use a clamped style.FrameRounding value but instead + adjust inner image rounding when FramePadding > FrameRounding. (#2942, #845) - Shortcuts: - IsItemHovered() without ImGuiHoveredFlags_AllowWhenBlockedByActiveItem doesn't filter out the signal when activated item is a shortcut remote activation; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1071d3d8c..0a044a97b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1178,10 +1178,14 @@ bool ImGui::ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_ // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavCursor(bb, id); - RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding)); + RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); - window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + float image_rounding = ImMax(g.Style.FrameRounding - ImMax(padding.x, padding.y), g.Style.ImageRounding); + if (image_rounding > 0.0f) + window->DrawList->AddImageRounded(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col), image_rounding); + else + window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); return pressed; } From 9a6eb0ab2564925aac1bd1d9a7a3b3619192ca57 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Jan 2026 19:23:57 +0100 Subject: [PATCH 1611/2359] Backends: Vulkan: ImGui_ImplVulkanH_DestroyWindow() oes not call vkDestroySurfaceKHR(): because surface is created by caller. (#9163) # Conflicts: # backends/imgui_impl_vulkan.cpp --- backends/imgui_impl_vulkan.cpp | 32 +++++++++++++++----------- backends/imgui_impl_vulkan.h | 5 ++-- docs/CHANGELOG.txt | 4 ++++ examples/example_glfw_vulkan/main.cpp | 12 +++++----- examples/example_sdl2_vulkan/main.cpp | 12 +++++----- examples/example_sdl3_vulkan/main.cpp | 12 +++++----- examples/example_win32_vulkan/main.cpp | 12 +++++----- 7 files changed, 49 insertions(+), 40 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index f0ca7907a..f01d2145d 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,12 +27,13 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-01-05: Vulkan: Helper for creating render pass uses ImGui_ImplVulkanH_Window::AttachmentDesc to create render pass. Removed ClearEnabled. (#9152) -// 2025-11-24: Vulkan: Helper for creating a swap-chain (used by examples and multi-viewports) selects VkSwapchainCreateInfoKHR's compositeAlpha based on cap.supportedCompositeAlpha. (#8784) +// 2025-09-26: [Helpers] *BREAKING CHANGE*: Vulkan: Helper ImGui_ImplVulkanH_DestroyWindow() does not call vkDestroySurfaceKHR(): as surface is created by caller of ImGui_ImplVulkanH_CreateOrResizeWindow(), it is more consistent that we don't destroy it. (#9163) +// 2026-01-05: [Helpers] *BREAKING CHANGE*: Vulkan: Helper for creating render pass uses ImGui_ImplVulkanH_Window::AttachmentDesc to create render pass. Removed ClearEnabled. (#9152) +// 2025-11-24: [Helpers] Vulkan: Helper for creating a swap-chain (used by examples and multi-viewports) selects VkSwapchainCreateInfoKHR's compositeAlpha based on cap.supportedCompositeAlpha. (#8784) // 2025-10-15: Vulkan: Added IMGUI_IMPL_VULKAN_VOLK_FILENAME to configure path to volk.h header. (#9008) // 2025-09-26: *BREAKING CHANGE*: moved some fields in ImGui_ImplVulkan_InitInfo: init_info.RenderPass --> init_info.PipelineInfoMain.RenderPass, init_info.Subpass --> init_info.PipelineInfoMain.Subpass, init_info.MSAASamples --> init_info.PipelineInfoMain.MSAASamples, init_info.PipelineRenderingCreateInfo --> init_info.PipelineInfoMain.PipelineRenderingCreateInfo. // 2025-09-26: *BREAKING CHANGE*: renamed ImGui_ImplVulkan_MainPipelineCreateInfo to ImGui_ImplVulkan_PipelineInfo. Introduced very recently so shouldn't affect many users. -// 2025-09-26: *BREAKING CHANGE*: helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a VkImageUsageFlags image_usage` argument, default to VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT if 0. +// 2025-09-26: [Helpers] *BREAKING CHANGE*: Helper ImGui_ImplVulkanH_CreateOrResizeWindow() added a VkImageUsageFlags image_usage` argument, default to VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT if 0. // 2025-09-26: Vulkan: Added a way to customize shaders by filling ImGui_ImplVulkan_InitInfo::CustomShaderVertCreateInfo/CustomShaderFragCreateInfo. (#8585) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-09-04: Vulkan: Added ImGui_ImplVulkan_CreateMainPipeline(). (#8110, #8111) @@ -46,8 +47,8 @@ // 2025-02-14: *BREAKING CHANGE*: Added uint32_t api_version to ImGui_ImplVulkan_LoadFunctions(). // 2025-02-13: Vulkan: Added ApiVersion field in ImGui_ImplVulkan_InitInfo. Default to header version if unspecified. Dynamic rendering path loads "vkCmdBeginRendering/vkCmdEndRendering" (without -KHR suffix) on API 1.3. (#8326) // 2025-01-09: Vulkan: Added IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE to clarify how many image sampler descriptors are expected to be available in descriptor pool. (#6642) -// 2025-01-06: Vulkan: Added more ImGui_ImplVulkanH_XXXX helper functions to simplify our examples. -// 2024-12-11: Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) +// 2025-01-06: [Helpers] Vulkan: Added more ImGui_ImplVulkanH_XXXX helper functions to simplify our examples. +// 2024-12-11: [Helpers] Vulkan: Fixed setting VkSwapchainCreateInfoKHR::preTransform for platforms not supporting VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR. (#8222) // 2024-11-27: Vulkan: Make user-provided descriptor pool optional. As a convenience, when setting init_info->DescriptorPoolSize the backend will create one itself. (#8172, #4867) // 2024-10-07: Vulkan: Changed default texture sampler to Clamp instead of Repeat/Wrap. // 2024-10-07: Vulkan: Expose selected render state in ImGui_ImplVulkan_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks. @@ -55,7 +56,7 @@ // 2024-04-19: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define (you can also use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().) // 2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering. // 2024-02-12: *BREAKING CHANGE*: Dynamic rendering now require filling PipelineRenderingCreateInfo structure. -// 2024-01-19: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236) +// 2024-01-19: [Helpers] Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236) // 2024-01-11: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size (#3957). Fixed MinAllocationSize handing (#7189). // 2024-01-03: Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous "best practice" validation layer. (#7189, #4238) // 2024-01-03: Vulkan: Stopped creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT as we don't reset them. @@ -83,16 +84,16 @@ // 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). -// 2019-04-04: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. +// 2019-04-04: [Helpers] Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. -// 2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case. +// 2018-08-25: [Helpers] Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case. // 2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other backends. // 2018-06-08: Misc: Extracted imgui_impl_vulkan.cpp/.h away from the old combined GLFW+Vulkan example. // 2018-06-08: Vulkan: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. -// 2018-03-03: Vulkan: Various refactor, created a couple of ImGui_ImplVulkanH_XXX helper that the example can use and that viewport support will use. +// 2018-03-03: [Helpers] Vulkan: Various refactor, created a couple of ImGui_ImplVulkanH_XXX helper that the example can use and that viewport support will use. // 2018-03-01: Vulkan: Renamed ImGui_ImplVulkan_Init_Info to ImGui_ImplVulkan_InitInfo and fields to match more closely Vulkan terminology. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback, ImGui_ImplVulkan_Render() calls ImGui_ImplVulkan_RenderDrawData() itself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. @@ -1767,7 +1768,9 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V 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!"); - (void)instance; + IM_ASSERT(wd->Surface != VK_NULL_HANDLE); + IM_UNUSED(instance); + 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); @@ -1850,6 +1853,7 @@ void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevic void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator) { + IM_UNUSED(instance); vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) //vkQueueWaitIdle(bd->Queue); @@ -1862,9 +1866,11 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui vkDestroyPipeline(device, wd->Pipeline, allocator); vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); - vkDestroySurfaceKHR(instance, wd->Surface, allocator); - - *wd = ImGui_ImplVulkanH_Window(); + wd->RenderPass = VK_NULL_HANDLE; + wd->Swapchain = VK_NULL_HANDLE; + wd->Width = wd->Height = 0; + wd->FrameIndex = wd->ImageCount = wd->SemaphoreCount = wd->SemaphoreIndex = 0; + //vkDestroySurfaceKHR(instance, wd->Surface, allocator); // v1.92.6 (~2026-01-16): because wd->Surface is user provided we don't attempt to destroy it ourself. } void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 83376e597..0ebe1d42d 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -171,6 +171,7 @@ struct ImGui_ImplVulkan_RenderState // Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app. // // You probably do NOT need to use or care about those functions. +// WE DO NOT PROVIDE STRONG GUARANTEES OF BACKWARD/FORWARD COMPATIBILITY. // Those functions only exist because: // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. // 2) the multi-viewport / platform window implementation needs them internally. @@ -181,8 +182,6 @@ struct ImGui_ImplVulkan_RenderState // render pass, frame buffers, etc.). You may read this code if you are curious, but // it is recommended you use your own custom tailored code to do equivalent work. // -// We don't provide a strong guarantee that we won't change those functions API. -// // The ImGui_ImplVulkanH_XXX functions should NOT interact with any of the state used // by the regular ImGui_ImplVulkan_XXX functions. //------------------------------------------------------------------------- @@ -224,6 +223,7 @@ struct ImGui_ImplVulkanH_Window { // Input bool UseDynamicRendering; + VkSurfaceKHR Surface; // Surface created and destroyed by caller. VkSurfaceFormatKHR SurfaceFormat; VkPresentModeKHR PresentMode; VkAttachmentDescription AttachmentDesc; // RenderPass creation: main attachment description. @@ -233,7 +233,6 @@ struct ImGui_ImplVulkanH_Window int Width; // Generally same as passed to ImGui_ImplVulkanH_CreateOrResizeWindow() int Height; VkSwapchainKHR Swapchain; - VkSurfaceKHR Surface; VkRenderPass RenderPass; VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2cc2d9152..6de32507b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -105,6 +105,10 @@ Breaking Changes: - BeginPopupContextItem("foo", 1); // Behavior unchanged (as a courtesy we legacy interpret 1 as ImGuiPopupFlags_MouseButtonRight, will assert if disabling legacy behaviors. - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft. - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx. +- Backends: + - Vulkan: optional ImGui_ImplVulkanH_DestroyWindow() helper used by our example + code does not call vkDestroySurfaceKHR(): because surface is created by caller + of ImGui_ImplVulkanH_CreateOrResizeWindow(), it is more consistent. (#9163) Other Changes: diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index ab259a3e5..ccce94fb5 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -212,11 +212,9 @@ static void SetupVulkan(ImVector instance_extensions) // Your real engine/app may not use them. static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { - wd->Surface = surface; - // Check for WSI support VkBool32 res; - vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, wd->Surface, &res); + vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, surface, &res); if (res != VK_TRUE) { fprintf(stderr, "Error no WSI support on physical device 0\n"); @@ -226,6 +224,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; + wd->Surface = surface; wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode @@ -256,9 +255,10 @@ static void CleanupVulkan() vkDestroyInstance(g_Instance, g_Allocator); } -static void CleanupVulkanWindow() +static void CleanupVulkanWindow(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator); + vkDestroySurfaceKHR(g_Instance, wd->Surface, g_Allocator); } static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) @@ -532,7 +532,7 @@ int main(int, char**) ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); - CleanupVulkanWindow(); + CleanupVulkanWindow(&g_MainWindowData); CleanupVulkan(); glfwDestroyWindow(window); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 58f4f8e10..87a38ff90 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -203,11 +203,9 @@ static void SetupVulkan(ImVector instance_extensions) // Your real engine/app may not use them. static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { - wd->Surface = surface; - // Check for WSI support VkBool32 res; - vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, wd->Surface, &res); + vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, surface, &res); if (res != VK_TRUE) { fprintf(stderr, "Error no WSI support on physical device 0\n"); @@ -217,6 +215,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; + wd->Surface = surface; wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode @@ -247,9 +246,10 @@ static void CleanupVulkan() vkDestroyInstance(g_Instance, g_Allocator); } -static void CleanupVulkanWindow() +static void CleanupVulkanWindow(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator); + vkDestroySurfaceKHR(g_Instance, wd->Surface, g_Allocator); } static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) @@ -547,7 +547,7 @@ int main(int, char**) ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); - CleanupVulkanWindow(); + CleanupVulkanWindow(&g_MainWindowData); CleanupVulkan(); SDL_DestroyWindow(window); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index fa2296938..38c48d3a7 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -205,11 +205,9 @@ static void SetupVulkan(ImVector instance_extensions) // Your real engine/app may not use them. static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { - wd->Surface = surface; - // Check for WSI support VkBool32 res; - vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, wd->Surface, &res); + vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, surface, &res); if (res != VK_TRUE) { fprintf(stderr, "Error no WSI support on physical device 0\n"); @@ -219,6 +217,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; + wd->Surface = surface; wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode @@ -249,9 +248,10 @@ static void CleanupVulkan() vkDestroyInstance(g_Instance, g_Allocator); } -static void CleanupVulkanWindow() +static void CleanupVulkanWindow(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator); + vkDestroySurfaceKHR(g_Instance, wd->Surface, g_Allocator); } static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) @@ -550,7 +550,7 @@ int main(int, char**) ImGui_ImplSDL3_Shutdown(); ImGui::DestroyContext(); - CleanupVulkanWindow(); + CleanupVulkanWindow(&g_MainWindowData); CleanupVulkan(); SDL_DestroyWindow(window); diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index b70cb9fcc..75c5605cf 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -201,11 +201,9 @@ static void SetupVulkan(ImVector instance_extensions) // Your real engine/app may not use them. static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { - wd->Surface = surface; - // Check for WSI support VkBool32 res; - vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, wd->Surface, &res); + vkGetPhysicalDeviceSurfaceSupportKHR(g_PhysicalDevice, g_QueueFamily, surface, &res); if (res != VK_TRUE) { fprintf(stderr, "Error no WSI support on physical device 0\n"); @@ -215,6 +213,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Select Surface Format const VkFormat requestSurfaceImageFormat[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM }; const VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; + wd->Surface = surface; wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_COUNTOF(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode @@ -245,9 +244,10 @@ static void CleanupVulkan() vkDestroyInstance(g_Instance, g_Allocator); } -static void CleanupVulkanWindow() +static void CleanupVulkanWindow(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator); + vkDestroySurfaceKHR(g_Instance, wd->Surface, g_Allocator); } static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) @@ -516,7 +516,7 @@ int main(int, char**) ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); - CleanupVulkanWindow(); + CleanupVulkanWindow(&g_MainWindowData); CleanupVulkan(); ::DestroyWindow(hwnd); From d7598aa84fa0b803c3548d0982dc9af5ee2c4301 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Jan 2026 16:07:07 +0100 Subject: [PATCH 1612/2359] Backends: SDL2, SDL3: changed GetClipboardText() handler to return NULL on error aka clipboard contents is not text. (#9168) Consistent with other backends. --- backends/imgui_impl_sdl2.cpp | 6 +++++- backends/imgui_impl_sdl3.cpp | 6 +++++- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 3 ++- imgui.h | 2 +- 5 files changed, 15 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 371b1dac4..2049f117b 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-01-15: Changed GetClipboardText() handler to return nullptr on error aka clipboard contents is not text. Consistent with other backends. (#9168) // 2025-09-24: Skip using the SDL_GetGlobalMouseState() state when one of our window is hovered, as the SDL_MOUSEMOTION data is reliable. Fix macOS notch mouse coordinates issue in fullscreen mode + better perf on X11. (#7919, #7786) // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. // 2025-09-15: Content Scales are always reported as 1.0 on Wayland. (#8921) @@ -178,7 +179,10 @@ static const char* ImGui_ImplSDL2_GetClipboardText(ImGuiContext*) ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); - bd->ClipboardTextData = SDL_GetClipboardText(); + if (SDL_HasClipboardText()) + bd->ClipboardTextData = SDL_GetClipboardText(); + else + bd->ClipboardTextData = nullptr; return bd->ClipboardTextData; } diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index ffd9f8a59..a1a3eeb86 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-01-15: Changed GetClipboardText() handler to return nullptr on error aka clipboard contents is not text. Consistent with other backends. (#9168) // 2025-11-05: Fixed an issue with missing characters events when an already active text field changes viewports. (#9054) // 2025-10-22: Fixed Platform_OpenInShellFn() return value (unused in core). // 2025-09-24: Skip using the SDL_GetGlobalMouseState() state when one of our window is hovered, as the SDL_EVENT_MOUSE_MOTION data is reliable. Fix macOS notch mouse coordinates issue in fullscreen mode + better perf on X11. (#7919, #7786) @@ -151,7 +152,10 @@ static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*) ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); - bd->ClipboardTextData = SDL_GetClipboardText(); + if (SDL_HasClipboardText()) + bd->ClipboardTextData = SDL_GetClipboardText(); + else + bd->ClipboardTextData = nullptr; return bd->ClipboardTextData; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6de32507b..61798aa86 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -195,6 +195,8 @@ Other Changes: forcefully disable either. (#9109, #9116) - OpenGL3: Fixed embedded loader multiple init/shutdown cycles broken on some platforms. (#8792, #9112) + - SDL2, SDL3: changed GetClipboardText() handler to return NULL on error aka + clipboard contents is not text. Consistent with other backends. (#9168) - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. (#9076) [@Niminem] diff --git a/imgui.cpp b/imgui.cpp index 105041d18..4743838c3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5091,10 +5091,11 @@ void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr } } +// A conformant backend should return NULL on failure (e.g. clipboard data is not text). const char* ImGui::GetClipboardText() { ImGuiContext& g = *GImGui; - return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : ""; + return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : NULL; } void ImGui::SetClipboardText(const char* text) diff --git a/imgui.h b/imgui.h index 33c642b00..448221dce 100644 --- a/imgui.h +++ b/imgui.h @@ -3956,7 +3956,7 @@ struct ImGuiPlatformIO // Optional: Access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) - const char* (*Platform_GetClipboardTextFn)(ImGuiContext* ctx); + const char* (*Platform_GetClipboardTextFn)(ImGuiContext* ctx); // Should return NULL on failure (e.g. clipboard data is not text). void (*Platform_SetClipboardTextFn)(ImGuiContext* ctx, const char* text); void* Platform_ClipboardUserData; From 21d3299e588b5c702dcca0f448b4f937af369b4a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Jan 2026 16:08:40 +0100 Subject: [PATCH 1613/2359] Backends: fixed reappearing uses to NULL to favor nullptr. --- backends/imgui_impl_allegro5.cpp | 2 +- backends/imgui_impl_allegro5.h | 2 +- backends/imgui_impl_dx10.h | 2 +- backends/imgui_impl_dx11.h | 2 +- backends/imgui_impl_dx12.cpp | 2 +- backends/imgui_impl_dx12.h | 2 +- backends/imgui_impl_dx9.h | 2 +- backends/imgui_impl_glfw.cpp | 4 ++-- backends/imgui_impl_metal.h | 4 ++-- backends/imgui_impl_opengl2.h | 2 +- backends/imgui_impl_opengl3.cpp | 2 +- backends/imgui_impl_opengl3.h | 2 +- backends/imgui_impl_sdl2.cpp | 2 +- backends/imgui_impl_sdl3.cpp | 4 ++-- backends/imgui_impl_sdlgpu3.h | 2 +- backends/imgui_impl_sdlrenderer2.h | 2 +- backends/imgui_impl_sdlrenderer3.h | 2 +- backends/imgui_impl_vulkan.cpp | 2 +- backends/imgui_impl_vulkan.h | 2 +- backends/imgui_impl_wgpu.h | 2 +- 20 files changed, 23 insertions(+), 23 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index bb6660d88..6ee88a184 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -524,7 +524,7 @@ void ImGui_ImplAllegro5_SetDisplay(ALLEGRO_DISPLAY* display) if (bd->VertexDecl) { al_destroy_vertex_decl(bd->VertexDecl); - bd->VertexDecl = NULL; + bd->VertexDecl = nullptr; } if (bd->Display && !bd->VertexDecl) diff --git a/backends/imgui_impl_allegro5.h b/backends/imgui_impl_allegro5.h index 622430432..135c4ff8a 100644 --- a/backends/imgui_impl_allegro5.h +++ b/backends/imgui_impl_allegro5.h @@ -38,7 +38,7 @@ IMGUI_IMPL_API void ImGui_ImplAllegro5_SetDisplay(ALLEGRO_DISPLAY* display); IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplAllegro5_UpdateTexture(ImTextureData* tex); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h index 38ecbdfe3..9d7fb68ae 100644 --- a/backends/imgui_impl_dx10.h +++ b/backends/imgui_impl_dx10.h @@ -32,7 +32,7 @@ IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplDX10_UpdateTexture(ImTextureData* tex); // [BETA] Selected render state data shared with callbacks. diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h index c120bf093..1df4f3695 100644 --- a/backends/imgui_impl_dx11.h +++ b/backends/imgui_impl_dx11.h @@ -34,7 +34,7 @@ IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex); // [BETA] Selected render state data shared with callbacks. diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 14c0fc60f..056d23a6c 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -875,7 +875,7 @@ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info) init_info = &bd->InitInfo; bd->pd3dDevice = init_info->Device; - IM_ASSERT(init_info->CommandQueue != NULL); + IM_ASSERT(init_info->CommandQueue != nullptr); bd->pCommandQueue = init_info->CommandQueue; bd->RTVFormat = init_info->RTVFormat; bd->DSVFormat = init_info->DSVFormat; diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 3bb66c1fb..8d61dae77 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -64,7 +64,7 @@ IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex); // [BETA] Selected render state data shared with callbacks. diff --git a/backends/imgui_impl_dx9.h b/backends/imgui_impl_dx9.h index 600f0a750..021439b9a 100644 --- a/backends/imgui_impl_dx9.h +++ b/backends/imgui_impl_dx9.h @@ -31,7 +31,7 @@ IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplDX9_UpdateTexture(ImTextureData* tex); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 82c512fee..f166b45d2 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -251,10 +251,10 @@ static bool ImGui_ImplGlfw_IsWayland() return glfwGetPlatform() == GLFW_PLATFORM_WAYLAND; #else const char* version = glfwGetVersionString(); - if (strstr(version, "Wayland") == NULL) // e.g. Ubuntu 22.04 ships with GLFW 3.3.6 compiled without Wayland + if (strstr(version, "Wayland") == nullptr) // e.g. Ubuntu 22.04 ships with GLFW 3.3.6 compiled without Wayland return false; #ifdef GLFW_EXPOSE_NATIVE_X11 - if (glfwGetX11Display() != NULL) + if (glfwGetX11Display() != nullptr) return false; #endif return true; diff --git a/backends/imgui_impl_metal.h b/backends/imgui_impl_metal.h index 2a9a26a02..8af2c8b6b 100644 --- a/backends/imgui_impl_metal.h +++ b/backends/imgui_impl_metal.h @@ -39,7 +39,7 @@ IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(id device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex); #endif @@ -67,7 +67,7 @@ IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex); #endif diff --git a/backends/imgui_impl_opengl2.h b/backends/imgui_impl_opengl2.h index 014a03aca..65b0fe0b4 100644 --- a/backends/imgui_impl_opengl2.h +++ b/backends/imgui_impl_opengl2.h @@ -37,7 +37,7 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplOpenGL2_UpdateTexture(ImTextureData* tex); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 133b0ed27..6348b01b0 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -41,7 +41,7 @@ // 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375) // 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333) // 2023-03-23: OpenGL: Properly restoring "no shader program bound" if it was the case prior to running the rendering function. (#6267, #6220, #6224) -// 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns NULL. (#6154, #4445, #3530) +// 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns nullptr. (#6154, #4445, #3530) // 2023-03-06: OpenGL: Fixed restoration of a potentially deleted OpenGL program, by calling glIsProgram(). (#6220, #6224) // 2022-11-09: OpenGL: Reverted use of glBufferSubData(), too many corruptions issues + old issues seemingly can't be reproed with Intel drivers nowadays (revert 2021-12-15 and 2022-05-23 changes). // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h index b72b5c887..aabe04b07 100644 --- a/backends/imgui_impl_opengl3.h +++ b/backends/imgui_impl_opengl3.h @@ -40,7 +40,7 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex); // Configuration flags to add in your imconfig file: diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 2049f117b..4fb9c4d99 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -684,7 +684,7 @@ static void ImGui_ImplSDL2_UpdateMouseData() // Note that SDL_GetGlobalMouseState() is in theory slow on X11, but this only runs on rather specific cases. If a problem we may provide a way to opt-out this feature. SDL_Window* hovered_window = SDL_GetMouseFocus(); const bool is_relative_mouse_mode = SDL_GetRelativeMouseMode() != 0; - if (hovered_window == NULL && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) + if (hovered_window == nullptr && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) { // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) int mouse_x, mouse_y; diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index a1a3eeb86..f8bacc51b 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -191,7 +191,7 @@ static void ImGui_ImplSDL3_UpdateIme() SDL_StopTextInput(bd->ImeWindow); bd->ImeWindow = nullptr; } - if ((!bd->ImeDirty && bd->ImeWindow == window) || (window == NULL)) + if ((!bd->ImeDirty && bd->ImeWindow == window) || (window == nullptr)) return; // Start/update current input @@ -663,7 +663,7 @@ static void ImGui_ImplSDL3_UpdateMouseData() // Note that SDL_GetGlobalMouseState() is in theory slow on X11, but this only runs on rather specific cases. If a problem we may provide a way to opt-out this feature. SDL_Window* hovered_window = SDL_GetMouseFocus(); const bool is_relative_mouse_mode = SDL_GetWindowRelativeMouseMode(bd->Window); - if (hovered_window == NULL && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) + if (hovered_window == nullptr && bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode) { // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) float mouse_x, mouse_y; diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index cde9c5fe7..12b6528f3 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -48,7 +48,7 @@ IMGUI_IMPL_API void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, IMGUI_IMPL_API void ImGui_ImplSDLGPU3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLGPU3_DestroyDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex); // [BETA] Selected render state data shared with callbacks. diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h index a62e60927..860e95507 100644 --- a/backends/imgui_impl_sdlrenderer2.h +++ b/backends/imgui_impl_sdlrenderer2.h @@ -39,7 +39,7 @@ IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_d IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_UpdateTexture(ImTextureData* tex); // [BETA] Selected render state data shared with callbacks. diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h index 618cc2430..f5f53b9d2 100644 --- a/backends/imgui_impl_sdlrenderer3.h +++ b/backends/imgui_impl_sdlrenderer3.h @@ -39,7 +39,7 @@ IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_d IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_UpdateTexture(ImTextureData* tex); // [BETA] Selected render state data shared with callbacks. diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index f01d2145d..8f4bd5a62 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1156,7 +1156,7 @@ void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo* pi #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING VkPipelineRenderingCreateInfoKHR* pipeline_rendering_create_info = &pipeline_info->PipelineRenderingCreateInfo; - if (v->UseDynamicRendering && pipeline_rendering_create_info->pColorAttachmentFormats != NULL) + if (v->UseDynamicRendering && pipeline_rendering_create_info->pColorAttachmentFormats != nullptr) { // Deep copy buffer to reduce error-rate for end user (#8282) ImVector formats; diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 0ebe1d42d..4ad33b8f3 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -142,7 +142,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_i // Else, the pipeline can be created, or re-created, using ImGui_ImplVulkan_CreateMainPipeline() before rendering. IMGUI_IMPL_API void ImGui_ImplVulkan_CreateMainPipeline(const ImGui_ImplVulkan_PipelineInfo* info); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplVulkan_UpdateTexture(ImTextureData* tex); // Register a texture (VkDescriptorSet == ImTextureID) diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index f17fe6c25..7ab3dd31f 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -72,7 +72,7 @@ IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURen IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects(); -// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex); // [BETA] Selected render state data shared with callbacks. From 5dde06b32759faf1da252426688b8a04a1d6df61 Mon Sep 17 00:00:00 2001 From: E Date: Sun, 18 Jan 2026 17:45:38 -0500 Subject: [PATCH 1614/2359] Docs: fixed 'Tearaway' link in credits section (#9176) --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index c1b413629..a2d140734 100644 --- a/docs/README.md +++ b/docs/README.md @@ -209,7 +209,7 @@ Dear ImGui is using software and services provided free of charge for open sourc Credits ------- -Developed by [Omar Cornut](https://www.miracleworld.net) and every direct or indirect [contributors](https://github.com/ocornut/imgui/graphs/contributors) to the GitHub. The early version of this library was developed with the support of [Media Molecule](https://www.mediamolecule.com) and first used internally on the game [Tearaway](https://tearaway.mediamolecule.com) (PS Vita). +Developed by [Omar Cornut](https://www.miracleworld.net) and every direct or indirect [contributors](https://github.com/ocornut/imgui/graphs/contributors) to the GitHub. The early version of this library was developed with the support of [Media Molecule](https://www.mediamolecule.com) and first used internally on the game [Tearaway](https://youtu.be/w0oxBviRGlU) (PS Vita). Recurring contributors include Rokas Kupstys [@rokups](https://github.com/rokups) (2020-2022): a good portion of work on automation system and regression tests now available in [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine). From 14dfd5bf6ba3b555fd79b0d42ef714f0c3d40aab Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Jan 2026 11:42:08 +0100 Subject: [PATCH 1615/2359] Examples: DX12: update to VS2019 so it supports WIndows SDK 10.0 simplified versioning. --- .../example_win32_directx12.vcxproj | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj b/examples/example_win32_directx12/example_win32_directx12.vcxproj index bb98c4141..c4b81e76f 100644 --- a/examples/example_win32_directx12/example_win32_directx12.vcxproj +++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj @@ -21,34 +21,34 @@ {b4cf9797-519d-4afe-a8f4-5141a6b521d3} example_win32_directx12 - 10.0.20348.0 + 10.0 Application true Unicode - v140 + v142 Application true Unicode - v140 + v142 Application false true Unicode - v140 + v142 Application false true Unicode - v140 + v142 From ea122de913e087f77d68672a8810dee1960e2ea2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Jan 2026 11:49:11 +0100 Subject: [PATCH 1616/2359] Error handling: Improve error handling and recovery for TableSetupColumn(). --- docs/CHANGELOG.txt | 1 + imgui_tables.cpp | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 61798aa86..6dd87e848 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -184,6 +184,7 @@ Other Changes: activated by SetNextItemShortcut(). (#9138) - Error Handling: - Improve error handling and recovery for EndMenu()/EndCombo(). (#1651, #9165, #8499) + - Improve error handling and recovery for TableSetupColumn(). - Debug Tools: - Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to io.AddInputCharacter(). (#9099) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index af97b2e96..f5048e505 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1606,11 +1606,11 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); return; } - IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!"); + IM_ASSERT(table->IsLayoutLocked == false && "TableSetupColumn(): need to call before first row!"); IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()"); if (table->DeclColumnsCount >= table->ColumnsCount) { - IM_ASSERT_USER_ERROR(table->DeclColumnsCount < table->ColumnsCount, "Called TableSetupColumn() too many times!"); + IM_ASSERT_USER_ERROR(table->DeclColumnsCount < table->ColumnsCount, "TableSetupColumn(): called too many times!"); return; } @@ -1620,7 +1620,10 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo // Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa. // Give a grace to users of ImGuiTableFlags_ScrollX. if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0) - IM_ASSERT(init_width_or_weight <= 0.0f && "Can only specify width/weight if sizing policy is set explicitly in either Table or Column."); + { + IM_ASSERT_USER_ERROR(init_width_or_weight <= 0.0f, "TableSetupColumn(): can only specify width/weight if sizing policy is set explicitly in either Table or Column."); + return; + } // When passing a width automatically enforce WidthFixed policy // (whereas TableSetupColumnFlags would default to WidthAuto if table is not resizable) From 12223cc3e93fec65ef3b7ca3627bb125b23ddaa1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Jan 2026 12:04:43 +0100 Subject: [PATCH 1617/2359] Error handling: rework macros, add IM_ASSERT_USER_ERROR_RET(), IM_ASSERT_USER_ERROR_RETV() to simplify code. --- imgui.cpp | 72 ++++++++--------------------------------------- imgui_internal.h | 4 ++- imgui_tables.cpp | 70 +++++++++------------------------------------ imgui_widgets.cpp | 47 ++++++------------------------- 4 files changed, 36 insertions(+), 157 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4743838c3..151a17308 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3635,11 +3635,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { ImGuiContext& g = *GImGui; const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 1) - { - IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); - return; - } + IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 1, "Calling PushStyleVar() variant with wrong type!"); float* pvar = (float*)var_info->GetVarPtr(&g.Style); g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; @@ -3649,11 +3645,7 @@ void ImGui::PushStyleVarX(ImGuiStyleVar idx, float val_x) { ImGuiContext& g = *GImGui; const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) - { - IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); - return; - } + IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!"); ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); pvar->x = val_x; @@ -3663,11 +3655,7 @@ void ImGui::PushStyleVarY(ImGuiStyleVar idx, float val_y) { ImGuiContext& g = *GImGui; const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) - { - IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); - return; - } + IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!"); ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); pvar->y = val_y; @@ -3677,11 +3665,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { ImGuiContext& g = *GImGui; const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); - if (var_info->DataType != ImGuiDataType_Float || var_info->Count != 2) - { - IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!"); - return; - } + IM_ASSERT_USER_ERROR_RET(var_info->DataType == ImGuiDataType_Float && var_info->Count == 2, "Calling PushStyleVar() variant with wrong type!"); ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; @@ -5941,11 +5925,7 @@ void ImGui::EndFrame() // Don't process EndFrame() multiple times. if (g.FrameCountEnded == g.FrameCount) return; - if (!g.WithinFrameScope) - { - IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?"); - return; - } + IM_ASSERT_USER_ERROR_RET(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?"); CallContextHooks(&g, ImGuiContextHookType_EndFramePre); @@ -8221,11 +8201,7 @@ void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) void ImGui::PopItemFlag() { ImGuiContext& g = *GImGui; - if (g.ItemFlagsStack.Size <= 1) - { - IM_ASSERT_USER_ERROR(0, "Calling PopItemFlag() too many times!"); - return; - } + IM_ASSERT_USER_ERROR_RET(g.ItemFlagsStack.Size > 1, "Calling PopItemFlag() too many times!"); g.ItemFlagsStack.pop_back(); g.CurrentItemFlags = g.ItemFlagsStack.back(); } @@ -8255,11 +8231,7 @@ void ImGui::BeginDisabled(bool disabled) void ImGui::EndDisabled() { ImGuiContext& g = *GImGui; - if (g.DisabledStackSize <= 0) - { - IM_ASSERT_USER_ERROR(0, "Calling EndDisabled() too many times!"); - return; - } + IM_ASSERT_USER_ERROR_RET(g.DisabledStackSize > 0, "Calling EndDisabled() too many times!"); g.DisabledStackSize--; bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; //PopItemFlag(); @@ -8306,11 +8278,7 @@ void ImGui::PopTextWrapPos() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - if (window->DC.TextWrapPosStack.Size <= 0) - { - IM_ASSERT_USER_ERROR(0, "Calling PopTextWrapPos() too many times!"); - return; - } + IM_ASSERT_USER_ERROR_RET(window->DC.TextWrapPosStack.Size > 0, "Calling PopTextWrapPos() too many times!"); window->DC.TextWrapPos = window->DC.TextWrapPosStack.back(); window->DC.TextWrapPosStack.pop_back(); } @@ -8709,11 +8677,7 @@ void ImGui::PushFocusScope(ImGuiID id) void ImGui::PopFocusScope() { ImGuiContext& g = *GImGui; - if (g.FocusScopeStack.Size <= g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack) - { - IM_ASSERT_USER_ERROR(0, "Calling PopFocusScope() too many times!"); - return; - } + IM_ASSERT_USER_ERROR_RET(g.FocusScopeStack.Size > g.StackSizesInBeginForCurrentWindow->SizeOfFocusScopeStack, "Calling PopFocusScope() too many times!"); g.FocusScopeStack.pop_back(); g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0; } @@ -9104,11 +9068,7 @@ void ImGui::PushFont(ImFont* font, float font_size_base) void ImGui::PopFont() { ImGuiContext& g = *GImGui; - if (g.FontStack.Size <= 0) - { - IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!"); - return; - } + IM_ASSERT_USER_ERROR_RET(g.FontStack.Size > 0, "Calling PopFont() too many times!"); ImFontStackData* font_stack_data = &g.FontStack.back(); SetCurrentFont(font_stack_data->Font, font_stack_data->FontSizeBeforeScaling, font_stack_data->FontSizeAfterScaling); g.FontStack.pop_back(); @@ -9248,11 +9208,7 @@ ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed) void ImGui::PopID() { ImGuiWindow* window = GImGui->CurrentWindow; - if (window->IDStack.Size <= 1) - { - IM_ASSERT_USER_ERROR(0, "Calling PopID() too many times!"); - return; - } + IM_ASSERT_USER_ERROR_RET(window->IDStack.Size > 1, "Calling PopID() too many times!"); window->IDStack.pop_back(); } @@ -12457,11 +12413,7 @@ void ImGui::EndPopup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0) - { - IM_ASSERT_USER_ERROR(0, "Calling EndPopup() in wrong window!"); - return; - } + IM_ASSERT_USER_ERROR_RET((window->Flags & ImGuiWindowFlags_Popup) != 0 && g.BeginPopupStack.Size > 0, "Calling EndPopup() in wrong window!"); // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests) if (g.NavWindow == window) diff --git a/imgui_internal.h b/imgui_internal.h index 6af67614e..5a1816547 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2056,7 +2056,9 @@ struct ImGuiLocEntry // - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. // - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. #ifndef IM_ASSERT_USER_ERROR -#define IM_ASSERT_USER_ERROR(_EXPR,_MSG) do { if (!(_EXPR) && ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } } while (0) // Recoverable User Error +#define IM_ASSERT_USER_ERROR(_EXPR,_MSG) do { if (!(_EXPR)) { if (ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } } } while (0) // Recoverable User Error +#define IM_ASSERT_USER_ERROR_RET(_EXPR,_MSG) do { if (!(_EXPR)) { if (ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } return; } } while (0) // Recoverable User Error +#define IM_ASSERT_USER_ERROR_RETV(_EXPR,_RETV,_MSG) do { if (!(_EXPR)) { if (ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } return _RETV; } } while (0) // Recoverable User Error #endif // The error callback is currently not public, as it is expected that only advanced users will rely on it. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f5048e505..bb2be7631 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1348,11 +1348,7 @@ void ImGui::EndTable() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - if (table == NULL) - { - IM_ASSERT_USER_ERROR(table != NULL, "EndTable() call should only be done while in BeginTable() scope!"); - return; - } + IM_ASSERT_USER_ERROR_RET(table != NULL, "EndTable() call should only be done while in BeginTable() scope!"); // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) @@ -1601,18 +1597,10 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - if (table == NULL) - { - IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); - return; - } - IM_ASSERT(table->IsLayoutLocked == false && "TableSetupColumn(): need to call before first row!"); + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + IM_ASSERT_USER_ERROR_RET(table->DeclColumnsCount < table->ColumnsCount, "TableSetupColumn(): called too many times!"); + IM_ASSERT_USER_ERROR_RET(table->IsLayoutLocked == false, "TableSetupColumn(): need to call before first row!"); IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()"); - if (table->DeclColumnsCount >= table->ColumnsCount) - { - IM_ASSERT_USER_ERROR(table->DeclColumnsCount < table->ColumnsCount, "TableSetupColumn(): called too many times!"); - return; - } ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount]; table->DeclColumnsCount++; @@ -1620,10 +1608,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo // Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa. // Give a grace to users of ImGuiTableFlags_ScrollX. if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0) - { - IM_ASSERT_USER_ERROR(init_width_or_weight <= 0.0f, "TableSetupColumn(): can only specify width/weight if sizing policy is set explicitly in either Table or Column."); - return; - } + IM_ASSERT_USER_ERROR_RET(init_width_or_weight <= 0.0f, "TableSetupColumn(): can only specify width/weight if sizing policy is set explicitly in either Table or Column."); // When passing a width automatically enforce WidthFixed policy // (whereas TableSetupColumnFlags would default to WidthAuto if table is not resizable) @@ -1665,12 +1650,8 @@ void ImGui::TableSetupScrollFreeze(int columns, int rows) { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - if (table == NULL) - { - IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); - return; - } - IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!"); + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); + IM_ASSERT(table->IsLayoutLocked == false && "TableSetupColumn(): need to call before first row!"); IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS); IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit @@ -1746,11 +1727,7 @@ void ImGui::TableSetColumnEnabled(int column_n, bool enabled) { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - if (table == NULL) - { - IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); - return; - } + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above if (column_n < 0) column_n = table->CurrentColumn; @@ -1828,12 +1805,8 @@ void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); IM_ASSERT(target != ImGuiTableBgTarget_None); - if (table == NULL) - { - IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); - return; - } if (color == IM_COL32_DISABLE) color = 0; @@ -2131,11 +2104,7 @@ bool ImGui::TableSetColumnIndex(int column_n) { if (table->CurrentColumn != -1) TableEndCell(table); - if ((column_n >= 0 && column_n < table->ColumnsCount) == false) - { - IM_ASSERT_USER_ERROR(column_n >= 0 && column_n < table->ColumnsCount, "TableSetColumnIndex() invalid column index!"); - return false; - } + IM_ASSERT_USER_ERROR_RETV(column_n >= 0 && column_n < table->ColumnsCount, false, "TableSetColumnIndex() invalid column index!"); TableBeginCell(table, column_n); } @@ -3121,11 +3090,7 @@ void ImGui::TableHeadersRow() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - if (table == NULL) - { - IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); - return; - } + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); // Call layout if not already done. This is automatically done by TableNextRow: we do it here _only_ to make // it easier to debug-step in TableUpdateLayout(). Your own version of this function doesn't need this. @@ -3170,12 +3135,7 @@ void ImGui::TableHeader(const char* label) return; ImGuiTable* table = g.CurrentTable; - if (table == NULL) - { - IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); - return; - } - + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); IM_ASSERT(table->CurrentColumn != -1); const int column_n = table->CurrentColumn; ImGuiTableColumn* column = &table->Columns[column_n]; @@ -3350,11 +3310,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label ImGuiTable* table = g.CurrentTable; ImGuiWindow* window = g.CurrentWindow; ImDrawList* draw_list = window->DrawList; - if (table == NULL) - { - IM_ASSERT_USER_ERROR(table != NULL, "Call should only be done while in BeginTable() scope!"); - return; - } + IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!"); IM_ASSERT(table->CurrentRow == -1 && "Must be first row"); if (max_label_width == 0.0f) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0a044a97b..e64c59eac 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2065,10 +2065,7 @@ void ImGui::EndCombo() char name[16]; ImFormatString(name, IM_COUNTOF(name), "##Combo_%02d", g.BeginComboDepth); // FIXME: Move those to helpers? if (strcmp(g.CurrentWindow->Name, name) != 0) - { - IM_ASSERT_USER_ERROR(0, "Calling EndCombo() in wrong window!"); - return; - } + IM_ASSERT_USER_ERROR_RET(0, "Calling EndCombo() in wrong window!"); EndPopup(); } @@ -9150,11 +9147,7 @@ bool ImGui::BeginMainMenuBar() void ImGui::EndMainMenuBar() { ImGuiContext& g = *GImGui; - if (!g.CurrentWindow->DC.MenuBarAppending) - { - IM_ASSERT_USER_ERROR(0, "Calling EndMainMenuBar() not from a menu-bar!"); // Not technically testing that it is the main menu bar - return; - } + IM_ASSERT_USER_ERROR_RET(g.CurrentWindow->DC.MenuBarAppending, "Calling EndMainMenuBar() not from a menu-bar!"); // Not technically testing that it is the main menu bar EndMenuBar(); g.CurrentWindow->Flags |= ImGuiWindowFlags_NoSavedSettings; // Restore _NoSavedSettings (#8356) @@ -9414,12 +9407,8 @@ void ImGui::EndMenu() // Nav: When a left move request our menu failed, close ourselves. ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT_USER_ERROR_RET((window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu), "Calling EndMenu() in wrong window!"); - if ((window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) != (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) - { - IM_ASSERT_USER_ERROR(0, "Calling EndMenu() in wrong window!"); - return; - } ImGuiWindow* parent_window = window->ParentWindow; // Should always be != NULL is we passed assert. if (window->BeginCount == window->BeginCountPreviousFrame) if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet()) @@ -9716,11 +9705,7 @@ void ImGui::EndTabBar() return; ImGuiTabBar* tab_bar = g.CurrentTabBar; - if (tab_bar == NULL) - { - IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!"); - return; - } + IM_ASSERT_USER_ERROR_RET(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!"); // Fallback in case no TabItem have been submitted if (tab_bar->WantLayout) @@ -10361,11 +10346,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f return false; ImGuiTabBar* tab_bar = g.CurrentTabBar; - if (tab_bar == NULL) - { - IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); - return false; - } + IM_ASSERT_USER_ERROR_RETV(tab_bar != NULL, false, "Needs to be called between BeginTabBar() and EndTabBar()!"); IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL); @@ -10385,11 +10366,7 @@ void ImGui::EndTabItem() return; ImGuiTabBar* tab_bar = g.CurrentTabBar; - if (tab_bar == NULL) - { - IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); - return; - } + IM_ASSERT_USER_ERROR_RET(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); IM_ASSERT(tab_bar->LastTabItemIdx >= 0); ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) @@ -10404,11 +10381,7 @@ bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) return false; ImGuiTabBar* tab_bar = g.CurrentTabBar; - if (tab_bar == NULL) - { - IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); - return false; - } + IM_ASSERT_USER_ERROR_RETV(tab_bar != NULL, false, "Needs to be called between BeginTabBar() and EndTabBar()!"); return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder, NULL); } @@ -10420,11 +10393,7 @@ void ImGui::TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float return; ImGuiTabBar* tab_bar = g.CurrentTabBar; - if (tab_bar == NULL) - { - IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); - return; - } + IM_ASSERT_USER_ERROR_RET(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); SetNextItemWidth(width); TabItemEx(tab_bar, str_id, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder | ImGuiTabItemFlags_Invisible, NULL); } From b933599f00c1ec3a9c4fe0ab34710bad10063aa6 Mon Sep 17 00:00:00 2001 From: thedmd Date: Sat, 27 Sep 2025 15:09:52 +0200 Subject: [PATCH 1618/2359] Backends: DirectX12: added helpers to switch to Linear sampler (yet not made public, but intended to be forward declared). (#9173) --- backends/imgui_impl_dx12.cpp | 63 +++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 12 deletions(-) diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 056d23a6c..a5420782a 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -93,8 +93,10 @@ struct ImGui_ImplDX12_Data ImGui_ImplDX12_InitInfo InitInfo; IDXGIFactory5* pdxgiFactory; ID3D12Device* pd3dDevice; - ID3D12RootSignature* pRootSignature; - ID3D12PipelineState* pPipelineState; + ID3D12RootSignature* pRootSignatureLinear; + ID3D12RootSignature* pRootSignatureNearest; + ID3D12PipelineState* pPipelineStateLinear; + ID3D12PipelineState* pPipelineStateNearest; ID3D12CommandQueue* pCommandQueue; bool commandQueueOwned; DXGI_FORMAT RTVFormat; @@ -140,11 +142,27 @@ struct VERTEX_CONSTANT_BUFFER_DX12 float mvp[4][4]; }; +// FIXME-WIP: Allow user to forward declare those two, for until we come up with a backend agnostic API to do this. (#9173) +void ImGui_ImplDX12_SetupSamplerLinear(ID3D12GraphicsCommandList* command_list); +void ImGui_ImplDX12_SetupSamplerNearest(ID3D12GraphicsCommandList* command_list); + // Functions -static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr) +void ImGui_ImplDX12_SetupSamplerLinear(ID3D12GraphicsCommandList* command_list) { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + command_list->SetPipelineState(bd->pPipelineStateLinear); + command_list->SetGraphicsRootSignature(bd->pRootSignatureLinear); +} +void ImGui_ImplDX12_SetupSamplerNearest(ID3D12GraphicsCommandList* command_list) +{ + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + command_list->SetPipelineState(bd->pPipelineStateNearest); + command_list->SetGraphicsRootSignature(bd->pRootSignatureNearest); +} + +static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr) +{ // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer; @@ -186,8 +204,7 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; command_list->IASetIndexBuffer(&ibv); command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - command_list->SetPipelineState(bd->pPipelineState); - command_list->SetGraphicsRootSignature(bd->pRootSignature); + ImGui_ImplDX12_SetupSamplerLinear(command_list); command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); // Setup blend factor @@ -555,7 +572,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); if (!bd || !bd->pd3dDevice) return false; - if (bd->pPipelineState) + if (bd->pPipelineStateLinear) ImGui_ImplDX12_InvalidateDeviceObjects(); HRESULT hr = ::CreateDXGIFactory1(IID_PPV_ARGS(&bd->pdxgiFactory)); @@ -644,7 +661,15 @@ bool ImGui_ImplDX12_CreateDeviceObjects() if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK) return false; - bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature)); + bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignatureLinear)); + blob->Release(); + + // Root Signature for ImDrawCallback_SetSamplerNearest + staticSampler[0].Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK) + return false; + + bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignatureNearest)); blob->Release(); } @@ -657,7 +682,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.NodeMask = 1; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.pRootSignature = bd->pRootSignature; + psoDesc.pRootSignature = bd->pRootSignatureLinear; psoDesc.SampleMask = UINT_MAX; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = bd->RTVFormat; @@ -780,7 +805,18 @@ bool ImGui_ImplDX12_CreateDeviceObjects() desc.BackFace = desc.FrontFace; } - HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState)); + HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineStateLinear)); + if (result_pipeline_state != S_OK) + { + vertexShaderBlob->Release(); + pixelShaderBlob->Release(); + return false; + } + + // Pipeline State for ImDrawCallback_SetSamplerNearest + psoDesc.pRootSignature = bd->pRootSignatureNearest; + + result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineStateNearest)); vertexShaderBlob->Release(); pixelShaderBlob->Release(); if (result_pipeline_state != S_OK) @@ -813,8 +849,11 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() if (bd->commandQueueOwned) SafeRelease(bd->pCommandQueue); bd->commandQueueOwned = false; - SafeRelease(bd->pRootSignature); - SafeRelease(bd->pPipelineState); + SafeRelease(bd->pRootSignatureLinear); + SafeRelease(bd->pRootSignatureNearest); + SafeRelease(bd->pPipelineStateLinear); + SafeRelease(bd->pPipelineStateNearest); + if (bd->pTexUploadBufferMapped) { D3D12_RANGE range = { 0, bd->pTexUploadBufferSize }; @@ -961,7 +1000,7 @@ void ImGui_ImplDX12_NewFrame() ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?"); - if (!bd->pPipelineState) + if (!bd->pPipelineStateLinear) if (!ImGui_ImplDX12_CreateDeviceObjects()) IM_ASSERT(0 && "ImGui_ImplDX12_CreateDeviceObjects() failed!"); } From 8b86c939c7eb5346784d1030102f2236a3bd547c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Sep 2025 16:26:58 +0200 Subject: [PATCH 1619/2359] Backends: DirectX10, DirectX11, SDLGPU3: added nearest sampler in ImGui_ImplDX10_RenderState/ImGui_ImplDX11_RenderState/ImGui_ImplSDLGPU3_RenderState struct. (#6969, #5834, #7468, #3590, #9173, #8926, #7230, #5118, #3590, #2973, #6969) --- backends/imgui_impl_dx10.cpp | 8 +++++++- backends/imgui_impl_dx10.h | 3 ++- backends/imgui_impl_dx11.cpp | 8 +++++++- backends/imgui_impl_dx11.h | 3 ++- backends/imgui_impl_sdlgpu3.cpp | 11 +++++++++-- backends/imgui_impl_sdlgpu3.h | 3 ++- docs/CHANGELOG.txt | 5 +++++ 7 files changed, 34 insertions(+), 7 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index 5650a3c85..118798325 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -16,6 +16,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-01-19: DirectX11: Added 'SamplerNearest' in ImGui_ImplDX11_RenderState. Renamed 'SamplerDefault' to 'SamplerLinear'. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: DirectX10: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX10: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). @@ -75,6 +76,7 @@ struct ImGui_ImplDX10_Data ID3D10Buffer* pVertexConstantBuffer; ID3D10PixelShader* pPixelShader; ID3D10SamplerState* pTexSamplerLinear; + ID3D10SamplerState* pTexSamplerNearest; ID3D10RasterizerState* pRasterizerState; ID3D10BlendState* pBlendState; ID3D10DepthStencilState* pDepthStencilState; @@ -258,7 +260,8 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplDX10_RenderState render_state; render_state.Device = bd->pd3dDevice; - render_state.SamplerDefault = bd->pTexSamplerLinear; + render_state.SamplerLinear = bd->pTexSamplerLinear; + render_state.SamplerNearest = bd->pTexSamplerNearest; render_state.VertexConstantBuffer = bd->pVertexConstantBuffer; platform_io.Renderer_RenderState = &render_state; @@ -565,6 +568,8 @@ bool ImGui_ImplDX10_CreateDeviceObjects() desc.MinLOD = 0.f; desc.MaxLOD = 0.f; bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerLinear); + desc.Filter = D3D10_FILTER_MIN_MAG_MIP_POINT; + bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerNearest); } return true; @@ -581,6 +586,7 @@ void ImGui_ImplDX10_InvalidateDeviceObjects() if (tex->RefCount == 1) ImGui_ImplDX10_DestroyTexture(tex); if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; } + if (bd->pTexSamplerNearest) { bd->pTexSamplerNearest->Release(); bd->pTexSamplerNearest = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h index 9d7fb68ae..87945d64e 100644 --- a/backends/imgui_impl_dx10.h +++ b/backends/imgui_impl_dx10.h @@ -41,7 +41,8 @@ IMGUI_IMPL_API void ImGui_ImplDX10_UpdateTexture(ImTextureData* tex); struct ImGui_ImplDX10_RenderState { ID3D10Device* Device; - ID3D10SamplerState* SamplerDefault; + ID3D10SamplerState* SamplerLinear; + ID3D10SamplerState* SamplerNearest; ID3D10Buffer* VertexConstantBuffer; }; diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index 878930404..193127b4e 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-01-19: DirectX11: Added 'SamplerNearest' in ImGui_ImplDX11_RenderState. Renamed 'SamplerDefault' to 'SamplerLinear'. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. // 2025-06-11: DirectX11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. // 2025-05-07: DirectX11: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows). @@ -78,6 +79,7 @@ struct ImGui_ImplDX11_Data ID3D11Buffer* pVertexConstantBuffer; ID3D11PixelShader* pPixelShader; ID3D11SamplerState* pTexSamplerLinear; + ID3D11SamplerState* pTexSamplerNearest; ID3D11RasterizerState* pRasterizerState; ID3D11BlendState* pBlendState; ID3D11DepthStencilState* pDepthStencilState; @@ -272,7 +274,8 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX11_RenderState render_state; render_state.Device = bd->pd3dDevice; render_state.DeviceContext = bd->pd3dDeviceContext; - render_state.SamplerDefault = bd->pTexSamplerLinear; + render_state.SamplerLinear = bd->pTexSamplerLinear; + render_state.SamplerNearest = bd->pTexSamplerNearest; render_state.VertexConstantBuffer = bd->pVertexConstantBuffer; platform_io.Renderer_RenderState = &render_state; @@ -580,6 +583,8 @@ bool ImGui_ImplDX11_CreateDeviceObjects() desc.MinLOD = 0.f; desc.MaxLOD = 0.f; bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerLinear); + desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; + bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerNearest); } return true; @@ -597,6 +602,7 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() ImGui_ImplDX11_DestroyTexture(tex); if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; } + if (bd->pTexSamplerNearest) { bd->pTexSamplerNearest->Release(); bd->pTexSamplerNearest = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h index 1df4f3695..338e0093f 100644 --- a/backends/imgui_impl_dx11.h +++ b/backends/imgui_impl_dx11.h @@ -44,7 +44,8 @@ struct ImGui_ImplDX11_RenderState { ID3D11Device* Device; ID3D11DeviceContext* DeviceContext; - ID3D11SamplerState* SamplerDefault; + ID3D11SamplerState* SamplerLinear; + ID3D11SamplerState* SamplerNearest; ID3D11Buffer* VertexConstantBuffer; }; diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index e5934c302..9019c7de3 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -62,6 +62,7 @@ struct ImGui_ImplSDLGPU3_Data SDL_GPUShader* FragmentShader = nullptr; SDL_GPUGraphicsPipeline* Pipeline = nullptr; SDL_GPUSampler* TexSamplerLinear = nullptr; + SDL_GPUSampler* TexSamplerNearest = nullptr; SDL_GPUTransferBuffer* TexTransferBuffer = nullptr; uint32_t TexTransferBufferSize = 0; @@ -236,7 +237,8 @@ void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffe ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplSDLGPU3_RenderState render_state; render_state.Device = bd->InitInfo.Device; - render_state.SamplerDefault = render_state.SamplerCurrent = bd->TexSamplerLinear; + render_state.SamplerLinear = render_state.SamplerCurrent = bd->TexSamplerLinear; + render_state.SamplerNearest = bd->TexSamplerNearest; platform_io.Renderer_RenderState = &render_state; ImGui_ImplSDLGPU3_SetupRenderState(draw_data, &render_state, pipeline, command_buffer, render_pass, fd, fb_width, fb_height); @@ -592,9 +594,14 @@ void ImGui_ImplSDLGPU3_CreateDeviceObjects() sampler_info.enable_anisotropy = false; sampler_info.max_anisotropy = 1.0f; sampler_info.enable_compare = false; - bd->TexSamplerLinear = SDL_CreateGPUSampler(v->Device, &sampler_info); IM_ASSERT(bd->TexSamplerLinear != nullptr && "Failed to create sampler, call SDL_GetError() for more information"); + + sampler_info.min_filter = SDL_GPU_FILTER_NEAREST; + sampler_info.mag_filter = SDL_GPU_FILTER_NEAREST; + sampler_info.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST; + bd->TexSamplerNearest = SDL_CreateGPUSampler(v->Device, &sampler_info); + IM_ASSERT(bd->TexSamplerNearest != nullptr && "Failed to create sampler, call SDL_GetError() for more information"); } ImGui_ImplSDLGPU3_CreateGraphicsPipeline(); diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index 12b6528f3..1c73dfd71 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -57,7 +57,8 @@ IMGUI_IMPL_API void ImGui_ImplSDLGPU3_UpdateTexture(ImTextureData* tex); struct ImGui_ImplSDLGPU3_RenderState { SDL_GPUDevice* Device; - SDL_GPUSampler* SamplerDefault; // Default sampler (bilinear filtering) + SDL_GPUSampler* SamplerLinear; // Bilinear filtering sampler + SDL_GPUSampler* SamplerNearest; // Nearest/point filtering sampler SDL_GPUSampler* SamplerCurrent; // Current sampler (may be changed by callback) }; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6dd87e848..e8ff5aa0d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -190,6 +190,10 @@ Other Changes: non-ASCII values to io.AddInputCharacter(). (#9099) - Debug Log: can output to debugger on Windows. (#5855) - Backends: + - DirectX10: added 'SamplerNearest' in ImGui_ImplDX10_RenderState. + (+renamed 'SamplerDefault' to 'SamplerLinear', which was tagged as beta API) + - DirectX11: added 'SamplerNearest' in ImGui_ImplDX11_RenderState. + (+renamed 'SamplerDefault' to 'SamplerLinear', which was tagged as beta API) - GLFW: Avoid repeated glfwSetCursor()/glfwSetInputMode() calls when unnecessary. Lowers overhead for very high framerates (e.g. 10k+ FPS). [@maxliani] - GLFW: Added IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND to @@ -198,6 +202,7 @@ Other Changes: platforms. (#8792, #9112) - SDL2, SDL3: changed GetClipboardText() handler to return NULL on error aka clipboard contents is not text. Consistent with other backends. (#9168) + - SDL_GPU3: added 'TexSamplerNearest' in ImGui_ImplSDLGPU3_RenderState. - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. (#9076) [@Niminem] From 8c0b41037151d3b3c0f81d8dbcb508bda8b0b6f5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Jan 2026 16:18:18 +0100 Subject: [PATCH 1620/2359] Docs: tweaks. --- backends/imgui_impl_win32.cpp | 2 +- backends/imgui_impl_win32.h | 4 ++-- docs/CHANGELOG.txt | 22 +++++++++++----------- examples/example_android_opengl3/main.cpp | 6 ------ 4 files changed, 14 insertions(+), 20 deletions(-) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index de3c6fbd6..c344a1417 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -830,7 +830,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPA // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, -// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. +// neither of which we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. //--------------------------------------------------------------------------------------------------------- // This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable. // ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically. diff --git a/backends/imgui_impl_win32.h b/backends/imgui_impl_win32.h index 5ae399e0e..d2a960059 100644 --- a/backends/imgui_impl_win32.h +++ b/backends/imgui_impl_win32.h @@ -26,7 +26,7 @@ IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd); IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(); -// Win32 message handler your application need to call. +// Win32 message handler your application needs to call. // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on from this helper. // - You should COPY the line below into your .cpp code to forward declare the function and then you can call it. // - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. @@ -40,7 +40,7 @@ extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, -// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. +// neither of which we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e8ff5aa0d..023ae0263 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -187,33 +187,33 @@ Other Changes: - Improve error handling and recovery for TableSetupColumn(). - Debug Tools: - Debug Log: fixed incorrectly printing characters in IO log when submitting - non-ASCII values to io.AddInputCharacter(). (#9099) + non-ASCII values to `io.AddInputCharacter()`. (#9099) - Debug Log: can output to debugger on Windows. (#5855) - Backends: - - DirectX10: added 'SamplerNearest' in ImGui_ImplDX10_RenderState. - (+renamed 'SamplerDefault' to 'SamplerLinear', which was tagged as beta API) - - DirectX11: added 'SamplerNearest' in ImGui_ImplDX11_RenderState. - (+renamed 'SamplerDefault' to 'SamplerLinear', which was tagged as beta API) - - GLFW: Avoid repeated glfwSetCursor()/glfwSetInputMode() calls when unnecessary. + - DirectX10: added `SamplerNearest` in `ImGui_ImplDX10_RenderState`. + (+renamed `SamplerDefault` to `SamplerLinear`, which was tagged as beta API) + - DirectX11: added `SamplerNearest` in ImGui_ImplDX11_RenderState. + (+renamed `SamplerDefault` to `SamplerLinear`, which was tagged as beta API) + - GLFW: Avoid repeated `glfwSetCursor()` / `glfwSetInputMode()` unnecessary calls. Lowers overhead for very high framerates (e.g. 10k+ FPS). [@maxliani] - GLFW: Added IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND to forcefully disable either. (#9109, #9116) - OpenGL3: Fixed embedded loader multiple init/shutdown cycles broken on some platforms. (#8792, #9112) - - SDL2, SDL3: changed GetClipboardText() handler to return NULL on error aka + - SDL2, SDL3: changed `GetClipboardText()` handler to return NULL on error aka clipboard contents is not text. Consistent with other backends. (#9168) - - SDL_GPU3: added 'TexSamplerNearest' in ImGui_ImplSDLGPU3_RenderState. + - SDL_GPU3: added `SamplerNearest` in `ImGui_ImplSDLGPU3_RenderState`. - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling - SDL_CreateGPUDevice() with SDL_GPU_SHADERFORMAT_MSL. (#9076) [@Niminem] + `SDL_CreateGPUDevice()` with `SDL_GPU_SHADERFORMAT_MSL`. (#9076) [@Niminem] - Vulkan: helper for creating a swapchain (used by examples and multi-viewports) selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on `cap.supportedCompositeAlpha`, which seems to be required on some Android devices. (#8784) [@FelixStach] - - Win32: handle WM_IME_CHAR/WM_IME_COMPOSITION to support Unicode inputs on + - Win32: handle `WM_IME_CHAR`/`WM_IME_COMPOSITION` to support Unicode inputs on MBCS (non-Unicode) Windows. (#9099, #3653, #5961) [@ulhc, @ocornut, @Othereum] - Examples: - - Win32+DirectX12: ignore seemingly incorrect D3D12_MESSAGE_ID_FENCE_ZERO_WAIT + - Win32+DirectX12: ignore seemingly incorrect `D3D12_MESSAGE_ID_FENCE_ZERO_WAIT` warning on startups on some setups. (#9084, #9093) [@RT2Code, @LeoGautheron] diff --git a/examples/example_android_opengl3/main.cpp b/examples/example_android_opengl3/main.cpp index 0de952dbd..7f60ac631 100644 --- a/examples/example_android_opengl3/main.cpp +++ b/examples/example_android_opengl3/main.cpp @@ -151,12 +151,6 @@ void Init(struct android_app* app) ImGui_ImplAndroid_Init(g_App->window); ImGui_ImplOpenGL3_Init("#version 300 es"); - // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author! - // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - // Setup scaling float main_scale = 2.0f; ImGuiStyle& style = ImGui::GetStyle(); From 3803203d47c18c3a55bdb594fc59f89a8d25afc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A1draic=20Slattery?= Date: Wed, 21 Jan 2026 17:34:30 +0100 Subject: [PATCH 1621/2359] CI: update outdated GitHub Actions versions (#9186) --- .github/workflows/build.yml | 24 ++++++++++++------------ .github/workflows/static-analysis.yml | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 46ff68912..9bc81bf81 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -28,7 +28,7 @@ jobs: VS_PATH: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\ MSBUILD_PATH: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\ steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 with: path: ${{ github.workspace }}/imgui @@ -274,7 +274,7 @@ jobs: working-directory: ${{ github.workspace }}/imgui steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 with: path: ${{ github.workspace }}/imgui @@ -514,7 +514,7 @@ jobs: working-directory: ${{ github.workspace }}/imgui steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 with: path: ${{ github.workspace }}/imgui @@ -596,7 +596,7 @@ jobs: name: Build - iOS steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Build example_apple_metal run: | @@ -608,7 +608,7 @@ jobs: name: Build - Emscripten steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Install Dependencies run: | @@ -651,7 +651,7 @@ jobs: name: Build - Android steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Build example_android_opengl3 run: | @@ -670,11 +670,11 @@ jobs: MSBUILD_PATH: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\ steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 with: path: ${{ github.workspace }}/imgui - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 continue-on-error: true with: fetch-depth: 1 @@ -725,11 +725,11 @@ jobs: working-directory: ${{ github.workspace }}/imgui steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 with: path: ${{ github.workspace }}/imgui - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 with: fetch-depth: 1 repository: ocornut/imgui_test_engine @@ -763,11 +763,11 @@ jobs: # working-directory: ${{ github.workspace }}/imgui # # steps: -# - uses: actions/checkout@v5 +# - uses: actions/checkout@v6 # with: # path: ${{ github.workspace }}/imgui # -# - uses: actions/checkout@v5 +# - uses: actions/checkout@v6 # with: # fetch-depth: 1 # repository: ocornut/imgui_test_engine diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 53db04764..295628368 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -12,7 +12,7 @@ jobs: PVS-Studio: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 From 42b7704b70f3e19e87183160fa88cac52396fa6d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 21 Jan 2026 18:18:55 +0100 Subject: [PATCH 1622/2359] InputText: add ImGuiInputTextState::SetSelection() helper + make TextSrc valid outside scope for non-read only fields. (#9174) --- imgui_internal.h | 3 ++- imgui_widgets.cpp | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5a1816547..3cc3ef512 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1233,7 +1233,7 @@ struct IMGUI_API ImGuiInputTextState ImGuiInputTextFlags Flags; // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set. ImGuiID ID; // widget id owning the text state int TextLen; // UTF-8 length of the string in TextA (in bytes) - const char* TextSrc; // == TextA.Data unless read-only, in which case == buf passed to InputText(). Field only set and valid _inside_ the call InputText() call. + const char* TextSrc; // == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call. ImVector TextA; // main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1). ImVector TextToRevertTo; // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered) ImVector CallbackTextBackup; // temporary storage for callback to support automatic reconcile of undo-stack @@ -1267,6 +1267,7 @@ struct IMGUI_API ImGuiInputTextState int GetCursorPos() const; int GetSelectionStart() const; int GetSelectionEnd() const; + void SetSelection(int start, int end); void SelectAll(); // Reload user buf (WIP #2890) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e64c59eac..c557ddbe6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4304,6 +4304,7 @@ void ImGuiInputTextState::ClearSelection() { Stb->select_start int ImGuiInputTextState::GetCursorPos() const { return Stb->cursor; } int ImGuiInputTextState::GetSelectionStart() const { return Stb->select_start; } int ImGuiInputTextState::GetSelectionEnd() const { return Stb->select_end; } +void ImGuiInputTextState::SetSelection(int start, int end) { Stb->select_start = start; Stb->cursor = Stb->select_end = end; } float ImGuiInputTextState::GetPreferredOffsetX() const { return Stb->has_preferred_x ? Stb->preferred_x : -1; } void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; } void ImGuiInputTextState::ReloadUserBufAndSelectAll() { WantReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; } @@ -5630,7 +5631,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ g.LastItemData.StatusFlags = item_data_backup.StatusFlags; } } - if (state) + if (state && is_readonly) state->TextSrc = NULL; // Log as text From f21307e5c9bac40acab906ed2e8a5ce53e4d137d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 21 Jan 2026 18:25:38 +0100 Subject: [PATCH 1623/2359] InputText: ImGuiInputTextCallbackData::SelectAll() sets CursorPos. Added SetSelection() helper. Context was for #9174 but not specific to it. --- docs/CHANGELOG.txt | 3 +++ imgui.h | 7 ++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 023ae0263..ff21dab57 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -154,6 +154,9 @@ Other Changes: - Added ImGuiSliderFlags_ColorMarkers to opt-in adding R/G/B/A color markers next to each components, in multi-components functions. - Added a way to select a specific marker color. +- InputText: + - ImGuiInputTextCallbackData::SelectAll() also sets CursorPos to SelectionEnd. + - Added ImGuiInputTextCallbackData::SetSelection() helper. - Text, InputText: - Reworked word-wrapping logic: - Try to not wrap in the middle of contiguous punctuations. (#8139, #8439, #9094) diff --git a/imgui.h b/imgui.h index 448221dce..6baa6d746 100644 --- a/imgui.h +++ b/imgui.h @@ -2650,9 +2650,10 @@ struct ImGuiInputTextCallbackData 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; SelectionEnd = BufTextLen; } - void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } - bool HasSelection() const { return SelectionStart != SelectionEnd; } + void SelectAll() { SelectionStart = 0; CursorPos = 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; } }; // Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). From d448045669b317aa8377039e53ef801a8f697c8c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 21 Jan 2026 18:34:28 +0100 Subject: [PATCH 1624/2359] InputText: Added ImGuiInputTextCallbackData::ID field. --- docs/CHANGELOG.txt | 3 ++- imgui.h | 5 +++-- imgui_widgets.cpp | 22 +++++++++++++--------- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ff21dab57..afa1d5534 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -155,8 +155,9 @@ Other Changes: next to each components, in multi-components functions. - Added a way to select a specific marker color. - InputText: - - ImGuiInputTextCallbackData::SelectAll() also sets CursorPos to SelectionEnd. + - Made ImGuiInputTextCallbackData::SelectAll() also sets CursorPos to SelectionEnd. - Added ImGuiInputTextCallbackData::SetSelection() helper. + - Added ImGuiInputTextCallbackData::ID field. - Text, InputText: - Reworked word-wrapping logic: - Try to not wrap in the middle of contiguous punctuations. (#8139, #8439, #9094) diff --git a/imgui.h b/imgui.h index 6baa6d746..01e5113d7 100644 --- a/imgui.h +++ b/imgui.h @@ -2629,18 +2629,19 @@ struct ImGuiInputTextCallbackData ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only void* UserData; // What user passed to InputText() // Read-only + ImGuiID ID; // Widget ID // Read-only // Arguments for the different callback events // - During Resize callback, Buf will be same as your input buffer. // - However, during Completion/History/Always callback, Buf always points to our own internal data (it is not the same as your buffer)! Changes to it will be reflected into your own buffer shortly after the callback. // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. - ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] + ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; + bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land: == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 - bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] int CursorPos; // // Read-write // [Completion,History,Always] int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection int SelectionEnd; // // Read-write // [Completion,History,Always] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c557ddbe6..17e69c3b5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -134,7 +134,7 @@ static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); //------------------------------------------------------------------------- // For InputTextEx() -static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false); +static bool InputTextFilterCharacter(ImGuiContext* ctx, ImGuiInputTextState* state, unsigned int* p_char, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false); static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining = NULL, ImVec2* out_offset = NULL, ImDrawTextFlags flags = 0); //------------------------------------------------------------------------- @@ -4409,9 +4409,10 @@ void ImGui::PopPasswordFont() } // Return false to discard a character. -static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard) +static bool InputTextFilterCharacter(ImGuiContext* ctx, ImGuiInputTextState* state, unsigned int* p_char, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard) { unsigned int c = *p_char; + ImGuiInputTextFlags flags = state->Flags; // Filter non-printable (NB: isprint is unreliable! see #2467) bool apply_named_filters = true; @@ -4501,9 +4502,10 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, Im ImGuiContext& g = *GImGui; ImGuiInputTextCallbackData callback_data; callback_data.Ctx = &g; + callback_data.ID = state->ID; + callback_data.Flags = flags; callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; - callback_data.Flags = flags; callback_data.UserData = user_data; if (callback(&callback_data) != 0) return false; @@ -5020,7 +5022,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (Shortcut(ImGuiKey_Tab, ImGuiInputFlags_Repeat, id)) { unsigned int c = '\t'; // Insert TAB - if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data)) + if (InputTextFilterCharacter(&g, state, &c, callback, callback_user_data)) state->OnCharPressed(c); } // FIXME: Implement Shift+Tab @@ -5043,7 +5045,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ unsigned int c = (unsigned int)io.InputQueueCharacters[n]; if (c == '\t') // Skip Tab, see above. continue; - if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data)) + if (InputTextFilterCharacter(&g, state, &c, callback, callback_user_data)) state->OnCharPressed(c); } @@ -5129,7 +5131,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Insert new line unsigned int c = '\n'; - if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data)) + if (InputTextFilterCharacter(&g, state, &c, callback, callback_user_data)) state->OnCharPressed(c); } } @@ -5198,7 +5200,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ unsigned int c; int in_len = ImTextCharFromUtf8(&c, s, clipboard_end); s += in_len; - if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true)) + if (!InputTextFilterCharacter(&g, state, &c, callback, callback_user_data, true)) continue; char c_utf8[5]; ImTextCharToUtf8(c_utf8, c); @@ -5297,8 +5299,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { ImGuiInputTextCallbackData callback_data; callback_data.Ctx = &g; - callback_data.EventFlag = event_flag; + callback_data.ID = id; callback_data.Flags = flags; + callback_data.EventFlag = event_flag; callback_data.UserData = callback_user_data; // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925 @@ -5374,8 +5377,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { ImGuiInputTextCallbackData callback_data; callback_data.Ctx = &g; - callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize; + callback_data.ID = id; callback_data.Flags = flags; + callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize; callback_data.Buf = buf; callback_data.BufTextLen = apply_new_text_length; callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1); From cb3b7ff4fbdb7ff47cb81a0e78322110c8f4b2d3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 21 Jan 2026 18:46:38 +0100 Subject: [PATCH 1625/2359] InputText: added mGuiInputTextCallbackData::EventActive helpers. (#9174) --- docs/CHANGELOG.txt | 6 +++--- imgui.h | 1 + imgui_widgets.cpp | 3 +++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index afa1d5534..4324c69ef 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -155,9 +155,9 @@ Other Changes: next to each components, in multi-components functions. - Added a way to select a specific marker color. - InputText: - - Made ImGuiInputTextCallbackData::SelectAll() also sets CursorPos to SelectionEnd. - - Added ImGuiInputTextCallbackData::SetSelection() helper. - - Added ImGuiInputTextCallbackData::ID field. + - ImGuiInputTextCallbackData: SelectAll() also sets CursorPos to SelectionEnd. + - ImGuiInputTextCallbackData: Added SetSelection() helper. + - ImGuiInputTextCallbackData: Added ID and EventActive helpers. (#9174) - Text, InputText: - Reworked word-wrapping logic: - Try to not wrap in the middle of contiguous punctuations. (#8139, #8439, #9094) diff --git a/imgui.h b/imgui.h index 01e5113d7..4a9af9b7a 100644 --- a/imgui.h +++ b/imgui.h @@ -2638,6 +2638,7 @@ struct ImGuiInputTextCallbackData // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; + bool EventActivated; // Input field just got activated // Read-only // [Always] bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 17e69c3b5..8faf35e50 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4506,6 +4506,7 @@ static bool InputTextFilterCharacter(ImGuiContext* ctx, ImGuiInputTextState* sta callback_data.Flags = flags; callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; + callback_data.EventActivated = (g.ActiveId == state->ID && g.ActiveIdIsJustActivated); callback_data.UserData = user_data; if (callback(&callback_data) != 0) return false; @@ -5302,6 +5303,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ callback_data.ID = id; callback_data.Flags = flags; callback_data.EventFlag = event_flag; + callback_data.EventActivated = (g.ActiveId == state->ID && g.ActiveIdIsJustActivated); callback_data.UserData = callback_user_data; // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925 @@ -5380,6 +5382,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ callback_data.ID = id; callback_data.Flags = flags; callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize; + callback_data.EventActivated = (g.ActiveId == state->ID && g.ActiveIdIsJustActivated); callback_data.Buf = buf; callback_data.BufTextLen = apply_new_text_length; callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1); From 3aba95060ec7960e2c1c7d65163756b9d9c1e419 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 21 Jan 2026 19:53:31 +0100 Subject: [PATCH 1626/2359] Fonts: adding new fonts after removing all fonts mid-frame properly updates current state. --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4324c69ef..63235b2c2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -128,6 +128,7 @@ Other Changes: is enabled, creating side-effects when later disabling hinting or dynamically switching to stb_truetype rasterizer. - Post rescale GlyphOffset is always rounded. + - Adding new fonts after removing all fonts mid-frame properly updates current state. - Textures: - Fixed a building issue when ImTextureID is defined as a struct. - Fixed displaying texture # in Metrics/Debugger window. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 780f6b844..9889b2884 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3035,6 +3035,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) ImFontAtlasBuildInit(this); // Create new font + const bool is_first_font = (Fonts.Size == 0); ImFont* font; if (!font_cfg_in->MergeMode) { @@ -3092,6 +3093,8 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) } ImFontAtlasFontSourceAddToFont(this, font, font_cfg); + if (is_first_font) + ImFontAtlasBuildNotifySetFont(this, NULL, font); return font; } @@ -3254,6 +3257,9 @@ void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* shared_data->Font = new_font; if (ImGuiContext* ctx = shared_data->Context) { + if (ctx->FrameCount == 0 && old_font == NULL) // While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed. + continue; + if (ctx->IO.FontDefault == old_font) ctx->IO.FontDefault = new_font; if (ctx->Font == old_font) From 66bb8add7333b0fea779de5a7749198c2294d9a4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Jan 2026 14:28:46 +0100 Subject: [PATCH 1627/2359] Docs: better document Shortcut() related stuff. (#9188) Better document io.ConfigDpiScaleFonts. (#9179) --- docs/FAQ.md | 4 ++-- examples/example_glfw_metal/main.mm | 2 +- examples/example_glfw_opengl2/main.cpp | 2 +- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_glfw_vulkan/main.cpp | 2 +- examples/example_glfw_wgpu/main.cpp | 2 +- examples/example_sdl2_directx11/main.cpp | 2 +- examples/example_sdl2_opengl2/main.cpp | 2 +- examples/example_sdl2_opengl3/main.cpp | 2 +- examples/example_sdl2_sdlrenderer2/main.cpp | 2 +- examples/example_sdl2_vulkan/main.cpp | 2 +- examples/example_sdl2_wgpu/main.cpp | 2 +- examples/example_sdl3_directx11/main.cpp | 2 +- examples/example_sdl3_metal/main.mm | 2 +- examples/example_sdl3_opengl3/main.cpp | 2 +- examples/example_sdl3_sdlgpu3/main.cpp | 2 +- examples/example_sdl3_sdlrenderer3/main.cpp | 2 +- examples/example_sdl3_vulkan/main.cpp | 2 +- examples/example_sdl3_wgpu/main.cpp | 2 +- examples/example_win32_directx10/main.cpp | 2 +- examples/example_win32_directx11/main.cpp | 2 +- examples/example_win32_directx12/main.cpp | 2 +- examples/example_win32_directx9/main.cpp | 2 +- examples/example_win32_opengl3/main.cpp | 2 +- examples/example_win32_vulkan/main.cpp | 2 +- imgui.cpp | 2 +- imgui.h | 25 +++++++++++++-------- 27 files changed, 43 insertions(+), 36 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 282c65c3f..6c9526aa7 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -678,8 +678,8 @@ ImGui::PushFont(new_font, 42.0f); In `docking` branch or with multi-viewports: ```cpp -io.ConfigDpiScaleFonts = true; // Automatically overwrite style.FontScaleDpi in Begin() when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now. -io.ConfigDpiScaleViewports = true; // Scale Dear ImGui and Platform Windows when Monitor DPI changes. +io.ConfigDpiScaleFonts = true; // (Docking branch only) Automatically overwrite style.FontScaleDpi in Begin() when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now. +io.ConfigDpiScaleViewports = true; // (Docking branch only) Scale Dear ImGui and Platform Windows when Monitor DPI changes. ``` **Scaling style** (paddings, spacings, thicknesses) diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index 9627de70e..b6a802106 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -52,7 +52,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) id device = MTLCreateSystemDefaultDevice(); id commandQueue = [device newCommandQueue]; diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 4fa8b0792..52d3612d3 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -61,7 +61,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index af21d9094..98af19d21 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -92,7 +92,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index ccce94fb5..2ee284044 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -397,7 +397,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForVulkan(window, true); diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 60662b031..cea13682e 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -98,7 +98,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOther(window, true); diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index 1018913bc..65e4ca49c 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -83,7 +83,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForD3D(window); diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index 59cd7ed8e..cc3cce022 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -72,7 +72,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(window, gl_context); diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index 43e5aad0c..dea16869c 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -112,7 +112,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(window, gl_context); diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 9ede2cac8..5021039cf 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -74,7 +74,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForSDLRenderer(window, renderer); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 87a38ff90..49a6acfa9 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -403,7 +403,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForVulkan(window); diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index cddce3e63..1b24e1c51 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -81,7 +81,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOther(window); diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index 06d8ea505..88d7189a6 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -74,7 +74,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForD3D(window); diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index 9c9eab54a..b6dc5aa60 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -70,7 +70,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplMetal_Init(layer.device); diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 1b0e100e4..e5fa6d5a9 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -102,7 +102,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForOpenGL(window, gl_context); diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 3372d56b0..9d5dd31a4 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -76,7 +76,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForSDLGPU(window); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index e275e5f07..82ccec6ef 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -64,7 +64,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForSDLRenderer(window, renderer); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 38c48d3a7..705d6b523 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -402,7 +402,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForVulkan(window); diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index b5ae84bfd..cdf819e8b 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -88,7 +88,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplSDL3_InitForOther(window); diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 6a7687537..3a3b8e17e 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -65,7 +65,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 9ca7705fb..50fce7e98 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -65,7 +65,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 85c598fb1..bb9e8161b 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -145,7 +145,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 2fe01420c..19174d4b0 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -63,7 +63,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index f83d693f9..d214aa93e 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -73,7 +73,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplWin32_InitForOpenGL(hwnd); diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 75c5605cf..9470ce96c 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -390,7 +390,7 @@ int main(int, char**) // Setup scaling ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) - style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose) + style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); diff --git a/imgui.cpp b/imgui.cpp index 151a17308..976216cb6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9010,7 +9010,7 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) // Global scale factors final_size *= g.Style.FontScaleMain; // Main global scale factor - final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled. + final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor (in docking branch: automatically updated when io.ConfigDpiScaleFonts is enabled). // Window scale (mostly obsolete now) if (window != NULL) diff --git a/imgui.h b/imgui.h index 4a9af9b7a..936ce0add 100644 --- a/imgui.h +++ b/imgui.h @@ -1051,19 +1051,22 @@ namespace ImGui IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); - // Inputs Utilities: Keyboard/Mouse/Gamepad + // Inputs Utilities: Raw Keyboard/Mouse/Gamepad Access + // - Consider using the Shortcut() function instead of IsKeyPressed()/IsKeyChordPressed()! Shortcut() is easier to use and better featured (can do focus routing check). // - the ImGuiKey enum contains all possible keyboard, mouse and gamepad inputs (e.g. ImGuiKey_A, ImGuiKey_MouseLeft, ImGuiKey_GamepadDpadUp...). - // - (legacy: before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. This was obsoleted in 1.87 (2022-02) and completely removed in 1.91.5 (2024-11). See https://github.com/ocornut/imgui/issues/4921) - // - (legacy: any use of ImGuiKey will assert when key < 512 to detect passing legacy native/user indices) + // - (legacy: before v1.87 (2022-02), we used ImGuiKey < 512 values to carry native/user indices as defined by each backends. This was obsoleted in 1.87 (2022-02) and completely removed in 1.91.5 (2024-11). See https://github.com/ocornut/imgui/issues/4921) IMGUI_API bool IsKeyDown(ImGuiKey key); // is key being held. - IMGUI_API bool IsKeyPressed(ImGuiKey key, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyPressed(ImGuiKey key, bool repeat = true); // was key pressed (went from !Down to Down)? Repeat rate uses io.KeyRepeatDelay / KeyRepeatRate. IMGUI_API bool IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)? IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord); // was key chord (mods + key) pressed, e.g. you can pass 'ImGuiMod_Ctrl | ImGuiKey_S' as a key-chord. This doesn't do any routing or focus check, please consider using Shortcut() function instead. IMGUI_API int GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. IMGUI_API void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call. - // Inputs Utilities: Shortcut Testing & Routing [BETA] + // Inputs Utilities: Shortcut Testing & Routing + // - Typical use is e.g.: 'if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_S)) { ... }'. + // - Flags: Default route use ImGuiInputFlags_RouteFocused, but see ImGuiInputFlags_RouteGlobal and other options in ImGuiInputFlags_! + // - Flags: Use ImGuiInputFlags_Repeat to support repeat. // - ImGuiKeyChord = a ImGuiKey + optional ImGuiMod_Alt/ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Super. // ImGuiKey_C // Accepted by functions taking ImGuiKey or ImGuiKeyChord arguments // ImGuiMod_Ctrl | ImGuiKey_C // Accepted by functions taking ImGuiKeyChord arguments @@ -1075,8 +1078,10 @@ namespace ImGui // The whole system is order independent, so if Child1 makes its calls before Parent, results will be identical. // This is an important property as it facilitate working with foreign code or larger codebase. // - To understand the difference: - // - IsKeyChordPressed() compares mods and call IsKeyPressed() -> function has no side-effect. - // - Shortcut() submits a route, routes are resolved, if it currently can be routed it calls IsKeyChordPressed() -> function has (desirable) side-effects as it can prevents another call from getting the route. + // - IsKeyChordPressed() compares mods and call IsKeyPressed() + // -> the function has no side-effect. + // - Shortcut() submits a route, routes are resolved, if it currently can be routed it calls IsKeyChordPressed() + // -> the function has (desirable) side-effects as it can prevents another call from getting the route. // - Visualize registered routes in 'Metrics/Debugger->Inputs'. IMGUI_API bool Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0); IMGUI_API void SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0); @@ -1126,7 +1131,9 @@ namespace ImGui 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, which is also accessible from Demo->Tools->Metrics Debugger + // - 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 DebugFlashStyleColor(ImGuiCol idx); IMGUI_API void DebugStartItemPicker(); @@ -2271,7 +2278,7 @@ struct ImGuiStyle // - recap: ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors) float FontSizeBase; // Current base font size before external global factors are applied. Use PushFont(NULL, size) to modify. Use ImGui::GetFontSize() to obtain scaled value. float FontScaleMain; // Main global scale factor. May be set by application once, or exposed to end-user. - float FontScaleDpi; // Additional global scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. + float FontScaleDpi; // Additional global scale factor from viewport/monitor contents scale. In docking branch: when io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. From 3050f653cb5b6c79875659c4ac4bf43f9678e588 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Jan 2026 17:33:35 +0100 Subject: [PATCH 1628/2359] Menus, Nav: made navigation into menu-bar auto wrap on X axis. (#9178) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 2 +- imgui_widgets.cpp | 4 ++++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 63235b2c2..bd7715e2c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -135,6 +135,7 @@ Other Changes: - Menus: - Fixed MenuItem() label position and BeginMenu() arrow/icon/popup positions, when used inside a line with a baseline offset. + - Made navigation into menu-bar auto wrap on X axis. (#9178) - TreeNode: - Fixed highlight position when used inside a line with a large text baseline offset. (never quite worked in this situation; but then most of the time the text diff --git a/imgui.cpp b/imgui.cpp index 976216cb6..1f7115159 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13436,7 +13436,7 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wra // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it: // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest(). - if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main) + if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == window->DC.NavLayerCurrent) g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8faf35e50..de19ecf28 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9070,6 +9070,10 @@ void ImGui::EndMenuBar() NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat } } + else + { + NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_WrapX); + } PopClipRect(); PopID(); From b015acc464655943cd9e74444b8339b4baaec348 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Jan 2026 17:50:25 +0100 Subject: [PATCH 1629/2359] Viewports: added GetWindowViewport() in imgui_internal.h to increase consistency with code using this public API in docking branch. (#9140) --- imgui_internal.h | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_internal.h b/imgui_internal.h index 3cc3ef512..e8618ccc5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3223,6 +3223,7 @@ namespace ImGui IMGUI_API void UpdateMouseMovingWindowEndFrame(); // Viewports + inline ImGuiViewport* GetWindowViewport() { return GetMainViewport(); } // For code consistency. This is public API in docking branch. IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale); IMGUI_API void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport); From a117055b6b8c549be838cef73b29fd6d5d4218f1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 22 Jan 2026 18:24:12 +0100 Subject: [PATCH 1630/2359] Internals: move field for locality. --- imgui.cpp | 13 +++++++------ imgui_internal.h | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1f7115159..12c51ccb1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7975,13 +7975,14 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; // Default item width. Make it proportional to window size if window manually resizes - if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) - window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f); + const bool is_resizable_window = (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)); + if (is_resizable_window) + window->DC.ItemWidthDefault = ImTrunc(window->Size.x * 0.65f); else - window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f); - window->DC.ItemWidth = window->ItemWidthDefault; - window->DC.TextWrapPos = -1.0f; // disabled + window->DC.ItemWidthDefault = ImTrunc(g.FontSize * 16.0f); + window->DC.ItemWidth = window->DC.ItemWidthDefault; window->DC.ItemWidthStack.resize(0); + window->DC.TextWrapPos = -1.0f; // Disabled window->DC.TextWrapPosStack.resize(0); if (flags & ImGuiWindowFlags_Modal) window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg)); @@ -11448,7 +11449,7 @@ void ImGui::PushItemWidth(float item_width) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width - window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); + window->DC.ItemWidth = (item_width == 0.0f ? window->DC.ItemWidthDefault : item_width); g.NextItemData.HasFlags &= ~ImGuiNextItemDataFlags_HasWidth; } diff --git a/imgui_internal.h b/imgui_internal.h index e8618ccc5..0f5e5d9cd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2625,6 +2625,7 @@ struct IMGUI_API ImGuiWindowTempData // Local parameters stacks // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. float ItemWidth; // Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window). + float ItemWidthDefault; float TextWrapPos; // Current text wrap pos. ImVector ItemWidthStack; // Store item widths to restore (attention: .back() is not == ItemWidth) ImVector TextWrapPosStack; // Store text wrap pos to restore (attention: .back() is not == TextWrapPos) @@ -2715,7 +2716,6 @@ struct IMGUI_API ImGuiWindow int LastFrameActive; // Last frame number the window was Active. float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) - float ItemWidthDefault; ImGuiStorage StateStorage; ImVector ColumnsStorage; float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() From 7250fbde2e08774b3758b784b2a9b1ad0b0a3d76 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Jan 2026 14:29:20 +0100 Subject: [PATCH 1631/2359] Fixed warning compiling stb_truetype with MSVC, C++20 with /w15262 (#9189) --- imgui_draw.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 9889b2884..4d386e56a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -104,6 +104,7 @@ namespace IMGUI_STB_NAMESPACE #pragma warning (push) #pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration #pragma warning (disable: 6011) // (stb_rectpack) Dereferencing NULL pointer 'cur->next'. +#pragma warning (disable: 5262) // (stb_truetype) implicit fall-through occurs here; are you missing a break statement? #pragma warning (disable: 6385) // (stb_truetype) Reading invalid data from 'buffer': the readable size is '_Old_3`kernel_width' bytes, but '3' bytes may be read. #pragma warning (disable: 28182) // (stb_rectpack) Dereferencing NULL pointer. 'cur' contains the same NULL value as 'cur->next' did. #endif From e1217227b29282733ff61de21fa82d324863c8e5 Mon Sep 17 00:00:00 2001 From: RegimantasSimkus <91128330+RegimantasSimkus@users.noreply.github.com> Date: Mon, 19 Jan 2026 17:05:13 +0000 Subject: [PATCH 1632/2359] Tooltips, Disabled: fixed EndDisabledOverrideReenable() assertion when nesting a tooltip in a disabled block. (#9180, #7640) Amend f953ebf9ca --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bd7715e2c..d3e44bf14 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -175,6 +175,8 @@ Other Changes: noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - InvisibleButton: allow calling with size (0,0) to fit to available content size. (#9166, #7623) +- Tooltips, Disabled: fixed EndDisabledOverrideReenable() assertion when + nesting a tooltip in a disabled block. (#9180, #7640) [@RegimantasSimkus] - Added GetItemFlags() in public API for consistency and to expose generic flags of last submitted item. (#9127) - Images: diff --git a/imgui.cpp b/imgui.cpp index 12c51ccb1..6f7738195 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8259,8 +8259,8 @@ void ImGui::BeginDisabledOverrideReenable() void ImGui::EndDisabledOverrideReenable() { ImGuiContext& g = *GImGui; - g.DisabledStackSize--; IM_ASSERT(g.DisabledStackSize > 0); + g.DisabledStackSize--; g.ItemFlagsStack.pop_back(); g.CurrentItemFlags = g.ItemFlagsStack.back(); g.Style.Alpha = g.CurrentWindowStack.back().DisabledOverrideReenableAlphaBackup; From d1cf58e590226402a016cd6c1e5b53c2212b7f41 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Jan 2026 16:00:28 +0100 Subject: [PATCH 1633/2359] Nav: fixed WrapX/LoopX handling in menu layer. (#9178) Amend 3050f653cb --- docs/CHANGELOG.txt | 1 + imgui.cpp | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d3e44bf14..e2f14edec 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -171,6 +171,7 @@ Other Changes: - Nav: - Fixed remote/shortcut InputText() not teleporting mouse cursor when nav cursor is visible and `io.ConfigNavMoveSetMousePos` is enabled. + - Fixed a looping/wrapping issue when done in menu layer. (#9178) - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - InvisibleButton: allow calling with size (0,0) to fit to available content diff --git a/imgui.cpp b/imgui.cpp index 6f7738195..5a49b8918 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14252,9 +14252,13 @@ static void ImGui::NavUpdateCreateWrappingRequest() const ImGuiNavMoveFlags move_flags = g.NavMoveFlags; //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X; + + // Menu layer does not maintain scrolling / content size (#9178) + ImVec2 wrap_size = (g.NavLayer == ImGuiNavLayer_Menu) ? window->Size : window->ContentSize + window->WindowPadding; + if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) { - bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x; + bb_rel.Min.x = bb_rel.Max.x = wrap_size.x; if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row @@ -14274,7 +14278,7 @@ static void ImGui::NavUpdateCreateWrappingRequest() } if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) { - bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y; + bb_rel.Min.y = bb_rel.Max.y = wrap_size.y; if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column From c6e54c7ab54f1c96bf4a501e79c809d0b47d4e1d Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 13 Jan 2026 16:38:58 +0100 Subject: [PATCH 1634/2359] Comments about input queue being close to be supporting multi-thread. (#5772) --- imgui.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 5a49b8918..5bbb31b9c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10483,6 +10483,8 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) #endif // Remaining events will be processed on the next frame + // FIXME-MULTITHREADING: io.AddKeyEvent() etc. calls are mostly thread-safe apart from the fact they push to this + // queue which may be resized here. Could potentially rework this to narrow down the section needing a mutex? (#5772) if (event_n == g.InputEventsQueue.Size) g.InputEventsQueue.resize(0); else From c91bcea7a8cb0271bbdb11f6f8c9c2e7cff8c84e Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 25 Jan 2026 13:30:19 +0100 Subject: [PATCH 1635/2359] Backends: SDLGPU3: fixed missing release of TexSamplerNearest. (#9196) Amend/fix 8b86c939c7e --- backends/imgui_impl_sdlgpu3.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 9019c7de3..975fcefb9 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -637,6 +637,7 @@ void ImGui_ImplSDLGPU3_DestroyDeviceObjects() if (bd->VertexShader) { SDL_ReleaseGPUShader(v->Device, bd->VertexShader); bd->VertexShader = nullptr; } if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->Device, bd->FragmentShader); bd->FragmentShader = nullptr; } if (bd->TexSamplerLinear) { SDL_ReleaseGPUSampler(v->Device, bd->TexSamplerLinear); bd->TexSamplerLinear = nullptr; } + if (bd->TexSamplerNearest) { SDL_ReleaseGPUSampler(v->Device, bd->TexSamplerNearest); bd->TexSamplerNearest = nullptr; } if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->Device, bd->Pipeline); bd->Pipeline = nullptr; } } From d12b1a938e27b4b71f4d7ae0995f6681ae47b7a9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 Jan 2026 11:37:55 +0100 Subject: [PATCH 1636/2359] Demo: improved Selectable() demos. (#9193) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- imgui_demo.cpp | 53 +++++++++++++++++++++++++++++++++++++--------- imgui_widgets.cpp | 1 + 4 files changed, 47 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e2f14edec..4e126395d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -198,6 +198,8 @@ Other Changes: - Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to `io.AddInputCharacter()`. (#9099) - Debug Log: can output to debugger on Windows. (#5855) +- Demo: + - Slightly improve Selectable() demos. (#9193) - Backends: - DirectX10: added `SamplerNearest` in `ImGui_ImplDX10_RenderState`. (+renamed `SamplerDefault` to `SamplerLinear`, which was tagged as beta API) diff --git a/imgui.h b/imgui.h index 936ce0add..0706da641 100644 --- a/imgui.h +++ b/imgui.h @@ -1880,7 +1880,7 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. - ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. + ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) ImGuiColorEditFlags_NoColorMarkers = 1 << 11, // // ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5db91155b..b88e7bf2a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2309,15 +2309,45 @@ static void DemoWindowWidgetsSelectables() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selectables/Rendering more items on the same line"); - if (ImGui::TreeNode("Rendering more items on the same line")) + IMGUI_DEMO_MARKER("Widgets/Selectables/Multiple items on the same line"); + if (ImGui::TreeNode("Multiple items on the same line")) { - // (1) Using SetNextItemAllowOverlap() - // (2) Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. - static bool selected[3] = { false, false, false }; - ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(); ImGui::SmallButton("Link 1"); - ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(); ImGui::SmallButton("Link 2"); - ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(); ImGui::SmallButton("Link 3"); + // (1) + // - Using SetNextItemAllowOverlap() + // - Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. + { + static bool selected[3] = {}; + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(); ImGui::SmallButton("Link 1"); + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("hello.cpp", &selected[1]); ImGui::SameLine(); ImGui::SmallButton("Link 2"); + ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("hello.h", &selected[2]); ImGui::SameLine(); ImGui::SmallButton("Link 3"); + } + + // (2) + // - Using ImGuiSelectableFlags_AllowOverlap is a shortcut for calling SetNextItemAllowOverlap() + // - No visible label, display contents inside the selectable bounds. + // - We don't maintain actual selection in this example to keep things simple. + ImGui::Spacing(); + { + static bool checked[5] = {}; + static int selected_n = 0; + const float color_marker_w = ImGui::CalcTextSize("x").x; + for (int n = 0; n < 5; n++) + { + ImGui::PushID(n); + ImGui::AlignTextToFramePadding(); + if (ImGui::Selectable("##selectable", selected_n == n, ImGuiSelectableFlags_AllowOverlap)) + selected_n = n; + ImGui::SameLine(0, 0); + ImGui::Checkbox("##check", &checked[n]); + ImGui::SameLine(); + ImVec4 color((n & 1) ? 1.0f : 0.2f, (n & 2) ? 1.0f : 0.2f, 0.2f, 1.0f); + ImGui::ColorButton("##color", color, ImGuiColorEditFlags_NoTooltip, ImVec2(color_marker_w, 0)); + ImGui::SameLine(); + ImGui::Text("Some label"); + ImGui::PopID(); + } + } + ImGui::TreePop(); } @@ -2368,13 +2398,14 @@ static void DemoWindowWidgetsSelectables() if (winning_state) ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f))); + const float size = ImGui::CalcTextSize("Sailor").x; for (int y = 0; y < 4; y++) for (int x = 0; x < 4; x++) { if (x > 0) ImGui::SameLine(); ImGui::PushID(y * 4 + x); - if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(50, 50))) + if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(size, size))) { // Toggle clicked cell + toggle neighbors selected[y][x] ^= 1; @@ -2397,7 +2428,9 @@ static void DemoWindowWidgetsSelectables() "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item " "basis using PushStyleVar(). You'll probably want to always keep your default situation to " "left-align otherwise it becomes difficult to layout multiple items on a same line"); + static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true }; + const float size = ImGui::CalcTextSize("(1.0,1.0)").x; for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) @@ -2407,7 +2440,7 @@ static void DemoWindowWidgetsSelectables() sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y); if (x > 0) ImGui::SameLine(); ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment); - ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80)); + ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(size, size)); ImGui::PopStyleVar(); } } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index de19ecf28..6dcb12a40 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6484,6 +6484,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl } // Initialize/override default color options +// FIXME: Could be moved to a simple IO field. void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) { ImGuiContext& g = *GImGui; From ab6c9d9b128485d2c596d1bfd3bf4a4fdbac7e26 Mon Sep 17 00:00:00 2001 From: Tom Seddon Date: Sat, 24 Jan 2026 17:21:23 +0000 Subject: [PATCH 1637/2359] Ignore -Wsign-conversion warnings when building with gcc. (#9192) Co-authored-by: Tom Seddon --- imgui.cpp | 1 + imgui_draw.cpp | 1 + imgui_internal.h | 1 + imgui_tables.cpp | 1 + imgui_widgets.cpp | 1 + 5 files changed, 5 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 5bbb31b9c..6894b5dcf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1279,6 +1279,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false #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 "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result #endif // Debug options diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4d386e56a..00e058351 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -82,6 +82,7 @@ Index of this file: #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1 #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 "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result #endif //------------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index 0f5e5d9cd..ad7a1479f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -106,6 +106,7 @@ Index of this file: #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 "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result #endif // In 1.89.4, we moved the implementation of "courtesy maths operators" from imgui_internal.h in imgui.h diff --git a/imgui_tables.cpp b/imgui_tables.cpp index bb2be7631..d4e57e831 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -240,6 +240,7 @@ Index of this file: #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 "-Wstrict-overflow" #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 "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result #endif //----------------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6dcb12a40..8911863da 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -92,6 +92,7 @@ Index of this file: #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1 #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 "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result #endif //------------------------------------------------------------------------- From 814c6a194bcb1172df8b8ac9d6520ac0e77654dc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 Jan 2026 12:29:42 +0100 Subject: [PATCH 1638/2359] Log/Capture: fixed erroneously injecting extra carriage returns in output. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4e126395d..ceba9c0a7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -180,6 +180,8 @@ Other Changes: nesting a tooltip in a disabled block. (#9180, #7640) [@RegimantasSimkus] - Added GetItemFlags() in public API for consistency and to expose generic flags of last submitted item. (#9127) +- Log/Capture: fixed erroneously injecting extra carriage returns in output + buffer when ItemSpacing.y > FramePadding.y + 1. - Images: - Added style.ImageRounding, ImGuiStyleVar_ImageRounding to configure rounding of Image() widgets. (#2942, #845) diff --git a/imgui.cpp b/imgui.cpp index 6894b5dcf..7f8710cd9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15071,7 +15071,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* if (!text_end) text_end = FindRenderedTextEnd(text, text_end); - const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1); + 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) g.LogLinePosY = ref_pos->y; if (log_new_line) From 8306e32495448c21dc37973fa6dfc546d1a067d1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 28 Jan 2026 15:14:15 +0100 Subject: [PATCH 1639/2359] Nav: fixed speed scale for resizing/moving with keyboard/gamepad. (#323) Fix 04157da29. --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 4 ++-- imgui_internal.h | 1 + 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ceba9c0a7..1207595d2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -172,6 +172,10 @@ Other Changes: - Fixed remote/shortcut InputText() not teleporting mouse cursor when nav cursor is visible and `io.ConfigNavMoveSetMousePos` is enabled. - Fixed a looping/wrapping issue when done in menu layer. (#9178) + - Fixed speed scale for resizing/moving with keyboard/gamepad. We incorrectly + used io.DisplayFramebufferScale (very old code), effectively making those + actions faster on macOS/iOS retina screens. + (changed this to use a style scale factor that's not fully formalized yet) - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - InvisibleButton: allow calling with size (0,0) to fit to available content diff --git a/imgui.cpp b/imgui.cpp index 7f8710cd9..4813c1bf1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7006,7 +7006,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, int* border_hove if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f) { const float NAV_RESIZE_SPEED = 600.0f; - const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y); + const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * GetScale(); g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step; g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size g.NavWindowingToggleLayer = false; @@ -14521,7 +14521,7 @@ static void ImGui::NavUpdateWindowing() if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f) { const float NAV_MOVE_SPEED = 800.0f; - const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); + const float move_step = NAV_MOVE_SPEED * io.DeltaTime * GetScale(); g.NavWindowingAccumDeltaPos += nav_move_dir * move_step; g.NavHighlightItemUnderNav = true; ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos); diff --git a/imgui_internal.h b/imgui_internal.h index ad7a1479f..c17873ca4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3150,6 +3150,7 @@ namespace ImGui // - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. IMGUI_API ImGuiIO& GetIO(ImGuiContext* ctx); IMGUI_API ImGuiPlatformIO& GetPlatformIO(ImGuiContext* ctx); + inline float GetScale() { ImGuiContext& g = *GImGui; return g.Style._MainScale; } // FIXME-DPI: I don't want to formalize this just yet. Because reasons. Please don't use. 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); From 960aff24fc7a238a11276e5b5ac650ce76bd61db Mon Sep 17 00:00:00 2001 From: Ahmed Samy Date: Tue, 27 Jan 2026 00:43:09 +0200 Subject: [PATCH 1640/2359] Backends: Win32: use XInput Packet to avoid resubmitting gamepad data. (#9202, #8556) --- backends/imgui_impl_win32.cpp | 8 ++++++++ docs/CHANGELOG.txt | 2 ++ 2 files changed, 10 insertions(+) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index c344a1417..de92040aa 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-01-28: Inputs: Minor optimization not submitting gamepad input if packet number has not changed (reworked from 2025-09-23 attempt). (#9202, #8556) // 2025-12-03: Inputs: handle WM_IME_CHAR/WM_IME_COMPOSITION messages to support Unicode inputs on MBCS (non-Unicode) Windows. (#9099, #3653, #5961) // 2025-10-19: Inputs: Revert previous change to allow for io.ClearInputKeys() on focus-out not losing gamepad state. // 2025-09-23: Inputs: Minor optimization not submitting gamepad input if packet number has not changed. @@ -127,6 +128,7 @@ struct ImGui_ImplWin32_Data HMODULE XInputDLL; PFN_XInputGetCapabilities XInputGetCapabilities; PFN_XInputGetState XInputGetState; + DWORD XInputPacketNumber; #endif ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); } @@ -358,6 +360,9 @@ static void ImGui_ImplWin32_UpdateGamepads(ImGuiIO& io) if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS) return; io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + if (bd->XInputPacketNumber != 0 && bd->XInputPacketNumber == xinput_state.dwPacketNumber) + return; + bd->XInputPacketNumber = xinput_state.dwPacketNumber; #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) #define MAP_BUTTON(KEY_NO, BUTTON_ENUM) { io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); } @@ -771,6 +776,9 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPA case WM_SETFOCUS: case WM_KILLFOCUS: io.AddFocusEvent(msg == WM_SETFOCUS); +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + bd->XInputPacketNumber = 0; // FIXME: Technically, calling io.ClearInputKeys() directly would require this as well. +#endif return 0; case WM_INPUTLANGCHANGE: ImGui_ImplWin32_UpdateKeyboardCodePage(io); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1207595d2..80bd16b19 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -229,6 +229,8 @@ Other Changes: devices. (#8784) [@FelixStach] - Win32: handle `WM_IME_CHAR`/`WM_IME_COMPOSITION` to support Unicode inputs on MBCS (non-Unicode) Windows. (#9099, #3653, #5961) [@ulhc, @ocornut, @Othereum] + - Win32: minor optimization not submitting gamepad input if packet number has not + changed (reworked previous 1.92.4). (#9202, #8556) [@AhmedSamyMousa, @MidTerm-CN] - Examples: - Win32+DirectX12: ignore seemingly incorrect `D3D12_MESSAGE_ID_FENCE_ZERO_WAIT` warning on startups on some setups. (#9084, #9093) [@RT2Code, @LeoGautheron] From 6cc7787c77c344d3ecead3665d1805cc89bcbb39 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Jan 2026 14:12:57 +0100 Subject: [PATCH 1641/2359] Windows: shallow tweaks in window bg rendering to simplify diff w/ docking. --- imgui.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 4813c1bf1..e8f54efd5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7129,7 +7129,13 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar } if (override_alpha) bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); - window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom); + if (bg_col & IM_COL32_A_MASK) + { + ImRect bg_rect(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size); + ImDrawFlags bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom; + ImDrawList* bg_draw_list = window->DrawList; + bg_draw_list->AddRectFilled(bg_rect.Min, bg_rect.Max, bg_col, window_rounding, bg_rounding_flags); + } } // Title bar @@ -12781,6 +12787,7 @@ void ImGui::BringWindowToFocusFront(ImGuiWindow* window) } // Note technically focus related but rather adjacent and close to BringWindowToFocusFront() +// FIXME-FOCUS: Could opt-in/opt-out enable modal check like in FocusWindow(). void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; From 5166bec5d8293021d7396ab1d623aabe329b0d0a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Jan 2026 17:23:28 +0100 Subject: [PATCH 1642/2359] Scrollbar: rounding corners selected based on a generic helper. CalcRoundingFlagsForRectInRect() is backported and used multiple times by docking. --- imgui_draw.cpp | 11 +++++++++++ imgui_internal.h | 1 + imgui_widgets.cpp | 15 +-------------- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 00e058351..5c0767695 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -6114,6 +6114,17 @@ void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomRight); } +ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold) +{ + bool round_l = r_in.Min.x <= r_outer.Min.x + threshold; + bool round_r = r_in.Max.x >= r_outer.Max.x - threshold; + bool round_t = r_in.Min.y <= r_outer.Min.y + threshold; + bool round_b = r_in.Max.y >= r_outer.Max.y - threshold; + return ImDrawFlags_RoundCornersNone + | ((round_t && round_l) ? ImDrawFlags_RoundCornersTopLeft : 0) | ((round_t && round_r) ? ImDrawFlags_RoundCornersTopRight : 0) + | ((round_b && round_l) ? ImDrawFlags_RoundCornersBottomLeft : 0) | ((round_b && round_r) ? ImDrawFlags_RoundCornersBottomRight : 0); +} + // Helper for ColorPicker4() // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. // Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. diff --git a/imgui_internal.h b/imgui_internal.h index c17873ca4..b0da43d18 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3606,6 +3606,7 @@ namespace ImGui 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8911863da..0fabf7965 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -982,20 +982,7 @@ void ImGui::Scrollbar(ImGuiAxis axis) // Calculate scrollbar bounding box ImRect bb = GetWindowScrollbarRect(window, axis); - ImDrawFlags rounding_corners = ImDrawFlags_RoundCornersNone; - if (axis == ImGuiAxis_X) - { - rounding_corners |= ImDrawFlags_RoundCornersBottomLeft; - if (!window->ScrollbarY) - rounding_corners |= ImDrawFlags_RoundCornersBottomRight; - } - else - { - if ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) - rounding_corners |= ImDrawFlags_RoundCornersTopRight; - if (!window->ScrollbarX) - rounding_corners |= ImDrawFlags_RoundCornersBottomRight; - } + ImDrawFlags rounding_corners = CalcRoundingFlagsForRectInRect(bb, window->Rect(), g.Style.WindowBorderSize); float size_visible = window->InnerRect.Max[axis] - window->InnerRect.Min[axis]; float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f; ImS64 scroll = (ImS64)window->Scroll[axis]; From a9ca61a7ce82b83a89c1a00c2cd7e53b0ae26926 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Feb 2026 16:00:33 +0100 Subject: [PATCH 1643/2359] Fonts: fixed an issue where using PushFont() from the implicit/fallback "Debug" window when its recorded state is collapsed would incorrectly early out. (#9210, #8865) Amend 0e769c5, ca31693, d8da97f, 1bf41a0. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 30 +++++++++++++++++------------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 80bd16b19..7e3e4ae40 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -78,6 +78,9 @@ Breaking Changes: has already been rendered. (#9162) [@ocornut, @cyfewlp] - Removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. + - Fixed an issue where using PushFont() from the implicit/fallback "Debug" window when + its recorded state is collapsed would incorrectly early out. This would break e.g. using + direct draw-list calls such as GetForegroundDrawList() with current font. (#9210, #8865) - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). The default value has same meaning before and after. (#9157, #9146) diff --git a/imgui.cpp b/imgui.cpp index e8f54efd5..82f38ee8b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4566,13 +4566,13 @@ static void SetCurrentWindow(ImGuiWindow* window) g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking if (window) { - bool backup_skip_items = window->SkipItems; - window->SkipItems = false; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) { ImGuiViewport* viewport = window->Viewport; g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity() } + const bool backup_skip_items = window->SkipItems; + window->SkipItems = false; ImGui::UpdateCurrentFontSize(0.0f); window->SkipItems = backup_skip_items; ImGui::NavUpdateCurrentWindowIsScrollPushableX(); @@ -9000,16 +9000,6 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) g.Style.FontSizeBase = g.FontSizeBase; - // Early out to avoid hidden window keeping bakes referenced and out of GC reach. - // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching. - // FIXME: perhaps g.FontSize should be updated? - if (window != NULL && window->SkipItems) - { - ImGuiTable* table = g.CurrentTable; - if (table == NULL || (table->CurrentColumn != -1 && table->Columns[table->CurrentColumn].IsSkipItems == false)) // See 8465#issuecomment-2951509561 and #8865. Ideally the SkipItems=true in tables would be amended with extra data. - return; - } - // Restoring is pretty much only used by PopFont() float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; if (final_size == 0.0f) @@ -9039,10 +9029,24 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) final_size = ImClamp(final_size, 1.0f, IMGUI_FONT_SIZE_MAX); if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity; + g.FontSize = final_size; + g.DrawListSharedData.FontSize = g.FontSize; + + // Early out to avoid hidden window keeping bakes referenced and out of GC reach. + // - However this leave a pretty subtle and damning error surface area if g.FontBaked was mismatching. + // Probably needs to be reevaluated into e.g. setting g.FontBaked = nullptr to mark it as dirty. + // - Note that 'PushFont(); Begin(); End(); PopFont()' from within any collapsed window is not compromised, because Begin() calls SetCurrentWindow()->...->UpdateCurrentSize() + if (window != NULL && window->SkipItems) + { + ImGuiTable* table = g.CurrentTable; + const bool allow_early_out = table == NULL || (table->CurrentColumn != -1 && table->Columns[table->CurrentColumn].IsSkipItems == false); // See 8465#issuecomment-2951509561 and #8865. Ideally the SkipItems=true in tables would be amended with extra data. + if (allow_early_out) + return; + } + g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL; g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; - g.DrawListSharedData.FontSize = g.FontSize; g.DrawListSharedData.FontScale = g.FontBakedScale; } From 4b8e41cffb82b64777b6c682bedf33089517da04 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 Jan 2026 18:41:40 +0100 Subject: [PATCH 1644/2359] TabBar: expose NextScrollToTabId to internal API. --- imgui_internal.h | 3 ++- imgui_widgets.cpp | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index b0da43d18..e9e644f64 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2792,7 +2792,7 @@ struct ImGuiTabItem ImGuiTabItemFlags Flags; 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 + float Offset; // Position relative to beginning of tab bar float Width; // Width currently displayed float ContentWidth; // Width of label + padding, stored during BeginTabItem() call (misnamed as "Content" would normally imply width of label only) float RequestedWidth; // Width optionally requested by caller, -1.0f is unused @@ -2813,6 +2813,7 @@ struct IMGUI_API ImGuiTabBar ImGuiID ID; // Zero for tab-bars used by docking ImGuiID SelectedTabId; // Selected tab/window ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation + ImGuiID NextScrollToTabId; ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) int CurrFrameVisible; int PrevFrameVisible; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0fabf7965..54ff81bd6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9801,6 +9801,11 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Setup next selected tab ImGuiID scroll_to_tab_id = 0; + if (tab_bar->NextScrollToTabId) + { + scroll_to_tab_id = tab_bar->NextScrollToTabId; + tab_bar->NextScrollToTabId = 0; + } if (tab_bar->NextSelectedTabId) { tab_bar->SelectedTabId = tab_bar->NextSelectedTabId; From 76860017d51f25f943a1e607ab795b3615acefb5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Feb 2026 17:24:32 +0100 Subject: [PATCH 1645/2359] Clipper, Nav: fixed an UBSan warning when using in a ListClipper region . (#9160) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 3 ++- imgui_internal.h | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7e3e4ae40..253a4b020 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -179,6 +179,7 @@ Other Changes: used io.DisplayFramebufferScale (very old code), effectively making those actions faster on macOS/iOS retina screens. (changed this to use a style scale factor that's not fully formalized yet) + - Fixed an UBSan warning when using in a ListClipper region . (#9160) - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - InvisibleButton: allow calling with size (0,0) to fit to available content diff --git a/imgui.cpp b/imgui.cpp index 82f38ee8b..799836955 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3399,7 +3399,8 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) if (is_nav_request) { data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, nav_off_min, nav_off_max)); - data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, nav_off_min, nav_off_max)); + if (!g.NavScoringNoClipRect.IsInverted()) + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, nav_off_min, nav_off_max)); } if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1) data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount)); diff --git a/imgui_internal.h b/imgui_internal.h index e9e644f64..50691e1b9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2352,7 +2352,7 @@ struct ImGuiContext ImGuiDir NavMoveDirForDebug; ImGuiDir NavMoveClipDir; // FIXME-NAV: Describe the purpose of this better. Might want to rename? ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], modified for directional navigation scoring. - ImRect NavScoringNoClipRect; // Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted + ImRect NavScoringNoClipRect; // Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted. Unset/invalid if inverted. int NavScoringDebugCount; // Metrics for debugging int NavTabbingDir; // Generally -1 or +1, 0 when tabbing without a nav id int NavTabbingCounter; // >0 when counting items for tabbing From ea83628438f5d29f2b576b694efd3e864fc00b1c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Feb 2026 17:33:45 +0100 Subject: [PATCH 1646/2359] Nav: fixed navigation cursor briefly appearing when using API to focus an InputText() in a window with _NoNavInputs flag. (#9214) Amend 1566c96cc --- imgui.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 799836955..d45bc03fb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3972,6 +3972,9 @@ void ImGui::RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFl return; if (id == g.LastItemData.ID && (g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav)) return; + + // We don't early out on 'window->Flags & ImGuiWindowFlags_NoNavInputs' because it would be inconsistent with + // other code directly checking NavCursorVisible. Instead we aim for NavCursorVisible to always be false. ImGuiWindow* window = g.CurrentWindow; if (window->DC.NavHideHighlightOneFrame) return; @@ -12953,7 +12956,9 @@ void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWind void ImGui::SetNavCursorVisible(bool visible) { ImGuiContext& g = *GImGui; - if (g.IO.ConfigNavCursorVisibleAlways) + if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + visible = false; + else if (g.IO.ConfigNavCursorVisibleAlways) visible = true; g.NavCursorVisible = visible; } @@ -12962,7 +12967,9 @@ void ImGui::SetNavCursorVisible(bool visible) void ImGui::SetNavCursorVisibleAfterMove() { ImGuiContext& g = *GImGui; - if (g.IO.ConfigNavCursorVisibleAuto) + if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + g.NavCursorVisible = false; + else if (g.IO.ConfigNavCursorVisibleAuto) g.NavCursorVisible = true; g.NavHighlightItemUnderNav = g.NavMousePosDirty = true; } @@ -13906,7 +13913,7 @@ void ImGui::NavUpdateCreateMoveRequest() IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer); g.NavInitRequest = g.NavInitRequestFromMove = true; g.NavInitResult.ID = 0; - if (g.IO.ConfigNavCursorVisibleAuto) + if (g.IO.ConfigNavCursorVisibleAuto) // NO check for _NoNavInputs here as we assume MoveRequests cannot be created. g.NavCursorVisible = true; } From 226f62fa8fde6d51ed5fd2bf96d463c9ff08d0c7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Feb 2026 15:25:26 +0100 Subject: [PATCH 1647/2359] Demo: amend Shortcuts demo to clarify that ImGuiInputFlags_RouteOverActive may be used with focused route. (#9004) --- imgui_demo.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b88e7bf2a..7ab820573 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -7916,6 +7916,11 @@ static void DemoWindowInputs() ImGui::CheckboxFlags("ImGuiInputFlags_Repeat", &route_options, ImGuiInputFlags_Repeat); ImGui::RadioButton("ImGuiInputFlags_RouteActive", &route_type, ImGuiInputFlags_RouteActive); ImGui::RadioButton("ImGuiInputFlags_RouteFocused (default)", &route_type, ImGuiInputFlags_RouteFocused); + ImGui::Indent(); + ImGui::BeginDisabled(route_type != ImGuiInputFlags_RouteFocused); + ImGui::CheckboxFlags("ImGuiInputFlags_RouteOverActive##0", &route_options, ImGuiInputFlags_RouteOverActive); + ImGui::EndDisabled(); + ImGui::Unindent(); ImGui::RadioButton("ImGuiInputFlags_RouteGlobal", &route_type, ImGuiInputFlags_RouteGlobal); ImGui::Indent(); ImGui::BeginDisabled(route_type != ImGuiInputFlags_RouteGlobal); From 524f01d248599b55a56d8ba20879ffc4e107d6bd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Feb 2026 16:29:26 +0100 Subject: [PATCH 1648/2359] Metrics: browsing font baked data persist tree state when e.g. using LoadAll. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index d45bc03fb..56655951b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17313,7 +17313,7 @@ void ImGui::DebugNodeFont(ImFont* font) ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n]; if (baked->OwnerFont != font) continue; - PushID(baked_n); + PushID(baked->BakedId); if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) { if (SmallButton("Load all")) From 1bcc23ef123869240971427902b32109c8157e24 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Feb 2026 16:46:15 +0100 Subject: [PATCH 1649/2359] Fonts: avoid baking ExtraSizeScale twice into Ascent/Descent. Amend 55ad3b4 With extreme values of ExtraSizeScale offset would be noticeable in Descent - TextLink() function - or Ascent - TableAngledHeadersRow() function. --- imgui_draw.cpp | 2 +- misc/freetype/imgui_freetype.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5c0767695..5466a809b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4699,7 +4699,7 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig { // FIXME-NEWFONTS: reevaluate how to use sizing metrics // FIXME-NEWFONTS: make use of line gap value - float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; + float scale_for_layout = bd_font_data->ScaleFactor * baked->Size / src->ExtraSizeScale; int unscaled_ascent, unscaled_descent, unscaled_line_gap; stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index c358d89db..447afe25b 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -451,7 +451,7 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* s { // Read metrics FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; - const float scale = 1.0f / rasterizer_density; + const float scale = 1.0f / (rasterizer_density * src->ExtraSizeScale); baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. From 5fe48b6a0e2e1c9d73d9d7f9ebbe42ced3c41e21 Mon Sep 17 00:00:00 2001 From: tanksdude <58898485+tanksdude@users.noreply.github.com> Date: Tue, 10 Feb 2026 07:40:52 -0800 Subject: [PATCH 1650/2359] Docs: fixed some typos (#9217) --- backends/imgui_impl_glfw.h | 2 +- docs/BACKENDS.md | 2 +- docs/CHANGELOG.txt | 4 ++-- examples/example_glfw_wgpu/CMakeLists.txt | 2 +- examples/example_glfw_wgpu/README.md | 2 +- examples/example_sdl2_wgpu/CMakeLists.txt | 2 +- examples/example_sdl2_wgpu/README.md | 2 +- examples/example_sdl3_wgpu/CMakeLists.txt | 2 +- examples/example_sdl3_wgpu/README.md | 2 +- imgui.cpp | 12 ++++++------ imgui.h | 2 +- imgui_draw.cpp | 2 +- 12 files changed, 18 insertions(+), 18 deletions(-) diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index c01600d0c..7dc8cb5e1 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -48,7 +48,7 @@ IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* wi IMGUI_IMPL_API void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window); IMGUI_IMPL_API void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window); -// GFLW callbacks options: +// GLFW callbacks options: // - Set 'chain_for_all_windows=true' to enable chaining callbacks for all windows (including secondary viewports created by backends or by user) IMGUI_IMPL_API void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows); diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 62acb1e21..7839764cd 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -337,7 +337,7 @@ void MyImGuiBackend_UpdateTexture(ImTextureData* tex) { // Create texture based on tex->Width, tex->Height. // - Most backends only support tex->Format == ImTextureFormat_RGBA32. - // - Backends for particularly memory constrainted platforms may support tex->Format == ImTextureFormat_Alpha8. + // - Backends for particularly memory constrained platforms may support tex->Format == ImTextureFormat_Alpha8. // Upload all texture pixels // - Read from our CPU-side copy of the texture and copy to your graphics API. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 253a4b020..00349b9e7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -346,7 +346,7 @@ Other Changes: debug/metrics window is not in the same viewport as the table. - Backends: - NULL: added imgui_impl_null platform/renderer backend. - This is designed if you need to run e.g. context with no input or no ouput. + This is designed if you need to run e.g. context with no input or no output. - GLFW: fixed building on Linux platforms where Wayland headers are not available. (#9024, #8969, #8921, #8920) [@jagot] - GLFW: lower minimum requirement from GLFW 3.1 to GLFW 3.0. Though @@ -828,7 +828,7 @@ Breaking changes: which font input is providing which glyph. - Fonts: **IMPORTANT** on Thread Safety: - A few functions such as font->CalcTextSizeA() were by sheer luck (== accidentally) - thread-safe even thou we had never provided that guarantee before. They are + thread-safe even though we had never provided that guarantee before. They are definitively not thread-safe anymore as new glyphs may be loaded. - Textures: diff --git a/examples/example_glfw_wgpu/CMakeLists.txt b/examples/example_glfw_wgpu/CMakeLists.txt index 11248df26..86291f9e2 100644 --- a/examples/example_glfw_wgpu/CMakeLists.txt +++ b/examples/example_glfw_wgpu/CMakeLists.txt @@ -102,7 +102,7 @@ else() # Native/Desktop build option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") - option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 + option(DAWN_USE_GLFW OFF) # disable builtin GLFW in DAWN when we use SDL2 / SDL3 # Dawn builds many things by default - disable things we don't need option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF) diff --git a/examples/example_glfw_wgpu/README.md b/examples/example_glfw_wgpu/README.md index 119647211..04320d22c 100644 --- a/examples/example_glfw_wgpu/README.md +++ b/examples/example_glfw_wgpu/README.md @@ -89,7 +89,7 @@ Once the procedure for the specific builder is generated, the build command is * --- ### CMake useful options -#### Generator types (alternative to **ninja** bulder): +#### Generator types (alternative to **ninja** builder): - `-G Ninja` to build with __ninja__ builder - `-G "Unix Makefiles"` to build with __make__ builder - `-G "Visual Studio 17 2022" -A x64` to create a VS 2022 solution (.sln) file, Windows only diff --git a/examples/example_sdl2_wgpu/CMakeLists.txt b/examples/example_sdl2_wgpu/CMakeLists.txt index c4c3eee86..ae0d626a1 100644 --- a/examples/example_sdl2_wgpu/CMakeLists.txt +++ b/examples/example_sdl2_wgpu/CMakeLists.txt @@ -92,7 +92,7 @@ else() # Native/Desktop build else() set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 + option(DAWN_USE_GLFW OFF) # disable builtin GLFW in DAWN when we use SDL2 / SDL3 option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") diff --git a/examples/example_sdl2_wgpu/README.md b/examples/example_sdl2_wgpu/README.md index cdfd032da..afba7b857 100644 --- a/examples/example_sdl2_wgpu/README.md +++ b/examples/example_sdl2_wgpu/README.md @@ -89,7 +89,7 @@ Once the procedure for the specific builder is generated, the build command is * --- ### CMake useful options -#### Generator types (alternative to **ninja** bulder): +#### Generator types (alternative to **ninja** builder): - `-G Ninja` to build with __ninja__ builder - `-G "Unix Makefiles"` to build with __make__ builder - `-G "Visual Studio 17 2022" -A x64` to create a VS 2022 solution (.sln) file, Windows only diff --git a/examples/example_sdl3_wgpu/CMakeLists.txt b/examples/example_sdl3_wgpu/CMakeLists.txt index 0b8dc48e9..2f3d48f62 100644 --- a/examples/example_sdl3_wgpu/CMakeLists.txt +++ b/examples/example_sdl3_wgpu/CMakeLists.txt @@ -95,7 +95,7 @@ else() # Native/Desktop build else() set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository") - option(DAWN_USE_GLFW OFF) # disable buildin GLFW in DAWN when we use SDL2 / SDL3 + option(DAWN_USE_GLFW OFF) # disable builtin GLFW in DAWN when we use SDL2 / SDL3 option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON) set(DAWN_BUILD_MONOLITHIC_LIBRARY "STATIC" CACHE STRING "Build monolithic library: SHARED, STATIC, or OFF.") diff --git a/examples/example_sdl3_wgpu/README.md b/examples/example_sdl3_wgpu/README.md index bd7c33652..35857be9e 100644 --- a/examples/example_sdl3_wgpu/README.md +++ b/examples/example_sdl3_wgpu/README.md @@ -89,7 +89,7 @@ Once the procedure for the specific builder is generated, the build command is * --- ### CMake useful options -#### Generator types (alternative to **ninja** bulder): +#### Generator types (alternative to **ninja** builder): - `-G Ninja` to build with __ninja__ builder - `-G "Unix Makefiles"` to build with __make__ builder - `-G "Visual Studio 17 2022" -A x64` to create a VS 2022 solution (.sln) file, Windows only diff --git a/imgui.cpp b/imgui.cpp index 56655951b..35c7a7af2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -486,7 +486,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate understanding which font input is providing which glyph. - Fonts: **IMPORTANT** on Thread Safety: - - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even thou we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded. + - A few functions such as font->CalcTextSizeA() were, by sheer luck (== accidentally) thread-safe even though we had never provided that guarantee. They are definitively not thread-safe anymore as new glyphs may be loaded. - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font". - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. @@ -1467,7 +1467,7 @@ ImGuiStyle::ImGuiStyle() ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar - ScrollbarPadding = 2.0f; // Padding of scrollbar grab within its frame (same for both axises) + ScrollbarPadding = 2.0f; // Padding of scrollbar grab within its frame (same for both axes) GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. @@ -5215,7 +5215,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) g.MovingWindow = window; } -// This is not 100% symetric with StartMouseMovingWindow(). +// This is not 100% symmetric with StartMouseMovingWindow(). // We do NOT clear ActiveID, because: // - It would lead to rather confusing recursive code paths. Caller can call ClearActiveID() if desired. // - Some code intentionally cancel moving but keep the ActiveID to lock inputs (e.g. code path taken when clicking a disabled item). @@ -5296,7 +5296,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() StartMouseMovingWindow(hovered_window); //-V595 // FIXME: In principle we might be able to call StopMouseMovingWindow() below. - // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symetrical, at the later doesn't clear ActiveId. + // Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symmetrical, at the later doesn't clear ActiveId. // Cancel moving if clicked outside of title bar if ((hovered_window->BgClickFlags & ImGuiWindowBgClickFlags_Move) == 0) // set by io.ConfigWindowsMoveFromTitleBarOnly @@ -6704,7 +6704,7 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont size_desired[ImGuiAxis_Y] = (axis_mask & 2) ? size_contents.y + size_pad.y + decoration_h_without_scrollbars : window->Size.y; // Determine maximum window size - // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction + // Child windows are laid within their parent (unless they are also popups/menus) and thus have no restriction ImVec2 size_max = ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; if (window->Flags & ImGuiWindowFlags_Tooltip) @@ -8030,7 +8030,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) g.TooltipPreviousWindow = window; // Set default BgClickFlags - // This is set at the end of this function, so UpdateWindowManualResize()/ClampWindowPos() may use last-frame value if overriden by user code. + // This is set at the end of this function, so UpdateWindowManualResize()/ClampWindowPos() may use last-frame value if overridden by user code. // FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button. window->BgClickFlags = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->BgClickFlags : (g.IO.ConfigWindowsMoveFromTitleBarOnly ? ImGuiWindowBgClickFlags_None : ImGuiWindowBgClickFlags_Move); diff --git a/imgui.h b/imgui.h index 0706da641..8d0374b68 100644 --- a/imgui.h +++ b/imgui.h @@ -3815,7 +3815,7 @@ struct ImFontBaked unsigned int MetricsTotalSurface:26;// 3 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) unsigned int WantDestroy:1; // 0 // // Queued for destroy unsigned int LoadNoFallback:1; // 0 // // Disable loading fallback in lower-level calls. - unsigned int LoadNoRenderOnLayout:1;// 0 // // Enable a two-steps mode where CalcTextSize() calls will load AdvanceX *without* rendering/packing glyphs. Only advantagous if you know that the glyph is unlikely to actually be rendered, otherwise it is slower because we'd do one query on the first CalcTextSize and one query on the first Draw. + unsigned int LoadNoRenderOnLayout:1;// 0 // // Enable a two-steps mode where CalcTextSize() calls will load AdvanceX *without* rendering/packing glyphs. Only advantageous if you know that the glyph is unlikely to actually be rendered, otherwise it is slower because we'd do one query on the first CalcTextSize and one query on the first Draw. int LastUsedFrame; // 4 // // Record of that time this was bounds ImGuiID BakedId; // 4 // // Unique ID for this baked storage ImFont* OwnerFont; // 4-8 // in // Parent font diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5466a809b..dd66e24b7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3695,7 +3695,7 @@ void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src) IM_UNUSED(atlas); // IF YOU GET A CRASH IN THE IM_FREE() CALL HERE AND USED AddFontFromMemoryTTF(): // - DUE TO LEGACY REASON AddFontFromMemoryTTF() TRANSFERS MEMORY OWNERSHIP BY DEFAULT. - // - IT WILL THEREFORE CRASH WHEN PASSED DATA WHICH MAY NOT BE FREEED BY IMGUI. + // - IT WILL THEREFORE CRASH WHEN PASSED DATA WHICH MAY NOT BE FREED BY IMGUI. // - USE `ImFontConfig font_cfg; font_cfg.FontDataOwnedByAtlas = false; io.Fonts->AddFontFromMemoryTTF(....., &cfg);` to disable passing ownership/ // WE WILL ADDRESS THIS IN A FUTURE REWORK OF THE API. if (src->FontDataOwnedByAtlas) From c71b2a1fe63ff935af7e05aa6079d6ba7f161cda Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Feb 2026 17:56:37 +0100 Subject: [PATCH 1651/2359] Revert "Fonts: avoid baking ExtraSizeScale twice into Ascent/Descent." This reverts commit 1bcc23ef123869240971427902b32109c8157e24. --- imgui_draw.cpp | 2 +- misc/freetype/imgui_freetype.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dd66e24b7..fd7c0be7e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4699,7 +4699,7 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig { // FIXME-NEWFONTS: reevaluate how to use sizing metrics // FIXME-NEWFONTS: make use of line gap value - float scale_for_layout = bd_font_data->ScaleFactor * baked->Size / src->ExtraSizeScale; + float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; int unscaled_ascent, unscaled_descent, unscaled_line_gap; stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 447afe25b..c358d89db 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -451,7 +451,7 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* s { // Read metrics FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; - const float scale = 1.0f / (rasterizer_density * src->ExtraSizeScale); + const float scale = 1.0f / rasterizer_density; baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. From fd9873a5c2ed84c5cf080f894428c1020e83f782 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Feb 2026 18:12:53 +0100 Subject: [PATCH 1652/2359] Tables: internals: extract TableSetColumnDisplayOrder() out of TableBeginApplyRequests() and clarify API limitations. --- imgui_internal.h | 1 + imgui_tables.cpp | 45 +++++++++++++++++++++++++++++---------------- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 50691e1b9..d596db4e4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3543,6 +3543,7 @@ namespace ImGui IMGUI_API float TableCalcMaxColumnWidth(const ImGuiTable* table, int column_n); IMGUI_API void TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n); IMGUI_API void TableSetColumnWidthAutoAll(ImGuiTable* table); + IMGUI_API void TableSetColumnDisplayOrder(ImGuiTable* table, int column_n, int dst_order); IMGUI_API void TableRemove(ImGuiTable* table); IMGUI_API void TableGcCompactTransientBuffers(ImGuiTable* table); IMGUI_API void TableGcCompactTransientBuffers(ImGuiTableTempData* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index d4e57e831..6eaa973af 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -699,7 +699,7 @@ void ImGui::TableBeginApplyRequests(ImGuiTable* table) } // Handle reordering request - // Note: we don't clear ReorderColumn after handling the request. + // Note: we don't clear ReorderColumn after handling the request (FIXME: clarify why or add a test). if (table->InstanceCurrent == 0) { if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1) @@ -711,24 +711,12 @@ void ImGui::TableBeginApplyRequests(ImGuiTable* table) // In the configuration below, moving C to the right of E will lead to: // ... C [D] E ---> ... [D] E C (Column name/index) // ... 2 3 4 ... 2 3 4 (Display order) - const int reorder_dir = table->ReorderColumnDir; - IM_ASSERT(reorder_dir == -1 || reorder_dir == +1); + IM_ASSERT(table->ReorderColumnDir == -1 || table->ReorderColumnDir == +1); IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable); ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn]; - ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevEnabledColumn : src_column->NextEnabledColumn]; - IM_UNUSED(dst_column); - const int src_order = src_column->DisplayOrder; - const int dst_order = dst_column->DisplayOrder; - src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order; - for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir) - table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir; - IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir); - - // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[]. Rebuild later from the former. - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n; + ImGuiTableColumn* dst_column = &table->Columns[(table->ReorderColumnDir < 0) ? src_column->PrevEnabledColumn : src_column->NextEnabledColumn]; + TableSetColumnDisplayOrder(table, table->ReorderColumn, dst_column->DisplayOrder); table->ReorderColumnDir = 0; - table->IsSettingsDirty = true; } } @@ -742,6 +730,31 @@ void ImGui::TableBeginApplyRequests(ImGuiTable* table) } } +// Note that TableSetupScrollFreeze() enforce a display order range for frozen columns. +// So reordering a column across the frozen column barrier is illegal and will be undone. +void ImGui::TableSetColumnDisplayOrder(ImGuiTable* table, int column_n, int dst_order) +{ + IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount); + IM_ASSERT(dst_order >= 0 && dst_order < table->ColumnsCount); + + ImGuiTableColumn* src_column = &table->Columns[column_n]; + const int src_order = src_column->DisplayOrder; + if (src_order == dst_order) + return; + const int reorder_dir = (dst_order < src_order) ? -1 : +1; + + src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order; + for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir) + table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir; + //IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir); + + // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[]. Rebuild later from the former. + // FIXME-OPT: If this is called multiple times we'd effectively have a O(N^2) thing going on. + for (int n = 0; n < table->ColumnsCount; n++) + table->DisplayOrderToIndex[table->Columns[n].DisplayOrder] = (ImGuiTableColumnIdx)n; + table->IsSettingsDirty = true; +} + // Adjust flags: default width mode + stretch columns are not allowed when auto extending static void TableSetupColumnFlags(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags flags_in) { From 9f30044333a8259a21cac923edd273e171d07dcb Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Feb 2026 20:47:56 +0100 Subject: [PATCH 1653/2359] Backends: GLFW: try to set IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND automatically if headers are not available. (#9225) Amend/fix 10d0162378 for system without X11/Wayland headers. (#8921, #8920, #8969) --- backends/imgui_impl_glfw.cpp | 10 ++++++++++ docs/CHANGELOG.txt | 1 + 2 files changed, 11 insertions(+) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index f166b45d2..da54589fe 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -29,6 +29,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-02-10: Try to set IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND automatically if corresponding headers are not accessible. (#9225) // 2025-12-12: Added IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND to forcefully disable either. // 2025-12-10: Avoid repeated glfwSetCursor()/glfwSetInputMode() calls when unnecessary. Lowers overhead for very high framerates (e.g. 10k+ FPS). // 2025-11-06: Lower minimum requirement to GLFW 3.0. Though a recent version e.g GLFW 3.4 is highly recommended. @@ -109,6 +110,15 @@ #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. #endif +#if defined(__has_include) +#if !__has_include() || !__has_include() +#define IMGUI_IMPL_GLFW_DISABLE_X11 +#endif +#if !__has_include() +#define IMGUI_IMPL_GLFW_DISABLE_WAYLAND +#endif +#endif + // GLFW #if !defined(IMGUI_IMPL_GLFW_DISABLE_X11) && (defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)) #define GLFW_HAS_X11 1 diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 00349b9e7..69da2270c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -219,6 +219,7 @@ Other Changes: Lowers overhead for very high framerates (e.g. 10k+ FPS). [@maxliani] - GLFW: Added IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND to forcefully disable either. (#9109, #9116) + Try to set them automatically if headers are not accessible. (#9225) - OpenGL3: Fixed embedded loader multiple init/shutdown cycles broken on some platforms. (#8792, #9112) - SDL2, SDL3: changed `GetClipboardText()` handler to return NULL on error aka From 8ed10d538edb3657e4f9b879550821cba7ee184a Mon Sep 17 00:00:00 2001 From: Ryan Jensen Date: Fri, 6 Feb 2026 15:29:27 -0600 Subject: [PATCH 1654/2359] Docs: update comment on ImGuiConfigFlags_NavEnableKeyboard. (#9218) Reworked comment of original PR + trim trailing blanks. --- imgui.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui.h b/imgui.h index 8d0374b68..6f488e6a9 100644 --- a/imgui.h +++ b/imgui.h @@ -980,7 +980,7 @@ namespace ImGui // Disabling [BETA API] // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) - // - Tooltips windows are automatically opted out of disabling. Note that IsItemHovered() by default returns false on disabled items, unless using ImGuiHoveredFlags_AllowWhenDisabled. + // - Tooltips windows are automatically opted out of disabling. Note that IsItemHovered() by default returns false on disabled items, unless using ImGuiHoveredFlags_AllowWhenDisabled. // - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls) IMGUI_API void BeginDisabled(bool disabled = true); IMGUI_API void EndDisabled(); @@ -1239,7 +1239,7 @@ enum ImGuiItemFlags_ ImGuiItemFlags_ButtonRepeat = 1 << 3, // false // Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. ImGuiItemFlags_AutoClosePopups = 1 << 4, // true // MenuItem()/Selectable() automatically close their parent popup window. ImGuiItemFlags_AllowDuplicateId = 1 << 5, // false // Allow submitting an item with the same identifier as an item already submitted this frame without triggering a warning tooltip if io.ConfigDebugHighlightIdConflicts is set. - ImGuiItemFlags_Disabled = 1 << 6, // false // [Internal] Disable interactions. DOES NOT affect visuals. This is used by BeginDisabled()/EndDisabled() and only provided here so you can read back via GetItemFlags(). + ImGuiItemFlags_Disabled = 1 << 6, // false // [Internal] Disable interactions. DOES NOT affect visuals. This is used by BeginDisabled()/EndDisabled() and only provided here so you can read back via GetItemFlags(). }; // Flags for ImGui::InputText() @@ -1703,7 +1703,7 @@ enum ImGuiInputFlags_ enum ImGuiConfigFlags_ { ImGuiConfigFlags_None = 0, - ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. Enable full Tabbing + directional arrows + space/enter to activate. + ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. Enable full Tabbing + directional arrows + Space/Enter to activate. Note: some features such as basic Tabbing and CtrL+Tab are enabled by regardless of this flag (and may be disabled via other means, see #4828, #9218). ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad. ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct dear imgui to disable mouse inputs and interactions. ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. @@ -1880,7 +1880,7 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. - ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. + ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) ImGuiColorEditFlags_NoColorMarkers = 1 << 11, // // ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. From 87262dd07aad0148a42075cbbeac480903570930 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Feb 2026 21:50:05 +0100 Subject: [PATCH 1655/2359] Nav, IO: added undocumented ConfigNavEnableTabbing flag. (#9218) --- imgui.cpp | 3 ++- imgui_internal.h | 9 +++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 35c7a7af2..5e03d0b10 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4219,6 +4219,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac... // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this.. + ConfigNavEnableTabbing = true; ConfigNavWindowingWithGamepad = true; ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab); ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab); @@ -13978,7 +13979,7 @@ void ImGui::NavUpdateCreateTabbingRequest() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.NavWindow; IM_ASSERT(g.NavMoveDir == ImGuiDir_None); - if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs)) + if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs) || !g.ConfigNavEnableTabbing) return; const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt; diff --git a/imgui_internal.h b/imgui_internal.h index d596db4e4..9220149a0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2369,10 +2369,15 @@ struct ImGuiContext bool NavJustMovedToIsTabbing; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. - // Navigation: Windowing (Ctrl+Tab for list, or Menu button + keys or directional pads to move/resize) + // Navigation: extra config options (will be made public eventually) + // - Tabbing (Tab, Shift+Tab) and Windowing (Ctrl+Tab, Ctrl+Shift+Tab) are enabled REGARDLESS of ImGuiConfigFlags_NavEnableKeyboard being set. + // - Ctrl+Tab is reconfigurable because it is the only shortcut that may be polled when no window are focused. It also doesn't work e.g. Web platforms. + bool ConfigNavEnableTabbing; // = true. Enable tabbing (Tab, Shift+Tab). PLEASE LET ME KNOW IF YOU USE THIS. bool ConfigNavWindowingWithGamepad; // = true. Enable Ctrl+Tab by holding ImGuiKey_GamepadFaceLeft (== ImGuiKey_NavGamepadMenu). When false, the button may still be used to toggle Menu layer. - ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828) + ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). Set to 0 to disable. For reconfiguration (see #4828) ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X) + + // Navigation: Windowing (Ctrl+Tab for list, or Menu button + keys or directional pads to move/resize) ImGuiWindow* NavWindowingTarget; // Target window when doing Ctrl+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the Ctrl+Tab contents From 7b365fa6b4e991d9fa2f51f180ca286cfab3d228 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Feb 2026 22:04:15 +0100 Subject: [PATCH 1656/2359] Nav: fixed another occurence of nav cursor briefly appearing when Tabbing with ImGuiConfigFlags_NavEnableKeyboard disabled. (#9214, #9218) Amend 1566c96cc + ea83628. --- imgui.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 5e03d0b10..e24c1966b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12970,6 +12970,10 @@ void ImGui::SetNavCursorVisibleAfterMove() ImGuiContext& g = *GImGui; if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) g.NavCursorVisible = false; + else if (g.NavInputSource == ImGuiInputSource_Keyboard && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) == 0) + g.NavCursorVisible = false; + else if (g.NavInputSource == ImGuiInputSource_Gamepad && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + g.NavCursorVisible = false; else if (g.IO.ConfigNavCursorVisibleAuto) g.NavCursorVisible = true; g.NavHighlightItemUnderNav = g.NavMousePosDirty = true; From d67c66c437ba995435104c1ce90a5db31bb80c70 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Feb 2026 13:24:38 +0100 Subject: [PATCH 1657/2359] Changed RenderTextEllipsis() logic to not trim trailing blanks before the ellipsis. (#9229) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 8 +------- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 69da2270c..63b22da1c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -171,6 +171,9 @@ Other Changes: end of a line rather than at the beginning of next line. (#8990, #3237) - Fixed low-level word-wrapping function reading from *text_end when passed a string range. (#9107) [@achabense] + - Changed RenderTextEllipsis() logic to not trim trailing blanks before + the ellipsis, making ellipsis position more consistent and not arbitrary + hiding the possibility of multiple blanks. (#9229) - Nav: - Fixed remote/shortcut InputText() not teleporting mouse cursor when nav cursor is visible and `io.ConfigNavMoveSetMousePos` is enabled. diff --git a/imgui.cpp b/imgui.cpp index e24c1966b..63c6789a5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3905,13 +3905,7 @@ 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); - float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x; - while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) - { - // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text) - text_end_ellipsis--; - text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte - } + const float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &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)); From 291787bcacb486d72171f2bce3d4ce58cfc5a650 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Feb 2026 18:59:11 +0100 Subject: [PATCH 1658/2359] Fonts: comment about swapping EllipsisChar value. (#9228) --- imgui.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 6f488e6a9..81b2f8ba3 100644 --- a/imgui.h +++ b/imgui.h @@ -3858,10 +3858,10 @@ struct ImFont ImGuiID FontId; // Unique identifier for the font float LegacySize; // 4 // in // Font size passed to AddFont(). Use for old code calling PushFont() expecting to use that size. (use ImGui::GetFontBaked() to get font baked at current bound size). ImVector Sources; // 16 // in // List of sources. Pointers within OwnerAtlas->Sources[] - ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). + ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). If you ever want to temporarily swap this for an alternative/dummy char, make sure to clear EllipsisAutoBake. ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') - ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. - bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. + ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 17 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 8K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph (== EllipsisChar) needs to be generated by combining multiple '.'. ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() From 42f28ba305826f9338a781a5b50b7d5e4d555231 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Feb 2026 20:11:13 +0100 Subject: [PATCH 1659/2359] Fonts: avoid baking ExtraSizeScale twice into Ascent/Descent. (re) Reapply 1bcc23e + offset for our current internal font using it. --- imgui_draw.cpp | 4 ++-- misc/freetype/imgui_freetype.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index fd7c0be7e..6149395ac 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3175,7 +3175,7 @@ ImFont* ImFontAtlas::AddFontDefaultVector(const ImFontConfig* font_cfg_template) if (font_cfg.Name[0] == '\0') ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "ProggyVector.ttf"); font_cfg.ExtraSizeScale = 1.140f; // Match ProggyClean - font_cfg.GlyphOffset.y += -0.5f * (font_cfg.SizePixels / 13.0f); // Closer match ProggyClean + avoid descenders going too high (with current code). + font_cfg.GlyphOffset.y += 1.0f * (font_cfg.SizePixels / 13.0f); // Closer match ProggyClean + avoid descenders going too high (with current code). int ttf_compressed_size = 0; const char* ttf_compressed = GetDefaultCompressedFontDataProggyVector(&ttf_compressed_size); @@ -4699,7 +4699,7 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig { // FIXME-NEWFONTS: reevaluate how to use sizing metrics // FIXME-NEWFONTS: make use of line gap value - float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; + const float scale_for_layout = bd_font_data->ScaleFactor * baked->Size / src->ExtraSizeScale; int unscaled_ascent, unscaled_descent, unscaled_line_gap; stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index c358d89db..447afe25b 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -451,7 +451,7 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* s { // Read metrics FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; - const float scale = 1.0f / rasterizer_density; + const float scale = 1.0f / (rasterizer_density * src->ExtraSizeScale); baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. From 9c33672e5c3811e1c6ba6657b1be21787fd77ddd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Feb 2026 18:36:22 +0100 Subject: [PATCH 1660/2359] Examples: reword a comment to not mention AddFontDefault() explicitly. --- docs/FONTS.md | 6 +++--- examples/example_allegro5/main.cpp | 2 +- examples/example_android_opengl3/main.cpp | 2 +- examples/example_apple_metal/main.mm | 2 +- examples/example_apple_opengl2/main.mm | 2 +- examples/example_glfw_metal/main.mm | 2 +- examples/example_glfw_opengl2/main.cpp | 2 +- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_glfw_vulkan/main.cpp | 2 +- examples/example_glfw_wgpu/main.cpp | 2 +- examples/example_glut_opengl2/main.cpp | 2 +- examples/example_sdl2_directx11/main.cpp | 2 +- examples/example_sdl2_metal/main.mm | 2 +- examples/example_sdl2_opengl2/main.cpp | 2 +- examples/example_sdl2_opengl3/main.cpp | 2 +- examples/example_sdl2_sdlrenderer2/main.cpp | 2 +- examples/example_sdl2_vulkan/main.cpp | 2 +- examples/example_sdl2_wgpu/main.cpp | 2 +- examples/example_sdl3_directx11/main.cpp | 2 +- examples/example_sdl3_metal/main.mm | 2 +- examples/example_sdl3_opengl3/main.cpp | 2 +- examples/example_sdl3_sdlgpu3/main.cpp | 2 +- examples/example_sdl3_sdlrenderer3/main.cpp | 2 +- examples/example_sdl3_vulkan/main.cpp | 2 +- examples/example_sdl3_wgpu/main.cpp | 2 +- examples/example_win32_directx10/main.cpp | 2 +- examples/example_win32_directx11/main.cpp | 2 +- examples/example_win32_directx12/main.cpp | 2 +- examples/example_win32_directx9/main.cpp | 2 +- examples/example_win32_opengl3/main.cpp | 2 +- examples/example_win32_vulkan/main.cpp | 2 +- 31 files changed, 33 insertions(+), 33 deletions(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index a3eb57d95..2e3f4975b 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -116,14 +116,14 @@ style.FontSizeBase = 20.0f; **Load default font:** ```cpp ImGuiIO& io = ImGui::GetIO(); -io.Fonts->AddFontDefault(); // Load embedded font (auto-selected). -``` -```cpp io.Fonts->AddFontDefaultVector(); // Load embedded scalable font. ``` ```cpp io.Fonts->AddFontDefaultBitmap(); // Load embedded bitmap font (legacy). ``` +```cpp +io.Fonts->AddFontDefault(); // Load embedded font (legacy: auto-selected between the two above). +``` **Load .TTF/.OTF file with:** diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 54674a5d9..ebb6d76b0 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -49,7 +49,7 @@ int main(int, char**) ImGui_ImplAllegro5_Init(display); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_android_opengl3/main.cpp b/examples/example_android_opengl3/main.cpp index 7f60ac631..382006fa0 100644 --- a/examples/example_android_opengl3/main.cpp +++ b/examples/example_android_opengl3/main.cpp @@ -158,7 +158,7 @@ void Init(struct android_app* app) style.FontScaleDpi = main_scale; // Set initial font scale. // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 11f54549f..b8edbd2d1 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -69,7 +69,7 @@ ImGui_ImplMetal_Init(_device); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index aa9b39bad..1cfa882c8 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -57,7 +57,7 @@ ImGui_ImplOpenGL2_Init(); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index b6a802106..0ded0a3bd 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -62,7 +62,7 @@ int main(int, char**) ImGui_ImplMetal_Init(device); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 52d3612d3..48584eaf8 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -68,7 +68,7 @@ int main(int, char**) ImGui_ImplOpenGL2_Init(); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 98af19d21..20d39fccc 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -102,7 +102,7 @@ int main(int, char**) ImGui_ImplOpenGL3_Init(glsl_version); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 2ee284044..d70c7ce1b 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -420,7 +420,7 @@ int main(int, char**) ImGui_ImplVulkan_Init(&init_info); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index cea13682e..7c293a51c 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -113,7 +113,7 @@ int main(int, char**) ImGui_ImplWGPU_Init(&init_info); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index f3b4270f2..ca8017f5b 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -79,7 +79,7 @@ int main(int argc, char** argv) ImGui_ImplGLUT_InstallFuncs(); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index 65e4ca49c..cf3971646 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -90,7 +90,7 @@ int main(int, char**) ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index 6dbe190da..ea2afdab3 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -30,7 +30,7 @@ int main(int, char**) //ImGui::StyleColorsLight(); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index cc3cce022..3b3412b14 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -79,7 +79,7 @@ int main(int, char**) ImGui_ImplOpenGL2_Init(); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index dea16869c..0d992d47e 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -119,7 +119,7 @@ int main(int, char**) ImGui_ImplOpenGL3_Init(glsl_version); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 5021039cf..b69867354 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -81,7 +81,7 @@ int main(int, char**) ImGui_ImplSDLRenderer2_Init(renderer); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 49a6acfa9..f39534393 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -426,7 +426,7 @@ int main(int, char**) ImGui_ImplVulkan_Init(&init_info); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index 1b24e1c51..40a206cf1 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -93,7 +93,7 @@ int main(int, char**) ImGui_ImplWGPU_Init(&init_info); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index 88d7189a6..4337d4e2d 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -81,7 +81,7 @@ int main(int, char**) ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index b6dc5aa60..e6e306624 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -77,7 +77,7 @@ int main(int, char**) ImGui_ImplSDL3_InitForMetal(window); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index e5fa6d5a9..a36cfaba9 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -109,7 +109,7 @@ int main(int, char**) ImGui_ImplOpenGL3_Init(glsl_version); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 9d5dd31a4..8edbbbbad 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -89,7 +89,7 @@ int main(int, char**) ImGui_ImplSDLGPU3_Init(&init_info); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 82ccec6ef..88f9ac7fb 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -71,7 +71,7 @@ int main(int, char**) ImGui_ImplSDLRenderer3_Init(renderer); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 705d6b523..f461aab4c 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -425,7 +425,7 @@ int main(int, char**) ImGui_ImplVulkan_Init(&init_info); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index cdf819e8b..adf4524a5 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -101,7 +101,7 @@ int main(int, char**) ImGui_ImplWGPU_Init(&init_info); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 3a3b8e17e..2c3420709 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -72,7 +72,7 @@ int main(int, char**) ImGui_ImplDX10_Init(g_pd3dDevice); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 50fce7e98..524538ac1 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -72,7 +72,7 @@ int main(int, char**) ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index bb9e8161b..0d8bb20b1 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -167,7 +167,7 @@ int main(int, char**) //ImGui_ImplDX12_Init(g_pd3dDevice, APP_NUM_FRAMES_IN_FLIGHT, DXGI_FORMAT_R8G8B8A8_UNORM, g_pd3dSrvDescHeap, g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(), g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart()); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 19174d4b0..fbe4c3983 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -70,7 +70,7 @@ int main(int, char**) ImGui_ImplDX9_Init(g_pd3dDevice); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index d214aa93e..d18ea0bd8 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -80,7 +80,7 @@ int main(int, char**) ImGui_ImplOpenGL3_Init(); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 9470ce96c..7f1ccd0c8 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -413,7 +413,7 @@ int main(int, char**) ImGui_ImplVulkan_Init(&init_info); // Load Fonts - // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). + // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). From a8bf659143758dedcbe07887e7398cc0dbe08e1d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Feb 2026 19:35:41 +0100 Subject: [PATCH 1661/2359] Fonts: AddFontDefaultBitmap() doesn't need to explicitely set OversampleH/OversampleV to 1 as this is automatic. --- imgui.h | 2 +- imgui_draw.cpp | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index 81b2f8ba3..46ae2e5a6 100644 --- a/imgui.h +++ b/imgui.h @@ -3538,7 +3538,7 @@ struct ImFontConfig // Options bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. - bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Prevents fractional font size from working correctly! Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Prevents fractional font size from working correctly! Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, OversampleH/V will default to 1. ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6149395ac..1c5559e35 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3143,10 +3143,7 @@ ImFont* ImFontAtlas::AddFontDefaultBitmap(const ImFontConfig* font_cfg_template) #ifndef IMGUI_DISABLE_DEFAULT_FONT ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); if (!font_cfg_template) - { - font_cfg.OversampleH = font_cfg.OversampleV = 1; - font_cfg.PixelSnapH = true; - } + font_cfg.PixelSnapH = true; // Will also automatically set OversampleH = OversampleV = 1 if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f; // This only serves (1) as a reference for GlyphOffset.y setting and (2) as a default for pre-1.92 backend. if (font_cfg.Name[0] == '\0') From 041cdddf356c46fe2efeacaaae5625e669b9400c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Feb 2026 16:03:19 +0100 Subject: [PATCH 1662/2359] Fonts: add new ProggyForever font! Amend f006400 --- docs/CHANGELOG.txt | 22 +- docs/FONTS.md | 33 +- docs/README.md | 3 +- imconfig.h | 2 +- imgui.h | 2 +- imgui_draw.cpp | 601 ++++++++++------------ misc/fonts/ProggyVector-ExtractScript.txt | 17 - 7 files changed, 306 insertions(+), 374 deletions(-) delete mode 100644 misc/fonts/ProggyVector-ExtractScript.txt diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 63b22da1c..bbc9721fa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -116,15 +116,23 @@ Breaking Changes: Other Changes: - Fonts: - - Added AddFontDefaultVector(): a new embedded scalable font! - Based on ProggyVector by Tristan Grimmer, the same author as our good-old ProggyClean. - The font data was carefully subsetted, trimmed and compressed so the embedded - data is ~18 KB. Embedding a scalable default font ensures that Dear ImGui can - be easily and readily used in all contexts, even without file system access. - As always you can opt-out of the embedded font data if desired. A sizing tweak - was also applied to ensure the new font is a closer match to the classic font. + - Added AddFontDefaultVector(): a new embedded monospace scalable font: ProggyForever! + From https://github.com/ocornut/proggyforever: + "ProggyForever is an MIT-licensed partial reimplementation of the ProggyVector + font (originally by Tristan Grimmer), which itself is a vector-based + reinterpretation of the ProggyClean bitmap font that happily served as + Dear ImGui default font for over 10 years." [...] + "I commissioned Thiebault Courot to recreate this, applied various minor tweaks + and fixes, and reworked his editing pipeline toward shipping FontForge source + files so we can allow and track future changes." + - TL;DR; there was no strictly MIT-licensed matching font. We made it! + - The font data was carefully subsetted, trimmed and compressed so the embedded + data is ~14 KB. Embedding a scalable default font ensures that Dear ImGui can + be easily and readily used in all contexts, even without file system access. + - As always you can opt-out of the embedded font data if desired. - AddFontDefault() now automatically selects an embedded font between the classic pixel-looking one and the new scalable one. + Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() explicitely. - Fixed an issue related to EllipsisChar handling, while changing font loader or font loader flags dynamically in Style->Fonts menus. - imgui_freetype: fixed overwriting ImFontConfig::PixelSnapH when hinting diff --git a/docs/FONTS.md b/docs/FONTS.md index 2e3f4975b..1eeaefd2d 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -5,13 +5,16 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS The code in Dear ImGui embeds a copy of [ProggyClean.ttf](https://github.com/bluescan/proggyfonts) by Tristan Grimmer, a 13 pixels high, pixel-perfect font used by default. ProggyClean does not scale very nicely. -The code in Dear ImGui embeds a partial copy of [ProggyVector.ttf](https://github.com/bluescan/proggyfonts) by Tristan Grimmer and Source Foundry Authors, -a font mimicking ProggyClean which does scale nicely. +The code in Dear ImGui embeds a partial copy of [ProggyForever.ttf](https://github.com/ocornut/proggyforever) by Disco Hello & Tristan Grimmer, +a new font mimicking ProggyClean which does scale nicely. We embed fonts in the code so you can use Dear ImGui without any file system access. -If you use either of those fonts in your shipping product you should include their license as part of your software (see below for links). If you don't use them you can set `IMGUI_DISABLE_DEFAULT_FONT` in your [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) file to ship binaries without the fonts and save about ~26 KB. +Calling io.Fonts->AddFontDefaultBitmap() loads ProggyClean. +Calling io.Fonts->AddFontDefaultVector() loads ProggyForever. +Calling io.Fonts->AddFontDefault() selects one based on the expected default font size (when `style.FontSizeBase * style.FontScaleMain * style.FontSizeDpi >= 15` we use ProggyForever). + You may also load external .TTF/.OTF files, see instructions on this page. In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience. @@ -561,7 +564,20 @@ You can use the `UTF-8 Encoding viewer` in `Metrics/Debugger` to verify the cont ## Credits/Licenses For Fonts Included In Repository -Some fonts files are available in the `misc/fonts/` folder: +Embedded in source code: + +**ProggyClean.ttf**, by Tristan Grimmer +
MIT License +
(recommended loading setting: Size = 13.0, GlyphOffset.y = +1, PixelSnapH = true) +
https://github.com/bluescan/proggyfonts + +**ProggyForever.ttf**, by Disco Hello, Tristan Grimmer +
MIT License +
https://github.com/ocornut/proggyforever + +Extra fonts files are available in the `misc/fonts/` folder. +Compared to 2014 when they were first introduced, we now have better font support and we embed ProggyForever. +I believe all the files here are unnecessary nowadays. You can find font yourself. They might eventually be removed. **Roboto-Medium.ttf**, by Christian Robetson
Apache License 2.0 @@ -576,20 +592,11 @@ Some fonts files are available in the `misc/fonts/` folder:
Apache License 2.0
https://www.fontsquirrel.com/fonts/droid-sans -**ProggyClean.ttf**, by Tristan Grimmer -
MIT License -
(recommended loading setting: Size = 13.0, GlyphOffset.y = +1) -
https://github.com/bluescan/proggyfonts - **ProggyTiny.ttf**, by Tristan Grimmer
MIT License
(recommended loading setting: Size = 10.0, GlyphOffset.y = +1)
https://github.com/bluescan/proggyfonts -**ProggyVector.ttf**, by Tristan Grimmer, Source Foundry Authors -
MIT License + Bitstream Vera License -
https://github.com/bluescan/proggyfonts - **Karla-Regular.ttf**, by Jonathan Pinhorn
SIL OPEN FONT LICENSE Version 1.1 diff --git a/docs/README.md b/docs/README.md index a2d140734..c93847c86 100644 --- a/docs/README.md +++ b/docs/README.md @@ -217,7 +217,8 @@ Maintenance/support contracts, sponsoring invoices and other B2B transactions ar Omar: "I first discovered the IMGUI paradigm at [Q-Games](https://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it." -Embeds [ProggyClean.ttf, ProggyVector.ttf](https://www.proggyfonts.net) fonts by Tristan Grimmer (MIT license). +Embeds [ProggyClean](https://www.proggyfonts.net) font by Tristan Grimmer (MIT license). +
Embeds [ProggyForever](https://github.com/ocornut/proggyforever) fonts by Disco Hello, Tristan Grimmer (MIT license).
Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Special thanks to Alex Evans, Patrick Doane, Marco Koegler for kindly helping. Also thank you to everyone posting feedback, questions and patches on GitHub. diff --git a/imconfig.h b/imconfig.h index 322e5b89d..0d843be26 100644 --- a/imconfig.h +++ b/imconfig.h @@ -49,7 +49,7 @@ //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). -//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded fonts (ProggyClean/ProggyVector), remove ~9 KB + ~17 KB from output binary. AddFontDefaultXXX() functions will assert. +//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded fonts (ProggyClean/ProggyForever), remove ~9 KB + ~14 KB from output binary. AddFontDefaultXXX() functions will assert. //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available //---- Enable Test Engine / Automation features. diff --git a/imgui.h b/imgui.h index 46ae2e5a6..6fd1ceff6 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.92.6 WIP" -#define IMGUI_VERSION_NUM 19259 +#define IMGUI_VERSION_NUM 19260 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1c5559e35..0493f022a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -21,7 +21,7 @@ Index of this file: // [SECTION] ImGui Internal Render Helpers // [SECTION] Decompression code // [SECTION] Default font data (ProggyClean.ttf) -// [SECTION] Default font data (ProggyVector-minimal.ttf) +// [SECTION] Default font data (ProggyForever.ttf) */ @@ -3116,7 +3116,7 @@ static void Decode85(const unsigned char* src, unsigned char* dst) } #ifndef IMGUI_DISABLE_DEFAULT_FONT static const char* GetDefaultCompressedFontDataProggyClean(int* out_size); -static const char* GetDefaultCompressedFontDataProggyVector(int* out_size); +static const char* 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. @@ -3130,7 +3130,7 @@ static float GetExpectedContextFontSize(ImGuiContext* ctx) // Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg) { - if (OwnerContext == NULL || GetExpectedContextFontSize(OwnerContext) >= 16.0f) + if (OwnerContext == NULL || GetExpectedContextFontSize(OwnerContext) >= 15.0f) return AddFontDefaultVector(font_cfg); else return AddFontDefaultBitmap(font_cfg); @@ -3143,7 +3143,7 @@ ImFont* ImFontAtlas::AddFontDefaultBitmap(const ImFontConfig* font_cfg_template) #ifndef IMGUI_DISABLE_DEFAULT_FONT ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); if (!font_cfg_template) - font_cfg.PixelSnapH = true; // Will also automatically set OversampleH = OversampleV = 1 + font_cfg.PixelSnapH = true; // Prevents sub-integer scaling factors at lower-level layers. if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f; // This only serves (1) as a reference for GlyphOffset.y setting and (2) as a default for pre-1.92 backend. if (font_cfg.Name[0] == '\0') @@ -3161,21 +3161,23 @@ ImFont* ImFontAtlas::AddFontDefaultBitmap(const ImFontConfig* font_cfg_template) #endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT } -// Load a minimal version of ProggyVector, designed to match our good old ProggyClean, but nicely scalable. -// (See misc/fonts/ProggyVector-ExtractScript.txt for details) +// Load a minimal version of ProggyForever, designed to match our good old ProggyClean, but nicely scalable. +// (See build script in https://github.com/ocornut/proggyforever for details) ImFont* ImFontAtlas::AddFontDefaultVector(const ImFontConfig* font_cfg_template) { #ifndef IMGUI_DISABLE_DEFAULT_FONT ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (!font_cfg_template) + font_cfg.PixelSnapH = true; // Precisely match ProggyClean, but prevents sub-integer scaling factors at lower-level layers. if (font_cfg.SizePixels <= 0.0f) - font_cfg.SizePixels = 16.0f; + font_cfg.SizePixels = 13.0f; if (font_cfg.Name[0] == '\0') - ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "ProggyVector.ttf"); - font_cfg.ExtraSizeScale = 1.140f; // Match ProggyClean - font_cfg.GlyphOffset.y += 1.0f * (font_cfg.SizePixels / 13.0f); // Closer match ProggyClean + avoid descenders going too high (with current code). + ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "ProggyForever.ttf"); + font_cfg.ExtraSizeScale *= 1.015f; // Match ProggyClean + font_cfg.GlyphOffset.y += 0.5f * (font_cfg.SizePixels / 16.0f); // Closer match ProggyClean + avoid descenders going too high (with current code). int ttf_compressed_size = 0; - const char* ttf_compressed = GetDefaultCompressedFontDataProggyVector(&ttf_compressed_size); + const char* ttf_compressed = GetDefaultCompressedFontDataProggyForever(&ttf_compressed_size); return AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, font_cfg.SizePixels, &font_cfg); #else IM_ASSERT(0 && "Function is disabled in this build."); @@ -6285,11 +6287,8 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i //----------------------------------------------------------------------------- // [SECTION] Default font data (ProggyClean.ttf) //----------------------------------------------------------------------------- -// ProggyClean.ttf -// Copyright (c) 2004, 2005 Tristan Grimmer -// MIT license (see License.txt in http://www.proggyfonts.net/index.php?menu=download) -// Download and more information at http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php -// If you want a similar font which may be better scaled, consider using ProggyVector from the same author! +// MIT License / Copyright (c) 2004, 2005 Tristan Grimmer +// Download and more information at https://github.com/bluescan/proggyfonts //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_DEFAULT_FONT @@ -6474,331 +6473,265 @@ static const char* GetDefaultCompressedFontDataProggyClean(int* out_size) } //----------------------------------------------------------------------------- -// [SECTION] Default font data (ProggyVector-minimal.ttf) +// [SECTION] Default font data (ProggyForever-Regular-minimal.ttf) //----------------------------------------------------------------------------- -// Based on ProggyVector.ttf, Copyright (c) 2019,2023 Tristan Grimmer / Copyright (c) 2018 Source Foundry Authors / Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. -// MIT license + public domain, see licenses at https://github.com/bluescan/proggyfonts/tree/master/ProggyVector -//----------------------------------------------------------------------------- -// See misc/fonts/ProggyVector-ExtractScript.txt for FontForge script to create this from ProggyVector.ttf +// Based on ProggyForever: https://github.com/ocornut/proggyforever +// MIT license / Copyright (c) 2026 Disco Hello, Copyright (c) 2019,2023 Tristan Grimmer //----------------------------------------------------------------------------- -// File: 'ProggyVector-minimal.ttf' (23952 bytes) -// Exported using binary_to_compressed_c.exe -u8 "ProggyVector-minimal.ttf" proggy_vector_minimal_ttf -static const unsigned int proggy_vector_minimal_ttf_compressed_size = 18519; -static const unsigned char proggy_vector_minimal_ttf_compressed_data[18519] = +// File: 'output/ProggyForever-Regular-minimal.ttf' (18556 bytes) +// Exported using binary_to_compressed_c.exe -u8 "output/ProggyForever-Regular-minimal.ttf" proggy_forever_minimal_ttf +static const unsigned int proggy_forever_minimal_ttf_compressed_size = 14562; +static const unsigned char proggy_forever_minimal_ttf_compressed_data[14562] = { - 87,188,0,0,0,0,0,0,0,0,93,144,0,4,0,0,55,0,1,0,0,0,14,0,128,0,3,0,96,70,70,84,77,165,245,48,76,0,0,93,116,130,21,38,28,71,68,69,70,0,37,130,9,34,0,93,92,130,5,44,24,79,83,47,50,135, - 98,111,82,0,0,1,104,130,15,44,96,99,109,97,112,10,236,8,177,0,0,3,88,130,19,44,82,99,118,116,32,0,34,2,136,0,0,4,172,130,31,38,4,103,97,115,112,255,255,130,89,34,0,93,84,130,15,56, - 8,103,108,121,102,169,208,238,39,0,0,6,56,0,0,84,32,104,101,97,100,39,214,168,186,130,27,32,236,130,3,33,54,104,130,16,35,6,225,0,231,130,75,32,36,130,15,40,36,104,109,116,120,37,72, - 32,85,130,15,32,200,130,3,40,142,108,111,99,97,26,185,47,212,130,95,32,176,130,15,40,136,109,97,120,112,0,201,0,151,130,11,32,72,130,47,43,32,110,97,109,101,10,160,159,163,0,0,90,131, - 143,44,68,112,111,115,116,153,185,200,234,0,0,91,156,130,35,32,184,132,235,45,1,0,0,96,193,239,192,95,15,60,245,0,11,4,130,54,37,0,0,225,81,71,241,131,8,43,228,205,29,41,255,247,255, - 2,2,162,3,161,130,15,34,8,0,2,130,5,131,2,32,1,130,225,38,182,254,184,0,143,2,102,130,31,34,196,2,162,132,73,131,25,135,3,32,4,132,17,37,195,0,104,0,5,0,134,49,131,6,132,3,32,46,132, - 5,36,2,2,102,1,144,131,29,39,2,138,2,188,0,47,0,140,131,7,40,255,92,1,224,0,49,1,2,0,131,0,32,9,132,57,143,61,43,0,66,105,114,100,0,64,0,32,32,172,3,132,131,47,3,182,1,72,32,63,0,255, - 223,253,0,0,2,14,3,182,130,48,38,32,0,1,2,102,0,34,130,9,32,0,130,7,132,3,35,0,237,0,169,130,147,46,91,0,19,0,29,1,10,0,168,0,205,0,46,0,41,130,5,32,83,130,25,44,65,0,67,0,132,0,76, - 0,75,0,40,0,72,130,11,40,70,0,66,0,63,0,239,0,209,130,33,52,45,0,44,0,81,255,251,0,18,0,79,0,70,0,69,0,94,0,117,0,51,130,7,34,100,0,61,130,5,34,108,0,38,130,21,36,58,0,86,0,58,130, - 57,42,70,0,24,0,60,0,29,0,2,0,9,130,47,50,55,0,148,0,62,0,154,0,61,255,247,0,167,0,68,0,96,0,82,130,51,34,62,0,66,130,105,40,97,0,166,0,118,0,113,0,141,130,97,32,97,130,71,32,95,130, - 3,40,129,0,106,0,128,0,84,0,50,130,183,32,38,130,85,38,101,0,92,1,6,0,102,130,147,36,0,0,232,0,105,130,17,34,102,0,18,130,187,34,99,0,160,130,33,38,135,0,40,0,44,0,178,130,9,34,159, - 0,150,130,9,52,161,0,163,0,238,0,83,0,53,0,227,0,198,0,172,0,122,0,116,0,13,132,1,32,96,130,139,32,18,136,3,32,0,130,71,33,98,0,133,1,33,100,0,133,1,32,4,132,195,32,58,130,195,131, - 3,36,75,0,4,0,74,134,1,32,18,130,33,32,94,130,187,32,68,136,3,32,20,130,197,32,62,130,215,131,3,34,109,0,134,132,1,33,69,0,131,195,32,69,130,195,131,3,34,44,0,24,130,15,32,97,132,3, - 36,52,0,95,0,52,130,123,130,166,33,0,3,130,4,131,3,34,28,0,1,130,9,36,0,0,76,0,3,132,9,32,28,130,111,32,48,130,17,46,8,0,8,0,2,0,0,0,126,0,255,32,172,255,255,130,9,34,32,0,160,131, - 9,37,255,227,255,194,224,22,132,43,130,20,131,2,34,1,6,0,136,14,35,1,2,0,0,132,55,130,6,136,2,8,152,1,0,0,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29, - 30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89, - 90,91,92,93,94,95,96,97,0,134,135,137,139,147,152,158,163,162,164,166,165,167,169,171,170,172,173,175,174,176,177,179,181,180,182,184,183,188,187,189,190,0,114,100,101,105,0,120,161, - 112,107,0,118,106,0,136,154,0,115,0,0,103,119,132,161,39,108,124,0,168,186,129,99,110,131,12,38,109,125,0,98,130,133,151,131,10,131,3,37,185,0,193,0,0,194,131,9,33,0,121,130,5,47,132, - 140,131,141,138,143,144,145,142,149,150,0,148,156,157,155,130,18,32,113,130,3,32,122,130,3,130,2,34,34,2,136,130,5,33,42,0,133,1,8,186,80,0,100,0,170,1,22,1,132,2,2,2,16,2,36,2,56, - 2,104,2,124,2,166,2,182,2,208,2,226,3,26,3,52,3,132,3,214,3,246,4,46,4,126,4,150,4,238,5,66,5,120,5,194,5,224,5,244,6,14,6,84,6,224,7,12,7,80,7,122,7,162,7,184,7,208,8,0,8,24,8,46, - 8,76,8,116,8,132,8,170,8,202,8,254,9,42,9,98,9,160,9,248,10,10,10,66,10,98,10,152,10,208,10,246,11,20,11,38,11,68,11,86,11,116,11,128,11,152,11,234,12,52,12,100,12,180,12,238,13,16, - 13,108,13,148,13,194,13,236,14,18,14,38,14,96,14,128,14,176,14,222,15,18,15,60,15,122,15,152,15,190,15,224,16,18,16,76,16,146,16,178,16,240,16,254,17,68,17,122,130,1,8,225,158,17,228, - 18,12,18,88,18,142,18,162,19,32,19,66,19,176,19,246,20,40,20,56,20,68,20,192,20,206,21,8,21,34,21,80,21,160,21,184,21,232,22,4,22,32,22,62,22,88,22,146,22,198,23,4,23,80,23,196,24, - 40,24,96,24,146,24,208,25,46,25,116,25,188,25,228,26,48,26,84,26,114,26,156,26,212,26,244,27,16,27,52,27,100,27,154,27,244,28,46,28,98,28,162,29,10,29,82,29,144,30,0,30,68,30,134,30, - 210,31,38,31,84,31,122,31,212,32,68,32,176,33,36,33,182,34,50,34,188,35,44,35,128,35,206,36,24,36,104,36,192,36,238,37,20,37,64,37,118,37,216,38,38,38,104,38,160,38,222,39,60,39,134, - 39,174,39,250,40,50,40,100,40,158,40,226,41,42,41,92,41,178,42,16,0,2,0,34,0,0,1,50,2,170,0,3,0,7,0,46,177,1,0,47,60,178,7,4,0,237,50,177,6,5,220,60,178,3,2,130,10,34,0,177,3,131,22, - 32,5,131,22,39,178,7,6,1,252,60,178,1,131,23,53,51,17,33,17,39,51,17,35,34,1,16,238,204,204,2,170,253,86,34,2,102,0,130,83,8,71,237,255,255,1,126,2,228,0,14,0,20,0,0,37,50,23,22,20, - 14,1,35,34,39,38,53,52,55,54,19,3,35,3,53,51,1,53,50,17,6,33,25,15,32,19,21,21,19,85,15,80,18,113,140,42,13,47,30,9,19,19,24,41,19,19,1,221,254,160,1,96,123,0,131,75,38,169,1,185,1, - 191,2,189,132,159,34,0,1,17,131,115,39,51,17,1,104,87,254,234,87,130,25,35,4,254,252,1,130,3,61,0,2,0,1,0,5,2,102,2,183,0,5,0,46,0,0,19,51,54,55,35,6,15,1,35,62,1,55,35,53,130,12,130, - 14,38,53,51,55,51,14,1,7,134,5,33,21,35,131,11,34,21,35,7,131,34,51,229,123,31,11,123,11,50,52,80,10,32,10,129,149,7,13,14,7,133,152,132,12,32,123,132,5,40,121,140,8,26,8,125,144,53, - 79,130,30,51,1,10,112,46,46,178,195,37,121,37,71,30,49,49,29,73,194,37,120,37,131,3,36,73,29,98,30,71,131,22,32,0,130,169,8,40,91,255,237,2,41,2,210,0,8,0,18,0,72,0,0,1,21,54,55,54, - 53,52,39,38,39,53,6,7,6,29,1,6,23,22,19,46,1,39,38,35,38,131,18,39,22,23,30,1,23,22,23,53,130,12,8,166,52,55,54,55,53,51,21,20,30,4,23,21,39,38,47,2,34,39,21,22,23,22,21,20,7,6,7,21, - 1,102,56,26,31,31,32,132,62,25,8,2,26,30,44,1,1,1,3,7,12,25,79,59,21,30,13,23,16,36,46,82,53,50,53,61,71,82,56,19,21,20,20,11,22,35,25,33,16,8,8,98,43,54,58,63,74,1,54,205,10,20,37, - 49,39,29,21,91,194,5,62,20,6,10,25,34,24,254,84,10,37,11,1,1,5,13,23,85,12,15,5,9,6,13,2,217,11,45,42,144,45,50,6,57,57,3,10,3,5,4,6,3,81,10,14,7,8,2,1,202,16,43,46,71,72,50,49,4,58, - 0,5,0,19,0,17,2,84,2,172,130,9,38,22,0,38,0,55,0,71,130,219,37,0,7,35,18,19,3,130,166,33,51,50,133,228,38,35,34,7,6,20,23,6,65,239,7,33,51,50,131,193,33,1,22,131,30,32,52,130,239,40, - 38,34,14,2,21,20,55,20,7,140,33,8,124,2,40,254,177,58,96,234,160,60,13,34,7,11,24,20,20,20,19,21,52,17,5,165,43,54,52,46,38,39,36,61,55,41,40,254,24,13,34,27,20,20,5,10,27,12,27,23, - 20,10,204,68,33,25,67,41,39,67,30,26,68,42,40,2,172,253,200,98,1,140,1,14,253,205,28,10,1,18,20,19,32,18,19,38,11,27,77,38,37,38,53,57,36,36,37,40,51,54,1,162,18,18,20,38,11,23,11, - 4,8,18,22,14,27,28,75,37,17,37,35,56,73,40,16,38,36,0,130,0,63,3,0,29,255,243,2,98,2,209,0,11,0,37,0,85,0,0,19,62,1,53,52,35,34,6,7,6,23,22,3,20,23,132,223,45,63,1,54,55,62,2,55,38, - 39,38,47,1,38,39,130,26,43,55,38,53,54,55,54,51,50,30,1,29,1,130,208,41,7,30,3,23,54,61,1,54,38,59,132,13,34,22,23,34,131,227,37,6,43,1,34,39,38,130,22,8,147,237,30,57,71,34,40,3,14, - 38,19,102,53,29,57,18,15,53,41,12,5,6,7,4,3,2,26,20,34,19,67,17,27,47,26,22,50,86,2,75,42,52,35,78,35,34,24,59,33,53,40,46,26,38,1,2,1,81,20,19,36,36,49,43,47,5,10,40,81,104,8,100, - 73,70,13,1,221,18,49,44,61,35,14,53,35,17,254,239,71,49,27,13,4,23,6,3,3,4,5,1,1,34,26,41,26,86,21,36,36,33,38,163,66,66,99,37,23,23,60,24,38,41,45,31,41,42,69,53,57,33,46,91,26,6, - 24,108,52,51,38,45,63,1,52,64,63,64,85,20,127,130,250,52,0,1,1,10,1,186,1,102,2,191,0,3,0,0,1,17,51,17,1,10,92,130,16,34,5,254,251,130,14,41,0,168,255,174,1,141,3,7,0,7,130,12,55,6, - 16,23,35,38,16,55,1,141,132,132,80,149,149,3,7,217,254,88,216,224,1,157,220,130,26,39,0,205,255,179,1,178,3,12,132,39,8,48,22,16,7,35,54,16,39,1,29,149,149,80,132,132,3,12,220,254, - 96,221,216,1,175,210,0,0,1,0,46,0,90,2,57,2,100,0,27,0,0,19,39,54,55,22,23,53,51,21,55,131,7,8,64,7,23,22,23,7,46,1,39,21,35,53,7,39,54,219,173,19,25,129,43,87,88,55,33,14,30,176,88, - 54,33,44,33,109,33,87,174,42,99,1,100,96,28,40,70,24,186,186,48,30,17,20,49,96,48,30,19,68,18,59,18,196,196,92,67,56,132,203,48,0,41,0,100,2,61,2,85,0,11,0,0,37,53,35,53,51,130,94, - 49,51,21,35,21,1,8,223,223,84,225,225,100,208,80,209,209,80,208,130,135,44,205,255,85,1,125,0,141,0,25,0,0,23,38,130,136,45,54,55,34,38,39,38,53,52,55,54,51,50,23,22,65,207,5,8,44, - 6,241,6,30,59,17,7,7,20,29,5,4,43,13,15,32,19,22,3,13,91,17,171,8,42,51,37,15,18,29,13,13,15,49,18,4,19,20,31,6,15,17,92,86,16,130,83,40,83,1,52,2,23,1,133,0,5,130,219,46,53,33,21, - 22,21,83,1,195,1,1,52,81,40,25,16,130,156,38,1,0,237,255,255,1,126,130,115,35,13,0,0,4,139,109,8,34,20,1,85,47,25,11,21,44,13,16,30,20,22,1,9,10,19,33,48,18,5,20,20,63,0,0,1,0,65,255, - 208,2,41,2,230,131,83,8,37,23,0,55,51,0,7,65,1,38,99,95,254,217,98,48,2,81,197,253,176,198,0,0,3,0,67,255,243,2,38,2,203,0,7,0,18,0,32,130,247,51,50,17,52,39,6,7,22,19,38,35,34,7,6, - 21,20,23,54,55,5,16,67,111,6,32,16,131,221,8,57,1,56,148,8,104,149,35,185,33,78,93,35,21,8,63,63,1,1,137,45,60,120,60,61,241,121,60,61,72,1,34,48,46,130,182,72,1,232,72,111,77,102, - 49,46,79,78,54,254,240,68,23,92,91,180,1,109,92,88,130,198,130,147,39,132,0,0,1,254,2,189,0,130,199,8,34,51,53,51,17,6,7,38,53,54,55,51,17,51,21,132,144,32,111,1,107,35,94,142,82,2, - 0,25,89,82,33,80,26,253,149,82,133,51,44,76,0,0,2,30,2,202,0,54,0,0,1,34,130,48,33,62,1,131,137,36,21,20,14,1,7,130,2,49,6,15,1,14,5,7,33,21,33,53,52,62,4,63,1,62,3,55,69,50,5,8,102, - 46,1,35,1,27,70,132,1,96,93,23,100,67,65,30,12,8,20,49,10,30,34,18,9,14,20,19,20,28,17,1,100,254,46,27,33,39,42,40,12,22,17,14,9,18,11,47,9,5,37,16,53,15,2,123,73,58,29,51,14,55,52, - 89,49,62,15,12,30,49,11,33,34,16,7,18,16,18,22,27,17,82,63,17,26,34,38,43,40,13,22,19,12,12,20,13,61,40,19,24,52,33,15,19,130,211,44,75,255,243,2,34,2,203,0,56,0,0,19,54,131,154,69, - 120,6,69,128,6,37,43,1,38,39,46,1,69,175,5,33,22,51,68,234,6,34,43,1,53,68,245,11,8,161,7,97,120,73,74,64,58,26,16,6,31,97,93,37,22,69,67,127,25,12,14,54,35,14,23,31,65,23,62,45,131, - 34,10,44,44,67,86,77,107,30,10,36,33,72,51,88,25,26,2,172,31,29,26,56,34,29,46,17,78,24,23,68,36,51,101,55,55,1,1,4,10,3,5,11,95,30,5,15,77,25,32,65,34,36,78,63,20,27,54,28,29,21,7, - 10,0,2,0,40,0,0,2,64,2,189,0,6,0,17,0,0,55,51,17,14,3,39,1,51,17,51,21,35,21,35,53,33,136,242,61,108,39,24,106,1,26,135,119,119,90,254,185,245,1,114,87,170,61,38,6,1,180,254,56,78, - 167,167,0,0,0,1,0,72,130,227,32,23,130,63,32,36,135,227,36,21,20,7,14,1,132,218,34,2,39,53,136,214,8,69,39,38,34,7,17,33,21,33,196,47,35,120,69,68,109,50,80,22,36,12,14,69,41,20,10, - 88,96,129,37,11,9,15,17,53,170,66,1,135,254,214,1,194,14,65,64,109,141,62,25,11,1,1,5,12,7,3,97,46,90,30,29,48,22,36,15,47,35,1,96,79,130,175,38,67,255,246,2,38,2,191,130,173,32,54, - 130,175,136,95,66,149,6,38,22,39,54,51,50,23,22,70,9,6,67,123,7,39,54,59,1,30,2,23,21,38,130,149,8,91,35,6,7,6,214,34,68,101,25,9,53,30,51,69,34,37,21,8,46,51,117,105,57,60,61,56,117, - 130,58,49,9,3,89,89,104,9,19,7,25,32,30,17,8,60,44,19,9,9,73,69,51,108,43,92,30,39,99,42,22,43,46,75,59,36,12,249,97,63,62,226,63,60,85,71,113,38,43,192,83,87,1,4,9,4,3,88,32,1,2,71, - 71,0,130,0,8,62,1,0,70,0,0,2,28,2,189,0,9,0,0,9,1,35,18,55,54,55,33,53,33,2,28,254,244,105,120,101,22,17,254,155,1,214,2,150,253,106,1,39,232,54,41,79,0,0,3,0,66,255,243,2,39,2,203, - 0,14,0,28,0,58,130,209,33,20,23,132,211,34,52,39,38,131,210,34,55,50,53,134,9,32,21,130,24,34,37,20,7,66,58,6,36,35,34,38,53,52,130,91,33,38,39,68,96,6,130,244,8,95,167,82,26,33,65, - 40,37,37,37,68,69,35,37,141,125,32,30,63,93,24,8,72,23,1,0,121,78,29,31,16,58,170,113,128,39,24,75,43,23,32,9,14,60,61,208,61,61,198,100,28,10,36,37,128,37,35,35,35,145,115,60,28,30, - 67,22,28,85,24,7,126,135,26,17,46,46,75,49,38,115,104,97,73,49,47,16,11,26,32,25,38,35,76,50,49,49,51,130,222,39,0,2,0,63,255,249,2,35,130,175,38,13,0,53,0,0,19,20,66,171,11,40,18, - 38,39,53,22,23,30,1,54,130,152,36,6,7,14,1,34,133,156,130,14,66,251,10,8,97,6,7,38,163,134,68,34,37,79,29,23,78,30,34,59,32,72,36,31,19,36,61,35,100,18,18,19,39,63,81,40,86,30,15,23, - 11,61,139,130,59,34,12,15,23,42,93,47,63,36,1,219,164,43,43,78,118,36,11,41,42,253,206,1,17,78,15,6,1,2,1,18,50,198,36,15,30,16,15,33,90,44,42,71,67,19,97,89,49,65,73,62,114,65,133, - 46,22,4,2,133,167,45,239,0,111,1,129,2,66,0,15,0,32,0,0,1,72,26,14,34,3,22,21,130,17,132,159,32,52,130,172,40,54,50,1,129,22,20,23,39,20,130,0,57,23,55,21,5,45,44,22,19,48,13,26,11, - 6,5,10,29,13,31,1,251,33,18,20,20,16,35,130,5,49,42,13,254,236,17,56,24,20,19,5,9,28,13,31,13,25,12,5,130,108,36,2,0,209,255,197,132,107,38,31,0,47,0,0,23,54,130,81,35,34,38,39,38, - 132,89,69,248,10,37,7,6,7,46,3,19,142,137,60,209,42,14,18,15,19,29,5,4,5,9,29,13,15,31,20,22,3,3,4,21,29,51,29,6,9,8,8,171,139,147,62,9,36,19,24,42,29,13,13,31,12,26,12,5,20,20,31, - 6,12,18,29,12,54,34,58,18,7,13,11,12,2,11,138,162,130,146,8,57,0,1,0,41,0,116,2,57,2,75,0,14,0,0,45,1,53,36,55,21,14,2,7,30,2,31,1,2,57,253,240,1,140,132,91,126,156,52,28,74,115,78, - 130,116,196,78,148,49,86,33,44,55,19,9,26,41,27,45,132,207,38,45,0,205,2,61,1,245,75,31,5,36,55,53,33,21,37,130,3,44,45,2,16,253,240,2,16,205,81,81,216,80,80,133,99,58,44,0,114,2,60, - 2,73,0,11,0,0,1,37,53,4,23,21,5,53,62,1,55,54,1,213,254,87,130,98,60,253,240,28,73,58,195,1,93,151,85,148,49,78,196,86,9,26,21,68,0,2,0,81,255,255,2,33,2,223,130,151,130,107,75,199, - 14,61,3,39,62,1,51,50,22,29,1,6,15,1,14,1,29,1,35,53,54,55,62,2,53,54,39,38,43,1,34,6,75,223,12,56,124,72,33,130,78,106,117,2,85,32,29,44,96,2,87,17,48,45,1,25,38,73,9,37,94,75,243, - 12,56,156,46,52,85,86,73,4,77,60,22,21,44,30,55,54,72,61,13,34,45,25,41,20,29,57,131,191,44,2,255,251,255,225,2,162,2,224,0,16,0,95,130,193,36,35,38,7,6,7,74,116,10,46,19,22,23,14, - 1,7,6,35,34,39,38,39,46,1,53,65,206,8,33,21,20,130,39,42,6,35,17,38,35,53,6,7,6,46,1,68,101,6,8,203,54,30,1,31,1,22,23,51,22,55,54,61,1,54,39,46,2,34,6,7,14,2,29,1,20,23,22,23,62,1, - 1,111,10,10,17,53,6,6,22,32,37,38,29,29,62,17,236,3,50,12,49,40,78,96,83,79,104,75,45,18,27,56,132,64,54,196,88,31,8,14,39,14,19,56,18,20,38,30,69,46,33,53,83,43,60,26,43,17,7,14,9, - 12,34,12,11,5,2,38,18,71,53,42,37,32,84,77,27,82,82,122,81,117,1,229,1,8,27,94,64,32,32,35,33,60,91,29,8,254,167,3,59,10,43,19,37,25,32,109,63,104,50,98,64,142,54,26,98,37,60,18,26, - 47,15,7,254,242,1,45,34,16,14,6,27,29,62,86,119,66,37,2,22,10,4,14,9,13,2,23,10,6,7,25,36,16,33,7,2,11,31,113,93,47,12,115,100,87,3,1,41,0,0,2,0,18,130,4,45,86,2,189,0,10,0,23,0,0, - 19,51,46,3,39,130,202,8,61,1,15,1,35,54,19,51,22,18,30,1,23,35,39,202,213,13,39,30,18,7,13,19,37,30,32,54,105,41,188,123,28,83,63,39,15,104,56,1,3,44,132,98,62,23,43,67,125,100,100, - 183,124,2,65,85,254,254,192,120,46,183,0,130,0,38,3,0,79,255,255,2,58,132,87,45,21,0,44,0,0,55,51,50,55,54,52,38,39,38,70,243,10,42,43,1,3,17,51,50,23,22,23,20,7,71,197,5,68,240,7, - 8,88,175,149,124,26,10,20,20,40,80,149,127,104,23,8,33,32,82,115,96,207,112,64,60,2,6,13,21,6,12,30,17,84,26,41,66,69,129,78,67,24,67,51,16,32,78,60,21,28,57,21,24,253,144,2,189,46, - 46,86,39,15,30,26,7,13,10,7,22,38,47,76,94,50,49,0,1,0,70,255,243,2,25,2,203,0,25,0,0,37,6,76,84,10,39,21,38,35,34,7,6,21,16,131,151,8,41,55,2,25,76,90,147,76,78,139,71,91,88,78,79, - 87,98,49,49,197,58,68,20,19,25,38,95,96,171,232,90,44,39,97,58,71,74,142,254,225,34,10,15,130,218,39,0,2,0,69,0,0,2,44,130,219,34,12,0,23,134,217,34,53,52,39,132,219,133,208,8,32,21, - 16,7,6,35,170,86,153,32,13,50,25,23,41,62,83,101,189,172,63,63,172,55,71,78,142,54,78,157,56,30,11,18,131,173,39,85,87,179,254,250,66,22,0,130,163,32,94,130,79,32,35,130,79,38,11,0, - 0,51,17,33,21,135,1,49,94,1,196,254,161,1,53,254,203,1,96,2,189,79,208,80,254,80,130,43,32,117,130,43,36,41,2,190,0,12,131,43,34,50,54,51,131,44,53,51,21,35,17,117,28,75,60,1,17,254, - 174,246,246,2,189,1,76,222,76,254,184,131,171,34,1,0,51,130,255,32,40,130,255,32,31,135,255,74,164,8,32,21,130,177,65,3,8,8,53,53,35,53,51,2,40,86,116,71,56,61,36,75,80,81,139,96,79, - 25,38,43,58,109,47,49,194,60,45,134,230,57,70,24,29,45,94,170,175,94,97,50,98,25,19,26,71,71,146,254,226,30,189,78,0,130,143,32,69,130,143,32,36,135,187,79,93,5,55,35,17,33,17,69,101, - 1,20,102,102,254,236,2,189,254,225,1,31,253,67,1,78,254,178,130,144,34,1,0,100,130,47,32,3,134,47,37,53,51,17,35,53,33,130,188,47,51,21,100,157,157,1,159,157,157,80,2,30,79,79,253, - 226,68,115,6,36,61,255,247,1,222,130,43,32,17,131,187,33,7,6,66,58,7,131,52,61,17,20,1,169,38,51,29,63,183,185,80,23,28,191,1,36,41,38,7,5,77,30,36,95,1,137,79,254,40,132,134,151,32, - 100,130,59,53,24,0,0,51,17,51,17,62,3,55,51,6,7,30,2,23,35,46,3,39,6,7,130,159,51,38,116,86,55,20,119,194,97,126,102,52,19,122,29,90,66,42,16,58,19,130,173,52,200,38,115,85,54,20,191, - 95,173,143,72,27,43,129,96,60,23,57,20,254,238,130,79,32,108,130,183,32,57,130,79,32,5,133,79,41,33,21,108,101,1,104,2,189,253,147,134,171,32,38,130,31,32,68,130,31,50,20,0,0,1,3,35, - 39,46,2,39,17,35,17,51,22,23,62,2,55,130,229,8,40,1,236,145,77,21,13,39,54,17,88,135,90,45,18,86,24,8,136,88,2,102,254,142,56,32,101,137,44,253,154,2,189,229,115,45,218,59,22,253,67, - 0,72,87,8,32,35,133,247,37,51,17,51,30,3,23,130,192,8,38,35,46,1,39,38,39,17,70,128,31,92,69,43,17,97,128,31,93,34,72,22,2,189,69,210,156,98,38,2,59,253,67,70,210,78,164,49,253,197, - 130,63,48,2,0,58,255,247,2,46,2,198,0,13,0,29,0,0,18,16,72,101,5,46,16,39,38,35,34,7,19,34,17,16,55,54,50,22,23,130,1,8,58,21,16,7,6,164,34,33,77,78,33,34,34,35,76,75,35,110,250,141, - 47,93,54,24,48,32,61,141,50,1,242,254,216,68,65,65,64,1,48,64,67,67,253,193,1,103,1,15,66,23,11,11,22,46,94,176,254,239,65,21,130,102,39,0,2,0,86,0,0,2,46,130,167,41,12,0,26,0,0,19, - 51,50,55,54,79,194,5,67,216,8,8,51,22,20,7,6,43,1,17,187,117,56,33,11,10,39,39,40,78,109,101,218,125,65,35,10,19,16,49,189,117,1,104,21,7,7,37,61,60,37,34,253,144,2,189,53,30,28,49, - 101,39,119,254,230,130,87,36,58,255,159,2,104,130,191,42,23,0,32,0,0,37,30,1,23,21,35,130,251,35,6,34,39,38,137,188,54,16,1,6,16,22,50,54,16,38,34,1,248,26,56,30,64,62,23,24,53,145, - 47,140,135,193,52,254,152,34,68,153,68,69,151,92,29,66,35,59,70,27,27,35,22,66,1,14,136,195,43,254,171,1,125,68,254,217,134,130,1,47,131,130,111,32,72,130,199,32,50,130,199,34,9,0, - 40,134,199,34,52,39,38,135,196,44,21,20,6,7,6,7,30,4,31,1,35,46,2,130,134,32,35,130,25,8,43,17,173,111,82,33,36,38,36,79,109,101,219,123,54,66,23,24,34,56,16,19,6,13,35,28,48,107,54, - 45,16,6,16,13,59,12,24,37,1,119,31,30,124,32,32,131,220,55,52,60,88,45,60,26,32,28,29,34,13,24,66,54,90,105,91,31,11,31,26,1,254,216,68,159,6,36,37,2,203,0,58,74,225,11,130,102,73, - 237,8,43,51,50,23,30,2,23,21,38,47,1,38,34,130,136,36,6,21,20,23,22,130,1,33,30,1,76,96,5,8,108,34,39,46,1,39,79,110,102,118,33,11,29,27,75,14,7,62,40,58,24,47,103,63,79,37,54,16,45, - 26,13,39,21,32,43,87,28,58,21,11,6,8,14,32,69,13,13,39,189,146,48,90,27,57,75,27,130,67,72,23,28,52,27,27,17,3,1,9,16,25,24,43,77,118,57,33,9,4,11,9,4,96,23,7,12,13,7,17,45,21,20,32, - 12,19,13,28,13,3,3,8,38,165,153,40,13,3,5,24,10,0,130,175,43,24,0,0,2,81,2,189,0,7,0,0,33,67,189,6,44,1,2,234,2,57,234,2,110,79,79,253,146,0,131,35,36,60,255,243,2,43,130,35,37,34, - 0,0,5,35,34,132,204,130,164,37,38,53,17,51,17,20,71,116,6,33,55,54,132,13,131,208,60,1,82,29,49,59,10,9,42,12,30,18,4,16,103,21,11,38,75,54,24,56,10,2,101,11,17,34,61,13,130,119,60, - 19,11,25,41,12,48,105,1,176,253,250,43,34,11,32,11,27,52,20,205,1,67,254,80,105,35,58,30,48,132,111,32,29,130,147,32,76,130,111,32,15,130,124,36,2,3,35,38,2,130,114,8,44,51,30,3,23, - 19,2,76,111,107,123,27,80,30,48,33,98,12,31,49,67,22,181,2,189,254,162,254,161,85,1,2,96,155,107,40,106,168,226,75,2,103,0,1,0,2,130,63,32,102,130,63,32,30,130,63,40,3,35,47,1,38,47, - 1,14,2,130,154,34,35,2,3,132,70,8,72,51,18,23,22,23,18,55,2,102,109,99,40,25,10,8,15,4,10,16,12,41,15,98,44,66,86,10,28,21,14,5,86,112,39,14,26,8,58,19,2,189,253,67,244,157,59,51,85, - 22,59,99,75,254,87,1,9,1,180,68,206,153,96,37,2,48,254,255,88,173,43,1,165,140,130,107,32,9,130,107,32,95,130,107,32,31,132,107,36,19,54,55,46,1,132,173,8,83,1,23,19,51,6,7,14,1,7, - 22,23,30,1,23,35,38,39,46,1,1,59,197,109,174,46,30,17,40,31,64,83,108,39,100,44,167,109,28,41,45,95,14,47,113,22,42,15,108,12,16,32,101,1,46,254,210,1,2,68,46,23,56,43,88,119,57,143, - 64,1,8,40,61,68,138,22,75,173,36,64,24,20,26,52,167,130,98,71,223,8,32,19,130,12,33,19,51,130,95,36,6,7,17,35,17,131,94,8,45,39,51,22,23,22,1,52,181,109,29,88,33,51,39,101,29,44,78, - 72,16,108,44,47,64,1,136,1,53,46,143,52,82,63,254,197,1,59,47,71,126,117,25,76,79,107,0,130,62,33,0,55,130,187,32,49,130,187,8,47,16,0,0,51,53,54,18,54,55,33,53,33,21,14,3,7,33,21, - 55,109,180,65,25,254,144,1,229,26,67,106,144,47,1,144,73,156,1,6,95,36,79,71,36,95,150,202,67,80,131,59,44,148,255,166,1,205,3,24,0,7,0,0,23,17,69,243,5,43,148,1,57,220,220,90,3,114, - 74,253,35,75,132,95,8,52,62,255,210,2,40,2,233,0,13,0,0,19,22,23,18,31,1,35,39,46,1,47,1,38,39,158,31,43,212,41,67,96,60,34,62,25,50,121,42,2,233,62,85,254,84,82,134,120,68,124,51, - 102,244,80,31,6,36,154,255,167,1,210,134,95,70,87,5,44,17,154,220,220,1,56,89,75,2,220,74,252,143,132,95,36,61,1,177,2,43,130,191,32,14,130,144,39,7,35,19,51,30,1,23,22,65,106,6,59, - 52,136,111,203,88,25,74,28,58,18,111,8,12,24,75,2,112,191,1,12,32,99,36,77,24,13,16,32,130,252,45,1,255,247,255,167,2,114,255,243,0,3,0,0,7,130,245,49,9,2,123,89,76,76,0,1,0,167,2, - 51,1,169,3,2,0,10,130,83,33,35,38,65,202,6,8,33,22,1,169,112,33,39,64,10,111,9,26,20,48,2,51,46,56,92,13,13,36,29,67,0,0,2,0,68,255,243,2,19,2,27,130,227,32,57,78,1,9,38,61,1,35,34, - 7,6,5,72,159,8,49,55,54,59,1,53,52,39,38,43,1,34,7,53,51,50,62,1,50,130,168,32,22,82,86,5,8,94,35,34,39,54,52,38,160,70,21,27,78,44,38,116,96,42,24,1,31,48,144,84,50,53,35,38,54,59, - 77,107,36,37,61,88,34,40,40,19,32,40,50,24,59,27,76,14,8,1,31,10,42,2,2,158,73,20,7,57,50,81,18,39,22,133,83,44,45,81,67,39,40,13,17,13,68,25,27,2,73,1,1,3,9,15,40,66,36,76,250,24, - 21,1,30,14,15,131,163,32,96,130,163,52,44,2,246,0,25,0,47,0,0,19,20,23,22,50,55,54,55,62,2,55,54,130,147,36,46,1,34,6,7,132,1,79,126,5,68,133,5,32,7,131,186,8,86,6,7,35,17,51,193,70, - 28,69,19,32,18,28,16,4,2,1,43,26,51,46,37,14,30,10,20,4,6,5,48,107,86,52,57,15,3,47,23,43,40,61,106,48,5,4,83,92,1,7,134,50,20,5,8,21,31,54,35,17,17,16,114,47,29,13,10,10,21,22,41, - 25,46,168,80,52,54,121,24,24,110,78,38,27,24,80,44,23,130,136,35,0,1,0,82,130,147,36,3,2,27,0,30,73,199,14,36,22,23,21,38,39,69,25,9,8,57,51,50,55,2,3,72,91,128,73,69,123,62,87,54, - 24,50,33,41,24,45,76,27,47,35,41,76,40,67,91,62,27,40,76,72,128,167,74,35,7,16,17,91,32,9,17,7,12,40,53,91,123,53,28,58,0,2,0,61,130,95,43,9,2,245,0,28,0,51,0,0,55,30,1,130,72,130, - 243,36,1,55,54,52,39,130,95,35,39,38,35,34,130,245,36,14,2,21,20,5,130,234,132,17,32,52,78,236,7,8,37,17,51,17,35,38,200,24,48,22,42,20,37,11,16,6,2,1,1,2,2,3,12,35,80,45,26,29,9,17, - 6,3,1,14,50,101,62,63,17,130,252,8,60,30,29,57,102,75,48,16,11,92,83,2,101,29,13,15,26,29,35,49,17,17,32,17,17,17,30,26,80,20,22,22,37,52,34,16,114,82,80,37,16,54,122,25,88,100,37, - 73,45,15,20,1,42,253,11,19,0,0,0,2,0,62,130,159,32,44,130,255,38,10,0,36,0,0,19,33,132,149,131,147,32,1,87,7,12,35,29,1,33,21,80,85,6,8,67,55,162,1,47,14,21,60,20,26,69,46,40,1,110, - 96,100,129,74,74,116,60,83,170,50,15,254,114,46,46,90,72,76,23,24,1,54,37,42,54,18,5,46,38,254,157,40,72,74,126,164,79,37,148,46,46,56,3,83,48,50,33,10,11,0,0,1,0,66,130,120,44,40, - 2,224,0,22,0,0,51,17,35,53,51,53,131,242,34,59,1,21,131,119,8,35,29,1,51,21,35,17,231,165,165,22,21,43,99,136,140,50,19,19,169,169,1,143,78,71,43,84,21,40,73,19,17,62,88,78,254,113, - 130,62,37,0,76,255,3,2,23,130,183,37,18,0,63,0,0,19,134,155,32,53,131,190,33,46,1,80,245,5,49,23,52,38,53,51,6,29,1,6,20,14,3,35,7,53,51,54,55,131,1,34,53,6,7,132,217,34,39,46,3,77, - 142,5,8,106,168,83,26,33,98,27,8,9,15,13,28,47,27,60,38,38,125,105,55,1,83,1,1,1,17,62,60,45,222,102,53,36,66,34,33,1,32,29,48,40,70,42,20,17,29,32,10,6,48,24,43,42,1,13,147,41,12, - 113,37,33,77,27,50,16,31,13,50,50,173,67,13,29,10,34,45,95,93,193,113,99,66,37,2,78,1,1,2,46,46,60,77,38,9,15,24,13,15,28,72,48,48,24,110,74,37,26,24,131,251,32,97,130,188,35,13,2, - 245,0,130,12,42,19,54,59,1,50,23,22,21,17,35,17,81,160,6,33,7,6,131,12,8,38,51,189,50,106,10,68,38,64,92,57,20,26,73,38,19,7,4,92,92,1,207,80,32,57,127,254,185,1,71,105,23,9,52,26, - 47,20,21,254,214,130,68,35,0,2,0,166,130,84,51,129,2,219,0,21,0,33,0,0,33,35,53,54,61,1,35,53,51,21,20,130,248,34,22,29,1,130,2,41,20,6,17,20,43,1,34,61,1,52,130,109,38,21,1,128,92, - 1,127,218,130,222,63,1,15,71,16,16,71,15,114,28,120,187,77,64,16,35,37,126,11,23,40,16,18,66,16,37,2,103,14,14,81,14,14,130,166,37,0,118,255,4,1,187,130,91,43,15,0,27,0,0,23,53,51, - 50,54,53,17,130,92,41,17,20,6,7,6,35,19,50,29,1,134,88,63,51,118,143,46,44,144,236,22,23,45,80,149,14,14,73,14,14,252,80,80,58,1,227,77,253,208,46,96,25,51,3,215,131,79,32,81,130,81, - 130,170,33,0,113,130,88,34,84,2,218,130,175,8,61,0,1,7,21,35,17,51,17,62,1,55,54,55,51,6,7,30,3,23,35,38,1,20,68,95,95,29,89,33,40,51,111,158,62,31,94,69,44,17,113,186,1,15,60,211, - 2,218,254,90,27,80,30,37,44,141,57,40,121,89,56,22,245,131,75,32,141,130,4,36,119,2,190,0,8,130,7,55,7,17,35,17,52,39,35,53,1,119,2,92,1,139,2,190,192,254,2,2,9,40,63,78,130,26,41, - 0,41,0,0,2,69,2,27,0,38,130,12,33,54,51,65,114,13,32,21,130,55,76,176,7,130,10,8,72,51,20,6,21,54,55,50,1,71,46,85,66,29,28,84,15,12,39,38,25,16,84,3,9,17,30,55,14,15,84,77,1,33,89, - 60,1,217,66,47,50,137,254,207,1,45,114,26,26,29,26,111,254,211,1,96,69,16,30,28,26,112,254,211,2,14,8,29,9,57,2,0,1,0,65,231,5,40,27,0,18,0,0,1,52,35,34,65,217,6,33,22,23,130,127,130, - 114,61,1,177,107,100,28,9,92,83,7,2,51,114,171,92,1,71,137,95,31,40,254,214,2,14,49,30,92,212,254,185,130,174,37,0,69,255,243,2,36,130,179,34,15,0,28,66,223,13,131,75,35,19,34,39,38, - 88,17,6,8,51,16,6,166,81,27,34,67,39,37,82,26,35,69,36,37,143,179,46,15,15,46,178,117,61,62,122,1,7,146,44,14,54,53,97,149,41,13,52,51,254,136,157,51,134,51,159,71,70,254,243,142,0, - 131,95,36,95,255,3,2,42,130,95,32,10,131,95,34,37,50,16,132,162,36,20,23,22,23,34,76,96,6,65,40,5,46,20,7,6,1,82,132,132,101,28,9,79,25,34,105,46,131,177,8,32,48,103,99,60,57,127,39, - 59,1,151,117,37,49,147,43,14,72,80,254,192,3,11,41,26,80,74,73,129,196,62,18,0,2,130,187,40,4,2,15,2,26,0,14,0,32,85,95,15,39,20,1,54,55,51,17,35,17,68,93,10,8,33,190,34,65,66,34,35, - 78,25,32,65,34,35,1,24,7,2,83,92,47,105,136,53,25,127,40,50,101,111,54,54,51,99,151,39,130,191,47,199,1,40,38,28,252,248,1,62,81,130,61,74,206,63,19,130,195,34,1,0,129,130,200,32,25, - 130,195,44,25,0,0,1,38,43,1,34,6,7,6,29,1,130,195,8,53,21,35,17,51,22,20,6,21,54,59,1,22,23,2,25,56,84,39,10,63,21,45,1,1,92,90,1,2,56,127,5,82,49,1,155,48,24,21,45,43,42,30,48,146, - 60,2,14,6,18,24,23,84,2,38,130,82,35,0,1,0,106,70,15,6,39,39,0,0,1,34,21,20,23,75,15,9,86,136,10,33,46,1,84,150,5,8,72,55,54,50,23,21,38,1,67,121,25,28,109,12,139,59,59,183,108,108, - 80,57,36,35,29,27,67,10,9,29,66,40,36,55,54,185,83,80,1,211,78,37,17,17,19,2,26,116,78,45,45,32,90,51,24,21,40,36,19,19,13,2,2,6,12,36,34,60,76,41,40,31,84,43,133,123,41,128,255,254, - 1,230,2,174,0,17,0,74,223,5,36,53,17,51,21,51,130,204,130,210,59,59,1,1,230,169,103,43,43,92,221,221,24,22,60,160,2,39,41,94,2,2,160,79,254,237,59,18,18,130,60,51,1,0,84,255,242,2, - 20,2,13,0,24,0,0,37,6,43,1,38,35,34,130,61,8,61,17,20,51,54,55,54,53,54,53,51,20,22,29,1,35,1,190,37,123,9,4,5,184,91,124,73,30,34,3,92,1,86,57,71,1,213,1,69,254,187,139,8,36,40,57, - 240,83,63,194,72,196,0,0,1,0,50,0,0,2,54,2,14,131,135,40,1,3,35,46,3,39,51,23,22,130,1,8,40,62,1,63,1,2,54,198,119,25,72,55,34,13,95,50,30,22,46,15,26,57,30,50,2,14,253,242,64,194, - 143,91,34,135,81,60,125,40,68,157,81,135,131,67,130,148,33,2,104,130,67,32,27,130,12,43,3,35,2,38,39,51,30,2,23,19,51,23,130,5,131,71,32,51,130,87,8,58,1,39,1,52,89,88,89,33,9,91,22, - 49,16,6,72,102,25,16,22,14,5,11,31,12,31,91,131,88,11,32,12,1,33,254,223,1,100,136,34,93,220,70,27,1,4,80,48,71,44,17,50,151,56,153,253,242,35,107,39,130,93,130,167,32,38,130,167,32, - 67,130,99,39,35,0,0,51,54,55,46,2,130,99,46,3,23,62,1,55,51,14,3,7,30,1,23,35,39,38,130,1,33,7,6,130,1,57,38,140,80,61,92,34,14,103,18,55,40,26,9,109,29,10,103,24,74,55,34,14,25,169, - 27,107,130,198,33,45,17,132,4,58,171,103,79,113,44,16,23,70,52,33,12,139,39,12,31,92,69,43,17,30,211,33,65,38,29,58,21,132,4,133,115,8,40,70,255,2,2,25,2,15,0,50,0,0,23,51,54,59,1, - 50,55,54,53,54,52,39,35,34,38,61,1,52,55,53,50,54,51,17,20,23,22,59,1,17,130,241,34,54,51,21,69,131,5,130,5,8,80,20,6,35,33,38,54,119,59,45,37,102,39,17,25,1,1,189,84,100,1,17,57,18, - 24,25,68,163,1,1,35,11,47,1,1,1,88,66,254,248,1,1,174,1,29,45,64,10,18,8,100,63,252,32,28,50,1,254,202,77,31,27,1,82,54,52,1,83,41,37,76,40,66,115,51,32,32,81,127,21,39,0,130,255,32, - 101,130,255,32,8,130,139,32,17,130,255,33,53,54,88,38,5,32,21,131,238,8,34,6,7,33,21,101,39,60,114,109,254,203,1,150,39,59,115,60,27,21,1,65,80,46,70,134,129,68,78,46,70,136,69,33, - 24,71,131,63,40,92,255,151,2,3,3,38,0,44,66,111,6,130,193,83,72,8,130,11,32,55,130,222,71,147,6,32,20,84,214,5,33,29,1,132,219,8,76,2,3,33,122,44,43,26,27,56,72,59,71,25,26,43,43,123, - 33,36,68,22,21,23,26,48,46,28,23,21,24,46,56,105,34,35,109,113,70,28,23,88,21,28,72,111,109,35,35,84,14,19,71,110,74,33,40,11,10,41,33,76,115,63,19,15,0,1,1,6,255,181,1,92,3,9,0,3, - 130,123,43,17,51,17,1,6,86,75,3,84,252,172,0,131,151,32,102,130,151,32,16,130,151,40,50,0,0,23,53,51,50,55,54,132,140,34,55,38,39,130,1,137,163,33,23,22,132,142,35,23,22,51,22,72,59, - 8,130,167,8,99,35,102,34,72,20,22,22,31,43,28,16,37,9,6,22,20,72,34,31,124,43,42,10,6,7,33,65,16,21,28,32,96,35,23,42,42,125,105,83,16,20,70,108,74,34,42,9,6,15,31,40,26,59,97,63,20, - 14,84,35,34,110,113,36,24,11,10,37,1,88,39,33,61,100,109,36,34,0,1,0,40,0,241,2,61,1,215,0,33,0,0,19,39,54,55,54,51,50,23,30,1,130,115,130,149,33,55,23,87,136,6,131,151,8,89,35,34, - 7,14,1,118,78,12,21,41,76,37,19,28,41,11,57,36,56,13,5,3,77,33,36,83,39,22,33,28,51,16,19,19,38,17,7,12,1,20,18,71,36,70,11,15,41,14,76,73,22,27,17,51,59,68,12,19,37,65,10,13,33,27, - 44,0,2,0,232,255,227,1,138,2,193,0,6,0,20,0,0,55,54,55,51,19,21,35,2,52,131,115,33,22,21,133,106,8,34,246,9,29,60,34,132,14,23,21,37,35,46,49,15,17,37,21,181,79,187,254,246,210,2,102, - 76,21,23,46,27,66,18,5,21,0,130,71,48,105,255,109,2,18,2,161,0,8,0,43,0,0,37,17,6,7,79,220,5,34,53,38,39,89,241,5,36,54,55,53,51,21,130,197,32,21,130,16,32,39,71,127,5,32,21,130,36, - 37,35,21,1,93,66,40,130,0,8,70,66,117,60,67,13,22,24,70,115,51,62,49,19,46,23,34,27,8,16,8,48,50,11,9,55,55,59,1,151,6,56,54,87,88,54,56,212,135,9,75,75,115,58,37,60,28,82,12,134,134, - 8,17,8,81,26,5,8,3,254,102,1,3,1,10,28,81,4,4,23,135,0,82,115,8,43,44,2,203,0,27,0,0,19,52,51,50,23,131,115,73,231,8,8,47,21,33,21,33,53,51,53,35,53,51,187,227,62,70,9,8,50,60,103, - 20,8,185,185,1,12,254,26,117,99,99,1,221,238,28,86,5,5,31,96,33,61,86,68,218,80,80,218,68,130,219,42,102,0,92,2,38,2,0,0,13,0,47,70,91,11,8,32,34,7,6,20,23,7,38,39,54,55,46,1,53,52, - 55,38,39,55,23,54,50,23,55,23,22,23,7,22,20,7,22,23,6,130,27,8,86,6,34,250,32,45,46,30,31,31,30,92,30,32,11,82,10,36,80,3,22,7,30,72,12,48,82,50,90,50,83,22,14,9,83,30,31,23,61,38, - 9,80,3,50,90,229,28,28,31,42,43,29,28,28,28,86,92,76,10,32,75,3,36,43,11,44,43,69,10,44,79,29,28,78,22,13,8,79,49,88,39,21,57,33,11,75,3,29,133,231,86,239,7,43,35,0,0,1,6,7,21,51,21, - 35,21,35,131,216,33,53,39,130,221,79,22,8,8,80,23,19,51,7,14,1,7,51,21,1,145,5,38,201,201,101,200,200,45,155,122,19,30,68,33,11,108,44,47,64,27,181,109,50,51,53,11,126,1,130,9,62,17, - 51,247,247,51,17,71,52,32,48,111,55,17,76,79,107,47,1,53,80,80,86,17,52,0,0,2,1,10,255,188,1,96,3,2,0,3,0,7,67,61,5,8,45,3,17,51,17,1,10,86,86,86,68,1,101,254,155,1,226,1,100,254,156, - 0,2,0,99,255,164,2,6,2,203,0,17,0,85,0,0,19,20,23,22,23,54,53,52,39,38,130,1,33,6,7,130,1,32,5,92,10,8,37,43,1,39,46,3,39,70,224,11,35,2,53,52,55,66,44,6,35,51,31,1,22,130,58,86,216, - 5,66,74,6,33,30,1,130,17,8,129,22,181,42,40,112,61,8,12,17,39,117,28,18,4,3,9,1,81,92,50,5,4,51,50,86,20,20,27,18,20,43,11,88,60,73,26,7,61,38,46,87,46,16,92,59,50,35,61,18,18,39,20, - 9,13,20,53,82,60,42,13,33,7,7,18,26,59,5,5,20,92,36,33,1,98,35,37,36,53,38,48,20,13,20,15,35,58,18,25,4,5,19,77,84,48,44,32,14,25,58,39,40,2,3,4,3,12,3,77,36,43,13,15,44,36,25,25,47, - 50,41,25,87,46,39,67,61,38,27,7,3,2,130,0,8,40,3,17,77,37,7,20,15,16,11,22,18,26,33,3,2,10,46,41,37,0,0,0,2,0,160,2,123,1,201,2,217,0,11,0,23,0,0,1,52,59,1,74,174,6,33,53,39,138,11, - 36,1,99,16,70,16,130,2,43,195,14,72,15,15,72,14,2,204,13,13,68,135,2,33,0,3,130,71,51,58,2,104,2,126,0,27,0,51,0,75,0,0,37,50,55,21,6,34,39,91,150,5,46,51,50,23,21,46,2,43,1,34,7,6, - 21,20,22,7,82,126,9,75,202,9,34,20,23,22,79,122,7,68,56,9,89,249,5,8,126,1,85,45,46,52,106,36,73,28,12,13,42,139,57,56,35,43,14,6,13,64,31,33,70,150,55,90,24,26,74,68,64,33,18,76,70, - 111,56,32,137,27,5,32,9,1,105,53,92,160,96,52,35,17,91,165,99,72,45,34,8,50,35,35,42,26,219,25,49,22,11,24,68,31,82,32,103,20,51,17,6,2,34,33,64,60,68,26,63,19,5,42,37,72,42,37,116, - 68,70,14,56,123,23,24,54,64,15,124,35,130,73,87,61,76,24,129,48,31,41,12,70,87,83,52,60,28,20,0,130,219,38,135,0,220,1,224,2,203,130,9,41,17,0,46,0,0,55,53,33,21,3,130,203,130,179, - 33,50,55,130,173,34,61,1,21,73,162,8,80,51,5,8,122,34,7,53,54,63,1,50,23,22,29,1,35,38,146,1,78,138,104,22,8,22,22,62,22,43,18,9,53,80,96,33,9,103,33,56,79,49,27,93,71,40,60,35,132, - 33,11,64,4,220,59,59,1,43,37,13,49,18,18,8,18,46,22,19,22,130,61,70,22,28,89,28,8,1,55,20,11,31,59,16,9,2,92,31,44,211,18,0,0,0,2,0,40,0,67,1,245,1,242,0,12,0,29,0,0,1,23,21,39,53, - 62,3,55,21,14,1,7,22,23,21,38,39,46,1,130,15,32,1,130,148,8,49,21,6,1,94,151,235,29,86,64,40,16,29,93,255,78,72,15,20,53,118,28,28,87,32,61,26,78,1,26,126,89,196,38,24,72,54,34,13, - 90,24,79,23,67,59,89,12,17,45,98,24,130,17,53,27,52,22,90,67,0,1,0,44,0,174,2,60,1,150,0,5,0,0,37,53,33,130,237,41,1,232,254,68,2,16,174,151,81,232,130,131,42,1,0,178,0,225,1,182,1, - 46,0,3,65,11,5,39,178,1,4,225,77,77,0,4,66,3,8,39,10,0,37,0,61,0,85,0,86,143,5,32,53,85,200,8,41,21,20,7,6,7,30,1,23,30,5,81,241,5,35,43,1,21,39,66,12,46,8,32,246,51,45,14,23,19,18, - 42,54,65,119,145,48,16,20,5,11,8,3,8,11,8,18,32,11,72,65,10,18,26,16,23,133,66,20,39,8,32,1,113,9,15,30,33,9,12,254,225,1,71,93,50,24,7,3,1,10,7,4,11,12,11,27,50,17,102,12,19,7,140, - 3,66,31,40,8,40,1,0,159,2,135,1,202,2,205,0,3,0,0,1,21,33,53,1,202,254,213,2,205,70,70,0,0,0,2,0,150,1,160,1,211,2,203,0,13,0,35,130,29,80,201,5,46,35,34,7,6,20,22,50,55,22,23,30,1, - 20,14,1,103,70,13,8,61,1,132,15,6,13,38,14,22,45,24,28,54,92,11,30,31,13,23,23,34,18,32,54,84,46,26,45,46,66,8,7,35,2,4,17,50,16,30,17,7,24,26,76,52,228,13,29,13,55,60,54,30,12,21, - 63,39,38,72,43,44,1,5,132,115,32,44,130,120,34,60,2,38,130,143,38,15,0,0,51,53,33,21,101,69,11,47,44,2,16,254,206,222,222,84,222,222,80,80,160,155,80,155,130,2,130,152,47,0,161,2,14, - 1,190,3,159,0,27,0,0,19,54,51,50,130,153,38,21,20,7,14,2,7,51,130,208,33,54,55,130,1,8,52,52,39,38,34,7,164,66,46,100,43,18,6,15,40,67,59,20,204,254,227,21,36,114,15,21,7,23,106,68, - 3,132,27,48,20,32,10,35,19,51,60,54,18,54,53,20,33,100,27,29,38,12,38,34,130,142,50,0,1,0,163,2,9,1,206,3,161,0,55,0,0,1,20,7,22,23,88,146,5,36,34,47,1,38,39,131,1,32,53,94,4,10,92, - 154,10,38,35,34,14,3,7,53,54,130,139,8,92,22,1,196,86,47,24,25,12,36,133,17,7,7,14,8,7,17,10,20,11,39,24,23,26,95,14,2,28,23,59,32,37,71,18,6,52,17,17,23,39,15,14,14,8,77,38,112,37, - 11,3,59,65,22,8,26,25,67,22,71,1,2,1,1,4,2,4,5,56,15,3,7,56,7,13,29,18,18,51,33,10,13,42,12,4,8,2,5,6,2,57,17,60,19,130,159,40,238,2,81,1,221,3,2,0,9,130,159,34,6,7,35,132,238,53,55, - 1,221,143,20,76,17,25,26,20,38,14,3,2,156,21,21,33,33,24,48,18,133,207,44,83,255,55,2,65,2,14,0,30,0,0,37,6,78,3,5,39,17,20,23,22,51,50,53,17,74,209,6,33,50,55,68,18,5,8,47,1,175,42, - 181,42,83,91,18,33,66,127,93,17,6,5,8,7,23,40,23,39,14,24,60,73,72,254,252,2,215,254,186,54,30,55,158,1,51,254,106,42,8,3,10,70,20,14,24,133,95,36,53,255,164,2,3,85,35,5,43,5,17,38, - 39,38,53,52,54,59,1,17,35,130,1,56,1,23,136,56,34,132,106,224,71,95,92,1,141,10,78,43,67,90,108,252,231,2,224,253,32,130,56,48,1,0,227,1,14,1,133,1,174,0,15,0,0,1,22,21,20,107,176, - 9,8,35,51,50,1,110,23,35,29,17,34,23,24,50,14,17,32,1,152,23,43,26,34,12,23,22,35,54,20,6,0,1,0,198,255,71,1,148,130,65,41,17,0,0,5,50,53,52,38,39,51,130,61,8,33,7,6,43,1,34,39,53, - 22,1,17,62,33,11,59,54,46,33,25,37,28,37,36,128,43,21,49,15,54,49,53,18,11,11,61,131,102,8,57,0,172,2,14,1,202,3,151,0,13,0,0,19,54,55,51,17,51,21,33,53,51,17,14,1,7,172,42,73,68,103, - 254,235,103,21,70,21,3,132,6,13,254,172,53,53,1,30,4,11,4,0,3,0,122,0,220,1,239,69,79,6,32,37,68,67,5,34,39,22,51,101,144,6,106,122,9,32,39,103,204,10,8,71,21,20,138,1,82,213,20,25, - 53,27,29,44,21,70,20,62,244,49,87,46,25,43,16,45,8,3,76,43,67,87,49,51,220,59,59,172,9,37,33,68,79,38,21,9,27,203,39,53,11,19,17,46,57,20,34,98,54,31,53,53,88,89,0,2,0,116,0,67,2,65, - 1,242,91,143,5,34,1,23,21,130,161,41,6,7,53,62,1,55,38,39,7,38,130,230,33,23,22,130,19,8,61,3,7,53,54,1,86,235,29,86,32,59,29,28,94,29,54,97,76,72,78,59,60,78,37,15,40,64,87,28,72, - 1,242,197,38,24,72,27,50,23,89,23,79,24,42,84,126,59,67,90,50,50,65,32,38,13,33,54,72,24,89,59,0,130,0,59,4,0,13,255,129,2,45,3,11,0,5,0,20,0,24,0,36,0,0,37,51,53,6,7,6,23,53,35,131, - 108,44,54,55,51,21,51,21,35,21,19,5,39,37,1,65,45,8,8,65,6,7,1,27,137,9,12,68,89,194,22,67,25,34,34,80,59,59,69,253,237,13,2,19,254,11,115,68,103,254,235,103,63,49,12,195,13,16,94, - 211,87,57,31,91,33,47,46,253,52,87,1,231,123,51,123,1,95,17,254,172,52,52,1,31,12,7,130,122,33,0,3,136,123,36,30,0,34,0,46,130,121,80,150,8,37,7,6,7,51,21,33,133,128,92,31,6,34,34, - 7,37,143,131,59,8,63,48,82,44,43,15,29,39,83,36,205,254,226,22,72,19,54,9,6,6,19,25,23,96,60,1,37,142,143,58,247,26,30,34,47,29,22,40,36,75,34,53,52,20,66,17,50,12,9,6,32,18,33,17, - 17,34,172,144,152,65,19,7,32,19,65,19,6,32,79,65,19,25,47,45,1,50,52,35,34,15,1,14,1,7,53,55,62,1,55,137,192,32,22,75,212,5,41,47,1,34,39,46,2,39,53,30,1,101,182,8,34,43,1,53,65,61, - 22,8,45,135,95,90,37,17,25,7,15,8,18,21,19,11,16,35,71,42,42,49,16,21,96,47,48,85,9,8,29,8,7,13,23,14,8,18,24,7,38,27,93,14,2,6,21,82,33,65,98,20,8,56,212,113,5,7,2,5,2,56,4,5,2,2, - 3,27,28,46,51,23,7,5,20,79,58,31,32,1,2,2,4,4,4,2,58,6,8,2,10,56,8,25,12,40,51,0,2,0,96,255,244,1,239,2,219,0,50,0,67,130,227,33,54,55,66,100,5,72,27,7,35,62,1,63,1,131,211,36,55,54, - 61,1,52,130,3,32,51,131,210,36,7,14,2,15,1,81,137,5,33,51,19,69,25,5,33,35,34,66,247,6,8,119,50,1,82,68,89,31,31,11,33,25,35,38,87,52,56,17,22,53,6,27,8,12,5,15,4,8,1,96,12,18,43,12, - 11,27,5,13,31,19,28,71,40,30,10,4,16,25,23,39,31,6,5,57,7,24,65,7,57,89,17,11,4,14,3,3,44,46,75,40,27,35,49,5,25,7,13,6,17,8,16,32,2,3,5,5,65,72,45,25,40,39,11,10,26,5,13,36,25,10, - 31,22,38,2,149,9,27,13,51,14,23,29,13,13,16,56,14,1,0,0,0,3,90,175,5,39,3,101,0,10,0,23,0,31,98,145,23,39,3,46,1,39,51,30,1,23,98,153,23,39,145,22,70,22,92,19,61,19,98,161,22,36,2, - 49,23,79,23,130,2,137,111,32,104,132,111,32,27,151,111,35,17,7,35,55,151,107,34,114,77,98,151,102,34,177,123,123,138,211,32,102,132,99,32,35,151,99,42,3,38,39,14,1,7,35,54,55,51,22, - 152,215,43,47,48,35,15,52,16,69,85,20,94,44,62,151,116,41,50,51,33,15,53,16,102,23,51,74,138,123,32,81,132,123,32,62,153,123,40,34,7,6,29,1,35,52,55,54,94,110,5,32,22,79,205,5,43,51, - 6,7,6,35,34,46,1,47,1,46,3,151,255,8,33,172,14,18,6,22,63,27,26,42,6,9,30,34,7,10,26,11,19,8,13,62,3,53,17,15,32,18,9,6,14,7,7,18,5,151,169,63,92,7,4,11,30,4,49,27,28,1,6,17,4,5,13, - 9,15,19,3,73,23,8,8,3,3,7,4,4,9,4,0,4,66,11,12,34,35,0,47,151,189,32,19,86,222,6,36,59,1,50,21,7,138,11,151,177,32,19,76,76,5,38,196,15,72,14,14,72,15,151,157,35,93,14,14,67,135,2, - 66,151,8,38,126,0,8,0,22,0,44,132,137,53,1,39,14,3,18,6,20,30,1,51,50,55,54,52,39,38,35,34,3,7,35,19,110,2,8,8,89,21,20,7,22,18,22,23,35,39,202,213,48,46,13,13,39,29,18,35,12,34,26, - 16,33,21,22,5,20,52,29,101,54,105,214,61,14,46,77,56,42,39,61,46,120,34,14,104,56,1,3,158,156,43,43,132,97,62,2,11,26,44,31,11,21,20,45,13,44,253,115,183,2,145,35,72,38,22,70,38,39, - 53,66,41,138,254,141,105,43,183,0,130,0,32,2,132,4,38,78,2,189,0,7,0,23,131,141,46,17,35,14,1,7,6,15,1,35,19,33,21,35,21,51,132,3,63,33,53,164,154,53,12,38,13,30,30,50,92,205,1,120, - 169,153,153,178,254,240,1,3,1,107,45,133,50,106,108,180,2,100,83,5,32,180,131,74,45,1,0,70,255,71,2,25,2,203,0,51,0,0,1,130,202,78,63,5,131,217,43,55,21,6,7,34,6,7,22,23,22,21,20,71, - 149,5,37,51,50,53,52,46,3,71,33,7,8,88,55,54,50,23,2,25,79,87,98,49,49,75,45,76,59,68,20,19,47,43,6,22,8,26,3,15,120,22,25,40,36,39,62,14,3,7,7,4,129,73,78,14,45,116,55,159,78,2,67, - 58,71,74,142,175,70,42,34,10,15,97,23,9,3,1,34,7,32,19,82,11,61,15,43,14,26,8,9,9,6,8,87,96,171,89,50,152,50,25,39,132,226,43,0,98,0,0,2,39,3,104,0,11,0,19,101,29,13,68,3,7,50,98,1, - 188,254,170,1,70,254,186,1,95,240,21,71,21,92,18,62,18,134,217,36,2,237,23,77,23,130,2,130,72,32,2,138,71,32,15,142,71,34,7,35,55,138,67,35,113,114,77,98,134,63,35,3,104,123,123,138, - 59,32,102,130,131,32,24,142,59,67,179,9,33,31,1,138,68,32,151,67,167,7,35,95,20,33,52,134,77,33,2,233,67,152,6,36,23,39,63,0,3,134,143,32,101,130,83,33,25,0,130,234,101,247,11,32,3, - 66,195,6,33,55,54,66,209,11,133,13,138,100,44,85,15,71,15,3,4,28,51,15,196,15,72,14,132,8,134,105,41,3,20,14,14,67,7,4,3,14,67,134,7,36,0,0,2,0,100,130,4,34,3,3,104,130,111,32,18,130, - 195,95,33,5,43,21,35,17,51,21,3,46,1,39,51,22,23,101,128,6,38,216,21,70,22,92,47,52,101,135,7,38,2,237,23,77,23,60,63,140,63,32,15,142,63,34,7,35,55,134,60,35,77,114,77,98,135,57,65, - 60,5,135,119,32,102,130,119,32,21,144,55,33,54,55,130,120,33,35,38,134,61,41,208,82,70,85,20,95,44,62,71,48,136,67,41,61,84,102,23,51,74,51,0,0,3,134,191,32,101,130,71,34,23,0,35,142, - 73,67,255,22,134,87,32,58,67,238,12,136,91,32,20,67,223,11,42,2,0,4,0,0,2,39,2,189,0,19,131,93,38,55,51,50,55,62,1,55,81,133,6,47,43,1,21,51,21,35,3,17,35,53,51,17,51,50,22,21,106, - 19,5,8,54,170,48,66,45,43,36,10,28,9,21,50,54,94,48,132,132,103,63,63,151,171,162,81,45,59,64,99,78,15,17,43,21,57,120,85,36,87,32,33,221,70,254,179,1,77,70,1,42,170,181,179,85,45, - 21,20,130,102,33,0,70,130,4,38,35,3,102,0,16,0,60,130,201,32,17,96,135,5,41,17,51,17,35,38,39,38,39,17,19,69,134,5,33,30,1,84,192,8,48,61,1,51,6,7,6,34,39,46,4,47,1,46,1,39,46,1,80, - 206,5,8,121,70,128,16,44,34,93,65,97,128,74,59,93,26,39,63,27,25,43,28,31,20,3,10,24,4,11,7,15,9,11,62,3,53,17,28,8,18,11,9,12,15,3,18,4,5,3,7,6,3,7,26,9,2,2,189,37,100,78,215,147, - 2,65,253,67,167,137,215,59,253,190,3,0,44,31,27,13,11,1,3,13,1,4,13,11,19,3,72,23,7,1,2,4,3,6,7,2,10,1,4,1,3,3,27,8,6,0,0,3,0,58,255,243,2,46,3,104,0,13,0,26,0,34,83,209,11,43,35,34, - 6,16,39,16,51,50,23,22,21,16,131,164,33,38,19,130,162,131,210,8,53,198,35,75,76,35,34,34,34,77,76,68,106,250,126,63,61,192,27,94,47,140,246,21,70,22,92,18,63,18,130,67,67,64,156,157, - 64,66,132,254,205,152,1,109,90,94,181,254,190,36,5,22,66,2,162,67,178,8,142,115,32,30,156,115,35,1,7,35,55,148,111,36,1,129,114,77,98,150,108,34,3,29,123,71,159,5,133,219,32,102,132, - 219,32,39,157,103,67,240,11,149,112,32,86,67,251,11,150,121,33,2,158,68,11,12,139,127,32,70,156,127,66,27,40,148,155,32,148,66,35,38,151,181,32,181,66,41,34,34,0,0,4,66,43,6,40,101, - 0,13,0,26,0,38,0,50,156,209,32,1,67,188,22,148,192,33,1,143,67,203,12,151,167,32,201,67,218,11,8,34,0,1,0,75,0,82,2,30,2,9,0,36,0,0,37,7,39,54,63,1,54,55,46,3,39,55,30,2,23,54,55,23, - 14,3,7,109,205,5,58,7,38,39,46,1,1,52,174,59,21,32,64,40,18,22,64,48,30,11,58,55,79,30,11,47,128,59,132,12,63,11,30,24,56,32,21,59,11,15,57,69,247,165,55,20,30,60,37,17,20,61,45,28, - 11,55,50,76,28,11,43,122,55,132,12,43,11,28,22,53,30,20,55,11,14,53,67,0,130,0,52,3,0,4,255,223,2,88,2,221,0,18,0,33,0,72,0,0,9,1,30,2,78,109,5,51,38,53,39,38,53,38,39,52,5,54,55,38, - 35,34,7,6,7,6,29,1,68,91,5,34,46,1,39,89,67,5,32,53,73,143,5,41,55,22,23,7,22,23,30,1,23,22,68,121,5,8,134,34,38,39,38,1,186,254,255,15,50,37,21,78,33,34,1,2,1,1,1,254,234,168,84,23, - 91,42,19,36,13,33,2,39,44,28,10,31,10,89,24,5,1,1,4,98,63,88,116,57,70,35,15,84,14,4,13,6,2,3,16,30,92,46,68,49,42,17,41,1,231,254,167,35,33,11,67,73,148,13,23,10,37,8,7,7,6,10,251, - 225,113,78,13,27,30,62,182,47,14,10,18,172,56,39,6,21,6,119,56,69,16,16,39,41,221,88,50,77,95,23,12,112,28,15,49,51,18,27,140,68,133,48,22,14,7,16,130,222,50,0,2,0,74,255,243,2,31, - 3,102,0,34,0,41,0,0,5,34,39,81,86,5,33,38,39,80,141,5,37,51,50,55,62,1,53,131,11,130,223,130,227,37,14,1,3,38,39,51,130,202,8,77,1,46,67,42,39,13,34,9,19,2,2,1,101,11,33,89,85,35,11, - 2,102,22,12,17,30,10,10,48,71,21,49,65,93,18,61,19,13,21,17,12,31,25,41,42,18,23,1,228,254,37,80,20,63,57,19,61,191,1,54,254,80,102,73,19,27,20,5,5,27,4,2,247,57,67,23,77,24,0,136, - 135,32,104,130,135,32,40,164,135,37,19,6,7,35,54,55,156,134,37,106,56,59,76,65,33,161,133,37,3,117,61,62,83,40,65,11,12,32,46,165,131,68,77,9,32,23,156,137,32,68,75,247,10,161,143, - 33,2,246,76,2,11,33,0,3,65,163,6,38,101,0,34,0,46,0,58,165,153,67,149,22,156,165,32,134,67,156,12,161,167,33,3,33,67,167,12,32,2,75,239,6,36,102,0,19,0,24,104,173,21,36,19,7,35,54, - 55,104,178,18,36,148,115,76,44,54,104,183,20,37,1,175,124,58,66,0,72,191,6,42,71,2,189,0,8,0,23,0,0,37,50,86,24,5,8,48,21,7,17,51,21,51,50,23,22,21,20,7,6,43,1,21,1,62,158,60,36,75, - 103,102,102,127,192,46,16,63,65,126,127,250,124,75,30,18,247,250,2,189,127,112,38,38,117,47,50,92,247,5,40,94,255,243,2,62,2,219,0,60,68,217,9,66,246,6,34,53,52,55,67,206,6,35,21,17, - 35,17,130,12,130,91,39,23,6,7,6,21,20,31,2,109,115,5,67,194,9,8,110,39,229,75,60,84,26,7,22,8,26,70,84,6,1,90,30,39,4,114,91,20,7,93,119,39,105,39,116,3,116,35,11,24,10,38,22,32,45, - 19,31,30,10,16,55,97,50,41,9,14,23,86,29,52,12,20,32,32,7,25,35,53,55,10,12,89,42,15,8,103,70,23,34,253,236,2,23,151,33,12,13,36,156,9,60,19,18,38,19,10,25,11,22,27,26,45,54,56,35, - 14,10,41,10,2,3,7,0,0,0,3,0,68,130,179,40,48,3,18,0,13,0,66,0,77,130,183,40,20,23,22,50,54,55,54,61,1,98,167,5,33,7,53,102,237,5,32,51,104,105,8,93,181,6,41,30,1,23,35,38,53,38,39, - 6,7,83,210,9,88,104,5,32,39,95,200,6,8,130,160,88,13,52,60,21,44,116,123,29,10,138,97,92,10,12,20,43,18,37,43,92,55,58,16,3,3,12,1,10,3,4,6,4,1,92,18,2,2,15,44,39,61,37,82,49,51,63, - 62,122,123,76,27,32,50,73,28,11,99,9,24,39,52,17,159,84,15,2,26,25,48,89,18,58,20,1,24,50,87,4,3,5,13,4,7,30,31,44,8,8,30,80,115,14,13,22,35,40,26,10,17,14,2,42,19,9,10,30,28,23,12, - 45,39,83,86,47,46,13,92,20,8,143,55,80,31,11,11,30,49,65,22,142,223,32,72,196,223,68,33,5,180,221,37,143,12,150,77,65,76,184,216,38,1,64,12,165,84,93,0,65,183,16,32,78,196,215,43,3, - 7,35,55,51,30,1,23,35,38,39,38,180,221,43,26,90,69,123,73,23,77,23,69,17,28,29,185,227,40,3,116,177,33,111,33,22,36,36,138,231,39,2,250,0,13,0,66,0,103,196,231,36,55,50,53,51,20,88, - 223,5,33,47,1,130,235,32,35,71,102,5,75,93,5,36,23,30,4,23,22,180,253,8,33,40,37,62,56,18,16,26,12,20,19,10,12,7,14,4,5,10,29,6,2,1,62,26,25,46,18,18,23,18,7,20,10,4,6,65,19,56,41, - 223,73,94,30,8,5,8,15,10,9,130,88,49,39,14,19,61,36,35,6,13,16,6,18,7,2,5,0,0,0,4,67,195,5,41,2,217,0,13,0,66,0,78,0,90,65,37,69,69,233,22,65,27,52,35,123,15,71,15,130,2,32,196,93, - 166,5,65,7,56,32,182,93,222,11,135,247,33,3,77,132,247,34,82,0,96,196,247,48,2,14,1,20,30,1,51,50,54,55,54,53,52,46,1,34,23,85,42,6,37,54,51,50,23,22,20,180,253,55,68,22,11,33,26,16, - 32,33,6,5,32,28,32,115,40,59,56,40,41,82,55,58,41,39,65,7,56,8,47,1,55,20,26,45,30,11,31,12,12,15,31,31,10,162,38,38,37,54,55,74,37,35,113,0,0,3,0,20,255,243,2,88,2,27,0,14,0,26,0, - 80,0,0,55,6,7,6,20,86,151,5,41,61,1,35,34,55,51,53,52,38,39,130,214,38,7,6,21,19,50,55,21,130,29,36,35,34,39,38,39,134,7,34,53,52,55,110,97,6,37,35,34,7,6,7,53,131,244,132,248,35,29, - 1,35,21,86,17,5,8,132,176,51,15,8,23,22,32,67,15,10,24,42,149,164,15,4,18,33,33,16,45,108,75,52,51,42,17,23,80,40,14,8,31,58,21,32,90,39,23,112,36,46,60,24,23,49,49,60,8,8,72,63,91, - 34,34,94,89,34,36,246,1,60,23,236,9,36,18,70,21,24,50,33,46,55,67,24,57,38,7,25,7,8,23,107,254,241,48,80,32,5,2,43,13,18,55,15,4,63,37,56,122,34,10,41,56,30,31,30,4,5,79,32,60,60,56, - 54,145,42,17,1,6,10,123,18,9,0,1,0,82,255,71,2,3,130,223,34,56,0,0,90,23,5,103,203,9,32,55,132,170,36,23,21,38,39,38,130,189,32,21,95,10,7,82,168,7,71,203,5,8,94,34,39,53,22,1,53,63, - 14,2,4,11,4,116,66,73,14,25,36,74,125,67,52,19,21,56,57,20,66,34,103,104,34,56,11,70,46,7,8,40,46,5,20,7,44,46,33,26,36,26,40,36,128,43,16,24,4,8,14,6,6,66,73,131,71,36,61,35,73,22, - 8,10,91,47,8,3,14,40,149,150,40,14,1,10,34,6,7,90,25,9,3,1,48,44,51,20,90,130,5,54,0,3,0,62,255,243,2,44,3,18,0,12,0,39,0,50,0,0,19,51,54,59,1,130,152,132,154,65,121,6,34,43,1,34,119, - 116,8,33,22,29,109,161,5,32,3,71,60,6,8,34,162,64,25,22,192,2,8,12,17,35,136,42,43,170,87,108,74,75,12,12,23,129,75,73,111,66,86,110,61,60,254,114,140,19,8,71,41,6,8,45,38,52,17,1, - 53,1,44,20,34,19,39,42,41,254,188,54,86,32,6,2,73,73,129,161,74,42,67,68,119,42,3,150,28,3,2,38,55,80,31,11,11,31,48,65,22,0,130,0,141,155,32,47,169,155,37,19,7,35,62,3,55,161,153, - 39,167,162,77,17,51,39,24,9,159,150,38,215,177,22,65,48,31,11,145,147,32,51,169,147,70,180,11,161,153,32,2,70,161,8,33,29,28,159,157,32,154,70,135,11,32,4,65,207,5,41,2,217,0,12,0, - 39,0,51,0,63,169,161,86,133,23,161,173,38,147,15,71,16,16,71,15,69,53,6,159,175,32,77,69,28,11,50,2,0,109,255,252,2,34,3,6,0,14,0,27,0,0,5,35,34,38,109,250,6,37,23,22,59,1,1,38,73, - 163,7,8,54,2,34,117,81,92,122,214,52,16,22,108,254,237,20,29,30,45,28,10,99,9,24,38,52,17,4,100,91,1,16,67,254,173,86,24,7,2,15,21,33,33,48,31,11,11,31,48,66,21,0,0,0,2,0,134,136,91, - 130,15,142,91,37,3,7,35,62,2,55,138,87,38,50,162,78,27,81,24,9,139,80,35,192,177,34,101,65,247,5,139,75,32,25,145,167,84,8,6,34,39,6,7,138,80,43,254,100,92,31,74,92,31,70,68,22,68, - 22,139,85,40,16,132,44,132,44,86,29,86,29,130,163,32,3,133,163,33,2,217,130,255,34,26,0,38,144,89,85,74,7,85,72,11,131,11,138,102,35,100,15,71,15,130,2,38,195,15,72,14,14,72,15,139, - 104,32,66,70,134,12,34,0,2,0,109,235,5,46,219,0,46,0,65,0,0,1,22,23,14,1,7,22,21,72,98,6,69,82,5,43,22,59,2,50,23,46,2,39,38,39,46,1,130,205,34,39,54,55,85,93,5,32,3,112,248,11,8,123, - 38,43,1,34,7,6,1,211,10,6,23,78,24,190,98,56,86,112,65,62,61,62,123,17,5,2,2,1,2,4,1,8,11,5,7,8,16,11,5,15,124,15,79,40,17,58,16,109,36,28,157,37,37,68,67,39,37,55,7,9,25,13,23,113, - 30,10,2,196,30,16,7,24,7,190,186,151,72,38,69,72,123,127,67,70,1,1,2,9,13,7,10,9,17,12,5,5,38,46,25,12,18,58,18,39,28,254,99,92,49,51,51,51,89,113,68,4,2,6,109,36,0,0,0,2,110,239,6, - 39,225,0,18,0,53,0,0,19,110,229,5,32,17,110,248,10,73,53,10,32,39,131,200,32,35,130,170,32,7,73,51,6,80,132,5,8,88,189,51,115,170,92,110,97,28,9,92,83,7,186,38,62,26,25,45,43,38,4, - 9,11,8,4,3,7,8,17,10,7,2,63,27,25,45,34,36,7,3,19,16,3,5,1,191,92,212,254,185,1,71,137,95,30,41,254,214,2,14,49,188,72,65,33,35,38,3,9,10,5,3,2,3,18,11,44,63,35,35,28,7,4,18,9,3,3, - 0,3,65,95,5,43,3,18,0,13,0,27,0,40,0,0,1,34,114,203,7,36,53,52,39,38,3,69,68,10,37,16,6,3,46,1,39,130,2,8,69,51,30,3,23,1,52,142,80,27,35,106,27,10,81,26,36,175,49,15,136,45,58,117, - 61,62,122,124,20,60,28,16,28,11,100,9,24,38,52,17,1,210,203,150,41,13,116,38,50,151,39,13,254,33,158,51,67,202,56,18,71,72,254,243,140,2,110,22,65,32,16,69,52,9,141,131,32,33,157,131, - 76,32,5,149,126,37,51,23,140,76,82,58,152,119,38,3,31,23,154,106,71,0,142,243,32,38,157,111,69,3,8,33,46,1,149,116,42,118,90,70,123,74,23,77,23,70,17,56,152,121,33,2,226,68,239,5,32, - 72,135,123,39,2,225,0,13,0,27,0,62,158,123,75,76,9,66,22,22,149,146,32,53,66,32,31,65,153,24,32,166,66,41,25,34,0,0,4,66,43,5,33,2,217,132,187,34,39,0,51,157,189,69,155,23,149,179, - 32,31,80,199,12,65,73,25,32,149,68,31,13,49,3,0,44,0,71,2,60,2,22,0,11,0,15,0,27,0,0,37,75,90,10,36,37,53,33,21,39,138,15,44,1,114,16,92,15,15,92,16,254,186,2,16,202,133,10,41,85,14, - 14,87,13,13,90,80,80,170,130,8,49,15,15,0,3,0,24,255,211,2,75,2,57,0,10,0,20,0,47,130,225,36,6,7,22,23,22,98,170,6,114,7,6,37,54,3,6,7,38,39,106,2,5,38,51,50,23,54,55,22,23,68,147, - 5,8,102,43,1,38,1,182,40,191,21,35,25,55,27,81,42,36,65,103,31,10,14,187,215,50,30,44,2,85,40,136,44,58,101,59,29,45,21,25,82,43,137,45,59,26,87,1,111,46,218,25,12,7,13,41,148,67,94, - 44,111,34,31,74,56,212,254,182,55,32,34,2,94,67,111,202,56,18,52,33,49,18,17,93,63,115,204,55,17,7,0,0,0,2,0,97,255,243,2,13,3,5,0,24,0,34,130,229,74,83,7,83,241,8,33,54,53,130,10, - 38,35,38,3,46,2,39,51,130,176,8,60,23,1,177,35,78,24,36,119,33,11,92,27,29,54,97,28,9,92,83,2,138,28,96,28,11,100,13,29,70,28,79,67,19,6,119,40,54,1,69,254,187,74,31,34,96,31,40,1, - 41,253,243,23,2,61,29,106,31,11,17,36,90,130,96,139,111,32,30,154,111,67,142,6,145,108,37,37,20,143,76,41,99,150,104,36,238,21,156,55,122,140,211,32,35,154,99,32,1,79,57,7,33,6,7,146, - 213,33,254,220,67,126,5,35,67,23,67,23,150,110,36,61,177,33,111,33,70,188,5,32,3,65,71,5,39,2,217,0,24,0,36,0,48,154,117,66,190,24,145,235,32,17,66,187,12,150,132,32,113,66,184,12, - 44,2,0,52,255,55,2,65,3,5,0,38,0,44,130,133,44,19,51,14,3,7,14,2,15,1,14,2,7,6,131,1,48,43,1,53,51,50,55,54,55,46,1,39,38,39,51,23,30,1,65,105,6,8,89,59,164,98,55,58,25,21,8,13,14, - 5,2,28,10,17,13,6,18,15,26,12,38,41,60,54,61,27,12,22,35,77,28,73,3,98,50,62,42,173,44,119,76,31,109,115,1,155,132,140,62,49,20,33,32,14,6,72,25,32,26,11,30,10,18,3,12,73,59,23,54, - 85,187,65,174,7,125,152,107,2,119,47,129,42,134,0,0,0,2,0,95,130,143,40,42,2,224,0,10,0,30,0,0,107,185,5,37,23,22,51,50,16,5,99,147,8,34,35,34,39,130,141,8,58,17,35,17,51,1,68,101, - 27,9,77,26,34,134,254,241,48,103,99,60,57,58,60,99,40,20,41,38,11,92,92,1,210,115,38,50,148,43,13,1,151,7,80,74,73,130,131,72,72,8,16,36,20,254,244,3,169,0,0,3,133,243,33,2,204,130, - 243,34,50,0,62,133,245,35,1,7,14,9,130,248,33,7,6,145,240,32,21,67,186,9,32,7,138,11,56,1,59,164,98,55,58,12,16,25,7,5,3,4,2,4,4,7,7,22,47,13,6,40,65,83,65,2,13,32,153,65,148,12,53, - 115,1,155,132,140,31,37,60,17,13,8,7,6,8,12,18,19,61,92,16,7,43,65,10,12,38,47,62,18,14,66,15,15,132,5,43,0,1,0,18,255,243,2,18,2,203,0,65,130,167,32,6,130,247,46,38,39,35,55,54,55, - 51,53,38,61,1,38,52,55,53,130,2,37,35,55,51,54,55,54,111,182,10,48,7,51,6,7,35,21,20,6,29,1,22,21,51,14,1,7,35,104,231,5,48,62,1,55,2,18,65,146,91,32,63,28,87,13,7,5,58,1,130,0,8,86, - 83,25,62,42,130,45,38,104,66,8,8,58,78,108,43,14,6,240,15,9,221,1,1,180,5,15,5,150,10,45,44,73,53,65,8,17,8,25,38,1,33,33,62,139,26,16,10,10,2,5,13,9,11,10,15,1,2,10,50,205,48,17,39, - 97,6,7,47,110,36,48,34,16,9,2,6,4,62,2,3,10,32,10,92,52,50,36,6,102,24,5,35,0,14,0,174,130,193,32,0,132,0,34,1,0,4,134,11,32,1,130,7,32,10,134,11,32,2,130,7,32,16,134,11,36,3,0,29, - 0,78,134,11,131,43,32,112,134,11,36,5,0,9,0,134,134,11,32,6,130,7,44,148,0,3,0,1,4,9,0,0,0,2,0,0,134,11,32,1,130,11,32,6,134,11,32,2,130,11,32,12,134,11,36,3,0,58,0,18,134,11,32,4, - 130,23,32,108,134,11,32,5,130,21,32,114,134,11,32,6,130,23,35,144,0,46,0,143,2,39,70,0,111,0,110,0,116,0,131,7,40,114,0,103,0,101,0,32,0,50,130,36,32,48,130,7,32,58,130,3,32,46,134, - 7,38,50,0,49,0,45,0,56,130,3,34,50,0,48,130,33,51,53,0,0,70,111,110,116,70,111,114,103,101,32,50,46,48,32,58,32,46,130,3,39,50,49,45,56,45,50,48,50,130,30,133,107,32,86,130,81,36,114, - 0,115,0,105,132,103,32,32,130,89,40,0,86,101,114,115,105,111,110,32,136,140,33,2,0,132,0,35,255,156,0,35,130,8,32,1,130,3,141,2,32,195,132,21,32,2,130,201,58,4,0,5,0,6,0,7,0,8,0,9, - 0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,130,235,62,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,130,93,50,36,0,37,0,38,0,39,0,40,0,41,0,42,0,43,0,44, - 0,45,130,145,32,47,130,209,32,49,130,211,9,38,51,0,52,0,53,0,54,0,55,0,56,0,57,0,58,0,59,0,60,0,61,0,62,0,63,0,64,0,65,0,66,0,67,0,68,0,69,0,70,0,71,0,72,0,73,0,74,0,75,0,76,0,77,0, - 78,0,79,0,80,0,81,0,82,0,83,0,84,0,85,0,86,0,87,0,88,0,89,0,90,0,91,0,92,0,93,0,94,0,95,0,96,0,97,0,172,0,163,0,132,0,133,0,189,0,150,0,232,0,134,0,142,0,139,0,157,0,169,0,164,1,2, - 0,138,0,218,0,131,0,147,0,242,0,243,0,141,0,151,0,136,0,195,0,222,0,241,0,158,0,170,0,245,0,244,0,246,0,162,0,173,0,201,0,199,0,174,0,98,0,99,0,144,0,100,0,203,0,101,0,200,0,202,0, - 207,0,204,0,205,0,206,0,233,0,102,0,211,0,208,0,209,0,175,0,103,0,240,0,145,0,214,0,212,0,213,0,104,0,235,0,237,0,137,0,106,0,105,0,107,0,109,0,108,0,110,0,160,0,111,0,113,0,112,0, - 114,0,115,0,117,0,116,0,118,0,119,0,234,0,120,0,122,0,121,0,123,0,125,0,124,0,184,0,161,0,127,0,126,0,128,0,129,0,236,0,238,0,186,1,3,7,117,110,105,48,48,97,100,131,7,45,50,48,97,99, - 0,0,0,1,255,255,0,2,0,1,130,9,32,12,130,3,32,16,130,3,36,2,0,0,0,4,134,7,32,0,132,25,36,0,223,214,203,49,130,17,24,92,127,12,5,250,205,249,72,146, + 87,188,0,0,0,0,0,0,0,0,72,124,0,4,0,0,55,0,1,0,0,0,14,0,128,0,3,0,96,70,70,84,77,176,111,174,190,0,0,72,96,130,21,40,28,71,68,69,70,0,136,0,105,130,15,32,64,130,15,44,30,79,83,47,50, + 104,97,19,194,0,0,1,104,130,15,44,96,99,109,97,112,177,173,221,139,0,0,3,80,130,19,44,114,99,118,116,32,0,33,2,121,0,0,4,196,130,31,38,4,103,97,115,112,255,255,130,89,34,0,72,56,130, + 15,56,8,103,108,121,102,239,245,108,207,0,0,6,76,0,0,62,224,104,101,97,100,44,57,58,3,130,27,32,236,130,3,33,54,104,130,16,35,4,62,0,230,130,75,32,36,130,15,39,36,104,109,116,120,24, + 22,19,130,95,33,1,200,130,19,40,136,108,111,99,97,80,9,64,114,130,95,131,15,39,130,109,97,120,112,1,7,0,131,31,32,72,130,47,44,32,110,97,109,101,10,160,159,151,0,0,69,44,130,47,44, + 68,112,111,115,116,70,77,175,253,0,0,70,112,130,15,32,197,132,235,32,1,130,9,42,224,136,151,95,15,60,245,0,11,3,232,130,55,36,0,229,175,187,66,132,7,42,178,59,232,255,225,255,68,1, + 215,2,176,130,15,34,8,0,2,130,5,131,2,130,51,39,2,131,255,71,0,0,1,184,130,31,34,226,1,215,132,73,131,25,135,3,32,4,132,17,37,192,0,90,0,5,0,131,0,33,2,0,130,44,132,19,34,64,0,46,130, + 11,38,0,0,4,1,184,1,144,131,29,35,2,138,2,187,130,17,32,140,133,7,38,1,223,0,49,1,2,0,138,0,37,128,0,0,7,16,0,136,123,33,0,88,130,0,37,0,64,0,32,32,172,133,131,34,2,175,0,131,63,33, + 3,0,130,0,35,1,133,2,6,130,6,38,32,0,1,1,184,0,33,130,9,130,161,32,0,132,3,39,0,166,0,116,255,249,0,49,130,113,36,4,0,185,0,135,130,1,38,27,0,22,0,154,0,53,130,25,40,39,0,41,0,79,0, + 50,0,45,130,17,32,49,130,11,33,46,0,131,17,36,166,0,143,0,24,132,1,34,48,255,225,130,55,34,38,0,47,130,23,44,52,0,58,0,35,0,42,0,66,0,65,0,19,130,79,32,19,130,47,38,35,0,44,0,13,0, + 38,130,21,38,9,0,37,0,13,255,250,130,121,36,5,0,33,0,104,130,47,40,104,0,37,255,242,0,124,0,48,130,95,32,59,130,3,34,37,0,40,130,5,36,62,0,139,0,100,130,57,36,133,0,20,0,62,130,55, + 32,50,130,19,40,69,0,69,0,87,0,54,0,29,130,167,32,20,130,107,36,64,0,63,0,188,130,3,36,22,0,21,0,159,130,7,36,40,0,55,0,5,130,17,34,64,0,109,130,33,34,92,0,50,130,5,42,109,0,101,0, + 24,0,115,0,109,0,131,130,121,32,48,130,39,36,143,0,114,0,83,130,77,32,19,130,157,34,18,0,73,130,49,32,5,136,3,32,2,130,85,33,52,0,133,1,33,66,0,133,1,32,17,130,125,32,35,130,209,131, + 3,36,46,0,1,0,46,132,1,32,47,130,51,32,42,130,25,32,38,130,213,135,3,34,5,0,59,130,99,32,37,132,3,34,51,0,68,132,1,32,42,130,189,33,43,0,135,1,36,24,0,12,0,61,134,1,32,26,130,131,38, + 26,0,30,0,0,0,3,134,3,32,28,130,93,130,10,35,0,108,0,3,132,9,36,28,0,4,0,80,130,16,34,16,0,16,132,35,46,126,0,133,0,171,0,210,0,211,0,255,32,172,255,255,130,25,32,32,130,17,34,161, + 0,174,130,17,32,212,131,17,45,255,227,255,221,255,194,255,192,255,95,255,191,224,19,132,67,130,36,139,2,34,1,6,0,136,22,35,1,2,0,0,66,53,9,32,0,133,0,32,1,130,142,8,148,4,5,6,7,8,9, + 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69, + 70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,0,132,133,135,137,145,149,155,160,159,161,163,162,164,166,168,167,169,170,172,171,173,174,176,178, + 177,179,181,180,185,184,186,187,0,112,100,101,105,0,118,158,110,107,0,116,106,0,134,151,0,113,0,0,103,117,132,158,38,108,122,0,165,183,127,99,132,11,38,109,123,0,0,128,131,148,132, + 11,130,4,37,182,0,190,60,0,191,130,8,34,0,0,119,130,5,47,130,138,129,139,136,141,142,143,140,50,147,0,146,153,154,152,130,18,32,111,130,3,32,120,130,3,130,2,34,33,2,121,130,5,33,42, + 0,133,1,9,155,68,0,86,0,134,0,210,1,14,1,104,1,116,1,148,1,180,1,212,1,232,2,6,2,20,2,38,2,54,2,100,2,122,2,172,2,232,3,2,3,60,3,116,3,134,3,210,4,10,4,40,4,82,4,102,4,122,4,142,4, + 204,5,36,5,60,5,118,5,158,5,184,5,208,5,228,6,24,6,44,6,68,6,94,6,118,6,134,6,160,6,182,6,224,7,14,7,64,7,106,7,182,7,200,7,238,8,0,8,28,8,52,8,72,8,96,8,114,8,130,8,148,8,166,8,180, + 8,194,9,12,9,58,9,92,9,140,9,182,9,214,10,14,10,44,10,74,10,110,10,134,10,150,10,198,10,230,11,4,11,50,11,96,11,130,11,188,11,216,11,250,12,14,12,42,12,66,12,114,12,142,12,198,12,210, + 13,10,13,62,13,126,13,152,13,198,13,238,14,34,14,72,14,90,14,198,14,232,15,32,15,106,15,134,15,200,15,214,15,244,16,16,16,56,16,114,16,128,16,182,16,212,16,230,17,2,17,22,17,60,17, + 86,17,132,17,194,18,20,18,76,18,108,18,140,18,176,18,228,19,24,19,74,19,110,19,168,19,198,19,228,20,6,20,56,20,86,20,116,20,150,20,200,20,252,21,44,21,92,21,144,21,212,22,24,22,50, + 22,112,22,148,22,186,22,226,23,28,23,56,23,90,23,160,23,246,24,76,24,164,25,18,25,124,25,226,26,94,26,150,26,198,26,248,27,44,27,114,27,144,27,174,27,208,28,2,28,74,28,136,28,174,28, + 212,28,254,29,60,29,118,29,172,29,230,30,16,30,58,30,104,30,166,30,206,30,244,31,48,31,112,0,0,0,2,0,33,0,0,1,42,2,154,0,3,0,7,0,46,177,1,0,47,60,178,7,4,0,237,50,177,6,5,220,60,178, + 3,2,130,10,34,0,177,3,131,22,32,5,131,22,39,178,7,6,1,252,60,178,1,131,23,52,51,17,33,17,39,51,17,35,33,1,9,232,199,199,2,154,253,102,33,2,88,131,83,38,166,255,254,1,18,2,35,130,81, + 61,13,0,0,54,50,22,20,6,34,38,52,55,35,3,55,51,21,198,44,32,32,44,32,85,59,14,1,83,105,31,131,11,36,122,1,4,91,91,130,135,38,116,1,70,1,68,2,7,132,135,37,0,1,35,53,51,7,130,3,8,40, + 1,67,64,64,142,65,65,1,70,192,192,192,0,2,255,248,0,3,1,191,2,3,0,3,0,31,0,0,63,1,35,7,37,35,7,51,21,35,7,35,55,132,3,34,53,51,55,130,51,35,55,51,7,51,131,3,53,254,30,92,30,1,29,104, + 31,92,106,38,59,38,92,38,58,38,96,110,31,98,112,134,11,34,90,201,115,130,0,33,54,143,130,0,35,54,115,54,144,130,0,32,0,130,85,8,37,49,255,241,1,135,2,22,0,6,0,11,0,52,0,0,55,62,1,53, + 52,38,47,1,53,6,21,20,23,30,3,21,20,7,21,35,53,46,1,130,16,8,109,30,2,23,53,46,3,53,52,54,55,53,51,21,30,1,31,1,21,38,39,21,50,249,32,41,36,37,60,72,137,22,40,46,28,141,60,36,67,15, + 15,6,21,69,37,31,44,43,22,75,65,60,25,55,15,15,43,67,3,81,7,37,31,30,32,10,73,135,12,61,44,30,4,15,28,50,33,114,15,44,43,1,14,6,6,63,4,11,22,3,162,6,15,26,42,29,53,67,9,45,42,2,11, + 5,5,62,29,4,150,0,5,130,1,36,11,1,178,1,250,130,161,52,11,0,19,0,27,0,35,0,0,1,51,1,35,36,50,54,52,38,34,6,20,65,97,7,34,2,20,22,132,17,65,111,5,53,54,50,1,74,71,254,222,71,1,16,41, + 30,30,41,29,7,84,60,60,84,59,174,130,9,34,29,41,122,130,9,51,59,84,1,249,254,21,47,27,39,27,27,39,115,56,79,56,56,79,1,26,131,11,33,27,7,131,11,8,59,56,0,0,0,3,0,4,255,246,1,179,2, + 21,0,9,0,28,0,62,0,0,55,50,55,46,1,39,6,21,20,22,3,28,2,30,5,23,62,1,53,52,38,35,34,6,1,23,35,38,39,6,35,34,38,53,52,54,55,46,2,130,5,8,101,51,50,22,21,20,14,2,7,22,23,54,53,55,20, + 206,52,37,25,110,24,65,80,41,1,2,3,6,8,12,7,37,37,31,23,24,35,1,2,67,72,13,21,60,89,72,104,52,44,22,19,15,63,60,61,51,15,32,25,24,89,58,36,61,44,36,28,131,28,54,59,48,62,1,125,1,7, + 3,7,5,10,9,13,16,9,25,40,24,21,25,32,254,143,79,15,24,49,96,66,50,74,33,25,130,17,56,41,69,55,49,20,36,34,20,17,107,69,65,72,1,108,0,1,0,185,1,70,0,255,2,8,130,189,42,0,19,35,53,51, + 254,68,68,1,71,193,130,23,8,59,135,255,193,1,49,2,62,0,17,0,0,1,14,1,20,22,23,35,46,4,52,62,2,63,1,1,49,43,55,55,43,60,4,15,38,29,24,23,32,33,11,11,2,61,60,177,161,177,60,6,21,68,70, + 103,97,102,75,61,16,16,130,50,32,0,138,63,34,19,30,4,130,220,40,15,1,35,62,1,52,38,39,195,137,57,32,60,131,73,44,2,61,6,22,68,71,103,97,101,75,60,16,16,132,73,32,0,131,63,38,27,0,69, + 1,157,1,199,132,127,8,41,7,23,7,39,21,35,53,7,39,55,39,55,23,53,51,21,55,1,157,131,131,33,128,64,129,32,131,131,32,129,64,128,1,77,71,71,50,70,142,142,70,50,134,7,49,0,1,0,22,0,74, + 1,162,1,185,0,11,0,0,19,51,21,35,130,62,130,221,37,53,51,251,166,166,62,130,2,38,1,31,59,154,154,59,154,130,39,39,154,255,129,1,30,0,107,0,130,180,32,54,65,133,5,8,37,15,1,39,54,55, + 46,1,53,52,209,45,31,21,31,30,11,11,26,55,10,17,25,107,32,22,32,61,40,32,7,7,37,48,41,1,31,21,22,131,163,54,53,0,227,1,131,1,32,0,3,0,0,37,33,53,33,1,131,254,178,1,78,228,60,132,191, + 40,166,255,255,1,18,0,105,0,7,67,209,9,67,203,5,37,105,31,44,31,31,44,132,35,38,39,255,222,1,144,2,39,131,63,49,9,1,35,1,1,144,254,221,69,1,34,2,39,253,184,2,72,0,130,21,8,73,41,255, + 247,1,143,2,14,0,10,0,21,0,27,0,0,55,50,62,3,53,52,39,7,22,19,34,14,3,21,20,23,55,38,39,50,16,35,34,16,220,17,28,30,21,14,4,190,27,57,17,28,31,20,14,4,189,26,57,178,178,178,51,7,26, + 44,78,53,40,34,230,52,1,161,8,131,10,39,39,33,229,52,58,253,234,2,130,186,41,0,1,0,79,0,0,1,104,2,7,130,91,40,0,19,39,55,51,17,51,21,33,130,5,50,81,1,106,68,105,254,233,1,105,1,103, + 81,78,254,55,61,61,1,122,130,43,32,50,130,43,37,134,2,17,0,31,0,130,43,49,62,2,51,50,30,2,21,20,6,15,1,33,21,33,53,52,55,54,67,247,5,8,58,35,34,6,7,55,1,8,29,81,37,48,72,36,17,44,59, + 147,1,1,254,173,13,1,165,37,40,58,45,26,75,24,1,159,65,5,16,27,30,48,46,21,40,78,58,146,61,46,14,12,1,165,38,80,33,33,47,27,13,0,130,94,41,0,45,255,246,1,139,2,16,0,41,130,12,32,22, + 130,93,38,35,34,38,47,1,53,30,130,108,40,54,53,52,38,43,1,53,51,50,131,8,130,101,37,15,1,53,54,51,50,131,35,8,62,1,26,112,107,85,34,78,22,23,7,25,80,41,57,65,65,49,64,64,46,56,55,45, + 33,72,20,20,74,68,78,98,51,1,22,30,109,65,84,13,7,6,69,4,12,19,51,49,46,52,58,45,38,37,43,14,7,7,64,23,74,59,50,55,130,119,34,2,0,22,130,111,45,162,2,7,0,2,0,13,0,0,37,17,3,59,1,66, + 44,6,54,19,51,1,16,179,237,88,88,67,241,208,100,181,1,18,254,238,58,123,123,73,1,66,130,46,33,0,49,130,171,32,135,130,51,37,40,0,0,19,17,33,130,47,130,143,37,30,3,21,20,14,2,137,181, + 36,62,2,53,52,46,130,15,8,68,6,7,72,1,33,221,24,41,25,48,51,38,24,35,61,67,38,43,70,14,14,7,24,76,38,21,39,39,23,23,40,44,25,28,56,14,1,2,1,4,59,127,11,10,25,38,63,40,49,72,38,18,11, + 6,5,71,4,11,19,11,25,48,33,33,48,25,12,13,7,130,157,55,41,255,248,1,143,2,8,0,9,0,37,0,0,55,50,53,52,35,34,6,21,20,22,19,65,139,5,130,119,42,53,52,62,2,51,50,22,31,1,21,38,131,26,8, + 58,54,224,101,101,41,59,59,51,31,56,49,29,91,82,87,98,36,63,79,48,24,46,11,10,31,59,69,89,36,48,119,121,57,64,63,56,1,39,20,40,68,43,90,89,114,136,73,110,63,31,8,4,3,66,25,95,98,72, + 0,130,0,38,1,0,46,0,0,1,138,130,227,32,6,130,227,8,42,53,33,21,3,35,19,46,1,91,197,78,190,1,203,59,29,254,23,1,202,0,0,3,0,39,255,246,1,145,2,17,0,15,0,31,0,52,0,0,54,50,62,2,130,243, + 38,34,14,2,20,30,1,18,132,6,32,2,132,18,35,1,23,30,1,65,210,5,35,53,52,55,38,68,239,7,8,50,199,42,32,32,18,18,33,32,40,32,33,18,18,32,72,37,29,29,16,17,29,28,36,28,30,16,16,29,33,48, + 52,104,76,77,104,99,84,95,71,70,96,45,7,20,42,63,42,19,7,7,19,130,6,43,20,1,166,6,17,37,53,37,16,6,6,16,130,6,59,17,191,16,72,52,69,78,77,70,107,33,30,91,62,69,70,61,90,0,2,0,41,0, + 0,1,143,2,16,65,43,5,43,19,34,21,20,51,50,54,53,52,38,3,34,69,108,11,65,170,5,32,22,131,26,8,44,6,215,100,100,42,59,60,51,30,57,48,29,91,82,86,99,36,64,79,47,24,46,11,11,32,59,68,89, + 35,1,216,120,120,56,64,64,56,254,217,20,39,68,44,89,90,65,44,6,35,3,4,65,24,65,44,5,55,2,0,166,0,81,1,18,1,171,0,7,0,15,0,0,18,34,38,52,54,50,22,20,6,71,199,6,38,242,44,32,32,44,32, + 76,132,5,39,1,65,31,44,31,31,44,165,132,5,32,0,130,0,36,2,0,143,255,209,134,59,32,24,140,59,35,21,20,14,2,68,137,8,37,243,45,31,31,45,31,130,67,41,22,30,31,11,10,27,55,10,17,25,135, + 74,37,32,22,33,60,41,31,68,150,10,8,37,0,1,0,24,0,84,1,160,1,176,0,6,0,0,19,37,21,13,1,21,37,24,1,135,254,200,1,56,254,121,1,30,145,62,111,112,62,145,132,123,38,24,0,152,1,159,1,114, + 72,67,5,34,37,33,53,132,1,33,1,159,130,37,32,135,131,3,35,153,59,99,59,130,39,141,79,37,5,21,5,53,45,1,131,79,32,121,130,79,36,200,1,176,145,57,131,81,132,79,42,48,0,0,1,135,2,31,0, + 34,0,42,130,121,33,50,22,130,195,44,3,29,1,35,53,52,62,4,53,52,38,35,34,132,209,34,62,4,16,65,25,6,58,226,83,82,29,42,42,29,70,21,33,38,33,22,52,43,25,45,29,22,4,5,52,2,10,34,38,61, + 132,239,8,33,2,31,68,52,28,47,33,30,33,17,41,41,22,39,28,29,23,31,16,30,33,16,23,23,8,8,34,4,14,35,26,22,254,75,65,71,9,47,255,225,255,233,1,215,2,32,0,7,0,64,0,0,54,50,71,233,5,39, + 5,23,14,4,35,34,46,3,71,98,10,46,21,35,53,6,35,34,38,52,54,51,50,22,31,1,50,132,151,8,122,6,21,20,30,2,51,50,62,3,214,60,43,43,60,43,1,5,38,2,11,38,43,71,37,63,103,67,46,20,141,105, + 105,128,15,24,21,10,55,36,43,55,79,80,55,28,49,10,11,45,84,70,81,118,39,61,75,39,35,64,40,30,14,168,56,79,57,57,79,120,46,4,11,27,21,17,33,55,74,79,42,120,163,78,67,24,35,17,7,1,198, + 19,31,93,131,94,26,13,13,28,34,57,124,104,53,87,55,30,13,20,20,13,0,0,0,2,0,5,0,0,1,178,2,7,130,9,8,38,10,0,0,55,51,3,55,19,35,39,35,7,35,19,141,158,79,45,169,77,41,193,40,77,169,192, + 1,9,61,253,250,136,136,2,6,0,3,0,38,130,47,32,146,130,47,36,8,0,17,0,39,130,49,32,50,69,22,5,36,21,17,21,22,55,131,10,42,35,23,30,4,21,20,14,2,43,1,17,69,159,6,8,61,220,65,52,62,45, + 121,71,39,84,49,42,77,12,23,34,25,18,30,50,57,31,194,177,43,62,32,15,49,58,47,52,47,43,189,1,147,156,1,2,4,76,42,33,183,3,7,20,27,48,31,38,57,32,14,2,5,25,43,46,24,42,55,130,110,47, + 0,47,255,248,1,137,2,18,0,26,0,0,37,21,6,35,67,62,7,58,23,21,38,35,34,14,2,21,20,30,1,51,50,1,136,49,79,56,86,50,24,112,104,77,51,51,77,130,65,55,15,26,66,50,77,93,73,28,42,74,95,58, + 117,151,32,71,45,33,59,74,46,62,91,59,130,233,130,183,33,1,144,130,195,34,6,0,13,131,193,33,53,52,130,172,58,19,50,17,16,35,7,17,199,125,125,84,84,201,200,160,58,202,201,254,109,1, + 204,254,253,254,254,1,130,247,34,1,0,52,130,136,32,131,130,51,8,34,11,0,0,19,33,21,33,23,51,21,35,21,33,21,33,53,1,77,254,253,1,227,228,1,4,254,178,2,6,59,153,59,188,59,0,130,0,38, + 1,0,58,0,0,1,126,130,47,32,9,132,47,34,35,31,1,130,47,40,35,58,1,67,249,1,181,182,74,130,41,35,158,1,59,241,130,34,33,0,35,130,219,32,148,130,219,32,36,130,219,38,39,35,53,51,21,14, + 4,149,224,47,62,1,1,78,1,99,170,2,7,27,32,54,30,56,85,51,130,233,33,78,50,132,233,47,14,25,66,50,27,42,11,67,141,58,223,2,7,18,13,11,143,241,37,11,7,0,1,0,42,130,108,32,141,133,191, + 57,51,17,51,21,51,53,51,17,35,53,35,21,43,75,204,75,75,204,2,6,212,212,253,250,247,246,130,39,32,66,130,39,32,117,133,39,36,19,53,33,21,35,130,43,55,5,53,55,17,67,1,50,116,116,254, + 206,115,1,203,59,59,254,112,58,1,57,1,1,145,132,231,36,65,255,249,1,118,130,47,32,13,130,231,8,33,51,17,20,6,35,7,53,51,50,54,53,17,35,158,216,66,78,164,147,48,37,140,2,6,254,158,80, + 90,1,57,48,58,1,47,130,50,39,0,1,0,19,0,0,1,165,137,139,59,55,51,7,19,35,3,7,21,19,75,233,85,212,221,90,180,57,2,6,230,230,212,254,206,1,4,57,202,130,48,34,1,0,49,130,47,32,135,130, + 47,50,5,0,0,55,17,51,17,33,21,49,75,1,10,1,2,5,254,53,58,132,31,131,79,32,164,130,31,56,12,0,0,51,17,51,23,55,51,17,7,17,3,35,3,17,20,100,99,101,100,65,107,57,106,130,130,42,254,253, + 251,1,1,197,254,239,1,19,254,130,52,34,1,0,41,130,83,32,142,65,159,5,35,51,3,51,19,130,86,130,48,38,45,3,98,186,72,95,186,130,46,55,90,1,166,253,250,1,166,254,90,0,0,2,0,35,255,250, + 1,149,2,18,0,5,0,25,130,229,63,50,16,35,34,16,18,50,62,3,52,46,3,34,14,3,20,30,2,220,184,184,184,167,34,27,30,20,13,13,20,30,27,131,8,33,14,14,130,22,50,17,253,234,2,22,254,37,8,26, + 43,78,106,78,44,26,8,8,26,44,130,8,33,43,26,130,179,38,2,0,44,255,255,1,139,132,179,32,30,131,83,71,166,5,45,43,1,21,55,50,22,21,20,6,43,1,28,1,30,130,3,8,47,49,35,17,50,206,32,46, + 22,10,10,21,42,30,93,99,85,91,85,84,108,1,1,75,174,1,10,19,31,31,17,17,31,31,18,195,252,80,70,71,89,5,21,55,48,50,29,2,6,130,90,45,0,2,0,13,255,184,1,171,2,15,0,12,0,32,131,91,39,17, + 20,7,23,21,35,39,6,143,182,39,198,184,40,84,48,82,40,58,147,187,40,14,254,245,123,67,97,44,91,27,149,193,38,2,0,38,0,0,1,145,130,191,34,9,0,24,130,99,34,35,21,22,73,125,5,35,15,1,35, + 17,73,20,5,8,45,7,23,35,39,38,213,99,68,39,34,51,53,139,3,72,179,79,83,57,44,122,79,111,97,1,205,184,1,2,2,46,45,43,47,242,218,2,5,89,69,45,69,16,229,217,1,130,184,42,1,0,42,255,246, + 1,141,2,17,0,54,130,91,44,21,46,2,35,34,6,21,20,30,7,23,30,3,73,135,16,32,39,69,75,6,8,95,30,2,23,1,109,6,21,67,35,62,61,6,14,11,25,12,31,9,33,1,23,42,48,29,101,89,43,78,18,18,7,27, + 86,45,45,66,61,69,34,48,47,24,103,87,18,40,32,27,8,1,245,71,4,13,21,41,48,11,18,15,11,10,5,7,3,5,1,4,17,33,58,39,78,74,16,9,8,73,5,16,27,46,45,46,37,14,6,17,31,50,34,72,82,5,8,9,84, + 93,5,32,9,130,143,32,175,130,235,32,7,130,233,56,53,33,21,35,17,7,17,10,1,164,172,75,1,203,59,59,254,54,1,1,203,0,1,0,37,130,187,32,147,130,35,32,24,66,163,5,32,20,74,49,5,8,50,17, + 51,17,20,14,3,34,46,3,37,76,6,19,43,32,67,48,75,6,22,38,68,95,70,38,22,7,166,1,96,254,153,26,35,34,18,54,67,1,95,254,173,33,48,53,33,22,21,32,50,44,130,75,32,13,130,111,32,171,130, + 75,8,32,6,0,0,51,3,51,27,1,51,3,174,161,73,134,134,72,161,2,6,254,58,1,198,253,250,0,1,255,249,0,0,1,190,130,35,32,12,135,35,131,38,47,35,11,1,75,81,63,58,63,83,64,57,64,81,73,72,73, + 130,47,44,99,1,157,254,98,1,158,253,250,1,184,254,72,130,55,32,255,130,55,32,185,67,123,5,8,33,19,39,51,23,55,51,7,19,35,39,7,35,184,160,80,121,123,81,165,177,80,141,141,80,1,19,243, + 195,195,243,254,237,218,218,130,139,32,5,130,47,32,178,130,47,36,8,0,0,55,3,131,47,50,3,21,35,182,176,79,135,134,80,177,75,234,1,28,228,228,254,227,233,130,34,33,0,33,130,4,32,151, + 130,39,32,9,65,35,5,60,1,33,21,5,53,1,41,1,102,254,224,1,40,254,138,1,24,1,203,59,53,254,106,58,1,56,1,147,0,130,42,41,0,104,255,189,1,80,2,73,0,7,130,12,55,39,17,51,21,35,17,51,1, + 79,162,162,231,231,2,18,1,253,226,56,2,140,0,1,0,76,151,10,41,19,1,35,1,109,1,35,70,254,222,76,150,7,130,31,138,67,52,19,51,17,35,53,51,17,7,104,231,231,163,163,2,73,253,116,56,2,30, + 1,130,90,37,0,37,1,63,1,147,65,75,5,33,19,23,131,233,45,55,252,150,82,100,101,82,150,2,6,198,141,141,198,131,139,55,255,241,255,190,1,199,255,247,0,3,0,0,5,33,53,33,1,198,254,44,1, + 212,66,56,131,27,39,0,124,1,160,1,60,2,57,131,27,131,63,39,207,108,82,109,2,57,153,153,130,27,8,175,2,0,48,255,246,1,136,1,143,0,17,0,54,0,0,55,50,62,3,53,34,35,38,14,4,21,20,22,39, + 52,62,3,23,48,60,1,46,6,35,7,53,50,54,51,21,50,30,2,21,7,35,54,39,6,35,34,38,204,32,48,23,13,2,10,21,24,45,39,32,22,13,51,118,28,50,69,81,45,2,3,7,9,15,18,26,16,122,18,58,34,38,58, + 52,29,1,61,2,2,38,99,64,79,44,26,33,49,27,17,1,2,3,10,18,28,20,37,35,72,36,51,28,16,1,1,14,7,17,10,16,10,12,7,5,2,54,2,1,12,33,65,47,241,25,27,61,63,0,0,2,0,50,255,247,1,134,2,49,0, + 9,0,30,0,0,54,50,54,53,52,38,34,6,21,20,39,62,4,67,150,5,130,127,8,57,47,1,7,35,17,51,172,112,50,51,110,52,3,1,5,18,23,42,25,71,87,88,59,32,62,16,15,7,61,68,45,82,68,67,83,83,67,68, + 212,3,8,20,16,12,102,101,98,106,29,15,15,49,2,47,0,1,0,59,130,91,32,125,130,239,35,20,0,0,1,131,84,36,22,51,50,55,21,72,197,7,8,34,23,21,38,1,13,65,72,72,65,62,49,47,78,85,110,110, + 85,78,47,49,1,89,74,76,76,74,43,65,32,106,196,106,32,65,43,139,159,32,7,133,159,133,158,38,19,51,17,35,39,14,4,130,155,8,35,53,52,54,51,50,30,2,31,1,122,200,48,104,48,200,68,62,6,3, + 8,26,27,41,20,59,88,87,70,25,42,24,17,3,4,45,150,131,158,51,1,109,253,209,49,3,7,21,15,13,106,98,101,102,12,17,17,6,7,0,130,0,34,2,0,37,130,163,32,147,130,163,37,5,0,26,0,0,19,130, + 165,35,51,52,7,20,130,168,32,54,133,169,132,95,8,42,22,29,1,32,227,47,69,224,227,62,67,42,62,46,70,82,89,109,105,79,91,90,254,218,1,89,68,48,116,165,56,79,18,21,64,29,109,95,93,110, + 97,73,48,130,83,42,1,0,40,0,3,1,144,2,36,0,19,132,247,37,29,1,51,21,35,17,130,1,33,53,51,130,77,61,59,1,21,1,40,35,31,125,125,68,122,122,65,64,108,1,237,25,37,75,57,254,217,1,39,57, + 52,78,62,55,133,147,36,50,255,70,1,134,130,147,32,9,73,49,5,77,51,8,44,51,17,20,6,43,1,53,51,50,62,2,61,1,137,254,8,60,22,23,222,99,99,53,51,51,159,61,90,81,130,136,28,42,23,10,1,5, + 18,24,42,25,71,91,91,60,48,52,28,53,142,150,82,68,65,77,1,80,254,110,86,86,58,22,36,37,18,59,2,6,16,12,10,101,100,98,101,20,29,130,162,41,0,62,0,1,1,122,2,49,0,18,74,253,5,8,45,17, + 35,53,52,38,35,34,6,29,1,35,17,51,21,54,253,53,72,68,40,37,47,56,68,68,37,1,146,78,67,255,0,250,45,48,61,59,223,2,47,218,60,0,2,0,139,130,59,38,45,2,30,0,11,0,17,130,74,8,40,35,34, + 61,1,52,59,1,50,29,1,20,7,53,51,17,35,17,1,35,56,10,10,56,9,161,161,68,1,202,10,64,9,9,64,10,127,59,254,123,1,74,130,232,34,2,0,100,130,231,32,84,130,59,34,12,0,24,130,121,130,47,32, + 20,132,221,35,54,53,17,55,138,72,39,165,174,127,112,105,29,37,59,132,72,43,1,76,58,254,98,161,59,52,50,1,100,126,133,79,39,0,1,0,41,0,2,1,142,132,131,38,0,55,23,35,39,7,21,130,183, + 53,17,55,51,210,188,81,154,51,70,70,181,80,245,243,201,45,156,2,27,254,201,161,130,118,130,47,32,133,130,179,36,51,2,8,0,5,130,117,131,164,41,35,133,173,69,104,2,7,253,250,1,72,63, + 5,46,20,255,254,1,164,1,143,0,30,0,0,1,50,22,21,130,198,36,52,35,34,6,7,138,7,48,51,21,54,51,50,23,62,1,1,68,43,52,61,52,26,26,3,132,4,52,62,62,31,42,52,26,13,48,1,143,69,53,254,234, + 1,5,84,34,37,254,238,130,6,42,33,36,254,236,1,133,18,29,49,22,27,130,128,32,1,65,111,5,33,1,147,65,111,20,32,23,65,111,9,33,64,4,65,112,12,35,1,133,48,60,66,31,5,42,42,255,247,1,141, + 1,144,0,9,0,17,67,179,11,32,18,130,171,8,40,20,32,53,52,174,92,58,59,90,59,21,166,94,254,158,44,72,80,80,70,70,80,80,1,28,102,102,205,205,102,0,2,0,50,255,78,1,134,1,136,0,67,79,6, + 38,54,53,52,34,21,20,19,131,57,8,62,6,35,34,46,2,47,1,21,35,17,51,23,62,4,176,103,48,199,107,66,89,87,71,25,41,24,18,3,3,68,61,7,1,6,20,25,41,38,82,67,148,148,67,1,16,105,99,101,103, + 12,18,17,6,6,221,2,48,49,2,8,20,16,13,152,91,35,51,17,35,53,67,171,13,38,160,104,48,200,216,62,68,66,165,5,41,70,87,89,66,23,41,26,19,4,4,134,91,44,6,253,208,221,2,8,21,15,13,103,101, + 99,105,132,99,36,0,0,1,0,69,130,4,36,115,1,142,0,19,130,7,35,50,22,31,1,71,239,5,33,29,1,130,173,8,36,7,62,1,1,12,29,52,11,11,4,16,56,31,56,71,68,68,2,17,69,1,142,15,7,8,65,5,12,20, + 60,35,245,1,133,53,27,35,130,54,46,0,69,255,254,1,115,1,151,0,38,0,0,55,30,1,130,250,34,39,46,1,80,126,9,39,46,2,35,34,21,20,22,23,79,243,7,8,78,47,1,69,53,109,71,91,83,57,14,32,65, + 44,33,62,14,15,6,19,63,33,90,36,57,70,69,88,73,31,70,20,20,88,27,14,32,35,49,15,15,53,44,22,38,36,20,11,6,6,62,4,11,17,57,25,29,8,11,46,55,57,66,12,6,6,0,0,0,1,0,87,0,6,1,97,2,4,0, + 17,130,115,41,51,21,35,34,46,3,53,17,51,21,130,9,57,21,20,216,136,125,25,33,41,24,16,68,162,162,65,58,3,15,26,50,34,1,124,118,58,204,70,132,55,40,54,255,246,1,130,1,133,0,21,130,55, + 33,53,51,80,10,5,34,55,51,19,65,74,6,8,32,54,68,86,44,62,3,68,1,64,1,3,17,23,45,27,79,73,145,244,241,102,53,39,251,254,124,42,2,7,19,13,12,74,132,67,32,29,130,128,32,155,130,67,53, + 6,0,0,1,51,3,35,3,51,19,1,84,70,148,86,147,71,120,1,133,254,123,130,3,32,186,130,38,39,0,1,255,248,255,255,1,192,130,39,33,12,0,132,39,33,39,7,131,42,48,55,51,23,1,124,67,97,63,68, + 65,65,97,68,68,53,76,60,130,47,34,123,215,215,130,5,34,208,192,192,132,55,33,0,20,130,55,32,163,130,55,35,11,0,0,37,71,43,5,57,39,51,23,55,51,1,1,162,78,122,120,78,162,149,76,110,109, + 76,203,203,155,155,204,185,141,141,77,151,5,38,68,1,137,1,134,0,31,130,12,32,18,77,244,5,44,53,51,50,62,4,53,52,53,35,34,38,53,19,130,230,59,22,51,23,3,1,134,3,12,24,47,32,195,176, + 16,23,13,8,3,1,133,71,72,1,68,29,41,137,1,130,122,56,135,48,17,47,52,36,59,12,24,22,34,17,14,4,2,78,49,1,6,229,49,50,1,1,73,132,239,32,64,130,143,32,119,130,95,8,41,14,0,0,55,51,23, + 33,53,62,3,39,35,53,33,21,2,137,237,1,254,202,15,50,105,69,1,229,1,45,238,52,52,59,17,58,122,82,1,50,60,254,235,130,54,8,32,0,1,0,63,255,178,1,120,2,84,0,41,0,0,1,21,20,7,22,29,1,20, + 22,59,1,21,34,35,34,46,3,61,1,83,197,7,130,9,33,62,3,130,22,8,61,35,34,6,1,11,72,72,38,42,29,31,13,38,54,27,14,3,38,43,51,51,43,38,3,14,27,54,38,44,29,42,38,1,215,100,95,17,17,96,99, + 34,29,62,20,26,44,30,23,86,43,32,66,32,42,87,23,30,44,26,19,62,29,130,98,53,0,188,255,200,0,252,2,63,0,3,0,0,23,35,17,51,252,64,64,55,2,117,141,135,32,19,84,60,5,36,50,51,50,30,3,134, + 142,130,119,130,9,33,14,3,69,35,5,130,141,55,55,38,172,37,42,29,30,14,37,54,27,15,2,38,44,51,51,44,38,2,15,27,54,37,130,132,41,37,72,72,1,115,100,33,29,62,19,131,129,33,87,42,130,129, + 45,43,86,24,29,44,26,20,62,29,33,100,96,17,16,130,248,42,1,0,22,0,177,1,161,1,93,0,33,130,148,34,23,14,4,131,238,39,7,14,1,15,1,39,62,4,131,119,54,55,62,1,55,1,103,58,5,5,17,21,40, + 25,25,43,30,28,31,16,20,25,3,3,143,16,62,1,66,13,21,21,45,24,20,26,35,36,21,2,3,45,21,21,13,21,22,44,24,21,26,36,35,22,3,3,45,20,130,229,32,21,130,95,45,163,0,106,0,15,0,31,0,47,0, + 0,55,50,22,130,200,36,6,43,1,34,38,130,197,34,54,59,1,157,15,43,51,104,5,7,7,5,71,4,8,8,4,222,131,9,32,70,131,4,32,221,136,9,35,105,7,5,81,131,12,150,4,42,0,0,2,0,159,255,235,1,25, + 2,9,90,167,5,33,18,34,82,231,5,59,7,51,23,7,35,53,245,50,35,35,50,35,84,46,29,1,101,1,145,35,49,35,35,49,105,196,155,155,130,51,42,63,255,147,1,121,1,242,0,5,0,28,130,177,48,17,14, + 1,21,20,19,17,54,55,21,6,7,21,35,53,46,1,90,19,6,8,62,22,23,21,38,243,50,58,146,57,39,45,51,38,78,102,100,80,38,61,35,40,49,1,38,6,73,67,134,1,25,254,215,2,25,59,21,3,100,101,6,107, + 92,95,104,4,97,98,5,20,60,25,0,1,0,40,255,255,1,144,2,16,0,27,130,89,38,51,21,33,53,51,53,35,130,3,81,218,6,32,21,71,122,5,8,39,51,21,35,202,197,254,153,87,73,73,82,79,33,52,9,10,48, + 42,50,50,136,136,59,59,59,161,50,82,88,88,10,5,5,64,30,53,63,88,50,0,131,223,38,55,0,63,1,128,1,125,130,223,35,31,0,0,54,82,67,6,8,41,54,20,7,23,7,39,6,34,39,7,39,55,38,52,55,39,55, + 23,54,50,23,55,23,7,187,65,46,46,65,46,204,22,60,34,62,31,73,31,62,34,60,22,137,10,49,148,44,61,43,43,61,67,73,30,57,35,60,19,19,60,35,57,30,137,10,75,219,10,36,24,0,0,1,7,130,160, + 33,7,21,88,161,9,32,39,130,194,8,37,39,51,23,55,1,178,120,91,115,33,148,148,75,148,148,33,115,91,119,79,135,134,2,6,194,39,53,11,39,182,182,39,11,53,39,194,228,228,130,178,41,0,2,0, + 188,255,206,0,252,2,57,83,195,5,36,23,35,17,51,53,67,9,5,40,64,64,50,1,8,92,1,7,0,130,35,59,64,255,188,1,119,2,16,0,15,0,75,0,0,37,62,1,53,52,38,39,38,39,14,1,21,20,22,23,69,167,11, + 33,53,22,85,40,5,130,28,35,46,4,53,52,89,5,5,32,54,86,84,10,133,47,8,53,4,21,20,6,1,10,21,28,48,46,25,22,22,27,48,45,25,61,25,21,69,72,25,57,16,16,58,51,36,42,37,47,8,3,28,25,39,17, + 14,38,33,25,21,68,74,24,54,14,14,51,51,37,40,36,130,22,33,29,24,131,22,42,142,12,35,15,26,44,25,14,13,12,36,132,7,63,37,18,34,23,44,66,10,5,5,57,26,32,25,20,30,26,4,2,16,14,28,23,34, + 19,28,50,16,18,34,24,43,59,131,25,33,27,26,133,25,39,15,15,28,23,33,20,28,50,133,251,42,109,1,212,1,75,2,27,0,11,0,23,73,51,13,33,43,1,73,63,9,39,1,66,58,9,9,58,9,155,131,5,37,8,1, + 213,9,52,9,136,2,48,0,0,3,255,248,0,40,1,192,1,218,0,7,0,15,0,36,65,245,9,33,18,50,92,21,5,33,22,52,130,255,35,23,21,38,35,75,119,11,8,53,142,156,111,111,156,111,95,188,133,133,188, + 134,92,78,62,57,30,43,34,47,52,52,47,46,31,36,51,61,79,105,147,105,105,147,1,34,127,179,127,127,179,152,126,66,15,38,21,48,49,49,47,18,36,17,131,179,8,41,3,0,92,0,162,1,91,2,18,0,3, + 0,18,0,53,0,0,37,35,53,51,39,34,35,34,14,4,21,20,22,51,50,54,7,52,62,2,23,60,1,46,2,88,232,5,8,122,62,6,51,50,22,29,1,35,39,6,35,34,38,1,91,247,247,55,5,8,25,24,37,19,20,8,36,22,49, + 41,201,37,58,70,33,8,15,32,22,26,50,11,12,2,18,7,17,12,17,18,9,57,73,45,8,39,54,47,59,163,43,178,1,3,6,11,18,13,24,24,61,16,33,43,14,7,4,8,10,22,14,11,11,6,6,44,1,6,2,6,2,3,1,57,64, + 159,38,45,44,0,2,0,50,0,49,1,134,1,112,0,6,0,13,0,0,1,21,7,23,21,39,53,55,133,5,50,1,134,112,112,174,7,111,111,173,173,1,112,67,93,93,66,145,28,79,132,5,35,146,0,0,4,65,59,8,56,9,0, + 27,0,35,0,43,0,0,19,22,62,2,53,52,38,43,1,23,30,1,23,35,38,39,130,9,32,21,130,224,36,50,21,20,14,1,67,78,6,65,88,7,54,175,21,36,27,15,29,21,49,86,14,25,46,52,30,17,21,24,27,47,92,103, + 34,147,65,89,10,53,1,13,1,2,6,18,15,19,20,102,5,33,72,44,26,33,103,242,74,21,32,172,65,94,11,130,172,41,0,109,1,183,1,75,1,235,0,3,130,12,130,106,38,1,74,220,220,1,183,51,66,31,5,45, + 101,1,50,1,82,2,16,0,7,0,15,0,0,18,93,253,14,56,190,59,42,42,59,41,22,98,69,69,98,69,1,94,39,55,39,39,55,138,65,91,65,65,91,133,59,40,24,255,255,1,159,1,151,0,11,131,59,92,65,11,56, + 19,33,53,33,251,164,164,62,165,165,62,164,254,121,1,135,1,36,59,115,115,59,114,254,105,87,43,5,40,115,1,133,1,69,2,173,0,24,130,143,130,245,37,7,51,21,35,53,54,85,161,5,8,47,34,6,15, + 1,53,54,51,50,22,1,66,17,62,70,152,210,77,32,42,37,28,17,42,12,13,39,51,57,58,2,94,20,33,64,61,39,38,72,29,40,36,18,25,11,6,6,41,20,130,197,32,1,130,223,38,130,1,75,2,176,0,39,131, + 79,32,6,88,180,10,91,20,23,8,51,7,22,1,75,68,55,21,49,15,14,50,42,26,48,43,31,31,31,29,36,30,27,21,44,12,12,47,44,49,63,33,30,71,1,214,37,47,7,4,4,42,18,26,25,25,27,38,22,21,18,22, + 8,130,13,38,13,42,33,28,29,7,13,130,252,39,1,0,131,1,181,1,53,2,79,123,5,41,51,7,35,235,73,120,56,2,57,131,130,26,51,0,1,0,37,255,107,1,146,1,132,0,36,0,0,37,50,54,63,1,21,133,147, + 33,14,4,130,154,36,39,21,35,17,51,66,199,5,8,63,53,55,51,16,21,20,1,120,7,12,4,3,27,29,19,26,4,3,1,4,16,22,42,27,26,47,11,60,64,45,37,43,59,3,65,49,4,2,2,52,15,26,13,13,2,7,18,14,11, + 28,26,192,2,24,241,48,53,53,38,251,254,226,24,29,130,108,42,1,0,48,255,185,1,136,2,7,0,16,76,95,7,47,16,21,6,34,47,1,17,34,38,52,54,216,175,52,70,1,130,60,8,34,69,99,99,2,6,253,182, + 2,32,253,229,5,2,1,1,1,39,85,121,85,0,0,1,0,159,0,198,1,25,1,63,0,7,0,0,66,114,7,39,195,50,35,35,50,35,1,63,130,4,33,35,50,131,35,36,143,255,119,1,41,130,43,130,95,35,33,22,21,20,65, + 92,8,52,39,48,58,1,1,0,40,91,14,31,8,8,24,27,91,73,21,22,41,37,59,130,173,34,46,11,94,132,151,40,114,1,132,1,70,2,167,0,10,131,151,37,21,35,53,51,53,7,130,239,56,250,75,204,76,83,85, + 51,1,171,38,38,212,14,40,13,0,3,0,83,0,162,1,101,2,16,130,9,37,13,0,21,0,0,37,130,41,8,47,2,34,6,21,20,22,50,54,53,52,22,32,53,52,54,50,22,21,1,86,249,249,88,69,46,45,71,45,56,254, + 239,73,127,73,163,43,1,25,47,54,54,49,49,54,54,197,143,71,130,0,130,114,67,163,15,33,55,21,130,112,35,39,53,51,23,132,7,48,223,173,111,111,166,174,174,112,112,222,28,145,66,93,93,67, + 146,132,6,41,0,4,0,19,255,162,1,165,2,64,130,127,36,6,0,17,0,28,130,242,38,23,5,39,23,51,53,55,70,111,8,33,55,3,130,72,32,51,131,14,8,44,53,51,1,155,9,254,120,9,198,102,51,43,43,50, + 144,134,187,82,87,48,75,203,75,1,47,37,91,37,203,144,43,188,37,65,65,42,183,1,86,14,39,13,252,39,39,130,81,137,91,34,28,0,39,133,89,32,5,66,236,15,34,39,54,51,130,224,34,20,6,1,143, + 100,34,1,73,86,66,254,7,42,41,13,12,1,39,51,57,59,28,254,252,138,113,52,190,77,39,39,71,30,39,36,19,25,12,6,6,42,19,51,27,23,45,1,226,134,123,34,4,0,18,132,215,32,70,134,215,32,56, + 133,125,34,23,51,39,138,215,33,39,20,67,43,10,67,42,26,132,243,34,202,102,1,130,244,8,32,49,145,134,45,72,55,21,48,13,13,41,46,36,42,38,34,33,30,31,37,33,25,24,45,10,10,46,44,50,62, + 33,30,72,65,11,13,8,68,168,36,47,7,4,4,41,18,29,47,28,37,23,21,20,20,8,4,4,42,12,41,32,29,29,8,14,0,0,2,0,73,255,247,1,111,2,27,0,30,0,38,0,0,55,50,54,63,1,21,14,2,35,34,38,53,52,62, + 4,61,1,51,21,20,14,3,21,20,22,73,68,7,8,56,235,29,66,18,19,7,24,69,34,82,78,19,29,34,29,19,71,26,37,38,26,47,71,44,32,32,44,32,48,24,11,12,65,5,12,21,65,54,24,43,30,30,24,31,17,69, + 61,30,48,34,31,39,21,31,36,1,129,91,1,6,45,3,0,5,0,0,1,179,2,131,0,3,0,6,0,130,128,36,1,35,39,51,3,90,85,9,37,1,9,56,84,68,52,90,90,9,46,2,38,92,254,61,1,10,61,253,250,135,135,2,6, + 0,130,53,143,63,34,7,35,55,139,63,36,59,84,56,72,106,132,63,39,40,193,41,77,169,2,130,92,140,64,36,3,0,5,255,255,132,127,32,6,79,77,5,32,19,130,63,34,51,23,35,138,66,38,220,61,51,78, + 69,78,51,90,223,5,133,68,33,101,62,130,69,32,151,138,134,131,135,33,255,254,130,71,61,123,0,20,0,23,0,31,0,0,19,34,6,21,35,52,54,51,50,22,51,50,54,53,55,51,20,6,35,34,38,138,85,49, + 169,12,12,47,36,34,26,62,15,11,13,1,46,34,36,28,58,45,138,164,45,81,19,16,33,43,34,17,9,8,25,51,35,254,109,139,103,32,4,136,175,38,2,0,10,0,22,0,34,91,131,12,81,53,11,72,74,11,138, + 187,32,147,72,84,9,33,9,190,136,89,32,56,72,93,13,32,0,136,207,38,149,0,2,0,14,0,30,132,101,52,39,20,22,23,51,62,1,53,52,38,34,6,23,19,35,39,35,7,35,19,38,68,11,5,32,20,130,97,52,56, + 18,16,44,16,19,33,47,34,112,159,77,40,193,41,77,159,47,60,84,60,130,98,55,110,17,26,6,6,26,17,21,31,31,101,254,25,135,135,1,231,28,51,40,55,55,40,51,130,89,38,2,255,255,1,182,2,7,130, + 109,32,19,130,97,40,17,35,3,55,21,51,21,35,53,131,88,8,40,37,7,35,23,55,7,235,37,75,186,128,202,127,37,68,150,1,23,1,122,1,111,1,190,1,13,254,244,55,188,59,134,133,2,5,2,61,153,1,60, + 0,78,87,5,38,119,1,137,2,16,0,40,130,12,91,224,8,49,55,21,6,7,22,21,20,6,35,34,39,53,22,51,50,53,52,39,88,3,6,8,66,23,21,38,1,8,38,57,32,14,25,66,50,77,51,37,56,33,45,38,45,25,24,31, + 46,26,54,81,48,23,112,104,77,51,51,1,213,32,60,74,46,62,91,59,46,73,21,5,36,32,31,30,9,45,11,31,22,32,3,42,74,93,56,117,151,32,71,45,130,187,38,52,0,3,1,132,2,135,71,103,5,8,41,55, + 33,21,33,17,33,21,35,31,1,21,35,19,35,39,51,127,1,4,254,178,1,71,253,1,241,242,142,57,84,68,63,59,2,6,59,153,1,59,1,48,93,130,175,36,2,0,52,0,4,150,59,34,7,35,55,138,59,36,173,84,56, + 72,64,135,59,33,140,93,130,60,135,59,32,136,130,119,34,18,0,0,140,119,66,185,5,138,62,38,86,61,52,78,70,78,52,136,65,33,110,62,131,66,33,0,3,130,127,32,0,130,127,32,133,130,67,34,23, + 0,35,74,129,25,32,3,134,213,35,23,51,21,35,74,141,11,33,9,58,137,222,39,2,63,8,52,9,9,52,8,133,5,33,253,252,132,173,42,59,0,2,0,66,255,254,1,118,2,131,65,31,5,8,49,1,35,17,23,21,33, + 53,51,17,35,53,33,39,35,39,51,1,117,115,115,254,206,116,116,1,50,106,56,84,68,1,202,254,111,1,57,59,1,144,59,33,92,0,0,0,2,0,66,0,3,130,59,65,91,6,130,59,32,51,132,59,32,39,130,59, + 130,227,56,1,117,116,116,254,206,115,115,1,50,60,84,56,72,1,207,254,112,59,57,1,145,1,59,125,65,31,5,133,59,65,31,6,143,59,34,51,23,35,137,62,32,148,65,30,5,137,65,32,95,65,31,7,137, + 187,65,31,28,34,23,35,17,131,153,32,55,131,213,65,31,12,32,188,135,161,33,2,61,67,88,11,32,115,132,170,34,1,145,59,131,227,45,17,0,4,1,167,2,11,0,18,0,37,0,0,55,92,29,5,8,79,43,1,21, + 51,21,35,21,50,19,50,30,3,20,14,3,43,1,53,35,53,51,53,50,200,19,36,42,30,20,20,30,42,36,19,62,99,99,62,1,31,56,61,45,29,29,45,61,56,30,139,46,46,138,62,9,27,42,75,98,75,42,27,8,162, + 53,188,1,205,12,35,55,95,125,96,54,35,11,245,53,220,131,103,42,42,0,0,1,142,2,130,0,20,0,30,68,149,22,36,23,51,17,35,3,130,2,33,51,19,68,148,16,41,140,72,95,186,71,4,98,186,2,88,68, + 145,10,32,82,92,232,5,37,2,6,254,90,0,3,92,235,6,38,135,0,5,0,9,0,29,92,237,7,35,55,35,39,51,92,241,16,37,238,57,84,68,3,33,92,245,5,34,29,28,34,133,8,42,31,2,17,253,234,2,22,25,93, + 253,175,92,247,19,135,95,32,136,130,95,32,12,92,157,5,36,16,35,34,16,55,66,235,5,32,2,93,84,15,32,184,65,210,5,32,77,150,101,37,88,62,93,93,254,11,151,103,42,251,1,149,2,129,0,20,0, + 26,0,46,65,41,14,33,55,53,69,191,5,33,23,50,93,202,16,38,169,11,13,47,36,35,25,69,199,6,39,35,29,58,34,184,184,184,168,145,127,32,87,65,64,10,32,70,131,241,44,254,37,8,26,44,78,105, + 78,44,27,7,7,27,132,8,36,26,0,0,0,4,65,79,6,131,239,36,17,0,29,0,49,65,81,7,32,37,87,16,10,69,218,11,65,101,16,33,1,30,69,225,10,32,19,145,136,32,17,131,124,32,49,66,150,11,33,253, + 244,65,17,17,8,32,1,0,46,0,65,1,137,1,137,0,11,0,0,1,7,23,7,39,7,39,55,39,55,23,55,1,137,129,129,45,128,129,45,130,5,38,129,128,1,94,121,121,42,135,2,47,0,3,0,1,255,234,1,183,2,34, + 0,10,0,21,0,39,103,247,10,46,39,20,23,55,38,35,34,14,3,37,7,22,21,16,35,80,146,5,51,53,16,51,50,23,55,220,17,27,30,20,13,7,184,26,49,7,185,26,59,132,12,40,1,70,65,30,184,83,46,54,36, + 133,6,32,54,131,157,54,53,56,42,248,58,208,56,42,249,58,8,26,44,78,205,88,65,105,254,245,56,72,25,130,7,48,1,11,56,72,0,0,2,0,46,255,246,1,138,2,131,0,17,130,123,40,0,1,51,17,20,35, + 34,53,17,130,6,8,44,22,51,50,62,2,53,3,35,39,51,1,62,75,170,176,75,39,61,30,40,19,7,43,57,84,69,2,6,254,160,176,189,1,83,254,160,67,52,18,33,36,25,1,135,92,161,71,34,7,35,55,139,71, + 35,12,84,57,72,144,71,35,227,92,92,0,130,0,139,147,33,24,0,146,147,66,196,5,139,78,32,98,66,191,5,139,81,33,17,34,130,153,33,198,62,130,82,34,3,0,47,136,227,34,29,0,41,146,81,32,19, + 66,36,22,44,1,62,76,171,176,75,40,61,30,39,19,7,5,66,30,10,144,103,32,158,72,7,15,32,2,72,111,6,35,130,0,8,0,86,29,5,38,21,35,55,3,51,23,19,130,187,44,1,98,80,177,75,1,177,79,135,90, + 84,57,73,130,74,39,227,233,234,1,28,229,1,97,130,170,41,0,2,0,42,255,255,1,142,2,6,130,55,32,21,99,245,10,8,41,55,50,22,21,20,43,1,21,35,17,51,21,50,210,49,61,63,47,93,103,83,95,178, + 103,75,75,103,186,43,48,47,42,180,240,75,74,150,127,2,6,92,0,130,222,130,67,32,242,130,67,8,127,28,0,48,0,0,19,20,30,3,21,20,14,1,38,39,53,22,51,50,54,53,52,46,3,53,52,62,2,63,1,38, + 54,46,2,35,34,6,21,17,35,17,52,54,51,50,21,34,6,234,34,48,48,33,51,78,88,38,49,51,41,45,33,47,47,33,24,35,34,12,12,1,3,10,14,38,27,46,41,68,73,82,155,47,72,1,50,20,33,27,32,53,35,43, + 57,20,5,16,56,21,36,29,24,37,25,27,45,30,28,44,24,15,2,2,1,15,23,22,16,48,50,254,123,1,133,77,74,152,44,130,138,41,0,3,0,38,255,245,1,146,2,69,130,9,34,18,0,61,130,156,49,35,39,51, + 19,50,62,2,39,48,42,1,35,14,1,21,20,22,55,130,3,50,31,1,35,38,39,14,1,35,34,38,53,52,54,59,1,60,2,46,5,81,15,9,8,99,1,12,57,118,72,24,36,52,26,10,1,36,47,11,60,52,51,225,10,5,5,68, + 9,7,21,76,38,65,80,91,91,92,2,6,8,15,20,30,18,38,71,16,17,3,25,11,24,17,24,26,13,168,1,194,131,253,230,29,47,50,26,2,32,44,38,36,183,116,25,55,15,15,22,37,32,37,64,60,62,70,1,15,9, + 18,13,16,11,10,5,18,10,9,63,1,9,3,8,3,4,2,149,171,35,7,35,55,3,131,171,33,42,2,167,170,37,84,118,57,103,80,37,131,170,33,1,35,167,171,34,2,69,131,176,172,65,87,9,39,6,0,21,0,64,0,0, + 19,130,171,34,51,23,35,132,174,65,90,41,39,220,66,52,90,56,90,52,97,65,92,45,38,2,26,88,131,131,254,105,65,94,20,33,63,69,65,94,20,135,175,46,51,0,24,0,39,0,82,0,0,1,34,46,2,35,34, + 75,234,5,42,30,1,51,50,54,61,1,51,20,14,2,174,191,53,1,13,21,31,16,23,11,26,45,36,37,21,34,30,13,12,13,46,5,13,30,101,173,205,50,1,209,17,20,17,54,43,55,27,26,26,13,14,15,29,33,21, + 254,90,148,217,66,56,24,32,4,66,227,6,40,29,0,11,0,23,0,38,0,81,74,25,25,32,19,66,77,45,32,63,68,115,10,32,6,66,85,46,33,1,214,68,147,11,33,254,85,181,211,52,114,0,7,0,15,0,58,0,73, + 0,0,18,34,6,20,22,50,54,52,6,34,88,7,5,32,19,67,183,31,67,58,12,44,240,46,33,33,46,33,14,84,60,60,84,60,63,67,191,33,32,194,139,237,46,2,70,31,44,31,31,44,118,56,80,56,56,80,254,249, + 67,204,32,33,254,155,136,236,67,215,5,55,5,255,245,1,179,1,143,0,8,0,19,0,89,0,0,1,34,6,23,51,54,39,46,1,130,161,33,1,39,85,233,5,40,37,21,35,28,2,30,5,51,22,79,184,7,34,46,2,47,96, + 42,8,32,59,113,200,6,83,206,5,8,164,30,2,31,1,62,4,51,50,22,23,30,1,21,1,56,31,31,3,121,1,2,3,27,217,26,26,14,1,28,53,44,37,1,75,182,2,4,6,10,14,21,12,34,52,9,10,5,15,48,25,25,42,22, + 16,2,3,1,4,16,21,36,22,57,60,70,68,50,42,30,19,46,13,14,44,65,19,30,18,12,2,2,1,3,14,19,36,22,58,48,8,2,1,1,90,54,64,23,22,35,38,254,209,18,59,59,32,38,35,31,136,1,1,28,10,28,13,23, + 11,14,6,1,17,9,10,60,3,10,16,11,17,16,6,5,2,7,19,15,12,60,56,57,65,28,50,39,14,8,7,58,24,9,13,13,4,5,2,6,15,11,10,59,76,18,42,12,130,248,42,1,0,59,255,119,1,125,1,142,0,37,132,243, + 42,21,20,22,51,50,55,21,14,1,15,1,77,223,14,130,222,34,54,51,50,98,88,10,35,14,43,15,15,77,222,8,33,82,106,98,99,5,56,88,74,76,76,74,43,65,11,15,2,2,36,32,31,30,8,46,12,32,22,31,3, + 105,96,98,98,114,5,41,0,3,0,37,255,247,1,147,2,69,130,9,34,9,0,30,69,235,5,32,23,98,25,22,42,21,23,32,1,19,57,118,72,55,46,70,98,30,12,40,92,89,1,254,217,1,194,131,236,98,33,17,145, + 95,35,7,35,55,7,154,95,36,93,119,56,102,49,147,95,34,2,69,131,147,96,33,0,0,138,195,36,6,0,12,0,33,69,87,8,154,102,39,225,67,52,90,57,90,52,64,148,104,36,26,88,131,131,105,145,202, + 33,0,4,65,43,6,68,51,5,34,29,0,50,68,51,25,65,65,27,44,69,57,9,9,57,9,155,58,9,9,58,9,39,147,128,68,5,13,32,125,146,137,8,58,0,0,2,0,51,255,252,1,117,2,59,0,13,0,17,0,0,37,51,21,34, + 35,34,38,61,1,35,53,51,21,20,17,35,39,51,1,37,80,24,71,54,65,90,158,57,119,73,51,54,78,63,201,50,251,86,1,132,131,0,130,0,34,2,0,68,130,59,32,116,149,59,48,19,7,35,55,1,37,79,23,72, + 53,66,90,158,106,119,57,103,135,60,34,2,7,131,130,61,135,59,36,69,0,6,0,20,65,105,8,32,19,140,126,39,186,66,52,90,56,90,51,40,134,68,70,121,5,32,113,134,131,130,127,32,3,134,127,38, + 26,0,11,0,23,0,37,65,69,25,141,86,33,1,44,65,56,5,132,5,32,130,134,92,33,1,212,69,49,12,32,95,135,101,54,2,0,42,255,244,1,142,2,27,0,14,0,47,0,0,55,50,54,53,52,38,47,1,90,34,6,38,19, + 20,30,6,21,20,6,72,186,5,8,96,23,46,1,47,1,7,39,55,39,51,23,55,23,7,22,220,45,60,20,10,10,18,50,43,59,60,145,20,6,19,8,13,6,5,89,88,88,89,107,100,5,27,10,11,103,12,88,67,81,47,106, + 13,93,36,42,70,71,38,67,15,14,9,69,73,73,69,1,89,1,27,10,29,19,33,29,38,19,86,107,107,94,93,102,8,8,31,12,11,31,34,27,69,49,32,34,28,34,65,115,5,32,62,130,231,44,122,2,32,0,18,0,43, + 0,0,19,50,22,21,100,121,12,34,23,54,55,71,88,17,54,35,34,46,2,253,53,72,68,39,38,47,56,68,64,4,37,3,26,45,36,37,20,35,71,51,5,40,14,29,21,21,31,17,22,1,145,100,165,9,51,1,132,47,60, + 99,54,44,54,27,26,26,14,13,15,29,33,21,17,20,17,130,124,40,3,0,43,255,244,1,141,2,69,86,227,7,36,1,35,39,51,18,102,253,8,99,73,7,37,1,15,56,119,73,5,99,78,9,37,1,194,131,253,229,71, + 99,82,9,35,204,204,102,0,130,65,143,75,35,7,35,55,2,145,75,36,86,118,57,103,96,137,75,34,2,69,131,145,76,137,151,36,6,0,16,0,24,66,77,8,145,78,72,242,6,32,112,138,80,37,26,88,131,131, + 254,104,143,158,136,159,32,32,130,79,34,34,0,42,72,179,24,145,99,53,1,15,20,32,16,22,12,25,46,36,38,20,35,29,14,12,13,46,5,14,30,118,137,113,36,1,190,17,20,17,65,92,11,33,254,108,142, + 125,32,4,65,103,6,66,215,5,34,33,0,41,66,217,25,146,126,93,1,10,33,9,11,138,118,66,224,13,32,86,142,115,32,3,130,231,36,49,1,159,1,136,130,249,42,19,0,35,0,0,37,33,53,33,39,35,96,108, + 13,32,3,142,15,48,1,159,254,121,1,135,161,70,4,7,7,4,70,5,6,6,5,136,9,37,192,59,56,6,5,63,131,18,130,4,33,254,255,130,11,131,35,130,11,32,0,130,0,44,3,0,12,255,222,1,172,1,166,0,7, + 0,15,131,107,39,55,50,54,53,52,39,7,22,78,242,6,37,6,37,7,22,21,20,78,241,7,8,65,52,54,51,50,23,55,22,222,47,57,10,169,27,56,9,168,27,46,45,59,1,54,61,33,178,75,44,57,34,62,29,94,83, + 71,46,55,34,43,72,80,42,32,189,37,152,42,31,189,33,70,121,68,52,81,204,40,63,26,70,50,81,102,102,39,63,27,67,55,5,51,61,255,246,1,123,2,59,0,3,0,26,0,0,1,35,39,51,23,51,17,105,15,6, + 38,61,1,51,21,20,22,51,130,133,8,41,1,13,57,119,73,144,68,63,6,2,5,20,23,38,21,77,61,67,38,43,44,53,1,184,131,182,254,124,57,2,10,23,18,14,72,82,244,240,52,52,59,50,130,84,33,2,0,141, + 83,34,7,35,55,148,83,36,83,119,56,102,44,143,83,34,2,59,131,147,84,135,83,36,69,0,6,0,29,66,201,8,32,23,145,169,32,55,66,203,6,32,92,139,171,41,42,45,53,2,2,26,88,131,131,61,143,174, + 32,235,130,175,32,3,134,175,95,67,5,32,46,66,85,25,148,197,35,63,58,8,8,95,89,6,33,9,128,140,205,130,117,95,106,13,32,80,143,125,42,0,0,2,0,26,255,107,1,158,2,59,80,107,7,34,2,7,14, + 99,148,6,8,49,55,3,51,27,1,7,35,55,1,86,72,140,39,14,32,36,25,18,54,46,30,32,22,160,72,123,105,119,56,102,1,133,254,175,98,35,44,18,5,54,46,54,1,127,254,208,1,230,131,131,130,203,34, + 2,0,50,130,79,39,134,2,32,0,9,0,23,0,107,131,10,33,19,50,66,59,5,53,21,35,17,51,21,54,174,89,55,57,86,56,99,80,91,171,67,32,68,68,31,42,66,245,11,37,65,202,2,180,208,61,130,75,32,3, + 134,155,32,17,130,155,38,29,0,41,0,0,1,51,142,157,80,34,23,144,177,32,100,71,147,10,144,185,32,118,80,40,14,42,1,0,30,255,249,1,153,2,20,0,43,130,115,40,34,7,51,7,35,6,21,20,21,130, + 6,35,30,3,51,50,107,75,6,38,39,35,55,51,38,52,55,130,5,8,76,62,1,51,50,23,21,46,1,1,44,110,20,178,18,163,1,132,17,111,6,27,38,37,23,20,61,27,47,61,88,103,14,65,18,44,2,2,62,18,47,14, + 103,83,65,48,28,61,1,220,144,36,30,4,17,15,37,44,60,29,10,19,24,71,28,104,95,37,29,9,28,36,95,105,29,72,24,21,130,246,130,2,36,14,0,174,0,1,130,7,131,2,34,1,0,4,134,11,32,1,130,7,32, + 10,134,11,32,2,130,7,32,16,134,11,36,3,0,29,0,78,134,11,131,43,32,112,134,11,36,5,0,9,0,134,134,11,32,6,130,7,44,148,0,3,0,1,4,9,0,0,0,2,0,0,134,11,32,1,130,11,32,6,134,11,32,2,130, + 11,32,12,134,11,36,3,0,58,0,18,134,11,32,4,130,23,32,108,134,11,32,5,130,21,32,114,134,11,32,6,130,23,35,144,0,46,0,143,2,39,70,0,111,0,110,0,116,0,131,7,40,114,0,103,0,101,0,32,0, + 50,130,36,32,48,130,7,32,58,130,3,32,46,134,7,36,49,0,49,0,45,130,25,131,3,32,48,130,7,51,54,0,0,70,111,110,116,70,111,114,103,101,32,50,46,48,32,58,32,46,130,3,39,49,49,45,50,45,50, + 48,50,130,30,133,107,32,86,130,81,36,114,0,115,0,105,132,103,32,32,130,89,40,0,86,101,114,115,105,111,110,32,136,140,33,2,0,139,0,65,75,7,137,19,32,192,130,10,131,251,60,3,0,4,0,5, + 0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,130,235,8,50,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0,38,0,39,0,40,0,41, + 0,42,0,43,0,44,130,211,36,46,0,47,0,48,130,221,9,48,50,0,51,0,52,0,53,0,54,0,55,0,56,0,57,0,58,0,59,0,60,0,61,0,62,0,63,0,64,0,65,0,66,0,67,0,68,0,69,0,70,0,71,0,72,0,73,0,74,0,75, + 0,76,0,77,0,78,0,79,0,80,0,81,0,82,0,83,0,84,0,85,0,86,0,87,0,88,0,89,0,90,0,91,0,92,0,93,0,94,1,2,0,96,0,97,1,3,0,163,0,132,0,133,0,189,0,150,0,232,0,134,0,142,0,139,0,157,0,169,0, + 138,1,4,0,131,0,147,0,242,0,243,0,141,0,151,0,136,0,195,0,222,0,241,0,158,0,170,0,245,0,244,0,246,0,162,0,173,0,201,0,199,0,174,0,98,0,99,0,144,0,100,0,203,0,101,0,200,0,202,0,207, + 0,204,0,205,0,206,0,233,0,102,0,211,0,209,0,175,0,103,0,240,0,145,0,214,0,212,0,213,0,104,0,235,0,237,0,137,0,106,0,105,0,107,0,109,0,108,0,110,0,160,0,111,0,113,0,112,0,114,0,115, + 0,117,0,116,0,118,0,119,0,234,0,120,0,122,0,121,0,123,0,125,0,124,0,184,0,161,0,127,0,126,0,128,0,129,0,236,0,238,0,186,1,5,11,118,101,114,116,105,99,97,108,98,97,114,7,117,110,105, + 48,48,56,53,9,111,130,20,42,115,99,111,114,101,4,69,117,114,111,0,132,0,38,1,255,255,0,2,0,1,130,11,32,12,130,3,32,22,130,3,131,13,32,98,130,183,34,1,0,4,132,13,130,4,130,2,32,1,130, + 3,36,0,229,13,183,147,132,7,42,175,187,66,0,0,0,0,229,178,59,232,5,250,48,120,202,241, }; -static const char* GetDefaultCompressedFontDataProggyVector(int* out_size) +static const char* GetDefaultCompressedFontDataProggyForever(int* out_size) { - *out_size = proggy_vector_minimal_ttf_compressed_size; - return (const char*)proggy_vector_minimal_ttf_compressed_data; + *out_size = proggy_forever_minimal_ttf_compressed_size; + return (const char*)proggy_forever_minimal_ttf_compressed_data; } #endif // #ifndef IMGUI_DISABLE_DEFAULT_FONT diff --git a/misc/fonts/ProggyVector-ExtractScript.txt b/misc/fonts/ProggyVector-ExtractScript.txt deleted file mode 100644 index 697e88bcd..000000000 --- a/misc/fonts/ProggyVector-ExtractScript.txt +++ /dev/null @@ -1,17 +0,0 @@ -# Usage: fontforge.exe -script ProggyVector-ExtractScript.txt -Open("ProggyVector-Regular.ttf") -SelectMore(0x20,0xFF) -SelectMore(0x20AC) # Euro sign -SelectInvert() -DetachAndRemoveGlyphs() -SelectAll() -RemoveOverlap() -Simplify() -i=0 -while (i < 23) - SetTTFName(0x409,i,"") - i=i+1 -endloop -SetFontNames(".",".",".",".",".",".") -Generate("ProggyVector-minimal.ttf") -# At this point you can use binary_to_compressed_c.exe -u8 ProggyVector-minimal.ttf proggy_vector_minimal_ttf From 9f2b3bcf7a7625044799f064f0ad7aa446746c72 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Feb 2026 15:58:20 +0100 Subject: [PATCH 1663/2359] Backends: SDL2, SDL3: systems other than X11 are back to starting mouse capture on mouse down. Only X11 requires waiting for a drag by defaultadded ImGui_ImplSDL2_SetMouseCaptureMode(), ImGui_ImplSDL3_SetMouseCaptureMode(). (#9235, #3650, #6410, #3956, #3835) Amend aa83d5d455 --- backends/imgui_impl_sdl2.cpp | 28 ++++++++++++++++++++++------ backends/imgui_impl_sdl2.h | 7 +++++++ backends/imgui_impl_sdl3.cpp | 28 ++++++++++++++++++++++------ backends/imgui_impl_sdl3.h | 7 +++++++ docs/CHANGELOG.txt | 14 ++++++++++++++ 5 files changed, 72 insertions(+), 12 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 4fb9c4d99..f578977c4 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,6 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 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) // 2025-09-24: Skip using the SDL_GetGlobalMouseState() state when one of our window is hovered, as the SDL_MOUSEMOTION data is reliable. Fix macOS notch mouse coordinates issue in fullscreen mode + better perf on X11. (#7919, #7786) // 2025-09-18: Call platform_io.ClearPlatformHandlers() on shutdown. @@ -30,7 +31,7 @@ // 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) -// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) +// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g. Linux debuggers not claiming capture back. (#6410, #3650) // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. @@ -154,7 +155,7 @@ struct ImGui_ImplSDL2_Data SDL_Cursor* MouseLastCursor; int MouseLastLeaveFrame; bool MouseCanUseGlobalState; - bool MouseCanUseCapture; + ImGui_ImplSDL2_MouseCaptureMode MouseCaptureMode; // Gamepad handling ImVector Gamepads; @@ -514,13 +515,16 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void // Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse() // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) bd->MouseCanUseGlobalState = false; - bd->MouseCanUseCapture = false; + bd->MouseCaptureMode = ImGui_ImplSDL2_MouseCaptureMode_Disabled; #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE const char* sdl_backend = SDL_GetCurrentVideoDriver(); const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; for (const char* item : capture_and_global_state_whitelist) if (strncmp(sdl_backend, item, strlen(item)) == 0) - bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true; + { + bd->MouseCanUseGlobalState = true; + bd->MouseCaptureMode = (strcmp(item, "x11") == 0) ? ImGui_ImplSDL2_MouseCaptureMode_EnabledAfterDrag : ImGui_ImplSDL2_MouseCaptureMode_Enabled; + } #endif ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); @@ -650,6 +654,14 @@ void ImGui_ImplSDL2_Shutdown() IM_DELETE(bd); } +void ImGui_ImplSDL2_SetMouseCaptureMode(ImGui_ImplSDL2_MouseCaptureMode mode) +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + if (mode == ImGui_ImplSDL2_MouseCaptureMode_Disabled && bd->MouseCaptureMode != ImGui_ImplSDL2_MouseCaptureMode_Disabled) + SDL_CaptureMouse(SDL_FALSE); + bd->MouseCaptureMode = mode; +} + static void ImGui_ImplSDL2_UpdateMouseData() { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); @@ -658,8 +670,12 @@ static void ImGui_ImplSDL2_UpdateMouseData() // We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below) #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside. - // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture. - if (bd->MouseCanUseCapture) + // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue on X11 we we wait until mouse has moved to begin capture. + if (bd->MouseCaptureMode == ImGui_ImplSDL2_MouseCaptureMode_Enabled) + { + SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE); + } + else if (bd->MouseCaptureMode == ImGui_ImplSDL2_MouseCaptureMode_EnabledAfterDrag) { bool want_capture = false; for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) diff --git a/backends/imgui_impl_sdl2.h b/backends/imgui_impl_sdl2.h index 3c0a4a7e4..63ef7071a 100644 --- a/backends/imgui_impl_sdl2.h +++ b/backends/imgui_impl_sdl2.h @@ -47,4 +47,11 @@ IMGUI_IMPL_API float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_ind enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual }; IMGUI_IMPL_API void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = nullptr, int manual_gamepads_count = -1); +// (Advanced, for X11 users) Override Mouse Capture mode. Mouse capture allows receiving updated mouse position after clicking inside our window and dragging outside it. +// Having this 'Enabled' is in theory always better. But, on X11 if you crash/break to debugger while capture is active you may temporarily lose access to your mouse. +// The best solution is to setup your debugger to automatically release capture, e.g. 'setxkbmap -option grab:break_actions && xdotool key XF86Ungrab' or via a GDB script. See #3650. +// But you may independently decide on X11, when a debugger is attached, to set this value to ImGui_ImplSDL2_MouseCaptureMode_Disabled. +enum ImGui_ImplSDL2_MouseCaptureMode { ImGui_ImplSDL2_MouseCaptureMode_Enabled, ImGui_ImplSDL2_MouseCaptureMode_EnabledAfterDrag, ImGui_ImplSDL2_MouseCaptureMode_Disabled }; +IMGUI_IMPL_API void ImGui_ImplSDL2_SetMouseCaptureMode(ImGui_ImplSDL2_MouseCaptureMode mode); + #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp index f8bacc51b..a2bd606a6 100644 --- a/backends/imgui_impl_sdl3.cpp +++ b/backends/imgui_impl_sdl3.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 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_ImplSDL3_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) // 2025-11-05: Fixed an issue with missing characters events when an already active text field changes viewports. (#9054) // 2025-10-22: Fixed Platform_OpenInShellFn() return value (unused in core). @@ -32,7 +33,7 @@ // 2025-03-30: Update for SDL3 api changes: Revert SDL_GetClipboardText() memory ownership change. (#8530, #7801) // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set. // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468) -// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650) +// 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g. Linux debuggers not claiming capture back. (#6410, #3650) // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode. // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support. // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler. @@ -124,7 +125,7 @@ struct ImGui_ImplSDL3_Data SDL_Cursor* MouseLastCursor; int MousePendingLeaveFrame; bool MouseCanUseGlobalState; - bool MouseCanUseCapture; + ImGui_ImplSDL3_MouseCaptureMode MouseCaptureMode; // Gamepad handling ImVector Gamepads; @@ -518,13 +519,16 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void // Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse() // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) bd->MouseCanUseGlobalState = false; - bd->MouseCanUseCapture = false; + bd->MouseCaptureMode = ImGui_ImplSDL3_MouseCaptureMode_Disabled; #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE const char* sdl_backend = SDL_GetCurrentVideoDriver(); const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; for (const char* item : capture_and_global_state_whitelist) if (strncmp(sdl_backend, item, strlen(item)) == 0) - bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true; + { + bd->MouseCanUseGlobalState = true; + bd->MouseCaptureMode = (strcmp(item, "x11") == 0) ? ImGui_ImplSDL3_MouseCaptureMode_EnabledAfterDrag : ImGui_ImplSDL3_MouseCaptureMode_Enabled; + } #endif ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); @@ -629,6 +633,14 @@ void ImGui_ImplSDL3_Shutdown() IM_DELETE(bd); } +void ImGui_ImplSDL3_SetMouseCaptureMode(ImGui_ImplSDL3_MouseCaptureMode mode) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + if (mode == ImGui_ImplSDL3_MouseCaptureMode_Disabled && bd->MouseCaptureMode != ImGui_ImplSDL3_MouseCaptureMode_Disabled) + SDL_CaptureMouse(false); + bd->MouseCaptureMode = mode; +} + static void ImGui_ImplSDL3_UpdateMouseData() { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); @@ -637,8 +649,12 @@ static void ImGui_ImplSDL3_UpdateMouseData() // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below) #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside. - // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture. - if (bd->MouseCanUseCapture) + // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue on X11 we we wait until mouse has moved to begin capture. + if (bd->MouseCaptureMode == ImGui_ImplSDL3_MouseCaptureMode_Enabled) + { + SDL_CaptureMouse(bd->MouseButtonsDown != 0); + } + else if (bd->MouseCaptureMode == ImGui_ImplSDL3_MouseCaptureMode_EnabledAfterDrag) { bool want_capture = false; for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++) diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h index a822a259b..0720283c0 100644 --- a/backends/imgui_impl_sdl3.h +++ b/backends/imgui_impl_sdl3.h @@ -44,4 +44,11 @@ IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual }; IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = nullptr, int manual_gamepads_count = -1); +// (Advanced, for X11 users) Override Mouse Capture mode. Mouse capture allows receiving updated mouse position after clicking inside our window and dragging outside it. +// Having this 'Enabled' is in theory always better. But, on X11 if you crash/break to debugger while capture is active you may temporarily lose access to your mouse. +// The best solution is to setup your debugger to automatically release capture, e.g. 'setxkbmap -option grab:break_actions && xdotool key XF86Ungrab' or via a GDB script. See #3650. +// But you may independently decide on X11, when a debugger is attached, to set this value to ImGui_ImplSDL3_MouseCaptureMode_Disabled. +enum ImGui_ImplSDL3_MouseCaptureMode { ImGui_ImplSDL3_MouseCaptureMode_Enabled, ImGui_ImplSDL3_MouseCaptureMode_EnabledAfterDrag, ImGui_ImplSDL3_MouseCaptureMode_Disabled }; +IMGUI_IMPL_API void ImGui_ImplSDL3_SetMouseCaptureMode(ImGui_ImplSDL3_MouseCaptureMode mode); + #endif // #ifndef IMGUI_DISABLE diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bbc9721fa..58124f4a8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -235,6 +235,20 @@ Other Changes: platforms. (#8792, #9112) - SDL2, SDL3: changed `GetClipboardText()` handler to return NULL on error aka clipboard contents is not text. Consistent with other backends. (#9168) + - SDL2, SDL3: systems other than X11 are back to starting mouse capture on mouse down + (reverts 1.91.9 change). Only X11 requires waiting for a drag by default (not ideal, + but a better default for X11 users). Waiting for a drag to start mouse capture leads to + input drops when dragging after clicking on the edge of a window. + (#3650, #6410, #9235, #3956, #3835) + - SDL2, SDL3: added ImGui_ImplSDL2_SetMouseCaptureMode()/ImGui_ImplSDL3_SetMouseCaptureMode() + function for X11 users to disable mouse capturing/grabbing. (#3650, #6410, #9235, #3956, #3835) + - When attached to a debugger may want to call: + - `ImGui_ImplSDL3_SetMouseCaptureMode(ImGui_ImplSDL3_MouseCaptureMode_Disabled);` + - But you can also configure your system or debugger to automatically release + mouse grab when crashing/breaking in debugger, e.g. + - console: `setxkbmap -option grab:break_actions && xdotool key XF86Ungrab` + - or use a GDB script to capture SDL_CaptureMouse(false). See #3650. + - On platforms other than X11 this is unnecessary. - SDL_GPU3: added `SamplerNearest` in `ImGui_ImplSDLGPU3_RenderState`. - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ (vs Metallib shaders requiring macOS 14+). Requires application calling From eaa32bb787574510baed7f73a1010ea7347ff202 Mon Sep 17 00:00:00 2001 From: Naveen Regulla Date: Sat, 31 Jan 2026 07:45:47 +0530 Subject: [PATCH 1664/2359] Avoid using SSE intrinsic on ARM64/ARM64EC targets. (#9209, #5943, #4091) --- docs/CHANGELOG.txt | 2 ++ imgui_internal.h | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 58124f4a8..46c23c68d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -201,6 +201,8 @@ Other Changes: flags of last submitted item. (#9127) - Log/Capture: fixed erroneously injecting extra carriage returns in output buffer when ItemSpacing.y > FramePadding.y + 1. +- Misc: fixed build on ARM64/ARM64EC targets trying to use SSE/immintrin.h. + (#9209, #5943, #4091) [@navvyswethgraphics] - Images: - Added style.ImageRounding, ImGuiStyleVar_ImageRounding to configure rounding of Image() widgets. (#2942, #845) diff --git a/imgui_internal.h b/imgui_internal.h index 9220149a0..7dbe9784e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -60,7 +60,7 @@ Index of this file: #include // INT_MIN, INT_MAX // Enable SSE intrinsics if available -#if (defined __SSE__ || defined __x86_64__ || defined _M_X64 || (defined(_M_IX86_FP) && (_M_IX86_FP >= 1))) && !defined(IMGUI_DISABLE_SSE) +#if (defined __SSE__ || defined __x86_64__ || defined _M_X64 || (defined(_M_IX86_FP) && (_M_IX86_FP >= 1))) && !defined(IMGUI_DISABLE_SSE) && !defined(_M_ARM64) && !defined(_M_ARM64EC) #define IMGUI_ENABLE_SSE #include #if (defined __AVX__ || defined __SSE4_2__) From fbe973a8d0e95bfcf42dfe4aa6785d481230f9a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurenz=20Altenm=C3=BCller?= Date: Mon, 16 Feb 2026 14:36:36 +0100 Subject: [PATCH 1665/2359] Cast this to (void*) in zero-clearing memset calls to fix -Wnontrivial-memcall (#9247, #8295, #8129, #8135) Clang 20+ warns on memset(this, ...) for non-trivially copyable types via -Wnontrivial-memcall. Should separately investigate -Wnonontrivial-memaccess vs -Wnonontrivial-memcall. --- backends/imgui_impl_dx12.h | 2 +- imgui.cpp | 8 ++--- imgui.h | 20 ++++++------- imgui_draw.cpp | 12 ++++---- imgui_internal.h | 60 +++++++++++++++++++------------------- imgui_widgets.cpp | 8 ++--- 6 files changed, 55 insertions(+), 55 deletions(-) diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 8d61dae77..27ede2b21 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -44,7 +44,7 @@ struct ImGui_ImplDX12_InitInfo D3D12_GPU_DESCRIPTOR_HANDLE LegacySingleSrvGpuDescriptor; #endif - ImGui_ImplDX12_InitInfo() { memset(this, 0, sizeof(*this)); } + ImGui_ImplDX12_InitInfo() { memset((void*)this, 0, sizeof(*this)); } }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! diff --git a/imgui.cpp b/imgui.cpp index 63c6789a5..eb8160a79 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1568,7 +1568,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) ImGuiIO::ImGuiIO() { // Most fields are initialized with zero - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); IM_STATIC_ASSERT(IM_COUNTOF(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_COUNTOF(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Settings @@ -1974,7 +1974,7 @@ void ImGuiIO::AddFocusEvent(bool focused) ImGuiPlatformIO::ImGuiPlatformIO() { // Most fields are initialized with zero - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); Platform_LocaleDecimalPoint = '.'; } @@ -3231,7 +3231,7 @@ static void ImGuiListClipper_SeekCursorAndSetupPrevLine(ImGuiListClipper* clippe ImGuiListClipper::ImGuiListClipper() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); } ImGuiListClipper::~ImGuiListClipper() @@ -4525,7 +4525,7 @@ 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) { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); Ctx = ctx; Name = ImStrdup(name); NameBufLen = (int)ImStrlen(name) + 1; diff --git a/imgui.h b/imgui.h index 6fd1ceff6..402e1a3da 100644 --- a/imgui.h +++ b/imgui.h @@ -2144,7 +2144,7 @@ struct ImGuiTableSortSpecs int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. - ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); } + ImGuiTableSortSpecs() { memset((void*)this, 0, sizeof(*this)); } }; // Sorting specification for one column of a table (sizeof == 12 bytes) @@ -2155,7 +2155,7 @@ struct ImGuiTableColumnSortSpecs ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) ImGuiSortDirection SortDirection; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending - ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); } + ImGuiTableColumnSortSpecs() { memset((void*)this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- @@ -2881,7 +2881,7 @@ struct ImGuiListClipper #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9] //inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] - //inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] + //inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset((void*)this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] #endif }; @@ -3166,7 +3166,7 @@ struct ImDrawCmd int UserCallbackDataSize; // 4 // Size of callback user data when using storage, otherwise 0. int UserCallbackDataOffset;// 4 // [Internal] Offset of callback user data when using storage, otherwise -1. - ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed + ImDrawCmd() { memset((void*)this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! @@ -3212,7 +3212,7 @@ struct ImDrawListSplitter int _Count; // Number of active channels (1+) ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) - inline ImDrawListSplitter() { memset(this, 0, sizeof(*this)); } + inline ImDrawListSplitter() { memset((void*)this, 0, sizeof(*this)); } inline ~ImDrawListSplitter() { ClearFreeMemory(); } inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame IMGUI_API void ClearFreeMemory(); @@ -3505,7 +3505,7 @@ struct ImTextureData bool WantDestroyNextFrame; // rw - // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. // Functions - ImTextureData() { memset(this, 0, sizeof(*this)); Status = ImTextureStatus_Destroyed; TexID = ImTextureID_Invalid; } + ImTextureData() { memset((void*)this, 0, sizeof(*this)); Status = ImTextureStatus_Destroyed; TexID = ImTextureID_Invalid; } ~ImTextureData() { DestroyPixels(); } IMGUI_API void Create(ImTextureFormat format, int w, int h); IMGUI_API void DestroyPixels(); @@ -3582,7 +3582,7 @@ struct ImFontGlyph float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. int PackId; // [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) - ImFontGlyph() { memset(this, 0, sizeof(*this)); PackId = -1; } + ImFontGlyph() { memset((void*)this, 0, sizeof(*this)); PackId = -1; } }; // Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). @@ -3615,7 +3615,7 @@ struct ImFontAtlasRect unsigned short w, h; // Size ImVec2 uv0, uv1; // UV coordinates (in current texture) - ImFontAtlasRect() { memset(this, 0, sizeof(*this)); } + ImFontAtlasRect() { memset((void*)this, 0, sizeof(*this)); } }; // Flags for ImFontAtlas build @@ -3944,7 +3944,7 @@ struct ImGuiViewport void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND, GLFWWindow*, SDL_Window*) void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms) - ImGuiViewport() { memset(this, 0, sizeof(*this)); } + ImGuiViewport() { memset((void*)this, 0, sizeof(*this)); } // Helpers ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } @@ -4021,7 +4021,7 @@ struct ImGuiPlatformImeData float InputLineHeight; // Line height (for IME). ImGuiID ViewportId; // ID of platform window/viewport. - ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } + ImGuiPlatformImeData() { memset((void*)this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0493f022a..312c04c28 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -392,7 +392,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) ImDrawListSharedData::ImDrawListSharedData() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); InitialFringeScale = 1.0f; for (int i = 0; i < IM_COUNTOF(ArcFastVtx); i++) { @@ -424,7 +424,7 @@ void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error) ImDrawList::ImDrawList(ImDrawListSharedData* shared_data) { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); _SetDrawListSharedData(shared_data); } @@ -2417,7 +2417,7 @@ void ImGui::ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, in // FIXME-NEWATLAS: Oversample specification could be more dynamic. For now, favoring automatic selection. ImFontConfig::ImFontConfig() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); FontDataOwnedByAtlas = true; OversampleH = 0; // Auto == 1 or 2 depending on size OversampleV = 0; // Auto == 1 @@ -2641,7 +2641,7 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3 ImFontAtlas::ImFontAtlas() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); TexDesiredFormat = ImTextureFormat_RGBA32; TexGlyphPadding = 1; TexMinWidth = 512; @@ -5134,7 +5134,7 @@ void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) ImFontBaked::ImFontBaked() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); FallbackGlyphIndex = -1; } @@ -5151,7 +5151,7 @@ void ImFontBaked::ClearOutputData() ImFont::ImFont() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS Scale = 1.0f; #endif diff --git a/imgui_internal.h b/imgui_internal.h index 7dbe9784e..4c5b4f350 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -708,7 +708,7 @@ struct ImSpanAllocator int Offsets[CHUNKS]; int Sizes[CHUNKS]; - ImSpanAllocator() { memset(this, 0, sizeof(*this)); } + ImSpanAllocator() { memset((void*)this, 0, sizeof(*this)); } inline void Reserve(int n, size_t sz, int a=4) { IM_ASSERT(n == CurrIdx && n < CHUNKS); CurrOff = IM_MEMALIGN(CurrOff, a); Offsets[n] = CurrOff; Sizes[n] = (int)sz; CurrIdx++; CurrOff += (int)sz; } inline int GetArenaSizeInBytes() { return CurrOff; } inline void SetArenaBasePtr(void* base_ptr) { BasePtr = (char*)base_ptr; } @@ -889,7 +889,7 @@ struct ImDrawDataBuilder ImVector* Layers[2]; // Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. ImVector LayerData1; - ImDrawDataBuilder() { memset(this, 0, sizeof(*this)); } + ImDrawDataBuilder() { memset((void*)this, 0, sizeof(*this)); } }; struct ImFontStackData @@ -1164,7 +1164,7 @@ struct IMGUI_API ImGuiComboPreviewData float BackupPrevLineTextBaseOffset; ImGuiLayoutType BackupLayout; - ImGuiComboPreviewData() { memset(this, 0, sizeof(*this)); } + ImGuiComboPreviewData() { memset((void*)this, 0, sizeof(*this)); } }; // Stacked storage data for BeginGroup()/EndGroup() @@ -1198,7 +1198,7 @@ struct IMGUI_API ImGuiMenuColumns ImU16 OffsetMark; ImU16 Widths[4]; // Width of: Icon, Label, Shortcut, Mark (accumulators for current frame) - ImGuiMenuColumns() { memset(this, 0, sizeof(*this)); } + ImGuiMenuColumns() { memset((void*)this, 0, sizeof(*this)); } void Update(float spacing, bool window_reappearing); float DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark); void CalcNextTotalWidth(bool update_offsets); @@ -1210,7 +1210,7 @@ struct IMGUI_API ImGuiInputTextDeactivatedState ImGuiID ID; // widget id owning the text state (which just got deactivated) ImVector TextA; // text buffer - ImGuiInputTextDeactivatedState() { memset(this, 0, sizeof(*this)); } + ImGuiInputTextDeactivatedState() { memset((void*)this, 0, sizeof(*this)); } void ClearFreeMemory() { ID = 0; TextA.clear(); } }; @@ -1336,7 +1336,7 @@ struct ImGuiNextWindowData ImVec2 MenuBarOffsetMinVal; // (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) ImGuiWindowRefreshFlags RefreshFlagsVal; - ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); } + ImGuiNextWindowData() { memset((void*)this, 0, sizeof(*this)); } inline void ClearFlags() { HasFlags = ImGuiNextWindowDataFlags_None; } }; @@ -1368,7 +1368,7 @@ struct ImGuiNextItemData ImGuiID StorageId; // Set by SetNextItemStorageID() ImU32 ColorMarker; // Set by SetNextItemColorMarker(). Not exposed yet, supported by DragScalar,SliderScalar and for ImGuiSliderFlags_ColorMarkers. - ImGuiNextItemData() { memset(this, 0, sizeof(*this)); SelectionUserData = -1; } + ImGuiNextItemData() { memset((void*)this, 0, sizeof(*this)); SelectionUserData = -1; } inline void ClearFlags() { HasFlags = ImGuiNextItemDataFlags_None; ItemFlags = ImGuiItemFlags_None; } // Also cleared manually by ItemAdd()! }; @@ -1385,7 +1385,7 @@ struct ImGuiLastItemData ImRect ClipRect; // Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasClipRect) is set.. ImGuiKeyChord Shortcut; // Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasShortcut) is set.. - ImGuiLastItemData() { memset(this, 0, sizeof(*this)); } + ImGuiLastItemData() { memset((void*)this, 0, sizeof(*this)); } }; // Store data emitted by TreeNode() for usage by TreePop() @@ -1418,7 +1418,7 @@ struct IMGUI_API ImGuiErrorRecoveryState short SizeOfBeginPopupStack; short SizeOfDisabledStack; - ImGuiErrorRecoveryState() { memset(this, 0, sizeof(*this)); } + ImGuiErrorRecoveryState() { memset((void*)this, 0, sizeof(*this)); } }; // Data saved for each window pushed into the stack @@ -1479,7 +1479,7 @@ struct ImGuiPopupData ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup - ImGuiPopupData() { memset(this, 0, sizeof(*this)); ParentNavLayer = OpenFrameCount = -1; } + ImGuiPopupData() { memset((void*)this, 0, sizeof(*this)); ParentNavLayer = OpenFrameCount = -1; } }; //----------------------------------------------------------------------------- @@ -1557,7 +1557,7 @@ struct ImGuiInputEvent }; bool AddedByTestEngine; - ImGuiInputEvent() { memset(this, 0, sizeof(*this)); } + ImGuiInputEvent() { memset((void*)this, 0, sizeof(*this)); } }; // Input function taking an 'ImGuiID owner_id' argument defaults to (ImGuiKeyOwner_Any == 0) aka don't test ownership, which matches legacy behavior. @@ -1672,7 +1672,7 @@ struct ImGuiListClipperData int ItemsFrozen; ImVector Ranges; - ImGuiListClipperData() { memset(this, 0, sizeof(*this)); } + ImGuiListClipperData() { memset((void*)this, 0, sizeof(*this)); } void Reset(ImGuiListClipper* clipper) { ListClipper = clipper; StepNo = ItemsFrozen = 0; Ranges.resize(0); } }; @@ -1807,7 +1807,7 @@ struct IMGUI_API ImGuiTypingSelectState float LastRequestTime = 0.0f; bool SingleCharModeLock = false; // After a certain single char repeat count we lock into SingleCharMode. Two benefits: 1) buffer never fill, 2) we can provide an immediate SingleChar mode without timer elapsing. - ImGuiTypingSelectState() { memset(this, 0, sizeof(*this)); } + ImGuiTypingSelectState() { memset((void*)this, 0, sizeof(*this)); } void Clear() { SearchBuffer[0] = 0; SingleCharModeLock = false; } // We preserve remaining data for easier debugging }; @@ -1843,7 +1843,7 @@ struct ImGuiOldColumnData ImGuiOldColumnFlags Flags; // Not exposed ImRect ClipRect; - ImGuiOldColumnData() { memset(this, 0, sizeof(*this)); } + ImGuiOldColumnData() { memset((void*)this, 0, sizeof(*this)); } }; struct ImGuiOldColumns @@ -1864,7 +1864,7 @@ struct ImGuiOldColumns ImVector Columns; ImDrawListSplitter Splitter; - ImGuiOldColumns() { memset(this, 0, sizeof(*this)); } + ImGuiOldColumns() { memset((void*)this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- @@ -1892,7 +1892,7 @@ struct ImGuiBoxSelectState ImRect BoxSelectRectPrev; // Selection rectangle in absolute coordinates (derived every frame from BoxSelectStartPosRel and MousePos) ImRect BoxSelectRectCurr; - ImGuiBoxSelectState() { memset(this, 0, sizeof(*this)); } + ImGuiBoxSelectState() { memset((void*)this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- @@ -2003,7 +2003,7 @@ struct ImGuiWindowSettings bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) bool WantDelete; // Set to invalidate/delete the settings entry - ImGuiWindowSettings() { memset(this, 0, sizeof(*this)); } + ImGuiWindowSettings() { memset((void*)this, 0, sizeof(*this)); } char* GetName() { return (char*)(this + 1); } }; @@ -2019,7 +2019,7 @@ struct ImGuiSettingsHandler void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' void* UserData; - ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } + ImGuiSettingsHandler() { memset((void*)this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- @@ -2108,7 +2108,7 @@ struct ImGuiDebugAllocInfo ImS16 LastEntriesIdx; // Current index in buffer ImGuiDebugAllocEntry LastEntriesBuf[6]; // Track last 6 frames that had allocations - ImGuiDebugAllocInfo() { memset(this, 0, sizeof(*this)); } + ImGuiDebugAllocInfo() { memset((void*)this, 0, sizeof(*this)); } }; struct ImGuiMetricsConfig @@ -2137,7 +2137,7 @@ struct ImGuiStackLevelInfo ImS8 DataType; // ImGuiDataType int DescOffset; // -1 or offset into parent's ResultsPathsBuf - ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); DataType = -1; DescOffset = -1; } + ImGuiStackLevelInfo() { memset((void*)this, 0, sizeof(*this)); DataType = -1; DescOffset = -1; } }; struct ImGuiDebugItemPathQuery @@ -2150,7 +2150,7 @@ struct ImGuiDebugItemPathQuery ImGuiTextBuffer ResultsDescBuf; ImGuiTextBuffer ResultPathBuf; - ImGuiDebugItemPathQuery() { memset(this, 0, sizeof(*this)); } + ImGuiDebugItemPathQuery() { memset((void*)this, 0, sizeof(*this)); } }; // State for ID Stack tool queries @@ -2161,7 +2161,7 @@ struct ImGuiIDStackTool int LastActiveFrame; float CopyToClipboardLastTime; - ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); LastActiveFrame = -1; OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; } + ImGuiIDStackTool() { memset((void*)this, 0, sizeof(*this)); LastActiveFrame = -1; OptHexEncodeNonAsciiChars = true; CopyToClipboardLastTime = -FLT_MAX; } }; //----------------------------------------------------------------------------- @@ -2179,7 +2179,7 @@ struct ImGuiContextHook ImGuiContextHookCallback Callback; void* UserData; - ImGuiContextHook() { memset(this, 0, sizeof(*this)); } + ImGuiContextHook() { memset((void*)this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- @@ -2806,7 +2806,7 @@ struct ImGuiTabItem 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() - ImGuiTabItem() { memset(this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; } + ImGuiTabItem() { memset((void*)this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; } }; // Storage for a tab bar (sizeof() 160 bytes) @@ -2911,7 +2911,7 @@ struct ImGuiTableColumn ImGuiTableColumn() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); StretchWeight = WidthRequest = -1.0f; NameOffset = -1; DisplayOrder = IndexWithinEnabledSet = -1; @@ -3072,7 +3072,7 @@ struct IMGUI_API ImGuiTable bool MemoryCompacted; bool HostSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis - ImGuiTable() { memset(this, 0, sizeof(*this)); LastFrameActive = -1; } + ImGuiTable() { memset((void*)this, 0, sizeof(*this)); LastFrameActive = -1; } ~ImGuiTable() { IM_FREE(RawData); } }; @@ -3101,7 +3101,7 @@ struct IMGUI_API ImGuiTableTempData 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() - ImGuiTableTempData() { memset(this, 0, sizeof(*this)); LastTimeActive = -1.0f; } + ImGuiTableTempData() { memset((void*)this, 0, sizeof(*this)); LastTimeActive = -1.0f; } }; // sizeof() ~ 16 @@ -3138,7 +3138,7 @@ struct ImGuiTableSettings ImGuiTableColumnIdx ColumnsCountMax; // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) - ImGuiTableSettings() { memset(this, 0, sizeof(*this)); } + ImGuiTableSettings() { memset((void*)this, 0, sizeof(*this)); } ImGuiTableColumnSettings* GetColumnSettings() { return (ImGuiTableColumnSettings*)(this + 1); } }; @@ -3789,7 +3789,7 @@ struct ImFontLoader // FIXME: At this point the two other types of buffers may be managed by core to be consistent? size_t FontBakedSrcLoaderDataSize; - ImFontLoader() { memset(this, 0, sizeof(*this)); } + ImFontLoader() { memset((void*)this, 0, sizeof(*this)); } }; #ifdef IMGUI_ENABLE_STB_TRUETYPE @@ -3886,7 +3886,7 @@ struct ImFontAtlasBuilder ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. ImFontAtlasRectId PackIdLinesTexData; - ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } + ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } }; IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 54ff81bd6..3309aea90 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4251,7 +4251,7 @@ static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* st // We added an extra indirection where 'Stb' is heap-allocated, in order facilitate the work of bindings generators. ImGuiInputTextState::ImGuiInputTextState() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); Stb = IM_NEW(ImStbTexteditState); memset(Stb, 0, sizeof(*Stb)); } @@ -4301,7 +4301,7 @@ void ImGuiInputTextState::ReloadUserBufAndMoveToEnd() { WantReloadUserBuf ImGuiInputTextCallbackData::ImGuiInputTextCallbackData() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); } // Public API to manipulate UTF-8 text from within a callback. @@ -9548,7 +9548,7 @@ struct ImGuiTabBarSection float WidthAfterShrinkMinWidth; float Spacing; // Horizontal spacing at the end of the section. - ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); } + ImGuiTabBarSection() { memset((void*)this, 0, sizeof(*this)); } }; namespace ImGui @@ -9564,7 +9564,7 @@ namespace ImGui ImGuiTabBar::ImGuiTabBar() { - memset(this, 0, sizeof(*this)); + memset((void*)this, 0, sizeof(*this)); CurrFrameVisible = PrevFrameVisible = -1; LastTabItemIdx = -1; } From acdaaef625193f10292e9055cb7c901d186c9500 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 16 Feb 2026 16:45:08 +0100 Subject: [PATCH 1666/2359] Backends: further zealous warning fixes. (#9247) --- backends/imgui_impl_dx12.h | 10 ++++++++++ backends/imgui_impl_vulkan.cpp | 8 ++++++++ backends/imgui_impl_vulkan.h | 10 ++++++++++ 3 files changed, 28 insertions(+) diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 27ede2b21..b8be8db22 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -24,6 +24,12 @@ #include // DXGI_FORMAT #include // D3D12_CPU_DESCRIPTOR_HANDLE +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#endif + // Initialization data, for ImGui_ImplDX12_Init() struct ImGui_ImplDX12_InitInfo { @@ -76,4 +82,8 @@ struct ImGui_ImplDX12_RenderState ID3D12GraphicsCommandList* CommandList; }; +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 8f4bd5a62..c3a304989 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -116,6 +116,14 @@ #pragma warning (disable: 4127) // condition expression is constant #endif +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) +#endif + // Forward Declarations struct ImGui_ImplVulkan_FrameRenderBuffers; struct ImGui_ImplVulkan_WindowRenderBuffers; diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 4ad33b8f3..5b3baf00c 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -50,6 +50,12 @@ //#define IMGUI_IMPL_VULKAN_VOLK_FILENAME // Default // Reminder: make those changes in your imconfig.h file, not here! +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#endif + #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES) #define VK_NO_PROTOTYPES #endif @@ -261,4 +267,8 @@ struct ImGui_ImplVulkanH_Window } }; +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + #endif // #ifndef IMGUI_DISABLE From ff673d31dfe6fe15ed2b1f6767562775f6280c43 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 16 Feb 2026 18:04:07 +0100 Subject: [PATCH 1667/2359] Backends: WebGPU: minor build fix for Emscripten 5.0.0 (note: our examples currently don't build with 5.0.1). Getting 'warning: unused function 'CreateWGPUSurface' [-Wunused-function]' in some build paths. cc #9246 --- backends/imgui_impl_wgpu.h | 9 +++++++++ docs/CHANGELOG.txt | 1 + examples/example_glfw_wgpu/main.cpp | 6 +++--- examples/example_sdl3_wgpu/main.cpp | 4 ++-- 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 7ab3dd31f..522234545 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -33,12 +33,21 @@ // Setup Emscripten default if not specified. #if defined(__EMSCRIPTEN__) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) #include + +#ifdef __EMSCRIPTEN_MAJOR__ +#if (__EMSCRIPTEN_MAJOR__ >= 4) && (__EMSCRIPTEN_MINOR__ >= 0) && (__EMSCRIPTEN_TINY__ >= 10) +#define IMGUI_IMPL_WEBGPU_BACKEND_DAWN +#else +#define IMGUI_IMPL_WEBGPU_BACKEND_WGPU +#endif +#else #if (__EMSCRIPTEN_major__ >= 4) && (__EMSCRIPTEN_minor__ >= 0) && (__EMSCRIPTEN_tiny__ >= 10) #define IMGUI_IMPL_WEBGPU_BACKEND_DAWN #else #define IMGUI_IMPL_WEBGPU_BACKEND_WGPU #endif #endif +#endif #include #if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) && !defined(__EMSCRIPTEN__) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 46c23c68d..19a9e720c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -259,6 +259,7 @@ Other Changes: selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on `cap.supportedCompositeAlpha`, which seems to be required on some Android devices. (#8784) [@FelixStach] + - WebGPU: fixes for Emscripten 5.0.0 (note: our examples currently don't build with 5.0.1). - Win32: handle `WM_IME_CHAR`/`WM_IME_COMPOSITION` to support Unicode inputs on MBCS (non-Unicode) Windows. (#9099, #3653, #5961) [@ulhc, @ocornut, @Othereum] - Win32: minor optimization not submitting gamepad input if packet number has not diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 7c293a51c..1a6373c8a 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -40,8 +40,8 @@ static int wgpu_surface_width = 1280; static int wgpu_surface_height = 800; // Forward declarations -static bool InitWGPU(GLFWwindow* window); -static WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, GLFWwindow* window); +static bool InitWGPU(GLFWwindow* window); +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, GLFWwindow* window); static void glfw_error_callback(int error, const char* description) { @@ -408,7 +408,7 @@ static WGPUDevice RequestDevice(WGPUAdapter& adapter) #endif // __EMSCRIPTEN__ #endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU -static bool InitWGPU(GLFWwindow* window) +bool InitWGPU(GLFWwindow* window) { WGPUTextureFormat preferred_fmt = WGPUTextureFormat_Undefined; // acquired from SurfaceCapabilities diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index adf4524a5..c02a5be9c 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -40,8 +40,8 @@ static int wgpu_surface_width = 1280; static int wgpu_surface_height = 800; // Forward declarations -static bool InitWGPU(SDL_Window* window); -static WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window); +static bool InitWGPU(SDL_Window* window); +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window); static void ResizeSurface(int width, int height) { From 7609963448f673c55a247c5f77e53eb15b142bfa Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Feb 2026 17:25:00 +0100 Subject: [PATCH 1668/2359] Demo: fixes for Emscripten 5.0+ --- imgui_demo.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7ab820573..ab79c8c5f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -141,7 +141,7 @@ Index of this file: #include // PRId64/PRIu64, not avail in some MinGW headers. #endif #ifdef __EMSCRIPTEN__ -#include // __EMSCRIPTEN_major__ etc. +#include // __EMSCRIPTEN_MAJOR__ etc. #endif // Visual Studio warnings @@ -8239,8 +8239,12 @@ void ImGui::ShowAboutWindow(bool* p_open) #endif #ifdef __EMSCRIPTEN__ ImGui::Text("define: __EMSCRIPTEN__"); +#ifdef __EMSCRIPTEN_MAJOR__ + ImGui::Text("Emscripten: %d.%d.%d", __EMSCRIPTEN_MAJOR__, __EMSCRIPTEN_MINOR__, __EMSCRIPTEN_TINY__); +#else ImGui::Text("Emscripten: %d.%d.%d", __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__); #endif +#endif #ifdef NDEBUG ImGui::Text("define: NDEBUG"); #endif From f921abe7e7af4ff51a1f5c036ad413643f89cb78 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Feb 2026 17:44:04 +0100 Subject: [PATCH 1669/2359] InputTextMultiline(): fixed a minor bug where Shift+Wheel would allow a small horizontal scroll offset. (#9249) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 7 +++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 19a9e720c..4967e462a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -168,6 +168,8 @@ Other Changes: next to each components, in multi-components functions. - Added a way to select a specific marker color. - InputText: + - InputTextMultiline(): fixed a minor bug where Shift+Wheel would allow a small + horizontal scroll offset when there should be none. (#9249) - ImGuiInputTextCallbackData: SelectAll() also sets CursorPos to SelectionEnd. - ImGuiInputTextCallbackData: Added SetSelection() helper. - ImGuiInputTextCallbackData: Added ID and EventActive helpers. (#9174) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3309aea90..9fb5c2fc5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5400,7 +5400,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; - ImVec2 text_size(0.0f, 0.0f); ImRect clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size if (is_multiline) clip_rect.ClipWith(draw_window->ClipRect); @@ -5458,7 +5457,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ line_visible_n1 = ImMin(line_visible_n1, line_count); // Store text height (we don't need width) - text_size = ImVec2(inner_size.x, line_count * g.FontSize); + float text_size_y = line_count * g.FontSize; //GetForegroundDrawList()->AddRect(draw_pos + ImVec2(0, line_visible_n0 * g.FontSize), draw_pos + ImVec2(frame_size.x, line_visible_n1 * g.FontSize), IM_COL32(255, 0, 0, 255)); // Calculate blinking cursor position @@ -5518,7 +5517,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } if (new_scroll_y != scroll_y) { - const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); + const float scroll_max_y = ImMax((text_size_y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); scroll_y = ImClamp(new_scroll_y, 0.0f, scroll_max_y); draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag draw_window->Scroll.y = scroll_y; @@ -5611,7 +5610,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_multiline) { // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)... - Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y)); + Dummy(ImVec2(0.0f, text_size_y + style.FramePadding.y)); g.NextItemData.ItemFlags |= (ImGuiItemFlags)ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop; EndChild(); item_data_backup.StatusFlags |= (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredWindow); From e118ea06e0b7cbed940bd0a4694a3fcfe3695272 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Feb 2026 17:45:07 +0100 Subject: [PATCH 1670/2359] Version 1.92.6 --- docs/CHANGELOG.txt | 146 +++++++++++++++++++++++---------------------- docs/FONTS.md | 8 +-- imgui.cpp | 11 ++-- imgui.h | 7 ++- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 9 files changed, 95 insertions(+), 87 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4967e462a..f63c073aa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,35 +36,24 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.92.6 WIP (In Progress) + VERSION 1.92.6 (2026-02-17) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.92.6 + Breaking Changes: -- Commented out legacy names obsoleted in 1.90 (Sept 2023): - - BeginChildFrame() --> BeginChild() with ImGuiChildFlags_FrameStyle flag. - - EndChildFrame() --> EndChild(). - - ShowStackToolWindow() --> ShowIDStackToolWindow(). - - IM_OFFSETOF() --> offsetof(). - - IM_FLOOR() --> IM_TRUNC() [internal, for positive values only] -- Hashing: handling of "###" operator to reset to seed within a string identifier - doesn't include the "###" characters in the output hash anymore: - Before: GetID("Hello###World") == GetID("###World") != GetID("World"); - Now: GetID("Hello###World") == GetID("###World") == GetID("World"); - - This has the property of facilitating concatenating and manipulating - identifiers using "###", and will allow fixing other dangling issues. - - This will invalidate hashes (stored in .ini data) for Tables and Windows - that are using the "###" operators. (#713, #1698) -- Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name. - Fonts: - AddFontDefault() now automatically selects an embedded font between: - - AddFontDefaultVector(): new scalable font. Recommended at any higher size. - AddFontDefaultBitmap(): classic pixel-clean font. Recommended at Size 13px with no scaling. + - AddFontDefaultVector(): new scalable font. Recommended at any higher size. - The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) - reaching a small threshold. Prefer calling either based on your own logic. - And you can call AddFontDefaultBitmap() to ensure legacy behavior. - - Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which - did erroneously make a copy of the font data, essentially defeating the purpose + reaching a small threshold, but old codebases may not set any of them properly. + As as a result, it is likely that old codebase may still default to AddFontDefaultBitmap(). + - Prefer explicitly calling either of them based on your own logic! + You can call AddFontDefaultBitmap() to ensure legacy behavior. + - Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did + erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory (undetected since July 2015 and now spotted by @TellowKrinkle, this is perhaps the oldest bug in Dear ImGui history, albeit for a rarely used feature!) (#9086, #8465) @@ -74,13 +63,8 @@ Breaking Changes: until a shutdown of the owning context or font atlas. - The fact that handling of `FontDataOwnedByAtlas = false` was broken bypassed the issue altogether. - - Fixed a crash when trying to use AddFont() with MergeMode=true on a font that - has already been rendered. (#9162) [@ocornut, @cyfewlp] - Removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. - - Fixed an issue where using PushFont() from the implicit/fallback "Debug" window when - its recorded state is collapsed would incorrectly early out. This would break e.g. using - direct draw-list calls such as GetForegroundDrawList() with current font. (#9210, #8865) - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). The default value has same meaning before and after. (#9157, #9146) @@ -91,8 +75,8 @@ Breaking Changes: - We have now changed this behavior to: cleanup a very old API quirk, facilitate use by bindings, and to remove the last and error-prone non-zero default value. Also because we deemed it extremely rare to use those helper functions with the Left mouse button! - As using the LMB would generally be triggered via another widget, e.g. a Button() + - a OpenPopup()/BeginPopup() call. + As using the LMB would generally be triggered via another widget, + e.g. a Button() + a OpenPopup()/BeginPopup() call. - Before: The default = 1 means ImGuiPopupFlags_MouseButtonRight. Explicitly passing a literal 0 means ImGuiPopupFlags_MouseButtonLeft. - After: The default = 0 means ImGuiPopupFlags_MouseButtonRight. @@ -108,6 +92,21 @@ Breaking Changes: - BeginPopupContextItem("foo", 1); // Behavior unchanged (as a courtesy we legacy interpret 1 as ImGuiPopupFlags_MouseButtonRight, will assert if disabling legacy behaviors. - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft. - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx. +- Commented out legacy names obsoleted in 1.90 (Sept 2023): + - BeginChildFrame() --> BeginChild() with ImGuiChildFlags_FrameStyle flag. + - EndChildFrame() --> EndChild(). + - ShowStackToolWindow() --> ShowIDStackToolWindow(). + - IM_OFFSETOF() --> offsetof(). + - IM_FLOOR() --> IM_TRUNC() [internal, for positive values only] +- Hashing: handling of "###" operator to reset to seed within a string identifier + doesn't include the "###" characters in the output hash anymore: + Before: `GetID("Hello###World") == GetID("###World") != GetID("World")` + After: `GetID("Hello###World") == GetID("###World") == GetID("World")` + - This has the property of facilitating concatenating and manipulating + identifiers using "###", and will allow fixing other dangling issues. + - This will invalidate hashes (stored in .ini data) for Tables and Windows + that are using the "###" operators. (#713, #1698) +- Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name. - Backends: - Vulkan: optional ImGui_ImplVulkanH_DestroyWindow() helper used by our example code does not call vkDestroySurfaceKHR(): because surface is created by caller @@ -116,7 +115,7 @@ Breaking Changes: Other Changes: - Fonts: - - Added AddFontDefaultVector(): a new embedded monospace scalable font: ProggyForever! + - Added `AddFontDefaultVector()`: a new embedded monospace scalable font: ProggyForever! From https://github.com/ocornut/proggyforever: "ProggyForever is an MIT-licensed partial reimplementation of the ProggyVector font (originally by Tristan Grimmer), which itself is a vector-based @@ -130,27 +129,33 @@ Other Changes: data is ~14 KB. Embedding a scalable default font ensures that Dear ImGui can be easily and readily used in all contexts, even without file system access. - As always you can opt-out of the embedded font data if desired. - - AddFontDefault() now automatically selects an embedded font between + - `AddFontDefault()` now automatically selects an embedded font between the classic pixel-looking one and the new scalable one. - Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() explicitely. - - Fixed an issue related to EllipsisChar handling, while changing + Prefer calling `AddFontDefaultVector()` or `AddFontDefaultBitmap()` explicitely. + - Fixed a crash when trying to use `AddFont()` with `MergeMode==true` on a font that + has already been rendered. (#9162) [@ocornut, @cyfewlp] + - Fixed an issue where using `PushFont()` from the implicit/fallback "Debug" window + when its recorded state is collapsed would incorrectly early out. This would break + e.g. using direct draw-list calls such as GetForegroundDrawList() with current font. + (#9210, #8865) + - Fixed an issue related to `EllipsisChar` handling, while changing font loader or font loader flags dynamically in Style->Fonts menus. - - imgui_freetype: fixed overwriting ImFontConfig::PixelSnapH when hinting + - imgui_freetype: fixed overwriting `ImFontConfig::PixelSnapH` when hinting is enabled, creating side-effects when later disabling hinting or dynamically switching to stb_truetype rasterizer. - - Post rescale GlyphOffset is always rounded. + - Post rescale `ImFontConfig::GlyphOffset` is always rounded. - Adding new fonts after removing all fonts mid-frame properly updates current state. - Textures: - - Fixed a building issue when ImTextureID is defined as a struct. + - Fixed a building issue when `ImTextureID` is defined as a struct. - Fixed displaying texture # in Metrics/Debugger window. - Menus: - - Fixed MenuItem() label position and BeginMenu() arrow/icon/popup positions, + - Fixed `MenuItem()` label position and `BeginMenu()` arrow/icon/popup positions, when used inside a line with a baseline offset. - Made navigation into menu-bar auto wrap on X axis. (#9178) - TreeNode: - Fixed highlight position when used inside a line with a large text baseline offset. (never quite worked in this situation; but then most of the time the text - baseline offset ends up being zero or FramePadding.y for a given line). + baseline offset ends up being zero or `FramePadding.y` for a given line). - Tables: - Fixed an issue where a very thin scrolling table would advance parent layout slightly differently depending on its visibility (caused by a mismatch @@ -161,70 +166,71 @@ Other Changes: data has missing or duplicate values. (#9108, #4046) - ColorEdit: - Added R/G/B/A color markers next to each component (enabled by default). - - Added ImGuiColorEditFlags_NoColorMarkers to disable them. - - Added style.ColorMarkerSize to configure width of color component markers. + - Added `ImGuiColorEditFlags_NoColorMarkers` to disable them. + - Added `style.ColorMarkerSize` to configure width of color component markers. - Sliders, Drags: - - Added ImGuiSliderFlags_ColorMarkers to opt-in adding R/G/B/A color markers + - Added `ImGuiSliderFlags_ColorMarkers` to opt-in adding R/G/B/A color markers next to each components, in multi-components functions. - Added a way to select a specific marker color. - InputText: - InputTextMultiline(): fixed a minor bug where Shift+Wheel would allow a small horizontal scroll offset when there should be none. (#9249) - - ImGuiInputTextCallbackData: SelectAll() also sets CursorPos to SelectionEnd. - - ImGuiInputTextCallbackData: Added SetSelection() helper. - - ImGuiInputTextCallbackData: Added ID and EventActive helpers. (#9174) + - ImGuiInputTextCallbackData: `SelectAll()` also sets `CursorPos` to `SelectionEnd`. + - ImGuiInputTextCallbackData: Added `SetSelection()` helper. + - ImGuiInputTextCallbackData: Added `ID` and `EventActivated` members. (#9174) - Text, InputText: - Reworked word-wrapping logic: - Try to not wrap in the middle of contiguous punctuations. (#8139, #8439, #9094) - Try to not wrap between a punctuation and a digit. (#8503) - - Inside InputTextMultiline() with _WordWrap: prefer keeping blanks at the - end of a line rather than at the beginning of next line. (#8990, #3237) - - Fixed low-level word-wrapping function reading from *text_end when passed + - Inside `InputTextMultiline()` with WordWrap enabled: prefer keeping blanks at + the end of a line rather than at the beginning of next line. (#8990, #3237) + - Fixed low-level word-wrapping function reading from `*text_end` when passed a string range. (#9107) [@achabense] - - Changed RenderTextEllipsis() logic to not trim trailing blanks before + - Changed `RenderTextEllipsis()` logic to not trim trailing blanks before the ellipsis, making ellipsis position more consistent and not arbitrary hiding the possibility of multiple blanks. (#9229) - Nav: - Fixed remote/shortcut InputText() not teleporting mouse cursor when nav cursor is visible and `io.ConfigNavMoveSetMousePos` is enabled. - - Fixed a looping/wrapping issue when done in menu layer. (#9178) + - Fixed a looping/wrapping issue when used in menu layer. (#9178) - Fixed speed scale for resizing/moving with keyboard/gamepad. We incorrectly - used io.DisplayFramebufferScale (very old code), effectively making those - actions faster on macOS/iOS retina screens. + used `io.DisplayFramebufferScale` as a scaling factor (very old code), + effectively making those actions faster on macOS/iOS retina screens. (changed this to use a style scale factor that's not fully formalized yet) - - Fixed an UBSan warning when using in a ListClipper region . (#9160) + - Fixed an UBSan warning when using in a `ImGuiListClipper` region . (#9160) - Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - InvisibleButton: allow calling with size (0,0) to fit to available content size. (#9166, #7623) -- Tooltips, Disabled: fixed EndDisabledOverrideReenable() assertion when +- Tooltips, Disabled: fixed `EndDisabledOverrideReenable()` assertion when nesting a tooltip in a disabled block. (#9180, #7640) [@RegimantasSimkus] -- Added GetItemFlags() in public API for consistency and to expose generic +- Added `GetItemFlags()` in public API for consistency and to expose generic flags of last submitted item. (#9127) -- Log/Capture: fixed erroneously injecting extra carriage returns in output - buffer when ItemSpacing.y > FramePadding.y + 1. - Misc: fixed build on ARM64/ARM64EC targets trying to use SSE/immintrin.h. (#9209, #5943, #4091) [@navvyswethgraphics] +- Log/Capture: + - Fixed erroneously injecting extra carriage returns in output text buffer + when `ItemSpacing.y` > `FramePadding.y + 1` while emitting items. - Images: - - Added style.ImageRounding, ImGuiStyleVar_ImageRounding to configure - rounding of Image() widgets. (#2942, #845) - - ImageButton() doesn't use a clamped style.FrameRounding value but instead - adjust inner image rounding when FramePadding > FrameRounding. (#2942, #845) + - Added `style.ImageRounding`, `ImGuiStyleVar_ImageRounding `to configure + rounding of `Image()` widgets. (#2942, #845) + - `ImageButton()` doesn't use a clamped `style.FrameRounding` value but instead + adjust inner image rounding when `FramePadding > `FrameRounding`. (#2942, #845) - Shortcuts: - - IsItemHovered() without ImGuiHoveredFlags_AllowWhenBlockedByActiveItem + - IsItemHovered() without `ImGuiHoveredFlags_AllowWhenBlockedByActiveItem` doesn't filter out the signal when activated item is a shortcut remote activation; - (which mimicks what's done internally in the ItemHoverable() function). (#9138) + (which mimicks what's done internally in the `ItemHoverable()` function). (#9138) - Fixed tooltip placement being affected for a frame when located over an item - activated by SetNextItemShortcut(). (#9138) + activated by `SetNextItemShortcut()`. (#9138) - Error Handling: - - Improve error handling and recovery for EndMenu()/EndCombo(). (#1651, #9165, #8499) - - Improve error handling and recovery for TableSetupColumn(). + - Improved error handling and recovery for `EndMenu()`/`EndCombo()`. (#1651, #9165, #8499) + - Improved error handling and recovery for `TableSetupColumn()`. - Debug Tools: - Debug Log: fixed incorrectly printing characters in IO log when submitting non-ASCII values to `io.AddInputCharacter()`. (#9099) - - Debug Log: can output to debugger on Windows. (#5855) + - Debug Log: can output to debugger on Windows via Win32 `OutputDebugString()` (#5855) - Demo: - - Slightly improve Selectable() demos. (#9193) + - Slightly improve `Selectable()` demos. (#9193) - Backends: - DirectX10: added `SamplerNearest` in `ImGui_ImplDX10_RenderState`. (+renamed `SamplerDefault` to `SamplerLinear`, which was tagged as beta API) @@ -232,7 +238,7 @@ Other Changes: (+renamed `SamplerDefault` to `SamplerLinear`, which was tagged as beta API) - GLFW: Avoid repeated `glfwSetCursor()` / `glfwSetInputMode()` unnecessary calls. Lowers overhead for very high framerates (e.g. 10k+ FPS). [@maxliani] - - GLFW: Added IMGUI_IMPL_GLFW_DISABLE_X11 / IMGUI_IMPL_GLFW_DISABLE_WAYLAND to + - GLFW: Added `IMGUI_IMPL_GLFW_DISABLE_X11` / `IMGUI_IMPL_GLFW_DISABLE_WAYLAND` to forcefully disable either. (#9109, #9116) Try to set them automatically if headers are not accessible. (#9225) - OpenGL3: Fixed embedded loader multiple init/shutdown cycles broken on some @@ -244,14 +250,14 @@ Other Changes: but a better default for X11 users). Waiting for a drag to start mouse capture leads to input drops when dragging after clicking on the edge of a window. (#3650, #6410, #9235, #3956, #3835) - - SDL2, SDL3: added ImGui_ImplSDL2_SetMouseCaptureMode()/ImGui_ImplSDL3_SetMouseCaptureMode() + - SDL2, SDL3: added `ImGui_ImplSDL2_SetMouseCaptureMode()`/`ImGui_ImplSDL3_SetMouseCaptureMode()` function for X11 users to disable mouse capturing/grabbing. (#3650, #6410, #9235, #3956, #3835) - When attached to a debugger may want to call: - `ImGui_ImplSDL3_SetMouseCaptureMode(ImGui_ImplSDL3_MouseCaptureMode_Disabled);` - But you can also configure your system or debugger to automatically release mouse grab when crashing/breaking in debugger, e.g. - console: `setxkbmap -option grab:break_actions && xdotool key XF86Ungrab` - - or use a GDB script to capture SDL_CaptureMouse(false). See #3650. + - or use a GDB script to call SDL_CaptureMouse(false). See #3650. - On platforms other than X11 this is unnecessary. - SDL_GPU3: added `SamplerNearest` in `ImGui_ImplSDLGPU3_RenderState`. - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ @@ -261,7 +267,7 @@ Other Changes: selects `VkSwapchainCreateInfoKHR`'s `compositeAlpha` value based on `cap.supportedCompositeAlpha`, which seems to be required on some Android devices. (#8784) [@FelixStach] - - WebGPU: fixes for Emscripten 5.0.0 (note: our examples currently don't build with 5.0.1). + - WebGPU: fixes for Emscripten 5.0.0 (note: current examples do not build with 5.0.1). - Win32: handle `WM_IME_CHAR`/`WM_IME_COMPOSITION` to support Unicode inputs on MBCS (non-Unicode) Windows. (#9099, #3653, #5961) [@ulhc, @ocornut, @Othereum] - Win32: minor optimization not submitting gamepad input if packet number has not diff --git a/docs/FONTS.md b/docs/FONTS.md index 1eeaefd2d..1e51cde48 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -11,8 +11,8 @@ a new font mimicking ProggyClean which does scale nicely. We embed fonts in the code so you can use Dear ImGui without any file system access. If you don't use them you can set `IMGUI_DISABLE_DEFAULT_FONT` in your [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) file to ship binaries without the fonts and save about ~26 KB. -Calling io.Fonts->AddFontDefaultBitmap() loads ProggyClean. Calling io.Fonts->AddFontDefaultVector() loads ProggyForever. +Calling io.Fonts->AddFontDefaultBitmap() loads ProggyClean. Calling io.Fonts->AddFontDefault() selects one based on the expected default font size (when `style.FontSizeBase * style.FontScaleMain * style.FontSizeDpi >= 15` we use ProggyForever). You may also load external .TTF/.OTF files, see instructions on this page. @@ -170,7 +170,7 @@ ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); 🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary.** ```cpp // Load a first font -ImFont* font = io.Fonts->AddFontDefault(); +ImFont* font = io.Fonts->AddFontDefaultVector(); ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 0.0f, &config); // Merge into first font to add e.g. Asian characters @@ -294,7 +294,7 @@ Example Setup: // Merge icons into default tool font #include "IconsFontAwesome.h" ImGuiIO& io = ImGui::GetIO(); -io.Fonts->AddFontDefault(); +io.Fonts->AddFontDefaultVector(); ImFontConfig config; config.MergeMode = true; config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced @@ -451,7 +451,7 @@ As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiF #### Pseudo-code: ```cpp // Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font -ImFont* font = io.Fonts->AddFontDefault(); +ImFont* font = io.Fonts->AddFontDefaultVector(); int rect_ids[2]; rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1); rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1); diff --git a/imgui.cpp b/imgui.cpp index eb8160a79..93cff908c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 WIP +// dear imgui, v1.92.6 // (main code and documentation) // Help: @@ -413,13 +413,14 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - BeginPopupContextItem("foo", 1); // Behavior unchanged (as a courtesy we legacy interpret 1 as ImGuiPopupFlags_MouseButtonRight, will assert if disabling legacy behaviors. - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft. - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx. - - 2025/12/23 (1.92.6) - Fonts:AddFontDefault() now automatically selects an embedded font between the new scalable AddFontDefaultVector() and the classic pixel-clean AddFontDefaultBitmap(). - The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) reaching a small threshold. Prefer calling either based on your own logic. You can call AddFontDefaultBitmap() to ensure legacy behavior. + - 2025/12/23 (1.92.6) - Fonts: AddFontDefault() now automatically selects an embedded font between the new scalable AddFontDefaultVector() and the classic pixel-clean AddFontDefaultBitmap(). + The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) reaching a small threshold, but old codebases may not set any of them properly. As as a result, it is likely that old codebase may still default to AddFontDefaultBitmap(). + Prefer calling either based on your own logic. You can call AddFontDefaultBitmap() to ensure legacy behavior. - 2025/12/23 (1.92.6) - Fonts: removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary (and misdocumented). Post-rescale GlyphOffset is always rounded. - 2025/12/17 (1.92.6) - Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name for now. - 2025/12/11 (1.92.6) - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore. - - Before: GetID("Hello###World") == GetID("###World") != GetID("World"); - - Now: GetID("Hello###World") == GetID("###World") == GetID("World"); + - Before: GetID("Hello###World") == GetID("###World") != GetID("World") + - After: GetID("Hello###World") == GetID("###World") == GetID("World") - This has the property of facilitating concatenating and manipulating identifiers using "###", and will allow fixing other dangling issues. - This will invalidate hashes (stored in .ini data) for Tables and Windows that are using the "###" operators. (#713, #1698) - 2025/11/24 (1.92.6) - Fonts: Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory. diff --git a/imgui.h b/imgui.h index 402e1a3da..e3edac89c 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 WIP +// dear imgui, v1.92.6 // (headers) // Help: @@ -29,8 +29,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.6 WIP" -#define IMGUI_VERSION_NUM 19260 +#define IMGUI_VERSION "1.92.6" +#define IMGUI_VERSION_NUM 19261 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -4043,6 +4043,7 @@ namespace ImGui inline void PopButtonRepeat() { PopItemFlag(); } inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } inline void PopTabStop() { PopItemFlag(); } + // You do not need those functions! See #7838 on GitHub for more info. IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ab79c8c5f..c0c4de946 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 WIP +// dear imgui, v1.92.6 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 312c04c28..20a24a9e6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 WIP +// dear imgui, v1.92.6 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 4c5b4f350..c57457595 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 WIP +// dear imgui, v1.92.6 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 6eaa973af..8df32585b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 WIP +// dear imgui, v1.92.6 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9fb5c2fc5..23a75aa8c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 WIP +// dear imgui, v1.92.6 // (widgets code) /* From 6ded5230d043aa32c755e65c910c2af5002fb9f9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 17 Feb 2026 18:21:37 +0100 Subject: [PATCH 1671/2359] Changelog formatting amends --- docs/CHANGELOG.txt | 68 +++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f63c073aa..3098743cd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,46 +44,46 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v Breaking Changes: - Fonts: - - AddFontDefault() now automatically selects an embedded font between: - - AddFontDefaultBitmap(): classic pixel-clean font. Recommended at Size 13px with no scaling. - - AddFontDefaultVector(): new scalable font. Recommended at any higher size. + - `AddFontDefault()` now automatically selects an embedded font between: + - `AddFontDefaultBitmap()`: classic pixel-clean font. Recommended at Size 13px with no scaling. + - `AddFontDefaultVector()`: new scalable font. Recommended at any higher size. - The default selection is based on (style.FontSizeBase * FontScaleMain * FontScaleDpi) reaching a small threshold, but old codebases may not set any of them properly. As as a result, it is likely that old codebase may still default to AddFontDefaultBitmap(). - Prefer explicitly calling either of them based on your own logic! - You can call AddFontDefaultBitmap() to ensure legacy behavior. + You can call `AddFontDefaultBitmap()` to ensure legacy behavior. - Fixed handling of `ImFontConfig::FontDataOwnedByAtlas = false` which did erroneously make a copy of the font data, essentially defeating the purpose of this flag and wasting memory (undetected since July 2015 and now spotted by @TellowKrinkle, this is perhaps the oldest bug in Dear ImGui history, albeit for a rarely used feature!) (#9086, #8465) HOWEVER, fixing this bug is likely to surface bugs in user/app code: - - Prior to 1.92, font data only needs to be available during the atlas->AddFontXXX() call. - Since 1.92, font data needs to available until atlas->RemoveFont(), or more typically + - Prior to 1.92, font data only needs to be available during the `atlas->AddFontXXX()` call. + Since 1.92, font data needs to available until `atlas->RemoveFont()`, or more typically until a shutdown of the owning context or font atlas. - The fact that handling of `FontDataOwnedByAtlas = false` was broken bypassed the issue altogether. - - Removed ImFontConfig::PixelSnapV added in 1.92 which turns out is unnecessary - (and misdocumented). Post-rescale GlyphOffset is always rounded. - - Popups: changed compile-time 'ImGuiPopupFlags popup_flags = 1' default value to be '= 0' for - BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid(), OpenPopupOnItemClick(). + - Removed `ImFontConfig::PixelSnapV` added in 1.92 which turns out is unnecessary + (and was mis-documented). Post-rescale `GlyphOffset` is always rounded. + - Popups: changed compile-time `ImGuiPopupFlags popup_flags = 1` default value to be `= 0` for + `BeginPopupContextItem()`, `BeginPopupContextWindow()`, `BeginPopupContextVoid()`, `OpenPopupOnItemClick()`. The default value has same meaning before and after. (#9157, #9146) - - Before this version, those functions had a 'ImGuiPopupFlags popup_flags = 1' default + - Before this version, those functions had a `ImGuiPopupFlags popup_flags = 1` default value in their function signature. This was introduced by a change on 2020/06/23 (1.77) - while changing the signature from 'int mouse_button' to 'ImGuiPopupFlags popup_flags' + while changing the signature from `int mouse_button` to `ImGuiPopupFlags popup_flags` and trying to preserve then-legacy behavior. - We have now changed this behavior to: cleanup a very old API quirk, facilitate use by bindings, and to remove the last and error-prone non-zero default value. Also because we deemed it extremely rare to use those helper functions with the Left mouse button! As using the LMB would generally be triggered via another widget, e.g. a Button() + a OpenPopup()/BeginPopup() call. - - Before: The default = 1 means ImGuiPopupFlags_MouseButtonRight. - Explicitly passing a literal 0 means ImGuiPopupFlags_MouseButtonLeft. - - After: The default = 0 means ImGuiPopupFlags_MouseButtonRight. - Explicitly passing a literal 1 also means ImGuiPopupFlags_MouseButtonRight + - Before: The default = 1 means `ImGuiPopupFlags_MouseButtonRight`. + Explicitly passing a literal 0 means `ImGuiPopupFlags_MouseButtonLeft`. + - 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. + explicitly using a named `ImGuiPopupFlags_MouseButtonXXXX` value. Recap: - BeginPopupContextItem("foo"); // Behavior unchanged (use Right button) - BeginPopupContextItem("foo", ImGuiPopupFlags_MouseButtonLeft); // Behavior unchanged (use Left button) @@ -93,11 +93,11 @@ Breaking Changes: - BeginPopupContextItem("foo", 0); // !! Behavior changed !! Was Left button. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft. - BeginPopupContextItem("foo", ImGuiPopupFlags_NoReopen); // !! Behavior changed !! Was Left button + flags. Now will defaults to Right button! --> Use ImGuiPopupFlags_MouseButtonLeft | xxx. - Commented out legacy names obsoleted in 1.90 (Sept 2023): - - BeginChildFrame() --> BeginChild() with ImGuiChildFlags_FrameStyle flag. - - EndChildFrame() --> EndChild(). - - ShowStackToolWindow() --> ShowIDStackToolWindow(). - - IM_OFFSETOF() --> offsetof(). - - IM_FLOOR() --> IM_TRUNC() [internal, for positive values only] + - `BeginChildFrame()` --> `BeginChild()` with `ImGuiChildFlags_FrameStyle` flag. + - `EndChildFrame()` --> `EndChild()`. + - `ShowStackToolWindow()` --> `ShowIDStackToolWindow()`. + - `IM_OFFSETOF()` --> `offsetof()`. + - `IM_FLOOR()` --> `IM_TRUNC()` [internal, for positive values only] - Hashing: handling of "###" operator to reset to seed within a string identifier doesn't include the "###" characters in the output hash anymore: Before: `GetID("Hello###World") == GetID("###World") != GetID("World")` @@ -106,11 +106,11 @@ Breaking Changes: identifiers using "###", and will allow fixing other dangling issues. - This will invalidate hashes (stored in .ini data) for Tables and Windows that are using the "###" operators. (#713, #1698) -- Renamed helper macro IM_ARRAYSIZE() -> IM_COUNTOF(). Kept redirection/legacy name. +- Renamed helper macro `IM_ARRAYSIZE()` -> `IM_COUNTOF()`. Kept redirection/legacy name. - Backends: - - Vulkan: optional ImGui_ImplVulkanH_DestroyWindow() helper used by our example - code does not call vkDestroySurfaceKHR(): because surface is created by caller - of ImGui_ImplVulkanH_CreateOrResizeWindow(), it is more consistent. (#9163) + - Vulkan: optional `ImGui_ImplVulkanH_DestroyWindow()` helper used by our example + code does not call `vkDestroySurfaceKHR()`: because surface is created by caller + of `ImGui_ImplVulkanH_CreateOrResizeWindow()`, it is more consistent. (#9163) Other Changes: @@ -128,22 +128,22 @@ Other Changes: - The font data was carefully subsetted, trimmed and compressed so the embedded data is ~14 KB. Embedding a scalable default font ensures that Dear ImGui can be easily and readily used in all contexts, even without file system access. + - Expect minor fixes/improvements in following releases. - As always you can opt-out of the embedded font data if desired. - `AddFontDefault()` now automatically selects an embedded font between the classic pixel-looking one and the new scalable one. - Prefer calling `AddFontDefaultVector()` or `AddFontDefaultBitmap()` explicitely. + Prefer calling `AddFontDefaultVector()` or `AddFontDefaultBitmap()` explicitly. - Fixed a crash when trying to use `AddFont()` with `MergeMode==true` on a font that has already been rendered. (#9162) [@ocornut, @cyfewlp] - Fixed an issue where using `PushFont()` from the implicit/fallback "Debug" window when its recorded state is collapsed would incorrectly early out. This would break - e.g. using direct draw-list calls such as GetForegroundDrawList() with current font. + e.g. using direct draw-list calls such as `GetForegroundDrawList()` with current font. (#9210, #8865) - Fixed an issue related to `EllipsisChar` handling, while changing font loader or font loader flags dynamically in Style->Fonts menus. - imgui_freetype: fixed overwriting `ImFontConfig::PixelSnapH` when hinting is enabled, creating side-effects when later disabling hinting or dynamically switching to stb_truetype rasterizer. - - Post rescale `ImFontConfig::GlyphOffset` is always rounded. - Adding new fonts after removing all fonts mid-frame properly updates current state. - Textures: - Fixed a building issue when `ImTextureID` is defined as a struct. @@ -154,7 +154,7 @@ Other Changes: - Made navigation into menu-bar auto wrap on X axis. (#9178) - TreeNode: - Fixed highlight position when used inside a line with a large text baseline offset. - (never quite worked in this situation; but then most of the time the text + (it never quite worked in this situation; but then most of the time the text baseline offset ends up being zero or `FramePadding.y` for a given line). - Tables: - Fixed an issue where a very thin scrolling table would advance parent layout @@ -180,7 +180,7 @@ Other Changes: - ImGuiInputTextCallbackData: Added `ID` and `EventActivated` members. (#9174) - Text, InputText: - Reworked word-wrapping logic: - - Try to not wrap in the middle of contiguous punctuations. (#8139, #8439, #9094) + - Try to not wrap in the middle of contiguous punctuation. (#8139, #8439, #9094) - Try to not wrap between a punctuation and a digit. (#8503) - Inside `InputTextMultiline()` with WordWrap enabled: prefer keeping blanks at the end of a line rather than at the beginning of next line. (#8990, #3237) @@ -198,7 +198,7 @@ Other Changes: effectively making those actions faster on macOS/iOS retina screens. (changed this to use a style scale factor that's not fully formalized yet) - Fixed an UBSan warning when using in a `ImGuiListClipper` region . (#9160) -- Scrollbar: fixed a codepath leading to a divide-by-zero (which would not be +- Scrollbar: fixed a code-path leading to a divide-by-zero (which would not be noticeable by user but detected by sanitizers). (#9089) [@judicaelclair] - InvisibleButton: allow calling with size (0,0) to fit to available content size. (#9166, #7623) @@ -219,7 +219,7 @@ Other Changes: - Shortcuts: - IsItemHovered() without `ImGuiHoveredFlags_AllowWhenBlockedByActiveItem` doesn't filter out the signal when activated item is a shortcut remote activation; - (which mimicks what's done internally in the `ItemHoverable()` function). (#9138) + (which mimics what's done internally in the `ItemHoverable()` function). (#9138) - Fixed tooltip placement being affected for a frame when located over an item activated by `SetNextItemShortcut()`. (#9138) - Error Handling: @@ -257,7 +257,7 @@ Other Changes: - But you can also configure your system or debugger to automatically release mouse grab when crashing/breaking in debugger, e.g. - console: `setxkbmap -option grab:break_actions && xdotool key XF86Ungrab` - - or use a GDB script to call SDL_CaptureMouse(false). See #3650. + - or use a GDB script to call `SDL_CaptureMouse(false)`. See #3650. - On platforms other than X11 this is unnecessary. - SDL_GPU3: added `SamplerNearest` in `ImGui_ImplSDLGPU3_RenderState`. - SDL_GPU3: macOS version can use MSL shaders in order to support macOS 10.14+ From b8a1f74fd950bd089982159236ee734b3c2ff11d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Feb 2026 16:05:19 +0100 Subject: [PATCH 1672/2359] Version 1.92.7 WIP + minor demo tweaks. --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 16 ++++++++-------- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 25 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3098743cd..960b3f5b8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.92.7 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.92.6 (2026-02-17) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 93cff908c..0260481d4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 +// dear imgui, v1.92.7 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index e3edac89c..6ab81771f 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 +// dear imgui, v1.92.7 WIP // (headers) // Help: @@ -29,8 +29,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.6" -#define IMGUI_VERSION_NUM 19261 +#define IMGUI_VERSION "1.92.7 WIP" +#define IMGUI_VERSION_NUM 19262 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c0c4de946..4cbf94a07 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 +// dear imgui, v1.92.7 WIP // (demo code) // Help: @@ -731,7 +731,7 @@ struct ExampleTreeNode // Tree structure char Name[28] = ""; int UID = 0; - ExampleTreeNode* Parent = NULL; + ExampleTreeNode* Parent = NULL; ImVector Childs; unsigned short IndexInParent = 0; // Maintaining this allows us to implement linear traversal more easily @@ -746,7 +746,7 @@ struct ExampleTreeNode // (this is a minimal version of what a typical advanced application may provide) struct ExampleMemberInfo { - const char* Name; // Member name + const char* Name; // Member name ImGuiDataType DataType; // Member type int DataCount; // Member count (1 when scalar) int Offset; // Offset inside parent structure @@ -781,7 +781,7 @@ static void ExampleTree_DestroyNode(ExampleTreeNode* node) } // Create example tree data -// (this allocates _many_ more times than most other code in either Dear ImGui or others demo) +// (this allocates _many_ more times than most other code in all of Dear ImGui or others demo) static ExampleTreeNode* ExampleTree_CreateDemoTree() { static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" }; @@ -9448,7 +9448,7 @@ static void ShowExampleAppLayout(bool* p_open) struct ExampleAppPropertyEditor { ImGuiTextFilter Filter; - ExampleTreeNode* VisibleNode = NULL; + ExampleTreeNode* SelectedNode = NULL; void Draw(ExampleTreeNode* root_node) { @@ -9477,7 +9477,7 @@ struct ExampleAppPropertyEditor ImGui::SameLine(); ImGui::BeginGroup(); // Lock X position - if (ExampleTreeNode* node = VisibleNode) + if (ExampleTreeNode* node = SelectedNode) { ImGui::Text("%s", node->Name); ImGui::TextDisabled("UID: 0x%08X", node->UID); @@ -9550,7 +9550,7 @@ struct ExampleAppPropertyEditor tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsToParent; // Left arrow support tree_flags |= ImGuiTreeNodeFlags_SpanFullWidth; // Span full width for easier mouse reach tree_flags |= ImGuiTreeNodeFlags_DrawLinesToNodes; // Always draw hierarchy outlines - if (node == VisibleNode) + if (node == SelectedNode) tree_flags |= ImGuiTreeNodeFlags_Selected; if (node->Childs.Size == 0) tree_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet; @@ -9560,7 +9560,7 @@ struct ExampleAppPropertyEditor if (node->DataMyBool == false) ImGui::PopStyleColor(); if (ImGui::IsItemFocused()) - VisibleNode = node; + SelectedNode = node; if (node_open) { for (ExampleTreeNode* child : node->Childs) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 20a24a9e6..19209fed7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 +// dear imgui, v1.92.7 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index c57457595..b188009a9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 +// dear imgui, v1.92.7 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 8df32585b..a51f2f012 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 +// dear imgui, v1.92.7 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 23a75aa8c..9f5c3645e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.92.6 +// dear imgui, v1.92.7 WIP // (widgets code) /* From 635a5c0a127233b478d25690274a574bda3925bc Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Feb 2026 16:08:49 +0100 Subject: [PATCH 1673/2359] Clipper: clear DisplayStart/DisplayEnd fields when Step() returns false. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + 2 files changed, 3 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 960b3f5b8..97be5c905 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking Changes: Other Changes: +- Clipper: clear DisplayStart/DisplayEnd fields when Step() returns false. + ----------------------------------------------------------------------- VERSION 1.92.6 (2026-02-17) diff --git a/imgui.cpp b/imgui.cpp index 0260481d4..7f0fc1189 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3289,6 +3289,7 @@ void ImGuiListClipper::End() } TempData = NULL; } + DisplayStart = DisplayEnd = ItemsCount; // Clear this so code which may be reused past last Step() won't trip on a non-empty range. ItemsCount = -1; } From 0653a0d42a98ac6fac5d785b2e16b232ee0550e2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Feb 2026 16:47:30 +0100 Subject: [PATCH 1674/2359] Demo: use ImGui version of TreeNodeGetOpen/TreeNodeSetOpen + comments. --- imgui_demo.cpp | 31 +++++++++++++------------------ imgui_widgets.cpp | 6 ++++-- 2 files changed, 17 insertions(+), 20 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4cbf94a07..a461bae6b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -290,6 +290,14 @@ ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback = NULL; void* GImGuiDemoMarkerCallbackUserData = NULL; #define IMGUI_DEMO_MARKER(section) do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback("imgui_demo.cpp", __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0) +// Sneakily forward declare functions which aren't worth putting in public API yet +namespace ImGui +{ + IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); + IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); + IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool is_open); +} + //----------------------------------------------------------------------------- // [SECTION] Demo Window / ShowDemoWindow() //----------------------------------------------------------------------------- @@ -1746,9 +1754,6 @@ static void DemoWindowWidgetsDragsAndSliders() // [SECTION] DemoWindowWidgetsFonts() //----------------------------------------------------------------------------- -// Forward declare ShowFontAtlas() which isn't worth putting in public API yet -namespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); } - static void DemoWindowWidgetsFonts() { IMGUI_DEMO_MARKER("Widgets/Fonts"); @@ -3079,16 +3084,6 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d } } - static bool TreeNodeGetOpen(ExampleTreeNode* node) - { - return ImGui::GetStateStorage()->GetBool((ImGuiID)node->UID); - } - - static void TreeNodeSetOpen(ExampleTreeNode* node, bool open) - { - ImGui::GetStateStorage()->SetBool((ImGuiID)node->UID, open); - } - // When closing a node: 1) close and unselect all child nodes, 2) select parent if any child was selected. // FIXME: This is currently handled by user logic but I'm hoping to eventually provide tree node // features to do this automatically, e.g. a ImGuiTreeNodeFlags_AutoCloseChildNodes etc. @@ -3096,11 +3091,11 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d { // Recursive close (the test for depth == 0 is because we call this on a node that was just closed!) int unselected_count = selection->Contains((ImGuiID)node->UID) ? 1 : 0; - if (depth == 0 || TreeNodeGetOpen(node)) + if (depth == 0 || ImGui::TreeNodeGetOpen((ImGuiID)node->UID)) { for (ExampleTreeNode* child : node->Childs) unselected_count += TreeCloseAndUnselectChildNodes(child, selection, depth + 1); - TreeNodeSetOpen(node, false); + ImGui::TreeNodeSetOpen((ImGuiID)node->UID, false); } // Select root node if any of its child was selected, otherwise unselect @@ -3134,7 +3129,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d { if (node->Parent != NULL) // Root node isn't visible nor selectable in our scheme selection->SetItemSelected((ImGuiID)node->UID, selected); - if (node->Parent == NULL || TreeNodeGetOpen(node)) + if (node->Parent == NULL || ImGui::TreeNodeGetOpen((ImGuiID)node->UID)) for (ExampleTreeNode* child : node->Childs) TreeSetAllInOpenNodes(child, selection, selected); } @@ -3154,7 +3149,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d return NULL; // Recurse into childs. Query storage to tell if the node is open. - if (curr_node->Childs.Size > 0 && TreeNodeGetOpen(curr_node)) + if (curr_node->Childs.Size > 0 && ImGui::TreeNodeGetOpen((ImGuiID)curr_node->UID)) return curr_node->Childs[0]; // Next sibling, then into our own parent @@ -9463,7 +9458,7 @@ struct ExampleAppPropertyEditor Filter.Build(); ImGui::PopItemFlag(); - if (ImGui::BeginTable("##bg", 1, ImGuiTableFlags_RowBg)) + if (ImGui::BeginTable("##list", 1, ImGuiTableFlags_RowBg)) { for (ExampleTreeNode* node : root_node->Childs) if (Filter.PassFilter(node->Name)) // Filter root node diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9f5c3645e..e8b819197 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6726,6 +6726,8 @@ bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char return TreeNodeBehavior(id, flags, label, label_end); } +// 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) { ImGuiContext& g = *GImGui; @@ -6733,11 +6735,11 @@ bool ImGui::TreeNodeGetOpen(ImGuiID storage_id) return storage->GetInt(storage_id, 0) != 0; } -void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool open) +void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool is_open) { ImGuiContext& g = *GImGui; ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; - storage->SetInt(storage_id, open ? 1 : 0); + storage->SetInt(storage_id, is_open ? 1 : 0); } bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) From 3fecb234c81d9cef7dd34c79ba7f6f008468196e Mon Sep 17 00:00:00 2001 From: Adem Budak Date: Thu, 19 Feb 2026 13:27:19 +0300 Subject: [PATCH 1675/2359] Examples: SDL3+WGPU: fixed build warning. (#9255) --- examples/example_sdl3_wgpu/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index c02a5be9c..795ffbacf 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -513,7 +513,7 @@ static bool InitWGPU(SDL_Window* window) #include #endif -static WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) +WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window) { SDL_PropertiesID propertiesID = SDL_GetWindowProperties(window); From c234426f8985a30ac6c464f409ca75bedb38f85d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Feb 2026 16:32:14 +0100 Subject: [PATCH 1676/2359] TreeNode: comments on ImGuiTreeNodeFlags_Leaf. (#4833) --- imgui.h | 2 +- imgui_widgets.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 6ab81771f..a68e81010 100644 --- a/imgui.h +++ b/imgui.h @@ -1306,7 +1306,7 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. - ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). Note: will always open a tree/id scope and return true. If you never use that scope, add ImGuiTreeNodeFlags_NoTreePushOnOpen. ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding() before the node. ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e8b819197..928942964 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6744,6 +6744,7 @@ void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool is_open) bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) { + // Leaf node always open a new tree/id scope. If you never use it, add ImGuiTreeNodeFlags_NoTreePushOnOpen. if (flags & ImGuiTreeNodeFlags_Leaf) return true; From f7fbe5bd91a0838be043ce243c1618329aaf14bb Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 20 Feb 2026 14:56:18 +0100 Subject: [PATCH 1677/2359] Update README.md --- docs/README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/README.md b/docs/README.md index c93847c86..9057b14c9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -55,8 +55,8 @@ if (ImGui::Button("Save")) ImGui::InputText("string", buf, IM_COUNTOF(buf)); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ``` -![sample code output (dark, segoeui font, freetype)](https://user-images.githubusercontent.com/8225057/191050833-b7ecf528-bfae-4a9f-ac1b-f3d83437a2f4.png) -![sample code output (light, segoeui font, freetype)](https://user-images.githubusercontent.com/8225057/191050838-8742efd4-504d-4334-a9a2-e756d15bc2ab.png) +sample code output (dark) +sample code output (light) ```cpp // Create a window called "My First Tool", with a menu bar. @@ -116,6 +116,19 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: - [imgui-demo-binaries-20250625.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20250625.zip) (Windows, 1.92.0, built 2025/06/25, master) or [older binaries](https://www.dearimgui.com/binaries). +### Gallery + +Examples projects using Dear ImGui: [Tracy](https://github.com/wolfpld/tracy) (profiler), [ImHex](https://github.com/WerWolv/ImHex) (hex editor/data analysis), [RemedyBG](https://remedybg.itch.io/remedybg) (debugger) and [hundreds of others](https://github.com/ocornut/imgui/wiki/Software-using-Dear-ImGui). + +For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues?q=label%3Agallery)! + +For a list of third-party widgets and extensions, check out the [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page. + +| | | +|--|--| +| Custom engine [erhe](https://github.com/tksuoran/erhe) (docking branch)
[![erhe](https://user-images.githubusercontent.com/8225057/190203358-6988b846-0686-480e-8663-1311fbd18abd.jpg)](https://user-images.githubusercontent.com/994606/147875067-a848991e-2ad2-4fd3-bf71-4aeb8a547bcf.png) | Custom engine for [Wonder Boy: The Dragon's Trap](http://www.TheDragonsTrap.com) (2017)
[![the dragon's trap](https://user-images.githubusercontent.com/8225057/190203379-57fcb80e-4aec-4fec-959e-17ddd3cd71e5.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) | +| Custom engine (untitled)
[![editor white](https://user-images.githubusercontent.com/8225057/190203393-c5ac9f22-b900-4d1e-bfeb-6027c63e3d92.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/editor_white.png) | Tracy Profiler ([github](https://github.com/wolfpld/tracy))
[![tracy profiler](https://user-images.githubusercontent.com/8225057/190203401-7b595f6e-607c-44d3-97ea-4c2673244dfb.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v176/tracy_profiler.png) | + ### Getting Started & Integration See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide for details. @@ -143,19 +156,6 @@ Officially maintained backends (in repository): Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. -### Gallery - -Examples projects using Dear ImGui: [Tracy](https://github.com/wolfpld/tracy) (profiler), [ImHex](https://github.com/WerWolv/ImHex) (hex editor/data analysis), [RemedyBG](https://remedybg.itch.io/remedybg) (debugger) and [hundreds of others](https://github.com/ocornut/imgui/wiki/Software-using-Dear-ImGui). - -For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues?q=label%3Agallery)! - -For a list of third-party widgets and extensions, check out the [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page. - -| | | -|--|--| -| Custom engine [erhe](https://github.com/tksuoran/erhe) (docking branch)
[![erhe](https://user-images.githubusercontent.com/8225057/190203358-6988b846-0686-480e-8663-1311fbd18abd.jpg)](https://user-images.githubusercontent.com/994606/147875067-a848991e-2ad2-4fd3-bf71-4aeb8a547bcf.png) | Custom engine for [Wonder Boy: The Dragon's Trap](http://www.TheDragonsTrap.com) (2017)
[![the dragon's trap](https://user-images.githubusercontent.com/8225057/190203379-57fcb80e-4aec-4fec-959e-17ddd3cd71e5.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) | -| Custom engine (untitled)
[![editor white](https://user-images.githubusercontent.com/8225057/190203393-c5ac9f22-b900-4d1e-bfeb-6027c63e3d92.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/editor_white.png) | Tracy Profiler ([github](https://github.com/wolfpld/tracy))
[![tracy profiler](https://user-images.githubusercontent.com/8225057/190203401-7b595f6e-607c-44d3-97ea-4c2673244dfb.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v176/tracy_profiler.png) | - ### Support, Frequently Asked Questions (FAQ) See: [Frequently Asked Questions (FAQ)](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) where common questions are answered. From e8281fdf1a62ebf5a53554c3bd2e52cbb9257fd9 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 20 Feb 2026 15:09:20 +0100 Subject: [PATCH 1678/2359] Update README --- docs/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/README.md b/docs/README.md index 9057b14c9..1551f48df 100644 --- a/docs/README.md +++ b/docs/README.md @@ -55,8 +55,8 @@ if (ImGui::Button("Save")) ImGui::InputText("string", buf, IM_COUNTOF(buf)); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ``` -sample code output (dark) -sample code output (light) +sample code output (dark) +sample code output (light) ```cpp // Create a window called "My First Tool", with a menu bar. @@ -90,7 +90,7 @@ for (int n = 0; n < 50; n++) ImGui::EndChild(); ImGui::End(); ``` -![my_first_tool_v188](https://user-images.githubusercontent.com/8225057/191055698-690a5651-458f-4856-b5a9-e8cc95c543e2.gif) +![my_first_tool_v192 6](https://github.com/user-attachments/assets/6c76658c-302f-403b-af26-d517e2bfb0d4) Dear ImGui allows you to **create elaborate tools** as well as very short-lived ones. On the extreme side of short-livedness: using the Edit&Continue (hot code reload) feature of modern compilers you can add a few widgets to tweak variables while your application is running, and remove the code a minute later! Dear ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, an entire game-making editor/framework, etc. From 05481194b61ae494db8dcfbcd05358bd3a6e759e Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 20 Feb 2026 15:25:35 +0100 Subject: [PATCH 1679/2359] Update README Added a section on useful extensions and widgets with links. --- docs/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/README.md b/docs/README.md index 1551f48df..4f090545a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -151,6 +151,8 @@ Officially maintained backends (in repository): - Frameworks: AGS/Adventure Game Studio, Amethyst, Blender, bsf, Cinder, Cocos2d-x, Defold, Diligent Engine, Ebiten, Flexium, GML/Game Maker Studio, GLEQ, Godot, GTK3, Irrlicht Engine, JUCE, LÖVE+LUA, Mach Engine, Magnum, Marmalade, Monogame, NanoRT, nCine, Nim Game Lib, Nintendo 3DS/Switch/WiiU (homebrew), Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, raylib, SFML, Sokol, Unity, Unreal Engine 4/5, UWP, vtk, VulkanHpp, VulkanSceneGraph, Win32 GDI, WxWidgets. - Many bindings are auto-generated (by good old [cimgui](https://github.com/cimgui/cimgui) or our newer [dear_bindings](https://github.com/dearimgui/dear_bindings)), you can use their metadata output to generate bindings for other languages. +Useful extensions + [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page: - Automation/testing, Text editors, node editors, timeline editors, plotting, software renderers, remote network access, memory editors, gizmos, etc. Notable and well supported extensions include [ImPlot](https://github.com/epezent/implot) and [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine). From 221bac8b06e4e903b63ddb15bf0966e1f89cbb6a Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Feb 2026 16:16:27 +0100 Subject: [PATCH 1680/2359] Style: border sizes are now scaled and rounded by ScaleAllSizes(). Lift 1.0f limit in Style Editor. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 8 ++++++++ imgui.h | 2 +- imgui_demo.cpp | 29 +++++++++++++++++------------ 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 97be5c905..9ec3687c6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,7 @@ Breaking Changes: Other Changes: +- Style: border sizes are now scaled (and rounded) by ScaleAllSizes(). - Clipper: clear DisplayStart/DisplayEnd fields when Step() returns false. diff --git a/imgui.cpp b/imgui.cpp index 7f0fc1189..53a020d2b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1529,11 +1529,15 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) _MainScale *= scale_factor; WindowPadding = ImTrunc(WindowPadding * scale_factor); WindowRounding = ImTrunc(WindowRounding * scale_factor); + WindowBorderSize = ImTrunc(WindowBorderSize * scale_factor); WindowMinSize = ImTrunc(WindowMinSize * scale_factor); WindowBorderHoverPadding = ImTrunc(WindowBorderHoverPadding * scale_factor); ChildRounding = ImTrunc(ChildRounding * scale_factor); + ChildBorderSize = ImTrunc(ChildBorderSize * scale_factor); PopupRounding = ImTrunc(PopupRounding * scale_factor); + PopupBorderSize = ImTrunc(PopupBorderSize * scale_factor); FramePadding = ImTrunc(FramePadding * scale_factor); + FrameBorderSize = ImTrunc(FrameBorderSize * scale_factor); FrameRounding = ImTrunc(FrameRounding * scale_factor); ItemSpacing = ImTrunc(ItemSpacing * scale_factor); ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor); @@ -1550,17 +1554,21 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) ImageRounding = ImTrunc(ImageRounding * scale_factor); ImageBorderSize = ImTrunc(ImageBorderSize * scale_factor); TabRounding = ImTrunc(TabRounding * scale_factor); + TabBorderSize = ImTrunc(TabBorderSize * scale_factor); TabMinWidthBase = ImTrunc(TabMinWidthBase * scale_factor); TabMinWidthShrink = ImTrunc(TabMinWidthShrink * scale_factor); TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected; TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; + TabBarBorderSize = ImTrunc(TabBarBorderSize * scale_factor); TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); + TreeLinesSize = ImTrunc(TreeLinesSize * scale_factor); TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor); DragDropTargetRounding = ImTrunc(DragDropTargetRounding * scale_factor); DragDropTargetBorderSize = ImTrunc(DragDropTargetBorderSize * scale_factor); DragDropTargetPadding = ImTrunc(DragDropTargetPadding * scale_factor); ColorMarkerSize = ImTrunc(ColorMarkerSize * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); + SeparatorTextBorderSize = ImTrunc(SeparatorTextBorderSize * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor); diff --git a/imgui.h b/imgui.h index a68e81010..d84e0ca25 100644 --- a/imgui.h +++ b/imgui.h @@ -2354,7 +2354,7 @@ struct ImGuiStyle ImGuiHoveredFlags HoverFlagsForTooltipNav; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. // [Internal] - float _MainScale; // FIXME-WIP: Reference scale, as applied by ScaleAllSizes(). + float _MainScale; // FIXME-WIP: Reference scale, as applied by ScaleAllSizes(). PLEASE DO NOT USE THIS FOR NOW. float _NextFrameFontSizeBase; // FIXME: Temporary hack until we finish remaining work. // Functions diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a461bae6b..8c681cb76 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8369,6 +8369,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ref == NULL) ref = &ref_saved_style; + // The logic behind dynamically changing 'max_border_size' is to not encourage people to increase border size too much: it'll likely reveal lots of subtle rendering artifacts and this isn't a priority right now. + // Note that _MainScale is currently internal PLEASE DO NOT USE IN YOUR CODE. + const float default_border_size = (float)(int)style._MainScale; + const float max_border_size = IM_MAX(default_border_size, 2.0f); + PushItemWidth(GetWindowWidth() * 0.50f); { @@ -8397,11 +8402,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) if (SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding - { bool border = (style.WindowBorderSize > 0.0f); if (Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } + { bool border = (style.WindowBorderSize > 0.0f); if (Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? default_border_size : 0.0f; } } SameLine(); - { bool border = (style.FrameBorderSize > 0.0f); if (Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } + { bool border = (style.FrameBorderSize > 0.0f); if (Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? default_border_size : 0.0f; } } SameLine(); - { bool border = (style.PopupBorderSize > 0.0f); if (Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } + { bool border = (style.PopupBorderSize > 0.0f); if (Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? default_border_size : 0.0f; } } } // Save/Revert button @@ -8430,10 +8435,10 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); SeparatorText("Borders"); - SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); - SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); - SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); - SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, max_border_size, "%.0f"); + SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, max_border_size, "%.0f"); + SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, max_border_size, "%.0f"); + SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, max_border_size, "%.0f"); SeparatorText("Rounding"); SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); @@ -8448,9 +8453,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat("ScrollbarPadding", &style.ScrollbarPadding, 0.0f, 10.0f, "%.0f"); SeparatorText("Tabs"); - SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); - SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); - SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); + SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, max_border_size, "%.0f"); + SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, max_border_size, "%.0f"); + SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, IM_MAX(3.0f, max_border_size), "%.0f"); SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); DragFloat("TabMinWidthBase", &style.TabMinWidthBase, 0.5f, 1.0f, 500.0f, "%.0f"); DragFloat("TabMinWidthShrink", &style.TabMinWidthShrink, 0.5f, 1.0f, 500.0f, "%0.f"); @@ -8475,7 +8480,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) style.TreeLinesFlags = option; EndCombo(); } - SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 2.0f, "%.0f"); + SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, max_border_size, "%.0f"); SliderFloat("TreeLinesRounding", &style.TreeLinesRounding, 0.0f, 12.0f, "%.0f"); SeparatorText("Windows"); @@ -8497,7 +8502,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); SliderFloat("ImageRounding", &style.ImageRounding, 0.0f, 12.0f, "%.0f"); - SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, max_border_size, "%.0f"); SeparatorText("Tooltips"); for (int n = 0; n < 2; n++) From b5ccee78b66fe9f9853005fca4458643ce11b69e Mon Sep 17 00:00:00 2001 From: r-lyeh <35402248+r-lyeh@users.noreply.github.com> Date: Fri, 20 Feb 2026 15:54:56 +0100 Subject: [PATCH 1681/2359] Examples: WGPU: fixed undefined behaviors in example init code. (#9246, #9256) [@r-lyeh] --- docs/CHANGELOG.txt | 3 +++ examples/example_glfw_wgpu/main.cpp | 24 +++++++++++++++++------- examples/example_sdl2_wgpu/main.cpp | 24 +++++++++++++++++------- examples/example_sdl3_wgpu/main.cpp | 24 +++++++++++++++++------- 4 files changed, 54 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9ec3687c6..4645c48a9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,9 @@ Other Changes: - Style: border sizes are now scaled (and rounded) by ScaleAllSizes(). - Clipper: clear DisplayStart/DisplayEnd fields when Step() returns false. +- Examples: + - WGPU: fixed undefined behaviors in example code for requesting adapter + and device. (#9246, #9256) [@r-lyeh] ----------------------------------------------------------------------- diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 1a6373c8a..f77314bd6 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -385,23 +385,29 @@ static WGPUAdapter RequestAdapter(WGPUInstance& instance) { WGPURequestAdapterOptions adapter_options = {}; - WGPUAdapter local_adapter; + WGPUAdapter local_adapter = nullptr; WGPURequestAdapterCallbackInfo adapterCallbackInfo = {}; + adapterCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly; adapterCallbackInfo.callback = handle_request_adapter; adapterCallbackInfo.userdata1 = &local_adapter; - wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + WGPUFuture future = wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + WGPUFutureWaitInfo waitInfo = { future, false }; + wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull); IM_ASSERT(local_adapter && "Error on Adapter request"); return local_adapter; } -static WGPUDevice RequestDevice(WGPUAdapter& adapter) +static WGPUDevice RequestDevice(WGPUInstance& instance, WGPUAdapter& adapter) { - WGPUDevice local_device; + WGPUDevice local_device = nullptr; WGPURequestDeviceCallbackInfo deviceCallbackInfo = {}; + deviceCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly; deviceCallbackInfo.callback = handle_request_device; deviceCallbackInfo.userdata1 = &local_device; - wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + WGPUFuture future = wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + WGPUFutureWaitInfo waitInfo = { future, false }; + wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull); IM_ASSERT(local_device && "Error on Device request"); return local_device; } @@ -449,7 +455,11 @@ bool InitWGPU(GLFWwindow* window) // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - wgpu_instance = wgpuCreateInstance(nullptr); + WGPUInstanceDescriptor instanceDesc = {}; + WGPUInstanceFeatureName timedWaitAny = WGPUInstanceFeatureName_TimedWaitAny; + instanceDesc.requiredFeatureCount = 1; + instanceDesc.requiredFeatures = &timedWaitAny; + wgpu_instance = wgpuCreateInstance(&instanceDesc); #ifdef __EMSCRIPTEN__ getAdapterAndDeviceViaJS(); @@ -476,7 +486,7 @@ bool InitWGPU(GLFWwindow* window) WGPUAdapter adapter = RequestAdapter(wgpu_instance); ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter); - wgpu_device = RequestDevice(adapter); + wgpu_device = RequestDevice(wgpu_instance, adapter); // Create the surface. wgpu_surface = CreateWGPUSurface(wgpu_instance, window); diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index 40a206cf1..66bd77015 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -369,23 +369,29 @@ static WGPUAdapter RequestAdapter(WGPUInstance& instance) { WGPURequestAdapterOptions adapter_options = {}; - WGPUAdapter local_adapter; + WGPUAdapter local_adapter = nullptr; WGPURequestAdapterCallbackInfo adapterCallbackInfo = {}; + adapterCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly; adapterCallbackInfo.callback = handle_request_adapter; adapterCallbackInfo.userdata1 = &local_adapter; - wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + WGPUFuture future = wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + WGPUFutureWaitInfo waitInfo = { future, false }; + wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull); IM_ASSERT(local_adapter && "Error on Adapter request"); return local_adapter; } -static WGPUDevice RequestDevice(WGPUAdapter& adapter) +static WGPUDevice RequestDevice(WGPUInstance& instance, WGPUAdapter& adapter) { - WGPUDevice local_device; + WGPUDevice local_device = nullptr; WGPURequestDeviceCallbackInfo deviceCallbackInfo = {}; + deviceCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly; deviceCallbackInfo.callback = handle_request_device; deviceCallbackInfo.userdata1 = &local_device; - wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + WGPUFuture future = wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + WGPUFutureWaitInfo waitInfo = { future, false }; + wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull); IM_ASSERT(local_device && "Error on Device request"); return local_device; } @@ -434,7 +440,11 @@ static bool InitWGPU(SDL_Window* window) // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - wgpu_instance = wgpuCreateInstance(nullptr); + WGPUInstanceDescriptor instanceDesc = {}; + WGPUInstanceFeatureName timedWaitAny = WGPUInstanceFeatureName_TimedWaitAny; + instanceDesc.requiredFeatureCount = 1; + instanceDesc.requiredFeatures = &timedWaitAny; + wgpu_instance = wgpuCreateInstance(&instanceDesc); #ifdef __EMSCRIPTEN__ getAdapterAndDeviceViaJS(); @@ -461,7 +471,7 @@ static bool InitWGPU(SDL_Window* window) WGPUAdapter adapter = RequestAdapter(wgpu_instance); ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter); - wgpu_device = RequestDevice(adapter); + wgpu_device = RequestDevice(wgpu_instance, adapter); // Create the surface. wgpu_surface = CreateWGPUSurface(wgpu_instance, window); diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index 795ffbacf..aa67d3098 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -380,23 +380,29 @@ static WGPUAdapter RequestAdapter(WGPUInstance& instance) { WGPURequestAdapterOptions adapter_options = {}; - WGPUAdapter local_adapter; + WGPUAdapter local_adapter = nullptr; WGPURequestAdapterCallbackInfo adapterCallbackInfo = {}; + adapterCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly; adapterCallbackInfo.callback = handle_request_adapter; adapterCallbackInfo.userdata1 = &local_adapter; - wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + WGPUFuture future = wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo); + WGPUFutureWaitInfo waitInfo = { future, false }; + wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull); IM_ASSERT(local_adapter && "Error on Adapter request"); return local_adapter; } -static WGPUDevice RequestDevice(WGPUAdapter& adapter) +static WGPUDevice RequestDevice(WGPUInstance& instance, WGPUAdapter& adapter) { - WGPUDevice local_device; + WGPUDevice local_device = nullptr; WGPURequestDeviceCallbackInfo deviceCallbackInfo = {}; + deviceCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly; deviceCallbackInfo.callback = handle_request_device; deviceCallbackInfo.userdata1 = &local_device; - wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + WGPUFuture future = wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo); + WGPUFutureWaitInfo waitInfo = { future, false }; + wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull); IM_ASSERT(local_device && "Error on Device request"); return local_device; } @@ -445,7 +451,11 @@ static bool InitWGPU(SDL_Window* window) // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) - wgpu_instance = wgpuCreateInstance(nullptr); + WGPUInstanceDescriptor instanceDesc = {}; + WGPUInstanceFeatureName timedWaitAny = WGPUInstanceFeatureName_TimedWaitAny; + instanceDesc.requiredFeatureCount = 1; + instanceDesc.requiredFeatures = &timedWaitAny; + wgpu_instance = wgpuCreateInstance(&instanceDesc); #ifdef __EMSCRIPTEN__ getAdapterAndDeviceViaJS(); @@ -472,7 +482,7 @@ static bool InitWGPU(SDL_Window* window) WGPUAdapter adapter = RequestAdapter(wgpu_instance); ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter); - wgpu_device = RequestDevice(adapter); + wgpu_device = RequestDevice(wgpu_instance, adapter); // Create the surface. wgpu_surface = CreateWGPUSurface(wgpu_instance, window); From 37b7a7a9dfc4a775c371bbd0ab8ceaf132c78fce Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Sun, 8 Feb 2026 00:43:34 +0100 Subject: [PATCH 1682/2359] Demo: move imgui manual IMGUI_DEMO_MARKER inside tree nodes. (#3689) So that the manual switches less often when the user does not want it. Most switches now happen only after opening a tree node. --- imgui_demo.cpp | 250 ++++++++++++++++++++++++------------------------- 1 file changed, 122 insertions(+), 128 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8c681cb76..f2baf2345 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -282,7 +282,7 @@ static void HelpMarker(const char* desc) } } -// Helper to wire demo markers located in code to an interactive browser +// Helper to wire demo markers located in code to an interactive browser (e.g. imgui_manual) typedef void (*ImGuiDemoMarkerCallback)(const char* file, int line, const char* section, void* user_data); extern ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback; extern void* GImGuiDemoMarkerCallbackUserData; @@ -438,9 +438,9 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); ImGui::Spacing(); - IMGUI_DEMO_MARKER("Help"); if (ImGui::CollapsingHeader("Help")) { + IMGUI_DEMO_MARKER("Help"); ImGui::SeparatorText("ABOUT THIS DEMO:"); ImGui::BulletText("Sections below are demonstrating many aspects of the library."); ImGui::BulletText("The \"Examples\" menu above leads to more demo contents."); @@ -461,13 +461,13 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::ShowUserGuide(); } - IMGUI_DEMO_MARKER("Configuration"); if (ImGui::CollapsingHeader("Configuration")) { ImGuiIO& io = ImGui::GetIO(); if (ImGui::TreeNode("Configuration##2")) { + IMGUI_DEMO_MARKER("Configuration"); ImGui::SeparatorText("General"); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); ImGui::SameLine(); HelpMarker("Enable keyboard controls."); @@ -571,9 +571,9 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Spacing(); } - IMGUI_DEMO_MARKER("Configuration/Backend Flags"); if (ImGui::TreeNode("Backend Flags")) { + IMGUI_DEMO_MARKER("Configuration/Backend Flags"); HelpMarker( "Those flags are set by the backends (imgui_impl_xxx files) to specify their capabilities.\n" "Here we expose them as read-only fields to avoid breaking interactions with your backend."); @@ -591,9 +591,9 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Spacing(); } - IMGUI_DEMO_MARKER("Configuration/Style, Fonts"); if (ImGui::TreeNode("Style, Fonts")) { + IMGUI_DEMO_MARKER("Configuration/Style, Fonts"); ImGui::Checkbox("Style Editor", &demo_data.ShowStyleEditor); ImGui::SameLine(); HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function."); @@ -601,9 +601,9 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Spacing(); } - IMGUI_DEMO_MARKER("Configuration/Capture, Logging"); if (ImGui::TreeNode("Capture/Logging")) { + IMGUI_DEMO_MARKER("Configuration/Capture, Logging"); HelpMarker( "The logging API redirects all text output so you can easily capture the content of " "a window or a block. Tree nodes can be automatically expanded.\n" @@ -621,9 +621,9 @@ void ImGui::ShowDemoWindow(bool* p_open) } } - IMGUI_DEMO_MARKER("Window options"); if (ImGui::CollapsingHeader("Window options")) { + IMGUI_DEMO_MARKER("Window options"); if (ImGui::BeginTable("split", 3)) { ImGui::TableNextColumn(); ImGui::Checkbox("No titlebar", &no_titlebar); @@ -825,9 +825,9 @@ static ExampleTreeNode* ExampleTree_CreateDemoTree() static void DemoWindowWidgetsBasic() { - IMGUI_DEMO_MARKER("Widgets/Basic"); if (ImGui::TreeNode("Basic")) { + IMGUI_DEMO_MARKER("Widgets/Basic"); ImGui::SeparatorText("General"); IMGUI_DEMO_MARKER("Widgets/Basic/Button"); @@ -1040,9 +1040,9 @@ static void DemoWindowWidgetsBasic() static void DemoWindowWidgetsBullets() { - IMGUI_DEMO_MARKER("Widgets/Bullets"); if (ImGui::TreeNode("Bullets")) { + IMGUI_DEMO_MARKER("Widgets/Bullets"); ImGui::BulletText("Bullet point 1"); ImGui::BulletText("Bullet point 2\nOn multiple lines"); if (ImGui::TreeNode("Tree node")) @@ -1062,9 +1062,9 @@ static void DemoWindowWidgetsBullets() static void DemoWindowWidgetsCollapsingHeaders() { - IMGUI_DEMO_MARKER("Widgets/Collapsing Headers"); if (ImGui::TreeNode("Collapsing Headers")) { + IMGUI_DEMO_MARKER("Widgets/Collapsing Headers"); static bool closable_group = true; ImGui::Checkbox("Show 2nd header", &closable_group); if (ImGui::CollapsingHeader("Header", ImGuiTreeNodeFlags_None)) @@ -1093,9 +1093,9 @@ static void DemoWindowWidgetsCollapsingHeaders() static void DemoWindowWidgetsColorAndPickers() { - IMGUI_DEMO_MARKER("Widgets/Color"); if (ImGui::TreeNode("Color/Picker Widgets")) { + IMGUI_DEMO_MARKER("Widgets/Color"); static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f); static ImGuiColorEditFlags base_flags = ImGuiColorEditFlags_None; @@ -1294,9 +1294,9 @@ static void DemoWindowWidgetsColorAndPickers() static void DemoWindowWidgetsComboBoxes() { - IMGUI_DEMO_MARKER("Widgets/Combo"); if (ImGui::TreeNode("Combo")) { + IMGUI_DEMO_MARKER("Widgets/Combo"); // Combo Boxes are also called "Dropdown" in other systems // Expose flags as checkbox for the demo static ImGuiComboFlags flags = 0; @@ -1391,9 +1391,9 @@ static void DemoWindowWidgetsComboBoxes() static void DemoWindowWidgetsDataTypes() { - IMGUI_DEMO_MARKER("Widgets/Data Types"); if (ImGui::TreeNode("Data Types")) { + IMGUI_DEMO_MARKER("Widgets/Data Types"); // DragScalar/InputScalar/SliderScalar functions allow various data types // - signed/unsigned // - 8/16/32/64-bits @@ -1526,9 +1526,9 @@ static void DemoWindowWidgetsDataTypes() static void DemoWindowWidgetsDisableBlocks(ImGuiDemoWindowData* demo_data) { - IMGUI_DEMO_MARKER("Widgets/Disable Blocks"); if (ImGui::TreeNode("Disable Blocks")) { + IMGUI_DEMO_MARKER("Widgets/Disable Blocks"); ImGui::Checkbox("Disable entire section above", &demo_data->DisableSections); ImGui::SameLine(); HelpMarker("Demonstrate using BeginDisabled()/EndDisabled() across other sections."); ImGui::TreePop(); @@ -1541,12 +1541,12 @@ static void DemoWindowWidgetsDisableBlocks(ImGuiDemoWindowData* demo_data) static void DemoWindowWidgetsDragAndDrop() { - IMGUI_DEMO_MARKER("Widgets/Drag and drop"); if (ImGui::TreeNode("Drag and Drop")) { - IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets"); + IMGUI_DEMO_MARKER("Widgets/Drag and drop"); if (ImGui::TreeNode("Drag and drop in standard widgets")) { + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets"); // ColorEdit widgets automatically act as drag source and drag target. // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F // to allow your own widgets to use colors in their drag and drop interaction. @@ -1559,9 +1559,9 @@ static void DemoWindowWidgetsDragAndDrop() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items"); if (ImGui::TreeNode("Drag and drop to copy/swap items")) { + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items"); enum Mode { Mode_Copy, @@ -1627,9 +1627,9 @@ static void DemoWindowWidgetsDragAndDrop() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)"); if (ImGui::TreeNode("Drag to reorder items (simple)")) { + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)"); // FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice. // This code was always slightly faulty but in a way which was not easily noticeable. // Until we fix this, enable ImGuiItemFlags_AllowDuplicateId to disable detecting the issue. @@ -1661,9 +1661,9 @@ static void DemoWindowWidgetsDragAndDrop() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Tooltip at target location"); if (ImGui::TreeNode("Tooltip at target location")) { + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Tooltip at target location"); for (int n = 0; n < 2; n++) { // Drop targets @@ -1699,9 +1699,9 @@ static void DemoWindowWidgetsDragAndDrop() static void DemoWindowWidgetsDragsAndSliders() { - IMGUI_DEMO_MARKER("Widgets/Drag and Slider Flags"); if (ImGui::TreeNode("Drag/Slider Flags")) { + IMGUI_DEMO_MARKER("Widgets/Drag and Slider Flags"); // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! static ImGuiSliderFlags flags = ImGuiSliderFlags_None; ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp); @@ -1756,9 +1756,9 @@ static void DemoWindowWidgetsDragsAndSliders() static void DemoWindowWidgetsFonts() { - IMGUI_DEMO_MARKER("Widgets/Fonts"); if (ImGui::TreeNode("Fonts")) { + IMGUI_DEMO_MARKER("Widgets/Fonts"); ImFontAtlas* atlas = ImGui::GetIO().Fonts; ImGui::ShowFontAtlas(atlas); // FIXME-NEWATLAS: Provide a demo to add/create a procedural font? @@ -1772,9 +1772,9 @@ static void DemoWindowWidgetsFonts() static void DemoWindowWidgetsImages() { - IMGUI_DEMO_MARKER("Widgets/Images"); if (ImGui::TreeNode("Images")) { + IMGUI_DEMO_MARKER("Widgets/Images"); ImGuiIO& io = ImGui::GetIO(); ImGui::TextWrapped( "Below we are displaying the font texture (which is the only texture we have access to in this demo). " @@ -1865,9 +1865,9 @@ static void DemoWindowWidgetsImages() static void DemoWindowWidgetsListBoxes() { - IMGUI_DEMO_MARKER("Widgets/List Boxes"); if (ImGui::TreeNode("List Boxes")) { + IMGUI_DEMO_MARKER("Widgets/List Boxes"); // BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild() // using the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. // You may be tempted to simply use BeginChild() directly. However note that BeginChild() requires EndChild() @@ -1930,9 +1930,9 @@ static void DemoWindowWidgetsListBoxes() static void DemoWindowWidgetsMultiComponents() { - IMGUI_DEMO_MARKER("Widgets/Multi-component Widgets"); if (ImGui::TreeNode("Multi-component Widgets")) { + IMGUI_DEMO_MARKER("Widgets/Multi-component Widgets"); static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; static int vec4i[4] = { 1, 5, 100, 255 }; @@ -1980,9 +1980,9 @@ static void DemoWindowWidgetsPlotting() // Plot/Graph widgets are not very good. // Consider using a third-party library such as ImPlot: https://github.com/epezent/implot // (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions) - IMGUI_DEMO_MARKER("Widgets/Plotting"); if (ImGui::TreeNode("Plotting")) { + IMGUI_DEMO_MARKER("Widgets/Plotting"); ImGui::Text("Need better plotting and graphing? Consider using ImPlot:"); ImGui::TextLinkOpenURL("https://github.com/epezent/implot"); ImGui::Separator(); @@ -2053,9 +2053,9 @@ static void DemoWindowWidgetsPlotting() static void DemoWindowWidgetsProgressBars() { - IMGUI_DEMO_MARKER("Widgets/Progress Bars"); if (ImGui::TreeNode("Progress Bars")) { + IMGUI_DEMO_MARKER("Widgets/Progress Bars"); // Animate a simple progress bar static float progress_accum = 0.0f, progress_dir = 1.0f; progress_accum += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; @@ -2090,9 +2090,9 @@ static void DemoWindowWidgetsProgressBars() static void DemoWindowWidgetsQueryingStatuses() { - IMGUI_DEMO_MARKER("Widgets/Querying Item Status (Edited,Active,Hovered etc.)"); if (ImGui::TreeNode("Querying Item Status (Edited/Active/Hovered etc.)")) { + IMGUI_DEMO_MARKER("Widgets/Querying Item Status (Edited,Active,Hovered etc.)"); // Select an item type const char* item_names[] = { @@ -2202,9 +2202,9 @@ static void DemoWindowWidgetsQueryingStatuses() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Querying Window Status (Focused,Hovered etc.)"); if (ImGui::TreeNode("Querying Window Status (Focused/Hovered etc.)")) { + IMGUI_DEMO_MARKER("Widgets/Querying Window Status (Focused,Hovered etc.)"); static bool embed_all_inside_a_child_window = false; ImGui::Checkbox("Embed everything inside a child window for testing _RootWindow flag.", &embed_all_inside_a_child_window); if (embed_all_inside_a_child_window) @@ -2291,10 +2291,10 @@ static void DemoWindowWidgetsQueryingStatuses() static void DemoWindowWidgetsSelectables() { - IMGUI_DEMO_MARKER("Widgets/Selectables"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Selectables")) { + IMGUI_DEMO_MARKER("Widgets/Selectables"); // Selectable() has 2 overloads: // - The one taking "bool selected" as a read-only selection information. // When Selectable() has been clicked it returns true and you can alter selection state accordingly. @@ -2314,10 +2314,10 @@ static void DemoWindowWidgetsSelectables() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selectables/Multiple items on the same line"); + IMGUI_DEMO_MARKER("Widgets/Selectables/Rendering more items on the same line"); if (ImGui::TreeNode("Multiple items on the same line")) { - // (1) + IMGUI_DEMO_MARKER("Widgets/Selectables/Multiple items on the same line"); // - Using SetNextItemAllowOverlap() // - Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. { @@ -2356,9 +2356,9 @@ static void DemoWindowWidgetsSelectables() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selectables/In Tables"); if (ImGui::TreeNode("In Tables")) { + IMGUI_DEMO_MARKER("Widgets/Selectables/In Tables"); static bool selected[10] = {}; if (ImGui::BeginTable("split1", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) @@ -2392,9 +2392,9 @@ static void DemoWindowWidgetsSelectables() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selectables/Grid"); if (ImGui::TreeNode("Grid")) { + IMGUI_DEMO_MARKER("Widgets/Selectables/Grid"); static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; // Add in a bit of silly fun... @@ -2426,9 +2426,9 @@ static void DemoWindowWidgetsSelectables() ImGui::PopStyleVar(); ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment"); if (ImGui::TreeNode("Alignment")) { + IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment"); HelpMarker( "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item " "basis using PushStyleVar(). You'll probably want to always keep your default situation to " @@ -2689,9 +2689,9 @@ struct ExampleDualListBox static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_data) { - IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); if (ImGui::TreeNode("Selection State & Multi-Select")) { + IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select"); HelpMarker("Selections can be built using Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data."); ImGui::BulletText("Wiki page:"); @@ -2699,9 +2699,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::TextLinkOpenURL("imgui/wiki/Multi-Select", "https://github.com/ocornut/imgui/wiki/Multi-Select"); // Without any fancy API: manage single-selection yourself. - IMGUI_DEMO_MARKER("Widgets/Selection State/Single-Select"); if (ImGui::TreeNode("Single-Select")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Single-Select"); static int selected = -1; for (int n = 0; n < 5; n++) { @@ -2715,9 +2715,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // Demonstrate implementation a most-basic form of multi-selection manually // This doesn't support the Shift modifier which requires BeginMultiSelect()! - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (manual/simplified, without BeginMultiSelect)"); if (ImGui::TreeNode("Multi-Select (manual/simplified, without BeginMultiSelect)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (manual/simplified, without BeginMultiSelect)"); HelpMarker("Hold Ctrl and Click to select multiple items."); static bool selection[5] = { false, false, false, false, false }; for (int n = 0; n < 5; n++) @@ -2737,9 +2737,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // Demonstrate handling proper multi-selection using the BeginMultiSelect/EndMultiSelect API. // Shift+Click w/ Ctrl and other standard features are supported. // We use the ImGuiSelectionBasicStorage helper which you may freely reimplement. - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); if (ImGui::TreeNode("Multi-Select")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select"); ImGui::Text("Supported features:"); ImGui::BulletText("Keyboard navigation (arrows, page up/down, home/end, space)."); ImGui::BulletText("Ctrl modifier to preserve and toggle selection."); @@ -2778,9 +2778,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d } // Demonstrate using the clipper with BeginMultiSelect()/EndMultiSelect() - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with clipper)"); if (ImGui::TreeNode("Multi-Select (with clipper)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with clipper)"); // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection static ImGuiSelectionBasicStorage selection; @@ -2825,9 +2825,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // - (3) BeginXXXX process // - (4) Focus process // - (5) EndXXXX process - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with deletion)"); if (ImGui::TreeNode("Multi-Select (with deletion)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with deletion)"); // Storing items data separately from selection data. // (you may decide to store selection data inside your item (aka intrusive storage) if you don't need multiple views over same items) // Use a custom selection.Adapter: store item identifier in Selection (instead of index) @@ -2886,9 +2886,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d } // Implement a Dual List Box (#6648) - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (dual list box)"); if (ImGui::TreeNode("Multi-Select (dual list box)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (dual list box)"); // Init default state static ExampleDualListBox dlb; if (dlb.Items[0].Size == 0 && dlb.Items[1].Size == 0) @@ -2902,9 +2902,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d } // Demonstrate using the clipper with BeginMultiSelect()/EndMultiSelect() - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (in a table)"); if (ImGui::TreeNode("Multi-Select (in a table)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (in a table)"); static ImGuiSelectionBasicStorage selection; const int ITEMS_COUNT = 10000; @@ -2949,9 +2949,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (checkboxes)"); if (ImGui::TreeNode("Multi-Select (checkboxes)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (checkboxes)"); ImGui::Text("In a list of checkboxes (not selectable):"); ImGui::BulletText("Using _NoAutoSelect + _NoAutoClear flags."); ImGui::BulletText("Shift+Click to check multiple boxes."); @@ -2987,9 +2987,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d } // Demonstrate individual selection scopes in same window - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (multiple scopes)"); if (ImGui::TreeNode("Multi-Select (multiple scopes)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (multiple scopes)"); // Use default select: Pass index to SetNextItemSelectionUserData(), store index in Selection const int SCOPES_COUNT = 3; const int ITEMS_COUNT = 8; // Per scope @@ -3049,9 +3049,9 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // are more likely to build an array mapping sequential indices to visible tree nodes, since your // filtering/search + clipping process will benefit from it. Having this will make this interpolation much easier. // - Consider this a prototype: we are working toward simplifying some of it. - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (trees)"); if (ImGui::TreeNode("Multi-Select (trees)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (trees)"); HelpMarker( "This is rather advanced and experimental. If you are getting started with multi-select, " "please don't start by looking at how to use it for a tree!\n\n" @@ -3191,10 +3191,10 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d // - Showcase basic drag and drop. // - Showcase TreeNode variant (note that tree node don't expand in the demo: supporting expanding tree nodes + clipping a separate thing). // - Showcase using inside a table. - IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (ImGui::TreeNode("Multi-Select (advanced)")) { + IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)"); // Options enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode }; static bool use_clipper = true; @@ -3437,12 +3437,12 @@ static void EditTabBarFittingPolicyFlags(ImGuiTabBarFlags* p_flags) static void DemoWindowWidgetsTabs() { - IMGUI_DEMO_MARKER("Widgets/Tabs"); if (ImGui::TreeNode("Tabs")) { - IMGUI_DEMO_MARKER("Widgets/Tabs/Basic"); + IMGUI_DEMO_MARKER("Widgets/Tabs"); if (ImGui::TreeNode("Basic")) { + IMGUI_DEMO_MARKER("Widgets/Tabs/Basic"); ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None; if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) { @@ -3467,9 +3467,9 @@ static void DemoWindowWidgetsTabs() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Tabs/Advanced & Close Button"); if (ImGui::TreeNode("Advanced & Close Button")) { + IMGUI_DEMO_MARKER("Widgets/Tabs/Advanced & Close Button"); // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable; ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", &tab_bar_flags, ImGuiTabBarFlags_Reorderable); @@ -3508,9 +3508,9 @@ static void DemoWindowWidgetsTabs() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Tabs/TabItemButton & Leading-Trailing flags"); if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags")) { + IMGUI_DEMO_MARKER("Widgets/Tabs/TabItemButton & Leading-Trailing flags"); static ImVector active_tabs; static int next_tab_id = 0; if (next_tab_id == 0) // Initialize with some default tabs @@ -3581,12 +3581,12 @@ static void DemoWindowWidgetsTabs() static void DemoWindowWidgetsText() { - IMGUI_DEMO_MARKER("Widgets/Text"); if (ImGui::TreeNode("Text")) { - IMGUI_DEMO_MARKER("Widgets/Text/Colored Text"); + IMGUI_DEMO_MARKER("Widgets/Text"); if (ImGui::TreeNode("Colorful Text")) { + IMGUI_DEMO_MARKER("Widgets/Text/Colored Text"); // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink"); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow"); @@ -3595,9 +3595,9 @@ static void DemoWindowWidgetsText() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text/Font Size"); if (ImGui::TreeNode("Font Size")) { + IMGUI_DEMO_MARKER("Widgets/Text/Font Size"); ImGuiStyle& style = ImGui::GetStyle(); const float global_scale = style.FontScaleMain * style.FontScaleDpi; ImGui::Text("style.FontScaleMain = %0.2f", style.FontScaleMain); @@ -3632,9 +3632,9 @@ static void DemoWindowWidgetsText() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping"); if (ImGui::TreeNode("Word Wrapping")) { + IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping"); // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. ImGui::TextWrapped( "This text should automatically wrap on the edge of the window. The current implementation " @@ -3666,9 +3666,9 @@ static void DemoWindowWidgetsText() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text/UTF-8 Text"); if (ImGui::TreeNode("UTF-8 Text")) { + IMGUI_DEMO_MARKER("Widgets/Text/UTF-8 Text"); // UTF-8 test with Japanese characters // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 @@ -3700,9 +3700,9 @@ static void DemoWindowWidgetsText() static void DemoWindowWidgetsTextFilter() { - IMGUI_DEMO_MARKER("Widgets/Text Filter"); if (ImGui::TreeNode("Text Filter")) { + IMGUI_DEMO_MARKER("Widgets/Text Filter"); // Helper class to easy setup a text filter. // You may want to implement a more feature-full filtering scheme in your own application. HelpMarker("Not a widget per-se, but ImGuiTextFilter is a helper to perform simple filtering on text strings."); @@ -3729,12 +3729,12 @@ static void DemoWindowWidgetsTextInput() { // To wire InputText() with std::string or any other custom string type, // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. - IMGUI_DEMO_MARKER("Widgets/Text Input"); if (ImGui::TreeNode("Text Input")) { - IMGUI_DEMO_MARKER("Widgets/Text Input/Multi-line Text Input"); + IMGUI_DEMO_MARKER("Widgets/Text Input"); if (ImGui::TreeNode("Multi-line Text Input")) { + IMGUI_DEMO_MARKER("Widgets/Text Input/Multi-line Text Input"); // WE ARE USING A FIXED-SIZE BUFFER FOR SIMPLICITY HERE. // If you want to use InputText() with std::string or any custom dynamic string type: // - For std::string: use the wrapper in misc/cpp/imgui_stdlib.h/.cpp @@ -3763,9 +3763,9 @@ static void DemoWindowWidgetsTextInput() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text Input/Filtered Text Input"); if (ImGui::TreeNode("Filtered Text Input")) { + IMGUI_DEMO_MARKER("Widgets/Text Input/Filtered Text Input"); struct TextFilters { // Modify character input by altering 'data->Eventchar' (ImGuiInputTextFlags_CallbackCharFilter callback) @@ -3795,9 +3795,9 @@ static void DemoWindowWidgetsTextInput() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text Input/Password input"); if (ImGui::TreeNode("Password Input")) { + IMGUI_DEMO_MARKER("Widgets/Text Input/Password input"); static char password[64] = "password123"; ImGui::InputText("password", password, IM_COUNTOF(password), ImGuiInputTextFlags_Password); ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); @@ -3806,9 +3806,9 @@ static void DemoWindowWidgetsTextInput() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text Input/Completion, History, Edit Callbacks"); if (ImGui::TreeNode("Completion, History, Edit Callbacks")) { + IMGUI_DEMO_MARKER("Widgets/Text Input/Completion, History, Edit Callbacks"); struct Funcs { static int MyCallback(ImGuiInputTextCallbackData* data) @@ -3868,9 +3868,9 @@ static void DemoWindowWidgetsTextInput() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text Input/Resize Callback"); if (ImGui::TreeNode("Resize Callback")) { + IMGUI_DEMO_MARKER("Widgets/Text Input/Resize Callback"); // To wire InputText() with std::string or any other custom string type, // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. @@ -3914,9 +3914,9 @@ static void DemoWindowWidgetsTextInput() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text Input/Eliding, Alignment"); if (ImGui::TreeNode("Eliding, Alignment")) { + IMGUI_DEMO_MARKER("Widgets/Text Input/Eliding, Alignment"); static char buf1[128] = "/path/to/some/folder/with/long/filename.cpp"; static ImGuiInputTextFlags flags = ImGuiInputTextFlags_ElideLeft; ImGui::CheckboxFlags("ImGuiInputTextFlags_ElideLeft", &flags, ImGuiInputTextFlags_ElideLeft); @@ -3924,9 +3924,9 @@ static void DemoWindowWidgetsTextInput() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Text Input/Miscellaneous"); if (ImGui::TreeNode("Miscellaneous")) { + IMGUI_DEMO_MARKER("Widgets/Text Input/Miscellaneous"); static char buf1[16]; static ImGuiInputTextFlags flags = ImGuiInputTextFlags_EscapeClearsAll; ImGui::CheckboxFlags("ImGuiInputTextFlags_EscapeClearsAll", &flags, ImGuiInputTextFlags_EscapeClearsAll); @@ -3947,9 +3947,9 @@ static void DemoWindowWidgetsTextInput() static void DemoWindowWidgetsTooltips() { - IMGUI_DEMO_MARKER("Widgets/Tooltips"); if (ImGui::TreeNode("Tooltips")) { + IMGUI_DEMO_MARKER("Widgets/Tooltips"); // Tooltips are windows following the mouse. They do not take focus away. ImGui::SeparatorText("General"); @@ -4046,13 +4046,13 @@ static void DemoWindowWidgetsTooltips() static void DemoWindowWidgetsTreeNodes() { - IMGUI_DEMO_MARKER("Widgets/Tree Nodes"); if (ImGui::TreeNode("Tree Nodes")) { + IMGUI_DEMO_MARKER("Widgets/Tree Nodes"); // See see "Examples -> Property Editor" (ShowExampleAppPropertyEditor() function) for a fancier, data-driven tree. - IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Basic trees"); if (ImGui::TreeNode("Basic trees")) { + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Basic trees"); for (int i = 0; i < 5; i++) { // Use SetNextItemOpen() so set the default state of a node to be open. We could @@ -4076,9 +4076,9 @@ static void DemoWindowWidgetsTreeNodes() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Hierarchy lines"); if (ImGui::TreeNode("Hierarchy lines")) { + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Hierarchy lines"); static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DefaultOpen; HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); @@ -4105,9 +4105,9 @@ static void DemoWindowWidgetsTreeNodes() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Advanced, with Selectable nodes"); if (ImGui::TreeNode("Advanced, with Selectable nodes")) { + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Advanced, with Selectable nodes"); HelpMarker( "This is a more typical looking tree with selectable nodes.\n" "Click to select, Ctrl+Click to toggle, click on arrows or double-click to open."); @@ -4216,9 +4216,9 @@ static void DemoWindowWidgetsTreeNodes() static void DemoWindowWidgetsVerticalSliders() { - IMGUI_DEMO_MARKER("Widgets/Vertical Sliders"); if (ImGui::TreeNode("Vertical Sliders")) { + IMGUI_DEMO_MARKER("Widgets/Vertical Sliders"); const float spacing = 4; ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); @@ -4288,10 +4288,10 @@ static void DemoWindowWidgetsVerticalSliders() static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) { - IMGUI_DEMO_MARKER("Widgets"); //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (!ImGui::CollapsingHeader("Widgets")) return; + // IMGUI_DEMO_MARKER("Widgets"); const bool disable_all = demo_data->DisableSections; // The Checkbox for that is inside the "Disabled" section at the bottom if (disable_all) @@ -4339,13 +4339,12 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) static void DemoWindowLayout() { - IMGUI_DEMO_MARKER("Layout"); if (!ImGui::CollapsingHeader("Layout & Scrolling")) return; - IMGUI_DEMO_MARKER("Layout/Child windows"); if (ImGui::TreeNode("Child windows")) { + IMGUI_DEMO_MARKER("Layout/Child windows"); ImGui::SeparatorText("Child windows"); HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window."); @@ -4477,9 +4476,9 @@ static void DemoWindowLayout() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Layout/Widgets Width"); if (ImGui::TreeNode("Widgets Width")) { + IMGUI_DEMO_MARKER("Layout/Widgets Width"); static float f = 0.0f; static bool show_indented_items = true; ImGui::Checkbox("Show indented items", &show_indented_items); @@ -4565,9 +4564,9 @@ static void DemoWindowLayout() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout"); if (ImGui::TreeNode("Basic Horizontal Layout")) { + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout"); ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)"); // Text @@ -4658,9 +4657,9 @@ static void DemoWindowLayout() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Layout/Groups"); if (ImGui::TreeNode("Groups")) { + IMGUI_DEMO_MARKER("Layout/Groups"); HelpMarker( "BeginGroup() basically locks the horizontal position for new line. " "EndGroup() bundles the whole group so that you can use \"item\" functions such as " @@ -4705,9 +4704,9 @@ static void DemoWindowLayout() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Layout/Text Baseline Alignment"); if (ImGui::TreeNode("Text Baseline Alignment")) { + IMGUI_DEMO_MARKER("Layout/Text Baseline Alignment"); { ImGui::BulletText("Text baseline:"); ImGui::SameLine(); HelpMarker( @@ -4833,11 +4832,10 @@ static void DemoWindowLayout() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Layout/Scrolling"); if (ImGui::TreeNode("Scrolling")) { - // Vertical scroll functions IMGUI_DEMO_MARKER("Layout/Scrolling/Vertical"); + // Vertical scroll functions HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position."); static int track_item = 50; @@ -5123,9 +5121,9 @@ static void DemoWindowLayout() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Layout/Text Clipping"); if (ImGui::TreeNode("Text Clipping")) { + IMGUI_DEMO_MARKER("Layout/Text Clipping"); static ImVec2 size(100.0f, 100.0f); static ImVec2 offset(30.0f, 30.0f); ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f"); @@ -5188,9 +5186,9 @@ static void DemoWindowLayout() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Layout/Overlap Mode"); if (ImGui::TreeNode("Overlap Mode")) { + IMGUI_DEMO_MARKER("Layout/Overlap Mode"); static bool enable_allow_overlap = true; HelpMarker( @@ -5226,7 +5224,6 @@ static void DemoWindowLayout() static void DemoWindowPopups() { - IMGUI_DEMO_MARKER("Popups"); if (!ImGui::CollapsingHeader("Popups & Modal windows")) return; @@ -5248,9 +5245,9 @@ static void DemoWindowPopups() // With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state. // This may be a bit confusing at first but it should quickly make sense. Follow on the examples below. - IMGUI_DEMO_MARKER("Popups/Popups"); if (ImGui::TreeNode("Popups")) { + IMGUI_DEMO_MARKER("Popups/Popups"); ImGui::TextWrapped( "When a popup is active, it inhibits interacting with windows that are behind the popup. " "Clicking outside the popup closes it."); @@ -5341,9 +5338,9 @@ static void DemoWindowPopups() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Popups/Context menus"); if (ImGui::TreeNode("Context menus")) { + IMGUI_DEMO_MARKER("Popups/Context menus"); HelpMarker("\"Context\" functions are simple helpers to associate a Popup to a given Item or Window identifier."); // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: @@ -5428,9 +5425,9 @@ static void DemoWindowPopups() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Popups/Modals"); if (ImGui::TreeNode("Modals")) { + IMGUI_DEMO_MARKER("Popups/Modals"); ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside."); if (ImGui::Button("Delete..")) @@ -5505,9 +5502,9 @@ static void DemoWindowPopups() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Popups/Menus inside a regular window"); if (ImGui::TreeNode("Menus inside a regular window")) { + IMGUI_DEMO_MARKER("Popups/Menus inside a regular window"); ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); ImGui::Separator(); @@ -5691,7 +5688,6 @@ static void ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags) static void DemoWindowTables() { //ImGui::SetNextItemOpen(true, ImGuiCond_Once); - IMGUI_DEMO_MARKER("Tables"); if (!ImGui::CollapsingHeader("Tables & Columns")) return; @@ -5731,9 +5727,9 @@ static void DemoWindowTables() // Demos if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Basic"); if (ImGui::TreeNode("Basic")) { + IMGUI_DEMO_MARKER("Tables/Basic"); // Here we will showcase three different ways to output a table. // They are very simple variations of a same thing! @@ -5794,9 +5790,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Borders, background"); if (ImGui::TreeNode("Borders, background")) { + IMGUI_DEMO_MARKER("Tables/Borders, background"); // Expose a few Borders related flags interactively enum ContentsType { CT_Text, CT_FillButton }; static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; @@ -5865,9 +5861,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Resizable, stretch"); if (ImGui::TreeNode("Resizable, stretch")) { + IMGUI_DEMO_MARKER("Tables/Resizable, stretch"); // By default, if we don't enable ScrollX the sizing policy for each column is "Stretch" // All columns maintain a sizing weight, and they will occupy all available width. static ImGuiTableFlags flags = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody; @@ -5897,9 +5893,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Resizable, fixed"); if (ImGui::TreeNode("Resizable, fixed")) { + IMGUI_DEMO_MARKER("Tables/Resizable, fixed"); // Here we use ImGuiTableFlags_SizingFixedFit (even though _ScrollX is not set) // So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small) // If there is not enough available width to fit all columns, they will however be resized down. @@ -5931,9 +5927,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Resizable, mixed"); if (ImGui::TreeNode("Resizable, mixed")) { + IMGUI_DEMO_MARKER("Tables/Resizable, mixed"); HelpMarker( "Using TableSetupColumn() to alter resizing policy on a per-column basis.\n\n" "When combining Fixed and Stretch columns, generally you only want one, maybe two trailing columns to use _WidthStretch."); @@ -5981,9 +5977,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Reorderable, hideable, with headers"); if (ImGui::TreeNode("Reorderable, hideable, with headers")) { + IMGUI_DEMO_MARKER("Tables/Reorderable, hideable, with headers"); HelpMarker( "Click and drag column headers to reorder columns.\n\n" "Right-click on a header to open a context menu."); @@ -6041,9 +6037,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Padding"); if (ImGui::TreeNode("Padding")) { + IMGUI_DEMO_MARKER("Tables/Padding"); // First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding. // We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding. HelpMarker( @@ -6151,9 +6147,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Explicit widths"); if (ImGui::TreeNode("Sizing policies")) { + IMGUI_DEMO_MARKER("Tables/Explicit widths"); static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody; PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable); @@ -6260,9 +6256,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Vertical scrolling, with clipping"); if (ImGui::TreeNode("Vertical scrolling, with clipping")) { + IMGUI_DEMO_MARKER("Tables/Vertical scrolling, with clipping"); HelpMarker( "Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\n" "We also demonstrate using ImGuiListClipper to virtualize the submission of many items."); @@ -6305,9 +6301,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Horizontal scrolling"); if (ImGui::TreeNode("Horizontal scrolling")) { + IMGUI_DEMO_MARKER("Tables/Horizontal scrolling"); HelpMarker( "When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingFixedFit, " "as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\n" @@ -6396,9 +6392,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Columns flags"); if (ImGui::TreeNode("Columns flags")) { + IMGUI_DEMO_MARKER("Tables/Columns flags"); // Create a first table just to show all the options/flags we want to make visible in our example! const int column_count = 3; const char* column_names[column_count] = { "One", "Two", "Three" }; @@ -6471,9 +6467,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Columns widths"); if (ImGui::TreeNode("Columns widths")) { + IMGUI_DEMO_MARKER("Tables/Columns widths"); HelpMarker("Using TableSetupColumn() to setup default width."); static ImGuiTableFlags flags1 = ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBodyUntilResize; @@ -6540,9 +6536,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Nested tables"); if (ImGui::TreeNode("Nested tables")) { + IMGUI_DEMO_MARKER("Tables/Nested tables"); HelpMarker("This demonstrates embedding a table into another table cell."); if (ImGui::BeginTable("table_nested1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) @@ -6585,9 +6581,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Row height"); if (ImGui::TreeNode("Row height")) { + IMGUI_DEMO_MARKER("Tables/Row height"); HelpMarker( "You can pass a 'min_row_height' to TableNextRow().\n\nRows are padded with 'style.CellPadding.y' on top and bottom, " "so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0f'.\n\n" @@ -6650,9 +6646,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Outer size"); 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:"); @@ -6718,9 +6714,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Background color"); if (ImGui::TreeNode("Background color")) { + IMGUI_DEMO_MARKER("Tables/Background color"); static ImGuiTableFlags flags = ImGuiTableFlags_RowBg; static int row_bg_type = 1; static int row_bg_target = 1; @@ -6776,9 +6772,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Tree view"); if (ImGui::TreeNode("Tree view")) { + IMGUI_DEMO_MARKER("Tables/Tree view"); static ImGuiTableFlags table_flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; static ImGuiTreeNodeFlags tree_node_flags_base = ImGuiTreeNodeFlags_SpanAllColumns | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_DrawLinesFull; @@ -6864,9 +6860,9 @@ static void DemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Item width"); if (ImGui::TreeNode("Item width")) { + IMGUI_DEMO_MARKER("Tables/Item width"); HelpMarker( "Showcase using PushItemWidth() and how it is preserved on a per-column basis.\n\n" "Note that on auto-resizing non-resizable fixed columns, querying the content width for " @@ -6911,9 +6907,9 @@ static void DemoWindowTables() // Demonstrate using TableHeader() calls instead of TableHeadersRow() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Custom headers"); if (ImGui::TreeNode("Custom headers")) { + IMGUI_DEMO_MARKER("Tables/Custom headers"); const int COLUMNS_COUNT = 3; if (ImGui::BeginTable("table_custom_headers", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) { @@ -6964,9 +6960,9 @@ static void DemoWindowTables() // Demonstrate using ImGuiTableColumnFlags_AngledHeader flag to create angled headers if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Angled headers"); if (ImGui::TreeNode("Angled headers")) { + IMGUI_DEMO_MARKER("Tables/Angled headers"); const char* column_names[] = { "Track", "cabasa", "ride", "smash", "tom-hi", "tom-mid", "tom-low", "hihat-o", "hihat-c", "snare-s", "snare-c", "clap", "rim", "kick" }; const int columns_count = IM_COUNTOF(column_names); const int rows_count = 12; @@ -7033,9 +7029,9 @@ static void DemoWindowTables() // while playing it nice with context menus provided by TableHeadersRow()/TableHeader() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Context menus"); if (ImGui::TreeNode("Context menus")) { + IMGUI_DEMO_MARKER("Tables/Context menus"); HelpMarker( "By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\n" "Using ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body."); @@ -7144,9 +7140,9 @@ static void DemoWindowTables() // Demonstrate creating multiple tables with the same ID if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Synced instances"); if (ImGui::TreeNode("Synced instances")) { + IMGUI_DEMO_MARKER("Tables/Synced instances"); HelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc."); static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoSavedSettings; @@ -7187,9 +7183,9 @@ static void DemoWindowTables() }; if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Sorting"); if (ImGui::TreeNode("Sorting")) { + IMGUI_DEMO_MARKER("Tables/Sorting"); // Create item list static ImVector items; if (items.Size == 0) @@ -7272,9 +7268,9 @@ static void DemoWindowTables() //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // [DEBUG] if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - IMGUI_DEMO_MARKER("Tables/Advanced"); if (ImGui::TreeNode("Advanced")) { + IMGUI_DEMO_MARKER("Tables/Advanced"); static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti @@ -7596,7 +7592,6 @@ static void DemoWindowTables() // [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!] static void DemoWindowColumns() { - IMGUI_DEMO_MARKER("Columns (legacy API)"); bool open = ImGui::TreeNode("Legacy Columns API"); ImGui::SameLine(); HelpMarker("Columns() is an old API! Prefer using the more flexible and powerful BeginTable() API!"); @@ -7604,9 +7599,9 @@ static void DemoWindowColumns() return; // Basic columns - IMGUI_DEMO_MARKER("Columns (legacy API)/Basic"); if (ImGui::TreeNode("Basic")) { + IMGUI_DEMO_MARKER("Columns (legacy API)/Basic"); ImGui::Text("Without border:"); ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border ImGui::Separator(); @@ -7649,9 +7644,9 @@ static void DemoWindowColumns() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Columns (legacy API)/Borders"); if (ImGui::TreeNode("Borders")) { + IMGUI_DEMO_MARKER("Columns (legacy API)/Borders"); // NB: Future columns API should allow automatic horizontal borders. static bool h_borders = true; static bool v_borders = true; @@ -7687,9 +7682,9 @@ static void DemoWindowColumns() } // Create multiple items in a same cell before switching to next column - IMGUI_DEMO_MARKER("Columns (legacy API)/Mixed items"); if (ImGui::TreeNode("Mixed items")) { + IMGUI_DEMO_MARKER("Columns (legacy API)/Mixed items"); ImGui::Columns(3, "mixed"); ImGui::Separator(); @@ -7719,9 +7714,9 @@ static void DemoWindowColumns() } // Word wrapping - IMGUI_DEMO_MARKER("Columns (legacy API)/Word-wrapping"); if (ImGui::TreeNode("Word-wrapping")) { + IMGUI_DEMO_MARKER("Columns (legacy API)/Word-wrapping"); ImGui::Columns(2, "word-wrapping"); ImGui::Separator(); ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); @@ -7734,9 +7729,9 @@ static void DemoWindowColumns() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Columns (legacy API)/Horizontal Scrolling"); if (ImGui::TreeNode("Horizontal Scrolling")) { + IMGUI_DEMO_MARKER("Columns (legacy API)/Horizontal Scrolling"); ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f)); ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f); ImGui::BeginChild("##ScrollingRegion", child_size, ImGuiChildFlags_None, ImGuiWindowFlags_HorizontalScrollbar); @@ -7760,9 +7755,9 @@ static void DemoWindowColumns() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Columns (legacy API)/Tree"); if (ImGui::TreeNode("Tree")) { + IMGUI_DEMO_MARKER("Columns (legacy API)/Tree"); ImGui::Columns(2, "tree", true); for (int x = 0; x < 3; x++) { @@ -7806,13 +7801,11 @@ static void DemoWindowColumns() static void DemoWindowInputs() { - IMGUI_DEMO_MARKER("Inputs & Focus"); if (ImGui::CollapsingHeader("Inputs & Focus")) { ImGuiIO& io = ImGui::GetIO(); // Display inputs submitted to ImGuiIO - IMGUI_DEMO_MARKER("Inputs & Focus/Inputs"); ImGui::SetNextItemOpen(true, ImGuiCond_Once); bool inputs_opened = ImGui::TreeNode("Inputs"); ImGui::SameLine(); @@ -7822,6 +7815,7 @@ static void DemoWindowInputs() "- in 'Tools->Debug Log->IO'."); if (inputs_opened) { + IMGUI_DEMO_MARKER("Inputs & Focus/Inputs"); if (ImGui::IsMousePosValid()) ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y); else @@ -7847,7 +7841,6 @@ static void DemoWindowInputs() } // Display ImGuiIO output flags - IMGUI_DEMO_MARKER("Inputs & Focus/Outputs"); ImGui::SetNextItemOpen(true, ImGuiCond_Once); bool outputs_opened = ImGui::TreeNode("Outputs"); ImGui::SameLine(); @@ -7860,6 +7853,7 @@ static void DemoWindowInputs() "rules leading to how those flags are set)."); if (outputs_opened) { + IMGUI_DEMO_MARKER("Inputs & Focus/Outputs"); ImGui::Text("io.WantCaptureMouse: %d", io.WantCaptureMouse); ImGui::Text("io.WantCaptureMouseUnlessPopupClose: %d", io.WantCaptureMouseUnlessPopupClose); ImGui::Text("io.WantCaptureKeyboard: %d", io.WantCaptureKeyboard); @@ -7903,9 +7897,9 @@ static void DemoWindowInputs() // - If you call Shortcut() WITHOUT any routing option, it uses ImGuiInputFlags_RouteFocused. // TL;DR: Most uses will simply be: // - Shortcut(ImGuiMod_Ctrl | ImGuiKey_A); // Use ImGuiInputFlags_RouteFocused policy. - IMGUI_DEMO_MARKER("Inputs & Focus/Shortcuts"); if (ImGui::TreeNode("Shortcuts")) { + IMGUI_DEMO_MARKER("Inputs & Focus/Shortcuts"); static ImGuiInputFlags route_options = ImGuiInputFlags_Repeat; static ImGuiInputFlags route_type = ImGuiInputFlags_RouteFocused; ImGui::CheckboxFlags("ImGuiInputFlags_Repeat", &route_options, ImGuiInputFlags_Repeat); @@ -7995,9 +7989,9 @@ static void DemoWindowInputs() } // Display mouse cursors - IMGUI_DEMO_MARKER("Inputs & Focus/Mouse Cursors"); if (ImGui::TreeNode("Mouse Cursors")) { + IMGUI_DEMO_MARKER("Inputs & Focus/Mouse Cursors"); const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "Wait", "Progress", "NotAllowed" }; IM_ASSERT(IM_COUNTOF(mouse_cursors_names) == ImGuiMouseCursor_COUNT); @@ -8024,9 +8018,9 @@ static void DemoWindowInputs() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Inputs & Focus/Tabbing"); if (ImGui::TreeNode("Tabbing")) { + IMGUI_DEMO_MARKER("Inputs & Focus/Tabbing"); ImGui::Text("Use Tab/Shift+Tab to cycle through keyboard editable fields."); static char buf[32] = "hello"; ImGui::InputText("1", buf, IM_COUNTOF(buf)); @@ -8040,9 +8034,9 @@ static void DemoWindowInputs() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Inputs & Focus/Focus from code"); if (ImGui::TreeNode("Focus from code")) { + IMGUI_DEMO_MARKER("Inputs & Focus/Focus from code"); bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); bool focus_3 = ImGui::Button("Focus on 3"); @@ -8082,9 +8076,9 @@ static void DemoWindowInputs() ImGui::TreePop(); } - IMGUI_DEMO_MARKER("Inputs & Focus/Dragging"); if (ImGui::TreeNode("Dragging")) { + IMGUI_DEMO_MARKER("Inputs & Focus/Dragging"); ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget."); for (int button = 0; button < 3; button++) { @@ -8792,9 +8786,9 @@ static void ShowExampleMenuFile() if (ImGui::MenuItem("Save As..")) {} ImGui::Separator(); - IMGUI_DEMO_MARKER("Examples/Menu/Options"); if (ImGui::BeginMenu("Options")) { + IMGUI_DEMO_MARKER("Examples/Menu/Options"); static bool enabled = true; ImGui::MenuItem("Enabled", "", &enabled); ImGui::BeginChild("child", ImVec2(0, 60), ImGuiChildFlags_Borders); @@ -8809,9 +8803,9 @@ static void ShowExampleMenuFile() ImGui::EndMenu(); } - IMGUI_DEMO_MARKER("Examples/Menu/Colors"); if (ImGui::BeginMenu("Colors")) { + IMGUI_DEMO_MARKER("Examples/Menu/Colors"); float sz = ImGui::GetTextLineHeight(); for (int i = 0; i < ImGuiCol_COUNT; i++) { From 2000008b474b9ccc0b7916d2c9e378f92b7635f0 Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Sun, 22 Feb 2026 16:35:57 +0100 Subject: [PATCH 1683/2359] Examples: Emscripten: add tabindex=-1 to canvas in shell_minimal.html. (#9259) Without tabindex, the canvas element is not focusable in the DOM, so pongasoft/emscripten-glfw's focus/blur listeners on the canvas never fire. This means glfwSetWindowFocusCallback is never called etc. Ref: https://github.com/pongasoft/emscripten-glfw/issues/29 --- docs/CHANGELOG.txt | 3 +++ examples/libs/emscripten/shell_minimal.html | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4645c48a9..a6a9dfd01 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,9 @@ Other Changes: - Style: border sizes are now scaled (and rounded) by ScaleAllSizes(). - Clipper: clear DisplayStart/DisplayEnd fields when Step() returns false. - Examples: + - Emscripten: added `tabindex=-1` to canvas in our shell_minimal.htm. Without it, + the canvas was not focusable in the DOM, which in turn make some backends + (e.g. pongasoft/emscripten-glfw) not receive focus loss events. (#9259) [@pthom] - WGPU: fixed undefined behaviors in example code for requesting adapter and device. (#9246, #9256) [@r-lyeh] diff --git a/examples/libs/emscripten/shell_minimal.html b/examples/libs/emscripten/shell_minimal.html index bcf626261..bcc5834a1 100644 --- a/examples/libs/emscripten/shell_minimal.html +++ b/examples/libs/emscripten/shell_minimal.html @@ -29,7 +29,7 @@ - +